Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I want to remove the element tag and want to preserve the text inside the tag. I use the replace function of RegExp but it removed everything: The tag and the text inside the tag. I dont want that, I want to remove the tag only. Clean up the text, remove the tags, I want to present the text only. ``` var str = str.replace(/<.>[^.]*\/.>/, ""); ``` I used this, but there's a problem, it also removed the text inside it!
what about `var obj = $('#element');` `var str = obj.text();`
If you're indeed using jQuery, and want to remove all tags, then simply set the .html() to the .text() ``` var e = $("#yourelement"); e.html( e.text() ); ```
How to remove a tag, and preserved the text in the element using RegExp?
[ "", "javascript", "jquery", "regex", "" ]
Is there any way to indicate to ReSharper that a null reference won't occur because of Design-by-Contract Requires checking? For example, the following code will raise the warning (`Possible 'null' assignment to entity marked with 'NotNull' attribute`) in ReSharper on lines 7 and 8: ``` private Dictionary<string, string> _Lookup = new Dictionary<string, string>(); public void Foo(string s) { Contract.Requires(!String.IsNullOrEmpty(s)); if (_Lookup.ContainsKey(s)) _Lookup.Remove(s); } ``` What is really odd is that if you remove the `Contract.Requires(...)` line, the ReSharper message goes away. **Update** I found the solution through ExternalAnnotations which was also mentioned by Mike below. Here's an example of how to do it for a function in Microsoft.Contracts: * Create a directory called `Microsoft.Contracts` under the `ExternalAnnotations` ReSharper directory. * Next, Create a file called `Microsoft.Contracts.xml` and populate like so: ``` <assembly name="Microsoft.Contracts"> <member name="M:System.Diagnostics.Contracts.Contract.Requires(System.Boolean)"> <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/> <parameter name="condition"> <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)"> <argument>0</argument> </attribute> </parameter> </member> </assembly> ``` * Restart Visual Studio, and the message goes away!
**Note**: as of the current R# 8.0 EAP, this functionality is included. --- Here's the solution for the current (i.e. .NET 4.0) version of Code Contracts: Inside `...\ExternalAnnotations\mscorlib\Contracts.xml`, add the following: ``` <assembly name="mscorlib"> <member name="M:System.Diagnostics.Contracts.Contract.Assert(System.Boolean)"> <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/> <parameter name="condition"> <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)"> <argument>0</argument> </attribute> </parameter> </member> <member name="M:System.Diagnostics.Contracts.Contract.Assert(System.Boolean, System.String)"> <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/> <parameter name="condition"> <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)"> <argument>0</argument> </attribute> </parameter> </member> <member name="M:System.Diagnostics.Contracts.Contract.Assume(System.Boolean)"> <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/> <parameter name="condition"> <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)"> <argument>0</argument> </attribute> </parameter> </member> <member name="M:System.Diagnostics.Contracts.Contract.Assume(System.Boolean, System.String)"> <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/> <parameter name="condition"> <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)"> <argument>0</argument> </attribute> </parameter> </member> <member name="M:System.Diagnostics.Contracts.Contract.Requires(System.Boolean)"> <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/> <parameter name="condition"> <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)"> <argument>0</argument> </attribute> </parameter> </member> <member name="M:System.Diagnostics.Contracts.Contract.Requires``1(System.Boolean)"> <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/> <parameter name="condition"> <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)"> <argument>0</argument> </attribute> </parameter> </member> <member name="M:System.Diagnostics.Contracts.Contract.Requires(System.Boolean,System.String)"> <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/> <parameter name="condition"> <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)"> <argument>0</argument> </attribute> </parameter> </member> <member name="M:System.Diagnostics.Contracts.Contract.Requires``1(System.Boolean,System.String)"> <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/> <parameter name="condition"> <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)"> <argument>0</argument> </attribute> </parameter> </member> <member name="M:System.Diagnostics.Contracts.Contract.Invariant(System.Boolean)"> <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/> <parameter name="condition"> <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)"> <argument>0</argument> </attribute> </parameter> </member> <member name="M:System.Diagnostics.Contracts.Contract.Invariant(System.Boolean,System.String)"> <attribute ctor="M:JetBrains.Annotations.AssertionMethodAttribute.#ctor"/> <parameter name="condition"> <attribute ctor="M:JetBrains.Annotations.AssertionConditionAttribute.#ctor(JetBrains.Annotations.AssertionConditionType)"> <argument>0</argument> </attribute> </parameter> </member> </assembly> ```
I'd like to add that for people writing their own assertion methods and such, you can include these attributes without an external XML file. In Visual Studio, go to `ReSharper > Options > Code Annotations` and click the `Copy default implementation to clipboard` button. Then create a new file (anywhere you want in your solution) and paste in the code from the clipboard. Now, you can create methods like this: ``` public class Require { [AssertionMethod] public static void That( [AssertionCondition(AssertionConditionType.IS_TRUE)] bool requiredCondition, string message = null) { ... } ... } ``` Now any call to `Require.That(a != null)` will indicate to ReSharper that you can't get past this line if `a` is null. Unlike the ExternalAnnotations technique, this will work for anyone using your methods, without any additional work on their part. ### Update Resharper has changed their contract annotation model as of version 7. Here's what the above method would look like now: ``` public class Require { [ContractAnnotation("requiredCondition:false => halt")] public static void That( bool requiredCondition, string message = null) { ... } ... } ```
ReSharper - Possible Null Assignment when using Microsoft.Contracts
[ "", "c#", "resharper", "code-contracts", "design-by-contract", "microsoft-contracts", "" ]
I have a SQL 2005 database with approx 250 tables. I want to temporarily enable ON DELETE CASCADE to all of the Foreign Keys so that I can do a bulk delete easily. I then want to turn off ON DELETE CASCADE on all Foreign Keys. The only way I know of doing this, is to use Management Studio to generate a full database create script, do some kind of search and replace to strip out everything but Foreign Keys, save the script, then do some more search and replacing to add the ON DELETE CASCADE. Then I run the script, do my delete, and then run the other script. Is there an easier way to produce this script? This method seems far too prone to error and I will have to keep the script up to date with any other changes we make to the database, or re-generate it manually each time I may need to use it. Is an alternative option to run a select on the system tables to "generate" the script for me? Could it even be possible to run an update on a system table that enables and disables ON DELETE CASCADE?
Here's a script I used for a similiar purpose. It does not support composite foreign keys (which use more than one field.) And it would probably need some tweaking before it will work for your situation. *EDIT: In particular it does not handle multi-column foreign keys correctly.* ``` select DropStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema + '].[' + ForeignKeys.ForeignTableName + '] DROP CONSTRAINT [' + ForeignKeys.ForeignKeyName + ']; ' , CreateStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema + '].[' + ForeignKeys.ForeignTableName + '] WITH CHECK ADD CONSTRAINT [' + ForeignKeys.ForeignKeyName + '] FOREIGN KEY([' + ForeignKeys.ForeignTableColumn + ']) REFERENCES [' + schema_name(sys.objects.schema_id) + '].[' + sys.objects.[name] + ']([' + sys.columns.[name] + ']) ON DELETE CASCADE; ' from sys.objects inner join sys.columns on (sys.columns.[object_id] = sys.objects.[object_id]) inner join ( select sys.foreign_keys.[name] as ForeignKeyName ,schema_name(sys.objects.schema_id) as ForeignTableSchema ,sys.objects.[name] as ForeignTableName ,sys.columns.[name] as ForeignTableColumn ,sys.foreign_keys.referenced_object_id as referenced_object_id ,sys.foreign_key_columns.referenced_column_id as referenced_column_id from sys.foreign_keys inner join sys.foreign_key_columns on (sys.foreign_key_columns.constraint_object_id = sys.foreign_keys.[object_id]) inner join sys.objects on (sys.objects.[object_id] = sys.foreign_keys.parent_object_id) inner join sys.columns on (sys.columns.[object_id] = sys.objects.[object_id]) and (sys.columns.column_id = sys.foreign_key_columns.parent_column_id) ) ForeignKeys on (ForeignKeys.referenced_object_id = sys.objects.[object_id]) and (ForeignKeys.referenced_column_id = sys.columns.column_id) where (sys.objects.[type] = 'U') and (sys.objects.[name] not in ('sysdiagrams')) ```
[Andomar's answer](https://stackoverflow.com/a/871124/1501497) above is good but works for single-column foreign key constraints only. I adapted it a little for multi-column constraints: ``` create function dbo.fk_columns (@constraint_object_id int) returns varchar(255) as begin declare @r varchar(255) select @r = coalesce(@r + ',', '') + c.name from sys.foreign_key_columns fkc join sys.columns c on fkc.parent_object_id = c.object_id and fkc.parent_column_id = c.column_id where fkc.constraint_object_id = @constraint_object_id return @r end select distinct DropStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema + '].[' + ForeignKeys.ForeignTableName + '] DROP CONSTRAINT [' + ForeignKeys.ForeignKeyName + '] ' , CreateStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema + '].[' + ForeignKeys.ForeignTableName + '] WITH CHECK ADD CONSTRAINT [' + ForeignKeys.ForeignKeyName + '] FOREIGN KEY(' + dbo.fk_columns(constraint_object_id) + ')' + 'REFERENCES [' + schema_name(sys.objects.schema_id) + '].[' + sys.objects.[name] + '] ' + ' ON DELETE CASCADE' from sys.objects inner join sys.columns on (sys.columns.[object_id] = sys.objects.[object_id]) inner join ( select sys.foreign_keys.[name] as ForeignKeyName ,schema_name(sys.objects.schema_id) as ForeignTableSchema ,sys.objects.[name] as ForeignTableName ,sys.columns.[name] as ForeignTableColumn ,sys.foreign_keys.referenced_object_id as referenced_object_id ,sys.foreign_key_columns.referenced_column_id as referenced_column_id ,sys.foreign_keys.object_id as constraint_object_id from sys.foreign_keys inner join sys.foreign_key_columns on (sys.foreign_key_columns.constraint_object_id = sys.foreign_keys.[object_id]) inner join sys.objects on (sys.objects.[object_id] = sys.foreign_keys.parent_object_id) inner join sys.columns on (sys.columns.[object_id] = sys.objects.[object_id]) and (sys.columns.column_id = sys.foreign_key_columns.parent_column_id) -- Uncomment this if you want to include only FKs that already -- have a cascade constraint. -- where (delete_referential_action_desc = 'CASCADE' or update_referential_action_desc = 'CASCADE') ) ForeignKeys on (ForeignKeys.referenced_object_id = sys.objects.[object_id]) and (ForeignKeys.referenced_column_id = sys.columns.column_id) where (sys.objects.[type] = 'U') and (sys.objects.[name] not in ('sysdiagrams')) ``` You can also use the query to help *remove* `ON DELETE CASCADE` from FKs that currently have it. This still doesn't handle the case where the columns are named different things in the two tables - another user-defined function would need to be defined for that.
SQL Script to alter ALL Foreign Keys to add ON DELETE CASCADE
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I'm prompting the user for a filename, if they enter a valid filename the first time, it works. However, if its invalid the first time, every other check fails. How would I fix this? Also, let's say they just specify a directory, how would I get the names of all the text files and how many there are? ``` int main() { ifstream inFile; int result; string filename; cout << "If the executable is not in the same directory as the\nfile, then a directory needs to be provided\n\n"; while (true) { cout << "Enter the file name: "; getline(cin, filename); inFile.open(filename.c_str(), ios::in); if (!inFile) cout << "\n**File failed to open**\n\n"; else break; } result = countLOC(inFile); cout << "\nThere are " << result << " lines of code in \"" << filename << "\"\n\n"; inFile.close(); return 0; } ```
This is because the error bits in the object 'inFile' have been set. You need to reset the error bits before you do anything else. ``` if (!inFile) { cout << "\n**File failed to open**\n\n"; inFile.clear(); } else break; ```
Call [clear](http://www.cplusplus.com/reference/iostream/ios/clear/) to reset the state before the call to open.
Prompting a user for the filename or directory
[ "", "c++", "file", "filenames", "istream", "" ]
Is the Java Virtual Machine really a virtual machine in the same sense as my VMWare or Parallels file?
No. VMWare and the rest actually virtualize the *hardware* of the machine. The operating system running inside of a VMWare container (or Parallels or Windows' virtualization containers or Bochs or ...) have varying degrees of awareness of running within a virtualized container. Within VMWare, the operating system has no idea that it is running within a virtual container. The operating system is not modified at all, although specialized drivers are usually installed (most importantly video) to prevent performance problems. Some other VM's don't do full hardware virtualization and instead require the OS inside the container the make special calls to the container in place of the regular hardware calls. The JVM is not a virtual machine in that sense at all. No hardware other than the processor is virtualized. The JVM is essentially a virtualized CPU plus the same sort of runtime that is included with a C++ or any other object oriented language, plus garbage collection and other necessities. Additionally, of course, Java class files (and JAR files, etc) are not machine code, but an intermediate byte code. So the JVM has to compile or interpret class files (whether contained in a JAR file or not) at runtime, and has the ability to load and find new code dynamically at runtime. The JVM is called a virtual machine because the JVM definition defines an abstract machine. This includes registers, stack, etc, and the byte code that Java source is compiled to is practically machine code for this virtual machine. The JVM then interprets or compiles this byte code into native machine instructions. The difference is essentially that the JVM is a virtualized **processor** and the other virtual machines are virtualized **machines** (including video card, network, and other external devices and hardware registers).
No. There is a difference between system virtual machine and process virtual machine. JVM is a process virtual machine, whereas the VMWare and the kind are system virtual machines. For more please refer to the [wikipedia entry](http://en.wikipedia.org/wiki/Virtual_machine). As far as parallel virtual machines are concern, the above mentioned entry states, > PVM (Parallel Virtual Machine) are not > strictly virtual machines, as the > applications running on top still have > access to all OS services, and are > therefore not confined to the system > model provided by the "VM".
Is the Java Virtual Machine really a virtual machine in the same sense as my VMWare or Parallels file?
[ "", "java", "jvm", "" ]
I have a class like this ``` public class foo { private void getThread() { var AllThreads = from sc in db.ScreenCycles join s in db.Screens on sc.ScreenID equals s.ScreenID select s; } } ``` I want to make the AllThreads variable a class variable instead of a method variable. Like this... ``` public class foo { var AllThreads; private void getThread() { AllThreads = from sc in db.ScreenCycles join s in db.Screens on sc.ScreenID equals s.ScreenID select s; } } ``` How ever it wont let me declare a class variable of type var. How to I achieve this?
To preserve your original code, try this ``` public class foo IEnumerable<ScreenCycles> AllThreads; private void getThread() { AllThreads = from sc in db.ScreenCycles join s in db.Screens on sc.ScreenID equals s.ScreenID select s; } } ```
You could do it like this: ``` public class foo { IEnumerable<string> AllThreads; private void getThread() { AllThreads = (from sc in db.ScreenCycles join s in db.Screens on sc.ScreenID equals s.ScreenID select s.Screen1 + " " + sc.Thread); } } ``` Updated per Joel's suggestion.
LINQ2SQL: How do I declare a member variable of type var?
[ "", "c#", ".net", "linq-to-sql", "var", "" ]
I want to fade a window in/out in my application. Fading in occurs on `Window.Loaded` and I wanted to fade out on close (`Window.Closed` or `Window.Closing`). Fading in works perfectly, but `Window.Closing` is not allowed value for `RoutedEvent` property. What `RoutedEvent` should I be using for Close? ``` <Window.Triggers> <EventTrigger RoutedEvent="Window.Loaded"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:2" FillBehavior="HoldEnd" /> </Storyboard> </BeginStoryboard> </EventTrigger> <EventTrigger RoutedEvent="Window.Closing"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:2" FillBehavior="HoldEnd" /> </Storyboard> </BeginStoryboard> </EventTrigger> </Window.Triggers> ``` I get a error on , Value 'Window.Closing' cannot be assigned to property 'RoutedEvent'. Invalid event name.
Closing is not a routed event, so you can't use it in an EventTrigger. Perhaps you could start the storyboard in the handler of the ClosingEvent in the code-behind and cancel the event... something like that : ``` private bool closeStoryBoardCompleted = false; private void Window_Closing(object sender, CancelEventArgs e) { if (!closeStoryBoardCompleted) { closeStoryBoard.Begin(); e.Cancel = true; } } private void closeStoryBoard_Completed(object sender, EventArgs e) { closeStoryBoardCompleted = true; this.Close(); } ```
I thought I'd add another solution of doing this, using behaviors from the Expression SDK and combining it with the solution from @Thomas. Using that, we can define a "CloseBehavior" that handles the code behind of starting a storyboard and closing the window when it's done. ``` using System.ComponentModel; using System.Windows; using System.Windows.Interactivity; using System.Windows.Media.Animation; namespace Presentation.Behaviours { public class CloseBehavior : Behavior<Window> { public static readonly DependencyProperty StoryboardProperty = DependencyProperty.Register("Storyboard", typeof(Storyboard), typeof(CloseBehavior), new PropertyMetadata(default(Storyboard))); public Storyboard Storyboard { get { return (Storyboard)GetValue(StoryboardProperty); } set { SetValue(StoryboardProperty, value); } } protected override void OnAttached() { base.OnAttached(); AssociatedObject.Closing += onWindowClosing; } private void onWindowClosing(object sender, CancelEventArgs e) { if (Storyboard == null) { return; } e.Cancel = true; AssociatedObject.Closing -= onWindowClosing; Storyboard.Completed += (o, a) => AssociatedObject.Close(); Storyboard.Begin(AssociatedObject); } } } ``` The behavior defines a storyboard as a dependency property, so we can set it in xaml and when the `AssociatedObject` (the window where we define the behavior) is closing, this storyboard is started using `Storyboard.Begin()`. Now, in xaml we simply add the behavior to the window using the following xaml ``` <Window x:Class="Presentation.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:behave="clr-namespace:Presentation.Behaviours" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" x:Name="window"> <Window.Resources> <Storyboard x:Key="ExitAnimation"> <DoubleAnimation Storyboard.Target="{Binding ElementName='window'}" Storyboard.TargetProperty="(Window.Opacity)" Duration="0:0:1" From="1" To="0"/> </Storyboard> </Window.Resources> <i:Interaction.Behaviors> <behave:CloseBehavior Storyboard="{StaticResource ExitAnimation}"/> </i:Interaction.Behaviors> <Grid> </Grid> </Window> ``` Note the xml namespace `i` from the System.Windows.Interactivity dll, and also that the window is referenced, so it has to have a `x:Name` assigned. Now we simply add the behavior to every window on which we wish to execute a storyboard before closing the application, instead of copying the logic to every code-behind in each window.
Fading out a wpf window on close
[ "", "c#", "wpf", "animation", "eventtrigger", "routedevent", "" ]
This seems to be a very odd problem that I cannot figure out for the life of me. I have a path (string) that looks like this: > D:\development\php\bchat\chat\index.php I need to check if the file in question is a PHP file. I figure the most logical way is to take a substring starting from the . to the end of the string and see if it == .php So i tried: ``` bool isphp = (path.Substring(path.LastIndexOf('.')) == ".php") ? true : false; ``` This always returned false. I thought maybe there was a trailing space at the end screwing me up so i put a TrimEnd() on path before it. But that didn't change anything. So i tried this: ``` bool isphp = (path.EndsWith(".php") == true) ? true : false; ``` This also always returns false. **EDIT** I have now also tried this: ``` bool isphp = (Path.GetExtension(path) == ".php"); ``` But this also returns false.
The following code works fine on my machine: ``` public static void Main() { string path = @"D:\development\php\bchat\chat\index.php"; bool isPhp = path.EndsWith(".php"); Console.WriteLine(isPhp); } ``` So I would guess there is something else about your string that is causing it not to work. Maybe it is a case thing in which case add StringComparison.InvariantCultureIgnoreCase to your EndsWith call like this. ``` public static void Main() { string path = @"D:\development\php\bchat\chat\index.pHp"; bool isPhp = path.EndsWith(".php", StringComparison.OrdinalIgnoreCase); Console.WriteLine(isPhp); } ``` If that doesn't work put a break point on the comparison line and then type this into the Immediate window: ``` path[path.Length-1] ``` You should get this as a result: ``` 112 'p' ``` If you don't you can tell that your path does not end with a standard p character.
Use the Path-class. It has a GetExtension() method: ``` var path = @"D:\development\php\bchat\chat\index.php"; if( Path.GetExtension( path.ToUpperInvariant() ) == ".PHP" ) {} ``` EDIT: Added check for upper/lower cases
Problem Checking the End of a String
[ "", "c#", "string", "" ]
The simple piece of midlet code (class Moo) below (after the excerpts) deadlocks (At least I assume it deadlocks after reading this post on threads [here](http://developers.sun.com/mobility/midp/ttips/threading3/index.html)). I have reproduced the relevant excerpts from the post : ``` String url = ... Connection conn = null; try { conn = Connector.open( url ); // do something here } catch( IOException e ){ // error } ``` **The root of the problem is the blocking nature of the open() call. On some platforms, the system does the actual connection under the covers, on the equivalent of a separate thread. The calling thread blocks until the connection thread makes the connection. At the same time, the security subsystem may require the user to confirm the connection, and the connection thread blocks until the event thread gets confirmation from the user. Deadlock occurs because the event thread is already waiting for the connection thread.** ``` public class Moo extends MIDlet { protected void destroyApp(boolean arg0) throws MIDletStateChangeException { // TODO Auto-generated method stub } protected void pauseApp() { } protected void startApp() throws MIDletStateChangeException { Display display = Display.getDisplay(this); MyCanvas myCanvas = new MyCanvas(); display.setCurrent(myCanvas); myCanvas.repaint(); } class MyCanvas extends Canvas { protected void paint(Graphics graphics) { try { Image bgImage = Image.createImage(getWidth(), getHeight()); HttpConnection httpConnection = (HttpConnection) Connector .open("http://stackoverflow.com/content/img/so/logo.png"); Image image = Image.createImage(httpConnection .openInputStream()); bgImage.getGraphics().drawImage(image, 0, 0, 0); httpConnection.close(); graphics.drawImage(bgImage, 0, 0, 0); } catch (IOException e) { e.printStackTrace(); } } } } ``` Can someone please tell me how the system thread invocation is done here (event and notification threads) and the sequence of events leading to the deadlock. I am not clear as to what are the thread involved here that lead to deadlock. 1. Is there any documentation on j2me thread model? 2. Where can I get the sources for j2me system classes (I want to check out the implementation of Connection classes)? **EDIT** : In the above code I get the logic. But the below code should at least work right? This one also deadlocks where I am doing the network connection in a separate thread. ``` public class Foo extends MIDlet { protected void destroyApp(boolean arg0) throws MIDletStateChangeException { // TODO Auto-generated method stub } protected void pauseApp() { // TODO Auto-generated method stub } protected void startApp() throws MIDletStateChangeException { Display display = Display.getDisplay(this); MyCanvas myCanvas = new MyCanvas(); display.setCurrent(myCanvas); myCanvas.repaint(); } class MyCanvas extends Canvas { protected void paint(Graphics graphics) { try { Image bgImage = Image.createImage(getWidth(), getHeight()); FetchImage fetchImage = new FetchImage(); Thread thread = new Thread(fetchImage); thread.start(); thread.join(); bgImage.getGraphics().drawImage(fetchImage.image, 0, 0, 0); graphics.drawImage(bgImage, 0, 0, 0); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public class FetchImage implements Runnable { public Image image; public void run() { HttpConnection httpConnection; try { httpConnection = (HttpConnection) Connector .open("http://10.4.71.200/stage/images/front/car.png"); image = Image.createImage(httpConnection.openInputStream()); httpConnection.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } ```
> Where can I get the sources for > j2me system classes (I want to check > out the implementation of Connection > classes)? You cant. Its actually vendor dependent. The way in which Nokia handles this situation may be different from Motorola. The lesson you have to learn is that don't do expensive computation in system callbacks as that might make the system unresponsive. So put the time consuming operation in a sepearate thread and always return from call backs as early as possible. Even though you have created a separate thread in your second example, you wait for its completion in paint() and it eventually makes a result of no threading at all! One thing you can do is ``` class MyCanvas extends Canvas { Image image; boolean imageFetchFailed; protected void paint(Graphics g) { if (image == null) { fetchImage(); g.drawString("Fetching...", getWidth() >> 1, getHeight() >> 1, Graphics.HCENTER | Graphics.TOP) } else if (imageFetchFailed) { g.drawString("Failed to fetch image", getWidth() >> 1, getHeight() >> 1, Graphics.HCENTER | Graphics.TOP) } else { g.drawImage(image, 0, 0, 0); } } private void fetchImage() { new Thread(new Runnable() { public void run() { HttpConnection httpConnection = null; try { httpConnection = (HttpConnection) Connector .open("http://10.4.71.200/stage/images/front/car.png"); image = Image.createImage(httpConnection.openInputStream()); } catch (IOException e) { e.printStackTrace(); imageFetchFailed = true; } if (httpConnection != null) { try { httpConnection.close(); } catch (IOException ignored) { } } // Following will trigger a paint call // and this time image wont be null and will get painted on screen repaint(); } }).start(); } } ```
Well, the basic problem is that some Java VM implementations use the same Java thread to do everything. One of the first thing you need to figure out about the threading model of your VM is who developed it. There is a list of J2ME licensees here: <http://java.sun.com/javame/licensees/index.jsp> From that information, try to figure out how many native threads your VM is using. The 2 usual models are either run all bytecode interpretation into one native thread or run each java thread into its own native thread. The next step is to gather information about how asynchronous the underlying operating system APIs are. When developing the VM, the licensees would have had to write native code to port the VM to the operating system. Any Inter-Process Communication or use of slow transmission medium (from flash card to GPS signal) might be implemented using a separate native thread that could allow the bytecode interpreter thread to keep running while the system waits for some data. The next step is to realize how badly implemented the VM is. Typically, your problem happens when the VM uses only one internal java thread for all callbacks methods in the MIDP spec. So, you don't get a chance to react to keypad events until after your connection is opened if you try to open it in the wrong java thread. Worse, you can actually prevent the screen from being refreshed because Canvas.paint() would be called in the same java thread as javax.microedition.media.PlayerListener.playerUpdate() for example. From the VM implementation perspective, the golden rule is that any callback that you don't control (because it can end up in "user" code, like a listener) cannot be called from the same java thread you use unblock standard API calls. A lot of VM out there simply break that rule, hence the Sun recommendation that JavaME developers work around it.
j2me networking, threads and deadlocks
[ "", "java", "multithreading", "java-me", "mobile", "deadlock", "" ]
I have a QTransform object and would like to know the angle in degrees that the object is rotated by, however there is no clear example of how to do this: <http://doc.trolltech.com/4.4/qtransform.html#basic-matrix-operations> Setting it is easy, getting it back out again is hard.
Assuming, that the transform **ONLY** contains a rotation it's easy: Just take the acos of the m11 element. It still works if the transform contains a translation, but if it contains shearing or scaling you're out of luck. These can be reconstructed by decomposing the matrix into a shear, scale and rotate matrix, but the results you get aren't most likely what you're looking for.
The simplest general way is to transform (0,0) and (1,0), then use trigonometric functions (arctan) to get the angle
How do I extract the angle of rotation from a QTransform?
[ "", "c++", "qt", "math", "transform", "" ]
I am trying to use <http://code.google.com/p/amazon-s3-php-class/> to force-dowload files from AWS S3. I have an mp3 that I want people to "play" or "download." By default the when you access the file directly on s3 it begins to play in the browser. I need to add an option to actually download. I have Googled and found came up with nothing. I conceptually know what needs to happen but don't know how to produce it php. I know I need to modify the headers to Content-Disposition: attachment. Any help would be greatly appreciated. Thanks, Michael
The php scripts that have been mentioned so far will work ok, but the main downside is that every time a visitor on your site requests a file, your own servers will load it from the S3 and then relay that data to the browser. For low traffic sites, it's probably not a big deal, but for high traffic ones, you definitely want to avoid running everything through your own servers. Luckily, there's a fairly straight-forward way to set your files to be forced to download from the S3. And you're exactly right - you just want to set the content-type and content-disposition (just setting content-disposition will work in some browsers, but setting both should work in all browsers). This code is assuming that you're using the Amazon S3 PHP class from Undesigned: ``` <?php // set S3 auth and get your bucket listing // then loop through the bucket and copy each file over itself, replacing the "request headers": S3::copyObject($bucketName, $filename, $bucketName, $filename, "public-read", array(), array("Content-Type" => "application/octet-stream", "Content-Disposition" => "attachment")); ?> ``` Now all your files will be forced to download. You may need to clear your cache to see the change. And obviously, don't do that on any file that you actually do want to be loaded "inline" in the browser. The nice part with this solution is that applications that load media files directly (like let's say an mp3 player in Flash) don't care about the content-type or content-disposition, so you can still play your files in the browser and then link to download that same file. If the user already finished loading the file in flash, they'll most likely still have it in their cache, which means their download will be super quick and it won't even cost you any extra bandwidth charges from the S3.
Amazon has now solved this problem and allows overriding of headers on a per-request basis with signed requests: <http://docs.amazonwebservices.com/AmazonS3/latest/API/index.html?RESTObjectGET.html> w00t!
Force-Download with php on Amazon S3
[ "", "php", "download", "amazon-s3", "" ]
I have 2 simple questions about python: 1.How to get number of lines of a file in python? 2.How to locate the position in a file object to the last line easily?
lines are just data delimited by the newline char `'\n'`. 1) Since lines are variable length, you have to read the entire file to know where the newline chars are, so you can count how many lines: ``` count = 0 for line in open('myfile'): count += 1 print count, line # it will be the last line ``` 2) reading a chunk from the end of the file is the fastest method to find the last newline char. ``` def seek_newline_backwards(file_obj, eol_char='\n', buffer_size=200): if not file_obj.tell(): return # already in beginning of file # All lines end with \n, including the last one, so assuming we are just # after one end of line char file_obj.seek(-1, os.SEEK_CUR) while file_obj.tell(): ammount = min(buffer_size, file_obj.tell()) file_obj.seek(-ammount, os.SEEK_CUR) data = file_obj.read(ammount) eol_pos = data.rfind(eol_char) if eol_pos != -1: file_obj.seek(eol_pos - len(data) + 1, os.SEEK_CUR) break file_obj.seek(-len(data), os.SEEK_CUR) ``` You can use that like this: ``` f = open('some_file.txt') f.seek(0, os.SEEK_END) seek_newline_backwards(f) print f.tell(), repr(f.readline()) ```
Let's not forget ``` f = open("myfile.txt") lines = f.readlines() numlines = len(lines) lastline = lines[-1] ``` NOTE: this reads the whole file in memory as a list. Keep that in mind in the case that the file is very large.
Two simple questions about python
[ "", "python", "file", "" ]
Is it possible to disable the hittest on a Windows Forms window, and if so, how do I do it? I want to have a opaque window that cannot be clicked. Thanks in advance, Christoph
If you're talking to a different process, you need to send and retrieve Windows messages. <http://www.c-sharpcorner.com/UploadFile/thmok/SendingWindowsMessageinCSharp11262005042819AM/SendingWindowsMessageinCSharp.aspx> Have a look at this link: Using Window Messages to Implement Global System Hooks in C# <http://www.codeproject.com/KB/system/WilsonSystemGlobalHooks.aspx> Global system hooks allow an application to intercept Windows messages intended for other applications. This has always been difficult (impossible, according to MSDN) to implement in C#. This article attempts to implement global system hooks by creating a DLL wrapper in C++ that posts messages to the hooking application's message queue.
Do you want a window that cannot be moved? Set FormBorderStyle to none.
How can I disable hittests on a Windows Form?
[ "", "c#", "winforms", "winapi", "" ]
What is the difference between `JOIN` and `UNION`? Can I have an example?
`UNION` puts lines from queries after each other, while `JOIN` makes a cartesian product and subsets it -- completely different operations. Trivial example of `UNION`: ``` mysql> SELECT 23 AS bah -> UNION -> SELECT 45 AS bah; +-----+ | bah | +-----+ | 23 | | 45 | +-----+ 2 rows in set (0.00 sec) ``` similary trivial example of `JOIN`: ``` mysql> SELECT * FROM -> (SELECT 23 AS bah) AS foo -> JOIN -> (SELECT 45 AS bah) AS bar -> ON (33=33); +-----+-----+ | foo | bar | +-----+-----+ | 23 | 45 | +-----+-----+ 1 row in set (0.01 sec) ```
[UNION](http://msdn.microsoft.com/en-us/library/ms180026.aspx "UNION") combines the results of two or more queries into a single result set that includes all the rows that belong to all queries in the union. By using [JOINs](http://msdn.microsoft.com/en-us/library/ms191517.aspx "JOINS"), you can retrieve data from two or more tables based on logical relationships between the tables. Joins indicate how SQL should use data from one table to select the rows in another table. The UNION operation is different from using JOINs that combine columns from two tables. UNION Example: ``` SELECT 1 AS [Column1], 2 AS [Column2] UNION SELECT 3 AS [Column1], 4 AS [Column2] ``` Output: ``` Column1 Column2 ------------------- 1 2 3 4 ``` JOIN Example: ``` SELECT a.Column1, b.Column2 FROM TableA a INNER JOIN TableB b ON a.Id = b.AFKId ``` This will output all the rows from both the tables for which the condition `a.Id = b.AFKId` is true.
What is the difference between JOIN and UNION?
[ "", "sql", "database", "join", "union", "" ]
I need to generate reports in my PHP website (in zend framework) Formats required: ``` PDF (with tables & images) // presently using Zend_Pdf XLS (with tables & images) DOC (with tables & images) CSV (only tables) ``` Please recommend robust and fast solution for generating reports in PHP. Platform: *Zend Framework on LAMP* **I know there are some tricky solutions for creating such reports, i wonder is there any open source report generation utility that can be used with LAMP environment**
Excel: <http://www.phpexcel.net>
In my LAMP based application, I integrated the ability to generate report with JasperReports successfully. For that, I use PHP/Java Bridge to communicate with Jasper java classes. You might want to try Zend Server since it provide this component at installation time. Check this blog, it was a source of inspiration for my final solution : <http://www.rjohnson.id.au/wordpress/2007/10/27/bullet-proof-jasper-reports-and-php/>
Report generation in PHP (formats required pdf,xls,doc,csv)
[ "", "php", "zend-framework", "zend-pdf", "" ]
This is a multipart question: First, what is your personal opinion of Workflow? Second, are there any other good .NET-based workflow engines? Some information about my usage: * Using both static and dynamic workflows * Integrate with Castle (Monorail and Windsor) * Utilizing queuing via MSMQ * We want a simple, clean, non-leviathan framework. * GUI workflow editing is not really required, but I don't care if it has it. I don't care whether the workflow is defined in DB, XML or Code, as however we decide to define it we can write an adapter if it's not already supported. Proprietary (free or fee) is fine, but open source is preferred.
I don't like the fact that workflows are persisted to the database in a binary format. It means you can't make sense of it by just looking at the database. There is only very weak support for versioning. This means that if you update your workflow it is a real hassle to make sure any existing workflows running on the previous version can finish. You need to mess around with web.config and specify the different version's of your .dll files. I did play around with a couple. [WorkflowGen](http://www.workflowgen.com/) was pretty easy to use and powerful. But in the end I just decided to roll my own because we only needed workflows for simple tasks such as sending emails to suppliers when purchase orders were raised and invoices needed to be paid. I also had complete control of the source and could make modifications this way.
I have used <http://codeplex.com/simplestatemachine> in one production system successfully (an ASP.NET system for handling 350+ different government business license issuance). A simple state machine is implemented in Boo, so we just expose the definition in a text file which the system administrator can modify. In the editor we do verification to make sure the editing is correct and the workflow is actually functional. Today I found this, <https://github.com/nblumhardt/stateless>, which looks interesting. We switched to an open source alternative simply because our experience with Workflow was not good.
Workflow Engine for .NET
[ "", "c#", ".net", "workflow", "workflow-foundation", "" ]
The pragmatists have won the argument of surrogate vs. natural primary keys in favor of surrogate keys\*. In my own work I always use SQL Server identity columns without a second thought. But it occurs to me that, for a table to be in 1st normal form, I should be able to identify a natural key and enforce it with a unique constraint. I can't do this for all the tables in my database, so my database doesn't even meet the lowest criteria of normalization. Do you agree that a table with a surrogate primary key must also have a unique constraint on a natural key in order to be in 1NF? \*I think Joe Celko is still fighting the good fight, see the [last paragraph](http://www.intelligententerprise.com/channels/business_intelligence/showArticle.jhtml;jsessionid=3O5G0FAW0VNDGQSNDLOSKHSCJUNN2JVN?articleID=201806814&pgno=2). Edited to add: Thanks for the responses. My impression is that adding a unique constraint is not a common practice, so I'm somewhat surprised that the responses so far have been unanimous.
# Yes! If the table is supposed to record at most instance of the natural key, you need a constraint on the relevant column(s) to enforce that. Otherwise, you can end up with a table of 50,000,000 rows, each with a different ID value but otherwise identical -- which is pathetic or ludicrous or a travesty, depending on your viewpoint.
Let me reframe the question. The interesting point isn't whether the table is or is not in 1NF. The interesting point is whether the natural data is in 1NF. If you remove the ID column, and then wipe out the duplicates, you've performed what's called a "projection" in relational speak. The result is in 1NF by definition. If you remove the ID column, but don't wipe out duplicates, you end up with a bag of rows, not a set. If the application somehow doesn't prevent duplicates from getting into that bag, then the bag is not in 1NF. My answer boils down to the same as Jonathan's and Tom's. The net effect is that you've moved the defense of data integrity back out of the DBMS and back into the application. Application programmers tend to do this, in this case and in many others. If they code their applications right, then it's a matter of preference. If they don't, then they've regressed to the state of the art before databases were introduced.
Does a table with a surrogate key require a unique constraint on a natural key to be in 1NF?
[ "", "sql", "database", "database-design", "" ]
There is no built in `reverse` method for Python's `str` object. How can I reverse a string?
Using [slicing](https://stackoverflow.com/questions/509211/understanding-slicing): ``` >>> 'hello world'[::-1] 'dlrow olleh' ``` --- Slice notation takes the form `[start:stop:step]`. In this case, we omit the `start` and `stop` positions since we want the whole string. We also use `step = -1`, which means, "repeatedly step from right to left by 1 character".
@Paolo's `s[::-1]` is fastest; a slower approach (maybe more readable, but that's debatable) is `''.join(reversed(s))`.
How do I reverse a string in Python?
[ "", "python", "string", "" ]
I try to calculate with JS' modulo function, but don't get the right result (which should be 1). Here is a hardcoded piece of code. ``` var checkSum = 210501700012345678131468; alert(checkSum % 97); Result: 66 ``` Whats the problem here? Regards, Benedikt
A bunch of improvements to Benedikt's version: `cRest += '' + cDivident;` is a bugfix; `parseInt(divisor)` makes it possible to pass both arguments as strings; check for empty string at the end makes it always return numerical values; added var statements so it's not using global variables; converted foreach to old-style for so it works in browsers with older Javascript; fixed the `cRest == 0;` bug (thanks @Dan.StackOverflow). ``` function modulo(divident, divisor) { let cDivident = ''; let cRest = ''; for (let i in divident) { let cChar = divident[i]; let cOperator = cRest + '' + cDivident + '' + cChar; if (cOperator < parseInt(divisor)) { cDivident += '' + cChar; } else { cRest = cOperator % divisor; if (cRest == 0) { cRest = ''; } cDivident = ''; } } cRest += '' + cDivident; if (cRest == '') { cRest = 0; } return cRest; } ```
For an IBAN calculation form a normal bankaccount number I end up with a very large number contained in a string datatype. From this large number I have to find the rest when divided by 97 -> large number % 97. As soon as I convert the datatype to an integer I get an overflow resulting in a negative integer and eventually a wrong rest value. As I saw some verbose pieces of code (which also gave wrong outcome), I could not resist to share my own. Credits go to [Finding Modulus of a Very Large Number with a Normal Number](http://www.devx.com/tips/Tip/39012) ``` modulo: function(divident, divisor) { var partLength = 10; while (divident.length > partLength) { var part = divident.substring(0, partLength); divident = (part % divisor) + divident.substring(partLength); } return divident % divisor; } ``` N.B. I use 10 positions here as this is smaller than the 15 (and some) positions of max integer in JavaScript, it results in a number bigger than 97 and it's a nice round number. The first two arguments matter.
Modulo in JavaScript - large number
[ "", "javascript", "integer", "modulo", "" ]
In C#, is there a way to put a static variable in a method like VB.Net? ``` Static myCollection As Collection ```
> Why doesn't C# support static method > variables? > > Q: In C++, it's possible to write a > static method variable, and have a > variable that can only be accessed > from inside the method. C# doesn't > provide this feature. Why? > > A: There are two reasons C# doesn't > have this feature. > > First, it is possible to get nearly > the same effect by having a > class-level static, and adding method > statics would require increased > complexity. > > Second, method level statics are > somewhat notorious for causing > problems when code is called > repeatedly or from multiple threads, > and since the definitions are in the > methods, it's harder to find the > definitions. > > -- [msdn c# faq](http://blogs.msdn.com/csharpfaq/archive/2004/05/11/130248.aspx)
No there isn't but how is this different then having a static variable at the class level? [Actually if you look](http://weblogs.asp.net/psteele/pages/7717.aspx) into how shared is implemented, it is a compiler trick that creates a static field on the class.
Static variables in C#
[ "", "c#", "variables", "static-variables", "" ]
There are a lot of programs, Visual Studio for instance, that can detect when an outside program modifies a file and then reload the file if the user wants chooses. Is there a relatively easy way to do this sort of thing in C++ (doesn't necessarily have to be platform independent)?
There are several ways to do this depending on the platform. I would choose from the following choices: ## Cross Platform Trolltech's Qt has an object called [QFileSystemWatcher](http://doc.qt.io/qt-5/qfilesystemwatcher.html) which allows you to monitor files and directories. I'm sure there are other cross platform frameworks that give you this sort of capability too, but this one works fairly well in my experience. ## Windows (Win32) There is a Win32 api called [FindFirstChangeNotification](http://msdn.microsoft.com/en-us/library/aa364417%28VS.85%29.aspx) which does the job. There is a nice article which a small wrapper class for the api called [How to get a notification if change occurs in a specified directory](http://www.codeproject.com/KB/files/DirCheck.aspx) which will get you started. ## Windows (.NET Framework) If you are ok using C++/CLI with the .NET Framework then [System.IO.FileSystemWatcher](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher%28VS.80%29.aspx#Mtps_DropDownFilterText) is your class of choice. Microsoft has a nice article on [how to monitor file system changes](http://msdn.microsoft.com/en-us/library/chzww271.aspx) using this class. ## OS X The [FSEvents](http://developer.apple.com/documentation/Darwin/Conceptual/FSEvents_ProgGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40005289-CH1-DontLinkElementID_15) API is new for OS X 10.5 and very full-featured. ## Linux Use [inotify](http://en.wikipedia.org/wiki/Inotify) as Alex mentioned in his answer.
If you don't need to be platform-independent, an approach on Linux that may be less of a machine load than "polling" (checking periodically) is `inotify`, see <http://en.wikipedia.org/wiki/Inotify> and the many links from it for example. For Windows, see <http://msdn.microsoft.com/en-us/library/aa365261(VS.85).aspx> .
How do I make my program watch for file modification in C++?
[ "", "c++", "file-io", "filesystems", "monitoring", "fsevents", "" ]
Almost everything is in the title : Here's what I'd like to do : 1. A nice html page with a php authentication process (http first then http**s** & so on) 2. Launch a flex app which *knows* (I don't know **how** (this is the actual question !)) the user has already been authenticated and display his/her stuff he/she has to do for the day (or whatever...). Of course if someone try to call directly the flex app I would display an "authentication error" message and then redirect to the authentication page. I'm sorry for my English which is perfectible. I was thinking about the session cookie : first authenticate then ass a variable on the server side, something like : ``` $_SESSION['authenticate']=true ``` Then, on the flex side, just send the cookie and ask if the user is properly authenticated, something like calling a php web page like : ``` https://is_authenticated.php?php_session=xxxx ``` Thank you Olivier
What are you using on the server side? Remember that you shouldn't do anything in the flex application other then send the SESSION ID along with any requests. Any time where the client checks security, you have a bug. The server must validate the session and determine if the request is allowed. It sounded in your last comment that you are worried about people manually calling a web page. Each page must check to see if the user is authenticated. I don't know your specific application, but you may try looking at [AMFPHP](http://www.amfphp.org) and see how they do [session authentication](http://www.amfphp.org/docs/helperclasses.html). Good luck!
Your on the right track! You could use session-authentication, these links might help you out: * <http://www.zend.com/zend/spotlight/sessionauth7may.php> * <http://www.tizag.com/phpT/phpsessions.php> There is also the possibility to use http-authentication * <https://www.php.net/features.http-auth> however http-authentication is not as flexible as session-authentication, and also means some more configuration on the serverside.I would therefore recommend you to stick with sessions.
Any idea how to do (1) php authentication (2) launch a flex app which knows the user has already been authenticated
[ "", "php", "apache-flex", "authentication", "" ]
I am making a web site for my college project. The project is website thats gets everything from web service. Can somebody tell whats going on, and how i fix it ? On one of my pages i have ListView control to display product items, and Pager on same page. On the first time page renderes fine and everything is displayed. When i click on nextPage on Pager, its reload page but doesn't display second page, rather displays same data, if i push once more then i am gettin: ``` Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request. ``` My products page i quiet simple: ``` <asp:ListView ID="lv_ProductList" runat="server" DataKeyNames="product_id"> <LayoutTemplate> <asp:PlaceHolder ID="itemPlaceholder" runat="server" /> <br /> <br /> <asp:DataPager ID="pageTopics" runat="server" PageSize="8" PagedControlID="lv_ProductList" > <Fields> <asp:NextPreviousPagerField ShowFirstPageButton="false" ShowPreviousPageButton="true" ShowNextPageButton="false" ButtonCssClass="span" /> <asp:NumericPagerField /> <asp:NextPreviousPagerField ShowFirstPageButton="false" ShowPreviousPageButton="false" ShowNextPageButton="true" ShowLastPageButton="false" /> </Fields> </asp:DataPager> </LayoutTemplate> <ItemTemplate> <div class="item"> <img src="images/pic_1.jpg" width="91" height="105" alt="iPod" class="left" /> <h3><a href="http://www.justwebtemplates.com"><%# Eval("product_name") %></a></h3> <p><%# Eval("product_desc").ToString().Substring(0,90) + "..." %> </p> <div><a href="http://www.freewebsitetemplates.com" class="details">details</a> <a href="http://www.freewebsitetemplates.com" class="addtocart">add to cart</a></div> <div class="divider"></div> </div> </ItemTemplate> <EmptyDataTemplate>No products found</EmptyDataTemplate> <EmptyItemTemplate>No products found</EmptyItemTemplate> </asp:ListView> ``` And in the code behind i have: ``` protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { getProductsList(); } } public void getProductsList() { Store.Service myProducts = new Store.Service(); var products = myProducts.getProductList(); lv_ProductList.DataSource = products; lv_ProductList.DataBind(); } ``` and on the web service: ``` [WebMethod] public List<ws_product> getProductList() { using (DataClassesDataContext myProducts = new DataClassesDataContext()) { var productList = from p in myProducts.ws_products select p; return productList.ToList(); } ``` } Can somebody tell whats going on ? Also if i take Pager outside the ListView, then i don't get error, however if i click on the nextpage link it displays same set of data. How do i fix it ? Thank you in advance.
On your code behind add: ``` protected void lds_Selecting(object sender, LinqDataSourceSelectEventArgs args) { Store.Service myProducts = new Store.Service(); args.Result = myProducts.getProductList(); } ``` Add asp:LinqDataSource to the page: ``` <asp:LinqDataSource ID="lds" runat="server" OnSelecting="lds_Selecting" /> <asp:ListView ID="lv_ProductList" runat="server" DataKeyNames="product_id" DataSourceID="lds"> <LayoutTemplate> <asp:PlaceHolder ID="itemPlaceholder" runat="server" /> <br /> <br /> <asp:DataPager ID="pageTopics" runat="server" PageSize="8" PagedControlID="lv_ProductList" > <Fields> <asp:NextPreviousPagerField ShowFirstPageButton="false" ShowPreviousPageButton="true" ShowNextPageButton="false" ButtonCssClass="span" /> <asp:NumericPagerField /> <asp:NextPreviousPagerField ShowFirstPageButton="false" ShowPreviousPageButton="false" ShowNextPageButton="true" ShowLastPageButton="false" /> </Fields> </asp:DataPager> </LayoutTemplate> <ItemTemplate> <div class="item"> <img src="images/pic_1.jpg" width="91" height="105" alt="iPod" class="left" /> <h3><a href="http://www.justwebtemplates.com"><%# Eval("product_name") %></a></h3> <p><%# Eval("product_desc").ToString().Substring(0,90) + "..." %> </p> <div><a href="http://www.freewebsitetemplates.com" class="details">details</a> <a href="http://www.freewebsitetemplates.com" class="addtocart">add to cart</a></div> <div class="divider"></div> </div> </ItemTemplate> <EmptyDataTemplate>No products found</EmptyDataTemplate> <EmptyItemTemplate>No products found</EmptyItemTemplate> </asp:ListView> ``` this should work.
This isn't exactly my area of expertise, but I may be able to provide some conceptual guidance. Although you have put a pager control on your page, you have not implemented paging in your codebehind or your service. Your service is going to need to accept index and length parameters, so the browser can say "I'm now on item 20 and I'm looking at 10 at a time, so now go to the db and send back items 30-39." Your service must actually support the paging. Alternatively, you could load all items into the page once and use a jQuery-like library to do "virtual" paging, instead of posting back, but I imagine that is outside the scope of your school project.
Problem: Failed to load viewstate
[ "", "c#", ".net", "asp.net", "linq", "web-services", "" ]
I have an `input type="file"` element with `size="70"` and `width="522px"`. It looks and works fine in all browsers on Windows but in Firefox on Linux the input element is bigger than 522 pixels. Things I tried: 1. `max-width:522px` but it doesn't work (Linux). 2. setting `size="52"` and `min-width:522px;` looks fine in Linux but doesn't work on in Firefox on Windows. What can I do to specify 522 pixels width?
The problem is that the browser doesn't consider the button as part of the input. So if you have something like: ``` <div style="width: 500px; overflow: hidden"> <input type="file" id="uploadfile_0" class="fileinput" style="border: 2px solid #a9a9a9; width: 100%; height: 22px;" name="uploadfile_0"/> </div> ``` The input button browse is outside the parent, and I don't think there is an easy solution to this. You can read [about styling input type="file"](http://www.quirksmode.org/dom/inputfile.html) on quirksmode.org
Specify only CSS `width`, like this: ``` <input type="file" style="width: 522px;" ..... /> ```
Input type file size varies in Linux/ Windows
[ "", "javascript", "html", "css", "" ]
The code is fairly simple --- the issue is that there is an invalid character in the groupPath string (a '/' to be exact). What I'm trying to do (at least as a stop gap) is skip over DirectoryEntries that I can't get the cn for --- regardless of why. However when I run this code the catch block doesn't run and I get instead: The server is not operational. and an unhandled System.Runtime.InteropServices.COMException. Why would the catch block not catch this exception. ``` try { using (DirectoryEntry groupBinding = new DirectoryEntry("LDAP://" + groupPath)) { using (DirectorySearcher groupSearch = new DirectorySearcher(groupBinding)) { using (DirectoryEntry groupEntry = groupSearch.FindOne().GetDirectoryEntry()) { results.Add(string.Format("{0}", groupEntry.Properties["cn"].Value.ToString())); } } } } catch { Logger.Error("User has bad roles"); } ``` Additional observations: The code is actually in a custom RoleProvider, and the curious thing is that if I reference, this provider in a simple winforms app, and call this same method with the same inputs the catch block does exactly what it's suppose to do. I think this suggests that the proposed answer concerning .NET exceptions versus COM exceptions is not accurate. Although I am at a loss to understand why this code would not catch when executed from the WebDev server
When you don't specify what to catch, it defaults to .NET exceptions. Your exception is in COM where .NET isn't set to catch the exception. The best way to deal with this is to catch the COM exception, which should look something like this: ``` try { } catch (System.Runtime.InteropServices.COMException COMex) { } catch (System.Exception ex) { } ```
There's three reasons: 1. There's a bug in the runtime 2. The application and/or thread is ending as part of some of the code that executes 3. You're not seeing the whole picture Personally I vote for 3, and I have had countless debugging sessions where I wonder why some piece of code isn't handling my exceptions, when in fact it was Visual Studio that was configured to stop on all thrown exceptions, regardless of whether they was caught or not. Have you tried just asking the program to continue running in the debugger and see if it then ends up in the catch-block? Also, check the setting in Visual Studio, go to the Debug->Exceptions dialog, and check if you got any of the Thrown checkboxes checked. If you have, that might be your problem. Of course, if you see this problem at runtime, no debugger attached, then I have no idea, except for point 1 and 2 above. And of course there's always point 4: The unknown.
Why would this catch all block not in fact catch all
[ "", "c#", ".net", "directoryservices", "roleprovider", "" ]
If I want to declare a vector of unknown size, then assign values to index 5, index 10, index 1, index 100, in that order. Is it easily doable in a vector? It seems there's no easy way. Cause if I initialize a vector without a size, then I can't access index 5 without first allocating memory for it by doing resize() or five push\_back()'s. But resize clears previously stored values in a vector. I can construct the vector by giving it a size to begin with, but I don't know how big the vector should. So how can I not have to declare a fixed size, and still access non-continuous indices in a vector? (I doubt an array would be easier for this task).
Resize doesn't clear the vector. You can easily do something like: ``` if (v.size() <= n) v.resize(n+1); v[n] = 42; ``` This will preserve all values in the vector and add just enough default initialized values so that index `n` becomes accessible. That said, if you don't need all indexes or contigous memory, you might consider a different data structure.
Would an std::map between integer keys and values not be an easier solution here? Vectors will require a contiguous allocation of memory, so if you're only using the occasional index, you'll "waste" a lot of memory.
C++: Assigning values to non-continuous indexes in vectors?
[ "", "c++", "stl", "vector", "" ]
I have an application (C#) and I am tasked with putting some simple licensing scheme in it. While doing that I need to save that information somewhere in computer to limit the usage. I need to save a date and a counter. How and where I should save the information which, on Windows Vista, doesnt require administrative privileges to run? (Which means saving it in System32, Program Files, HKEY\_LOCAL\_MACHINE is not an option.) Please do not flood the answers with "don't do it" or "it will be cracked anyway". I do understand those logics. I just need to do anything best that can be done for this purpose.
Consider using a third-party licensing component, such as [XHEO](http://www.xheo.com/) - there's no need to reinvent the wheel. If you are still required to write your own license system, consider using the user's profile directories or the `HKEY_CURRENT_USER` branch.
we use a signed XML license file. It's a simple XML file, that displays what the user has purchased. The nice thing about this is that it's future compat. You can easily add a product feature, or product line, expiration dates, and feature attributes. It's easy for our commerce site to create and package licenses on demand, just be sure your private keys never get out. The pros outway the cons here for us, and the biggest problem we can't circumvent, is simply coping the license file. here is a sample xml file ``` <?xml version="1.0" encoding="utf-8"?> <ProductName> <License> <LicenseId>20025fb9-5349-46d4-a530-55b0295beaaa</LicenseId> <CustomerName>Scott.Cate@Example.com</CustomerName> <MajorVersion>2008</MajorVersion> <Product>Friendly Display Name</Product> <ProductType>Enterprise</ProductType> <Features> <!--Add features here--> </Features> <Expires>0001-01-01T00:00:00</Expires> </License> <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo> <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /> <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /> <Reference URI=""> <Transforms> <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /> </Transforms> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> <DigestValue>u3{..........}U2jo=</DigestValue> </Reference> </SignedInfo> <SignatureValue>QFg1kI{...............}DwDIE=</SignatureValue> </Signature> </ProductName> ``` And we use simple .NET built in API's to do the XML signing, and confirmation that it is singed and valid. Things I like ... .. It's easy to read. (for tech support) .. It's easy to replace .. Easy to store, in the files system, or in our case, the database, for easy access into and out of the UI. (we have an in place update/upgrade system) .. it's easy to upgrade. We have a service that takes your old license, and after validation, offers upgrade pricing based on what's already been purchased. Then the commerce system logs the old and new license files for reference. Things I don't like ... .. Could be copied, stolen easily
Where and how should I save license related information?
[ "", "c#", ".net", "licensing", "copy-protection", "" ]
Say, I have a string that I need to verify the correct format of; e.g. `RR1234566-001` (2 letters, 7 digits, dash, 1 or more digits). I use something like: ``` Regex regex = new Regex(patternString); if (regex.IsMatch(stringToMatch)) { return true; } else { return false; } ``` This works to tell me whether the `stringToMatch` follows the pattern defined by `patternString`. What I need though (and I end up extracting these later) are: `123456` and `001` -- i.e. portions of the `stringToMatch`. Please note that this is NOT a question about how to construct regular expressions. What I am asking is: "Is there a way to match and extract values simultaneously without having to use a split function later?"
You can use regex groups to accomplish that. For example, this regex: ``` (\d\d\d)-(\d\d\d\d\d\d\d) ``` Let's match a telephone number with this regex: ``` var regex = new Regex(@"(\d\d\d)-(\d\d\d\d\d\d\d)"); var match = regex.Match("123-4567890"); if (match.Success) .... ``` If it matches, you will find the first three digits in: ``` match.Groups[1].Value ``` And the second 7 digits in: ``` match.Groups[2].Value ``` P.S. In C#, you can use a @"" style string to avoid escaping backslashes. For example, @"\hi\" equals "\\hi\\". Useful for regular expressions and paths. P.S.2. The first group is stored in Group[1], not Group[0] as you would expect. That's because Group[0] contains the entire matched string.
Use grouping and Matches instead. I.e.: ``` // NOTE: pseudocode. Regex re = new Regex("(\\d+)-(\\d+)"); Match m = re.Match(stringToMatch)) if (m.Success) { String part1 = m.Groups[1].Value; String part2 = m.Groups[2].Value; return true; } else { return false; } ``` You can also name the matches, like this: ``` Regex re = new Regex("(?<Part1>\\d+)-(?<Part2>\\d+)"); ``` and access like this ``` String part1 = m.Groups["Part1"].Value; String part2 = m.Groups["Part2"].Value; ```
Regular expressions C# - is it possible to extract matches while matching?
[ "", "c#", "regex", "extract", "" ]
Where can I get a list of browser differences in the implementation of DOM?
check out <http://quirksmode.org/> Its been a great help to me. It also has a wealth of classy javascript tutorials. cheers, jrh
Okay it's only for Gecko but for Gecko specific references take a look at <http://developer.mozilla.org/en/gecko_dom_reference>
Wanted: Resource for documented Cross-Browser differences
[ "", "javascript", "dom", "cross-browser", "" ]
I've got a nested loop construct like this: ``` for (Type type : types) { for (Type t : types2) { if (some condition) { // Do something and break... break; // Breaks out of the inner loop } } } ``` Now how can I break out of both loops? I've looked at similar questions, but none concerns Java specifically. I couldn't apply these solutions because most used gotos. I don't want to put the inner loop in a different method. I don't want to return the loops. When breaking I'm finished with the execution of the loop block.
Like other answerers, I'd definitely *prefer* to put the loops in a different method, at which point you can just return to stop iterating completely. This answer just shows how the requirements in the question can be met. You can use `break` with a label for the outer loop. For example: ``` public class Test { public static void main(String[] args) { outerloop: for (int i=0; i < 5; i++) { for (int j=0; j < 5; j++) { if (i * j > 6) { System.out.println("Breaking"); break outerloop; } System.out.println(i + " " + j); } } System.out.println("Done"); } } ``` This prints: ``` 0 0 0 1 0 2 0 3 0 4 1 0 1 1 1 2 1 3 1 4 2 0 2 1 2 2 2 3 Breaking Done ```
Technically the correct answer is to label the outer loop. In practice if you want to exit at any point inside an inner loop then you would be better off externalizing the code into a method (a static method if needs be) and then call it. That would pay off for readability. The code would become something like that: ``` private static String search(...) { for (Type type : types) { for (Type t : types2) { if (some condition) { // Do something and break... return search; } } } return null; } ``` Matching the example for the accepted answer: ``` public class Test { public static void main(String[] args) { loop(); System.out.println("Done"); } public static void loop() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i * j > 6) { System.out.println("Breaking"); return; } System.out.println(i + " " + j); } } } } ```
How do I break out of nested loops in Java?
[ "", "java", "loops", "nested-loops", "" ]
I have found various plugins for auto-growing a *textarea*, but not input text fields. Does anybody know if any exist?
Here's a plugin that'll do what you're after: **EDIT**: I've fixed the plugin as per Mathias' comment. :) See a demo here: **<http://jsfiddle.net/rRHzY>** The plugin: ``` (function($){ $.fn.autoGrowInput = function(o) { o = $.extend({ maxWidth: 1000, minWidth: 0, comfortZone: 70 }, o); this.filter('input:text').each(function(){ var minWidth = o.minWidth || $(this).width(), val = '', input = $(this), testSubject = $('<tester/>').css({ position: 'absolute', top: -9999, left: -9999, width: 'auto', fontSize: input.css('fontSize'), fontFamily: input.css('fontFamily'), fontWeight: input.css('fontWeight'), letterSpacing: input.css('letterSpacing'), whiteSpace: 'nowrap' }), check = function() { if (val === (val = input.val())) {return;} // Enter new content into testSubject var escaped = val.replace(/&/g, '&amp;').replace(/\s/g,'&nbsp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); testSubject.html(escaped); // Calculate new width + whether to change var testerWidth = testSubject.width(), newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth, currentWidth = input.width(), isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth) || (newWidth > minWidth && newWidth < o.maxWidth); // Animate width if (isValidWidthChange) { input.width(newWidth); } }; testSubject.insertAfter(input); $(this).bind('keyup keydown blur update', check); }); return this; }; })(jQuery); ```
I have a jQuery plugin on GitHub: <https://github.com/MartinF/jQuery.Autosize.Input> It uses the same approach as James answer but have some of the changes mentioned in the comments. You can see an live example here: <http://jsfiddle.net/mJMpw/6/> Example: ``` <input type="text" value="" placeholder="Autosize" data-autosize-input='{ "space": 40 }' /> input[type="data-autosize-input"] { width: 90px; min-width: 90px; max-width: 300px; transition: width 0.25s; } ``` You just use css to set min/max-width and use a transition on the width if you want a nice effect. You can specify the space / distance to the end as the value in json notation for the data-autosize-input attribute on the input element. Of course you can also just initialize it using jQuery ``` $("selector").autosizeInput(); ```
Is there a jQuery autogrow plugin for text fields?
[ "", "javascript", "jquery", "scripting", "" ]
I recently switched to a new setup that is reporting PHP Notices; my code has worked fine without these notices being fixed, but I am wondering if it makes sense to fix every one and leave them reported or just ignore them and turn notice reporting off. What are some different opinions on this? Are there any best practices associated with notices?
Errors are errors. They have to be fixed before your code works. Warnings are warnings. They warn you that what you're doing is probably a bad idea, even if it works (or seems to work) for you at the moment. So they too should probably be fixed. Notices are notices. They should be noticed. Hence the name. It may not be a problem that your code generates some, but it's something you should examine and judge on a case-by-case basis. And of course, it is much easier to notice notices if you don't get 400 of them. So there's a big benefit to trying to eliminate them. It makes the ones you haven't yet noticed become more noticeable.
Yes, I would eliminate notices from any PHP code I write, even if it's just turning off the specific notice ID once I've investigated all instances of it. Notices (i.e. undefined index, initialised variable) very often indicate a situation you've forgotten to anticipate. You should investigate each one, eliminate the real problems, then possibly suppress the others (with a comment stating why). The PHP manual itself states "NOTICE messages will warn you about bad style", so I guess the official "best practice" would be pretty much what I outlined. Follow good style, unless you have a valid reason not to.
Should PHP 'Notices' be reported and fixed?
[ "", "php", "" ]
In the mold of [a previous question I asked about the so-called safe library deprecations](https://stackoverflow.com/questions/900338/why-cant-i-use-strerror), I find myself similarly bemused as to why `fopen()` should be deprecated. The function takes two C strings, and returns a FILE\* ptr, or NULL on failure. Where are the thread-safety problems / string overrun problems? Or is it something else? Thanks in advance
There is an official ISO/IEC JTC1/SC22/WG14 (C Language) technical report **TR24731-1** (bounds checking interfaces) and its rationale available at: * <http://www.open-std.org/jtc1/sc22/wg14> There is also work towards TR24731-2 (dynamic allocation functions). The stated rationale for `fopen_s()` is: > ## 6.5.2 File access functions > > When creating a file, the `fopen_s` and `freopen_s` functions improve security by protecting the file from unauthorized access by setting its file protection and opening the file with exclusive access. The specification says: ## 6.5.2.1 The fopen\_s function ### Synopsis ``` #define __STDC_WANT_LIB_EXT1__ 1 #include <stdio.h> errno_t fopen_s(FILE * restrict * restrict streamptr, const char * restrict filename, const char * restrict mode); ``` ### Runtime-constraints None of `streamptr`, `filename`, or `mode` shall be a null pointer. If there is a runtime-constraint violation, `fopen_s` does not attempt to open a file. Furthermore, if `streamptr` is not a null pointer, `fopen_s` sets `*streamptr` to the null pointer. ### Description > The `fopen_s` function opens the file whose name is the string pointed to by > `filename`, and associates a stream with it. > > The mode string shall be as described for `fopen`, with the addition that modes starting > with the character ’w’ or ’a’ may be preceded by the character ’u’, see below: > > * `uw` truncate to zero length or create text file for writing, default permissions > * `ua` append; open or create text file for writing at end-of-file, default permissions > * `uwb` truncate to zero length or create binary file for writing, default permissions > * `uab` append; open or create binary file for writing at end-of-file, default > permissions > * `uw+` truncate to zero length or create text file for update, default permissions > * `ua+` append; open or create text file for update, writing at end-of-file, default > permissions > * `uw+b` or `uwb+` truncate to zero length or create binary file for update, default > permissions > * `ua+b` or `uab+` append; open or create binary file for update, writing at end-of-file, > default permissions > > To the extent that the underlying system supports the concepts, files opened for writing > shall be opened with exclusive (also known as non-shared) access. If the file is being > created, and the first character of the mode string is not ’u’, to the extent that the > underlying system supports it, the file shall have a file permission that prevents other > users on the system from accessing the file. If the file is being created and first character > of the mode string is ’u’, then by the time the file has been closed, it shall have the > system default file access permissions10). > > If the file was opened successfully, then the pointer to `FILE` pointed to by `streamptr` > will be set to the pointer to the object controlling the opened file. Otherwise, the pointer > to `FILE` pointed to by `streamptr` will be set to a null pointer. > > Returns > > The `fopen_s` function returns zero if it opened the file. If it did not open the file or if > there was a runtime-constraint violation, `fopen_s` returns a non-zero value. > > 10) These are the same permissions that the file would have been created with by fopen.
You *can* use `fopen()`. Seriously, don't take any notice of Microsoft here, they're doing programmers a real disservice by deviating from the ISO standards . They seem to think that people writing code are somehow brain-dead and don't know how to check parameters before calling library functions. If someone isn't willing to learn the intricacies of C programming, they really have no business doing it. They should move on to a safer language. This appears to be just another attempt at vendor lock-in by Microsoft of developers (although they're not the only ones who try it, so I'm not specifically berating them). I usually add: ``` #define _CRT_SECURE_NO_WARNINGS ``` (or the `"-D"` variant on the command line) to most of my projects to ensure I'm not bothered by the compiler when writing perfectly valid, legal C code. Microsoft has provided extra functionality in the `fopen_s()` function (file encodings, for one) as well as changing how things are returned. This may make it better for Windows programmers but makes the code inherently unportable. If you're only ever going to code for Windows, by all means use it. I myself prefer the ability to compile and run my code anywhere (with as little change as possible). --- As of C11, these safe functions are now a part of the standard, though optional. Look into Annex K for full details.
Why can't I use fopen?
[ "", "c++", "c", "deprecated", "tr24731", "" ]
I am trying to figure out how to add a custom file type to be recognised by Netbeans. I am editing .tpl files and I would like them to be recognised as PHP/HTML files. I've looked [here](http://www.techienuggets.com/Comments?tx=38126) and [here](http://forums.netbeans.org/ptopic3275.html) but I cant find cnd.properties in config directory and there is no `Advanced Options` dialog in the options dialog. I'm using Netbeans 6.5 with PHP and all modules up to date.
Let me guess, for Smarty templates? I did the following 1. Open Tools and Select Options. 2. Select Miscellaneous tab. 3. Select Files sub-tab thing. 4. Click on **New** file extension and enter **tpl**. 5. Select the mime type. 6. Click OK. Done! 7. (Restart of Netbeans may be required to see the actual changes)
In NetBeans 8.XX this is achieved by going to **NetBeans > Preferences > Miscellaneous > Files**. In the row **File Extension** click on **NEW** and enter your new file extension without the dot (example: *tpl*). Choose the **Associated File Type (MIME)** and click **Apply**.
Add a custom file extension to Netbeans
[ "", "php", "netbeans", "ide", "" ]
What's the best javascript library, or plugin or extension to a library, that has implemented autosaving functionality? The specific need is to be able to 'save' a data grid. Think gmail and Google Documents' autosave. I don't want to reinvent the wheel if its already been invented. I'm looking for an existing implementation of the magical autoSave() function. Auto-Saving:pushing to server code that saves to persistent storage, usually a DB. The server code framework is outside the scope of this question. Note that I'm not looking for an Ajax library, but a library/framework a level higher: interacts with the form itself. daemach introduced an implementation on top of jQuery @ <http://daemach.blogspot.de/2007/03/autosave-jquery-plugin.html> [script host down]. I'm not convinced it meets the lightweight and well engineered criteria though. **Criteria** * stable, lightweight, well engineered * saves onChange and/or onBlur * saves no more frequently then a given number of milliseconds * handles multiple updates happening at the same time * doesn't save if no change has occurred since last save * saves to different urls per input class
Autosave should be pretty simple to implement, and you could use one of the major frameworks like jquery or mootools. All you need to do is use window.setTimeout() once your user edits something that should be autosaved, and have that timeout call the javascript frameworks standard AJAX stuff. For example (with jquery): ``` var autosaveOn = false; function myAutosavedTextbox_onTextChanged() { if (!autosaveOn) { autosaveOn = true; $('#myAutosavedTextbox').everyTime("300000", function(){ $.ajax({ type: "POST", url: "autosavecallbackurl", data: "id=1", success: function(msg) { $('#autosavenotify').text(msg); } }); }); //closing tag } } ```
I know that this question is old, but I would like to include a code that I like the most. I found it here: <http://codetunnel.io/how-to-implement-autosave-in-your-web-app/> Here is the code: ``` var $status = $('#status'), $commentBox = $('#commentBox'), timeoutId; $commentBox.keypress(function () { // or keyup to detect backspaces $status.attr('class', 'pending').text('changes pending'); // If a timer was already started, clear it. if (timeoutId) clearTimeout(timeoutId); // Set timer that will save comment when it fires. timeoutId = setTimeout(function () { // Make ajax call to save data. $status.attr('class', 'saved').text('changes saved'); }, 750); }); ``` It saves after the user stops writing for more than 750 milliseconds. It also has a status letting the user know that the changes have been saved or not
AJAX Autosave functionality
[ "", "javascript", "ajax", "synchronize", "" ]
I am reading a raw audio file (CD track rip) in, doing byte swapping, and then writing back out to a wav file. The routine I have processes the bytes properly, but only does about half the file. I am a VB.NET Developer, not really a C# developer, and this code does not convert to VB.NET properly (It gets an overflow error). It's not really a "swap" so much as a calc/prune. **(short)((buffer[i + 1] \* 256) + buffer[i])** I believe it is writing only half of the samples, but I've no idea how to fix! ``` public static short[] SwapBytesArray(string fileName) { byte[] buffer = System.IO.File.ReadAllBytes(fileName); long fileLength = buffer.LongLength; if ((fileLength & 1) == 1) { throw new ArgumentException("File length must be an even number of bytes"); } System.Collections.Generic.List<short> sList = new System.Collections.Generic.List<short>(); for (long i = 0; i < fileLength - 1; i += 2) { byte tmp = buffer[i]; sList.Add((short)((buffer[i + 1] * 256) + buffer[i])); //buffer[i + 1] = tmp; } return sList.ToArray(); } ```
Why do you want to return an array of `short`? If you are writing back out to a file wouldn't a `byte[]` array be a better choice? i.e ``` public static byte[] SwapBytes(string fileName) { byte[] buffer = System.IO.File.ReadAllBytes(fileName); long fileLength = buffer.LongLength; if ((fileLength & 1) == 1) { throw new ArgumentException("File length must be an even number of bytes"); } for (long i = 0; i < fileLength - 1 ; i +=2 ) { byte tmp = buffer[i]; buffer[i] = buffer[i + 1]; buffer[i + 1] = tmp; } return buffer; } ```
If the size of the file is greater than maximum integer, then you'll overflow the index variable (index should be a long since num is a long). Presumably you use buffer.LongLength instead of buffer.Length because your data is known to be larger, so a likely issue regardless.
Swapping bytes in a file
[ "", "c#", "audio", "" ]
As I understand it, you're supposed to use the `Environment.GetFolderPath` method so you have OS independent code... Windows XP uses `C:\Documents and Settings\`. Windows Vista uses `C:\ProgramData` and `C:\Users`. I'm using the code below on a Windows Vista computer and it's returning a `C:\Documents and Settings\` directory instead of `C:\ProgramData` like it should... Any ideas? ``` string commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); try { File.CreateText( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\mycompany\\uid"); log.Debug("Created file successfully"); } catch (Exception ex) { log.Error("Unable to create the uid file: ", ex); } ```
My installer copied a log.txt file which had been generated on an XP computer. I was looking at that log file thinking it was generated on Vista. Once I fixed my log4net configuration to be "Vista Compatible". Environment.GetFolderPath was returning the expected results. Therefore, I'm closing this post. The following SpecialFolder path reference might be useful: Output On Windows Server 2003: ``` SpecialFolder.ApplicationData: C:\Documents and Settings\blake\Application Data SpecialFolder.CommonApplicationData: C:\Documents and Settings\All Users\Application Data SpecialFolder.ProgramFiles: C:\Program Files SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files SpecialFolder.DesktopDirectory: C:\Documents and Settings\blake\Desktop SpecialFolder.LocalApplicationData: C:\Documents and Settings\blake\Local Settings\Application Data SpecialFolder.MyDocuments: C:\Documents and Settings\blake\My Documents SpecialFolder.System: C:\WINDOWS\system32` ``` Output on Vista: ``` SpecialFolder.ApplicationData: C:\Users\blake\AppData\Roaming SpecialFolder.CommonApplicationData: C:\ProgramData SpecialFolder.ProgramFiles: C:\Program Files SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files SpecialFolder.DesktopDirectory: C:\Users\blake\Desktop SpecialFolder.LocalApplicationData: C:\Users\blake\AppData\Local SpecialFolder.MyDocuments: C:\Users\blake\Documents SpecialFolder.System: C:\Windows\system32 ```
**Output on Ubuntu 9.10 -> Ubuntu 12.04 with mono 2.10.8.1:** ``` SpecialFolder.ApplicationData: /home/$USER/.config SpecialFolder.CommonApplicationData: /usr/share SpecialFolder.ProgramFiles: SpecialFolder.DesktopDirectory: /home/$USER/Desktop SpecialFolder.LocalApplicationData: /home/$USER/.local/share SpecialFolder.MyDocuments: /home/$USER SpecialFolder.System: SpecialFolder.Personal: /home/$USER ``` **Output on Ubuntu 16.04 with mono 4.2.1** ``` SpecialFolder.ApplicationData: /home/$USER/.config SpecialFolder.CommonApplicationData: /usr/share SpecialFolder.ProgramFiles: SpecialFolder.DesktopDirectory: /home/$USER/Desktop SpecialFolder.LocalApplicationData: /home/$USER/.local/share SpecialFolder.MyDocuments: /home/$USER SpecialFolder.Desktop: /home/$USER/Desktop SpecialFolder.Personal: /home/$USER SpecialFolder.System: SpecialFolder.Programs: SpecialFolder.Favorites: SpecialFolder.Startup: SpecialFolder.Recent: SpecialFolder.SendTo: SpecialFolder.StartMenu: SpecialFolder.MyMusic: /home/$USER/Music SpecialFolder.MyVideos: /home/$USER/Videos SpecialFolder.MyComputer: SpecialFolder.NetworkShortcuts: SpecialFolder.Fonts: /home/$USER/.fonts SpecialFolder.Templates: /home/$USER/Templates SpecialFolder.CommonStartMenu: SpecialFolder.CommonPrograms: SpecialFolder.CommonStartup: SpecialFolder.CommonDesktopDirectory: SpecialFolder.PrinterShortcuts: SpecialFolder.InternetCache: SpecialFolder.Cookies: SpecialFolder.History: SpecialFolder.Windows: SpecialFolder.MyPictures: /home/$USER/Pictures SpecialFolder.UserProfile: /home/$USER SpecialFolder.SystemX86: SpecialFolder.ProgramFilesX86: SpecialFolder.CommonProgramFiles: SpecialFolder.CommonProgramFilesX86: SpecialFolder.CommonTemplates: /usr/share/templates SpecialFolder.CommonDocuments: SpecialFolder.CommonAdminTools: SpecialFolder.AdminTools: SpecialFolder.CommonMusic: SpecialFolder.CommonPictures: SpecialFolder.CommonVideos: SpecialFolder.Resources: SpecialFolder.LocalizedResources: SpecialFolder.CommonOemLinks: SpecialFolder.CDBurning: ``` where $USER is the current user **Output on Ubuntu 16.04 using dotnet core (3.0.100)** ``` ApplicationData: /home/$USER/.config CommonApplicationData: /usr/share ProgramFiles: DesktopDirectory: /home/$USER/Desktop LocalApplicationData: /home/$USER/.local/share MyDocuments: /home/$USER System: Personal: /home/$USER ``` **Output on Android 6 using Xamarin 7.2** ``` Environment.SpecialFolder.ApplicationData: /data/user/0/$APPNAME/files/.config Environment.SpecialFolder.CommonApplicationData: /usr/share Environment.SpecialFolder.ProgramFiles: Environment.SpecialFolder.DesktopDirectory: /data/user/0/$APPNAME/files/Desktop Environment.SpecialFolder.LocalApplicationData: /data/user/0/$APPNAME/files/.local/share Environment.SpecialFolder.MyDocuments: /data/user/0/$APPNAME/files Environment.SpecialFolder.Desktop: /data/user/0/$APPNAME/files/Desktop Environment.SpecialFolder.Personal: /data/user/0/$APPNAME/files Environment.SpecialFolder.Startup: Environment.SpecialFolder.Recent: Environment.SpecialFolder.SendTo: Environment.SpecialFolder.StartMenu: Environment.SpecialFolder.MyMusic: /data/user/0/$APPNAME/files/Music Environment.SpecialFolder.MyVideos: /data/user/0/$APPNAME/files/Videos Environment.SpecialFolder.MyComputer: Environment.SpecialFolder.NetworkShortcuts: Environment.SpecialFolder.Fonts: /data/user/0/$APPNAME/files/.fonts Environment.SpecialFolder.Templates: /data/user/0/$APPNAME/files/Templates Environment.SpecialFolder.CommonStartMenu: Environment.SpecialFolder.CommonPrograms: Environment.SpecialFolder.CommonStartup: Environment.SpecialFolder.CommonDesktopDirectory: Environment.SpecialFolder.PrinterShortcuts: Environment.SpecialFolder.InternetCache: Environment.SpecialFolder.Cookies: Environment.SpecialFolder.History: Environment.SpecialFolder.Windows: Environment.SpecialFolder.MyPictures: /data/user/0/$APPNAME/files/Pictures Environment.SpecialFolder.UserProfile: /data/user/0/$APPNAME/files Environment.SpecialFolder.SystemX86: Environment.SpecialFolder.ProgramFilesX86: Environment.SpecialFolder.CommonProgramFiles: Environment.SpecialFolder.CommonProgramFilesX86: Environment.SpecialFolder.CommonTemplates: /usr/share/templates Environment.SpecialFolder.CommonDocuments: Environment.SpecialFolder.CommonAdminTools: Environment.SpecialFolder.AdminTools: Environment.SpecialFolder.CommonMusic: Environment.SpecialFolder.CommonPictures: Environment.SpecialFolder.CommonVideos: Environment.SpecialFolder.Resources: Environment.SpecialFolder.LocalizedResources: Environment.SpecialFolder.CommonOemLinks: Environment.SpecialFolder.CDBurning: ``` Where $APPNAME is the name of your Xamarin application (eg. MyApp.Droid) **Output on Android 11 using MAUI - .net 7.0** ``` Environment.SpecialFolder.MyDocuments: /data/user/0/$APPNAME/files Environment.SpecialFolder.Personal: /data/user/0/$APPNAME/files ``` **Output on Android 11 using MAUI - .net 8.0** ``` Environment.SpecialFolder.MyDocuments: /data/user/0/$APPNAME/files/Documents Environment.SpecialFolder.Personal: /data/user/0/$APPNAME/files/Documents ``` **Output on iOS Simulator 10.3 using Xamarin 7.2** ``` ApplicationData: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/.config CommonApplicationData: /usr/share ProgramFiles: /Applications DesktopDirectory: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Desktop LocalApplicationData: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents MyDocuments: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents Desktop: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Desktop MyDocuments: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents Startup: Recent: SendTo: StartMenu: MyMusic: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Music MyVideos: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Videos MyComputer: NetworkShortcuts: Fonts: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/.fonts Templates: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Templates CommonStartMenu: CommonPrograms: CommonStartup: CommonDesktopDirectory: PrinterShortcuts: InternetCache: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Library/Caches Cookies: History: Windows: MyPictures: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Pictures UserProfile: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID SystemX86: ProgramFilesX86: CommonProgramFiles: CommonProgramFilesX86: CommonTemplates: /usr/share/templates CommonDocuments: CommonAdminTools: AdminTools: CommonMusic: CommonPictures: CommonVideos: Resources: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Library LocalizedResources: CommonOemLinks: CDBurning: ``` Where $DEVICEGUID is the simulator GUID (depending on the selected simulator) **Output on ipad 10.3 using Xamarin 7.2** ``` SpecialFolder.MyDocuments: /var/mobile/Containers/Data/Application/$APPLICATIONGUID/Documents ``` **Output on ipad 13.3 using Xamarin 16.4** ``` SpecialFolder.MyDocuments: /var/mobile/Containers/Data/Application/$APPLICATIONGUID/Documents SpecialFolder.UserProfile: /private/var/mobile/Containers/Data/Application/$APPLICATIONGUID/Documents ``` **Output on windows 10 using .net core 3.1** ``` SpecialFolder.MyDocuments: C:\Users\$USER\Documents ``` **Output on Ubuntu 18.04 using .net core 3.1** ``` SpecialFolder.MyDocuments: /home/$USER ``` **Output on Ubuntu 22.04 using .net core 7.0.112** ``` SpecialFolder.Personal: /home/$USER SpecialFolder.MyDocuments: /home/$USER ``` **Output on Ubuntu 22.04 using .net core 8.0.100-rc.2.23502.2** ****WARNING BREAKING CHANGE**** ``` SpecialFolder.Personal: /home/$USER/Documents SpecialFolder.MyDocuments: /home/$USER/Documents ``` **Output on MacOS Catalina using .net core 3.1** ``` SpecialFolder.Desktop: /Users/$USER/Desktop SpecialFolder.Programs: SpecialFolder.MyDocuments: /Users/$USER SpecialFolder.Favorites: /Users/$USER/Library/Favorites SpecialFolder.Startup: SpecialFolder.Recent: SpecialFolder.SendTo: SpecialFolder.StartMenu: SpecialFolder.MyMusic: /Users/$USER/Music SpecialFolder.MyVideos: SpecialFolder.DesktopDirectory: /Users/$USER/Desktop SpecialFolder.MyComputer: SpecialFolder.NetworkShortcuts: SpecialFolder.Fonts: /Users/$USER/Library/Fonts SpecialFolder.Templates: SpecialFolder.CommonStartMenu: SpecialFolder.CommonPrograms: SpecialFolder.CommonStartup: SpecialFolder.CommonDesktopDirectory: SpecialFolder.ApplicationData: /Users/$USER/.config SpecialFolder.PrinterShortcuts: SpecialFolder.LocalApplicationData: /Users/$USER/.local/share SpecialFolder.InternetCache: /Users/$USER/Library/Caches SpecialFolder.Cookies: SpecialFolder.History: SpecialFolder.CommonApplicationData: /usr/share SpecialFolder.Windows: SpecialFolder.System: /System SpecialFolder.ProgramFiles: /Applications SpecialFolder.MyPictures: /Users/$USER/Pictures SpecialFolder.UserProfile: /Users/$USER SpecialFolder.SystemX86: SpecialFolder.ProgramFilesX86: SpecialFolder.CommonProgramFiles: SpecialFolder.CommonProgramFilesX86: SpecialFolder.CommonTemplates: SpecialFolder.CommonDocuments: SpecialFolder.CommonAdminTools: SpecialFolder.AdminTools: SpecialFolder.CommonMusic: SpecialFolder.CommonPictures: SpecialFolder.CommonVideos: SpecialFolder.Resources: SpecialFolder.LocalizedResources: SpecialFolder.CommonOemLinks: SpecialFolder.CDBurning: ``` **Output on Snap Package - Core 18 using .net core 3.1** ``` Desktop: Programs: MyDocuments: /home/$USER/snap/$APPNAME/x$VERSIONNUMBER MyDocuments: /home/$USER/snap/$APPNAME/x$VERSIONNUMBER Favorites: Startup: Recent: SendTo: StartMenu: MyMusic: MyVideos: DesktopDirectory: MyComputer: NetworkShortcuts: Fonts: Templates: CommonStartMenu: CommonPrograms: CommonStartup: CommonDesktopDirectory: ApplicationData: /home/$USER/snap/$APPNAME/x$VERSIONNUMBER/.config PrinterShortcuts: LocalApplicationData: InternetCache: Cookies: History: CommonApplicationData: /usr/share Windows: System: ProgramFiles: MyPictures: UserProfile: /home/$USER/snap/$APPNAME/x$VERSIONNUMBER SystemX86: ProgramFilesX86: CommonProgramFiles: CommonProgramFilesX86: CommonTemplates: CommonDocuments: CommonAdminTools: AdminTools: CommonMusic: CommonPictures: CommonVideos: Resources: LocalizedResources: CommonOemLinks: CDBurning: ``` Note: I found that if a snap environment if `/home/$USER/snap/$APPNAME/x$VERSION/.local/share` exists then `LocalApplicationData` will return that path. However if the path doesn't exist it returns empty string. Also testing with dotnet 8 on Linux `Environment.GetFolderPath(Environment.SpecialFolder.Personal)` returns empty string if $HOME/Documents folder doesn't exist.
Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista
[ "", "c#", ".net", "special-folders", "" ]
I'm working with Java project that requires very advanced manipulations of images. In fact, I'm doing most of the manipulation using OpenCV, and I'm using JNI to wrap around the OpenCV functions that I need. I am extremely satisfied with the performance OpenCV gives, the people who wrote the OpenCV code deserve great great credit for the code. In sharp contrast to what I experience with the code Java devs wrote. I started out optimistic over the choice of my programming language, my first working iteration of the project works fine, but its performance is nowhere near to realtime (getting about 1 frame per 2 seconds.) I've done some optimizations of MY code and its helped a lot. I've been able to push the frame rate up to about 10-20 frames per second, which is great, but what I'm finding is that to do any further optimizations I have to rewrite Java code to do the same thing but 10-20x more efficient. I'm appalled at how the developers of Java pay very little attention to performance, especially when writing the classes for Media related classes. I've downloaded OpenJDK and I'm exploring the functions I'm using. For example, there is a function under the Raster class called getPixels(...) and it gets the pixels of the image. I was expecting this function to be a highly optimized function in the source code, with several calls to System.arrayCopy to further optimize performance. Instead what I found was extremely "Classy" code, where they are calling 5-6 different classes and 10-20 different methods just to accomplish what I can do in one line: ``` for (int i =0; i < n; i++) { long p = rawFrame[i]; p = (p << 32) >>> 32; byte red = (byte) ((p >> 16) & 0xff); byte green = (byte) ((p >> 8) & 0xff); byte blue = (byte) ((p) & 0xff); byte val = (byte)(0.212671f * red + 0.715160f * green + 0.072169f * blue); data[i] = val; grayFrameData[i] = (val & 0x80) + (val & (0x7f)); } ``` The code above transforms an image to grayscale and gets the float pixel data, in roughly 1-10ms. If I wanted to do the same with Java built in functions, the conversion to grayscale itself takes 200-300ms and then grabbing the float pixels takes about 50-100ms. This is unacceptable for real time performance. Note to get a speedup, I make heavy use of bitwise operators, which Java devs shy away from. I understand that they need to handle the general case, but even so, can't they at least give options for optimizations or at the very least a warning how slow this code may perform. My question is, at this late point in the development (I already have my first iteration, not I'm working on a second that performs more in real time) should I bite the bullet and switch over to C/C++ where I can fine tune things a lot more, or should I stick with Java and hope things will become more realtime friendly so that I won't have to rewrite already implemented Java code to get a speedup. I'm really beginning to become disgusted with how "classy" and slow Java really is. The amount of classes there are seems like overkill.
I've done computer vision work with Java, and I think it is perfectly usable for computer vision and realtime stuff, you just have to know how to use it. ### Potential Optimizations: If you need help optimizing your code, I'd be glad to assist -- for example, I can tell you that you will probably get a performance boost by making a method ``` `public static final int getGrayScale(final int pixelRGB){ return (0.212671f * ((pixelRGB >> 16) & 0xff) + 0.715160f * ((pixelRGB >> 8) & 0xff) + 0.072169f * ((pixelRGB) & 0xff)); }` ``` and using this in your for{pixels} loop. By using a method call, the JVM can much more heavily optimize this operation, and can probably optimize the for loop more too. If you've got RAM to burn, you can create a static, final lookup table of output grayscale bytes for all possible 24-bit pixel pixel colors. This will be ~16 MB in RAM, but then you don't have to do any floating point arithmetic, just a single array access. This *may* be faster, depending on which JVM you are using, and whether or not it can optimize out array bounds checking. ### Places to find similar, faster image processing code: I would strongly suggest that you take a look at the code for the ImageJ image processing app & its libraries, specifically ij.process.TypeConverter. Just like your code, it relies heavily on **direct array operations with bit-twiddling** and a **minimum of extra array creation**. The Java2D libraries (part of the standard JRE) and the Java Advanced Imaging(JAI) library provide other ways to do image processing directly on image data rapidly without having to roll your own operation every time. For Java2D, you just have to be careful which functions you use. ### Why the Java2D libraries are so indirect: Most of the "class-iness" is due to supporting multiple color models and storage formats (I.E. HSB images, float-based color models, indexed color models). The indirection exists for a reason, and sometimes actually boosts performance -- the BufferedImage class (for example) hooks directly into graphics memory in recent VMs to make some operations MUCH faster. Indirection lets it mask this from the user a lot of the time.
> My question is, at this late point in the development (I already have my first iteration, not I'm working on a second that performs more in real time) should I bite the bullet and switch over to C/C++ where I can fine tune things a lot more, or should I stick with Java and hope things will become more realtime friendly so that I won't have to rewrite already implemented Java code to get a speedup. You are asking should I 1. Switch to a language where I can satisfy my performance requirements. 2. Stick with Java and hope things improve. There might be other options.... but option 2 doesn't seem realistic, you can't just "hope" that the code becomes faster :p A few points to note: 1. OpenJDK does not nescceraly have the same performance as the Sun JDK, have you tried the Sun JDK? 2. If the performance optimizations that you need done are in a few methods, then it might be worth re-writing them and sticking with Java...
Java Realtime Performance
[ "", "java", "performance", "real-time", "" ]
I'm trying to merge 2 lists using "Union" so I get rid of duplicates. Following is the sample code: ``` public class SomeDetail { public string SomeValue1 { get; set; } public string SomeValue2 { get; set; } public string SomeDate { get; set; } } public class SomeDetailComparer : IEqualityComparer<SomeDetail> { bool IEqualityComparer<SomeDetail>.Equals(SomeDetail x, SomeDetail y) { // Check whether the compared objects reference the same data. if (Object.ReferenceEquals(x, y)) return true; // Check whether any of the compared objects is null. if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) return false; return x.SomeValue1 == y.SomeValue1 && x.SomeValue2 == y.SomeValue2; } int IEqualityComparer<SomeDetail>.GetHashCode(SomeDetail obj) { return obj.SomeValue1.GetHashCode(); } } List<SomeDetail> tempList1 = new List<SomeDetail>(); List<SomeDetail> tempList2 = new List<SomeDetail>(); List<SomeDetail> detailList = tempList1.Union(tempList2, SomeDetailComparer).ToList(); ``` Now the question is can I use Union and still get the record which has the latest date (using SomeDate property). The record itself can either be in tempList1 or tempList2. Thanks in advance
The operation that is really suited to this purpose is an [full outer join](http://en.wikipedia.org/wiki/Outer_join#Full_outer_join). The `Enumerable` class has an implementation of inner join, which you can use to find the duplicates and select whichever you prefer. ``` var duplicates = Enumerable.Join(tempList1, tempList2, keySelector, keySelector, (item1, item2) => (item1.SomeDate > item2.SomeDate) ? item1 : item2) .ToList(); ``` `keySelector` is simply a function (could be a lambda expression) that extracts a key from an object of type `SomeDetail`. Now, to implement the full outer join, try something like this: ``` var keyComparer = (SomeDetail item) => new { Value1 = item.SomeValue1, Value2 = item.SomeDetail2 }; var detailList = Enumerable.Union(tempList1.Except(tempList2, equalityComparer), tempList2.Except(tempList1, equalityComparer)).Union( Enumerable.Join(tempList1, tempList2, keyComparer, keyComparer (item1, item2) => (item1.SomeDate > item2.SomeDate) ? item1 : item2)) .ToList(); ``` `equalityComparer` should be an object that implements `IEqualityComparer<SomeDetail>` and effectively uses the `keyComparer` function for testing equality. Let me know if that does the job for you.
Why not just use HashSet<T>? ``` List<SomeDetail> tempList1 = new List<SomeDetail>(); List<SomeDetail> tempList2 = new List<SomeDetail>(); HashSet<SomeDetail> hs = new HashSet<SomeDetail>(new SomeDetailComparer()); hs.UnionWith(tempList1); hs.UnionWith(tempList2); List<SomeDetail> detailList = hs.ToList(); ```
C# Generic List Union Question
[ "", "c#", "linq", "generics", "" ]
I have a datagridview which we will call dataGridViewExample. My object (the uncommon datatypes is because my database is SQLite): ``` class MyObject { public Int64 Vnr { get; set; } public string Name { get; set; } public Single Price { get; set; } public int Amount { get; set; } } ``` Here is the relevant code: ``` //This form gets called with a .ShowDialog(); in my form1. private List<MyObjecte> ExampleList = new List<MyObject>(); public MyForm() { dataGridViewExample.DataSource = OrdreInkøbsListe; } private void AddtoDataGridViewExample() { //Add a new MyObject to the list ExampleList.Add(new myObject() { Vnr = newVnr, Amount = newAmount, Price = newPrice, Name = newName }); //refresh datasource dataGridViewExample.DataSource = null; dataGridViewExample.Refresh(); dataGridViewExample.DataSource = OrdreInkøbsListe; ddataGridViewExample.Refresh(); } ``` When MyForm gets called with a .ShowDialog, it shows up fine and displays my DataGridView example just fine. As you can read from the code, the `ExampleList`is initially empty, so it just shows an empty datagridview with 4 columns: Vnr, Name, Price & Amount. If I click inside it etc. nothing happens - so everything is working as planned, so far. Everytime I call `AddtoDataGridViewExample()` it adds the new object to the Datagridview, and the datagridview does update, listing all the objects added so far (they show themself as rows, again according to plan). Now, remember that I just said that nothing happened if you clicked inside `DataGridViewExample` before I have called `AddtoDataGridViewExample()`? Well, after having called `AddtoDataGridViewExample()` once or more, the program will crash if I click inside `DataGridViewExample` (for example: the users wants to select a row). It throws an **IndexOutOfRangeException** and talks about an -1 index. It also throws the exception in the other form, on the line where I call MyForm with `.ShowDialog()`; I really am stuck on this, do you guys have any idea what is wrong?? **My only clue is** that I do believe the refresh of `DataGridViewExample`'s datasource might be the cause of the problem. Another **important** note: I have yet bound any events to my `DataGridViewExample`. So you can rule that idea out. Here is all `DataGridViewExample`'s properties: ``` this.dataGridViewExample.AllowUserToAddRows = false; this.dataGridViewExample.AllowUserToDeleteRows = false; this.dataGridViewExample.AllowUserToResizeColumns = false; this.dataGridViewExample.AllowUserToResizeRows = false; this.dataGridViewExample.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.dataGridViewExample.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridViewExample.Location = new System.Drawing.Point(591, 53); this.dataGridViewExample.MultiSelect = false; this.dataGridViewExample.Name = "dataGridViewExample"; this.dataGridViewExample.ReadOnly = true; this.dataGridViewExample.RowHeadersVisible = false; this.dataGridViewExample.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridViewExample.ShowEditingIcon = false; this.dataGridViewExample.Size = new System.Drawing.Size(240, 150); this.dataGridViewExample.TabIndex = 31; ```
I guess the click event tries to get the currently selected row and do something with it, while `dataGridViewExample.DataSource = null;` clears the datasource, and the currently selected row becomes null. If you set the `DataGridView.DataSource` to the list, you don't need to reset it to null, refresh, and reset it to the list again (and refresh again) to see the changes. It will be enough to just refresh the `DataGridView`. You can also just try using an `BindingList<T>` object instead of a `List<T>`, which will automatically notify your grid of its internal changes (Adding and removing elements), and there's also an `INotifyPropertyChanged` interface you can implement on your `MyObject` class, that will make every property change in an object show on the grid (For any changes made to the object in the code, and not through the grid itself).
Have you tried running the debugger and break when InedxOutOfRangeException is thrown to see where the exception is thrown? Select Debug > Exceptions then there's a Find button on the dialog so you don't have to browse through all of the possibilities.
Datagridview causing IndexOutOfRangeException when clicked upon
[ "", "c#", "winforms", "datagridview", "" ]
I'm trying to display tooltips in Java which may or may not be paragraph-length. How can I word-wrap long tooltips?
If you wrap the tooltip in `<html>` and `</html>` tags, you can break lines with `<br>` tags. See <https://web.archive.org/web/20060625031340/http://www.jguru.com/faq/view.jsp?EID=10653> for examples and discussion. Main take-awy from that discussion: `fButton.setToolTipText("<html><font face=\"sansserif\" color=\"green\">first line<br>second line</font></html>");` Or you can use the JMultiLineToolTip class that can be found many places on the net, including <https://github.com/ls-cwi/yoshiko-app/blob/master/src/main/java/com/yoshiko/internal/view/JMultiLineToolTip.java>
Tooltip text which starts with "`<html>`" will be treated as HTML. Of course that might be very wide HTML. You can override [JComponent.createTooltip](http://java.sun.com/javase/6/docs/api/javax/swing/JComponent.html#createToolTip()) to replace the tooltip with your own component which can display whatevee you like.
Multi-line tooltips in Java?
[ "", "java", "swing", "tooltip", "" ]
I'm working in Microsoft Visual C# 2008 Express. Let's say I have a string and the contents of the string is: `"This is my <myTag myTagAttrib="colorize">awesome</myTag> string."` I'm telling myself that I want to do something to the word "awesome" - possibly call a function that does something called "colorize". What is the best way in C# to go about detecting that this tag exists and getting that attribute? I've worked *a little* with XElements and such in C#, but mostly to do with reading in and out XML files. Thanks! -Adeena
Another solution: ``` var myString = "This is my <myTag myTagAttrib='colorize'>awesome</myTag> string."; try { var document = XDocument.Parse("<root>" + myString + "</root>"); var matches = ((System.Collections.IEnumerable)document.XPathEvaluate("myTag|myTag2")).Cast<XElement>(); foreach (var element in matches) { switch (element.Name.ToString()) { case "myTag": //do something with myTag like lookup attribute values and call other methods break; case "myTag2": //do something else with myTag2 break; } } } catch (Exception e) { //string was not not well formed xml } ``` I also took into account your comment to Dabblernl where you want parse multiple attributes on multiple elements.
You can extract the XML with a regular expression, load the extracted xml string in a XElement and go from there: ``` string text=@"This is my<myTag myTagAttrib='colorize'>awesome</myTag> text."; Match match=Regex.Match(text,@"(<MyTag.*</MyTag>)"); string xml=match.Captures[0].Value; XElement element=XElement.Parse(xml); XAttribute attribute=element.Attribute("myTagAttrib"); if(attribute.Value=="colorize") DoSomethingWith(element.Value);// Value=awesome ``` This code will throw an exception if no MyTag element was found, but that can be remedied by inserting a line of: ``` if(match.Captures.Count!=0) {...} ``` It gets even more interesting if the string could hold more than just the MyTag Tag...
How do I work with an XML tag within a string?
[ "", "c#", "xml", "linq", "xelement", "" ]
Let's say that I have a bunch of class instances that serve different purposes, so I want to be able to reference them directly by name: ``` SomeObject aardvark = new SomeObject(); SomeObject llama = new SomeObject(); SomeObject tiger = new SomeObject(); SomeObject chicken = new SomeObject(); ``` But then I also want an array of them for easy iteration: ``` SomeObject[] animals = {aardvark, llama, tiger, chicken}; ``` My question is this. What happens when I do this: ``` llama = new SomeObject(); ``` I'll be creating a totally new llama object. How does this affect my animals array? Will it be referencing the NEW llama object, or somehow still referencing a copy of the old one? I know Java is "pass by value", but I still get confused by stuff like this. When I use the NEW keyword, does the "value" of that object reference change? Thanks!
Your animals array will be unaffected. Maybe this'll make it easier to visualize. Your initial setup looks like this: ``` chicken ---------------------------> SomeObject tiger ---------------------> SomeObject ^ llama -------------> SomeObject ^ | aardvark --> SomeObject ^ | | ^ | | | | | | | animals -----> {[0], [1], [2], [3]} ``` When you do this: ``` llama = new SomeObject(); ``` you're creating a new "SomeObject", and then changing llama to point at it. ``` chicken ---------------------------> SomeObject tiger ---------------------> SomeObject ^ SomeObject ^ | aardvark --> SomeObject ^ | | ^ | | | | | | | animals -----> {[0], [1], [2], [3]} llama -------> SomeObject ``` The important thing to remember is that (non-primitive) variables and array elements are just references to objects, and whenever you see "x = y;" (even if x is an array subscript) it means "make x refer to what y *currently* refers to".
Your `animals` array will keep the reference you put there (the "old" version) when you assign a different reference (e.g. the "new" version) to name `llama`. In other words, the array contains references to values (objects) and not to the specific expressions you used to build the array (whether those expressions are simple names of variables or more complicated forms).
Does the "new" keyword change the value of an object reference?
[ "", "java", "" ]
in SQLite with C# I want to do ``` SELECT * FROM media WHERE mediaId= for each SELECT mediaId FROM fav WHERE userId=1 ORDER BY indx DESC LIMIT 0, 100 ``` The syntax is obviously incorrect. I have no idea how to use the param from one select statement in another.
Most direct translation of your invalid syntax: ``` SELECT * FROM media WHERE mediaId IN (SELECT mediaId FROM fav WHERE userId=1) ORDER BY indx DESC LIMIT 0, 100 ``` A better style (maybe more speedy, but I haven't measured: ``` SELECT media.* FROM media JOIN fav USING (mediaId) WHERE fav.userId=1 ORDER BY media.indx DESC LIMIT 0, 100 ``` Both of these are standard SQL, btw, and the second form in particular will tend to work well on just about any relational DB implementation.
You need there join statements: ``` SELECT * FROM fav WHERE fav.userId=1 LEFT JOIN media ON media.mediaId=fav.mediaID ORDER BY indx DESC LIMIT 0, 100 ```
sqlite How do i select using results from another select?
[ "", "c#", "sqlite", "" ]
``` int valueToWrite = 0xFFFFFFFF; static char buffer2[256]; int* writePosition = (int* ) &buffer2[5]; *writePosition = valueToWrite; //OR * ((int*) &buffer2[10] ) = valueToWrite; ``` Now, I ask you guys which one do you find more readable. The 2 step technique involving a temporary variable or the one step technique? Do not worry about optimization, they both optimize to the same thing, as you can see here. Just tell me which one is more readable for you. ``` or DWORD PTR ?buffer2@?1??main@@9@4PADA+5, -1 or DWORD PTR ?buffer2@?1??main@@9@4PADA+10, -1 ```
``` int* writePosition = (int* ) &buffer2[5] ``` Or ``` *((int*) &buffer2[10] ) = valueToWrite; ``` Are both incorrect because on some platforms access to unaligned values (+5 +10) may cost hundreds of CPU cycles and on some (like older ARM) it would cause an illegal operation. The correct way is: ``` memcpy( buffer+5, &valueToWrite, sizeof(valueToWrite)); ``` And it is more readable.
Once you encapsulate it inside a class, it does not really matter which technique you use. The method name will provide the description as to what the code is doing. Thus, in most cases you will not have to delve into the actual impl. to see what is going on. ``` class Buffer { char buffer2[256]; public: void write(int pos, int value) { int* writePosition = (int*) &buffer2[pos]; *writePosition = value; } } ```
Which is more readable (C++ = )
[ "", "c++", "c", "" ]
A good rule of thumb by is that I intelligently refactor any method over 50 lines. The count does not include comments and white space but actual code. The reason I also say intelligently is there are plenty of times where a class over 50 lines is acceptable and cannot or should not be changed. I do not have a rule of thumb for classes. Generally I don't check classes to see if they should be refactored. On my currently project I have just about complete a class that is almost 4000 lines long. However no methods over 50, and most of the lines and methods are private and not acting on any data outside of the class. What is the rule of thumb for refactoring classes?
When the class violates the [SRP](http://en.wikipedia.org/wiki/Single_responsibility_principle), it's time to refactor. > The single responsibility principle is a computer programming > principle that states that every module or class should have > responsibility over a single part of the functionality provided by the > software, and that responsibility should be entirely encapsulated by > the class. All its services should be narrowly aligned with that > responsibility
If your classes have broken one of following "rules", you should consider to refactor. You are looking for **SOLID**, more detailed screencasts can be found [here](http://www.dimecasts.net/Casts/ByTag/SOLID%20Principle). * **S**RP: single responsibility principle, there should never be more than one reason for a class to change. * **O**CP: open closed principle, software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. * **L**SP: liskov substitution principle, functions that use references to base classes must be able to use objects of derived classes without knowing it. * **I**SP: interface segregation principle, clients should not be forced to depend upon interfaces that they do not use. * **D**IP: dependency inversion principle: + high level modules should not depend upon low level modules. Both Should depend upon abstractions. + abstractions should not depend upon details. Details should depend upon abstractions.
In C# how many lines before a class should be consider to be refactored?
[ "", "c#", "refactoring", "class", "" ]
I have [this](http://wiki.nazgulled.net/en/easy-settings) open-source library that I'm having some trouble fixing a problem... This library allows to easily create an XML file to store application settings. But I'm having an issue saving the changes. I have another application where I'm using this library and every time that application window is done resizing, I call the Save() method of the library to save the window size/position to the XML file. Most of times it works fine, everything is saved. Once in a while though, I get an exception saying the file is being used by another process. I really need to make sure that changes are saved every time the Save() method is called, I need to handle this exception somehow or prevent it from happening. What are you guys suggestions for best handling this situation? The code for the Save() method is the following: ``` public void Save() { // Create a new XML file if there's no root element if(xDocument.DocumentElement == null) { xDocument = new XmlDocument(); xDocument.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + "<" + XmlRootElement + ">\n</" + XmlRootElement + ">"); } // OMITTED CODE WAS HERE (NOT IMPORTANT FOR THE PROBLEM) // Create a new XML writer for the XML file XmlWriter xWriter = XmlWriter.Create(XmlFilePath, new XmlWriterSettings() { Indent = true, IndentChars = "\t" }); // Sort the XML file using the XSL sylesheet and save it xslTransform.Transform(xDocument, xWriter); // Clear the buffer and close the XML writer stream xWriter.Flush(); xWriter.Close(); } ```
It could be the case that the window-resizing-completed events are firing so quickly, that the save function is being called, the called again before it finishes running the first time. This would result in the error you're describing (the other process using the file is... YOU!). [Try surrounding your code with a lock, thusly](http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.80).aspx): ``` lock(some_shared_object) { //Your code here } ```
XmlWriter is IDisposable. You should wrap it in a using() clause. <http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.aspx>
Saving XML stream in C# says that it's being used by another process
[ "", "c#", "xml", "file", "process", "save", "" ]
I've looked everywhere for this function and cannot find the header files to make this work. It says clrscr() undeclared which brings me to the question. Is clrscr(); a function in C++?
It used to be a function in <conio.h>, in old Borland C compilers. It's not a C++ standard function.
And before someone posts the usual "please email me the conio.h file" request, can I point out that this ancient Borland header file only contained the declaration of the function. You would also need the supporting Borland library, which will not be compatible with any modern C++ compilation system.
Is clrscr(); a function in C++?
[ "", "c++", "" ]
I have the C# method ``` private static string TypeNameLower(object o) { return o.GetType().Name.ToLower(); } ``` to give me the lower case type name of the input object. But if input is a string set to null or a nullable int set to null then this method of course fails. How do I get the type name in this situation?
Jeff is correct. That's like asking what kind of cake would have been in an empty box with no label. As an alternative to Fortran's answer you could also do: ``` string TypeNameLower<T>(T obj) { return typeof(T).Name.ToLower(CultureInfo.InvariantCulture); } string TypeNameLower(object obj) { if (obj != null) { return obj.GetType().Name.ToLower(CultureInfo.InvariantCulture); } else { return null; } } string s = null; TypeNameLower(s); // goes to the generic version ``` That way, C# will pick the generic one at compile time if it knows enough about the type you're passing in.
I thought I'd post my answer, even though this question is old, because in my opinion, the accepted answer is wrong. That answer was pretty creative, so I don't mean to knock it. And for all I know, it *could* be what the OP really wanted. But, as you'll see from my examples below, I think that in almost **all** cases, the idea of using the generic function described in the accepted answer is either (A) unnecessary or (B) flat-out wrong. I've copied the generic function I'm talking about from the accepted answer and pasted it below for reference: ``` string TypeNameLower<T>(T obj) { return typeof(T).Name.ToLower(); } ``` Now, let's see some ways this function might be used: **Examples where the Generic Function is Unnecessary:** ``` var s = "hello"; var t = TypeNameLower(s); //or foreach(char c in "banana") WriteLine(TypeNameLower(c)); //or foreach(MyCustomStruct x in listOfMyCustomStruct) WriteLine(TypeNameLower(x)); ``` In these examples the function works--that is, it does return the *correct* values which are "string", "char", and "mycustomstruct", respectively. However in all cases like these, (i.e. where the generic function actually does return the correct type), the compiler knows ahead of time what the defined type of the variable is, and so does the programmer, of course (unless they got confused about their variable names). So the function is completely unnecessary, and the programmer may as well have done this: ``` var s = "hello"; var t = "string"; //or foreach(char c in "banana") WriteLine("char"); //or foreach(MyCustomStruct x in listOfMyCustomStruct) WriteLine("mycustomstruct"); ``` That might seem naive at first, but think about it for a while...it might take a while for it to really sink in...Try to come up with ANY scenario where using the generic function provides accurate information at **Runtime** that isn't already known (and hence could be auto-generated by the compiler or code-generation utilities such as T4 templates) at **compile-time**. Now the point of the previous set of examples was just to demonstrate a minor annoyance with the generic function--that it is unnecessary in every case where it returns the *correct* result. But more importantly, take a look at the examples below. They demonstrates that in any other case, the result of the generic function is actually ***wrong*** if you expect the function to return the name of the *true* runtime type of the object. The function is actually **only** guaranteed to return the name of a type that the true value is assignable to, which might be an ancestor class, an interface, or "object" itself. **Examples where the Generic Function is Wrong** ``` Stream ms = new MemoryStream(); IEnumerable str = "Hello"; IComparable i = 23; object j = 1; TypeNameLower(ms); //returns "stream" instead of "memorystream" TypeNameLower(str); //returns "ienumerable" instead of "string" TypeNameLower(i); //returns "icomparable" instead of "int32" TypeNameLower(j); //returns "object" instead of "int32" TypeNameLower<object>(true); //returns "object" instead of "bool" ``` In all cases, the results are quite wrong as you can see. Now, I admit that the last two lines were a bit contrived to demonstrate the point (not to mention that `TypeNameLower(j)` would actually be compiled to use the non-generic version of the function that is also part of the accepted answer--but you get the idea...) The problem is that the function actually ignores the type of the object being passed in, and only uses the (compile-time) information of the generic parameter type to return the value. A better implementation would be as follows: ``` string TypeNameLower<T>(T obj) { Type t; if (obj == null) t = typeof(T); else t = obj.GetType(); return t.Name.ToLower(); } ``` Now the function returns the name of the true runtime type whenever the object is non-null, and it defaults to the compile-time/defined type when the type is `null`. Importantly, this function could be used WITHOUT a non-generic version!! The result would be that the function would **never** return `null`. The most general return value would be "object" e.g: ``` object x = null; string s = null; byte[] b = null; MyClass m = null; TypeNameLower(x); // returns "object" TypeNameLower(s); // returns "string" TypeNameLower(b); // returns "byte[]" TypeNameLower(m); // returns "myclass" ``` Note that this is actually **more consistent** with the defined objective of the function, as requested by the OP. That is, if the OP *really* does want to find out what the type-name of the object was *if it weren't null*, then returning null would NEVER be an appropriate answer, because null ISN'T the name of any Type, and typeof(null) isn't defined. Every variable in C# descends from `System.Object`, so by definition, if the value weren't `null` then it *would* be an `Object` and that is in many cases the most that can be determined about a null reference at runtime.
How to get the lowercase name of an object, even when null, in C#
[ "", "c#", "" ]
This question has been asked similarly [before](https://stackoverflow.com/questions/66420/how-do-you-launch-the-javascript-debugger-in-google-chrome), but I can't seem to debug Javascript in Google Chrome. If I go to Page > Developer the "Debug Javascript" (`Ctrl`+`Shift`+`L`) is disabled. `Alt` + `` ` `` doesn't work. I'm developing a 'content script' extension so I'm launching chrome with `--enable-extensions`. What I'd ideally like to do is set breakpoints and step/run through my script as it executes. I'm a little over my head when it comes to JavaScript, so any guidance is appreciated. I can get to the 'JavaScript Console,' but can't find the content scripts inside of that. I'm also not sure how that differs from the 'JavaScript Debugger.' I'm using the latest Dev build of Chrome (2.0.181.1) on Windows XP.
These answers all seem to be out of date, and since this is ranking highly in google, here's the up-to-date answer: In Chrome press `CTRL+SHIFT+i` to bring up the developer tools. Select 'Sources' Click the small arrow that allows you to select from the scripts ![enter image description here](https://i.stack.imgur.com/jyX6Z.png) Then select 'Content scripts' ![enter image description here](https://i.stack.imgur.com/4s8B1.png) You'll then need to know the id of your extension (available from the chrome manage extensions page) to get to your scripts and debug them as normal.
Put the following command in your script: ``` debugger; ``` That will launch the Javascript debugger when it gets to that point
Google Chrome Javascript Debugger and Content Scripts
[ "", "javascript", "google-chrome", "script-debugging", "" ]
I want my notices to stop displaying in PHP. Theres no errors in the code, it just says things like undefined index. Which nothing can be done about. So how do I stop it from displaying? ``` Notice: Undefined variable: username in C:\wamp\www\watchedit\includes\config.php on line 37 Notice: Undefined variable: key in C:\wamp\www\watchedit\includes\config.php on line 42 ```
This will turn off notices for the environment programmatically-- from PHP.net. ``` // Report all errors except E_NOTICE error_reporting(E_ALL ^ E_NOTICE); ``` In some places, you can prefix the statement with "@" and it will silence just that location if it causes a notice.
You should check with [`isset`](http://docs.php.net/isset) if the variable exists before trying to read its value.
Stop Notices From Displaying In PHP
[ "", "php", "" ]
I write JavaScript code and I try to use its functional language nature. In other functional languages (or even in Ruby), if I don't explicitly set the return value of a function, it will return the value of the last evaluated expression. JavaScript does not follow this pattern. (To be precise, JavaScript always returns a value as well. If nothing was set, then `undefined`.) My question is the following: I have a function that doesn't need to (and does not) return a value. Does it make sense in a functional programming context to have a function with no explicit return value? Or did a fail somewhere if I found myself in this case? For example, I have the following function. It checks periodically if location hash was changed, and if so, calls the given function. ``` LIB_hashManager = function(f, context) { var prev = ''; var pollHash = function() { if (prev !== window.location.hash) { prev = window.location.hash; f.apply(context); } }; window.setInterval(pollHash, 100); }; ``` Should I return here anything? **Update** Meanwhile it came to my mind, that if anytime in the future I'll need to extend the knowledge of `LIB_hashManager`, following the functional constructor pattern, I can simply add methods to an object and `LIB_hashManager` will return that produced object. ``` LIB_hashManager = function(f, context) { // inside logic // ... }; ``` And later I may write: ``` LIB_hashManager = function(f, context) { // inside logic // ... // return public methods return { // ... } }; ``` So doesn't make sense then to return an empty object in the first case?
A "pure" functional programming environment would have no side effects -- each function's work would be *entirely* in computing its return value; that's not really feasible in typical uses of Javascript, and so it's perfectly acceptable, when a function has done its work through side effects, to have it return nothing at all, i.e., be a "procedure" rather than a function.
> My question is the following: I have a function that doesn't need to (and does not) return a value. Does it make sense in a functional programming context to have a function with no explicit return value? Or did a fail somewhere if I found myself in this case? According to the academic description of a function: a function must give the same output given an input. A function that does not have any output is absolutely useless, because functions are not supposed to have any side effects. However, since functional programming languages often need at least 1 side effect, the convention to return nothing is to return a unit or "()". Since this concept does not exist in Javascript, it shouldn't matter to you, since Javascript isn't strongly typed anyway.
Should I always give a return value to my function?
[ "", "javascript", "functional-programming", "return-value", "methodology", "" ]
I'm coding a basic OpenGL game and I've got some code that handles the mouse in terms of moving the camera. I'm using the following method: ``` int windowWidth = 640; int windowHeight = 480; int oldMouseX = -1; int oldMouseY = -1; void mousePassiveHandler(int x, int y) { int snapThreshold = 50; if (oldMouseX != -1 && oldMouseY != -1) { cam.yaw((x - oldMouseX)/10.0); cam.pitch((y - oldMouseY)/10.0); oldMouseX = x; oldMouseY = y; if ((fabs(x - (windowWidth / 2)) > snapThreshold) || (fabs(y - (windowHeight / 2)) > snapThreshold)) { oldMouseX = windowWidth / 2; oldMouseY = windowHeight / 2; glutWarpPointer(windowWidth / 2, windowHeight / 2); } } else { oldMouseX = windowWidth / 2; oldMouseY = windowHeight / 2; glutWarpPointer(windowWidth / 2, windowHeight / 2); } glutPostRedisplay(); } ``` However, after looking around in circles you'll find the camera starts to "roll" (rotate). Since I'm only calling Pitch and Yaw, I don't see how this is possible. Here is the code I'm using for my Camera class: <http://pastebin.com/m20d2b01e> As far as I know, my camera "rolling" shouldn't happen. It should simply pitch up and down or yaw left and right. NOT roll. What could be causing this?
Congratulations -- you have discovered Lie group theory! Yes, it's possible. The outcome of a series of transformations depends on the order in which they're executed. Doing a pitch followed by a yaw is not the same as a doing a yaw, followed by a pitch. In fact, in the limit of infinitesimally small yaws and pitches, the difference amounts to a pure roll; the general case is a little more complicated. (Physicists call this the "commutation relationships of the rotational group".) If you're familiar with rotation matrices, you can work it out quite easily.
You will probably need to use [quaternions](http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation) for composing rotations, if you are not doing so already. This avoids the problem of [gimbal lock](http://en.wikipedia.org/wiki/Gimbal_lock) which you can get when orienting a camera by rotation around the 3 axes. [Here is how to convert between them.](http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles)
How could simply calling Pitch() and Yaw() cause the camera to eventually Roll()?
[ "", "c++", "opengl", "camera", "glut", "" ]
I've seen some methods like this: ``` void SomeClass::someMethod() const; ``` What does this const declaration do, and how can it help optimize a program? **Edit** I see that the first part of this question has been asked before... **BUT**, it still doesn't answer the second part: how would this optimize the program?
If the compiler knows that the fields of a class instance are not modified across a const member function call, it doesn't have to reload any fields that it may have kept in registers before the const function call. This is sort of referred to the in C++ FAQ in the [discussion on const\_cast](http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.14).
It tells the compiler that the method has no effect on the classes state; you can't assign to anything in it. Have a look at the [C++ FAQ Lite 18.10](http://www.parashift.com/c++-faq-lite/const-correctness.html).
How does const after a function optimize the program?
[ "", "c++", "optimization", "constants", "keyword", "" ]
When i try to ``` $ make depend -f gcc.mak ``` a middleware on my Ubuntu machine I get this ``` /usr/include/../include/limits.h:125:26: error: no include path in which to search for limits.h ``` This is the contents around limits.h:125: ``` /* Get the compiler's limits.h, which defines almost all the ISO constants. We put this #include_next outside the double inclusion check because it should be possible to include this file more than once and still get the definitions from gcc's header. */ #if defined __GNUC__ && !defined _GCC_LIMITS_H_ /* `_GCC_LIMITS_H_' is what GCC's file defines. */ # include_next <limits.h> #endif ``` I tried setting ``` $ export INCLUDE=/usr/lib/gcc/x86_64-linux-gnu/4.3/include-fixed/ $ export C_INCLUDE_PATH=/usr/lib/gcc/x86_64-linux-gnu/4.3/include-fixed/ $ export CPLUS_INCLUDE_PATH=/usr/lib/gcc/x86_64-linux-gnu/4.3/include-fixed/ ``` (which is where I found another limits.h on my system). I already have libc6-dev installed, could it be that its limits.h has been overwritten by another package? Do I need another -dev package? Or is an environment variable required; perhaps this could be circumvented in some other way?
the package that you need is glibc.
I have encountered this problem doing a cross-compile. When you execute a 'make depend' the Makefile will invoke the makedepend program as seen from this assignment: ``` MAKEDEPPROG=makedepend ``` makedepend only searches some default include directories starting with `/usr/include` Since the `#include_next` directive means to include the next found instance of the named include file in the search path, this will fail if another one is not found. For me, the solution was to direct makedepend to search my cross-compiler include directories first. I did this by changing the `MAKEDEPPROG` assignment to include the `-I` directive: ``` MAKEDEPPROG=makedepend -I < path/to/cross-compiler/include-fixed > ``` I suggest reading about the makedepend program (about which I knew nothing before). For example, it was not obvious to me that makedepend would not use an environment search path. The `-I` directive puts the specified search path before makedepend's default paths.
GCC build problem (#include_next limits.h)
[ "", "c++", "linux", "gcc", "g++", "gnu-make", "" ]
I'm trying to run jstack command on my java application. Application is rather big, running inside jboss AS occupying about 4gb of memory. OS is Windows Server 2003 Standard edition. Every time i get an error "Not enough storage is available to process this command". There is enough ram, 16gb, and disk space. So, any ideas?
I ran into this recently on Win2008r2 and thought I'd share my solution since it took a while to figure out. [Rob's comment about psexec -s](https://stackoverflow.com/questions/906620/jstack-and-not-enough-storage-is-available-to-process-this-command/1677263#1677263) is what did it for me. It appears that on Vista and later jstack doesn't work against services because of the user context. It has nothing to do with memory. I suspect this is the same reason people have seen this problem on 2003 via remote desktop, unless you use the /admin or /console switch on mstsc. As of Vista the tightened security is probably what broke it. Starting my app from a cmd window worked fine, but that doesn't help me debug our standard install. Enabling the java debug port (for VisualVM, Eclipse or most any Java debugger) requires an app restart, so you lose the state you're probably trying to capture if you don't already have debugging enabled. Starting the service under my user credentials did not work - I was a little surprised at that. But psexec -s runs jstack from the system context, which worked like a charm. Oh, and you'll need to run psexec from an elevated cmd prompt, if UAC is on.
In the past I have seen this when the JVM is running as a Windows Service on Windows 2003. First, check to see if this is an [issue with the TMP directory](http://blogs.oracle.com/lmalventosa/entry/jconsole_local_process_list_on "issue with the TMP directory"). Second, jstack (or the other utilities like jconsole) will not connect to the local process unless it is running in the same session. If the service is running as a specific user, you may be able to connect by logging into the same session. If you are using Remote Desktop, you can connect using "mstsc /admin" (used to be /console) and try to run jstack again. Definitely check to make sure the TMP directory is set properly if this doesn't fix the problem. If the service is running as LocalSystem, the above procedure probably will not help much. I don't know if there is a way to log into the same session as LocalSystem. Some other alternatives may be to set the process up for remote monitoring and use jvisualvm (from the server itself or another machine) to connect over a port and do a thread dump.
Jstack and Not enough storage is available to process this command
[ "", "java", "jstack", "" ]
i am using c# to create a button for IE and this button performs certain actions that all depend on the document being a PDF document. I am trying to setup a guard to prevent any action taking place if the document type is not a PDF but not sure how as IE hands over the document to adobe and reader takes charge. I am using both SHDocWv have looked at the WebBrowserClass objects and not sure how to figure this out. any suggestions?
It's a little bit problematic to do this AFAIK. Value of *IWebBrowser2::Type* property depends on what plug-in you have installed that handles PDFs, because some plug-ins creates HTML wrapper for PDF file (like Adobe) so you get "HTML Document" as type and some plug-ins don't do this (like Foxit), so you can't relay on this exclusively. So if you got PDF with HTML wrapper you can use *IHTMLDocument2::mimeType* to find out exact type of the document (JPEG/GIF/PNG/etc. files are all wrapped in HTML by the browser). But as I know it is unreliable too, for instance on my machine it returns "Firefox Document" for HTML documents because .html files are associated with Firefox :s But I didn't test to see if this is the case with PDFs alos. Another options is to use *GetUrlCacheEntryInfoEx* API call to obtain file in local browser cache which stores document, then read it (only the beginning of the file, I think only the first 256 bytes are important) and call *FindMimeFromData* with data you just read and it will return mime type.
Check mime type of the document or see the window.location.href of webbrowser... If pdf is being displayed, you would be able to find it...
How to find out what "kind" of document is being displayed in IE
[ "", "c#", "internet-explorer", "bho", "" ]
I use MS SQL 2008 and I want to create a trigger in a database that is created dynamic. Creating the database is called within a stored procedure of an other database and runs perfectly, but when I want to add a trigger or a stored procedure, the executing fails. If I try to run the dynamiy SQL with an ``` EXEC('USE dbase GO CREATE TRIGGER [blah] GO') ``` I get: > Wrong syntax near 'GO' And if I remove the 'USE ...' the trigger will be created in the wrong database. Is there a trick to avoid my problems? Thx
"GO" is not T-SQL language. It's a keyword interpreted by client tools like SSMS as a batch separator (that means "send text to server"). Now, CREATE TRIGGER must be the first statement in the batch so the "USE dbname" can not used. If you mention "USE dbnname" before the EXEC, then it may up in the default database for the connection. You'd have to test (I can't right now, sorry) ``` --Might work USE dbase EXEC ('CREATE TRIGGER [blah] ') ``` Or you'll have to use sqlcmd or osql to connect and run the code: this allows you to set the db context on connection. Not within T-SQL though. Or you can try ALTER LOGIN xxx WITh DEFAULT\_DATABASE = dbname before EXEC ``` ALTER LOGIN xxx WITH DEFAULT_DATABASE = dbname --Now the EXEC will connect to default db if above approach fails EXEC('CREATE TRIGGER [blah] ') ```
You can switch the database before calling exec, and switch back right after: ``` use newdb exec ('CREATE TRIGGER [blah] ...') use originaldb ``` Or create a linked server to the right database, with RPC enalbed, and: ``` EXEC ('CREATE TRIGGER [blah] ...') AT LinkedServerName ``` Or create a different user that has the Default Catalog in the database where you'd like to create the trigger and: ``` EXECUTE AS LOGIN = 'UserName' EXEC ('CREATE TRIGGER [blah] ...') REVERT ```
Creating a trigger dynamic
[ "", "sql", "sql-server", "stored-procedures", "triggers", "dynamic-sql", "" ]
In javascript, can I declare properties of an object to be constant? Here is an example object: ``` var XU = { Cc: Components.classes }; ``` or ``` function aXU() { this.Cc = Components.classes; } var XU = new aXU(); ``` just putting "const" in front of it, doesn't work. I know, that i could declare a function with the same name (which would be also kind of constant), but I am looking for a simpler and more readable way. Browser-compatibility is not important. It just has to work on the Mozilla platform, as it is for a Xulrunner project. Thank you a lot! Cheers.
Since you only need it to work on the Mozilla platform, you can define a getter with no corresponding setter. The best way to do it is different for each of your examples. ### In an object literal, there is a special syntax for it: ``` var XU = { get Cc() { return Components.classes; } }; ``` In your second exampe, you can use the `__defineGetter__` method to add it to either `aXU.prototype` or to `this` inside the constructor. Which way is better depends on whether the value is different for each instance of the object. **Edit:** To help with the readability problem, you could write a function like `defineConstant` to hide the uglyness. ``` function defineConstant(obj, name, value) { obj.__defineGetter__(name, function() { return value; }); } ``` Also, if you want to throw an error if you try to assign to it, you can define a setter that just throws an Error object: ``` function defineConstant(obj, name, value) { obj.__defineGetter__(name, function() { return value; }); obj.__defineSetter__(name, function() { throw new Error(name + " is a constant"); }); } ``` ### If all the instances have the same value: ``` function aXU() { } defineConstant(aXU.prototype, "Cc", Components.classes); ``` ### or, if the value depends on the object: ``` function aXU() { // Cc_value could be different for each instance var Cc_value = return Components.classes; defineConstant(this, "Cc", Cc_value); } ``` For more details, you can read the [Mozilla Developer Center documentation](https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Getters_and_Setters).
**UPDATE**: This works! ``` const FIXED_VALUE = 37; FIXED_VALUE = 43; alert(FIXED_VALUE);//alerts "37" ``` Technically I think the answer is no (Until [const](https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Statements:const) makes it into the wild). You can provide wrappers and such, but when it all boils down to it, you can redefine/reset the variable value at any time. The closest I think you'll get is defining a "constant" on a "class". ``` // Create the class function TheClass(){ } // Create the class constant TheClass.THE_CONSTANT = 42; // Create a function for TheClass to alert the constant TheClass.prototype.alertConstant = function(){ // You can’t access it using this.THE_CONSTANT; alert(TheClass.THE_CONSTANT); } // Alert the class constant from outside alert(TheClass.THE_CONSTANT); // Alert the class constant from inside var theObject = new TheClass(); theObject.alertConstant(); ``` However, the "class" **TheClass** itself can be redefined later on
Javascript: constant properties
[ "", "javascript", "object", "constants", "" ]
I've recently discovered the very useful '-i' flag to Python ``` -i : inspect interactively after running script, (also PYTHONINSPECT=x) and force prompts, even if stdin does not appear to be a terminal ``` this is great for inspecting objects in the global scope, but what happens if the exception was raised in a function call, and I'd like to inspect the local variables of the function? Naturally, I'm interested in the scope of where the exception was first raised, is there any way to get to it?
At the interactive prompt, immediately type ``` >>> import pdb >>> pdb.pm() ``` pdb.pm() is the "post-mortem" debugger. It will put you at the scope where the exception was raised, and then you can use the usual pdb commands. I use this *all the time*. It's part of the standard library (no ipython necessary) and doesn't require editing debugging commands into your source code. The only trick is to remember to do it right away; if you type any other commands first, you'll lose the scope where the exception occurred.
In ipython, you can inspect variables at the location where your code crashed without having to modify it: ``` >>> %pdb on >>> %run my_script.py ```
How do I inspect the scope of a function where Python raises an exception?
[ "", "python", "debugging", "" ]
I'm trying to extract data from the following page: <http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&param2=&param3=&param4=&param5=2009-04-22&param6=37#> Which, conveniently and inefficiently enough, includes all the data embedded as a csv file in the header, set as a variable called gs\_csv. How do I extract this? `Document.body.innerhtml` skips the header where the data is, what is the alternative that includes the header (or better yet, the value associated with `gs_csv`)? (Sorry, new to all this, I've been searching through loads of documentation, and trying a lot of them, but nothing so far has worked). --- Thanks to Sinan (this is mostly his solution transcribed into Python). ``` import win32com.client import time import os import os.path ie = Dispatch("InternetExplorer.Application") ie.Visible=False ie.Navigate("http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&param2=&param3=&param4=&param5=2009-04-22&param6=37#") time.sleep(20) webpage=ie.document.body.innerHTML s1=ie.document.scripts(1).text s1=s1[s1.find("gs_csv")+8:-11] scriptfilepath="c:\FO Share\bmreports\script.txt" scriptfile = open(scriptfilepath, 'wb') scriptfile.write(s1.replace('\n','\n')) scriptfile.close() ie.quit ```
**Untested:** Did you try looking at what [Document.scripts](http://msdn.microsoft.com/en-us/library/aa752604(VS.85).aspx) contains? **UPDATE:** For some reason, I am having immense difficulty getting this to work using the Windows Scripting Host (but then, I don't use it very often, apologies). Anyway, here is the Perl source that works: ``` use strict; use warnings; use Win32::OLE; $Win32::OLE::Warn = 3; my $ie = get_ie(); $ie->{Visible} = 1; $ie->Navigate( 'http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?' .'param1=&param2=&param3=&param4=&param5=2009-04-22&param6=37#' ); sleep 1 until is_ready( $ie ); my $scripts = $ie->Document->{scripts}; for my $script (in $scripts ) { print $script->text; } sub is_ready { $_[0]->{ReadyState} == 4 } sub get_ie { Win32::OLE->new('InternetExplorer.Application', sub { $_[0] and $_[0]->Quit }, ); } __END__ C:\Temp> ie > output ``` `output` now contains everything within the script tags.
fetch the source of that page using ajax, and parse the response text like XML using jquery. It should be simple enought to get the text of the first tag you encounter inside the I'm out of touch with jquery, or I would have posted code examples. EDIT: I assume you are talking about fetching the csv on the client side.
Alternative to innerhtml that includes header?
[ "", "python", "html", "css", "dom", "com", "" ]
Is there some built in Card graphics library built into .Net/Windows? Is there any way to utilize the card graphics used by the various card games that come with Windows? They look really nice and it would be cool if there was some built in functionality for this.
Actually there is, sort of. It's not builtin, but it is a free download from Microsoft. There are a pair of .Net project templates, one for C# and one for VB. Both include a set of card face and card back images. The C# one is here: <http://msdn.microsoft.com/en-us/vcsharp/aa336742.aspx> And the VB one is here: <http://visualstudiogallery.msdn.microsoft.com/en-us/a4747c87-2ad2-4004-99bb-2a2f5f043edd> (note: editied to fix C# link --RBarryYoung, May 31, 2009 3pm)
Bit late to post on this but.. there is this one I am using <http://deckofcards.codeplex.com/>
Is there a built in Playing Card library in .Net?
[ "", "c#", ".net", "" ]
all. I'm a very, very new programmer. My language of choice at the moment is Python, and I feel like I have a decent feel for it. I'm just now starting to learn about recursion. (By the way, if anyone could recommend a good guide on this, please let me know!) Just so you all know, this question is very elementary, and the code I'm posting is horribly, horribly wrong. Anyway, I'm trying to write a function that will get all the friends within a specified degree. If I pass it 0 as the degree, I just want myself. If I pass it 1, I want me and all my friends. 2, I want me, my friends, and all their friends, and so on. I've tried quite a few different ways of doing this, but none work. I try to visualize how it should work in theory, and I can't quite get that either because I'm so inexperienced in this area. Maybe a kind soul here can show me all the ways in which this code fails and then explain how to do it properly and/or recommend a good guide on the subject. Here goes: ``` def getFriends(self,degree,friendList): if degree == 0: friendList.append(self) return friendList else: friendList = friendList.append(self) for each in self.friends: each.getFriends(degree-1,friendList) ``` It doesn't work, and I know I've done stupid, stupid things. Someone please slap me and point me in the correct direction! Thanks.
``` friendList = friendList.append(self) ``` This sets `friendList` to `None`, unconditionally, as that's the invariable return value of any list's `append` method -- so, fix *that* weirdness first...!-) Once you've fixed that, you still need to fix the function so that it always ends with `return` of something -- "falling off the end" returns `None`. E.g.: ``` def getFriends(self,degree, friendList): if degree == 0: friendList.append(self) return friendList else: friendList.append(self) for each in self.friends: each.getFriends(degree-1, friendList) return friendList ``` which can and clearly should be refactored to eliminate the duplication (DRY, Don't Repeat Yourself, is THE heart of programming...): ``` def getFriends(self,degree, friendList): friendList.append(self) if degree > 0: for each in self.friends: each.getFriends(degree-1, friendList) return friendList ``` PS: that (the `alist=alist.append(...)` issue) **precisely** how I got back in touch with my wife Anna in 2002 (we'd been not-quite-sweetheart friends many years before but had lost track of each other) -- she started studying Python, used exactly this erroneous construct, couldn't understand why it failed -- looked around the Python community, saw and recognized my name, mailed me asking about it... less than two years later we were married, and soon after she was the first woman member of the Python Software Foundation and my co-author in "Python Cookbook" 2nd ed. So, of course, I've got an incredible sweet spot for this specific Python error...;-).
You can move friendList.append(self) to the line before the if - you need it in both cases. You also don't need to assign the result to friendlist - it's a bug. In your algorithm, you will likely to add the same people twice - if A is a friend of B and B is a friend of A. So, you need to keep a set of friends that you've processed already. Before processing, check this set and don't do anything if the person has been processed already.
Getting friends within a specified degree of separation
[ "", "python", "recursion", "" ]
Does anyone have code to detect duplicate JARs in the classpath? Background: When there are two versions of the same JAR in the classpath, really strange things can happen. This can even happen when using tools like Maven: Change a dependency and build the WAR without cleaning first. Since `target/webapp/WEB-INF/lib` wasn't cleaned, the dependency will be in there twice. Is there a safety-net for this?
[JBoss Tattletale](http://www.jboss.org/tattletale) might help you with this. It's a free tool which scans the JAR files used by your project and gives you a report about them. Amongst its feature are: * Spot if a class is located in multiple JAR files * Spot if the same JAR file is located in multiple locations * Find similar JAR files that have different version numbers
There is a Maven plugin to do just that: [maven-duplicate-finder-plugin](https://github.com/ning/maven-duplicate-finder-plugin) **[EDIT]** If you want to do it in unit tests yourself, use ``` getClass().getClassLoader().getResources( "com/pany/package/Java.class" ) ``` If this returns more than one `URL`, you have duplicates on the classpath. The drawback is that this only works for cases where you had conflicts in the past. On the positive side, it's just a few lines of code (or one line when you write a helper method) and it works on your build server.
How to detect duplicate JARs in the classpath?
[ "", "java", "jar", "classpath", "" ]
I would like to write simple scripts in C#. Stuff I would normally use .bat or 4NT .btm files for. Copying files, parsing text, asking user input, and so on. Fairly simple but doing this stuff right in a batch file is really hard (no exceptions for example). I'm familiar with command line "scripting" wrappers like AxScript so that gets me part of the way there. What I'm missing is the easy file-manipulation framework. I want to be able to do cd(".."), copy(srcFile, destFile) type functionality. Tools I have tried: * NANT, which we use in our build process. Not a good scripting tool. Insanely verbose XML syntax and to add a simple function you must write an extension assembly. Can't do it inline. * PowerShell. Looks great, but I just haven't been able to switch over to this as my primary shell. Too many differences from 4NT. Whatever I do needs to run from an ordinary command prompt and not require a special shell to run it through. Can PowerShell be used as a script executor? * Perl/Python/Ruby. Really hate learning an entirely new language and framework just to do batch file operations. Haven't been able to dedicate the time I need to do this. Plus, we're a 99% .NET shop for our toolchain and I really want to leverage our existing experience and codebase. Are there frameworks out there that are trying to solve this problem of "make a batch file in C#" that you have used? I want the power of C#/.NET with the immediate-mode type functionality of a typical cmd.exe shell language. Am I alone in wanting something like this?
I would try to get over the PowerShell anxiety because it is the shell of the future. All of the software coming out of Microsoft is using it as their management interface and especially version 2.0 is ridiculously useful. I'm a C# developer most of the time but PowerShell has solved that whole "WindowsApplication42" problem of temp projects just piling up. PowerShell gives you full access to the .NET framework in a command line shell so even if you don't know how to do something in PowerShell, you most likely know how to do it in .NET.
IronPython and IronRuby **do** let you leverage all of your .NET "experience and codebase" (they don't answer your objection to learning new languages, however).
What's a good way to write batch scripts in C#?
[ "", "c#", "shell", "command-line", "powershell", "batch-file", "" ]
I have a bunch of flows and data processing applications that I occasionally need to spy on, meaning I need to know what files they read. This is mostly to aid in packaging testcases, but can also be useful when debugging. Is there a way to run the executables in such a way that produces such a list? I have two thoughts on this: 1. There is a command that I can invoke and that command invokes my apps. Something along the lines of GDB. I call GDB, give it a path to the executable and some arguments and GDB calls it for me. Perhaps there's something similar to telling me how system resources are used. 2. Maybe the more interesting (but unnecessary side path) solution. 1. create library called libc.so which implements fopen (and some others) 2. change LD\_LIBRARY\_PATH to point at the new library 3. make a copy of the real libc.so and rename fopen (nepof, perhaps) in an editor 4. my library loads the copy and calls the renamed function as necessary to provide fopen functionality. 5. call the app which then calls my proxy fopen. Alternative #1 would certainly be the preferable one but comments on how to do #2 more easily are welcome too.
One option is to use strace: ``` strace -o logfile -eopen yourapp ``` This will log all file-open events, but it will impose a performance penalty that may be significant. It has the advantage of being easy to use however. Another option is to use LD\_PRELOAD. This corresponds to your option #2. The basic idea is to do something like this: ``` #define _GNU_SOURCE #include <stdio.h> #include <dlfcn.h> int open(const char *fn, int flags) { static int (*real_open)(const char *fn, int flags); if (!real_open) { real_open = dlsym(RTLD_NEXT, "open"); } fprintf(stderr, "opened file '%s'\n", fn); return real_open(fn, flags); } ``` Then build with: ``` gcc -fPIC -shared -ldl -o preload-example.so preload-example.c ``` And run your program with eg: ``` $ LD_PRELOAD=$PWD/preload-example.so cat /dev/null opened file '/dev/null' ``` This has much less overhead. Note, however, that there are other entry points for opening files - eg, fopen(), openat(), or one of the many legacy compatibility entry points: ``` 00000000000747d0 g DF .text 000000000000071c GLIBC_2.2.5 _IO_file_fopen 0000000000068850 g DF .text 000000000000000a GLIBC_2.2.5 fopen 000000000006fe60 g DF .text 00000000000000e2 GLIBC_2.4 open_wmemstream 00000000001209c0 w DF .text 00000000000000ec GLIBC_2.2.5 posix_openpt 0000000000069e50 g DF .text 00000000000003fb GLIBC_2.2.5 _IO_proc_open 00000000000dcf70 g DF .text 0000000000000021 GLIBC_2.7 __open64_2 0000000000068a10 g DF .text 00000000000000f5 GLIBC_2.2.5 fopencookie 000000000006a250 g DF .text 000000000000009b GLIBC_2.2.5 popen 00000000000d7b10 w DF .text 0000000000000080 GLIBC_2.2.5 __open64 0000000000068850 g DF .text 000000000000000a GLIBC_2.2.5 _IO_fopen 00000000000d7e70 w DF .text 0000000000000020 GLIBC_2.7 __openat64_2 00000000000e1ef0 g DF .text 000000000000005b GLIBC_2.2.5 openlog 00000000000d7b10 w DF .text 0000000000000080 GLIBC_2.2.5 open64 0000000000370c10 g DO .bss 0000000000000008 GLIBC_PRIVATE _dl_open_hook 0000000000031680 g DF .text 0000000000000240 GLIBC_2.2.5 catopen 000000000006a250 g DF .text 000000000000009b GLIBC_2.2.5 _IO_popen 0000000000071af0 g DF .text 000000000000026a GLIBC_2.2.5 freopen64 00000000000723a0 g DF .text 0000000000000183 GLIBC_2.2.5 fmemopen 00000000000a44f0 w DF .text 0000000000000088 GLIBC_2.4 fdopendir 00000000000d7e70 g DF .text 0000000000000020 GLIBC_2.7 __openat_2 00000000000a3d00 w DF .text 0000000000000095 GLIBC_2.2.5 opendir 00000000000dcf40 g DF .text 0000000000000021 GLIBC_2.7 __open_2 00000000000d7b10 w DF .text 0000000000000080 GLIBC_2.2.5 __open 0000000000074370 g DF .text 00000000000000d7 GLIBC_2.2.5 _IO_file_open 0000000000070b40 g DF .text 00000000000000d2 GLIBC_2.2.5 open_memstream 0000000000070450 g DF .text 0000000000000272 GLIBC_2.2.5 freopen 00000000000318c0 g DF .text 00000000000008c4 GLIBC_PRIVATE __open_catalog 00000000000d7b10 w DF .text 0000000000000080 GLIBC_2.2.5 open 0000000000067e80 g DF .text 0000000000000332 GLIBC_2.2.5 fdopen 000000000001e9b0 g DF .text 00000000000003f5 GLIBC_2.2.5 iconv_open 00000000000daca0 g DF .text 000000000000067b GLIBC_2.2.5 fts_open 00000000000d7d60 w DF .text 0000000000000109 GLIBC_2.4 openat 0000000000068850 w DF .text 000000000000000a GLIBC_2.2.5 fopen64 00000000000d7d60 w DF .text 0000000000000109 GLIBC_2.4 openat64 00000000000d6490 g DF .text 00000000000000b6 GLIBC_2.2.5 posix_spawn_file_actions_addopen 0000000000121b80 g DF .text 000000000000008a GLIBC_PRIVATE __libc_dlopen_mode 0000000000067e80 g DF .text 0000000000000332 GLIBC_2.2.5 _IO_fdopen ``` You may need to hook all of these for completeness - at the very least, the ones not prefixed with \_ should be hooked. In particular, *be sure to hook fopen seperately*, as the libc-internal call from fopen() to open() is not hooked by a LD\_PRELOAD library. A similar caveat applies to strace - there is the 'openat' syscall as well, and depending on your architecture there may be other legacy syscalls as well. But not as many as with LD\_PRELOAD hooks, so if you don't mind the performance hit, it may be an easier option.
``` man strace ``` example (assume 2343 is the process id): ``` # logging part strace -p 2343 -ff -o strace_log.txt # displaying part grep ^open strace_log.txt ```
How can I detect file accesses in Linux?
[ "", "c++", "linux", "resources", "" ]
How can I find prime numbers through bit operations in C++?
Try implementing a [prime sieve](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) using a bitset. The algorithm only needs to store whether a certain number is a prime or not. One bit is sufficient for that.
I think the way to do this is to not think of the bitset as its numerical representation as we normally do, but to think of it at a list of numbers. So the bitset ``` 1111 ``` would represent the numbers 1, 2, 3, and 4. Now if we say that a '1' represents prime and a '0' represents not prime, we can make a sieve as follows. Set all the bits to 1 (I'm going to use 16 bits that represent the integers 1 through 16) ``` 1111 1111 1111 1111 ``` I know that one is not prime, so I'm setting it to zero. ``` 0111 1111 1111 1111 ``` Now, I know that the next '1' I encounter represents a prime, but all multiples of that number are by definition *not* prime, so I leave the next '1' alone, but set all of its multiples to '0'. Since the next '1' represents the number 2, I zero every second bit. ``` 0110 1010 1010 1010 ``` The benefit of this method over others is that as I traverse the rest of the bits, I don't need to check each one to see if it's divisible by 2 (so nothing like `if i % 2 == 0` is necessary). I can just keep incrementing the index by 2 and I know I'll always land on a non-prime. Now I just do the same thing again with the next '1' I encounter (the next prime starting from the last prime I identified, 2). I know it's prime, since it isn't divisible by any of the numbers below it. I know all of its multiples are prime, so since it's in the third position, I set every third following bit to '0'. Some of them are already '0' since they're also multiples of 2. That's okay, just leave them '0'. ``` 0110 1010 0010 1000 ``` The next '1' that you encounter is the fifth bit. Now you *could* keep going until you reach the end, but since 5 is greater than the square root of the number of bits that I started with, I know I'm not going to find any more composites, so I'm done. --- After a little more searching I found a really good implementation example in Deitel & Deitel's [C++ How to Program](http://books.google.com/books?id=HhGB8fOiUy8C&pg=RA2-PA132&lpg=RA2-PA132&dq=test+if+number+is+prime+using+bitset&source=bl&ots=wOeGo29Tfg&sig=QxFsYkfB9dLyOCVP6SaQ6ihZzl4&hl=en&ei=OO0XSrjcLaOxtgei3-X2DA&sa=X&oi=book_result&ct=result&resnum=4#PRA2-PA133,M1). They also provide good explanations of the algorithm and code.
How can I find prime numbers through bit operations in C++?
[ "", "c++", "math", "primes", "" ]
I'd like to set a variable in my Symfony action that holds the rendered template data for that action. I'm returning some JSON content with the action, and I'd like to store what the action would be outputting into the JSON and return it. ``` public function executeAjaxPriceAdditionCreate(sfWebRequest $request) { $this->form = new ProductPriceAdditionAjaxForm(); $json['success'] = $this->processAjaxPriceAdditionForm($request, $this->form); $this->setTemplate('ajaxPriceAdditionNew'); $json['content'] = ???; // THIS IS WHERE THE RENDERED TEMPLATE CONTENT SHOULD GO. $this->getResponse()->setHttpHeader('Content-Type','application/json; charset=utf-8'); return $this->renderText(json_encode($json)); } ```
What I ended up doing was using a flash instead of trying to send JSON. The template of the AJAX content tried to detect the flash at the top, and if so, it did the "success" methods (closing the modal pop-up box).
If you name your template as a partial, you can use ``` $json['content] = $this->getPartial('ajaxPriceAdditionNew'); ``` See [getPartial API](http://www.symfony-project.org/api/1_2/sfAction#method_getpartial)
In Symfony, how to retrieve the rendered template content as a variable in an action?
[ "", "php", "templates", "symfony1", "action", "" ]
What are the benefits to defining methods as `protected` in C#? like : ``` protected void KeyDemo_KeyPress( object sender, KeyPressEventArgs e ) { // some code } ``` As compared to something like this: ``` private void FormName_Click( object sender, EventArgs e ) { //some code } ``` I've seen such examples in many books and I don't understand why and when do they use `private` vs `protected`?
**Protected methods can be called from derived classes. Private methods can't.** That's the one and only difference between private and protected methods.
Often 'protected' is used when you want to have a child class override an otherwise 'private' method. ``` public class Base { public void Api() { InternalUtilityMethod(); } protected virtual void InternalUtilityMethod() { Console.WriteLine("do Base work"); } } public class Derived : Base { protected override void InternalUtilityMethod() { Console.WriteLine("do Derived work"); } } ``` So we have the override behavior we know and love from inheritance, without unnecessarily exposing the InternalUtilityMethod to anyone outside our classes. ``` var b = new Base(); b.Api(); // returns "do Base work" var d = new Derived(); d.Api(); // returns "do Derived work" ```
"protected" methods in C#?
[ "", "c#", ".net", "visual-studio", "oop", "access-modifiers", "" ]
I'd be interested to hear how people handle conditional markup, specifically in their masterpages between release and debug builds. The particular scenario this is applicable to is handling concatenated js and css files. I'm currently using the .Net port of YUI compress to produce a single site.css and site.js from a large collection of separate files. One thought that occurred to me was to place the js and css include section in a user control or collection of panels and conditionally display the `<link>` and `<script>` markup based on the Debug or Release state of the assembly. Something along the lines of: ``` #if DEBUG pnlDebugIncludes.visible = true #else pnlReleaseIncludes.visible = true #endif ``` The panel is really not very nice semantically - wrapping `<script>` tags in a `<div>` is a bit gross; there must be a better approach. I would also think that a block level element like a `<div>` within `<head>` would be invalid html. Another idea was this could possibly be handled using web.config section replacements, but I'm not sure how I would go about doing that.
There's a decent discussion on changes in web.config settings here: [Using different Web.config in development and production environment](https://stackoverflow.com/questions/305447/using-different-web-config-in-development-and-production-environment) Note: you are asking a different question but I suggest taking a look at that anyway because it's an awesome collection of suggestions of how to switch between live and debug settings and all the answers (IMO) have some value - not just the highest voted/accepted answer. **Personally**, I use a method explained here and think it is the most flexible and is applicable to all types of configuration changes as it is file based but allows them to be auto-swapped based on solution configurations: <http://www.hanselman.com/blog/ManagingMultipleConfigurationFileEnvironmentsWithPreBuildEvents.aspx> Essentially, you run a pre-build event to swap out the web config with another one on disc with the solution configuration name appended to the filename. For example, I have web.config.release, web.config.debug and even a web.config.neilathome. I then use the exact same methods for conditional bits of code by creating partial classes and putting the stuff that changes between my solution configurations in their own files. For example, I have sync\_timersettings.cs which is a partial class containing a few constants that define how often my update code calls a web-service. Or you could just put all your settings in an app.settings file and do it that way. I find it a very flexible solution, it lets me swap out chunks of javascript and css and as long as you take the time to put things that change between configurations in their own files, you can probably go to a state where you can be debugging in the debug solution configuration and then switch to release and deploy in one click. One further note: ``` #if DEBUG pnlDebugIncludes.visible = true #else pnlReleaseIncludes.visible = true #endif ``` **Responses to comments:** This is only useful if you have a debug solution configuration and one other one which is your live deployment. It won't work when you (like me) have a staging, release and neilonhislaptop solution configuration as the DEBUG symbol is only set when you have debugging enabled. The work-around is to go to the properties page of your web application and in the build tab, put a conditional symbol in for each of your build configurations. IE, set you build configuration to release and put 'release' in the conditional symbol box in that tab. Then do the same for different build configurations, the conditional symbol box in there will automatically change depending on your build configuration. #if conditional compile directives will work as expected then. Bayard asked for more information on how to use this to change mark-up between configurations. Well you *could* use to to swap out the entire .aspx page - have home.aspx.release and home.aspx.debug but it would mean you had to repeat a lot of mark-up in each file. My solution is to add a partial class to my application. For example, my 'ViewImage' page has the following class definition in it: ``` public partial class ViewImage : System.Web.UI.Page ``` ..so I created some class files with the same signature and named them 'ViewImage\_titleset.cs.debug' and 'ViewImage\_titleset.cs.staging': ``` namespace Website { public partial class ViewImage : System.Web.UI.Page { public void SetTitle() { Page.Title = "Running in debug mode"; } } } ``` and ``` namespace Website { public partial class ViewImage : System.Web.UI.Page { public void SetTitle() { Page.Title = "Running in staging mode"; } } } ``` ..calling SetTitle in the page load event for ViewImage would change the title depending on which build configuration was in place. This will only work if you are altering the page programmatically. It's better to use the conditional compilation method above for changing code like this and reserve the file-swap method for changing out non-code files such as images or web.configs. Just make sure you don't set the alternative files to be deployed on publish.
I just tried this in my Master page in my ASP.NET MVC project and it worked. If in DEBUG mode I use the development version of jQuery and if not in DEBUG mode, I use the minified version of jQuery: ``` <head runat="server"> <% #if DEBUG %> <script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery.js") %>"></script> <% #else %> <script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery.min.js") %>"></script> <% #endif %> </head> ```
JS/CSS include section replacement, Debug vs Release
[ "", "asp.net", "javascript", "msbuild", "compression", "" ]
I've done some XML serialization before but i used Attributes, I'm not sure this is doable for my next assignment, here's a brief list of XML manip requirementes. * General Purpose XMl manipulation, tied to a treeview, no schema. * Load/Save XML. * Load/Save Attributes as well as Values (i believe the term is Element Text?), and be mindful of the Node's name. * Comments can be safely ignored as can Document info markup (ie, the UTF-8 and schema tags) Any suggestions on how best to handle this?
I probably wouldn't bother with an object model and `IXmlSerializable` - it sounds like you might just as well talk in terms of an `XmlElement` / `XmlDocument` - i.e. pass the data around as a block of xml. Since you have no schema it would be pointless to shred it out; you might as well do it via an xml DOM. When you say treeview - is this winforms, asp.net, wpf? I believe the asp.net treeview can take an xml source, but for winforms you'd have to iterate the nodes yourself.
Don't know what exactly you mean with "before but i used Attributes" but I would recommend XmlSerializer too: * With "simple" classes it works usually out of the box. * Collections might need some more work, but it depends on your requirements and object structure. * There are other build in XML serializers like XAML or the WCF DataContractSerializer. All have pros and cons. But if you want to fine tune your XML format, XMLSerializer is the most flexibel one. * You can approach your format step by step: If the default looks good, your done. If not you have to add just some attributes in most cases. * If you want complete control, you can still implement IXmlSerialize to fine tune your format. * Everything applies on a per class basis: Use the default where appropriate, add some attributes where required and implement IXmlSerializable as required.
XML Serialization, in this case, IXmlSerializable or Attributes
[ "", "c#", ".net", "xml", "ixmlserializable", "" ]
I'm currently developing a monthly checklist system for our organization. A user may login, select a month, then submit a list of yes/no questions relevant to that month for our organization's purposes. Some of the questions are used in more than 1 month's checklist, so I'm creating an intersection table to facilitate this one-to-many relationship. The fields are ChecklistMonth and ChecklistQuestionID. I'm unsure of how to store the ChecklistMonth field, however. If I use a smalldatetime, it seems a bit overkill, as I am only interested in the month. It will also look a bit dated in future years. On the other hand, it seems a bit wasteful to create a table with the fields MonthID and Month in order to identify only the month. What is everyone's opinion on this? Thanks in advance.
If it is a month without regard to year, I would just use a TINYINT. I don't think that you need a separate lookup table since the numbers of the months are pretty distinct and universal (without getting into Chinese or Jewish calendars, etc...). If you use any sort of datetime then you always need to remember the exact rules around it. Are you storing it as the first day of the month? Middle day of the month? What year? Plus, it's extra, unnecessary room being used in the DB. EDIT: I thought that I had already added this to my response, but apparently not... remember to add a check constraint to the column: ``` CHECK (month BETWEEN 1 AND 12) ```
Bite the bullet, use the MonthID. It's the better decision in the long term, as it's clearer, and the waste involved in having an enumeration table for Month is trivial. (And by the way, the decision to use an enumeration table for month, while some may consider it unnecessary, is, I think, the right one.)
Using a smalldatetime or int for storing a month in database
[ "", "sql", "database", "database-design", "" ]
I am trying to read a image file (.jpeg to be exact), and 'echo' it back to the page output, but have is display an image... my index.php has an image link like this: ``` <img src='test.php?image=1234.jpeg' /> ``` and my php script does basically this: 1) read 1234.jpeg 2) echo file contents... 3) I have a feeling I need to return the output back with a mime-type, but this is where I get lost Once I figure this out, I will be removing the file name input all together and replace it with an image id. If I am unclear, or you need more information, please reply.
The PHP Manual has [this example](http://php.net/manual/en/function.fpassthru.php): ``` <?php // open the file in a binary mode $name = './img/ok.png'; $fp = fopen($name, 'rb'); // send the right headers header("Content-Type: image/png"); header("Content-Length: " . filesize($name)); // dump the picture and stop the script fpassthru($fp); exit; ?> ``` The important points is that you must send a Content-Type header. Also, you must be careful not include any extra white space (like newlines) in your file before or after the `<?php ... ?>` tags. As suggested in the comments, you can avoid the danger of extra white space at the end of your script by omitting the `?>` tag: ``` <?php $name = './img/ok.png'; $fp = fopen($name, 'rb'); header("Content-Type: image/png"); header("Content-Length: " . filesize($name)); fpassthru($fp); ``` You still need to carefully avoid white space at the top of the script. One particularly tricky form of white space is a [UTF-8 BOM](http://en.wikipedia.org/wiki/Byte_order_mark#UTF-8). To avoid that, make sure to save your script as "ANSI" (Notepad) or "ASCII" or "UTF-8 without signature" (Emacs) or similar.
I feel like we can make this code a little bit easier by just getting the mime type from $image\_info: ``` $file_out = "myDirectory/myImage.gif"; // The image to return if (file_exists($file_out)) { $image_info = getimagesize($file_out); //Set the content-type header as appropriate header('Content-Type: ' . $image_info['mime']); //Set the content-length header header('Content-Length: ' . filesize($file_out)); //Write the image bytes to the client readfile($file_out); } else { // Image file not found header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found"); } ``` With this solution any type of image can be processed but it is just another option. Thanks *ban-geoengineering* for your contribution.
Return a PHP page as an image
[ "", "php", "image-processing", "http-headers", "mime-types", "" ]
I have a DataTable bound to a DataGridView. I have FullRowSelect enabled in the DGV. Is there a way to get the selected row as a DataRow so that I can get strongly typed access to the selected row's values?
I'm not sure how to do it w/o a BindingSource, here is how to do it with one: ``` var drv = bindingSoure1.Current as DataRowView; if (drv != null) var row = drv.Row as MyRowType; ```
``` DataRowView currentDataRowView = (DataRowView)dgv1.CurrentRow.DataBoundItem DataRow row = currentDataRowView.Row ```
How Do I Get the Selected DataRow in a DataGridView?
[ "", "c#", "winforms", "data-binding", "ado.net", "datagridview", "" ]
I'm developing a window application in C# VS2005. I have a dataGridView in which the first column has Checkboxes. Now i want the Column header also to be a CheckBox which if i select all the Checkboxex in the column should get selected. How can i do this.? I referred the [Code Project link](http://www.codeproject.com/KB/grid/DataGridView_winforms.aspx) But if i use that, if i click the **FirstCell (not the Header)** all the below cells are getting selected. But i want a CheckBox in the Column header. How can i do this.?
I also needed to have a `CheckBox` in the column header of a `DataGridView` column. Here's how I did it: * Create a class which inherits from `DataGridViewColumnHeaderCell` * Internally use a `System.Windows.Forms.CheckBox` to store the checked state and provide the OS styled visual `CheckBox` representation. * Use a `Bitmap` as a buffer and draw the regular `CheckBox` on it (using `CheckBox.DrawToBitmap`) * Override `DataGridViewColumnHeaderCell.Paint` and, if necessary, update the buffer before drawing the buffer to the `Graphics` supplied by `Paint` * Provide a Checked property on the derived `DataGridViewColumnHeaderCell`, and also a CheckedChanged event * Substitute the derived `DataGridViewColumnHeaderCell` in the column's `HeaderCell` when the `DataGridView` is being populated. * Check and uncheck the `CheckBox` when it is the column header is clicked, only if the mouse click is within the bounds of the `CheckBox` * Implement the check-all/uncheck-all outside of the derived class by listening to the `CheckedChanged` event, updating the underlying data object and then calling `ResetBindings` to update the `DataGridView` Here's the class I wrote which is derived from `DataGridViewColumnHeaderCell`: ``` class DataGridViewCheckBoxColumnHeaderCell : DataGridViewColumnHeaderCell { private Bitmap buffer; private CheckBox checkBox; private Rectangle checkBoxBounds; public DataGridViewCheckBoxColumnHeaderCell() { this.checkBox = new CheckBox(); } public event EventHandler CheckedChanged; public bool Checked { get { return this.checkBox.Checked; } set { if (!this.Checked == value) { this.checkBox.Checked = value; if (this.buffer != null) { this.buffer.Dispose(); this.buffer = null; } this.OnCheckedChanged(EventArgs.Empty); if (this.DataGridView != null) { this.DataGridView.Refresh(); } } } } protected override void Paint( Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates dataGridViewElementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { // Passing String.Empty in place of // value and formattedValue prevents // this header cell from having text. base.Paint( graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, String.Empty, String.Empty, errorText, cellStyle, advancedBorderStyle, paintParts); if (this.buffer == null || cellBounds.Width != this.buffer.Width || cellBounds.Height != this.buffer.Height) { this.UpdateBuffer(cellBounds.Size); } graphics.DrawImage(this.buffer, cellBounds.Location); } protected override Size GetPreferredSize( Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize) { return this.checkBox.GetPreferredSize(constraintSize); } protected override void OnMouseClick(DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Left && this.checkBoxBounds.Contains(e.Location)) { this.Checked = !this.Checked; } base.OnMouseClick(e); } private void UpdateBuffer(Size size) { Bitmap updatedBuffer = new Bitmap(size.Width, size.Height); this.checkBox.Size = size; if (this.checkBox.Size.Width > 0 && this.checkBox.Size.Height > 0) { Bitmap renderedCheckbox = new Bitmap( this.checkBox.Width, this.checkBox.Height); this.checkBox.DrawToBitmap( renderedCheckbox, new Rectangle(new Point(), this.checkBox.Size)); MakeTransparent(renderedCheckbox, this.checkBox.BackColor); Bitmap croppedRenderedCheckbox = AutoCrop( renderedCheckbox, Color.Transparent); // TODO implement alignment, right now it is always // MiddleCenter regardless of this.Style.Alignment this.checkBox.Location = new Point( (updatedBuffer.Width - croppedRenderedCheckbox.Width) / 2, (updatedBuffer.Height - croppedRenderedCheckbox.Height) / 2); Graphics updatedBufferGraphics = Graphics.FromImage(updatedBuffer); updatedBufferGraphics.DrawImage( croppedRenderedCheckbox, this.checkBox.Location); this.checkBoxBounds = new Rectangle( this.checkBox.Location, croppedRenderedCheckbox.Size); renderedCheckbox.Dispose(); croppedRenderedCheckbox.Dispose(); } if (this.buffer != null) { this.buffer.Dispose(); } this.buffer = updatedBuffer; } protected virtual void OnCheckedChanged(EventArgs e) { EventHandler handler = this.CheckedChanged; if (handler != null) { handler(this, e); } } // The methods below are helper methods for manipulating Bitmaps private static void MakeTransparent(Bitmap bitmap, Color transparencyMask) { int transparencyMaskArgb = transparencyMask.ToArgb(); int transparentArgb = Color.Transparent.ToArgb(); List deadColumns = new List(); for (int x = 0; x = 0; x--) { if (deadColumns.Count == bitmap.Height) { break; } for (int y = bitmap.Height - 1; y >= 0; y--) { if (deadColumns.Contains(y)) { continue; } int pixel = bitmap.GetPixel(x, y).ToArgb(); if (pixel == transparencyMaskArgb) { bitmap.SetPixel(x, y, Color.Transparent); } else if (pixel != transparentArgb) { deadColumns.Add(y); break; } } } } public static Bitmap AutoCrop(Bitmap bitmap, Color backgroundColor) { Size croppedSize = bitmap.Size; Point cropOrigin = new Point(); int backgroundColorToArgb = backgroundColor.ToArgb(); for (int x = bitmap.Width - 1; x >= 0; x--) { bool allPixelsAreBackgroundColor = true; for (int y = bitmap.Height - 1; y >= 0; y--) { if (bitmap.GetPixel(x, y).ToArgb() != backgroundColorToArgb) { allPixelsAreBackgroundColor = false; break; } } if (allPixelsAreBackgroundColor) { croppedSize.Width--; } else { break; } } for (int y = bitmap.Height - 1; y >= 0; y--) { bool allPixelsAreBackgroundColor = true; for (int x = bitmap.Width - 1; x >= 0; x--) { if (bitmap.GetPixel(x, y).ToArgb() != backgroundColorToArgb) { allPixelsAreBackgroundColor = false; break; } } if (allPixelsAreBackgroundColor) { croppedSize.Height--; } else { break; } } for (int x = 0; x = 0 && xWhole = 0) { bitmapSection.SetPixel(x, y, bitmap.GetPixel(xWhole, yWhole)); } else { bitmapSection.SetPixel(x, y, Color.Transparent); } } } return bitmapSection; } } ```
The above solution is kind of good, but there is also an easier way! Simply add these two methods and then you would have what you want! First add a `show_chkBox` method to your code and call it in the `onload` function of your form or after creating your `DataGridView`: ``` private void show_chkBox() { Rectangle rect = dataGridView1.GetCellDisplayRectangle(0, -1, true); // set checkbox header to center of header cell. +1 pixel to position rect.Y = 3; rect.X = rect.Location.X + (rect.Width/4); CheckBox checkboxHeader = new CheckBox(); checkboxHeader.Name = "checkboxHeader"; //datagridview[0, 0].ToolTipText = "sdfsdf"; checkboxHeader.Size = new Size(18, 18); checkboxHeader.Location = rect.Location; checkboxHeader.CheckedChanged += new EventHandler(checkboxHeader_CheckedChanged); dataGridView1.Controls.Add(checkboxHeader); } ``` and then you would have the checkbox in the header. For the selecting problem, just add this code: ``` private void checkboxHeader_CheckedChanged(object sender, EventArgs e) { CheckBox headerBox = ((CheckBox)dataGridView1.Controls.Find("checkboxHeader", true)[0]); int index = 0; for (int i = 0; i < dataGridView1.RowCount; i++) { dataGridView1.Rows[i].Cells[0].Value = headerBox.Checked; } } ```
How to have Checkbox as ColumnHeader of dataGridView
[ "", "c#", "visual-studio", "" ]
Over the course of the last couple of hours I have been tracking down a fairly specific bug with that occurs because another application has the clipboard open. Essentially as the clipboard is a shared resource (as per ["Why does my shared clipboard not work?"](http://blogs.msdn.com/rds/archive/2006/11/20/why-does-my-shared-clipboard-not-work-part-2.aspx)) and you attempt to execute ``` Clipboard.SetText(string) ``` or ``` Clipboard.Clear(). ``` The following exception is thrown: ``` System.Runtime.InteropServices.ExternalException: Requested Clipboard operation did not succeed. at System.Windows.Forms.Clipboard.ThrowIfFailed(Int32 hr) at System.Windows.Forms.Clipboard.SetDataObject(Object data, Boolean copy, Int32 retryTimes, Int32 retryDelay) at System.Windows.Forms.Clipboard.SetText(String text, TextDataFormat format) at System.Windows.Forms.Clipboard.SetText(String text) ``` My initial solution was to retry after a short pause, until I realised that Clipboard.SetDataObject has fields for the number of times and the length of the delay. .NET's default behaviour is to try 10 times with a 100 msec delay. There is one final thing that has been noted by the end user. That is, despite the exception being thrown, the copy to clipboard operation still works. I haven't been able to find any further information about why this may be. My current solution to the issue is just to silently ignore the exception... is this really the best way?
As the clipboard is shared by all UI applications, you will run into this from time to time. Obviously, you don't want your application to crash if it failed to write to the clipboard, so gracefully handling ExternalException is reasonable. I would suggest presenting an error to the user if the SetObjectData call to write to the clipboard fails. A suggestion would be to use (via [P/Invoke](http://en.wikipedia.org/wiki/Platform_Invocation_Services)) [`user32!GetOpenClipboardWindow`](http://msdn.microsoft.com/en-us/library/ms649044(VS.85).aspx) to see if another application has the clipboard open. It will return the HWND of the window which has the clipboard open, or `IntPtr.Zero` if no application had it open. You could spin on the value until its `IntPtr.Zero` for a specified amount of time.
Another workaround would be to use `Clipboard.SetDataObject` instead of `Clipboard.SetText`. According to [this MSDN article](http://msdn.microsoft.com/en-us/library/ms158293.aspx) this method has two parameters - **retryTimes** and **retryDelay** - that you can use like this: ``` System.Windows.Forms.Clipboard.SetDataObject( "some text", // Text to store in clipboard false, // Do not keep after our application exits 5, // Retry 5 times 200); // 200 ms delay between retries ```
How to handle a blocked clipboard and other oddities
[ "", "c#", ".net", "clipboard", "" ]
I am interested in formatting all the files in a Visual Studio (ver. 2005) project all at once. Currently, there is a way to format a single document by doing something like **Edit->Advanced->Format Document**. However, I don't see a single command to format all the files of a project all at once. Any idea how to do that?
Tim Abell wrote a macro to do this on his [blog](http://timwise.blogspot.com/2009/01/format-all-document-in-visual-studio.html): > Here's a handy macro script for visual studio I knocked together today. > It runs "edit, format document" on every document of the listed file types. > > You have to keep an eye on it as it's interactive and does sometimes pop up a message and wait for an answer. > > You can get the vb file at <https://github.com/timabell/vs-formatter-macro> > More info at <https://github.com/timabell/vs-formatter-macro/wiki> The original code is available at the blog post. Note that this is older than the version available on github above.
The [Format All Files](https://marketplace.visualstudio.com/items?itemName=munyabe.FormatAllFiles) extension worked for me. Nothing to do, just install and click!
Formatting - at once - all the files in a Visual Studio project
[ "", "c#", "visual-studio", "visual-studio-2005", "formatting", "" ]
Please define what `stdClass` is.
`stdClass` is PHP's generic empty class, kind of like `Object` in Java or `object` in Python (**Edit:** but not actually used as universal base class; thanks *@Ciaran for* [pointing this out](https://stackoverflow.com/a/992654/911182)). It is useful for anonymous objects, dynamic properties, etc. An easy way to consider the StdClass is as an alternative to associative array. See this example below that shows how `json_decode()` allows to get an StdClass instance or an associative array. Also but not shown in this example, `SoapClient::__soapCall` returns an StdClass instance. ``` <?php //Example with StdClass $json = '{ "foo": "bar", "number": 42 }'; $stdInstance = json_decode($json); echo $stdInstance->foo . PHP_EOL; //"bar" echo $stdInstance->number . PHP_EOL; //42 //Example with associative array $array = json_decode($json, true); echo $array['foo'] . PHP_EOL; //"bar" echo $array['number'] . PHP_EOL; //42 ``` See [Dynamic Properties in PHP and StdClass](http://krisjordan.com/dynamic-properties-in-php-with-stdclass) for more examples.
`stdClass` is just a generic 'empty' class that's used when casting other types to objects. Despite what the other two answers say, `stdClass` is **not** the base class for objects in PHP. This can be demonstrated fairly easily: ``` class Foo{} $foo = new Foo(); echo ($foo instanceof stdClass)?'Y':'N'; // outputs 'N' ``` I don't believe there's a concept of a base object in PHP
What is stdClass in PHP?
[ "", "php", "stdclass", "" ]
I am using the Ado.Net Entity Framework with ASP.NET MVC. In my MSSQL 2008 Database I have for example the following simplified tables and relations: ``` (Song) 1--* (Version) 1 -- 1 (VersionInfo) ``` Is it possible to automatically have the linked Versions and their VersionInfo's deleted when I delete a Song? Currently I am using something like the following code, which is a lot of manual work, since some tables have up to 8 relations and those relations have subrelations too sometimes: ``` db = new Database() //Entities Song song = db.Song.First(); Song.Version.Load(); foreach(Version version in Song.Version.ToList()) { //Remove Song-Version Reference. song.Version.Remove(version); //Get The VersionInfo so we can delete it after we deleted the Version object. version.VersionInfoReference.Load(); VersionInfo versionInfo = version.VersionInfo; //Now we can delete the Version Object. db.DeleteObject(version); //Now we can also delete the versionInfo, since the reference is gone. db.DeleteObject(versionInfo); } db.DeleteObject(song); ``` There must be an easier way to get cascading deletions. I already tried setting the relationship setting in MSSQL to Cascade when Deleting, but it didn't do a thing... Did I miss something there? Anyway, how do other people solve this problem?
You should not be doing this in the Entity Framework. All popular relational databases support `ON CASCADE DELETE` on foreign keys which is a lot more efficient as well. I suggest you just go with that. It appears in your case you may have to cascade deletes in song to version and deletes in version to version info. Just load up the table designer in SQL Manager and you should see the relevant options under relationships.
I tried it with a simpler database, 2 tables, and found out that cascade is only from the 1 side of a 1-many. ``` table A id - int b_id - int table B id - int ``` Relationship is set between A.b\_id and B.id. Delete rule is cascade. When I delete A, B is not deleted. When I delete B, A is deleted. Problem is, I want to have B deleted when I delete A. I guess that is only possible manually.
ADO.NET Entity Framework: How to get auto cascading deletions?
[ "", "c#", "database", "entity-framework", "ado.net", "" ]
I have a website that makes heavy use of Ajax. Occasionally I need to load large image files on the page for the user. My question is, when these large image files are being download, is there a way to stop them if, say, the user navigates away from the page displaying the image? Thanks.
I had the exact same issue, when users 'paged' quickly through (ajax) search results the browser was still trying to download profile images for every page not just the current one. This code worked for me, called on the paging event just before the new search was run: ``` //cancel image downloads if(window.stop !== undefined) { window.stop(); } else if(document.execCommand !== undefined) { document.execCommand("Stop", false); } ``` Essentially it's like clicking the "Stop" button on the browser. Tested in **IE, FireFox, Chrome, Opera and Safari**
like this. ``` $(img).attr('src',''); ```
Javascript: Cancel/Stop Image Requests
[ "", "javascript", "image", "" ]
I'm using the Entity Framework and I developed this extension method: ``` public static IQueryable<TResult> Like<TResult>(this IQueryable<TResult> query, Expression<Func<TResult, string>> field, string value) { var expression = Expression.Lambda<Func<TResult, bool>>( Expression.Call(field.Body, typeof(string).GetMethod("Contains"), Expression.Constant(value)), field.Parameters); return query.Where(expression); } ``` this code work correctly if I use it like this: ``` var result = from e in context.es.Like(r => r.Field, "xxx") select e ``` Now I need to call this extension method programmatically: ``` public static IQueryable<TSource> SearchInText<TSource>(this IQueryable<TSource> source, string textToFind) { // Collect fields PropertyInfo[] propertiesInfo = source.ElementType.GetProperties(); List<string> fields = new List<string>(); foreach (PropertyInfo propertyInfo in propertiesInfo) { if ( (propertyInfo.PropertyType == typeof(string)) || (propertyInfo.PropertyType == typeof(int)) || (propertyInfo.PropertyType == typeof(long)) || (propertyInfo.PropertyType == typeof(byte)) || (propertyInfo.PropertyType == typeof(short)) ) { fields.Add(propertyInfo.Name); } } ParameterExpression parameter = Expression.Parameter(typeof(TSource), source.ElementType.Name); Expression expression = Expression.Lambda(Expression.Property(parameter, typeof(TSource).GetProperty(fields[0])), parameter); Expression<Func<TSource, string>> field = Expression.Lambda<Func<TSource, string>>(expression, parameter); return source.Like(field, textToFind); } ``` Now this code doesn't work! I need to understand how to declare the "field" of the Like extended methods. ``` Expression<Func<TSource, string>> field = Expression.Lambda<Func<TSource, string>>(expression, parameter); ``` At runtime I receive this error: Impossibile utilizzare un'espressione di tipo 'System.Func`2[TestMdf.Equipment,System.String]' per un tipo restituito 'System.String'
This is my first release: ``` public static IQueryable<TSource> SearchInText<TSource>(this IQueryable<TSource> source, string textToFind) { if (textToFind.Trim() == "") { return source; } string[] textToFindList = textToFind.Replace("'", "''").Split(' '); // Collect fields PropertyInfo[] propertiesInfo = source.ElementType.GetProperties(); List<string> fieldList = new List<string>(); foreach (PropertyInfo propertyInfo in propertiesInfo) { if ( (propertyInfo.PropertyType == typeof(string)) || (propertyInfo.PropertyType == typeof(int)) || (propertyInfo.PropertyType == typeof(long)) || (propertyInfo.PropertyType == typeof(byte)) || (propertyInfo.PropertyType == typeof(short)) ) { fieldList.Add(propertyInfo.Name); } } ParameterExpression parameter = Expression.Parameter(typeof(TSource), source.ElementType.Name); MethodInfo concatMethod = typeof(String).GetMethod("Concat", new Type[] { typeof(string), typeof(string) }); var spaceExpression = Expression.Constant(" "); var concatenatedField = BinaryExpression.Add(spaceExpression, Expression.MakeMemberAccess(parameter, typeof(TSource).GetProperty(fieldList[0])), concatMethod); for (int i = 1; i < fieldList.Count; i++) { concatenatedField = BinaryExpression.Add(concatenatedField, spaceExpression, concatMethod); concatenatedField = BinaryExpression.Add(concatenatedField, Expression.MakeMemberAccess(parameter, typeof(TSource).GetProperty(fieldList[i])), concatMethod); } concatenatedField = BinaryExpression.Add(concatenatedField, spaceExpression, concatMethod); var fieldsExpression = Expression.Call(concatenatedField, "ToUpper", null, null); var clauseExpression = Expression.Call( fieldsExpression, typeof(string).GetMethod("Contains", new Type[] { typeof(string) }), Expression.Constant(textToFindList[0].ToUpper()) ); if (textToFindList.Length == 1) { return source.Where(Expression.Lambda<Func<TSource, bool>>(clauseExpression, parameter)); } BinaryExpression expression = Expression.And(Expression.Call( fieldsExpression, typeof(string).GetMethod("Contains", new Type[] { typeof(string) }), Expression.Constant(textToFindList[1].ToUpper()) ), clauseExpression); for (int i = 2; i < textToFindList.Length; i++) { expression = Expression.And(Expression.Call( fieldsExpression, typeof(string).GetMethod("Contains", new Type[] { typeof(string) }), Expression.Constant(textToFindList[i].ToUpper()) ), expression); } return source.Where(Expression.Lambda<Func<TSource, bool>>(expression, parameter)); } ``` I will modify to manage some rules like "phrase" + and - operator.
I assume your second code snippet is just a truncated example - if you really did that, then the results would be unpredictable, because you're taking the first property returned by reflection, which can change between runs of your program. You'll get better answers if you say "This worked" followed by a description of what happened, and "This didn't work" followed by a description of how you could tell that it didn't work (compiler error? runtime error? exception message?) Firstly, are you aware of [Dynamic Linq](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx)? It allows you to delay decisions about how a query should be structured until runtime and may solve many of your problems for you. But assuming this is a learning exercise... Your `Like` extension method takes an expression (which a caller ought to usually write out as a lambda, as that's the whole point of these things). That expression will convert a "record" from a query result set and return a string value (presumably selecting it from the data stored in the record). The method also takes a value string. But it then constructs (by hand) its own predicate that calls the `Contains` method on the body of the `field` lambda. I guess this ought to work, because the result of that lambda is a string. However, I can't see why you're doing this the hard way. What's wrong with: ``` var result = from e in context.es where e.Field.Contains("xxx")) select e ```
Trying to develop a new extension method
[ "", "c#", "linq", "entity-framework", "linq-to-entities", "lambda", "" ]
I have a scheduled task that I need to kick off by browsing to a page, my webhost doesn't allow me to use the windows scheduler. One job this task performs is to get some data from a bunch of other websites, due to how slow web-requests can be I've set up the task to use threading. Running this task from an mvc action seems to cause the whole webserver to go wacky, making it refuse to load any more pages. Is it bad to use threading from a web-app? Is there a way for me to safely do it? What threading limits are there? I really just need to know some more information? **EDIT: SUBQUESTIONS** If I use threads from the threadpool (which is used by the ASP.NET runtime (**thanks Anton**), can I limit how many of the threads it can use? What is the ASP.NET threadpool size limit? Would be be better to have a separate site which does this? Perhaps a virtual folder containing a separate ASP.NET application? That would stop me from limiting the threadpool right?
When servicing incoming requests, ASP.NET runtime acquires threads from .NET `ThreadPool`, which has limited capacity. So if you're using threads from that tread pool, this may harm your applications' scalability. The way around this will be spawning a usual `Thread`, but these can be killed when your AppPool gets recycled.
I would be surprised if it actively caused a problem, as long as those threads don't try to talk back to the request/response (which may now be gone). What symptoms are you seeing? Can you define "wacky"? I use threads routinely for logging etc, without issue. To minimise the impact, you could use a producer/consume pattern, so you only have one (or a few) worker threads, servicing however-many ASP.NET MVC request/response threads.
Can I safely spawn threads in ASP.NET MVC?
[ "", "c#", ".net", "asp.net-mvc", "" ]
I need to download and install about 50 CRLs once a week and install them on several Windows servers. Downloading is the easy part, is there a way I could script the CRL import process?
I don't know a way to do it via script. Can you write C code? If I understand what you want to do, you will use the [CryptUiWizImport](http://msdn.microsoft.com/en-us/library/aa380598.aspx) function, and the [CRYPTUI\_WIZ\_IMPORT\_SRC\_INFO](http://msdn.microsoft.com/en-us/library/aa380870(VS.85).aspx) structure. Here's a [sample of code that installs a Cert](http://blogs.msdn.com/alejacma/archive/2008/01/31/how-to-import-a-certificate-without-user-interaction-c-c.aspx); the corresponding CRL import is similar. **Addendum**: [This post](http://blogs.msdn.com/powershell/archive/2006/04/25/583236.aspx) points out that Win32 APIs (such as CryptUiWizImport) are not directly accessible from PowerShell, and then describes a possible workaround: from within the PowerShell script, dynamically generate and compile C# code that does the P/Invoke stuff, and then run the resulting assembly. This would allow you to do the CryptUiWizImport strictly from a powershell script, although it would be a pretty exotic one.
Here is my final source (slightly scrubbed for the public) - but should work. I won't change the accepted answer, but I do hope this helps (as does upvoting the question and answers!). **Note:** This will import both a CRL or a regular certificate into the LOCAL MACHINE Trusted Root store. Changing the below `CERT_SYSTEM_STORE_LOCAL_MACHINE` to `CERT_SYSTEM_STORE_CURRENT_USER` in the call CertOpenStore will change it to work for the Current User store. ``` using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace ConsoleApplication2 { class Program { public struct CRYPTUI_WIZ_IMPORT_SRC_INFO { public Int32 dwSize; public Int32 dwSubjectChoice; [MarshalAs(UnmanagedType.LPWStr)]public String pwszFileName; public Int32 dwFlags; [MarshalAs(UnmanagedType.LPWStr)]public String pwszPassword; } [DllImport("CryptUI.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern Boolean CryptUIWizImport( Int32 dwFlags, IntPtr hwndParent, IntPtr pwszWizardTitle, ref CRYPTUI_WIZ_IMPORT_SRC_INFO pImportSrc, IntPtr hDestCertStore ); [DllImport("CRYPT32.DLL", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr CertOpenStore( int storeProvider, int encodingType, IntPtr hcryptProv, int flags, String pvPara ); public const Int32 CRYPTUI_WIZ_IMPORT_SUBJECT_FILE = 1; public const Int32 CRYPT_EXPORTABLE = 0x00000001; public const Int32 CRYPT_USER_PROTECTED = 0x00000002; public const Int32 CRYPTUI_WIZ_NO_UI = 0x0001; private static int CERT_STORE_PROV_SYSTEM = 10; private static int CERT_SYSTEM_STORE_CURRENT_USER = (1 << 16); private static int CERT_SYSTEM_STORE_LOCAL_MACHINE = (2 << 16); static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage: certimp.exe list.crl"); Environment.ExitCode = 1; } else { IntPtr hLocalCertStore = CertOpenStore( CERT_STORE_PROV_SYSTEM, 0, IntPtr.Zero, CERT_SYSTEM_STORE_LOCAL_MACHINE, "ROOT" ); CRYPTUI_WIZ_IMPORT_SRC_INFO importSrc = new CRYPTUI_WIZ_IMPORT_SRC_INFO(); importSrc.dwSize = Marshal.SizeOf(importSrc); importSrc.dwSubjectChoice = CRYPTUI_WIZ_IMPORT_SUBJECT_FILE; importSrc.pwszFileName = args[0]; importSrc.pwszPassword = null; importSrc.dwFlags = CRYPT_EXPORTABLE | CRYPT_USER_PROTECTED; if (!CryptUIWizImport( CRYPTUI_WIZ_NO_UI, IntPtr.Zero, IntPtr.Zero, ref importSrc, hLocalCertStore )) { Console.WriteLine("CryptUIWizImport error " + Marshal.GetLastWin32Error()); Environment.ExitCode = -1; } } } } } ```
Programmatically install Certificate Revocation List (CRL)
[ "", "c#", "powershell", "scripting", "vbscript", "batch-file", "" ]
The per key handling of updating the registry seems a bit poor when dealing with large volumes of data. Are there any libraries that would treat all keys as tables and allow INSERTS, UPDATES, or SELECTS in a more programmatic fasion?
If you want do do scripting windows powershell has some quite nifty [registry access](http://tfl09.blogspot.com/2007/01/using-registry-with-powershell.html). It handles the registry as if it were a filesystem.
WMI offers access to the registry and has a [SQL like language called WQL](http://msdn.microsoft.com/en-us/library/aa394606(VS.85).aspx).
SQL like wrapper for Windows Registry?
[ "", "sql", "windows", "registry", "" ]
How do I convert a string to a binary array in PHP?
I think you are asking for the equivalent to the Perl pack/unpack functions. If that is the case, I suggest you look at the PHP pack/unpack functions: * [Unpack](http://us.php.net/manual/en/function.unpack.php "Unpack data from binary string") * [Pack](http://us.php.net/pack "Pack Data Into Binary string")
Let's say that you want to convert $stringA="Hello" to binary. First take the first character with ord() function. This will give you the ASCII value of the character which is decimal. In this case it is 72. Now convert it to binary with the dec2bin() function. Then take the next function. You can find how these functions work at <http://www.php.net>. OR use this piece of code: ``` <?php // Call the function like this: asc2bin("text to convert"); function asc2bin($string) { $result = ''; $len = strlen($string); for ($i = 0; $i < $len; $i++) { $result .= sprintf("%08b", ord($string{$i})); } return $result; } // If you want to test it remove the comments //$test=asc2bin("Hello world"); //echo "Hello world ascii2bin conversion =".$test."<br/>"; //call the function like this: bin2ascii($variableWhoHoldsTheBinary) function bin2ascii($bin) { $result = ''; $len = strlen($bin); for ($i = 0; $i < $len; $i += 8) { $result .= chr(bindec(substr($bin, $i, 8))); } return $result; } // If you want to test it remove the comments //$backAgain=bin2ascii($test); //echo "Back again with bin2ascii() =".$backAgain; ?> ```
String to byte/binary arrays in PHP
[ "", "php", "arrays", "" ]
We have only a very small number of customers (fewer than 50) and we would like each one to have its own separate log file into which all of its server side logging info goes. I know you could use NDC and filters to direct log statements to different files using the standard appenders in Log4j but that would require quite a bit more setup (to create loggers for all existing customers) and it wouldn't automatically accomodate the addition of a new customer into the system. Have you ever seen an appender which would split out log statements to separate files based on the Log4j NDC value? I figure I could build a new appender to do it but I can't say I want to if I can get something already built that works well.
SiftingAppender which ships with logback (log4j's successor) is designed precisely to handle this situation. As its name implies, a `SiftingAppender` can be used to separate (or sift) logging according to a given runtime attribute. For example, `SiftingAppender` can separate logging events according to user sessions, so that the logs generated by every user go into distinct log files, one log file per user. For example, `SiftingAppender` can separate logging events into distinct log files, one file per user. The [documentation for SiftingAppender](http://logback.qos.ch/manual/appenders.html#SiftingAppender) contains an example for separating logs based on user id.
It sounds like you want a multi-file appender sort of thing, where you give a part of a filename and the rest is filled in with the NDC. I am not aware of anything like this. Probably you would have to roll your own. If you roll your own, you probably want to create an `Appender` that internally uses a `Map` of `RollingFileAppender`s that is created dynamically. I don't know if an Appender has access to the NDC, however. This would probably be a non-trivial undertaking.
Have you seen an appender that would log to separate files based on NDC in Log4j?
[ "", "java", "logging", "log4j", "" ]
I have seen many products bundeled with JDK, I wonder if there is a way where one can install JDK by simply unzipping contents to a directory, so there is no icon created in add/remove programs, no registry entries etc. Also in this case: How can we configure Java plugin for browsers? And how can we configure settings as seen via Control Panel entry for Java?
Yes, you can create a zipped up JDK, unzip it on the target machine and run java, javac, etc. from that directory to your heart's content. The easiest way to create such a zip file is to install the JDK on a machine and then zip up the contents of the JDK directory. We do this in certain circumstances where we need to control exactly what configuration of Java will be used in our deployments. In that case, our scripts just point JAVA\_HOME (or the equivalent) to our internally bundled JDK instead of relying on a sysadmin to install exactly what we need prior to arrival. In terms of integrating with the browsers, that can be a bit more problematic. The short answer is no, you can't integrate directly with the browser without *some* sort of installer.
According to [this](https://stackoverflow.com/a/6571736/1646025), I created a [batch script](https://github.com/hydra1983/usr_local_bin/tree/master/extra/jdk2z) to build jdk archives automatically. The essential parts of the link are: > * Create working JDK directory ("C:\JDK" in this case) > * Download latest version of JDK from oracle (for example "jdk-7u7-windows-i586.exe") > * Download and install 7-zip (or download 7-zip portable version if you are not administrator) > * With 7-zip extract all the files from "jdk-[6-7]u?-windows-i586.exe" in directory "C:\JDK" > * In command shell (cmd.exe) do the following: > 1. change directory to directory C:\JDK.rsrc\JAVA\_CAB10 > 2. execute command: **extrac32 111** > * Unpack C:\JDK.rsrc\JAVA\_CAB10\tools.zip with 7-zip > * In command shell (cmd.exe) do the following: > 1. change directory to C:\JDK.rsrc\JAVA\_CAB10\tools\ > 2. execute command: **for /r %x in (\*.pack) do .\bin\unpack200 -r "%x" "%~dx%~px%~nx.jar"** (this will convert all pack files into jar) > * Copy whole directory and all subdir of c:\JDK.rsrc\JAVA\_CAB10\tools" where you want your JDK to be and setup manually JAVA\_HOME and PATH to point to your JDK dir and its BIN subdir.
Installing Java manually on Windows?
[ "", "java", "windows", "installation", "" ]
(note: I'm quite familiar with Java, but not with Hibernate or JPA - yet :) ) I want to write an application which talks to a DB2/400 database through JPA and I have now that I can get all entries in the table and list them to System.out (used MyEclipse to reverse engineer). I understand that the @Table annotation results in the name being statically compiled with the class, but I need to be able to work with a table where the name and schema are provided at runtime (their defintion are the same, but we have many of them). Apparently this is not SO easy to do, and I'd appreciate a hint. I have currently chosen Hibernate as the JPA provider, as it can handle that these database tables are not journalled. So, the question is, how can I at runtime tell the Hibernate implementation of JPA that class A corresponds to database table B? (edit: an overridden tableName() in the Hibernate NamingStrategy may allow me to work around this intrinsic limitation, but I still would prefer a vendor agnostic JPA solution)
You need to use the [XML version](http://docs.jboss.org/hibernate/stable/core/reference/en/html/tutorial-firstapp.html#tutorial-firstapp-mapping) of the configuration rather than the annotations. That way you can dynamically generate the XML at runtime. Or maybe something like [Dynamic JPA](http://www.dynamicjava.org/projects/dynamic-jpa) would interest you? I think it's necessary to further clarify the issues with this problem. The first question is: are the set of tables where an entity can be stored known? By this I mean you aren't dynamically creating tables at runtime and wanting to associate entities with them. This scenario calls for, say, three tables to be known at *compile-time*. If that is the case you can possibly use JPA inheritance. The OpenJPA documentation details the [table per class](http://openjpa.apache.org/builds/1.0.2/apache-openjpa-1.0.2/docs/manual/jpa_overview_mapping_inher.html#jpa_overview_mapping_inher_tpc) inheritance strategy. The advantage of this method is that it is pure JPA. It comes with limitations however, being that the tables have to be known and you can't easily change which table a given object is stored in (if that's a requirement for you), just like objects in OO systems don't generally change class or type. If you want this to be truly dynamic and to move entities between tables (essentially) then I'm not sure JPA is the right tool for you. An [awful lot of magic](http://www.cforcoding.com/2009/05/orms-vs-sql-jpa-story.html) goes into making JPA work including load-time weaving (instrumentation) and usually one or more levels of caching. What's more the entity manager needs to record changes and handle updates of managed objects. There is no easy facility that I know of to instruct the entity manager that a given entity should be stored in one table or another. Such a move operation would implicitly require a delete from one table and insertion into another. If there are child entities this gets more difficult. Not impossible mind you but it's such an unusual corner case I'm not sure anyone would ever bother. A lower-level SQL/JDBC framework such as [Ibatis](http://www.cforcoding.com/2009/06/spring-and-ibatis-tutorial.html) may be a better bet as it will give you the control that you want. I've also given thought to dynamically changing or assigning at annotations at runtime. While I'm not yet sure if that's even possible, even if it is I'm not sure it'd necessarily help. I can't imagine an entity manager or the caching not getting hopelessly confused by that kind of thing happening. The other possibility I thought of was dynamically creating subclasses at runtime (as anonymous subclasses) but that still has the annotation problem and again I'm not sure how you add that to an existing persistence unit. It might help if you provided some more detail on what you're doing and why. Whatever it is though, I'm leaning towards thinking you need to rethink what you're doing or how you're doing it or you need to pick a different persistence technology.
You may be able to specify the table name at load time via a custom [ClassLoader](http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html) that re-writes the `@Table` annotation on classes as they are loaded. At the moment, I am not 100% sure how you would ensure Hibernate is loading its classes via this ClassLoader. Classes are re-written using [the ASM bytecode framework](http://asm.ow2.org/). **Warning:** These classes are experimental. ``` public class TableClassLoader extends ClassLoader { private final Map<String, String> tablesByClassName; public TableClassLoader(Map<String, String> tablesByClassName) { super(); this.tablesByClassName = tablesByClassName; } public TableClassLoader(Map<String, String> tablesByClassName, ClassLoader parent) { super(parent); this.tablesByClassName = tablesByClassName; } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { if (tablesByClassName.containsKey(name)) { String table = tablesByClassName.get(name); return loadCustomizedClass(name, table); } else { return super.loadClass(name); } } public Class<?> loadCustomizedClass(String className, String table) throws ClassNotFoundException { try { String resourceName = getResourceName(className); InputStream inputStream = super.getResourceAsStream(resourceName); ClassReader classReader = new ClassReader(inputStream); ClassWriter classWriter = new ClassWriter(0); classReader.accept(new TableClassVisitor(classWriter, table), 0); byte[] classByteArray = classWriter.toByteArray(); return super.defineClass(className, classByteArray, 0, classByteArray.length); } catch (IOException e) { throw new RuntimeException(e); } } private String getResourceName(String className) { Type type = Type.getObjectType(className); String internalName = type.getInternalName(); return internalName.replaceAll("\\.", "/") + ".class"; } } ``` The `TableClassLoader` relies on the `TableClassVisitor` to catch the [visitAnnotation](http://asm.ow2.org/current/doc/javadoc/user/org/objectweb/asm/ClassVisitor.html#visitAnnotation(java.lang.String,%20boolean)) method calls: ``` public class TableClassVisitor extends ClassAdapter { private static final String tableDesc = Type.getDescriptor(Table.class); private final String table; public TableClassVisitor(ClassVisitor visitor, String table) { super(visitor); this.table = table; } @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { AnnotationVisitor annotationVisitor; if (desc.equals(tableDesc)) { annotationVisitor = new TableAnnotationVisitor(super.visitAnnotation(desc, visible), table); } else { annotationVisitor = super.visitAnnotation(desc, visible); } return annotationVisitor; } } ``` The `TableAnnotationVisitor` is ultimately responsible for changing the `name` field of the `@Table` annotation: ``` public class TableAnnotationVisitor extends AnnotationAdapter { public final String table; public TableAnnotationVisitor(AnnotationVisitor visitor, String table) { super(visitor); this.table = table; } @Override public void visit(String name, Object value) { if (name.equals("name")) { super.visit(name, table); } else { super.visit(name, value); } } } ``` Because I didn't happen to find an `AnnotationAdapter` class in ASM's library, here is one I made myself: ``` public class AnnotationAdapter implements AnnotationVisitor { private final AnnotationVisitor visitor; public AnnotationAdapter(AnnotationVisitor visitor) { this.visitor = visitor; } @Override public void visit(String name, Object value) { visitor.visit(name, value); } @Override public AnnotationVisitor visitAnnotation(String name, String desc) { return visitor.visitAnnotation(name, desc); } @Override public AnnotationVisitor visitArray(String name) { return visitor.visitArray(name); } @Override public void visitEnd() { visitor.visitEnd(); } @Override public void visitEnum(String name, String desc, String value) { visitor.visitEnum(name, desc, value); } } ```
JPA: How do I specify the table name corresponding to a class at runtime?
[ "", "java", "hibernate", "jpa", "" ]
my `mysqli_fetch_array(mysqi_query($db, $query))` doesn't appear to be getting the correct information from the database, and therefore, the PHP application is not working as it should. Here are the queries, ``` <?php if($_GET){ $current = mysqli_fetch_array(mysqli_query($db, "SELECT * from `tbl_user` WHERE `userid` = '".$_GET['userid']."'")); $currentperms = mysqli_fetch_array(mysqli_query($db, "SELECT * from `tbl_perms` WHERE `userid` = '".$_GET['userid']."'")); } ?> ``` Concurrently, the `if ($current['userid'] == "1") {echo(" selected ");}` isn't outputting anything at all, so the correct option isn't selected in the SELECT tag. So, where: I'd expect: echo($currentperms['newapp']); not to equal 1, becuase it is set so in the database, the result of which is "1". I have test this by echoing the string gained. Newapp is not a column in the table either, so it shouldn't be returning "1" as a result. With this: ``` if $current['userid'] == "1") { echo(" selected "); } ``` Nothing is being echoed, however, the variable has been used in the script earlier, and the output of which is "1". Please help me, I'm going through the roof :| @sasa: output: Success!Array ( [0] => 1 [userid] => 1 [1] => shamil.nunhuck [username] => shamil.nunhuck [2] => Shamil Nunhuck [userfullname] => Shamil Nunhuck [3] => shamil.nunhuck@localhost [useremail] => shamil.nunhuck@localhost [4] => 6363d731bd7492fe4c33fc3d90fd61bc [userpassword] => 6363d731bd7492fe4c33fc3d90fd61bc [5] => 1 [userlevel] => 1 [6] => Administrator [usertitle] => Administrator [7] => 1 [tos] => 1 ) Array ( [0] => 1 [userid] => 1 [1] => 0 [ptodo] => 0 [2] => 0 [usercp] => 0 [3] => 0 [pm] => 0 [4] => 0 [bug] => 0 [5] => 0 [abug] => 0 [6] => 0 [admincp] => 0 [7] => 0 [intmgs] => 0 [8] => 0 [adduser] => 0 [9] => 0 [pass] => 0 [10] => 0 [useredit] => 0 [11] => 0 [listuser] => 0 [12] => 0 [newapp] => 0 )
Try this code: ``` // I put some echo for testing if(!empty($_GET['id'])) { $id = (int)$_GET['id']; $sql = mysqli_query($db, "SELECT * from tbl_user WHERE userid = $id LIMIT 1"); if(mysqli_affected_rows($db) == 0) { echo "There is no user with that id"; } else { $current = mysql_fetch_assoc($sql); $currentperms = mysql_fetch_assoc(mysqli_query($db, "SELECT * from tbl_perms WHERE userid = $id")); echo "Success!"; // Or try to print result print_r($current); print_r($currentperms); } } else { echo "There is no user id"; } ``` OR maybe just a syntax error: > With this: > > ``` > if $current['userid'] == "1") { > echo(" selected "); > } > ``` It should be: ``` if($current['userid'] == 1) { echo(" selected "); } ```
If the issue is that the database is returning incorrect information it's probably best you just post the mysql portion of the code (esp. the query), the current results and what results you expected to see. also fyi, I hope your parsing your $\_GET and $\_POST vars prior to dumping them into that query. Passing them straight into the SQL like that is not a good idea.
mysqli array -> query not attaining correct data
[ "", "php", "mysqli", "echo", "" ]
I'm trying to parse the DMOZ content/structures XML files into MySQL, but all existing scripts to do this are very old and don't work well. How can I go about opening a large (+1GB) XML file in PHP for parsing?
There are only two php APIs that are really suited for processing large files. The first is the old [expat](https://www.php.net/manual/en/book.xml.php) api, and the second is the newer [XMLreader](https://www.php.net/manual/en/book.xmlreader.php) functions. These apis read continuous streams rather than loading the entire tree into memory (which is what simplexml and DOM does). For an example, you might want to look at this partial parser of the DMOZ-catalog: ``` <?php class SimpleDMOZParser { protected $_stack = array(); protected $_file = ""; protected $_parser = null; protected $_currentId = ""; protected $_current = ""; public function __construct($file) { $this->_file = $file; $this->_parser = xml_parser_create("UTF-8"); xml_set_object($this->_parser, $this); xml_set_element_handler($this->_parser, "startTag", "endTag"); } public function startTag($parser, $name, $attribs) { array_push($this->_stack, $this->_current); if ($name == "TOPIC" && count($attribs)) { $this->_currentId = $attribs["R:ID"]; } if ($name == "LINK" && strpos($this->_currentId, "Top/Home/Consumer_Information/Electronics/") === 0) { echo $attribs["R:RESOURCE"] . "\n"; } $this->_current = $name; } public function endTag($parser, $name) { $this->_current = array_pop($this->_stack); } public function parse() { $fh = fopen($this->_file, "r"); if (!$fh) { die("Epic fail!\n"); } while (!feof($fh)) { $data = fread($fh, 4096); xml_parse($this->_parser, $data, feof($fh)); } } } $parser = new SimpleDMOZParser("content.rdf.u8"); $parser->parse(); ```
This is a very similar question to [Best way to process large XML in PHP](https://stackoverflow.com/questions/1167062/best-way-to-process-large-xml-in-php/8250302) but with a very good specific answer upvoted addressing the specific problem of DMOZ catalogue parsing. However, since this is a good Google hit for large XMLs in general, I will repost my answer from the other question as well: My take on it: <https://github.com/prewk/XmlStreamer> A simple class that will extract all children to the XML root element while streaming the file. Tested on 108 MB XML file from pubmed.com. ``` class SimpleXmlStreamer extends XmlStreamer { public function processNode($xmlString, $elementName, $nodeIndex) { $xml = simplexml_load_string($xmlString); // Do something with your SimpleXML object return true; } } $streamer = new SimpleXmlStreamer("myLargeXmlFile.xml"); $streamer->parse(); ```
Parsing Huge XML Files in PHP
[ "", "php", "xml", "parsing", "" ]
I want to write a script to rename downloaded papers with their titles automatically, I'm wondering if there is any library or tricks i can make use of? The PDFs are all generated by TeX and should have some 'formal' structures.
You could try to use [pyPdf](http://pybrary.net/pyPdf/) and [this example](http://blog.isnotworking.com/2006/08/extract-pdf-title-from-all-files-on.html). **for example:** ``` from pyPdf import PdfFileWriter, PdfFileReader def get_pdf_title(pdf_file_path): with open(pdf_file_path) as f: pdf_reader = PdfFileReader(f) return pdf_reader.getDocumentInfo().title title = get_pdf_title('/home/user/Desktop/my.pdf') ```
Assuming all these papers are from arXiv, you could instead extract the arXiv id (I'd guess that searching for "arXiv:" in the PDF's text would consistently reveal the id as the first hit). Once you have the arXiv reference number (and have done a `pip install arxiv`), you can get the title using ``` paper_ref = '1501.00730' arxiv.query(id_list=[paper_ref])[0].title ```
Extracting titles from PDF files?
[ "", "python", "pdf", "" ]
I need to get a list of all caller methods for a method of interest for me in Java. Is there a tool that can help me with this? Edit: I forgot to mention that I need to do this from a program. I'm usig Java Pathfinder and I want to run it an all the methods that call my method of interest.
For analyzing bytecode, I would recommend [ASM](http://asm.ow2.org/). Given a list of Classes to analyze, a visitor can be made which finds the method calls you're interested in. One implementation which analyses classes in a jar file is below. Note that ASM uses [internalNames](http://asm.ow2.org/current/doc/javadoc/user/index.html) with '/' instead of '.' as a separator. Specify the target method as a [standard declaration](http://asm.ow2.org/current/doc/javadoc/user/org/objectweb/asm/commons/Method.html#getMethod(java.lang.String)) without modifiers. For example, to list methods that could be calling System.out.println("foo") in the java runtime jar: ``` java -cp "classes;asm-3.1.jar;asm-commons-3.1.jar" App \ c:/java/jdk/jre/lib/rt.jar \ java/io/PrintStream "void println(String)" ``` *Edit*: source and line numbers added: Note that this only indicates the last target method invocation per calling method - the original q only wanted to know *which* methods. I leave it as an exercise for the reader to show line numbers of the calling method declaration, or the line numbers of every target invocation, depending on what you're actually after. :) results in: ``` LogSupport.java:44 com/sun/activation/registries/LogSupport log (Ljava/lang/String;)V LogSupport.java:50 com/sun/activation/registries/LogSupport log (Ljava/lang/String;Ljava/lang/Throwable;)V ... Throwable.java:498 java/lang/Throwable printStackTraceAsCause (Ljava/io/PrintStream;[Ljava/lang/StackTraceElement;)V -- 885 methods invoke java/io/PrintStream println (Ljava/lang/String;)V ``` source: ``` public class App { private String targetClass; private Method targetMethod; private AppClassVisitor cv; private ArrayList<Callee> callees = new ArrayList<Callee>(); private static class Callee { String className; String methodName; String methodDesc; String source; int line; public Callee(String cName, String mName, String mDesc, String src, int ln) { className = cName; methodName = mName; methodDesc = mDesc; source = src; line = ln; } } private class AppMethodVisitor extends MethodAdapter { boolean callsTarget; int line; public AppMethodVisitor() { super(new EmptyVisitor()); } public void visitMethodInsn(int opcode, String owner, String name, String desc) { if (owner.equals(targetClass) && name.equals(targetMethod.getName()) && desc.equals(targetMethod.getDescriptor())) { callsTarget = true; } } public void visitCode() { callsTarget = false; } public void visitLineNumber(int line, Label start) { this.line = line; } public void visitEnd() { if (callsTarget) callees.add(new Callee(cv.className, cv.methodName, cv.methodDesc, cv.source, line)); } } private class AppClassVisitor extends ClassAdapter { private AppMethodVisitor mv = new AppMethodVisitor(); public String source; public String className; public String methodName; public String methodDesc; public AppClassVisitor() { super(new EmptyVisitor()); } public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { className = name; } public void visitSource(String source, String debug) { this.source = source; } public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { methodName = name; methodDesc = desc; return mv; } } public void findCallingMethodsInJar(String jarPath, String targetClass, String targetMethodDeclaration) throws Exception { this.targetClass = targetClass; this.targetMethod = Method.getMethod(targetMethodDeclaration); this.cv = new AppClassVisitor(); JarFile jarFile = new JarFile(jarPath); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().endsWith(".class")) { InputStream stream = new BufferedInputStream(jarFile.getInputStream(entry), 1024); ClassReader reader = new ClassReader(stream); reader.accept(cv, 0); stream.close(); } } } public static void main( String[] args ) { try { App app = new App(); app.findCallingMethodsInJar(args[0], args[1], args[2]); for (Callee c : app.callees) { System.out.println(c.source+":"+c.line+" "+c.className+" "+c.methodName+" "+c.methodDesc); } System.out.println("--\n"+app.callees.size()+" methods invoke "+ app.targetClass+" "+ app.targetMethod.getName()+" "+app.targetMethod.getDescriptor()); } catch(Exception x) { x.printStackTrace(); } } } ```
Edit: the original question was edited to indicate a runtime solution was needed - this answer was given before that edit and only indicates how to do it during development. If you are using Eclipse you can right click the method and choose "Open call hierarchy" to get this information. Updated after reading comments: Other IDEs support this as well in a similar fashion (at least Netbeans and IntelliJ do)
How can I find all the methods that call a given method in Java?
[ "", "java", "" ]
Is it possible to zero out the memory of deleted objects in C++? I want to do this to reproduce a coredump in unit test: ``` //Some member variable of object-b is passed-by-pointer to object-a //When object-b is deleted, that member variable is also deleted //In my unit test code, I want to reproduce this //even if I explicitly call delete on object-b //accessBMemberVariable should coredump, but it doesn't //I'm assuming even though object-b is deleted, it's still intact in memory A *a = new A(); { B *b = new B(a); delete b; } a->accessBMemberVariable(); ```
You probably should override the `delete` operator. Example for the given class B: ``` class B { public: // your code ... // override delete void operator delete(void * p, size_t s) { ::memset(p, 0, s); ::operator delete(p, s); } }; ``` **EDIT:** Thanks *litb* for pointing this out.
> accessBMemberVariable should coredump, but it doesn't Nah, why should it? It's quite possible that the memory that b used to occupy is now owned by the CRT, the CRT that your application owns. The CRT may opt to not release memory back to the OS. Core dumps will only happen if you access memory *not* owned by your application. Zeroing out the memory occupied by b may not do you any good depending on the type of variable that A has the address of. My advice would be to allocate B on the stack, that should bring out the fireworks... but then again, not quite in the way you'd expect... So if you really want a core dump you should use the OS functions to allocate memory and free it: ``` char *buf = OS_Alloc(sizeof(B)); B *b = new(buf) B(); a->someBMember = &b->myMember; b->~B(); OS_Free(buf); a->accessBMemberVariable(); ```
how do clean up deleted objects in C++
[ "", "c++", "" ]
In my program, I'm using the WndProc override to stop my form being resized. Thing is, the cursor is still there when you move the pointer to the edge of the form. Is there any way to hide this cursor?
I have found a way using WndProc thanks to the link Lasse sent me. Thanks for your reply Jon but it wasn't exactly what I wanted. For those who want to know how I did it, I used this: ``` protected override void WndProc(ref Message m) { const int WM_NCHITTEST = 0x0084; switch (m.Msg) { case WM_NCHITTEST: return; } base.WndProc(ref m); } ``` I haven't tested it thoroughly so don't know if there are any side-effects but it works fine for me at the moment :).
Why not set the [`FormBorderStyle`](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formborderstyle.aspx) property appropriately instead? Then you don't need to use `WndProc` either. Here's some sample code to demonstrate - click the button to toggle whether or not the form can be resized: ``` using System; using System.Windows.Forms; using System.Drawing; class Test { [STAThread] static void Main(string[] args) { Button button = new Button { Text = "Toggle border", AutoSize = true, Location = new Point(20, 20) }; Form form = new Form { Size = new Size (200, 200), Controls = { button }, FormBorderStyle = FormBorderStyle.Fixed3D }; button.Click += ToggleBorder; Application.Run(form); } static void ToggleBorder(object sender, EventArgs e) { Form form = ((Control)sender).FindForm(); form.FormBorderStyle = form.FormBorderStyle == FormBorderStyle.Fixed3D ? FormBorderStyle.Sizable : FormBorderStyle.Fixed3D; } } ```
C# Hide Resize Cursor
[ "", "c#", "user-interface", "mouse-cursor", "" ]
I have a database full of names like: ``` John Smith Scott J. Holmes Dr. Kaplan Ray's Dog Levi's Adrian O'Brien Perry Sean Smyre Carie Burchfield-Thompson Björn Árnason ``` There are a few foreign names with accents in them that need to be converted to strings with non-accented characters. I'd like to convert the full names (after stripping characters like " ' " , "-") to user logins like: ``` john.smith scott.j.holmes dr.kaplan rays.dog levis adrian.obrien perry.sean.smyre carie.burchfieldthompson bjorn.arnason ``` So far I have: ``` Fullname.strip() # get rid of leading/trailing white space Fullname.lower() # make everything lower case ... # after bad chars converted/removed Fullname.replace(' ', '.') # replace spaces with periods ```
Take a look at this link [redacted] Here is the code from the page ``` def latin1_to_ascii (unicrap): """This replaces UNICODE Latin-1 characters with something equivalent in 7-bit ASCII. All characters in the standard 7-bit ASCII range are preserved. In the 8th bit range all the Latin-1 accented letters are stripped of their accents. Most symbol characters are converted to something meaningful. Anything not converted is deleted. """ xlate = { 0xc0:'A', 0xc1:'A', 0xc2:'A', 0xc3:'A', 0xc4:'A', 0xc5:'A', 0xc6:'Ae', 0xc7:'C', 0xc8:'E', 0xc9:'E', 0xca:'E', 0xcb:'E', 0xcc:'I', 0xcd:'I', 0xce:'I', 0xcf:'I', 0xd0:'Th', 0xd1:'N', 0xd2:'O', 0xd3:'O', 0xd4:'O', 0xd5:'O', 0xd6:'O', 0xd8:'O', 0xd9:'U', 0xda:'U', 0xdb:'U', 0xdc:'U', 0xdd:'Y', 0xde:'th', 0xdf:'ss', 0xe0:'a', 0xe1:'a', 0xe2:'a', 0xe3:'a', 0xe4:'a', 0xe5:'a', 0xe6:'ae', 0xe7:'c', 0xe8:'e', 0xe9:'e', 0xea:'e', 0xeb:'e', 0xec:'i', 0xed:'i', 0xee:'i', 0xef:'i', 0xf0:'th', 0xf1:'n', 0xf2:'o', 0xf3:'o', 0xf4:'o', 0xf5:'o', 0xf6:'o', 0xf8:'o', 0xf9:'u', 0xfa:'u', 0xfb:'u', 0xfc:'u', 0xfd:'y', 0xfe:'th', 0xff:'y', 0xa1:'!', 0xa2:'{cent}', 0xa3:'{pound}', 0xa4:'{currency}', 0xa5:'{yen}', 0xa6:'|', 0xa7:'{section}', 0xa8:'{umlaut}', 0xa9:'{C}', 0xaa:'{^a}', 0xab:'<<', 0xac:'{not}', 0xad:'-', 0xae:'{R}', 0xaf:'_', 0xb0:'{degrees}', 0xb1:'{+/-}', 0xb2:'{^2}', 0xb3:'{^3}', 0xb4:"'", 0xb5:'{micro}', 0xb6:'{paragraph}', 0xb7:'*', 0xb8:'{cedilla}', 0xb9:'{^1}', 0xba:'{^o}', 0xbb:'>>', 0xbc:'{1/4}', 0xbd:'{1/2}', 0xbe:'{3/4}', 0xbf:'?', 0xd7:'*', 0xf7:'/' } r = '' for i in unicrap: if xlate.has_key(ord(i)): r += xlate[ord(i)] elif ord(i) >= 0x80: pass else: r += i return r # This gives an example of how to use latin1_to_ascii(). # This creates a string will all the characters in the latin-1 character set # then it converts the string to plain 7-bit ASCII. if __name__ == '__main__': s = unicode('','latin-1') for c in range(32,256): if c != 0x7f: s = s + unicode(chr(c),'latin-1') print 'INPUT:' print s.encode('latin-1') print print 'OUTPUT:' print latin1_to_ascii(s) ```
If you are not afraid to install third-party modules, then have a look at the [python port of the Perl module `Text::Unidecode`](http://www.tablix.org/~avian/blog/archives/2009/01/unicode_transliteration_in_python/) (it's also [on pypi](http://pypi.python.org/pypi/Unidecode)). The module does nothing more than use a lookup table to transliterate the characters. I glanced over the code and it looks very simple. So I suppose it's working on pretty much any OS and on any Python version (crossingfingers). It's also easy to bundle with your application. With this module you don't have to create your lookup table manually ( = reduced risk it being incomplete). The advantage of this module compared to the unicode normalization technique is this: Unicode normalization does not replace all characters. A good example is a character like "æ". Unicode normalisation will see it as "Letter, lowercase" (Ll). This means using the `normalize` method will give you neither a replacement character nor a useful hint. Unfortunately, that character is not representable in ASCII. So you'll get errors. The mentioned [module](http://www.tablix.org/~avian/blog/archives/2009/01/unicode_transliteration_in_python/) does a better job at this. This will actually replace the "æ" with "ae". Which is actually useful and makes sense. The most impressive thing I've seen is that it goes much further. It even replaces Japanese Kana characters *mostly* properly. For example, it replaces "は" with "ha". Wich is perfectly fine. It's not fool-proof though as the current version replaces "ち" with "ti" instead of "chi". So you'll have to handle it with care for the more exotic characters. Usage of the module is straightforward:: ``` from unidecode import unidecode var_utf8 = "æは".decode("utf8") unidecode( var_utf8 ).encode("ascii") >>> "aeha" ``` Note that I have nothing to do with this module directly. It just happens that I find it very useful. **Edit:** The patch I submitted fixed the bug concerning the Japanese kana. I've only fixed the one's I could spot right away. I may have missed some.
Python String Cleanup + Manipulation (Accented Characters)
[ "", "python", "regex", "unicode", "string", "" ]
I am trying to get into web development, specially interested building the front-end, UI part of websites while learning JavaScript maybe with AJAX technology. (I have a UI, HCI background.) However, I have absolutely no previous knowledge about server-end web development either. To my understanding, frameworks like Django seem to pretty good at this (correct me if I am misunderstanding). So the question is: how much Django, or Rails do I need to know, if my interest is primarily the user interface part of web development. Can I just let somebody else do the back-end stuff? Pardon me for my imprecise choice of terminologies.
You can make a career of front-end user interface development without know a ton about server code. You would do well though to have at least a rudimentary understanding of what happens on the server when you send it a request, where your data comes from, and what the life-cycle of a web page is. This assumes that you have the support of back-end developers. As you mentioned Ajax in your question that implies that you want your web sites to actually do something, which will require things to happen on the back-end (such as storage, manipulation of data, logging in a user, etc.). As with all things, the more you know, the easier it will be to get what you want from the dedicated professionals. I would suggest that you learn about programming in general, not try an learn a language and framework. In particular, try to understand datatypes, server settings (like timeouts, post versus get, etc.), security and database interactions as they exist beyond JavaScript/ECMAScript. That way when a developer is explaining why they cannot do something you have requested or are offering alternatives, you are speaking the same language.
You need to know a bit about the server side. Here's what you need to know. If you have a heavy JavaScript website, you're likely going to want to pass information from the server to clients with JSON (JavaScript Object Notation). This is just a way to format data into strings that JavaScript knows how to convert to objects. So, each of your server-side functions that send data to the client will return JSON. If you have someone writing the server-side for you, that's all you should have to know. You're JS functions will receive JSON, and then you deal with it. If you have to write the server-side yourself, then that involves 1) getting data from database 2) formatting the data 3) converting to JSON. I have open-sourced a commenting widget that accepts JSON messages, and gives examples of how you would set up the Django server code. Maybe it will help you: <http://www.trailbehind.com/comment_widget/>
Do I need server-end knowledge (e.g. Django, Rails), if I want to do Javascript, AJAX stuff?
[ "", "javascript", "ruby-on-rails", "django", "user-interface", "" ]
So you know off the bat, this is a project I've been assigned. I'm not looking for an answer in code, but more a direction. What I've been told to do is go through a file and count the actual lines of code while at the same time recording the function names and individual lines of code for the functions. The problem I am having is determining a way when reading from the file to determine if the line is the start of a function. So far, I can only think of maybe having a string array of data types (int, double, char, etc), search for that in the line and then search for the parenthesis, and then search for the absence of the semicolon (so i know it isn't just the declaration of the function). So my question is, is this how I should go about this, or are there other methods in which you would recommend? The code in which I will be counting will be in C++.
Three approaches come to mind. 1. Use regular expressions. This is fairly similar to what you're thinking of. Look for lines that look like function definitions. This is fairly quick to do, but can go wrong in many ways. ``` char *s = "int main() {" ``` is not a function definition, but sure looks like one. ``` char * /* eh? */ s ( int /* comment? // */ a ) // hello, world /* of confusion { ``` is a function definition, but doesn't look like one. Good: quick to write, can work even in the face of syntax errors; bad: can easily misfire on things that look like (or fail to look like) the "normal" case. Variant: First run the code through, e.g., GNU indent. This will take care of some (but not all) of the misfires. 2. Use a proper lexer and parser. This is a much more thorough approach, but you may be able to re-use an open source lexer/parsed (e.g., from gcc). Good: Will be 100% accurate (will never misfire). Bad: One missing semicolon and it spews errors. 3. See if your compiler has some debug output that might help. This is a variant of (2), but using your compiler's lexer/parser instead of your own.
Your idea can work in 99% (or more) of the cases. Only a real C++ compiler can do 100%, in which case I'd compile in debug mode (`g++ -S prog.cpp`), and get the function names and line numbers from the debug information of the assembly output (`prog.s`). My thoughts for the 99% solution: * Ignore comments and strings. * Document that you ignore preprocessor directives (`#include`, `#define`, `#if`). * Anything between a toplevel `{` and `}` is a function body, except after `typedef`, `class`, `struct`, `union`, `namespace` and `enum`. * If you have a `class`, `struct` or `union`, you should be looking for method bodies inside it. * The function name is sometimes tricky to find, e.g. in `long(*)(char) f(int);` . * Make sure your parser works with template functions and template classes.
finding a function name and counting its LOC
[ "", "c++", "string", "" ]
Is it possible to declare more than one variable using a `with` statement in Python? Something like: ``` from __future__ import with_statement with open("out.txt","wt"), open("in.txt") as file_out, file_in: for line in file_in: file_out.write(line) ``` ... or is cleaning up two resources at the same time the problem?
It is possible in [Python 3 since v3.1](http://docs.python.org/3.1/reference/compound_stmts.html#with) and [Python 2.7](http://docs.python.org/dev/whatsnew/2.7.html#other-language-changes). The new [`with` syntax](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement) supports multiple context managers: ``` with A() as a, B() as b, C() as c: doSomething(a,b,c) ``` Unlike the `contextlib.nested`, this guarantees that `a` and `b` will have their `__exit__()`'s called even if `C()` or it's `__enter__()` method raises an exception. You can also use earlier variables in later definitions (h/t [Ahmad](https://stackoverflow.com/questions/893333/multiple-variables-in-a-with-statement#comment78254813_1073814) below): ``` with A() as a, B(a) as b, C(a, b) as c: doSomething(a, c) ``` As of Python 3.10, [you can use parentheses](https://docs.python.org/3/whatsnew/3.10.html#parenthesized-context-managers): ``` with ( A() as a, B(a) as b, C(a, b) as c, ): doSomething(a, c) ```
Note that if you split the variables into lines, prior to Python 3.10 you must use backslashes to wrap the newlines. ``` with A() as a, \ B() as b, \ C() as c: doSomething(a,b,c) ``` Parentheses don't work, since Python creates a tuple instead. ``` with (A(), B(), C()): doSomething(a,b,c) ``` Since tuples lack a `__enter__` attribute, you get an error (undescriptive and does not identify class type): > ``` > AttributeError: __enter__ > ``` If you try to use `as` within parentheses, Python catches the mistake at parse time: ``` with (A() as a, B() as b, C() as c): doSomething(a,b,c) ``` > ``` > SyntaxError: invalid syntax > ``` ## When will this be fixed? This issue is tracked in <https://bugs.python.org/issue12782>. Python announced in [PEP 617](https://www.python.org/dev/peps/pep-0617/) that they would replace the original parser with a new one. Because Python's original parser is LL(1), it [cannot distinguish](https://www.python.org/dev/peps/pep-0617/#some-rules-are-not-actually-ll-1) between "multiple context managers" `with (A(), B()):` and "tuple of values" `with (A(), B())[0]:`. The new parser can properly parse multiple context managers surrounded by parentheses. The new parser has been enabled in 3.9. It was reported that this syntax will still be rejected until the old parser is removed in Python 3.10, and this syntax change was reported in the [3.10 release notes](https://docs.python.org/3/whatsnew/3.10.html). But in my testing, it works in trinket.io's Python 3.9.6 as well.
Multiple variables in a 'with' statement?
[ "", "python", "with-statement", "" ]
The code is this one: ``` $vendors[] = array( "id" => $row['vendorID'], "name" => $row['name'] == "" ? "-" : $row['name'], "tel1" => $row['phone1'] == "" ? "-" : $row['phone1'], "tel2" => $row['phone2'] == "" ? "-" : $row['phone2'], "mail" => $row['email'] == "" ? "-" : $row['email'], "web" => $row['web'] == "" ? "-" : $row['web']); ``` Can somebody explain me exactly what it is? Look like an [Alternative syntax](https://www.php.net/manual/en/control-structures.alternative-syntax.php) but I haven't managed to find infos. Thanks you
This is a [ternary operator](https://www.php.net/ternary#language.operators.comparison.ternary): > The expression `(expr1) ? (expr2) : (expr3)` evaluates to `expr2` if `expr1` evaluates to `TRUE`, and `expr3` if `expr1` evaluates to `FALSE`.
It means: if value is "" (empty), then set to "-" (hyphen), else set to whatever it is. Just read a?b:c as «if a then b else c».
I've encountered this kind of syntax: var == "" ? "-" : var. Can somebody explain?
[ "", "php", "syntax", "" ]
I've learned that to have a singleton lazy loading, this is the pattern to use: ``` private MyObject() { } public static MyObject Instance { get { return SingletonCreator.CreatorInstance; } } private static class SingletonCreator { private static readonly MyObject _instance = new MyObject(); public static MyObject CreatorInstance { get { return _instance; } } } ``` But a more simple pattern would be: ``` private static readonly MyObject _instance = new MyObject(); private MyObject() { } public static MyObject Instance { get { return _instance; } } ``` This wouldn't be lazy loading. But is this really something that I should bother about in a web application?
Unless you have static methods which don't need the singleton, just including a static constructor is enough to make the class lazy. Without the static constructor it's still *mostly* lazy. See my [singleton implementation page](http://pobox.com/~skeet/csharp/singleton.html) for more details and options. I'd normally the code you gave at the bottom of the question - it's lazy enough, unless you *really* don't want to initialize the singleton unless it's going to be used. (Basically with `beforefieldinit` set, the JIT will generally make sure that every type used in a method is initialized; without `beforefieldinit` it has to wait until the first actual use of the class during execution. See my [`beforefieldinit` page](http://pobox.com/~skeet/csharp/beforefieldinit.html) for more information - but the important point is that it's still not going to initialize all singletons as soon as the assembly is loaded, or anything like that.)
Lazy loading usually implies that you're lazily loading something from a database. What you're doing is usually called "[lazy initialization](http://en.wikipedia.org/wiki/Lazy_initialization)" (technically "lazy initialization" is a method of implementation of a lazy loading pattern). As to your original questions: first off, you don't need a singleton. If you *still* need it, [here's](http://www.yoda.arachsys.com/csharp/singleton.html) how this should be done properly. Third, you don't need a singleton.
Should I bother about lazy loading in a web application?
[ "", "c#", ".net", "performance", "lazy-loading", "" ]