Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Can some one give me a best way to implement a daily job with .NET technology. I have an asp.net application with the sqlserver database hosted in shared hosting, GODaddy in my instance. My application is used to add / change the data in the database which is performing quite fairly at this time. I got a new requirement to send some email alerts daily based on some data criteria that were stored in the database. Initially I thought to write a windows service, but godaddy is not allowing to access the database other than its hosted applications. Does someone has any idea to send alerts daily at 1:00AM? Thanks in advance
See [Easy Background Tasks in ASP.NET](https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/) by Jeff Atwood. Copy/paste from the link: ``` private static CacheItemRemovedCallback OnCacheRemove = null; protected void Application_Start(object sender, EventArgs e) { AddTask("DoStuff", 60); } private void AddTask(string name, int seconds) { OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved); HttpRuntime.Cache.Insert(name, seconds, null, DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, OnCacheRemove); } public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r) { // do stuff here if it matches our taskname, like WebRequest // re-add our task so it recurs AddTask(k, Convert.ToInt32(v)); } ```
I haven't used GoDaddy for anything other than domain registration, so I have no experience with what you can or cannot do on their hosting platform. I also don't know what their support or knowledge base is like, but I'd say your best option is to ask GoDaddy what they recommend. Otherwise, you might keep implementing something that's technically feasible, but is blocked by the hosting company. If it's not something that's a prime-time application, one quick and dirty thing to do is to have some kind of external bot calling a (secure) web page on the server that fires off the notification process. Not a real solution, but if this site is just a hobby of yours, it could get you by until you find something the host will allow. Might also be a good time to find a new host, if this one is not meeting your requirements. There are lots of good ASP.NET hosts available these days.
Schedule a job in hosted web server
[ "", "c#", "asp.net", "web", "" ]
In the SQL Server, I am trying to insert values from one table to another by using the below query: ``` delete from tblTable1 insert into tblTable1 select * from tblTable1_Link ``` I am getting the following error: > Column name or number of supplied values does not match table definition. I am sure that both the tables have the same structure, same column names and same data types.
They don't have the same structure... I can guarantee they are different I know you've already created it... [There is already an object named ‘tbltable1’ in the database](https://stackoverflow.com/questions/1152811/there-is-already-an-object-named-tbltable1-in-the-database) What you may want is this (which also fixes your other issue): ``` Drop table tblTable1 select * into tblTable1 from tblTable1_Link ```
I want to also mention that if you have something like ``` insert into blah select * from blah2 ``` and blah and blah2 are identical keep in mind that a computed column will throw this same error... I just realized that when the above failed and I tried ``` insert into blah (cola, colb, colc) select cola, colb, colc from blah2 ``` In my example it was fullname field (computed from first and last, etc)
Column name or number of supplied values does not match table definition
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
I have a column called check\_num (bank check number) as VARCHAR2 type in a payment\_line table(Oracle). The requirement is "I have to search all those checks which numbers are greater than 12345. Please suggest how can I achieve this?
There most likely is a more elegant solution, but this should do the trick: ``` SELECT * FROM payment_line pl WHERE LENGTH(TRIM(TRANSLATE(pl.check_num, '0123456789',' '))) IS NULL AND TRIM(TRANSLATE(pl.check_num, '0123456789','0123456789')) > 12345; ``` **edit:** If I understand your comment to Adam Paynter, for input of: ``` 0A132 1A117 2A123 12D24 02134 11111 12345 21334 ``` and you used `1A117` as your comparison the resulting set would be: ``` 2A123 12D24 02134 11111 12345 21334 ``` Can you confirm that both `02134` and `11111` should be in this result set? They dont seem to meet the requirements of `>` a value like `1A117`. If, however, that was a typo, you can actually run a simple string comparison to get this set: ``` SELECT * FROM payment_line pl WHERE pl.check_num > '1A117'; ``` **edit 2** OK, I think I see where you are going with this. You are looking to get the rows in the db that have been entered after the input row. If you look at my formatted list above, you will see that your result set is everything below your input string. So, with that in mind, i submit for your approval the following: ``` SELECT * FROM payment_line WHERE rowid > (select rowid from payment_line where check_num ='1A117'); ```
Unfortunately, Oracle does not provide a handy function such as `IS_INTEGER(...)`, otherwise you could have done a query like: ``` -- Fictional, though desirable, query: SELECT * FROM checks WHERE IS_INTEGER(check_num) AND TO_NUMBER(check_num) > 12345 ``` However, there is a way to emulate such a function: ``` -- Real, though less-than-desirable, query: SELECT * FROM checks WHERE TRIM(TRANSLATE(check_num, '0123456789', ' ')) IS NULL AND TO_NUMBER(check_num) > 12345 ``` The `TRANSLATE(check_num, '0123456789', ' ')` call replaces each digit within `check_num` with a space. For example: ``` check_num TRANSLATE(check_num, '0123456789', ' ') --------------------------------------------------------------------- '12345' ' ' 'cat' 'cat' '123cat45' ' cat ' ``` Therefore, if `check_num` contains **only** digits, then `TRIM(TRANSLATE(check_num, '0123456789', ' '))` will be `NULL` (that is, the empty string).
Cheque Number problem
[ "", "sql", "oracle", "" ]
I'm working on an auto-reload feature for WHIFF [<http://whiff.sourceforge.net>](http://whiff.sourceforge.net) (so you have to restart the HTTP server less often, ideally never). I have the following code to reload a package module "location" if a file is added to the package directory. It doesn't work on Windows XP. How can I fix it? I think the problem is that getmtime(dir) doesn't change on Windows when the directory content changes? I'd really rather not compare an os.listdir(dir) with the last directory content every time I access the package... ``` if not do_reload and hasattr(location, "__path__"): path0 = location.__path__[0] if os.path.exists(path0): dir_mtime = int( os.path.getmtime(path0) ) if fn_mtime<dir_mtime: print "dir change: reloading package root", location do_reload = True md_mtime = dir_mtime ``` In the code the "fn\_mtime" is the recorded mtime from the last (re)load. ... added comment: I came up with the following work around, which I think may work, but I don't care for it too much since it involves code generation. I dynamically generate a code fragment to load a module and if it fails it tries again after a reload. Not tested yet. ``` GET_MODULE_FUNCTION = """ def f(): import %(parent)s try: from %(parent)s import %(child)s except ImportError: # one more time... reload(%(parent)s) from %(parent)s import %(child)s return %(child)s """ def my_import(partname, parent): f = None # for pychecker parentname = parent.__name__ defn = GET_MODULE_FUNCTION % {"parent": parentname, "child": partname} #pr "executing" #pr defn try: exec(defn) # defines function f() except SyntaxError: raise ImportError, "bad function name "+repr(partname)+"?" partmodule = f() #pr "got", partmodule setattr(parent, partname, partmodule) #pr "setattr", parent, ".", partname, "=", getattr(parent, partname) return partmodule ``` Other suggestions welcome. I'm not happy about this...
long time no see. I'm not sure exactly what you're doing, but the equivalent of your code: ``` GET_MODULE_FUNCTION = """ def f(): import %(parent)s try: from %(parent)s import %(child)s except ImportError: # one more time... reload(%(parent)s) from %(parent)s import %(child)s return %(child)s """ ``` to be `exec`ed with: ``` defn = GET_MODULE_FUNCTION % {"parent": parentname, "child": partname} exec(defn) ``` is (per [the docs](http://docs.python.org/library/functions.html?highlight=__import__#__import__)), assuming parentname names a package and partname names a module in that package (if partname is a top-level name of the parentname package, such as a function or class, you'll have to use a getattr at the end): ``` import sys def f(parentname, partname): name = '%s.%s' % (parentname, partname) try: __import__(name) except ImportError: parent = __import__(parentname) reload(parent) __import__(name) return sys.modules[name] ``` without exec or anything weird, just call this `f` appropriately.
There are two things about your first code snippet that concern me: * You cast the float from getmtime to int. Dependening on the frequency this code is run, you might get unreliable results. * At the end of the code you assign dir\_mtime to a variable md\_mtime. fn\_mtime, which you check against, seems not to be updated.
python windows directory mtime: how to detect package directory new file?
[ "", "python", "windows-xp", "" ]
Is there a simple way to count the number of occurrences of all elements of a list into that same list in C#? Something like this: ``` using System; using System.IO; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Linq; string Occur; List<string> Words = new List<string>(); List<string> Occurrences = new List<string>(); // ~170 elements added. . . for (int i = 0;i<Words.Count;i++){ Words = Words.Distinct().ToList(); for (int ii = 0;ii<Words.Count;ii++){Occur = new Regex(Words[ii]).Matches(Words[]).Count;} Occurrences.Add (Occur); Console.Write("{0} ({1}), ", Words[i], Occurrences[i]); } } ```
How about something like this ... ``` var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 }; var g = l1.GroupBy( i => i ); foreach( var grp in g ) { Console.WriteLine( "{0} {1}", grp.Key, grp.Count() ); } ``` Edit per comment: I will try and do this justice. :) In my example, it's a `Func<int, TKey>` because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an `IGrouping<int,int>` (a grouping of ints keyed by an int). If I changed it to (`i => i.ToString()` ) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ... ``` private string SampleMethod( int i ) { // magically return "One" if i == 1, "Two" if i == 2, etc. } ``` So, that's a Func that would take an int and return a string, just like ... ``` i => // magically return "One" if i == 1, "Two" if i == 2, etc. ``` But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.
You can do something like this to count from a list of things. ``` IList<String> names = new List<string>() { "ToString", "Format" }; IEnumerable<String> methodNames = typeof(String).GetMethods().Select(x => x.Name); int count = methodNames.Where(x => names.Contains(x)).Count(); ``` To count a single element ``` string occur = "Test1"; IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"}; int count = words.Where(x => x.Equals(occur)).Count(); ```
A method to count occurrences in a list
[ "", "c#", ".net-3.5", "list", "count", "match", "" ]
I'm writing a RESTful API in Python using the [restish](http://ish.io/projects/show/restish) framework. I would like to write some unit tests (using the unittest package, for example), that will make different requests to my application and validate the results. The unit tests should be able to run as-is, without needing to start a separate web-server process. How do I set up a mock environment using restish to do this? Thanks
Restish has a built in TestApp class that can be used to test restish apps. Assuming you have a "test" dir in your root restish project callte "restest" created with [paster](http://pythonpaste.org/script/). ``` import os import unittest from paste.fixture import TestApp class RootTest (unittest.TestCase): def setUp(self): self.app = TestApp('config:%s/../development.ini' % os.path.dirname(os.path.abspath(__file__))) def tearDown(self): self.app = None def test_html(self): res = self.app.get('/') res.mustcontain('Hello from restest!') if __name__ == '__main__': unittest.main() ```
I test everything using [WebTest](http://pythonpaste.org/webtest/ "WebTest") and [NoseTests](http://code.google.com/p/python-nose/ "Nose") and I can strongly recommend it. It's fast, flexible and easy to set up. Just pass it your wsgi function and you're good to go.
Write unit tests for restish in Python
[ "", "python", "unit-testing", "" ]
Where can I find a control for WinForms that will highlight source code pasted into it? I would like one that has syntax highlighting support for many different languages but if it only works with C# I would be fine with that also.
[Scintilla.NET](http://scintillanet.codeplex.com/) is probably what you're looking for
Just recently have found a nice control from codeproject [Fast Colored TextBox for syntax highlighting](http://www.codeproject.com/KB/edit/FastColoredTextBox_.aspx). The only issue with using Rich Text Box as highlighter is slow performance on coloring, in cases when the size of the document is big. For a medium size documents this issue can be fixed by delayed highlighting.
A textbox/richtextbox that has syntax highlighting? [C#]
[ "", "c#", "winforms", "syntax", "textbox", "richtextbox", "" ]
I don't think so, but I thought I'd ask just in case. For example, for use in a class that encapsulates an int: ``` i = IntContainer(3) i + 5 ``` And I'm not just interested in this int example, I was looking for something clean and general, not overriding every int and string method. Thanks, sunqiang. That's just what I wanted. I didn't realize you could subclass these immutable types (coming from C++). ``` class IntContainer(int): def __init__(self,i): #do stuff here self.f = 4 def MultiplyBy4(self): #some member function self *= self.f return self print 3+IntContainer(3).MultiplyBy4() ```
sometimes maybe just subclass from int directly is enough. then `__add__` and `__radd__` need not costuming. ``` class IntContainer(int): pass i = IntContainer(3) print i + 5 # 8 print 4 + i # 7 class StrContainer(str): pass s = StrContainer(3) print s + '5' # 35 print '4' + s # 43 ```
This should do what you need: ``` class IntContainer(object): def __init__(self, x): self.x = x def __add__(self, other): # do some type checking on other return self.x + other def __radd__(self, other): # do some type checking on other return self.x + other ``` Output: ``` In [6]: IntContainer(3) + 6 Out[6]: 9 In [7]: 6 + IntContainer(3) Out[7]: 9 ``` For more information search for "radd" in the following docs: * <http://docs.python.org/reference/datamodel.html#special-method-names> You'll find other such methods for "right addition", "right subtraction", etc. Here's another link covering the same operators: * <http://www.siafoo.net/article/57#reversed-binary-operations> By the way, Python does have casting operators: * <http://www.siafoo.net/article/57#casts> But, they won't accomplish what you need in your example (basically because methods don't have any type annotation for parameters, so there's no good way to cast implicitly). So you can do this: ``` class IntContainer2(object): def __init__(self, x): self.x = x def __int__(self): return self.x ic = IntContainer2(3) print int(ic) + 6 print 6 + int(ic) ``` But this will fail: ``` print ic + 6 # error: no implicit coercion ```
does python have conversion operators?
[ "", "python", "operators", "" ]
I want to show certain parts of an `ItemTemplate` based according to whether a bound field is null. Take for example the following code: *(Code such as LayoutTemplate have been removed for brevity)* ``` <asp:ListView ID="MusicList" runat="server"> <ItemTemplate> <tr> <% if (Eval("DownloadLink") != null) { %> <td> <a href="<%#Eval("DownloadLink") %>">Link</a> </td> <% } %> </tr> </ItemTemplate> </asp:ListView> ``` The above gives the following run-time error: > Databinding methods such as Eval(), > XPath(), and Bind() can only be used > in the context of a databound control. **So how can put some conditional logic (like the above) in an `ItemTemplate` ?**
What about binding the "Visible" property of a control to your condition? Something like: ``` <asp:ListView ID="MusicList" runat="server"> <ItemTemplate> <tr runat="server" Visible='<%# Eval("DownloadLink") != null %>'> <td> <a href='<%#Eval("DownloadLink") %>'>Link</a> </td> </tr> </ItemTemplate> </asp:ListView> ```
To resolve "The server tag is not well formed." for the answers involving visibility, remove quotes from the Visible= parameter. So it will become: ``` <tr runat="server" Visible=<%# Eval("DownloadLink") != null ? true : false %>> ```
ASP.Net: Conditional Logic in a ListView's ItemTemplate
[ "", "c#", "asp.net", "data-binding", "listview", "logic", "" ]
In trying to understand the correlation between program objects and data in tables (here:[OO program and SQL database](https://stackoverflow.com/questions/1149877/oo-program-and-sql-database)), which I still don't really understand, a strong difference of opinion was revealed over whether it's ok to use a SQL db to store data for an OO program. 1. For a new programmer, is it ok/recommended, or not? 2. If not, is the alternative to an OO program a procedural program? Also I don't understand **[Object-relational impedance mismatch](http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch)**, which is what people *mean* when they say that it's "not OK to use an SQL DB to store data for an OO program": can someone summarize it, or is there a simple example that illustrates it?
> For a new programmer, is it ok/recommended, or not? That question implies that the system design/components/architecture are chosen/intended to benefit the programmer. Instead I prefer to choose the design/components/architecture to benefit the system (and the system's owners, users, and operators), and ensure that the programmers know (which may require some learning or training on their part) what they need in order to develop that system. The facts are: * OO is often a good way to develop software * SQL DBs are often a good way to store data * Designing the mapping from SQL to OO may be non-trivial > If not, is the alternative to an OO program a procedural program? Well, maybe, yes: one of the features of OO is subclassing, and subclasses/inheritance is one of the things that's problematic to model/store in a SQL database. For example, given a OOD like this ... ``` class Animal { int id; string name; abstract void eat(); abstract void breed(); } class Dog : Animal { bool pedigree; override void eat() {...} override void breed() {...} } class Bird : Animal { bool carnivore; int numberOfEggs; void fly() {...} override void eat() {...} override void breed() {...} } ``` ... it isn't obvious whether to store this data using 2 SQL tables, or 3. Whereas if you take the subclassing away: ``` class Dog { int id; string name; bool pedigree; void eat() {...} void breed() {...} } class Bird { int id; string name; bool carnivore; int numberOfEggs; void fly() {...} void eat() {...} void breed() {...} } ``` ... then it's easier/more obvious/more 1-to-1/more accurate to model this data using exactly two tables. > Also I don't understand Object-relational impedance mismatch Here's an article that's longer and more famous than the Wikipedia article; maybe it's easier to understand: [The Vietnam of Computer Science](http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx) Note that one of the *solutions*, which is proposes to the problem, is: > "**Manual mapping.** Developers simply > accept that it's not such a hard > problem to solve manually after all, > and write straight relational-access > code to return relations to the > language, access the tuples, and > populate objects as necessary." In other words, it's not such a hard problem in practice. It's a hard problem *in theory*, i.e. it's hard to write a tool which creates the mapping automatically and without your having to think about it; but that's true of many aspects of programming, not only this one.
I would say it if definitly OK to use an SQL Database to store data for an Object-oriented program (I do this almost all the time -- and it works quite fine) Procedural vs Object-Oriented is quite a debate ; I don't think you should choose depending on the storage type you're using : the choice should be more about your code and your application. OOP comes with many advantages, one of which is (in my opinion) better maintenability ; better isolation, encapsulation, and all that is true too. Actually, after having programmed in OOP for a couple of years, I would find hard (and I actually do...) to do procedural programming ; the ability of having data and related-methods to manipulate them in a single class, used a an independant entity, is really great.
OO and SQL
[ "", "sql", "database-design", "oop", "" ]
I'm using a jQuery tip plugin to show help tips when the user hovers certain elements of the page. I need to register the plugin events after the page is loaded using css selectors. The problem is I'm using an ASP.NET Update Panel and after the first postback, the tips stop working because the update panel replaces the page content but doesn't rebind the javascript events. I need a way to execute a javascript callback after the Update Panel refreshes its content, so I can rebind the javascript events to have the tips working again. Is there any way to do this?
Instead of putting your jQuery code inside of `$(document).ready()`, put it inside ``` function pageLoad(sender, args) { ... } ``` `pageLoad` is executed after every postback, synchronous or asynchronous. `pageLoad` is a reserved function name in ASP.NET AJAX that is for this purpose. `$(document).ready()` on the other hand, is executed only once, when the DOM is initially ready/loaded. See this [Overview of ASP.NET AJAX client lifecycle events](http://msdn.microsoft.com/en-us/library/bb386417.aspx)
The pageLoad didn't work. I used this instead: ``` var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_pageLoaded(pageLoaded); function pageLoaded() { } ```
How to have a javascript callback executed after an update panel postback?
[ "", "javascript", "asp.net-ajax", "updatepanel", "callback", "" ]
I think there must be an attribute to hide a public property from the datagridview. But I can't find it.
If you are adding the columns yourself... don't add the columns you don't want. If you have `AutoCreateColumns` enabled, then: * if it is a class-based model, add `[Browsable(false)]` to properties you don't want * or set the column's `.Visible` to false * or simply remove the columns you don't want afterwards
From [Is there an Attribute I can use in my class to tell DataGridView not to create a column for it when bound to a List<MyClass>](https://stackoverflow.com/questions/1066907/is-there-an-attribute-i-can-use-in-my-class-to-tell-datagridview-not-to-create-a) [Browsable(false)]
c# Hide a property in datagridview with datasource
[ "", "c#", "attributes", "datasource", "" ]
How does an inline function differ from a preprocessor macro?
Preprocessor macros are just substitution patterns applied to your code. They can be used almost anywhere in your code because they are replaced with their expansions before any compilation starts. Inline functions are actual functions whose body is directly injected into their call site. They can only be used where a function call is appropriate. Now, as far as using macros vs. inline functions in a function-like context, be advised that: * Macros are not type safe, and can be expanded regardless of whether they are syntatically correct - the compile phase will report errors resulting from macro expansion problems. * Macros can be used in context where you don't expect, resulting in problems * Macros are more flexible, in that they can expand other macros - whereas inline functions don't necessarily do this. * Macros can result in side effects because of their expansion, since the input expressions are copied wherever they appear in the pattern. * Inline function are not always guaranteed to be inlined - some compilers only do this in release builds, or when they are specifically configured to do so. Also, in some cases inlining may not be possible. * Inline functions can provide scope for variables (particularly static ones), preprocessor macros can only do this in code blocks {...}, and static variables will not behave exactly the same way.
First, the preprocessor macros are just "copy paste" in the code before the compilation. So there is no **type checking**, and some **side effects** can appear For example, if you want to compare 2 values: ``` #define max(a,b) ((a<b)?b:a) ``` The side effects appear if you use `max(a++,b++)` for example (`a` or `b` will be incremented twice). Instead, use (for example) ``` inline int max( int a, int b) { return ((a<b)?b:a); } ```
Inline functions vs Preprocessor macros
[ "", "c++", "c", "macros", "inline", "" ]
I help moderate a forum online, and on this forum we restrict the size of signatures. At the moment we test this via a simple Greasemonkey script I wrote; we wrap all signatures with a `<div>`, the script looks for them, and then measures the div's height and width. All the script does right now is make sure the signature resides in a particular height/width. I would like to start measuring the file size of the images inside of a signature automatically so that the script can automatically flag users who are including huge images in their signature. However, I can't seem to find a way to measure the size of images loaded on the page. I've searched and found a property special to IE (element.fileSize) but I obviously can't use that in my Greasemonkey script. Is there a way to find out the file size of an image in Firefox via JavaScript? Edit: People are misinterpreting the problem. The forums themselves do not host images; we host the BBCode that people enter as their signature. So, for example, people enter this: ``` This is my signature, check out my [url=http://google.com]awesome website[/url]! This image is cool! [img]http://image.gif[/img] ``` I want to be able to check on these images via Greasemonkey. I could write a batch script to scan all of these instead, but I'm just wondering if there's a way to augment my current script.
Short answer, you cannot Also, Check on jGuru [How can you check the file size from JavaScript in a form with an input type of file?](http://www.jguru.com/faq/view.jsp?EID=330134) You will find some important points > Well the answer is very simple, you cannot. > > Reason: The browser security does not allow the scripts > (Javascript/VBScript) or even applets and ActiveX Controls to read > files from the local hard disk. You can only read files if your code > is signed by some Certificate Authority (CA). Now the input type > "FILE" also does not have the permission to read files. We cannot do > anything about that since thats what HTML says. So since it cannot > read files, it cannot find the size of the file with which the input > tag is associated. Since it cannot find the file size, there is no > function exposed by JavaScript/VBScript to return the file size. But > if you need to find the file size, say in order to restrict the size > of the file uploaded to your web-server. Then you can do so by > counting the file contents on the server-side, once the user submits > it to the server. Thats what many of the free e-mail providers like > www.hotmail.com do.
As you know IE supports the fileSize property of an image. No such luck in other browsers ... however, you should be able to modify this script: <http://natbat.net/2008/Aug/27/addSizes/> It uses JSON to read HTTP headers of files and display their actual file size. That should help you prevent people uploading large animated GIFs. As for getting the dimensions: ``` var img = new Image(); theImage.src = "someimage.jpg"; actualwidth = theImage.width; actualheight = theImage.height; ``` This of course is a pure client-side approach to something best handled server-side.
How can you determine the file size in JavaScript?
[ "", "javascript", "image", "file", "greasemonkey", "" ]
I have to clear and redraw a raphael javascript main container. I've tried with ``` var paper = Raphael(10, 50, 320, 200); paper.remove(); // Doesn't work paper.node.removeNode(); //this neither paper.removeNode(); //this neither ``` Any idea?
Actually it's just come to my notice that there's the much easier paper.clear(); It's not documented.
When you create a paper it creates a DOM object. You can access this with ``` paper.canvas ``` When you create a new Raphael object, you create a new DOM object and leave the original one alone! This is the best way to do it considering everything though. If you want to delete the canvas you only need to do the next command: ``` //Note: after calling this function the paper object will be useless! //Make paper object null (or a new paper object) immediately! function clearPaper(paper){ var paperDom = paper.canvas; paperDom.parentNode.removeChild(paperDom); } ```
Simplest way to clear a container using raphaeljs javascript graphical library
[ "", "javascript", "svg", "raphael", "" ]
> **Possible Duplicate:** > [Advantages of SQL Server 2008 over SQL Server 2005?](https://stackoverflow.com/questions/198478/advantages-of-sql-server-2008-over-sql-server-2005) What are the major differences between Sql Server 2005 and Sql Server 2008? How could I convince my organization to invest in Sql Server 2008? For me, one major aspect that I see is that they have a good framework to programmatically generate SSIS packages with the use of ezAPI. I want to know your reasons. Thanks.
What's new in SQL Server 2008 <http://www.microsoft.com/sqlserver/2008/en/us/whats-new.aspx>
This might help <http://technet.microsoft.com/en-us/magazine/2008.04.overview.aspx?pr=blog> It covers new features of SQL Server 2008 from the perspective of management, developers and a few other aspects. cheers
What are the major differences between Sql Server 2005 and Sql Server 2008?
[ "", "sql", "sql-server", "database", "sql-server-2005", "sql-server-2008", "" ]
I just converted a code snippet from VB.NET to C# and stumbled over this issue. Consider this code: ``` Dim x As Integer = 5 Dim y As Object = x Dim z As Decimal = CType(y, Decimal) ``` No error from compiler or at runtime. z is five. Now let's translate this code to C# ``` int x = 5; object y = x; decimal z = (decimal)y; ``` No error from compiler but at runtime an exception is thrown: ``` Cannot unbox "y" to "decimal" ``` Now my question is, which would be the smartest C# way to do this. Currently my code looks like. ``` int x = 5; object y = x; decimal z = decimal.Parse(y.ToString()); ``` But another solution would be: ``` decimal z = (decimal)(int)y; ``` Which looks a bit confusing, but propably has less overhead than decimal.Parse, I guess.
`(decimal)(int)x` is the right way of doing so if you expect the boxed object to be an integer. Converting to string and parsing is not a good way to attack the problem and incurs some overhead. If you just know the object can be converted to `decimal` in some way, try `System.Convert.ToDecimal` method. It'll handle that for you.
How about: ``` z = Convert.ToDecimal(y); ```
What's the best approach to solve the c# unboxing exception when casting an object to a valuetype?
[ "", "c#", "unboxing", "" ]
Compile the following class ``` class Interface { virtual void doIt() = 0; virtual ~Interface() = 0; }; inline Interface::~Interface() {} ``` using `gcc -fdump-class-hierarchy`. `gcc` emits ``` Class Interface size=4 align=4 base size=4 base align=4 Interface (0x1a779c0) 0 nearly-empty vptr=((& Interface::_ZTV9Interface) + 8u) ``` What is the significance of "nearly-empty"? What does it mean?
The [C++ ABI](http://www.codesourcery.com/public/cxx-abi/abi.html) provides a definition of "nearly empty" classes and an interesting discussion of how they affect vtable construction: > A class that contains a virtual pointer, but no other data except (possibly) virtual bases. In particular, it: > > * has no non-static data members other than zero-width bitfields, > * has no direct base classes that are not either empty, nearly empty, or virtual, > * has at most one non-virtual, nearly empty direct base class, and > * has no proper base class that is empty, not morally virtual, and at an offset other than zero. I ran across this while researching the effect of nearly empty virtual bases on object size, vtable size, and virtual call overhead.
C++ has something called an "empty base optimization". If a class has no members, it doesn't need to take up space when it's used as a base class. An example of why this is important is `std::unary_function<T, U>`. It exists to provide you with an easy set of typedefs. Those typedefs should not contribute to the size of your functor class. If you have a base class with a vtable pointer, this pointer can likely be shared with the derived class. You simply create a vtable for the derived class which adds its own methods after that of the base class. You can now achieve a similar "no extra overhead" base class. Apparently GCC calls that "nearly empty".
What is a "nearly-empty" class?
[ "", "c++", "gcc", "abstract-base-class", "" ]
I'm currently working on a project where I need to save data depending upon the active no. of items. Its like.. Stores can have n no of items which can be dynamically added or reduced from admin back-end. Each item can either be activated or deactivated. NO problem. But I need to manage/save these dynamic n no. of items in a table for each store. I'm not able to decide on the table schema. Any help will be highly appreciated.
I suggest a standard many-to-many relationship using a middle table. So you would use 3 tables: * StoresTable: the list of stores * ItemsTable: the list of items * StoreItemsTable: a list of items-in-stores, each row will have a foreign key to both the stores table and the items table Hope that helps.
your problem is actually not that hard if you use a different approach. A store can have a number of items. So basically Susi's store has 1 item, but suddenly she wants 2, and you would like to add a column. This is very difficult if she suddenly wants to add 2000 items. The best approach would be to use a store table (which has the name of the store, the date it was created and a primary key) and a items table. You can then add items as entries to the table and link them to the store via the stores primary key. An example: ``` Store table: PK Name Owner 1 Sunshine Store Susi 2 Moonstore Harald Item table: PK Name Store_id Price 1 Candle 1 2.44 2 Table 1 51.44 3 Chair 2 6.55 ``` This allows you to add as many items to any store you want. The Store\_id is called a Foreign Key in this example, because it links the items to the store. You can then use SQL commands to select the items, e.g. ``` "Select * from ITEMS where Store_id = 1;" ``` and get all of Susi's items as an answer. Good luck!
How do create table with dynamic no. of columns for data entry
[ "", "sql", "sql-server", "schema", "" ]
I have this list var list = new List { 3, 1, 0, 5 }; I want to swap element 0 with 2 output 0, 1, 3, 5
If you just want it sorted, I'd use List.Sort(). If you want to swap, there is no built in method to do this. It'd be easy to write an extension method, though: ``` static void Swap<T>(this List<T> list, int index1, int index2) { T temp = list[index1]; list[index1] = list[index2]; list[index2] = temp; } ``` You could then do: ``` list.Swap(0,2); ```
Classic swap is... ``` int temp = list[0]; list[0] = list[2]; list[2] = temp; ``` I don't think Linq has any 'swap' functionality if that's what you're looking for.
Swap List<> elements with c# using LINQ
[ "", "c#", "linq", "" ]
As the question's title says, I want to get the system information (like OS name, version, etc.) of a remote system using Java. But before anyone answers this question, I just want to ask whether this is possible, if yes, then how? One more catch is that this should work for both Unix-based and Windows-based systems. I tried searching the Internet, but drew a blank (almost). EDIT: The Java app will be a desktop app, and it will have to credentials to be able to log onto the remote system, but there will be no HTTP/RMI that'll be used.
You need to clarify what you mean by "remote system" in this case - as in how are you communicating with it> Are we talking some form of HTTP? RMI? Applet running in a browser? Generally, however, the answer is "No, it's not possible".
For Windows you should be able to access WMI on the remote machine (with some ugly JNI glue), for UNIX systems I don't know of a way (unless you somehow have shell access, then you can probably try logging in via SSH and do a `uname -a` or similar). It's going to be a lot of work in either case and Java is hardly the right tool for that.
Get System Information of a Remote Machine (Using Java)
[ "", "java", "system-information", "" ]
I'm unable to get the height of a page in javascript when the page is larger than the screen. I thought this would get me the right height: ``` $(document).height(); ``` but that only gets the height of the screen, same as: ``` $('body').height(); ``` same as: ``` document.offsetHeight; ``` For some reason all these examples only return the height of the screen. Can somebody help?
Using jQuery (which you did specify), `$(document).height()` will return exactly what you're asking for. To clarify the usage of the `height()` method: ``` $('.someElement').height(); // returns the calculated pixel height of the element(s) $(window).height(); // returns height of browser viewport $(document).height(); // returns height of HTML document ``` I suspect, that if `$(document).height()` is not working for you, something is wrong. You may be: 1. Calling it too early. Like, before the DOM is ready 2. Have some uncleared floats that are not causing some block level elements to expand to their real height. Thus messing up height calculations. 3. Have something critical absolutely positioned. Absolutely positioned elements do not contribute towards height calculations of their parent elements.
If you're cool with using jQuery, what about getting the body or html height? like: ``` var winHeight = $('body').height(); ```
height of page in javascript
[ "", "javascript", "jquery", "height", "" ]
How do I remove the buttons in a jquery dialog? Per example, I tried re-calling .dialog with the correct new options, but the dialog seems unaffected. $('.selector').dialog('option', 'buttons', {} ); does not work, and nor does it work if actual new button strings and functions are declared. Thoughts?
Buttons cannot be added/set while the dialog is loading.
You are passing new buttons set in a wrong way. Options should be passed as an object. This will work: ``` var options = { buttons: {} }; $(selector).dialog('option', options); ``` No need to destroy and create new dialog. Of course you can also replace buttons object with a new set of buttons if you wish: ``` var options = { buttons: { NewButton: function () { $(this).dialog('close'); // add code here } } }; $(selector).dialog('option', options); ```
jQuery UI dialog - unable to remove buttons
[ "", "javascript", "jquery", "jquery-ui", "" ]
I have a windows form application which needs to be the TopMost. I've set my form to be the TopMost and my application works as I'd like it to except for in one case. There is a 3rd party application (referred to as *player.exe*) that displays SWF movie files on a portion of the screen that popup on top of my application. Using Process Monitor I determined that *player.exe* application calls `flash.exe <PositionX> <PositionY> <Width> <Height> <MovieFile>` in my case: `flash.exe 901 96 379 261 somemovie.swf` Since flash.exe is being spawned in a new process after my form has been set to the TopMost it is appearing on top of my application. First thing I did was make my application minimize the *player.exe* main application window hoping that this would prevent the Flash from appearing also. But, unfortunately it doesn't... even with the window minimized whenever the flash movie starts it shows up at the pixel location (901,96). I then tried creating a timer to keep setting the form.TopMost property to true every 10ms. This sort of works but you still see a very quick blip of the swf file. **Is there some type of Windows API call which can be used to temporarily prevent *player.exe* from spawning child processes which are visible? I admit it sounds a little far fetched. But, curious if anyone else has had a similar problem.** --- ## Addendum: This addendum is to provide a reply to some of the suggestions layed out in Mathew's post below. For the emergency situation described in the comments, I would look at possible solutions along these lines: > 1) How does the third party application normally get started and > stopped? Am I permitted to close it > the same way? If it is a service, the > Service Control Manager can stop it. > If it is a regular application, > sending an escape keystroke (with > SendInput() perhaps) or WM\_CLOSE > message to its main window may work. Easiest way to close the app is to CTRL-ALT-DEL, then kill process. -OR- The proper way is to Hold ESC while clicking the left mouse button... then input your username and password, navigate some menu's to stop the player. There is no PAUSE command... believe it or not. I don't think using WM\_CLOSE will help since minimizing the application doesn't. Would that kill the process also? If not, how do you reopen it. > 2) If I can't close it nicely, am I permitted to kill it? If so, > TerminateProcess() should work. I can't kill the process for two reasons. 1) Upon relaunch you need to supply username/password credentials... There may be a way to get around this since it doesn't prompt when the machine is rebooted but... 2) Whenever I kill the process in task manager **it doesn't die gracefully and asks if you want to send an error report**. > 3) If I absolutely have to leave the other process running, I would try > to see if I can programmatically > invoke fast user switching to take me > to a different session (in which there > will be no competing topmost windows). > I don't know where in the API to start > with this one. (Peter Ruderman > suggests SwitchDesktop() for this > purpose in his answer.) I got really excited by this idea... I found [this article](http://www.codeproject.com/KB/cs/csdesktopswitching.aspx) on CodeProject which provides a lot of the API Wrapper methods. I stopped implementing it because **I think that in order for desktop's to work you must have explorer.exe running (which I do not)**. **EDIT2**: On second thought... maybe explorer.exe isn't needed. I'll give it a try and report back. **Edit3**: Was unable to get the code in that article working. Will have to put this on hold for a moment. --- # Answer Summary As one might have expected, there is no simple answer to this problem. The best solution would be to problematically switch to a different desktop when you need to guarantee nothing will appear over it. I was unable to find a simple C# implementation of desktop switching that worked and I had a looming doubt that I would just be opening a whole new set of worms once it was implemented. Therefore, I decided not to implement the desktop switching. I did find a [C++ Implementation that works well.](http://www.codeproject.com/KB/system/VirtualDesktop.aspx) Please post working C# virtual desktop implementations for others.
Setting the TopMost property (or adding the WS\_EX\_TOPMOST style to a window) does not make it unique in the system. Any number of topmost windows may be created by any number of applications; the only guarantee is that all topmost windows will be drawn 'above' all non-topmost windows. If there are two or more topmost windows, the Z-order still applies. From your description, I suspect that flash.exe is also creating a topmost window. Aside from periodically forcing your window to the top of the Z-order, I think there is little you can do. Be warned, however, that this approach is dangerous: if two or more windows are simultaneously trying to force themselves to the top of the Z-order, the result will be a flickering mess that the user will likely have to use the task manager to escape. I recommend that your program not attempt to meddle with other processes on the computer (unless that is its explicit purpose, e.g. a task manager clone). The computer belongs to the user, and he may not value your program more highly than all others. **Addendum:** For the emergency situation described in the comments, I would look at possible solutions along these lines: 1. How does the third party application normally get started and stopped? Am I permitted to close it the same way? If it is a service, the [Service Control Manager](http://msdn.microsoft.com/en-us/library/ms685150(VS.85).aspx) can stop it. If it is a regular application, sending an escape keystroke (with [SendInput()](http://msdn.microsoft.com/en-us/library/ms646310(VS.85).aspx) perhaps) or [WM\_CLOSE](http://msdn.microsoft.com/en-us/library/ms632617(VS.85).aspx) message to its main window may work. 2. If I can't close it nicely, am I permitted to kill it? If so, [TerminateProcess()](http://msdn.microsoft.com/en-us/library/ms686714(VS.85).aspx) should work. 3. If I absolutely have to leave the other process running, I would try to see if I can programmatically invoke fast user switching to take me to a different session (in which there will be no competing topmost windows). I don't know where in the API to start with this one. (Peter Ruderman suggests [SwitchDesktop()](http://msdn.microsoft.com/en-us/library/ms686347(VS.85).aspx) for this purpose in his answer.)
You can use the [Process class](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx) to start flash.exe directly - and use an appropriate [ProcessStartInfo](http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.aspx) settings to show the window in a hidden state - or with a WindowStyle of hidden or minimized. You could also consider using the [SetWindowsHookEx](http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx) API to intercept the process start API calls, and when the process is flash.exe run some code to restore you window to top-most status.
Prevent Process 'A' from spawning Process 'B' which then shows up on top of what should be the "TopMost" Process 'C'
[ "", "c#", "windows", "winforms", "winapi", "always-on-top", "" ]
I'm currently trying to implement something that combines reverse engineering and graph theory. Therefore I'd like to disassemble PE binaries. There're some very sophisticated tools to do so, like IDA or w32dasm. Latter seems to be dead. IDA is not scriptable - as far as I know. The reason why I want a scriptable disassembler is, that I implement my program in C#. It gets a binary, and therefore it has to get the opcode somehow. I think I need to call some helping program with arguments. IDA cannot be called without GUI. It doesn't offer real cmdline options. Any ideas? Thanks, wishi
[dumpbin /disasm](<http://msdn.microsoft.com/en-us/library/xtf7fdaz(VS.71).aspx)> should do the trick. You could also script CDB to do it.
IDA has a built-in scripting language called IDC. Lots of examples [here](http://www.openrce.org/downloads/browse/IDA_Scripts). Also, IDA **can** be called without a GUI - consult the documentation for idaw.exe.
Scriptable Windows Disassembler [non cygwin]
[ "", "c#", "reverse-engineering", "portable-executable", "" ]
In the following JavaScript code there is a dollar (`$`) sign. What does it mean? ``` $(window).bind('load', function() { $('img.protect').protectImage(); }); ```
Your snippet of code looks like it's referencing methods from one of the popular JavaScript libraries (jQuery, ProtoType, mooTools, and so on). There's nothing mysterious about the use of `$` in JavaScript. `$` is simply a valid JavaScript identifier. JavaScript allows upper- and lower-case letters (in a wide variety of scripts, not just English), numbers (but not at the first character), `$`, `_`, and others.¹ Prototype, jQuery, and most javascript libraries use the `$` as the primary base object (or function). Most of them also have a way to relinquish the `$` so that it can be used with another library that uses it. In that case you use `jQuery` instead of `$`. In fact, `$` is just a shortcut for `jQuery`. --- ¹ For the first character of an identifier, JavaScript allows *"...any Unicode code point with the Unicode property “ID\_Start”..."* plus `$` and `_`; details in [the specification](https://tc39.es/ecma262/multipage/ecmascript-language-lexical-grammar.html#prod-IdentifierStartChar). For subsequent characters in an identifier, [it allows](https://tc39.es/ecma262/multipage/ecmascript-language-lexical-grammar.html#prod-IdentifierPartChar) anything with `ID_Continue` (which includes `_`) and `$` (and a couple of control characters for historical compatibility).
From [another answer](https://stackoverflow.com/questions/1122690/jquery-and-questions/1122740#1122740): **A little history** Remember, there is nothing inherently special about `$`. It is a variable name just like any other. In earlier days, people used to write code using document.getElementById. Because JavaScript is case-sensitive, it was normal to make a mistake while writing `document.getElementById`. Should I capital `'b'` of `'by'`? Should I capital `'i'` of `Id?` You get the drift. Because functions are first-class citizens in JavaScript, you can always do this: ``` var $ = document.getElementById; //freedom from document.getElementById! ``` When Prototype library arrived, they named their function, which gets the DOM elements, as `'$'`. Almost all the JavaScript libraries copied this idea. Prototype also introduced a `$$` function to select elements using CSS selector. jQuery also adapted `$` function but expanded to make it accept all kinds of 'selectors' to get the elements you want. Now, if you are already using Prototype in your project and wanted to include jQuery, you will be in problem as `'$'` could either refer to Prototype's implementation OR jQuery's implementation. That's why jQuery has the option of noConflict so that you can include jQuery in your project which uses Prototype and slowly migrate your code. I think this was a brilliant move on John's part! :)
What is the meaning of "$" sign in JavaScript
[ "", "javascript", "" ]
What would be the most efficient way to instanciate an object according to a generic type passed to a Factory class, for instance: ``` public class LoggerFactory { public static ILogger<T> Create<T>() { // Switch Statement? // Generic Dictionary? // EX.: if "T" is of type "string": return (ILogger<T>)new StringLogger(); } } ``` How would you do it? Which *branching statement*? etc...
I think it's best to keep it simple, perhaps something like this: ``` public static class LoggerFactory { static readonly Dictionary<Type, Type> loggers = new Dictionary<Type, Type>(); public static void AddLoggerProvider<T, TLogger>() where TLogger : ILogger<T>, new() { loggers.Add(typeof(T), typeof(TLogger)); } public static ILogger<T> CreateLogger<T>() { //implement some error checking here Type tLogger = loggers[typeof(T)]; ILogger<T> logger = (ILogger<T>) Activator.CreateInstance(tLogger); return logger; } } ``` You just call the `AddLoggerProvider` for each type you want to support, can be extended at runtime, it ensures you definetly add an implementation of the interface to the library and not some object, isn't very fast because of the `Activator`, but creating a logger wont likely be a bottleneck anyway. Hope it looks okay. Usage: ``` // initialize somewhere LoggerFactory.AddLoggerProvider<String, StringLogger>(); LoggerFactory.AddLoggerProvider<Exception, ExceptionLogger>(); // etc.. ILogger<string> stringLogger = LoggerFactory.CreateLogger<string>(); ``` Note: each `ILogger<T>` requires a parameterless constructor for the `Activator`, but that too is ensured with the `new()` generic constraint in the add method.
I think I'd do it like this: ``` public class LoggerFactory<T> { private static Dictionary<Type, Func<ILogger<T>>> LoggerMap = new Dictionary<Type, Func<ILogger<T>>> { { typeof(string), () => new StringILogger() as ILogger<T> }, { typeof(StringWriter), () => new StringWriterILogger() as ILogger<T> } }; public static ILogger<T> CreateLogger() { return LoggerMap[typeof(T)](); } } ``` You pay something of a readability price (all those angle brackets, sheesh), but as you can see it makes for very little program logic.
Factory Creating Objects According to a Generic Type C#
[ "", "c#", "generics", "interface", "factory", "" ]
I have a simple XSD: ``` <xs:element name="config"> <xs:complexType> <xs:sequence minOccurs="1" maxOccurs="unbounded"> <xs:element name="group" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> ``` On my xml file i put this: ``` <config> <group></group> <a></a> </config> ``` How block the insertion of `<a>` tag on my xml? **Obs: group appears on auto-complete on my C# xml editor!!!**
Problem Resolved!! Is a error on my **Visual Studio Express Edition** The Visual Studio 2008 (Full Version) process XSD correctly!! Thanks for all!!
You cannot "block" the insertion of the `<a>` unless you write a XML editor yourself which would understand and interpret the XSD schema on the fly. What you can do is validate the XML created against the schema and refuse it, if it's not valid. Marc
block invalid elements XSD?
[ "", "c#", "xsd", "" ]
Javascript is an incredible language and libraries like jQuery make it almost too easy to use. What should the original designers of Javascript have included in the language, or what should we be pressuring them into adding to future versions? Things I'd like to see:- * Some kind of compiled version of the language, so we programmers can catch more of our errors earlier, as well as providing a faster solution for browsers to consume. * optional strict types (eg, being able to declare a var as a float and keep it that way). I am no expert on Javascript, so maybe these already exist, but what else should be there? Are there any killer features of other programming languages that you would love to see?
Read [Javascript: The Good Parts](https://rads.stackoverflow.com/amzn/click/com/0596517742) from the author of [JSLint](http://www.jslint.com/), Douglas Crockford. It's really impressive, and covers the bad parts too.
One thing I've always longed for and ached for is some **support for hashing**. Specifically, let me track metadata about an object *without needing to add an expando property on that object*. Java provides **`Object.getHashCode()`** which, by default, uses the underlying memory address; Python provides **`id(obj)`** to get the memory address and **`hash(obj)`** to be customizable; etc. Javascript provides nothing for either. For example, I'm writing a Javascript library that tries to unobtrusively and gracefully enhance some objects you give me (e.g. your <li> elements, or even something unrelated to the DOM). Let's say I need to process each object exactly once. So after I've processed each object, I need a way to "mark it" as seen. Ideally, I could make my own hashtable or set (either way, implemented as a dictionary) to keep track: ``` var processed = {}; function process(obj) { var key = obj.getHashCode(); if (processed[key]) { return; // already seen } // process the object... processed[key] = true; } ``` But since that's not an option, I have to resort to adding a property onto each object: ``` var SEEN_PROP = "__seen__"; function process(obj) { if (obj[SEEN_PROP]) { // or simply obj.__seen__ return; // already seen } // process the object... obj[SEEN_PROP] = true; // or obj.__seen__ = true } ``` But *these objects aren't mine*, so this makes my script obtrusive. The technique is effectively a hack to work around the fact that I can't get a reliable hash key for any arbitrary object. Another workaround is to create wrapper objects for everything, but often you need a way to go from the original object to the wrapper object, which requires an expando property on the original object anyway. Plus, that creates a circular reference which causes memory leaks in IE if the original object is a DOM element, so this isn't a safe cross-browser technique. For developers of Javascript libraries, this is a recurring issue.
What is Javascript missing?
[ "", "javascript", "programming-languages", "" ]
Have seen this comment in a method: ``` //I wonder why Sun made input and output streams implement Closeable and left Socket behind ``` It would prevent creation of wrapper anonymous inner class which implements Closeable which delegates its close method to an instance of Socket.
Closeable was introduced in Java5 whereas Socket was introduced in JDK 1.0. In [Java7 Socket will be Closeable](http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html). EDIT You can use reflection in order to close any "closeable" object in Java 4/5/6 simply by testing the presence of a close method. Using this technique allow you to close, say, a ResultSet (that has a close() method but doesn't implements Closeable): ``` public static universalClose(Object o) { try { o.getClass().getMethod("close", null).invoke(o, null); } catch (Exception e) { throw new IllegalArgumentException("missing close() method"); } } ```
> public interface Closeable > > A Closeable is a source or destination of data > that can be closed. The close method > is invoked to release resources that > the object is holding (such as open > files). I think this is because the socket itself isn't a source or destination of data, but they are the inputstream/outputstream associated with the socket.
Why InputStream and OutputStream implement Closeable and Socket doesn't?
[ "", "java", "interface", "" ]
I need to take a variable that contains a URL, and check to see if the domain equals a certain domain, if it does, echo one variable, if not, echo another. ``` $domain = "http://www.google.com/docs"; if ($domain == google.com) { echo "yes"; } else { echo "no"; } ``` Im not sure how to write the second line where it checks the domain to see if $domain contains the url in the if statement.
This is done by using [`parse_url`](http://www.php.net/parse_url): ``` $host = parse_url($domain, PHP_URL_HOST); if($host == 'www.google.com') { // do something } ```
Slightly more advanced domain-finding function. ``` $address = "http://www.google.com/apis/jquery"; if (get_domain($address) == "google.com") { print "Yes."; } function get_domain($url) { $pieces = parse_url($url); $domain = isset($pieces['host']) ? $pieces['host'] : ''; if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) { return $regs['domain']; } return false; } ```
php check if domain equals value, then perform action
[ "", "php", "" ]
I'm having some trouble compiling/linking a set of classes, several of them dealing with a common global variable. Basically, I declare and define a extern variable foo in class A and access/update it in classes B and C. The relevant code looks like this: A.h ``` extern string foo; // declare it <=== compiler error "storage class specified for foo" ``` B.cpp ``` include A.h string foo; // define it main () { ... foo = "abc"; } ``` C.cpp ``` include A.h cout << foo; // print it ``` My current error is "storage class specified for foo". But, I'm wondering if this is the correct approach. Should I be using a static variable? Any help much appreciated, as I've been on this for at least an hour by now.
In A.h have you actually got the extern declaration within the actual class A? Your question currently says this in words but then your code snippet suggests it is at file level. The only way I can get the error you are talking about i.e. "storage class specified for foo" is for the following in A.h: ``` class A { public: extern std::string foo; }; ``` Perhaps this is your problem? Edit: Looking at your own answer I think this is what you've done. You want to replace `extern` with `static` and then define that static in A.cpp with a line like ``` std::string A::foo; ``` You can then subsequently access it in other places as `A::foo` eg. ``` std::cout << A::foo; ```
Since your error is on the extern, I'm guessing it doesn't know what the type is. Have you included string? `#include <string>` And if so, you need to put `std::` before it: ``` #include <string> extern std::string foo; ``` Side note, make sure you don't use any `using` directives (`using namespace std` or `using std::string`) in your header file, because then you force everyone who sues your header file to do the same, which is bad practice. ## Edit > ...but that's how I have it coded. Are you sure? I just tried this and it works completely fine in both VC++ and g++: ### A.h ``` #include <string> extern std::string foo; ``` ### B.cpp ``` #include "A.h" std::string foo; int main (void) { foo = "abc"; } ``` ### C.cpp ``` #include "A.h" #include <iostream> int some_function(void) { std::cout << foo << std::endl; } ``` Try that out and see if it works.
How to construct a static global variable in C++
[ "", "c++", "global-variables", "" ]
Hi I got the code from a book: ``` public class Container { Map<String, Object> components; public Container() { components = new HashMap<String, Object>(); Properties properties = new Properties(); try { properties.load(new FileInputStream("components.properties")); for (Map.Entry entry : properties.entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); processEntry(key, value); } } catch (Exception ex) { throw new RuntimeException(); } } private void processEntry(String key, String value) throws Exception { String parts[] = key.split("\\."); if (parts.length == 1) { Object component = Class.forName(value).newInstance(); components.put(parts[0], component); } else { Object component = components.get(parts[0]); Object reference = components.get(value); PropertyUtils.setProperty(component, parts[1], reference); } } public Object getComponent(String id) { return components.get(id); } } ``` My question is, on the line ``` PropertyUtils.setProperty(component, parts[1], reference); ``` The object's property in the Map is changed. Even though after the property is updated there's no component.put() to update the object inside the map, the object is updated. Why is that?
It's because the map only contains a *reference* to the object - not a copy of the object. When you change something in the object, you can see that change however you get to it - whether it's via the reference in the map or not. This is exactly the same as doing (say): ``` StringBuilder first = new StringBuilder(); StringBuilder second = first; first.append("Hello"); System.out.println(second); // Prints "Hello" ``` Here both `first` and `second` are references to the same `StringBuilder` object... when you change the contents of that object via `first.append()`, that change is still visible when you look at the object via the `second` reference in the subsequent line.
In java every object is a reference to an object. So if you put an object in a map, only the reference is stored and not a copy of the object. Hence each update to objects in a map will be seen when looking it up from the map. Because you will get a reference to the same object when retrieving it from the map.
Object's property is changed in the Map even without using put()?
[ "", "java", "dependency-injection", "inversion-of-control", "" ]
My program is ICAPServer (similar with httpserver), it's main job is to receive data from clients and save the data to DB. There are two main steps and two threads: 1. ICAPServer receives data from clients, puts the data in a queue (50kb <1ms); 2. another thread pops data from the queue, and writes them to DB SO, if 2nd step is too slow, the queue will fill up memory with those data. Wondering if anyone have any suggestion...
One note: before going for optimizations, it is very important to get some good measurement, and profiling. That said, I would bet the slow part in the second step is database communication; you could try to analyze the SQL statement and its execution plan. and then optimize it (it is one of the [features](http://www.sqlalchemy.org/features.html) of SQLAlchemy); if still it would be too slow, check about database optimizations. Of course, it is possible the bottleneck would be in a completely different place; in this case, you still have chances to optimize using C code, dedicated network, or more threads - just to give three possible example of completely different kind of optimizations. Another point: as I/O operations usually release the GIL, you could also try to improve performance just by adding another reader thread - and I think this could be a much cheaper solution.
It is hard to say for sure, but perhaps using two processes instead of threads will help in this situation. Since Python has the Global Interpreter Lock (GIL), it has the effect of only allowing any one thread to execute Python instructions at any time. Having a system designed around processes might have the following advantages: * Higher concurrency, especially on multiprocessor machines * Greater throughput, since you can probably spawn multiple queue consumers / DB writer processes to spread out the work. Although, the impact of this might be minimal if it is really the DB that is the bottleneck and not the process writing to the DB.
python program choice
[ "", "python", "sqlalchemy", "twisted", "" ]
How to find out the content between two words or two sets of random characters? The scraped page is not guaranteed to be Html only and the important data can be inside a javascript block. So, I can't remove the JavaScript. consider this: ``` <html> <body> <div>StartYYYY "Extract HTML", ENDYYYY </body> Some Java Scripts code STARTXXXX "Extract JS Code" ENDXXXX. </html> ``` So as you see the html markup may not be complete. I can fetch the page, and then without worrying about anything, I want to find the content called "Extract the name" and "Extract the data here in a JavaScript". What I am looking for is in python: Like this: ``` data = FindBetweenText(UniqueTextBeforeContent, UniqueTextAfterContent, page) ``` Where page is downloaded and data would have the text I am looking for. I rather stay away from regEx as some of the cases can be too complex for RegEx.
Here's my attempt, this is tested. While recursive, there should be no unnecessary string duplication, although a generator might be more optimal ``` def bracketed_find(s, start, end, startat=0): startloc=s.find(start, startat) if startloc==-1: return [] endloc=s.find(end, startloc+len(start)) if endloc == -1: return [s[startloc+len(start):]] return [s[startloc+len(start):endloc]] + bracketed_find(s, start, end, endloc+len(end)) ``` and here is a generator version ``` def bracketed_find(s, start, end, startat=0): startloc=s.find(start, startat) if startloc==-1: return endloc=s.find(end, startloc+len(start)) if endloc == -1: yield s[startloc+len(start):] return else: yield s[startloc+len(start):endloc] for found in bracketed_find(s, start, end, endloc+len(end)): yield found ```
if you are sure your markers are unique, do something like this ``` s=""" <html> <body> <div>StartYYYY "Extract HTML", ENDYYYY </body> Some Java Scripts code STARTXXXX "Extract JS Code" ENDXXXX. </html> """ def FindBetweenText(startMarker, endMarker, text): startPos = text.find(startMarker) if startPos < 0: return endPos = text.find(endMarker) if endPos < 0: return return text[startPos+len(startMarker):endPos] print FindBetweenText('STARTXXXX', 'ENDXXXX', s) ```
Finding content between two words withou RegEx, BeautifulSoup, lXml ... etc
[ "", "python", "screen-scraping", "fetch", "" ]
I have this code: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>sss</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script type='text/javascript'> function isAlphabet(obj){ var alphaExp = /[^a-z0-9_-]+/; if(!obj.value.match(alphaExp)){ return true; } else{ alert('the bad symbols'); obj.focus(); return false; } } </script> </head> <body> <form action="/"> <input type='text' id='letters' onblur="isAlphabet(this)"/> </form> </body> </html> ``` --- And I want to show an `Alert()` displaying only those characters for which validation fails. For example : If an input contains symbols like " #abc " , the Alert Message should show only "#". How can this be done?
Here's a simple way to do it... it's not be the most efficient though: ``` function isAlphabet(obj) { var val = obj.value; var alphaExp = /[^a-z0-9_-]+/; var valid = true; var badchars = ""; for( a = 0; a < val.length; a++ ) { if(val[a].match(alphaExp)) { badchars += "," + val[a]; valid = false; } } if( !valid ) { alert("The following characters are not allowed: " + badchars.substr(1)); obj.focus(); } return valid; } ```
Use a regular expression which matches the allowed characters to get a string where those are removed. If the string contains anything, the validation fails: ``` function isAlphabet(obj) { var alphaExp = /[a-z0-9_-]+/g; var illegal = obj.value.replace(alphaExp, ''); if (illegal.length){ alert('Input contains the characters '+illegal+' which are not allowed.'); obj.focus(); return false; } else { return true; } } ```
Validation, javascript
[ "", "javascript", "validation", "" ]
We've got a winforms LOB application, which under normal circumstances should be started from a launcher that should do basic version checks and download any updated components, before spawning the main process. One problem we're seeing is that some members of staff have found it loads faster by not running the update application, however this can lead to people not having the latest features and causes all manner of headache to support. What I'd like to be able to do is to throw up a warning if they haven't gone in through the initialise application. Ideally, I'd like to be able to do this without having to change the update application (as that means going and installing a new MSI on each client), and the approach that springs out is to find some way of finding information about the process that started "me" and check against a white/black list, forever I can't seem to find a way to do this? --- *Aside:* Of course, if I did resort to changing the update application, I'd probably change it to either pass a pre-shared secret as a command line argument, or better still, change the application such that I could just load it as a class library and instantiate the relevant class via reflection. ClickOnce has been ruled out as it [does not support being installed for multiple users](http://msdn.microsoft.com/en-us/library/142dbbz4.aspx)
See here: [How to get parent process in .NET in managed way](https://stackoverflow.com/questions/394816/how-to-get-parent-process-in-net-in-managed-way) From the link: ``` using System.Diagnostics; PerformanceCounter pc = new PerformanceCounter("Process", "Creating Process ID", Process.GetCurrentProcess().ProcessName); return Process.GetProcessById((int)pc.NextValue()); ``` [Edit: Also see the [System.Diagnostics FAQ](http://msdn.microsoft.com/en-us/netframework/aa569609.aspx#Question3) for some more information about this. Thanks to Justin for the link.]
I find if your process - which I assume you have control over - checks its version number vs the latest released version number (placed somewhere central db/ftp wherever u look for the update) , then you have all that logic in one place. I think that would be a simpler solution.
How do I discover how my process was started
[ "", "c#", ".net", "" ]
I have `$_SERVER['HTTP_REFERER']` — pretend it is <http://example.com/i/like/turtles.html>. What would I need to do to get just the `http://example.com` part out of the string, and store it in its own variable?
In this example, the best solution would be to use PHP's [`parse_url` method](http://www.php.net/manual/en/function.parse-url.php). This splits up the URL into an associative array. You would then build your final value by combining the `scheme` with the `host`: ``` if ( $parts = parse_url( "http://example.com/i/like/turtles.html" ) ) { echo $parts[ "scheme" ] . "://" . $parts[ "host" ]; } ```
I'd use [parse\_url](http://php.net/manual/en/function.parse-url.php) in the following way... ``` if ($urlParts = parse_url($myURI)) $baseUrl = $urlParts["scheme"] . "://" . $urlParts["host"]; ```
Extract Scheme and Host from HTTP_REFERER
[ "", "php", "string", "" ]
I'm trying to create a simple image gallery, showing 16 images per page. I'm using LIMIT 16 to display the correct amount on the page, but if there are more than 16 rows, I want to have links at the bottom, allowing the user to navigate to the next page. I know I could achieve the desired result by removing the limit and simply using a loop to display the first 16 items, but this would be inefficient. Obviously, COUNTING the number of rows would always = 16. ``` $sql .= "posts p, images im, postimages pi WHERE i.active = 1 AND pi.post_id = p.id AND pi.image_id = im.image_id ORDER BY created_at LIMIT 16"; ``` Can anyone suggest a more efficient way of doing it? Thanks
You need to offset your results for the given page you are on in addition to the separate query for getting the count that everyone else has mentioned. ``` $sql .= "posts p, images im, postimages pi WHERE i.active = 1 AND pi.post_id = p.id AND pi.image_id = im.image_id ORDER BY created_at LIMIT ". ($page - 1) * $pagesize .", ". $pagesize; ``` The normal warnings about SQL injection would apply here.
In `MySQL`: ``` SELECT SQL_CALC_FOUND_ROWS * FROM posts p, images im, postimages pi WHERE i.active = 1 AND pi.post_id = p.id AND pi.image_id = im.image_id ORDER BY created_at LIMIT 16; SELECT FOUND_ROWS(); ``` The first query will return `16` rows, and the second query will return you the number of rows which would be returned be there no `LIMIT` clause in the first query. You may use it to decide whether to show the "next" link or not.
SQL Count total number of rows whilst using LIMIT
[ "", "sql", "count", "limit", "" ]
I have a `<select>` list, which has been populated with several options, but want to remove those options to start again. I am using jQuery and have tried the following: ``` $("#selectId").length = 0; ``` But this seems to have no effect. Part of my problem is that I am using Firebug to debug the JavaScript, but the debugger does not break at the breakpoint, so I cannot see what is going on. Should it break when the JavaScript is within the `<head>` of my HTML file?
this would do: ``` $('#selectId').html(''); ```
This works too. ``` $("#selectId option").remove(); ```
jQuery select list removes all options
[ "", "javascript", "jquery", "select", "firebug", "" ]
I have the following class subclass of FilterInputStream with only one method overrided. However the performance of this class is so poor. It performs at 1/10 the speed of its superclass. I even took the same source code from InputStream of javasrc and used it in my subclass. Same performance hit. Is there something wrong with overriding classes? ``` public class NewLineStream extends FilterInputStream { public NewLineStream(InputStream in) { super(in); } public int read(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException (); } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException (); } else if (len == 0) { return 0; } int c = read(); if (c == -1) { return -1; } b[off] = (byte)c; int i = 1; try { for (; i < len ; i++) { c = read(); if (c == -1) { break; } if (b != null) { b[off + i] = (byte)c; } } } catch (IOException ee) { } return i; } ``` }
This method is reading byte-by-byte, I guess that's why it performs so poorly. FilterInputStreams usually are just wrapping other input streams, so if you're not going to do any filtering, just call read(byte[], int, int) on the wrapped stream.
Most of the time when developers feel they have found a bug in the JDK or how Java works, its usually just a misunderstand on the part of the developer. Java is more than ten years and most common bugs have been solved already. There more than few bad design decisions lying around which are perhaps too difficult to fix now but I cannot think of any which impacts performance or doesn't have a known work around.
Poor performance by overriding Java class?
[ "", "java", "file-io", "performance", "" ]
Sometimes, when I look through my header files I'd like to add something little to the (doxygen) documentation. That might be a quick note about the use of some function parameter, or just fixing a little typo. But then I think: Oh no, that'll trigger a recompile on the next `make` call! And for certain basic headers the whole project would recompile, which can take a long time. So, nevermind! Is there a solution to this dilemma? Are there approaches where the functions/classes are documented not directly in the headers? Or are there (plans for) a smart `make` that would notice that only some comment has changed, but no recompilation is necessary?
How about checking out (you do version control, don't you?) *another* copy of the codebase in a different directory, just for these kinds of edits? It can be a separate branch, or not. Then, when these kinds of small changes occur to you, you just make them here. You can commit them directly: now they are in a safe place, and won't disturb your actual development. Every once in a while, like once a week if your build times really are that long, you can merge these changes to what you are working on. Merge conflicts should rarely occur, as long as you document in one directory and write code in the other.
You could shorten the compile times using [ccache](http://ccache.samba.org/), possibly with the `CCACHE_UNIFY` environment option set. ccache hashes the pre-processor output, and serves the previously compiled object if no changes were detected. Man page section about CCACHE\_UNIFY > **`CCACHE_UNIFY`** > > If you set the environment variable `CCACHE_UNIFY` then ccache > will use the C/C++ unifier when hashing the pre-processor output > if -g is not used in the compile. The unifier is slower than a > normal hash, so setting this environment variable loses a little > bit of speed, but it means that ccache can take advantage of not > recompiling when the changes to the source code consist of > reformatting only. Note that using `CCACHE_UNIFY` changes the > hash, so cached compiles with `CCACHE_UNIFY` set cannot be used > when `CCACHE_UNIFY` is not set and vice versa. The reason the unifier > is off by default is that it can give incorrect line number > information in compiler warning messages.
Just adding some documentation triggers recompilation: Is there a solution?
[ "", "c++", "documentation", "makefile", "header", "" ]
Is there a way to make this faster? ``` while ($item = current($data)) { echo '<ATTR>',$item, '</ATTR>', "\n"; next($data); } ``` I do not like that I need to create new variables like $item.
``` <?php $transport = array('foot', 'bike', 'car', 'plane'); foreach ($transport as $value) { echo $value; } ?> ```
I do a little bench to comprobe it. ``` <?php $a = array(); for ($i = 0; $i < 100000; $i++) { $a[] = $i; } $start = microtime(true); foreach ($a as $k => $v) { $a[$k] = $a[$k] + 1; } echo "foreach : ", microtime(true) - $start, " Seconds\n"; $start = microtime(true); foreach ($a as $k => &$v) { $v = $v + 1; } echo "foreach with cursor : ", microtime(true) - $start, " Seconds\n"; $start = microtime(true); for ($i = 0; $i < count($a); ++$i) { $a[$i] = $a[$i] + 1; } echo "for : ", microtime(true) - $start, " Seconds\n"; $start = microtime(true); for ($i=0,$l=count($a);$i<$l;++$i) { $a[$i] = $a[$i] + 1; } echo "for with cached count : ", microtime(true) - $start, " Seconds\n"; ``` With results ``` foreach : 0.0039410591125488 Seconds foreach with cursor : 0.00357985496521 Seconds for : 0.0022602081298828 Seconds for with cached count : 0.0020480155944824 Seconds ``` Hope this helps
How to make array loop faster in PHP
[ "", "php", "" ]
I am considering the problem of validating real numbers of various formats, because this is very similar to a problem I am facing in design. Real numbers may come in different combinations of formats, for example: 1. with/without sign at the front 2. with/without a decimal point (if no decimal point, then perhaps number of decimals can be agreed beforehand) 3. base 10 or base 16 We need to allow for each combination, so there are 2x2x2=8 combinations. You can see that the complexity increases exponentially with each new condition imposed. In OO design, you would normally allocate a class for each number format (e.g. in this case, we have 8 classes), and each class would have a separate validation function. However, with each new condition, you have to double the number of classes required and it soon becomes a nightmare. In procedural programming, you use 3 flags (i.e. has\_sign, has\_decimal\_point and number\_base) to identify the property of the real number you are validating. You have a single function for validation. In there, you would use the flags to control its behaviour. ``` // This is part of the validation function ``` if (has\_sign) check\_sign(); for (int i = 0; i < len; i++) { if (has\_decimal\_point) // Check if number[i] is '.' and do something if it is. If not, continue ``` if (number_base = BASE10) // number[i] must be between 0-9 else if (number_base = BASE16) // number[i] must be between 0-9, A-F ``` } Again, the complexity soon gets out of hand as the function becomes cluttered with if statements and flags. **I am sure that you have come across design problems of this nature before - a number of independent differences which result in difference in behaviour. I would be very interested to hear how have you been able to implement a solution without making the code completely unmaintainable.** Would something like the bridge pattern have helped?
> In OO design, you would normally > allocate a class for each number > format (e.g. in this case, we have 8 > classes), and each class would have a > separate validation function. No no no no no. At most, you'd have a type for representing *Numeric Input* (in case `String` doesn't make it); another one for *Real Number* (in most languages you'd pick a built-in type, but anyway); and a *Parser* class, which has the knowledge to take a Numeric Input and transform it into a Real Number. To be more general, one difference of behaviour in and by itself doesn't automatically map to one class. It can just be a property inside a class. Most importantly, behaviours should be treated orthogonally. If (imagining that you write your own parser) you may have a sign or not, a decimal point or not, and hex or not, you have three **independent sources of complexity** and it would be ok to find three pieces of code, somewhere, that treat one of these issues each; but it would not be ok to find, anywhere, 2^3 = 8 different pieces of code that treat the different combinations in an explicit way. Imagine that add a new choice: suddenly, you remember that numbers might have an "e" (such as 2.34e10) and want to be able to support that. With the orthogonal strategy, you'll have **one more independent source of complexity**, the fourth one. With your strategy, the 8 cases would suddenly become 16! Clearly a no-no.
I don't know why you think that the OO solution would involve a class for each number pattern. My OO solution would be to use a regular expression class. And if I was being procedural, I would probably use the standard library strtod() function.
How do I handle combinations of behaviours?
[ "", "c++", "oop", "software-design", "procedural-programming", "" ]
I use ivy with the ivy eclipse plugin to download dependencies. Works great. But how can I attach the source code for those libraries, in order to step into these libraries?
Have you tried attaching the source configurations? ``` <dependencies defaultconfmapping="*->default,sources"> ```
There is an [ant task](http://code.google.com/p/ivy-eclipse/) that will modify the .classpath file to reference the source attachments.
How to attach source code of libraries downloaded with ivy
[ "", "java", "eclipse", "ivy", "ivyde", "" ]
I've coded some algorithms in Java and I need to include those algorithms in my web application. I'm using Apache Tomcat and what I need to do is that when, for example, I click on the start button on my web page a Java class should be executed. I think this done by using servlets, am I right? If so, do you know where I can find some literature about it? I've searching in internet but it's a little bit confusing for me.
Yes, you're right. You'd want to write a servlet that handles request to an URI. Here's some introduction: * <http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/servlet.html> Tomcat comes with some samples, you might look at the source code as a start, they should be in the webapps/sample directory. The Tomcat documentation is also a good start. * <http://tomcat.apache.org/tomcat-6.0-doc>
I would check out this [introduction to servlets](http://www.webdevelopersjournal.com/articles/intro_to_servlets.html) A servlet receives an HTTP request (e.g. a request for a page etc.). It will process that request via the methods `doGet()` or `doPost()`, and return an HTTP response. That response will contain your results (most likely an HTML page, although that's not mandatory). I would (in order) 1. get a static 'hello world' page going 2. get a static page returning some data from your libraries 3. get a dynamic page returning some data from your libraries using data from the HTTP request Integrating your library will be trivial, since a servlet is simply a Java class that can instantiate/call on any other Java class.
Apache Tomcat executing a Java class
[ "", "java", "apache", "tomcat", "servlets", "" ]
I have a socket server, written in C++ using boost::asio, and I'm sending data to a client. The server sends the data out in chunks, and the client parses each chunk as it receives it. Both are pretty much single threaded right now. What design should I use on the server to ensure that the server is just writing out the data as fast as it can and never waiting on the client to parse it? I imagine I need to do something asynchronous on the server. I imagine changes could be made on the client to accomplish this too, but ideally the server should not wait on the client regardless of how the client is written. I'm writing data to the socket like this: ``` size_t bytesWritten = m_Socket.Write( boost::asio::buffer(buffer, bufferSize)); ``` Update: I am going to try using Boost's mechanism to write asynchronously to the socket. See <http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio/tutorial/tutdaytime3/src.html> e.g. ``` boost::asio::async_write(socket_, boost::asio::buffer(message_), boost::bind(&tcp_connection::handle_write, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); ``` * Alex
If you set your socket to non-blocking, then writes should fail if they would otherwise block. You can then queue up the data however you like, and arrange for another attempt to be made later to write it. I don't know how to set socket options in the boost socket API, but that's what you're looking for. But this is probably more trouble than it's worth. You'd need to select a socket that's ready for writing, presumably from several open simultaneously, shove more data into it until it's full, and repeat. I don't know if the boost sockets API has an equivalent of `select`, so that you can wait on multiple sockets at once until any of them is ready to write. The reason that servers typically start a thread (or spawn a process) per client connection is precisely so that they can get on with serving other clients while they're waiting on I/O, while avoiding implementing their own queues. The simplest way to "arrange for another attempt later" is just to do blocking I/O in a dedicated thread. What you can't do, unless boost has done something unusual in its sockets API, is require the OS or the sockets library to queue up arbitrary amounts of data for you without blocking. There may be an async API which will call you back when the data is written.
You can ensure asynchronous communication by transporting the data not over TCP but over UDP. However, if you need to use TCP, let the client store the data away quickly and process it in a different thread or asynchronously with a cron job.
Sockets: How to send data to the client without 'waiting' on them as they receive/parse it
[ "", "c++", "sockets", "asynchronous", "boost-asio", "" ]
I'm doing some research in how to implement a event-handling scheme in C++ that can be easyest as its to implements an adpter to a class in java. The problem is that with the approach shown below, I will need to have all adapters already implemented with its function overriding in the devived class (because the linker needs it). On the other side, using a delegate strategy where I can use the adapter just in the derived class should imply in less performance considering the way it need to be implemented. wich one, or what on else should be the best approach to it? ``` class KeyboardAdapter { public: virtual void onKeyDown(int key) = 0; } class Controller : public KeyApadter { private: void onKeyDown(int key); } void Controller::onKeyDown(int key) {} class UserController : public Controller { private: void onKeyDown(int key); } void UserController::onKeyDown(int key) { // do stuff } int main() { UserController * uc = new UserController(); Controller * c = uc; c->_onKeyDown(27); } ```
Take a look at Boost.Signals library for an example of how you can implement event handling without classes with virtual functions (<http://www.boost.org/doc/libs/1_39_0/doc/html/signals.html>).
Given that your code appears to be handling keystrokes from the user, and given that nobody types faster than, say, 100-150 words per minute, I wouldn't worry too much about efficiency. Just do it the way that makes the most sense to you.
Best aproach to java like adapters event-handling in C++
[ "", "c++", "interface", "event-handling", "delegates", "adapter", "" ]
The following code gives me a System.IO.IOException with the message 'The process cannot access the file'. ``` private void UnPackLegacyStats() { DirectoryInfo oDirectory; XmlDocument oStatsXml; //Get the directory oDirectory = new DirectoryInfo(msLegacyStatZipsPath); //Check if the directory exists if (oDirectory.Exists) { //Loop files foreach (FileInfo oFile in oDirectory.GetFiles()) { //Check if file is a zip file if (C1ZipFile.IsZipFile(oFile.FullName)) { //Open the zip file using (C1ZipFile oZipFile = new C1ZipFile(oFile.FullName, false)) { //Check if the zip contains the stats if (oZipFile.Entries.Contains("Stats.xml")) { //Get the stats as a stream using (Stream oStatsStream = oZipFile.Entries["Stats.xml"].OpenReader()) { //Load the stats as xml oStatsXml = new XmlDocument(); oStatsXml.Load(oStatsStream); //Close the stream oStatsStream.Close(); } //Loop hit elements foreach (XmlElement oHitElement in oStatsXml.SelectNodes("/*/hits")) { //Do stuff } } //Close the file oZipFile.Close(); } } //Delete the file oFile.Delete(); } } } ``` I am struggling to see where the file could still be locked. All objects that could be holding onto a handle to the file are in using blocks and are explicitly closed. Is it something to do with using FileInfo objects rather than the strings returned by the static GetFiles method? Any ideas?
I assume you're getting the error on the oFile.Delete call. I was able to reproduce this error. Interestingly, the error only occurs when the file is *not* a zip file. Is this the behavior you are seeing? It appears that the C1ZipFile.IsZipFile call is not releasing the file when it's not a zip file. I was able to avoid this problem by using a FileStream instead of passing the file path as a string (the IsZipFile function accepts either). So the following modification to your code seems to work: ``` if (oDirectory.Exists) { //Loop files foreach (FileInfo oFile in oDirectory.GetFiles()) { using (FileStream oStream = new FileStream(oFile.FullName, FileMode.Open)) { //Check if file is a zip file if (C1ZipFile.IsZipFile(oStream)) { // ... } } //Delete the file oFile.Delete(); } } ``` In response to the original question in the subject: I don't know if it's possible to know if a file can be deleted without attempting to delete it. You could always write a function that attempts to delete the file and catches the error if it can't and then returns a boolean indicating whether the delete was successful.
I do not see problems in your code, everything look ok. To check is the problem lies in C1ZipFile I suggest you initialize zip from stream, instead of initialization from file, so you close stream explicitly: ``` //Open the zip file using (Stream ZipStream = oFile.OpenRead()) using (C1ZipFile oZipFile = new C1ZipFile(ZipStream, false)) { // ... ``` Several other suggestions: * You do not need to call Close() method, with *using (...)*, remove them. * Move xml processing (Loop hit elements) outsize zip processing, i.e. after zip file closeing, so you keep file opened as least as possible.
Why can't this file be deleted after using C1ZipFile?
[ "", "c#", ".net", "file-io", "using", "" ]
I have this array: ``` Array ( [1] => animal [1-1] => turtle [1-1-1] => sea turtle [1-1-2] => box turtle [1-1-3] => green turtle [1-1-3-1] => green turtle with brown tail ) ``` and I want some how to convert it into: ``` Array ( [1-title] => animal [1-sons] => array( [1-1-title] => turtle [1-1-sons] => array( [1-1-1] => sea turtle [1-1-2] => box turtle [1-1-3-title] => green turtle [1-1-3-sons] => array( [1-1-3-title] => green turtle ) ) ) ) ``` or maybe you can suggest a better way for organizing the result array.. but how to do that? I know that's not easy task at all, I'm writing a parser that will walk on data and make tree out of them.
The easiest way of organizing your data would be in such a way: ``` array ( 'Animal' => array ( 'Turtle' => array ( 'Sea Turtle', 'Box Turtle', 'Green Turtle' => array ( 'Green Turtle With Brown Tail', ), 'Common Turtle', ), ), ); // Or, otherwise written (equivalent to the above) $animals = array(); $animals['Animal'] = array(); $animals['Animal']['Turtle'] = array(); $animals['Animal']['Turtle'][] = 'Sea Turtle'; $animals['Animal']['Turtle'][] = 'Box Turtle'; $animals['Animal']['Turtle']['Green Turtle'] = array(); $animals['Animal']['Turtle']['Green Turtle'][] = 'Green Turtle With Brown Tail'; $animals['Animal']['Turtle'][] = 'Common Turtle'; ``` Essentially, the name of the animal is the value, unless it has children, then the value is an array and the key is the animal name. --- That way, you can easily parse the values by doing the following: ``` parse_animals($animals); function parse_animals($array, $indent = 0) { if(!is_array($array)) return; // A little safe guard in case. foreach($array as $key => $value) { echo str_repeat(' ', $indent) . "- "; if(is_array($value)) { echo $key . "\n"; parse_animals($value, $indent + 1); } else { echo $value . "\n"; } } } ``` The above in the console will output the following: ``` - Animal - Turtle - Sea Turtle - Box Turtle - Green Turtle - Green Turtle With Brown Tail - Common Turtle ``` **EDIT:** And here is a version that will output it for a webpage. ``` function parse_animals_web($array) { if(!is_array($array)) return; // A little safe guard in case. foreach($array as $key => $value) { echo '<ul>'; if(is_array($value)) { echo '<li>' . htmlentities($key) . "</li>"; parse_animals_web($value); } else { echo '<li>' . htmlentities($value) . "</li>"; } echo '</ul>'; } } ``` The output is: > * Animal > + Turtle > + Sea Turtle > + Box Turtle > + Green Turtle > - Green Turtle With Brown Tail > + Common Turtle --- Maybe you want to get the children of an animal. ``` function get_children_of($array, $name) { foreach($array as $key => $value) { if(is_array($value)) { if($key === $name) { return $value; } else { return get_children_of($value, $name); } } } return array(); } ``` Now we can get all the children of the `Green Turtle` and output them. ``` $green_turtle = get_children_of($animals, 'Green Turtle'); parse_array($green_turtle); ``` The output is: ``` - Green Turtle With Brown Tail ``` --- **EDIT:** Since you say you are stuck with the input array being in that weird format, here is a function that will convert your array into the format I specified above: ``` function convert_array($array) { $new_array = array(); $keys = array_keys($array); foreach($keys as $key) { $level = explode('-', $key); $cur_level = &$new_array; $cur_key = ''; foreach($level as $o_key) { $cur_key = ltrim($cur_key . '-' . $o_key, '-'); $next_key = $cur_key . '-1'; $value = $array[$cur_key]; $has_child = array_key_exists($next_key, $array); if($has_child) { if(!array_key_exists($value, $cur_level)) { $cur_level[$value] = array(); } $cur_level = &$cur_level[$value]; } else { $cur_level[] = $value; } } } return $new_array; } ```
Try this: ``` $array = array( '1' => 'animal', '1-1' => 'turtle', '1-1-1' => 'sea turtle', '1-1-2' => 'box turtle', '1-1-3' => 'green turtle', '1-1-3-1' => 'green turtle with brown tail' ); $tree = array(); foreach ($array as $path => $val) { $segments = explode('-', $path); $last = array_pop($segments); $tmp = &$tree; $path = ''; foreach ($segments as $segment) { $path .= $segment.'-'; if (!isset($tmp[$path.'sons'])) { $tmp[$path.'sons'] = array(); } $tmp = &$tmp[$path.'sons']; } $tmp[$path.$last.'-title'] = $val; } print_r($tree); ``` But your data structure doesn’t make much sense.
Convert a flat array with parent-child expressions as keys into a hierarchical multidimensional array
[ "", "php", "arrays", "recursion", "multidimensional-array", "hierarchical-data", "" ]
Backspace is the browser hotkey for Navigate Back To The Last Page. I know that when an input has the focus this hotkey is disabled. But I have keyup and keydown events binded to this input, and something I wrote is causing this trouble. Do you know the solution?
The problem was caused by the input removal before returning the onKeyDown event.
when you have handled the event from the input element, cancel that event's bubbling before returning.
How to avoid navigate back when the user types backspace on a HTML text input?
[ "", "javascript", "jquery", "html", "input", "" ]
I am just reading *Agile Principles, Patterns and Practices in C#* by R. Martin and M. Martin and they suggest in their book, to keep all your interfaces in a separate project, eg. *Interfaces*. As an example, if I have a *Gui* project, that contains all my custom Gui classes, I will keep their interfaces in the *Interfaces* project. Specifically I had a CustomButton class in *Gui*, I would keep the ICustomButton interface in *Interfaces*. The advantage is, that any class that needs an ICustomButton does not need a reference to *Gui* itself, but only to the much lighter weight *Interfaces* project. Also, should a class in the *Gui* project change and thus cause it to be rebuilt, only the projects directly referring to the CustomButton would need recompilation, whereas the ones referring to the ICustomButton may remain untouched. I understand that concept, but see a problem: Lets say I have this interface: ``` public interface ICustomButton { void Animate(AnimatorStrategy strategy); } ``` As you can see, it refers to AnimatorStrategy, which is a concrete class and therefore would sit in a different project, lets call it *Animation*. Now the interface project needs to refer to *Animation*. On the other hand, if *Animation* uses an interface defined in *Interfaces*, it needs to refer to it. Cyclic dependency - "Here we come". The only solution for this problem, that I see, is, that all methods defined in the interfaces take inputs that are themselves interfaces. Trying to implement this, will most likely have a domino effect though and quickly require an interface to be implemented even for the most basic classes. I don't know if I would like to deal with this overhead in development. Any suggestions?
**Beware of always, ever, and never - especially near all, none, or every.** Should you *always* put *all* of you interfaces in a separate assembly? No - not necessarily. Should you put interfaces that you expect external consumers of your code to implement - possibly. I would put interfaces into an external assembly if you expect multiple assemblies in your project to rely on them - this can help break coupling dependencies. I've also used this practice to solve circular referencing issues, where assemblies need to be aware of interfaces in one another. I don't put interfaces that are only used internally in a project in a separate assembly. I also don't promote interfaces into their own assembly when my projects are relatively small - or the interfaces are not intended to be used without the assembly that depends on them. As for the example you presented - I would suggest that you consider NOT referencing classes in your system from interfaces. Whenever possible, I try to have interfaces only reference other interfaces - this keeps things relatively decoupled. You can't always achieve this - and so when you have these types of interfaces - you have to keep them with the assembly they depend on. If you do decide to put interfaces into a separate assembly - you shouldn't necessarily put them all into a single assembly. You may want to break them out by their intended usage - this way consumers can pull in just the interfaces that are relevant to a particular domain of functionality.
The simple answer is AnimatorStrategy should also be an interface. The implementation for AnimatorStrategy is in the Animation project, but the interface would be in an AnimationInterfaces or Interfaces (as needed) project. I wouldn't necessarily have a single interfaces project, but one for each functional grouping. Clients of Animation would reference AnimationInterfaces and clients of Gui would reference GuiInterfaces. This way you preserve your contracts, without mixing in any implementation. For what it's worth I prefer to go the other way round with naming conventions. Put the interfaces in Animation, and the implementations in AnimationImpl (or similar). That way you are referencing the functional name.
Organizing interfaces
[ "", "c#", "interface", "circular-dependency", "" ]
Is there such a beastie? The simple [SOAP client](http://www.php.net/soap) that ships with PHP does not understand multi-part messages. Thanks in advance.
The native PHP [`SoapClient`](http://de3.php.net/manual/en/class.soapclient.php) class does not support multipart messages (and is strongly limited in all WS-\* matters) and I also I think that neither the PHP written libraries [NuSOAP](http://sourceforge.net/projects/nusoap/) nor [Zend\_Soap](http://framework.zend.com/manual/en/zend.soap.html) can deal with this sort of SOAP messages. I can think of two solutions: * extend the `SoapClient` class and overwrite the `SoapClient::__doRequest()` method to get hold of the actual response string which you can then parse at your whim. ``` class MySoapClient extends SoapClient { public function __doRequest($request, $location, $action, $version, $one_way = 0) { $response = parent::__doRequest($request, $location, $action, $version, $one_way); // parse $response, extract the multipart messages and so on } } ``` This could be somewhat tricky though - but worth a try. * use a more sophisticated SOAP client library for PHP. The first and only one that comes into my mind is [WSO2 WSF/PHP](http://wso2.org/projects/wsf/php) which features SOAP MTOM, WS-Addressing, WS-Security, WS-SecurityPolicy, WS-Secure Conversation and WS-ReliableMessaging at the cost of having to install a native PHP extension.
Even though this answer has been given a lot here already, I have put together a general solutions, that keeps in mind, that the XML can come without the wrapper. ``` class SoapClientExtended extends SoapClient { /** * Sends SOAP request using a predefined XML * * Overwrites the default method SoapClient::__doRequest() to make it work * with multipart responses. * * @param string $request The XML content to send * @param string $location The URL to request. * @param string $action The SOAP action. [optional] default='' * @param int $version The SOAP version. [optional] default=1 * @param int $one_way [optional] ( If one_way is set to 1, this method * returns nothing. Use this where a response is * not expected. ) * * @return string The XML SOAP response. */ public function __doRequest( $request, $location, $action, $version, $one_way = 0 ) { $result = parent::__doRequest($request, $location, $action, $version, $one_way); $headers = $this->__getLastResponseHeaders(); // Do we have a multipart request? if (preg_match('#^Content-Type:.*multipart\/.*#mi', $headers) !== 0) { // Make all line breaks even. $result = str_replace("\r\n", "\n", $result); // Split between headers and content. list(, $content) = preg_split("#\n\n#", $result); // Split again for multipart boundary. list($result, ) = preg_split("#\n--#", $content); } return $result; } } ``` This only works if you initialize the `SoapClientExtended` with the option `trace => true`.
PHP SOAP client that understands multi-part messages?
[ "", "php", "web-services", "soap", "" ]
I have a form where a couple of fields are coming out as required when I don't want them too. Here is the form from models.py ``` class CircuitForm(ModelForm): class Meta: model = Circuit exclude = ('lastPaged',) def __init__(self, *args, **kwargs): super(CircuitForm, self).__init__(*args, **kwargs) self.fields['begin'].widget = widgets.AdminSplitDateTime() self.fields['end'].widget = widgets.AdminSplitDateTime() ``` In the actual Circuit model, the fields are defined like this: ``` begin = models.DateTimeField('Start Time', null=True, blank=True) end = models.DateTimeField('Stop Time', null=True, blank=True) ``` My views.py for this is here: ``` def addCircuitForm(request): if request.method == 'POST': form = CircuitForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/sla/all') form = CircuitForm() return render_to_response('sla/add.html', {'form': form}) ``` What can I do so that the two fields aren't required?
If you don't want to modify blank setting for your fields inside models (doing so will break normal validation in admin site), you can do the following in your Form class: ``` def __init__(self, *args, **kwargs): super(CircuitForm, self).__init__(*args, **kwargs) for key in self.fields: self.fields[key].required = False ``` The redefined constructor won't harm any functionality.
> If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True Says so here: <http://docs.djangoproject.com/en/dev/topics/forms/modelforms/> Looks like you are doing everything right. You could check the value of `self.fields['end'].required`.
Django required field in model form
[ "", "python", "django", "forms", "model", "widget", "" ]
How to insert a NULL or empty value in a mysql date type field (NULL = yes). If I try to insert an empty value it inserts 0000-00-00 but I want to keep it empty or NULL. Thanks for help. **UPDATE** Please see that I have set default value as NULL ``` `payment_due_on` date DEFAULT NULL, ``` Ok OKies I have got it working now ``` function get_mysqlDate($date, $delimiter='/') { if(check_empty($date)) { return 'NULL'; } list($d, $m, $y) = explode($delimiter, $date); //$datetime = strtotime($date); return "'".date('Y-m-d', mktime(0,0,0,$m, $d, $y))."'"; } "... SET mydate = ".get_mysqldate($_POST['mydate'])." ...." ``` Cheers
If that's happening, it's because the column has been defined with `NOT NULL` or with a `default '0000-00-00'`. You need to change the column definition to allow `NULL`s and have no default. Your insert should be specifying NULL, as well, not `''`, if that's what you mean by "empty value".
phew.. was struggling with this null thing a bit. I had a php script that copies, formats and stores data from one database A to database B. there was a date field in database A with NULL values. but when I copied it it became 0000-00-00 in my database B. finally figure out it was because I was putting single quotes around NULL like ('NULL'). ``` $started_date = mysql_result($databaseA['result'],$i,"start_date"); if (empty($published_at_date)){ $insert_sql .= "NULL, "; } else { $insert_sql .= " '" . mysql_real_escape_string($started_date) ."', "; } ``` This fixed it.
how to insert an empty value in mysql date type field?
[ "", "php", "mysql", "date", "" ]
I have many textfields that show instruction text within the textbox (how the default value would look). On focus the color of the text becomes lighter, but doesn't go away until text is entered. When text is erased, the label returns. It's pretty slick. **A default value doesn't cut it, because these go away onfocus.** I have it working, but the code is complicated because it relies on negative margins that correspond to the individual widths of the textfields. I want a dynamic solution where the label for its textfield is positioned correctly automatically, probably using a script. Any help would be greatly appreciated. But I am not looking for default values as a solution. Thanks. Mike Edited to be more precise. Edited again to provide some simple code that illustrates the effect I am after: ``` <input style="position: relative; width: 150px; font-size: 10px; font-family: Verdana, sans-serif; " type="text" name="name" id="name" onfocus="javascript: document.getElementById('nameLabel').style.color='#BEBEBE';" onkeypress="javascript: if (event.keyCode!=9) {document.getElementById('nameLabel').innerHTML='&nbsp;';}" onkeyup="javascript: if (this.value=='') document.getElementById('nameLabel').innerHTML='Your&#160;Name';" onblur="javascript: if (this.value=='') {document.getElementById('nameLabel').style.color='#7e7e7e'; document.getElementById('nameLabel').innerHTML='Your&#160;Name';}"/> <label id="nameLabel" for="name" style="position: relative; margin-left: -150px; font-size: 10px; font-family: Verdana, sans-serif;">Your Name</label> ```
I would have taken a different approach (It's not entirely my idea, but i can't find the source for credit): 1st - Use html5 "placeholder" property. 2nd - Use [Modernizr.js](http://www.modernizr.com/) to detect support of placeholders in the browser and a simple jQuery script to add support to browsers that doesn't support it. So, the html will look something like that: ``` <input type="text" class="placeholder" placeholder="Help Text" /> <textarea class="placeholder" placeholder="Another help text"></textarea> ``` The css: ``` .placeholder{color:#ccc;} ``` And the javascript: ``` /* Set placeholder for browsers that don't support HTML5 <input placeholder='text'> * Depends on Modernizr v1.5 */ if (!Modernizr.input.placeholder){ $('input[placeholder], textarea[placeholder]') .focus(function() { var input = $(this); if (input.val() == input.attr('placeholder')) { input.val(''); input.removeClass('placeholder'); } }) .blur(function() { var input = $(this); if (input.val() == '') { input.addClass('placeholder'); input.val(input.attr('placeholder')); } }) //Run once on load .blur(); // Clear all 'placeholders' on submit $('input[placeholder], textarea[placeholder]').parents('form').submit(function() { $(this).find('[placeholder]').each(function() { var input = $(this); if (input.val() == input.attr('placeholder')) { input.val(''); } }); }); } ```
Do you mean like [this](http://cssmysite.com/contact)? But instead of 'required' it would have the label? I used a jQuery solution where I set the value of the input to 'required'. The input has a class of gray so the default text is lighter. --- Edit after comment Instead of using focus, you can change the input values on keydown and keyup. ``` $('.required_input').keydown(function() { if (this.value == 'required') { $(this).val('').removeClass('gray'); } } ); $('.required_input').keyup(function() { if (this.value == '') { $(this).val('required').addClass('gray'); } } ); $('.required_input').blur(function() { if (this.value == '') { $(this).val('required').addClass('gray'); } } ); ```
How can I position a label inside its textfield?
[ "", "javascript", "html", "css", "" ]
Is it possible to override += in Python?
Yes, override the [`__iadd__`](https://docs.python.org/3/reference/datamodel.html?highlight=iadd#object.__iadd__) method. Example: ``` def __iadd__(self, other): self.number += other.number return self ```
In addition to what's correctly given in answers above, it is worth explicitly clarifying that when `__iadd__` is overriden, the `x += y` operation does NOT end with the end of `__iadd__` method. Instead, it ends with `x = x.__iadd__(y)`. In other words, Python assigns the return value of your `__iadd__` implementation to the object you're "adding to", AFTER the implementation completes. This means it is possible to mutate the left side of the `x += y` operation so that the final implicit step fails. Consider what can happen when you are adding to something that's within a list: `>>> x[1] += y # x has two items` Now, if your `__iadd__` implementation (a method of an object at `x[1]`) erroneously or on purpose removes the first item (`x[0]`) from the beginning of the list, Python will then run your `__iadd__` method) & try to assign its return value to `x[1]`. Which will no longer exist (it will be at `x[0]`), resulting in an `ÌndexError`. Or, if your `__iadd__` inserts something to beginning of `x` of the above example, your object will be at `x[2]`, not `x[1]`, and whatever was earlier at `x[0]` will now be at `x[1]`and be assigned the return value of the `__iadd__` invocation. Unless one understands what's happening, resulting bugs can be a nightmare to fix.
Overriding "+=" in Python? (__iadd__() method)
[ "", "python", "operators", "overriding", "" ]
[Spring Framework](http://www.springsource.org/) 3 seems to be right around the corner, but the GA version is 2.5.6. If this is the first time I'm approaching the subject, should I start with the stable version, or should I start with the new version and save myself migration issues? How different is version 3 from version 2? How near is Spring 3?
I would start with the stable version. Less bugs, more documentation, more stable and easier to find answers to issues.. Spring 3 won't be vastly different. There is a Spring 3 reference manual but it's incomplete for the changes. Also, since Spring 3 is only on a milestone release (M3), it's still subject to change. You can read [What's New in Spring 3.0](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/ch02.html) but I imagine a lot of it won't mean anything to you yet.
I would start with Spring 3 for various reasons: * full Java 5 support (this is main reason for adopting Spring 3 for me) * Spring MVC support is deeply change between spring 2 and 3 (notably REST support). Learning spring 2 MVC is not a far-seeing imho. * new module organization (if you start with Spring 3, you don't need to migrate packages in the future) * OSGI compabitiliy * Ivy support You don't need to worry about bugs or incomplete documentation since you are still learning the framework concepts. In conclusion, learning Spring 3 instead Spring 2 is a far-seeing choice. However a very good introduction to Spring 2.x is given by [Spring in Action](http://www.manning.com/walls2/), an excellent book about the subject.
Should I learn Spring 2 or 3?
[ "", "java", "spring", "" ]
I have built a Library project (DLL) in .NET. And sometimes I use the DLL along with its PDB file as a reference in some other projects. Now in the new project, I cant browse through the code of the DLL to debug. I can only see the definitions of class/methods/variables. That's by using "show definition" by browsing through the "class view" However, only in case of an exception I the contents of the DLL opens and I could see the entire code of the DLL from the new project. How could I see the contents (code) of the DLL before an exception occur?
If you just need to browse the code, load the dll up in Reflector -- you don't even need the PDB file: <http://www.red-gate.com/products/reflector/>
If an app loads the DLL while running under the Visual Studio debugger, it should load the symbols automatically. If all you have is a DLL, you may need to write a "driver" app that does nothing but load and exercise the DLL entry points.
show definition (browse) in *.pdb of *.dll file
[ "", "c#", ".net", "debugging", "pdb-files", "" ]
What if I want to split a string using a delimiter that is a word? For example, `This is a sentence`. I want to split on `is` and get `This` and `a sentence`. In `Java`, I can send in a string as a delimiter, but how do I accomplish this in `C#`?
<http://msdn.microsoft.com/en-us/library/system.string.split.aspx> Example from the docs: ``` string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"; string[] stringSeparators = new string[] {"[stop]"}; string[] result; // ... result = source.Split(stringSeparators, StringSplitOptions.None); foreach (string s in result) { Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s); } ```
You can use the [Regex.Split](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.split.aspx) method, something like this: ``` Regex regex = new Regex(@"\bis\b"); string[] substrings = regex.Split("This is a sentence"); foreach (string match in substrings) { Console.WriteLine("'{0}'", match); } ``` **Edit**: This satisfies the example you gave. Note that an ordinary *String.Split* will also split on the "*is*" at the end of the word "This", hence why I used the *Regex* method and included the word boundaries around the "*is*". Note, however, that if you just wrote this example in error, then *String.Split* will probably suffice.
How do I split a string by a multi-character delimiter in C#?
[ "", "c#", ".net", "string", "" ]
Hello I have a table with articles and the articles have a column category. The categories are filled like 1,4,6,8 How can i check if there is a product which has in it for example category 5 I tried something like ``` select * from article where category in(5); ``` But that doesn't work. If I use like than i will have a problem with for example 1 and 10. So how can I do this in one mysql query?
1. Storing CSV in a column you need to query is a bad idea - you should use a separate table. 2. IN is not for CSVs - it's for listing values for a single column 3. Those arguments aside, you can use [`FIND_IN_SET()`](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set) For example: ``` SELECT * FROM article WHERE FIND_IN_SET('5', category) != 0; ```
You *could* do it with `select * from article where category='5' or category like '5,%' or category like '%,5' or category like '%,5,%'` But you really don't want to do that. Instead, what you're after is ``` create table article ( id INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY, headline VARCHAR(50) NOT NULL, body VARCHAR(50) NOT NULL ); create table articlecategory ( article_id INTEGER NOT NULL, category_id INTEGER NOT NULL, PRIMARY KEY (article_id, category_id) ); ``` And then ``` SELECT article.* FROM article,articlecategory WHERE articlecategory.article_id=article.id AND articlecategory.category_id=5; ```
How can I match a comma separated list against a value?
[ "", "sql", "mysql", "data-structures", "" ]
I tried using Visual Studio instead of VIM(+plugins), but to be honest - the only advantage of VS over VIM is it's ability to automatically manage my project. I know of existence of ViEmu for VS, but I would like to do the opposite - is there any way to manage projects from within VIM? I tried both [c.vim](http://www.vim.org/scripts/script.php?script_id=213) plugin and [Project](http://www.vim.org/scripts/script.php?script_id=69) plugins, but: * I have a problem while using c.vim on windows (from what I remember, there is an error with "slashes" in filepath ). * Project allows to organize projects, but it lacks features for generating makefiles / msbuild files (or am I wrong?). Are there any tips / solutions / hacks, which would allow me to use VIM to manage my projects? (ideally, using both makefiles and MSBuild files, but just one type of build files would be enough.)
Maybe I don't understand the question. VS is full features IDE - you edit, compile and debug without leaving it. vim in contrast is not IDE - its very powerful text editor. Yet vim has some build-in functionality oriented for programmers (e.g. :make command, compilation, automatic indentation etc.). vim is coming from Unix world where there several build tools (make, scons, cmake etc.). As you know you can "integrete" them using plugins which mostly very far from to be complete. I think what you tried to do in the beginning is the right thing - bring vim editing power to VS world.
To integrate vim with devenv, you can use devenv from Visual Studio to complie the project in vim. The command as follows: ``` Devenv SolutionName /build SolnConfigName [/project ProjName [/projectconfig ProjConfigName]] ``` Typicatlly, the devenv should located in C:\Program Files\Microsoft Visual Studio 8\Common7\IDE. Set it to the path of environment to make it callable from vim. We also need to make vim recognize the error messages thrown by the commandline build tool devenv. Just put the following lines in your vimrc: ``` " Quickfix mode: command line devenv error format au FileType cpp set makeprg=devenv.com\ /Build\ Debug\ *[SolutionName]* au FileType cpp set errorformat=\ %#%f(%l)\ :\ %#%t%[A-z]%#\ %m ``` Then You can use :make to compile and build the program from vim.
VIM: is there an easy way to manage Visual Studio solutions / makefile projects from Vim?
[ "", "c++", "visual-studio", "vim", "project-management", "makefile", "" ]
this is my code ``` private void sendToClient(Dictionary<string, string> reportDic) { Response.Clear(); Response.BufferOutput = false; String ReadmeText = "some text"; Response.ContentType = "application/zip"; Response.AddHeader("content-disposition", "filename=" + "filename.zip"); using (ZipFile zip = new ZipFile()) { zip.AddEntry("Readme.txt", ReadmeText); zip.Save(Response.OutputStream); } Response.Close(); } ``` at this point I'm simply trying to return a zip file with the readme.txt document inside the zip with the words "some text" inside the document. What I get is a zipfile named filename.zip(expected) with a document readme.txt(expected) with no text inside of the doucment(unexpected). This code is almost verbatim from the example [here](http://dotnetzip.codeplex.com/Wiki/View.aspx?title=Examples). Which makes me thing other people have run into this exact problem. My end goal is to do something like this. ``` private void sendToClient(Dictionary<string, string> reportDic) { Response.BufferOutput = false; Response.ContentType = "application/zip"; Response.AddHeader("content-dispostion", "filename=text.zip"); Response.ContentEncoding = Encoding.Default; Response.Charset = ""; using (ZipFile zip = new ZipFile()) { foreach (string key in reportDic.Keys) { zip.AddEntry(key, reportDic[key]); } zip.Save(Response.OutputStream); } Response.Close(); } ``` add three strings as files to the zip file, but I'll settle for getting the example working for now. Anyone have any suggestions? Thanks --UPDATE-- This should work, in fact if I copy it into a new project, it works just as advertised, I must have a toxic mix of dlls or some corruption in my project, that is obscure or something. Wonderful.
hint: don't use ``` HttpContext.Current.ApplicationInstance.CompleteRequest(); ``` instead, use ``` Response.Close(); ``` If you use the former, you will get HTML junk appended to the bottom of your zip file.
Have you tried putting in the AddFile method with some dummy text = I think this is required.
Sending Zip file to Client via Response with DotNetZip
[ "", "c#", "asp.net", "zip", "response", "dotnetzip", "" ]
I'm trying to get the resolution of the screen as well as the resolution of a specific window (in which a program is running) on Linux system. I don't need to modify the resolution, I only need the current values. As far as I know, we can call some system functions to do so on Windows, how can we do that on Linux, preferably using C/C++ language? Thanks in advance. update: Actually, I don't need to do a GUI, although I know Qt and GTK+ can do it, I'm reluctant to include an external library for just getting the resolution.
In X11, you'd need to call the Xlib's [XGetWindowAttributes](http://www.xfree86.org/4.4.0/XGetWindowAttributes.3.html) to get the various window info, including the size and position relative to parent. For an example of how it is used, you can google for 'xwininfo.c'. That said, probably you are going to use some more highlevel framework to do your window programming - and the chances are high that it already has some other primitives for this, see an example for [Qt](http://doc.trolltech.com/4.0/geometry.html) - so you might want to give a bit more background about the question.
To get screen resolution, you can use XRandR extension, like in [xrandr](http://google.com/codesearch/p?hl=en&sa=N&cd=3&ct=rc#GVFTOHYvCds/xc/programs/xrandr/xrandr.c&q=xrandr.c) sources: ``` SizeID current_size; XRRScreenSize *sizes; dpy = XOpenDisplay (display_name); // ... root = RootWindow (dpy, screen); sc = XRRGetScreenInfo (dpy, root); current_size = XRRConfigCurrentConfiguration (sc, &current_rotation); sizes = XRRConfigSizes(sc, &nsize); for (i = 0; i < nsize; i++) { printf ("%c%-2d %5d x %-5d (%4dmm x%4dmm )", i == current_size ? '*' : ' ', i, sizes[i].width, sizes[i].height, sizes[i].mwidth, sizes[i].mheight); // ... } ``` You can see the output typing "xrandr" in your xterm. Or, better, use the [xdpyinfo](http://google.com/codesearch/p?hl=en&sa=N&cd=2&ct=rc#QlD3RqLk4t4/xdpyinfo.c&q=xdpyinfo.c) method: ``` Display *dpy; // dpy = ... int scr = /* ... */ printf (" dimensions: %dx%d pixels (%dx%d millimeters)\n", DisplayWidth (dpy, scr), DisplayHeight (dpy, scr), DisplayWidthMM(dpy, scr), DisplayHeightMM (dpy, scr)); ```
How to programmatically get the resolution of a window and that of the system in Linux?
[ "", "c++", "linux", "screen-resolution", "" ]
Ok, I was eagerly awaiting the release of subsonic 3.0 to use as my low-level data layer, and now its out. I'm currently using the ActiveRecord templates (having tried both the repository and advanced templates) and I have one HUGE request and a few questions: Request: Other than bug fixes, Rob please spend the time to provide documentation. I don't mean 5 examples, I mean API complete documentation. Here's why: I'm testing subsonic by writing ASP.NET MembershipProvider and RoleProvider classes and simple questions continually slow me up using subsonic: Q. Assuming I have a class 'User' and I update/save/delete a record using ``` user.Save(); ``` I need information on how to get success/failure? Do I look for an exception on failure or can I get a count of 'affected' records (old school?) Q. If I get an exception, which exception(s) can I expect? I'll have more issues, but I really believe a good functional API documentation would solve the problem. If the answer is 'read the source code', then I'm sure you're going to chase quite a few developers away from subsonic. I really want to use the library, but the point is "use" the library, not reverse engineer it. -Jeff
Q. I need information on how to get success/failure? Do I look for an exception on failure or can I get a count of 'affected' records (old school?) If it doesn't throw an exception then it's worked Q. If I get an exception, which exception(s) can I expect? You can expect a [DbException](http://msdn.microsoft.com/en-us/library/system.data.common.dbexception.aspx)
We don't use custom exceptions. I spent 5 weeks writing docs - so yah I did spend some time on this. You could also find your answer there as well: <http://subsonicproject.com/docs>
Subsonic 3.0 General Questions
[ "", "c#", "subsonic", "subsonic3", "" ]
I have a map that relates integers to vectors (of objects). These vectors represent a set of tasks to perform. In order to reduce the amount of copying going on while using this map and vector I've set them up to make use of pointers. ``` std::map<int, std::vector<MyObject *> *> myMap; ``` During initialization of the class that holds myMap, I populate myMap by creating a new vector filled with new MyObjects. What I'm concerned with, however, is memory management. Now I have these various objects sitting out on the heap somewhere and I am responsible for cleaning them up when I'm done with them. I also know that I will NEVER be done with them until the program is finished. But what about in 10 weeks when someone decides that a clever way to modify this app involves removing items from the map/vectors. This would cause a memory leak. My question is how can I handle the **proper** deallocation of these objects so that even if they get removed via an STL function that the objects get successfully deallocated? Your help is much appreciated, let me know if I've missed anything critical! Thanks!
I agree the use of smart pointers is a good way to go, but there are at least two alternatives: a) Copying may not be as expensive as you think it is. Try implementing a map of values ``` std::map<int, std::vector<MyObject>> myMap; ``` b) Replace the vector with a class of your own that wraps the vector. In that classes destructor, handle the deallocation. You could also provide methods for adding and removing MyObjects.
Use a smart pointer boost:shared\_ptr rather than raw pointers, that way when the object is destroyed it will clear up the heap allocated memory as well. boost::shared\_ptr <http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/shared_ptr.htm> Also is there really a reason to have pointers to the vectors? They take up almost no space, and objects within an std::map are not moved anyway (unlike the objects in a vector which are moved/copied each time the vector reallocates, eg to get more space). EDIT: Also shared\_ptr is a component of tr1, and I'm pretty sure is in the next standard, so your compiler may already have it. There are also lots of other smart pointers around that are STL safe to give you an idea of how to write your own, a quick search on Google should find them. EDIT2: Just checked and the Visual Studio 2008 implementation of TR1 includes the shared\_ptr which is included in the [Visual C++ 2008 Feature Pack](http://www.microsoft.com/downloads/details.aspx?FamilyId=D466226B-8DAB-445F-A7B4-448B326C48E7&displaylang=en). I expect many other vendors have implementations available for at least parts of TR1, so if your not using VS search your vendors site for TR1 support.
Memory Management on Objects in a C++ Collection
[ "", "c++", "memory-management", "stl", "containers", "" ]
I want to get the default timezone (PST) of my system from Python. What's the best way to do that? I'd like to avoid forking another process.
Check out the Python [Time](http://docs.python.org/library/time.html) Module. ``` from time import gmtime, strftime print(strftime("%z", gmtime())) ``` Pacific Standard Time
This should work: ``` import time time.tzname ``` `time.tzname` returns a tuple of two strings: The first is the name of the local non-DST timezone, the second is the name of the local DST timezone. Example return: `('MST', 'MDT')`
Get time zone information of the system in Python?
[ "", "python", "datetime", "" ]
I'm writing a callback function for the [`FB.Connect.showPermissionDialog()`](http://wiki.developers.facebook.com/index.php/JS_API_M_FB.Connect.showPermissionDialog) function which accepts permissions and an optional callback function. It's supposed to be passed `null` if the user rejects the permissions dialog. But for some reason, my script always makes the post request even if the permissions request failed. ``` echo("FB.ensureInit ( function () { FB.Connect.showPermissionDialog('email,offline_access', function(accepted) { if(accepted==null) {alert('failure');} else { $.post(\"http://www.domain.com/permissions.php\", { username:$userID,mode:'accepted'});} }); });"); ``` Not sure why it's not reading the value of accepted properly. Thanks for the help.
My first guess is that the Javascript `null` value is not actually being returned, and some other false-like value is being returned instead. I'd try changing to this to test for all false-like values: ``` if (!accepted) {alert('failure')} else { ... ```
Do with firebug: ``` console.log(accepted) ``` And see what you're getting back. Could be undefined, which according to your logic still passes.
Callback function parameter issue
[ "", "javascript", "jquery", "facebook", "" ]
For my debugging needs, `pdb` is pretty good. However, it would be *much* cooler (and helpful) if I could go into `ipython`. Is this thing possible?
There is an `ipdb` project which embeds iPython into the standard pdb, so you can just do: ``` import ipdb; ipdb.set_trace() ``` It's installable via the usual `pip install ipdb`. `ipdb` is pretty short, so instead of easy\_installing you can also create a file `ipdb.py` somewhere on your Python path and paste the following into the file: ``` import sys from IPython.Debugger import Pdb from IPython.Shell import IPShell from IPython import ipapi shell = IPShell(argv=['']) def set_trace(): ip = ipapi.get() def_colors = ip.options.colors Pdb(def_colors).set_trace(sys._getframe().f_back) ```
In IPython 0.11, you can embed IPython directly in your code like this Your program might look like this ``` In [5]: cat > tmpf.py a = 1 from IPython import embed embed() # drop into an IPython session. # Any variables you define or modify here # will not affect program execution c = 2 ^D ``` This is what happens when you run it (I arbitrarily chose to run it inside an existing ipython session. Nesting ipython sessions like this in my experience can cause it to crash). ``` In [6]: In [6]: run tmpf.py Python 2.7.2 (default, Aug 25 2011, 00:06:33) Type "copyright", "credits" or "license" for more information. IPython 0.11 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]: who a embed In [2]: a Out[2]: 1 In [3]: Do you really want to exit ([y]/n)? y In [7]: who a c embed ```
Is it possible to go into ipython from code?
[ "", "python", "shell", "debugging", "ipython", "pdb", "" ]
I want to count several cpu instructions in my code. e.g. I would like to know how many additions, how many multiplications, how many float operations, how many branches my code executes. I currently use gprof under Linux for profiling my c++ code but it only gives the number of calls to my functions, and I manually estimate the number of instructions. Are there any tools that might do the trick for me? Maybe some virtual machine?
You may be able to use [Valgrind](http://valgrind.org/)'s [Callgrind](http://valgrind.org/docs/manual/cl-manual.html) with the `--dump-instr=yes` flag to achieve this
This is a general advice, not-Linux specific: you should be interested in CPU cycles instead. Forget about the number of instructions as a measure of performance. One instructions may cost same as other 10 together, so it won't tell you anything. You should focus on CPU cycles, and in multithreaded environments (most if not all today) in the time the thread is put to sleep ("switched/out"), which will give you the idea of how much time is waiting for I/O, DB, etc to complete and it impacts CPU privileged time.
Profiling instructions
[ "", "c++", "profiling", "instructions", "" ]
I'm looking to create an array or list with elements of a certain type (eg objects the implement a certain interface). I know I can create an object that does the same thing implementing Traversable and Iterator, or override ArrayObject. But maybe there's another way I have missed.
I would write a custom class that extended ArrayObject and threw an exception if you tried to assign a variable that wasn't the correct type, there's really no better way to do it that I can think of.
Do you mean something like: ``` $array=Array(); foreach ($itemsToAdd as $item) { if ($item instanceof NameOfwantedInterface) { Array_push($array,$item); } } ``` If you don't, them I'm sorry - it's just that your question isn't too clear.
php arrays with only one type
[ "", "php", "arrays", "" ]
The justification that I've seen for shall we say "Bastardizing" the Java bytecodes in Android was performance. (I suspect there is another reason.) However by changing the byte codes haven't they made hardware acceleration technologies such as Jazelle moot, and thus actually degraded the performance available for a Mobile Java platform? It appears counter intuitive to me knowing that the target platform is a ARM based mobile platform. While it MIGHT give you better performance on other CPU architectures it seems to spit in the face of ARM and Jazelle. What sort of quantitative effect does it have on Java performance? Does it actually improve performance, and if so how? What's the effect on other platforms? (i.e. x86,mips,yadda,yadda,yadda...)
Yes Dalvik makes Jazelle useless. The only question is was Jazelle useful to begin with or is it 90% marketing hype? A good JIT or AOT(ahead of Time) compiler tends to give much better performance than trying to use specialized instructions. The register based approach of Dalvik might be faster than a traditional java bytecode interpreter but if the difference in minor between that of an interpreter and that of a JIT. Hopefully one of the next versions of Android has a JIT. It takes ~5-10 years to write a good virtual machine with state of the art garbage collectors and optimizers. Sun (and Microsoft) have spent those years. Google hasn't. Hopefully they will keep investing in it so that one day Android Java code isn't a 90% slower than it should be.
[Wikipedia: Dalvik virtual machine](http://en.wikipedia.org/wiki/Dalvik_virtual_machine): > Unlike most virtual machines and true Java VMs which are stack machines, the Dalvik VM is a register-based architecture. > > Being optimized for low memory requirements, Dalvik has some specific characteristics that differentiate it from other standard VMs: > > * The VM was slimmed down to use less space. > * Dalvik has no just-in-time compiler. > * The constant pool has been modified to use only 32-bit indexes to simplify the interpreter. > * It uses its own bytecode, not Java bytecode. > > Moreover, Dalvik has been designed so that a device can run multiple instances of the VM efficiently. **Edit**: See Wikipedia: [Open Handset Alliance](http://en.wikipedia.org/wiki/Open_Handset_Alliance). The founding member includes Intel, Motorola, Qualcomm, and Texas Instruments. ARM joined an year later in December, 2008. So, I guess it didn't make sense for these companies to rely on a proprietary technology by then non-member, when the goal was to create opensource iPhone/Blackberry competitor.
Does Android castrate the ARM's Jazelle technology?
[ "", "java", "android", "architecture", "arm", "jazelle", "" ]
The strings are of the following pattern ``` 1.0.0.0 1.0.0.1 1.0.0.2 ... ... ... ``` I am looking for a code which will read the last created string and increment the last numeral by 1 and save it as a new string. How do I do it? Best Regards, Magic
You can split the string into the components, parse the last one so that you can increase it, and put them together again: ``` string[] parts = version.Split('.'); parts[3] = (Int32.Parse(parts[3]) + 1).ToString(); version = String.Join(".", parts); ``` Another method that may be slightly more efficient is to get only the last component using string operations: ``` int pos = version.LastIndexOf('.') + 1; int num = Int32.Parse(version.Substring(pos)); version = version.Substring(0, pos) + num.ToString(); ```
If your intention is to always get the last substring after a specific character (excluding the delimiter character of course (in this case a period)), which I believe is your intention: Keep it simple with a 1 liner: ``` string myLastSubString = myStringToParse.Split('.').Last(); ``` I'll let the other posts answer the rest of your query.
Extract All Characters after last occurrence of a pattern C#
[ "", "c#", "string", "" ]
I'm very new to Python in general, but I made an app in Python 2.6 / wxPython 2.8 that works perfectly when I run it through Python. But I wanted to go a step further and be able to deploy it as a Windows executable, so I've been trying out py2exe. But I haven't been able to get it to work. It would always compile an exe, but when I actually try to run that it barks some cryptic error message. At first they were simple messages saying it couldn't find certain DLLs, but even after giving it all the DLLs it wanted, it now returns this: ``` The application failed to initialize properly (0xc0000142). Click OK to terminate the application. ``` So I broke things down and just made a very, very simple application utilizing wxPython just to see if that would work, or if some of the more complicated features of my original app were getting in the way. But even my simple test returned the same error. Here's the code for the simple test script: ``` import wx class MainWindow(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, wx.ID_ANY, title, style=wx.DEFAULT_FRAME_STYLE ^ wx.MAXIMIZE_BOX) panel = wx.Panel(self, -1, style = wx.TAB_TRAVERSAL | wx.CLIP_CHILDREN | wx.FULL_REPAINT_ON_RESIZE) main_sizer = wx.BoxSizer(wx.VERTICAL) testtxt = wx.StaticText(panel, -1, label='This is a test!') main_sizer.Add(testtxt, 0, wx.ALIGN_CENTER) panel.SetSizerAndFit(main_sizer) self.Show(1) return app = wx.PySimpleApp() frame = MainWindow(None, -1, 'Test App') app.MainLoop() ``` And here's the py2exe setup script I used: ``` #!/usr/bin/python from distutils.core import setup import py2exe manifest = """ <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="0.64.1.0" processorArchitecture="x86" name="Controls" type="win32" /> <description>Test Program</description> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*" /> </dependentAssembly> </dependency> </assembly> """ setup( windows = [ { "script": "testme.py", "icon_resources": [(1, "testme.ico")], "other_resources": [(24,1, manifest)] } ], data_files=["testme.ico"] ``` ) Then I run `python setup.py py2exe`, it generates the EXE file, warns about some DLL files (which I subsequently copy into the dist directory), but then when I try to run the EXE, I get the error I quoted above immediately.
Note that there is a later version of the Visual C++ 2008 Redistributable package: [SP1](http://www.microsoft.com/downloads/info.aspx?na=47&p=2&SrcDisplayLang=en&SrcCategoryId=&SrcFamilyId=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&u=details.aspx%3ffamilyid%3dA5C84275-3B97-4AB7-A40D-3802B2AF5FC2%26displaylang%3den). However, both the SP1 and the earlier release don't install the DLLs into the path. As the download page says (my emphasis): > This package installs runtime > components of C Runtime (CRT), > Standard C++, ATL, MFC, OpenMP and > MSDIA libraries. For libraries that > support side-by-side deployment model > (CRT, SCL, ATL, MFC, OpenMP) they are > installed **into the native assembly > cache, also called WinSxS folder**, on > versions of Windows operating system > that support side-by-side assemblies. You will probably find these files in the `%WINDIR%\WinSxS` folder and not in the path.What I think you need to do is incorporate the manifest information for the relevant DLLs (found in `%WINDIR%\WinSxS\Manifests`) into your `setup.py`. I added the following section: ``` <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.30729.4918" processorArchitecture="X86" publicKeyToken="1fc8b3b9a1e18e3b" language="*" /> </dependentAssembly> </dependency> ``` immediately after the existing `<dependency>` section, and rebuilt the exe: it ran without problems. **Note:** depending on exactly what version of the Visual C++ files you installed, the above info may not be exactly correct. Look at the manifests on your system and use the correct `version`, `publicKeyToken` etc. Alternatively, look at [this answer](https://stackoverflow.com/questions/1145662/py2exe-compiled-python-windows-application-wont-run-because-of-dll) for how to deploy the DLLs with your application (as opposed to assuming they already exist on the target system). Oh ... I see you asked that original question ;-)
I've used py2exe before and I've never run across a situation like this.... However, it sounds like missing dependencies are your problem..... Does the packaged program work on your machine but not on others? If so, run the packaged application within DEPENDS (dependency walker) on both machines and compare to hopefully discern which packages didn't get included. Good Luck
How do I debug a py2exe 'application failed to initialize properly' error?
[ "", "python", "wxpython", "py2exe", "" ]
I have this working SQL statement: ``` select oriseqs.newID from oriseqs WHERE oriseqs.singlets=1 AND oriseqs.newID not in (select newID from cleanreport WHERE trash!="") ``` My question is how to avoid doing one select inside another in this particular case. I mean to rewrite the select statement in a way that there is no nested select. Here is the relevant schema if needed: ``` CREATE TABLE cleanreport(newID TEXT, perc TEXT, inicoord INTEGER, endcoord INTEGER, ilen INTEGER, trash TEXT, comments TEXT); CREATE TABLE oriseqs(newID TEXT, oldID TEXT, rawseq TEXT, singlets BOOLEAN); ```
There are multiple ways to approach almost any problem in SQL. In your particular problem, the first alternative that springs to mind is to use a left outer join and test for null in a joined column on the second table. However, the query that you have is perfectly reasonable. I see no reason to change it and doubt - at least upon first inspection - that you'll see better performance from an alternative.
``` SELECT oriseqs.newID FROM oriseqs AS o LEFT JOIN cleanreport AS cr ON o.newID = cr.newID WHERE oriseqs.singlets=1 AND trash != "" AND cr.newID IS NULL ``` What are the PKs?
Unnest an SQL statement
[ "", "sql", "sqlite", "" ]
I have this kinda interesting requirement. Typically you use XSLT to transform an XML document. The transformed HTML is viewable in a web browser, this works just great. I am also guessing the browser handles the transformation in memory, because if you view the page source of an xml document with XSLT, you don't see html, only xml. What I would like to do is the following. using c# 1. grab an xml file from the fileSystem.... Load it into some framework object 2. attach an XSLT stylesheet 3. output the rendered HTML back to an html file on the file system. Is this possible. I don't expect a full answer on the entire solution. Just a push in the right direction would be great :) thanks in advance.
You can use `System.Xml.Xsl` to do XSLT in C#. There's an article here: [XML transformation using Xslt in C#](http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63) that explains how - here's the core of it: ``` XPathDocument myXPathDoc = new XPathDocument(<xml file path>); XslTransform myXslTrans = new XslTransform(); myXslTrans.Load(<xsl file path>); XmlTextWriter myWriter = new XmlTextWriter("result.html", null); myXslTrans.Transform(myXPathDoc, null, myWriter); ``` (**Edit**: Note to @John: that code illustrates the basic idea. It doesn't pretend to be production quality.)
So, I found the answer, and pretty quickly... Its all explained here... <http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63>
XSLT and XML Question
[ "", "c#", ".net", "xml", "xslt", "" ]
I'm fairly new to PHP so I have a small problem as I'm learning: I built a Class called DataStrip.php ``` <?php final class DataStrip { public function DataStrip() { // constructor } public function stripVars($vars) { return $vars; } } ?> ``` and then I'm trying to pass the public function stripVars a value: ``` <?php include_once ('lib/php/com/DataStrip.php'); echo($projCat); $a = new DataStrip; $a->stripVars($projCat); echo($a); ?> ``` however, I get back this error: > ( ! ) Catchable fatal error: Object of class DataStrip could not be converted to string in *myfilepath* ... any advice perhaps on what I could be doing wrong here? Right now this is just a test function as I'm trying to get used to OOP PHP. :)
What do you expect it to happen? You're not saving the result of what stripVars returns into a variable: ``` $result = $a->stripVars($projCat); print $result; ``` What you are trying to do is print the object variable itself. If you want to control what happens when you try to print an object, you need to define the [`__toString` method](http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring).
if you want to do that... you need declarate the method \_\_toString() ``` <?php final class DataStrip { private $vars; public function DataStrip() { // constructor } public function stripVars($vars) { $this->vars = $vars; } public function __toString() { return (string) $this->vars; } } // then you can do $a = new DataStrip; $a->stripVars($projCat); echo($a); ?> ```
PHP Class won't return to a String
[ "", "php", "oop", "class", "return", "" ]
This question really is kinda pointless, but I'm just curious: This: ``` public sealed class MyClass { protected void MyMethod(){} } ``` compiles, but gives a warning while This: ``` public sealed class MyClass { public virtual void MyMethod(){} } ``` doesn't compile. Just out of sheer curiosity, is there a reason for this?
The only reason I can think of is that sometimes you would need to write protected methods to override other protected methods. The language *could* have been designed to allow this: ``` protected override void Foo() ``` but not this ``` protected void Foo() ``` but that might have been seen to be a little hard to follow - it's the *absence* of `override` which makes it useless, whereas in the case of ``` public virtual void Foo() ``` it's the *presence* of `virtual` that is useless. The presence of something "wrong" is probably easier to understand than the absence of something useful. In this case, being virtual may also have performance implications, whereas making something protected instead of private probably doesn't - so it's a bit more severe. These are just guesses though really - if we're really lucky, Eric Lippert will give a more definitive answer. He's the one you want, not me :) Best answer: treat warnings as errors and they're equivalent anyway ;)
[virtual](http://msdn.microsoft.com/en-us/library/9fkccyh4(VS.80).aspx) is used to declare a method/property "override-able". [sealed](http://msdn.microsoft.com/en-us/library/88c54tsw(VS.71).aspx) is used to declare that class cannot be inherited from. So a virtual method in a sealed class could never be overridden, as the class could never be inherited from. It just doesn't make sense. [protected](http://msdn.microsoft.com/en-us/library/bcd5672a(VS.71).aspx) affects access to a member, it does not declare it "override-able" as virtual does (though it is often used in that manner) and is accordingly not contradictory.
Why does this C# class declaration compile?
[ "", "c#", ".net", "sealed", "" ]
In [this question](https://stackoverflow.com/questions/1156936/how-to-make-array-loop-faster-in-php) a code bit is presented and the questioner wants to make it faster by eliminating the use of variables. Seems to me he's looking in the wrong place, but far be it from me to know. Here's the code ``` while ($item = current($data)) { echo '<ATTR>',$item, '</ATTR>', "\n"; next($data); } ``` Seems to me that the recreation of the strings `<ATTR>` etc. -- more than once on each line and every time the line is processed -- would have a cost associated with them (both in terms of speed and memory). Or perhaps the PHP processor smart enough so that there's no penalty to not putting the strings into variables before the loop? I use variables for clarity and centralization in any case, but: **is there a cost associated with using variables, not using variables, or what?** (Anybody who wants to answer for other **similar** languages please feel free.)
If you really want to micro-optimize this way (I don't think it is that relevant or useful, btw -- but I understand it's fun ^^ ), you can have a look at a PHP extension called [Vulcan Logic Disassembler](http://derickrethans.nl/vld.php) It allows you to get the bytecode generated for a PHP script. Then, you must use a command like this one, in command line, to launch the script : ``` php -dextension=vld.so -dvld.active=1 tests/temp/temp.php ``` For instance, with this script : ``` $data = array('a', 'b', 'c', 'd'); while ($item = current($data)) { echo '<ATTR>',$item, '</ATTR>', "\n"; next($data); } ``` You will get this bytecode dump : ``` line # op fetch ext return operands ------------------------------------------------------------------------------- 8 0 EXT_STMT 1 INIT_ARRAY ~0 'a' 2 ADD_ARRAY_ELEMENT ~0 'b' 3 ADD_ARRAY_ELEMENT ~0 'c' 4 ADD_ARRAY_ELEMENT ~0 'd' 5 ASSIGN !0, ~0 9 6 EXT_STMT 7 EXT_FCALL_BEGIN 8 SEND_REF !0 9 DO_FCALL 1 'current' 10 EXT_FCALL_END 11 ASSIGN $3 !1, $2 12 JMPZ $3, ->24 11 13 EXT_STMT 14 ECHO '%3CATTR%3E' 15 ECHO !1 16 ECHO '%3C%2FATTR%3E' 17 ECHO '%0A' 12 18 EXT_STMT 19 EXT_FCALL_BEGIN 20 SEND_REF !0 21 DO_FCALL 1 'next' 22 EXT_FCALL_END 13 23 JMP ->7 37 24 RETURN 1 25* ZEND_HANDLE_EXCEPTION ``` And with this script : ``` $data = array('a', 'b', 'c', 'd'); while ($item = current($data)) { echo "<ATTR>$item</ATTR>\n"; next($data); } ``` You will get : ``` line # op fetch ext return operands ------------------------------------------------------------------------------- 19 0 EXT_STMT 1 INIT_ARRAY ~0 'a' 2 ADD_ARRAY_ELEMENT ~0 'b' 3 ADD_ARRAY_ELEMENT ~0 'c' 4 ADD_ARRAY_ELEMENT ~0 'd' 5 ASSIGN !0, ~0 20 6 EXT_STMT 7 EXT_FCALL_BEGIN 8 SEND_REF !0 9 DO_FCALL 1 'current' 10 EXT_FCALL_END 11 ASSIGN $3 !1, $2 12 JMPZ $3, ->25 22 13 EXT_STMT 14 INIT_STRING ~4 15 ADD_STRING ~4 ~4, '%3CATTR%3E' 16 ADD_VAR ~4 ~4, !1 17 ADD_STRING ~4 ~4, '%3C%2FATTR%3E%0A' 18 ECHO ~4 23 19 EXT_STMT 20 EXT_FCALL_BEGIN 21 SEND_REF !0 22 DO_FCALL 1 'next' 23 EXT_FCALL_END 24 24 JMP ->7 39 25 RETURN 1 26* ZEND_HANDLE_EXCEPTION ``` *(This ouput is with PHP 5.2.6, which is the default on Ubuntu Jaunty)* In the end , you will probably notice there is not that much differences, and that it's often really just **micro**-optimisation ^^ What might be more interesting is to look at the differences between versions of PHP : you might seen that some operations have been optimized between PHP 5.1 and 5.2, for instance. For more informations, you can also have a look at [Understanding Opcodes](http://blog.libssh2.org/index.php?/archives/92-Understanding-Opcodes.html) Have fun ! EDIT : adding another test : With this code : ``` $attr_open = '<ATTR>'; $attr_close = '</ATTR>'; $eol = "\n"; $data = array('a', 'b', 'c', 'd'); while ($item = current($data)) { echo $attr_open, $item, $attr_close, $eol; next($data); } ``` You get : ``` line # op fetch ext return operands ------------------------------------------------------------------------------- 19 0 EXT_STMT 1 ASSIGN !0, '%3CATTR%3E' 20 2 EXT_STMT 3 ASSIGN !1, '%3C%2FATTR%3E' 21 4 EXT_STMT 5 ASSIGN !2, '%0A' 23 6 EXT_STMT 7 INIT_ARRAY ~3 'a' 8 ADD_ARRAY_ELEMENT ~3 'b' 9 ADD_ARRAY_ELEMENT ~3 'c' 10 ADD_ARRAY_ELEMENT ~3 'd' 11 ASSIGN !3, ~3 24 12 EXT_STMT 13 EXT_FCALL_BEGIN 14 SEND_REF !3 15 DO_FCALL 1 'current' 16 EXT_FCALL_END 17 ASSIGN $6 !4, $5 18 JMPZ $6, ->30 26 19 EXT_STMT 20 ECHO !0 21 ECHO !4 22 ECHO !1 23 ECHO !2 27 24 EXT_STMT 25 EXT_FCALL_BEGIN 26 SEND_REF !3 27 DO_FCALL 1 'next' 28 EXT_FCALL_END 28 29 JMP ->13 43 30 RETURN 1 31* ZEND_HANDLE_EXCEPTION ``` And, with this one (concatenations instead of ',') : ``` $attr_open = '<ATTR>'; $attr_close = '</ATTR>'; $eol = "\n"; $data = array('a', 'b', 'c', 'd'); while ($item = current($data)) { echo $attr_open . $item . $attr_close . $eol; next($data); } ``` you get : ``` line # op fetch ext return operands ------------------------------------------------------------------------------- 19 0 EXT_STMT 1 ASSIGN !0, '%3CATTR%3E' 20 2 EXT_STMT 3 ASSIGN !1, '%3C%2FATTR%3E' 21 4 EXT_STMT 5 ASSIGN !2, '%0A' 23 6 EXT_STMT 7 INIT_ARRAY ~3 'a' 8 ADD_ARRAY_ELEMENT ~3 'b' 9 ADD_ARRAY_ELEMENT ~3 'c' 10 ADD_ARRAY_ELEMENT ~3 'd' 11 ASSIGN !3, ~3 24 12 EXT_STMT 13 EXT_FCALL_BEGIN 14 SEND_REF !3 15 DO_FCALL 1 'current' 16 EXT_FCALL_END 17 ASSIGN $6 !4, $5 18 JMPZ $6, ->30 26 19 EXT_STMT 20 CONCAT ~7 !0, !4 21 CONCAT ~8 ~7, !1 22 CONCAT ~9 ~8, !2 23 ECHO ~9 27 24 EXT_STMT 25 EXT_FCALL_BEGIN 26 SEND_REF !3 27 DO_FCALL 1 'next' 28 EXT_FCALL_END 28 29 JMP ->13 43 30 RETURN 1 31* ZEND_HANDLE_EXCEPTION ``` So, never much of a difference ^^
Here is an interesting one, my initial tests show that storing the newline char into a variable instead of PHP parsing it with each iteration is faster. See below: ``` $nl = "\n"; while ($item = current($data)) { echo '<ATTR>',$item, '</ATTR>',$nl; next($data); } ```
How to Make PHP Faster: Does String Creation Have No Cost?
[ "", "php", "optimization", "" ]
My team is developing Java code in a couple different IDEs, with differing numbers of columns. It's worked well so far, but we've been asked to deliver compilable code to a partner with the source limited to 80 columns. We'd like to do this as a professional courtesy, but we're not able/willing to work with 80-column limited code on a day to day basis. Are there any tools available that will take Java code, and intelligently add line breaks so that it fits within 80 characters and still compiles correctly? Ideally, I'd like it to be one more automated step in our build process, to go recursively through our source directory for .java files and produce a copy with the new formatting. I'm not interested in the virtues of 80-column code or editors that do or don't word wrap, just in seeing whether there is a quick fix that will make everyone happy without anyone having to change the way they do things.
It's not as automated as you like, but in Eclipse you could define an 80-column profile (Preferences -> Java -> Code Style -> Formatter), then in the Package Explorer, right-click on your root package, and choose Source->Format.
Intellij and eclipse and almost any IDE will do that. But... Maybe you want to ask yourself if you want to automate that, even if you do that in an automated way, let's say maven, the code could be break up in a way it's harder to read than it was before, it can be breaking in the middle of an important line or method and you don't want that even if it compiles. What we have done in the past is set a couple of .xml file with the settings of eclipse or intellij (they both allow you to export the settings), then with maven use the checkstyle plugin to enforce developers to have this settings; it will allow you to do it in a day by day basis always with a developer deciding when the code should break the line. And lastly, maybe you want to use 100 or 120, they are the new 80.
Automatically reformat long-lined Java code to 80 columns and still compile?
[ "", "java", "ide", "coding-style", "" ]
I don't really care about encoding and stuff, as long as I get back the exact same byte array. So to sum up: How do I convert a byte array into a string, and then that string back into the same byte array I started with?
The absolute safest way to convert bytes to a string and back is to use base64: ``` string base64 = Convert.ToBase64String(bytes); byte[] bytes = Convert.FromBase64String(base64); ``` That way you're guaranteed not to get "invalid" unicode sequences such as the first half of a surrogate pair without the second half. Nothing's going to decide to normalize the data into something strange (it's all ASCII). There's no chance of using code points which aren't registered in Unicode, or anything like that. Oh, and you can cut and paste without much fear, too. Yes, you end up with 4 characters for every 3 bytes - but that's a small price to pay for the knowledge that your data won't be corrupted.
You can just use the `Convert` class as below. ``` /// <summary> /// Converts a string to byte array /// </summary> /// <param name="input">The string</param> /// <returns>The byte array</returns> public static byte[] ConvertToByteArray(string input) { return input.Select(Convert.ToByte).ToArray(); } /// <summary> /// Converts a byte array to a string /// </summary> /// <param name="bytes">the byte array</param> /// <returns>The string</returns> public static string ConvertToString(byte[] bytes) { return new string(bytes.Select(Convert.ToChar).ToArray()); } /// <summary> /// Converts a byte array to a string /// </summary> /// <param name="bytes">the byte array</param> /// <returns>The string</returns> public static string ConvertToBase64String(byte[] bytes) { return Convert.ToBase64String(bytes); } ```
How can I safely convert a byte array into a string and back?
[ "", "c#", "string", "arrays", "" ]
I have a regular expression which pulls name value pairs ``` ([^=;]*)=([^;]*) "Data Source=server;Initial Database=myDB;foo=bar;" ``` That works fine and I can get to the first result using ``` m.Groups[0] // "Data Source=server" m.Groups[1] // "Data Source" m.Groups[2] // "Server" ``` How do I get to the second and third set of matches? My terminology is probably wrong, I would appreciate help with that as well. Thanks!
``` Regex r = new Regex("([^=;]*)=([^;]*)"); MatchCollection mc = r.Matches("Data Source=server;Initial Database=myDB;foo=bar;"); foreach (Match m in mc) { Console.WriteLine(m.Groups[0]); Console.WriteLine(m.Groups[1]); Console.WriteLine(m.Groups[2]); } ```
As eschneider pointed out, a regular expression in this case is a bit of overkill. TIMTOWTDI ``` string thestring ="Data Source=server;Initial Database=myDB;foo=bar;"; var keyVals = from kv in thestring.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries) select new KeyValuePair<string,string>(kv.Split('=')[0],kv.Split('=')[1]); foreach (var keyVal in keyVals) { Console.WriteLine(keyVal.Key); Console.WriteLine(keyVal.Value); } ```
Getting results from a regular expressions in c#
[ "", "c#", "regex", "" ]
A bit of help please, consider the bit of code below. ``` public class Widget { public synchronized void doSomething() { ... } } public class LoggingWidget extends Widget { public synchronized void doSomething() { System.out.println(toString() + ": calling doSomething"); super.doSomething(); } } ``` I read that when doSomething() in LoggingWidget is called, the JVM will try to acquire a lock on LoggingWidget first and then on Widget. I am curious to know the reason. Is it because the JVM knows that doSomething() has a call to super.doSomething() or because calling a subclass method will always acquire a lock on the superclass as well. Cheers
You are mistaken - the locks are obtained at the *instance* level. There is only one lock in your example because there is only one instance created when you say: ``` Widget w = new LoggingWidget ``` You can view locks (also known as *monitors*, *mutexes* or *semaphores*) as being individually "attached" to every object instance in the `JVM`. If you had another `synchronized` method on the `LoggingWidget` subclass, you would see this to be true. It would not be possible to call this (new) method and the `doSomething` method at the same time [with different threads on same object]. This also holds true for another `synchronized` method on the superclass (i.e. it is not affected in any way by methods being overridden).
``` public synchronized void doSomething() { System.out.println(toString() + ": calling doSomething"); super.doSomething(); } ``` is the same as: ``` public void doSomething() { synchronized (this) { System.out.println(toString() + ": calling doSomething"); super.doSomething(); } } ``` You're locking on the instance, not the class. So when super.doSomething() is called, you already have that instance locked.
Reentrant locking
[ "", "java", "concurrency", "locking", "reentrancy", "" ]
I'm wondering what the best way to minify and concatenate all my js scripts in one in a build process is. I've got the actual minifying working, but now need to set a reference in my html page to the minified file. In the dev version it has references to five files which get concatenated. Should I juts xmlpoke or something like that? Are there more elegant techniques?
the way i usally do it is concat all the files together, minify using yui: ``` <target name="compress-js" unless="disable.js.compression"> <java fork="true" spawn="true" jar="tools/yuicompressor-2.3.6/yuicompressor-2.3.6.jar"> <arg value="-o" /> <arg value="${js.home}/lib/lib.js" /> <arg value="${js.home}/lib/lib.js" /> </java> </target> ``` and then just have one header that references the compressed file, and used disable.js.compression in dev so that your files dont get compressed.
In your file which includes the script files, do this (using which ever server side technology you use) ``` <% if (@IS_DEV@){ %> <script src="file1"></script> ... <script src="file5"></script> <% } else { %> <script src="@MINIFIED_FILE_PATH@"></script> <% } %> ``` Then use the "replace" ant target in your build file (assuming you use ant) to replace @IS\_DEV@ and @MINIFIED\_FILE\_PATH@ ``` <replace file="yourfile.jsp" token="@IS_DEV@" value="${IS_DEV}"/> <replace file="yourfile.jsp" token="@MINIFIED_FILE_PATH@" value="${YOUR_MINIFIED_FILE_PATH}"/> ```
Integrating js in build process
[ "", "javascript", "" ]
Good day, I need to extract portion of string which can looks like this: ``` "some_text MarkerA some_text_to_extract MarkerB some_text" "some_text MarkerA some_text_to_extract" ``` I need to extract `some_text_to_extract` in both cases. `MarkerA`, `MarkerB` - predefined text strings. I tried this regexps, but with no luck: ``` ".*\sMarkerA(.*)MarkerB.*" - does not work in case 2 ".*\sMarkerA(.*)(?=MarkerB)?.*" - wrong result "some_text_to_extract MarkerB some_text" ".*\sMarkerA(.*)(?:MarkerB)?.*" - does not work at all ``` Could you please help me with this issue?
Try: ``` ".*\sMarkerA(.*?)(?=$|MarkerB)" ``` Test code: ``` #!/usr/bin/env python tests = [ ("some_text MarkerA some_text_to_extract MarkerB some_text"," some_text_to_extract "), ("some_text MarkerA some_text_to_extract"," some_text_to_extract") ] import re reg = re.compile(r".*\sMarkerA(.*?)(?=$|MarkerB)") for (input,expected) in tests: mo = reg.match(input) assert mo is not None print mo.group(1),expected assert mo.group(1) == expected ```
First, get rid of the `.*` at the beginning and the end; you don't need to match the whole string. Then use alternation to match either the ending delimiter or the end of the string. ``` "MarkerA(.*?)(?:MarkerB|$)" ```
Extract substring between two tokens. Second token could be missing
[ "", "javascript", "regex", "" ]
I found [MSVCR90D.dll not found in debug mode with Visual C++ 2008](https://stackoverflow.com/questions/218747/msvcr90d-dll-not-found-in-debug-mode-with-visual-c-2008) question but none of given answers really gives answer to the question. Most of them point to turning off incremental linking but don't explain the true cause of the error and how it can be fixed **without** turning off incremental linking. I'd like to mention that my situation is a little different than the one in the original question. I am using C++ compiler from Visual Studio 2008 but within Qt Creator not within Visual Studio. Anyone?
Below is output from compiler. It's strange that running build the second time succeeds. However I suspect the problem might be due to this error with running mt.exe which is responsible for embedding information from manifest into executable... ``` Generating Code... link /LIBPATH:"c:\Qt\4.5.2-vc\lib" /NOLOGO /DEBUG /MANIFEST /MANIFESTFILE:"debug\formExtractor.intermediate.manifest" /SUBSYSTEM:WINDOWS "/MANIFESTDEPENDENCY:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' publicKeyToken='6595b64144ccf1df' language='*' processorArchitecture='*'" /OUT:debug\formExtractor.exe @.\nmD932.tmp mt.exe -nologo -manifest "debug\formExtractor.intermediate.manifest" -outputresource:debug\formExtractor.exe;1 'mt.exe' is not recognized as an internal or external command, operable program or batch file. NMAKE : fatal error U1077: 'mt.exe' : return code '0x1' Stop. NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\nmake.exe"' : return code '0x2' Stop. Exited with code 2. ``` **UPDATE** Failing to run mt.exe during the linking process was indeed the cause of the problem. I added path to Windows SDK (`C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin`) to the PATH environment variable and I'm able to run executable now. Comments to various answers; --- @Shay Output txt file from sxstrace is empty. Have no idea why. However there's the following information in the application log: ``` Faulting application formExtractor.exe, version 0.0.0.0, time stamp 0x4a638ee1, faulting module MSVCR90D.dll, version 6.0.6002.18005, time stamp 0x49e03824, exception code 0xc0000135, fault offset 0x0006f04e, process id 0xf68, application start time 0x01ca08ba801ac5cf. ``` Version 6.0.6002.18005? What the heck is this? --- @Kirill V. Lyadvinsky Dependency Walker finds `msvcr90d.dll` used by `qtwebkit4.dll` file in `c:\windows\winsxs\x86_microsoft.vc90.debugcrt_1fc8b3b9a1e18e3b_9.0.30729.1_none_bb1f6aa1308c35eb\MSVCR90D.DLL` but doesn't find (the other version of?) `msvcr90d.dll` file linked directly by the executable. However DW doesn't seem to show it's version anywhere, does it? Contest of formExtractor.intermediate.manifest file ``` <?xml version='1.0' encoding='UTF-8' standalone='yes'?> <assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level='asInvoker' uiAccess='false' /> </requestedPrivileges> </security> </trustInfo> <dependency> <dependentAssembly> <assemblyIdentity type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' publicKeyToken='6595b64144ccf1df' language='*' processorArchitecture='*' /> </dependentAssembly> </dependency> <dependency> <dependentAssembly> <assemblyIdentity type='win32' name='Microsoft.VC90.DebugCRT' version='9.0.21022.8' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' /> </dependentAssembly> </dependency> </assembly> ``` From the manifest file it looks like the executable is being linked to a different version of `msvcr90d.dll` than the `qtwebkit4.dll`. What's strange is the fact that both versions of `msvcr90d.dll` are present in `c:\windows\winsxs` folder in the following sub folders `x86_microsoft.vc90.debugcrt_1fc8b3b9a1e18e3b_9.0.21022.8_none_96748342450f6aa2` and `x86_microsoft.vc90.debugcrt_1fc8b3b9a1e18e3b_9.0.30729.1_none_bb1f6aa1308c35eb` Any ideas? --- @knight666 I'm using Qt framework which I compiled using exactly the compiler I'm using now so I think there's no mismatch here. Additionally Dependency Walker shows the missing `msvcr90d.dll` file is linked **directly** to the executable so it's not a fault of any 3rd party library I think.
Simply installing VS2008 Service Pack 1 will fix the problem, if it's an error where the Debug CRT is totally missing from the sxs folder. I had this happen to me with a fresh install of VS2008 on 64 bit Windows 7 and a solution containing a VC++ project. The debug build would crash when the C++ assembly was loaded at runtime, with a side-by-side error. On Vista and Win7 (but not XP) the SxS error gives details about exactly what assembly it tried and failed to load - in this case it was VC90.DebugCRT 9.0.22.19. I checked the (embedded) manifest for the VC assembly and sure enough, it included a reference to this assembly and version. Checking the sxs directory (%System Drive%\Windows\WinSxS) showed that there was no VC90 DebugCRT installed in side-by-side at all! I had installed the VC++ runtimes, but these don't include a debug runtime. VS2008 is meant to install a debug runtime, but it wasn't there. Turns out the original release of VS2008 [doesn't install](http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/8f08777b-1c4d-4e10-89a2-f7bc95cf5e98/#63c7a0d9-c525-46ef-ac1e-3726976d2193) a 64 bit VC++ DebugCRT, but installing SP1 does. Once I'd done this, no more runtime exceptions and side-by-side errors.
msvcr90d.dll not found in debug mode
[ "", "c++", "visual-studio-2008", "visual-c++", "linker", "msvcr90d.dll", "" ]
How to show and hide div every 1min in jquery
Give a look to the [setInterval](https://developer.mozilla.org/En/Window.setInterval) core function and to the jQuery's [Effects/toggle](http://docs.jquery.com/Effects/toggle) function: ``` setInterval(function(){$('#myDiv').toggle();}, 60000); ```
Try this: ``` setInterval(function() { $("#myDiv").toggle(); }, 60000); ```
show and hide div every 1min
[ "", "javascript", "jquery", "html", "" ]
In hibernate, is it possible to define a mapping for a class to a set of enums? I've been able to find examples of how to define mappings of Sets and I've been able to find separate examples for how to map Enums, but I cannot figure out how to define a of Enums for a class. Could anyone please provide me with an example? This is being built on top of an existing application, so I cannot alter the database schema. This is the relation I wish to model. Wicket is a normal class and WicketType is a Java Enum. ``` +----------------+ +------------+ +------------+ | Wicket | | Ref Table | | WicketType | +----------------+ +------------+ +------------+ | INT | W_ID | | | | W_TypeId | | .... | | FK | W_ID | FK | WicketType | | INT | TYPE |----| W_TypeId |----| | +----------------+ +------------+ +------------+ ``` Thanks again
Does [this](http://web.archive.org/web/20080518065304/http://www.hibernate.org/312.html) not do what you need? To elaborate on the flippant initial response, the reference provides a means to use the ordinal of the enum to map enumerations. In this case it's actually simpler than it looks, because you are hosting the enums in a set, you need to provide an accessor for the WicketType to the sub-type of IntEnumUserType, the super-type will take care of mapping the ordinal to the instance. ``` package test; public class WicketTypeState extends IntEnumUserType<WicketType> { private WicketType wicketType; public WicketTypeState() { // we must give the values of the enum to the parent. super(WicketType.class, WicketType.values()); } public WicketType getWicketType() { return wicketType; } public void setWicketType(final WicketType wicketType) { this.wicketType = wicketType; } } ``` Define the mappings for the enum table: ``` <hibernate-mapping package="test"> <class name="Wicket" table="Wicket"> <id name="id" column="ID"/> <set name="wicketTypes" table="WicketType" inverse="true"> <key column="ID"/> <one-to-many class="test.WicketTypeState"/> </set> </class> </hibernate-mapping> ``` Then for the type with the set of enums, define a set mapping for that property: ``` <hibernate-mapping package="test"> <class name="WicketTypeState" lazy="true" table="WicketType"> <id name="WicketType" type="test.WicketTypeState"/> </class> </hibernate-mapping> ``` This worked on my box(tm), let me know if you need any more info.
A simpler way is ``` <typedef name="WicketTypeType" class="org.hibernate.type.EnumType"> <param name="enumClass">Wicket</param> <param name="type">12</param> </typedef> <class name="Wicket"... <set name="WicketType" table="Ref Table"> <key column="W_ID" /> <element column="W_TypeID" type="WicketTypeType"/> </set> ... </class> ```
How to map a set of enum type in Hibernate?
[ "", "java", "hibernate", "orm", "nhibernate-mapping", "" ]
I have table named **'Dictionary'** with columns as follow: * ID bigint * TYPE varchar (200) * ITEM varchar (200) Table is used by various tables as simple dictionary / lookup. Eg it stores countries, titles, business type lists. **TYPE** column keeps info about type of dictionary , **ITEM** is dictionary string value. All works well but **I have problem to set up relationship between dictionary and foreigin tables.** When I'm using 'Foreign Key Relationship' I can not make it depended of 'TYPE" column. *(Please note same item with same type - eg 'countries' can be linked to several tables, when item with another type can be linked to different)* Currently I'm using USPs to manage that but I'd like to switch to standard relationship mechanism. Any advice how to get that?
It looks to me that you could consider an alternative design ``` Dictionary table ID (pk) DICTIONARY_TYPE_ID (fk to dictionaryType) ITEM DictionaryType table ID (pk) DESCRIPTION ``` and then make links to the **ID** of **DictionaryType** table in places where you currently want to reference **Type** field from your original design
From the context of the question, I'm guessing you'll need to do one of two things: * Make your `Type` column the primary key * or have the foreign keys depend on the `ID` field here. Foreign keys need to refer to a primary key, and it looks like your `Type` column isn't a PK.
Dictionary table relationships (MS SQL 2005)
[ "", "sql", "sql-server", "sql-server-2005", "foreign-key-relationship", "relationship", "" ]
Is there a way to reduce the capacity of a vector ? My code inserts values into a vector (not knowing their number beforehand), and when this finishes, the vectors are used only for read operations. I guess I could create a new vector, do a .reseve() with the size and copy the items, but I don't really like the extra copy operation. PS: I don't care for a portable solution, as long as it works for gcc.
``` std::vector<T>(v).swap(v); ``` Swapping the contents with another vector swaps the capacity. ``` std::vector<T>(v).swap(v); ==> is equivalent to std::vector<T> tmp(v); // copy elements into a temporary vector v.swap(tmp); // swap internal vector data ``` Swap() would only change the internal data structure.
With C++11, you can call the member function `shrink_to_fit()`. The [draft standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2798.pdf) section 23.2.6.2 says: > `shrink_to_fit` is a non-binding request > to reduce `capacity()` to `size()`. *[Note: The request is non-binding to > allow latitude for > implementation-specific optimizations. > —end note]*
How to reduce the capacity of a std::vector
[ "", "c++", "stl", "stdvector", "" ]
I got a pack of c++ files with static source code (already developped, not needed to do anything to them). There is an program/lib/way to get a list of the number of params each function withing one of those files? I mean, getting a result like: ``` #File a.cpp ##a() -> 3 paramss ##foo() -> 0 params (void) #File b.cpp ##test() -> 1 param .... ``` And a better question. There is any way to also process the number of returns it has? ``` #File a.cpp ##a() -> 3 params, 1 return ##foo() -> 0 params (void), 2 returns ``` For example if "foo" has a return if condition is true and another if false Thanks in advance.
You could try running [Doxygen](http://www.doxygen.nl/) over the source files. Since the content is (presumably) undocumented, you need to [configure](http://www.doxygen.nl/manual/starting.html#extract_all) doxygen to extract content from undocumented files. If you just want to browse a list of the available functions, you could use the HTML output. You could also configure Doxygen output to be XML, and then write a parser to pull statistics that you are looking for on each function.
I would count the number of "," and start at 1. This should give you an accurate count of the number of arguments to a function. Then I would check to see if "void" exists before the function name, if not then you can bet that there is a return value. ``` ifstream infile; infile.open(...); int i, ret, args; String s; ret = args = 0; s = infile.getline(); for( i=0; s[i] != '('; i++ ) { if( s[i] == 'v' && s[i+1] == 'o' && s[i+2] == 'i' && s[i+3] == 'd' ) { ret = 1; break; } } for( i=0; s[i] != '('; i++ ) {} for( i; s[i] != ')'; i++ ) { if( args == 0 && s[i] != ' ' ) { args++; } if( s[i] == ',' ) { args++; } } ```
C++ file parse number of arguments
[ "", "c++", "parsing", "numbers", "param", "" ]
An abstract function must be implemented by all concrete classes. Sometimes you want to force all derivative classes to implement the abstract function, even derivatives of concrete classes. ``` class Base { protected abstract Base Clone(); } class Concrete : Base { protected override Base Clone(){...}; } class Custom : Concrete {} ``` I would like the compiler to tell the programmer that the class `Custom` needs to implement `Clone()`. Is there way?
It's not possible for the compiler to enforce this. You might look at writing your own analysis plugin to [Gendarme](http://mono-project.com/Gendarme) or [FxCop](http://msdn.microsoft.com/en-us/library/bb429476(VS.80).aspx) to enforce such requirements.
I would guess you don't really need ALL derived classes to implement the abstract method, but it definitely sounds like you have a bit of a code smell in your design. If you don't have any functionality in the Concrete.Clone() method, then you can make your 'Concrete' class abstract as well (just be sure to change the name ;-). Leave out any reference of the Clone() method. ``` abstract class Base { protected abstract void Clone(); } abstract class Concrete : Base { } class Custom : Concrete { protected override void Clone() { /* do something */ } } ``` If you have some basic functionality in the Concrete.Clone() method, but need detailed information from a higher level, then break it out into it's own abstract method or property forcing a higher level implementation to supply this information. ``` abstract class Base { protected abstract void Clone(); } abstract class ConcreteForDatabases : Base { protected abstract string CopyInsertStatemement {get;} protected override void Clone() { // setup db connection & command objects string sql = CopyInsertStatemement; // process the statement // clean up db objects } } class CustomBusinessThingy : ConcreteForDatabases { protected override string CopyInsertStatemement {get{return "insert myTable(...) select ... from myTable where ...";}} } ```
How can I force all derived classes to implement an abstract method or property?
[ "", "c#", ".net", "rules", "" ]
I am a newbie in GWT, and also to Swing/SWT style interface building. I have worked with HTML for a long time, and I know how to build my UIs in that. However, I am having trouble translating this to GWT. What I am trying to make currently, is a simple UI with a table on the left with 4 columns, heading and a caption, and a panel on the right with an input and some dropdowns (filters for the list on the left). I have made this as a mockup in HTML, but I am having trouble translating this into GWT. Each row in the table should also have a select link for selecting an item in the table. I know of [UiBinder](http://code.google.com/p/google-web-toolkit-incubator/wiki/UiBinder), but seeing as there has been a page for it since december, and it's still not out, it doesn't seem like a viable option. I would love it if I could convert my HTML to some GWT code, but it seems like the stuff that exists in GWT is at a bit higher level of abstraction. It also seems hard to use DOM.createElement stuff combined with widgets, ie. creating my own custom panel.
The trick with GWT or Swing GUIs is to visualize your intended layout as a combination of the toolkit's layout widgets, nested inside each other. Based on your description, here's a high level view of how you might compose your GUI: Start with a [HorizontalSplitPanel](http://gwt.google.com/samples/Showcase/Showcase.html#CwHorizontalSplitPanel) for the highest level. For the left side (the table:) Create a [VerticalPanel](http://gwt.google.com/samples/Showcase/Showcase.html#CwVerticalPanel) and add 3 widgets to it - a image or html literal for the header, then a Grid with 4 columns for the table itself, then another image or literal for the caption. Add this vertical panel to the left side of the split panel (Alternatively, you might get away with one big [FlexTable](http://gwt.google.com/samples/Showcase/Showcase.html#CwFlexTable) for the entire left side. Especially if you're looking to emulate HTML tables with colspans and such) For the right side: Create a VerticalPanel, and just add headers, dropdowns, and text inputs as necessary. Alternatively, you could create a Grid if you want labels on the side of each dropdown or text input Add this right side panel to the right side of the HorizontalSplitPanel
What you're describing seems to be quite easily available in GWT, with the built-in panels. I suggest you take a look at [the GWT showcase](http://gwt.google.com/samples/Showcase/Showcase.html#CwDockPanel), and view the source to see how it's done. --- # Dock panel sample ![Dock panel screenshot](https://i.stack.imgur.com/6pFEd.png) ``` DockPanel dock = new DockPanel(); dock.setStyleName("cw-DockPanel"); dock.setSpacing(4); dock.setHorizontalAlignment(DockPanel.ALIGN_CENTER); // Add text all around dock.add(new HTML(constants.cwDockPanelNorth1()), DockPanel.NORTH); dock.add(new HTML(constants.cwDockPanelSouth1()), DockPanel.SOUTH); dock.add(new HTML(constants.cwDockPanelEast()), DockPanel.EAST); dock.add(new HTML(constants.cwDockPanelWest()), DockPanel.WEST); dock.add(new HTML(constants.cwDockPanelNorth2()), DockPanel.NORTH); dock.add(new HTML(constants.cwDockPanelSouth2()), DockPanel.SOUTH); // Add scrollable text in the center HTML contents = new HTML(constants.cwDockPanelCenter()); ScrollPanel scroller = new ScrollPanel(contents); scroller.setSize("400px", "100px"); dock.add(scroller, DockPanel.CENTER); ```
GWT panel design best practices
[ "", "java", "gwt", "" ]
Is there a jUnit parallel to NUnit's [`CollectionAssert`](http://www.nunit.org/index.php?p=collectionAssert&r=2.4)?
Using JUnit 4.4 you can use `assertThat()` together with the [Hamcrest](http://hamcrest.org/JavaHamcrest/) code (don't worry, it's shipped with JUnit, no need for an extra `.jar`) to produce complex self-describing asserts including ones that operate on collections: ``` import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.*; import static org.hamcrest.CoreMatchers.*; List<String> l = Arrays.asList("foo", "bar"); assertThat(l, hasItems("foo", "bar")); assertThat(l, not(hasItem((String) null))); assertThat(l, not(hasItems("bar", "quux"))); // check if two objects are equal with assertThat() // the following three lines of code check the same thing. // the first one is the "traditional" approach, // the second one is the succinct version and the third one the verbose one assertEquals(l, Arrays.asList("foo", "bar"))); assertThat(l, is(Arrays.asList("foo", "bar"))); assertThat(l, is(equalTo(Arrays.asList("foo", "bar")))); ``` Using this approach you will automagically get a good description of the assert when it fails.
Not directly, no. I suggest the use of [Hamcrest](http://hamcrest.org/JavaHamcrest/), which provides a rich set of matching rules which integrates nicely with jUnit (and other testing frameworks)
CollectionAssert in jUnit?
[ "", "java", "junit", "nunit", "assertion", "" ]
Before I start, I want to point out that I'm pretty sure this actually happened. All my logs suggest that it did. **I'd like to know whether I'm wrong and this is impossible, whether it's just incredibly unlikely (which I suspect), or if it's not that unlikely and I'm doing something fundamentally wrong.** I have 4 instances of the same code running as Windows Services on the same server. This server has a multicore (4) processor. Here's a summary of the code: ``` public class MyProcess { private System.Timers.Timer timer; // execution starts here public void EntryPoint() { timer = new System.Timers.Timer(15000); // 15 seconds timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed); timer.AutoReset = false; Timer_Elapsed(this, null); } private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { string uid = GetUID(); // this bit of code sends a message to an external process. // It uses the uid as an identifier - these shouldn't clash! CommunicationClass.SendMessage(uid); timer.Start(); } // returns an 18 digit number as a string private string GetUID() { string rndString = ""; Random rnd = new Random((int)DateTime.Now.Ticks); for (int i = 0; i < 18; i++) { rndString += rnd.Next(0, 10); } return rndString; } ``` The external process that receives these messages got confused - I think because the same uid came from two separate processes. Based on that, it appears that the `GetUID()` method returned the same "random" 18 digit string for two separate processes. I've seeded the Random class using DateTime.Now.Ticks which I thought would provide protection between threads - one tick is 100 nanoseconds, surely two threads couldn't get the same seed value. What I didn't account for obviously is that we're not talking about threads, we're talking about processes on a multicore processor. That means that this code can **literally** run twice at the same time. I think that's what's caused the clash. **Two processes running the same code at approximate 15 second intervals managed to hit the same code inside 100 nanoseconds. Is this possible? Am I on the right track here?** I'd be grateful for your thoughts or suggestions. --- To clarify, I can't really use a GUID - the external process I'm communicating with needs an 18 digit number. It's old, and I can't change it unfortunately.
You don't want **random** numbers for this purpose, you want **unique** numbers. I'm with @JP. I think you should look at using GUIDs for your message ids. **EDIT**: if you can't use a GUID, then think of a way to get a 64-bit number that is unique and use successive 3-bit chunks of it as an index into a 8-character alphabet (tossing the unused upper bits). One way to do this would be to have a database in which you create an entry for each new message with an auto-incremented 64-bit integer as the key. Use the key and translate it into your 18-character message id. If you don't want to rely on a database you can get something that works under certain conditions. For example, if the messages only need to be unique during the life of the processes, then you could use the process id as 32 bits of the value and get the remaining 22 required bits from a random number generator. Since no two processes running at the same time can have the same id, they should be guaranteed to have unique message ids. There are undoubtedly many other ways that you could do this if your situation doesn't fit into one of the above scenarios.
Unless there is some reason you can't, you should look at using a [GUID](http://msdn.microsoft.com/en-us/library/system.guid.newguid.aspx) for this purpose. You will eliminate collisions that way. Per comment: You could use a GUID and a 64-bit [FNV hash](http://isthe.com/chongo/tech/comp/fnv/) and use [XOR-folding](http://isthe.com/chongo/tech/comp/fnv/#xor-fold) to get your result to within the 59-bits that you have. Not as collision proof as a GUID, but better than what you have.
Random number clashes with same .Net code in different processes
[ "", "c#", ".net", "multithreading", "random", "multicore", "" ]
I'm new to c++ and i want to compile my testprogram . i have now 3 files **"main.cpp" "parse.cpp" "parse.h"** how can i compile it with one command?
Compile them both at the same time and place result in a.out ``` $ g++ file.cpp other.cpp ``` Compile them both at the same time and place results in prog2 ``` $ g++ file.cpp other.cpp -o prog2 ``` Compile each separately and then link them into a.out ``` $ g++ -c file.cpp $ g++ -c other.cpp $ g++ file.o other.o ``` Compile each separately and then link them into prog2 ``` $ g++ -c file.cpp $ g++ -c other.cpp $ g++ file.o other.o -o prog2 ```
Typically you will use the [make utility](http://unixhelp.ed.ac.uk/CGI/man-cgi?make) with a makefile. [Here is a tutorial](http://www.opussoftware.com/tutorial/TutMakefile.htm). If you only want a simple compilation though you can just use gcc directly... You don't specify the .h files as they are included by the .cpp files. > gcc a.cpp b.cpp -o program.out > ./program.out
compiling c++ with gcc/g++ compiler
[ "", "c++", "c", "gcc", "programming-languages", "" ]
I like Microsoft's Windows Forms tree-view object model. It has the tree, nodes, children collection, parent, prev, next (sibling), etc. and search function. However I'm looking for the same object model with no UI - simply tree object model. Does C# have this kind of model or do I have to implement it myself?
C# is a programming language. It does not have object models. You may be asking whether the .NET Framework has a built-in "tree" class. It does not. You can build your own using the generic collection classes like `LinkedList<T>` and `List<T>`.
You could always use XML and the XML namespaces. It's got all the things you requested. Start with and XMLDocument and keep added XMLNodes and adding XMLNodes to the XMLNodes for children. Then you can use xpath queries to retrieve nodes.
.NET tree object model
[ "", "c#", "treeview", "object-model", "" ]
I implemented a python com server and generate an executable and dll using py2exe tool. then I used regsvr32.exe to register the dll.I got a message that the registration was successful. Then I tried to add reference to that dll in .NET. I browsed to the dll location and select it, but I got an error message box that says: A reference to the dll could not be added, please make sure that the file is accessible and that it is a valid assembly or COM component.The code of the server and setup script is added below. I want to mention that I can run the server as a python script and consume it from .net using late binding. Is there something I'm missing or doing wrong? I would appreciate any help. thanks, Sarah # hello.py ``` import pythoncom import sys class HelloWorld: #pythoncom.frozen = 1 if hasattr(sys, 'importers'): _reg_class_spec_ = "__main__.HelloWorld" _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER _reg_clsid_ = pythoncom.CreateGuid() _reg_desc_ = "Python Test COM Server" _reg_progid_ = "Python.TestServer" _public_methods_ = ['Hello'] _public_attrs_ = ['softspace', 'noCalls'] _readonly_attrs_ = ['noCalls'] def __init__(self): self.softspace = 1 self.noCalls = 0 def Hello(self, who): self.noCalls = self.noCalls + 1 # insert "softspace" number of spaces print "Hello" + " " * self.softspace + str(who) return "Hello" + " " * self.softspace + str(who) if __name__=='__main__': import sys if hasattr(sys, 'importers'): # running as packed executable. if '--register' in sys.argv[1:] or '--unregister' in sys.argv[1:]: # --register and --unregister work as usual import win32com.server.register win32com.server.register.UseCommandLine(HelloWorld) else: # start the server. from win32com.server import localserver localserver.main() else: import win32com.server.register win32com.server.register.UseCommandLine(HelloWorld) ``` # setup.py ``` from distutils.core import setup import py2exe setup(com_server = ["hello"]) ```
I will answer my question to help any one may have similar questions. I hope that would help. I can not find my server on the COM tab because, .NET (& Visual-Studio) need COM servers with TLB. But Python's COM servers have no TLB. So to use the server from .NET by (C# and Late binding). The following code shows how to make this: // the C# code ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Type pythonServer; object pythonObject; pythonServer = Type.GetTypeFromProgID("PythonDemos.Utilities"); pythonObject = Activator.CreateInstance(pythonServer); } } } ` ```
The line: ``` _reg_clsid_ = pythoncom.CreateGuid() ``` creates a new GUID everytime this file is called. You can create a GUID on the command line: ``` C:\>python -c "import pythoncom; print pythoncom.CreateGuid()" {C86B66C2-408E-46EA-845E-71626F94D965} ``` and then change your line: ``` _reg_clsid_ = "{C86B66C2-408E-46EA-845E-71626F94D965}" ``` After making this change, I was able to run your code and test it with the following VBScript: ``` Set obj = CreateObject("Python.TestServer") MsgBox obj.Hello("foo") ``` I don't have MSVC handy to see if this fixes the "add reference" problem.
using registered com object dll from .NET
[ "", ".net", "python", "com", "py2exe", "" ]
I am just confused with the execution sequence of a SQL query when we use `GROUP BY` and `HAVING` with a `WHERE` clause. Which one gets executed first? What is the sequence?
in order: > **FROM** & **JOIN**s determine & filter rows > **WHERE** more filters on the rows > **GROUP BY** combines those rows into groups > **HAVING** filters groups > **ORDER BY** arranges the remaining rows/groups > **LIMIT** filters on the remaining rows/groups
Here is the complete sequence for sql server : ``` 1. FROM 2. ON 3. JOIN 4. WHERE 5. GROUP BY 6. WITH CUBE or WITH ROLLUP 7. HAVING 8. SELECT 9. DISTINCT 10. ORDER BY 11. TOP ``` So from the above list, you can easily understand the execution sequence of **`GROUP BY, HAVING and WHERE`** which is : ``` 1. WHERE 2. GROUP BY 3. HAVING ``` [**Get more information about it from Microsoft**](https://learn.microsoft.com/en-us/sql/t-sql/queries/select-transact-sql#logical-processing-order-of-the-select-statement) [More explanation](https://stackoverflow.com/a/47002068/5695953)
Execution sequence of Group By, Having and Where clause in SQL Server?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I iterate through a tree structure to collect the paths of the leaf nodes. Which way do you prefer to collect the result of the operation: a) merge the results of the children and return this ``` private Collection<String> extractPaths(final Element element, final IPath parentPath) { final IPath path = parentPath.append(element.getLabel()); final Collection<Element> children = getElementChildren(element); if (children.isEmpty()) return Collections.singletonList(path.toString()); final Set<String> result = new TreeSet<String>(); for (final Element child : children) result.addAll(extractPaths(child, path)); return result; } ``` b) provide the result collection as a parameter and add new elements in each recursion step ``` private void extractPaths(final Element element, final IPath parentPath, final Set<String> result) { final IPath path = parentPath.append(element.getLabel()); final Collection<Element> children = getElementChildren(element); if (children.isEmpty()) result.add(path.toString()); for (final Element child : children) extractPaths(child, path, result); } ```
The final solution I found after some refactoring is to implement variant b) but to pass a Visitor instead of the result collection: ``` private void traverse(final Element element, final Visitor... visitors) { for (final Visitor visitor : visitors) // push e.g. the parent path to the stack visitor.push(visitor.visit(element)); for (final Element child: getElementChildren(element)) traverse(child, visitors); for (final Visitor visitor : visitors) visitor.pop(); } ``` The Visitor provides also a stack to carry the information about the parent path. This solution allows me to separate the traversal logic from the collection logic, without the need of the more complex TreeIterator implementation. ``` private class CollectPathsVisitor extends ElementVisitor { public final Set<String> paths = new TreeSet<String>(); public Object visit(Element element) { final IPath parentPath = (IPath) peek(); final IPath path = parentPath.append(element.getLabel()); if (!hasChildren(element)) paths.add(path); return path; } } ```
Both can be used without any problems. Though, former solution is more clean since it doesn't change input parameters. No side effects is in the nature of functional programming.
How to collect the result of a recursive method
[ "", "java", "recursion", "" ]