Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm trying to edit a textbox's text in a Page\_Load form on an ASP.NET page, but when I try to edit TextBox1.Text it throws a NullReferenceException because the TextBox has not yet been instantiated. Specifically what I'm trying to implement is this: <http://www.codeproject.com/KB/user-controls/popupcalendarcontrol.aspx> but it is written for an older version of ASP.NET and does not work for me. Is there a way to instantiate the controls at the start of Page\_Load? or another event that I can catch on load? With a normal windows form I would call InitializeComponent() in the constructor.
There are absolutely different events you can attach to but it sounds like the page isn't loading the controls properly because they should be available by that point. You can take a look at the [ASP.NET Page Life Cycle](http://msdn.microsoft.com/en-us/library/ms178472.aspx) for more information.
Does the TextBox sit within a bound control, such as a FormView, GridView, DataList, etc? If so, then the control won't exist until after the databinding happens. Once that event happens, you can do something like > `DirectCast(myDataList.SelectedRow.FindControl("myTextBox"), > TextBox).Text`
NullReferenceException on Page_Load
[ "", "c#", "asp.net", "" ]
How can you get the FQDN of a local machine in C#?
*NOTE: This solution only works when targeting the .NET 2.0 (and newer) frameworks.* ``` using System; using System.Net; using System.Net.NetworkInformation; //... public static string GetFQDN() { string domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName; string hostName = Dns.GetHostName(); domainName = "." + domainName; if(!hostName.EndsWith(domainName)) // if hostname does not already include domain name { hostName += domainName; // add the domain name part } return hostName; // return the fully qualified name } ``` **UPDATE** Since a lot of people have commented that [Sam's Answer](https://stackoverflow.com/a/17079669/63074) is more concise I've decided to add some comments to the answer. The most important thing to note is that the code I gave is **not equivalent** to the following code: ``` Dns.GetHostEntry("LocalHost").HostName ``` While in the general case when the machine is networked and part of a domain, both methods will generally produce the same result, in other scenarios the results will differ. A scenario where the output will be different is when the machine is not part of a domain. In this case, the `Dns.GetHostEntry("LocalHost").HostName` will return `localhost` while the `GetFQDN()` method above will return the NETBIOS name of the host. This distinction is important when the purpose of finding the machine FQDN is to log information, or generate a report. Most of the time I've used this method in logs or reports that are subsequently used to map information back to a specific machine. If the machines are not networked, the `localhost` identifier is useless, whereas the name gives the needed information. So ultimately it's up to each user which method is better suited for their application, depending on what result they need. But to say that this answer is wrong for not being concise enough is superficial at best. See an example where the output will be different: <http://ideone.com/q4S4I0>
A slight simplification of Miky D's code ``` public static string GetLocalhostFqdn() { var ipProperties = IPGlobalProperties.GetIPGlobalProperties(); return string.Format("{0}.{1}", ipProperties.HostName, ipProperties.DomainName); } ```
How to find FQDN of local machine in C#/.NET ?
[ "", "c#", "localhost", "fqdn", "" ]
UPDATE: So pretty much everyone here has told me that I just need to start all over again on how I designed my classes (thank you folks for your excellent answers by the way!). Taking the hint, I started doing extensive reading on the [strategy pattern](http://www.dofactory.com/Patterns/PatternStrategy.aspx). I want to create behavior classes (or strategy classes) that inherit from an abstract base class or classes. The Candidate class would then have properties w/ the different abstract base class/classes as the `Type` for the behaviors or strategies. maybe something like this: ``` public abstract class SalaryStrategy { public abstract decimal Salary { get; set; } public abstract decimal Min { get; set; } public abstract decimal Mid { get; set; } public decimal CompaRatio { get { if (this.Mid == 0) { return 0; } else { return this.Salary / this.Mid; } } } } public class InternalCurrentSalaryStrategy { public override decimal Salary { get; set; } public override decimal Min { get { return this.Salary * .25m; } set { } } public override decimal Mid { get; set; } } public class Candidate { public int Id { get; set; } public string Name { get; set; } public SalaryStrategy CurrentSalaryStrategy { get; set; } } public static void Main(string[] args) { var internal = new Candidate(); internal.CurrentSalaryStrategy = new InternalCurrentSalaryStrategy(); var internalElp = new Candidate(); internalElp.CurrentSalaryStrategy = new InternalCurrentSalaryStrategy(); var elp = new Candidate(); // elp.CurrentSalaryStrategy can stay null cause it's not used for elps } ``` Any comments or suggestions? --- ORIGINAL Question: I am trying to learn and become more proficient at design patterns and principles. I have am currently working on a design for few classes that has stumped me. Here's a very condensed version of the code: ``` public class Candidate { public int Id { get; set; } public string Comments { get; set; } // lots more properties and behaviors... } public class InternalCandidate : Candidate { public decimal CurrentMid { get; set; } public decimal CurrentMax { get { return this.CurrentMin * 1.3m; } // lots more properties and behaviors... } public class EntryLevelCandidate : Candidate { public string Gpa { get; set; } // lots more properties and behaviors... } public class InternalEntryLevelCandidate /* what do I inherit here??? */ { // needs all of the properties and behaviors of // EntryLevelCandidate but also needs the CurrentMin and // CurrentMax (and possibly more) in InternalCandidate } ``` The InternalEntryLevelCandidate class is primarily an EntryLevelCandidate but needs to share some of the *implementations* of InternalCandidate. I say implementations because I don't want the implementations to be different or repeated, otherwise I would use an interface for common contracts and have concrete implementations in each class. Some of the implementations of the InternalCandidate properties and behaviors need to be common or shared. I have read about C++ and Ruby mixins, which seem to be something similar to what I want to do. I also read this interesting blog post that discusses an idea for a behavior type where a class would be able to inherit multiple behaviors while still maintaining a single "is a" relationship: <http://www.deftflux.net/blog/post/A-good-design-for-multiple-implementation-inheritance.aspx>. This seems to convey what I am wanting. Can anyone give me some direction on how I can accomplish this using good design practices?
**Immutable data value classes.** If any **properties** in your various Candidate subclasses represent some kind of meaningful data value, create an immutable class for it, with the behaviors you need. Each of your distinct Candidate subclasses can then use the data type, but your code is still encapsulated in the data classes. **Extension methods.** These could be overloaded to work with any classes. I'd avoid the decorator pattern and stick with compiled/reflectable functionality. **Composition.** Develop the unique behaviors in separate classes right away, and build your Candidate classes around them, rather than writing unique behaviors in your Candidate classes and trying to pull out their functionality for use in related classes later. Depending on how you use the classes, you could also implement and make use of explicit and implicit conversion operators to a related type, so instead of reimplementing interfaces (which you wanted to avoid), you could actually cast your object into the type/implementation you need for whatever purpose. Another thing I just thought of, related to that last paragraph, is to have a leasing system, where your class spawns and object of the appropriate type, allows it to be manipulated, then consumes it later to assimilate the updated information.
Here's a scholarly paper on the subject that I think is pretty interesting ([PDF link](http://users.jyu.fi/~sakkinen/inhws/papers/Crespo.pdf)). But, I think you are trying to impose *business logic* in your generalizations. You happen to know that an InternalCandidate will never have his GPA looked at. But, an InternalCandidate certainly has a GPA. So, you have cracked out this strange guy called an InternalEntryLevelCandidate because you happen to know that you want to look at this guy's GPA. Architecturally, I think the EntryLevelCandidate is incorrect. I would add a "Level" concept to a Candidate and give him a GPA. It's up to the *business logic* to decide if they look at the GPA or not. Edit: Also, [Scott Meyers](http://www.aristeia.com/effective-c++.html) does a great job of dissecting this issue in his books.
How To Implement Shared Behavior Between Classes (Without Multiple Inheritance Of Course) in C#
[ "", "c#", "design-patterns", "inheritance", "multiple-inheritance", "code-reuse", "" ]
I had a colleague check in code like this in C (syntax #1): ``` (*(*(*p_member).p_member).p_member).member ``` When I asked him why he didn't use -> (syntax #2): ``` p_member->p_member->p_member->member ``` he got really defensive stating that syntax #2 is more complicated than #1...I ended up changing his code because I had to modify it and couldn't read it, then he got mad that I actually touched it... Which syntax does the SO community prefer? Both are valid, but I find syntax #2 more readable. I'm setting this to community wiki due to the question being subjective.
The technical term for syntax # 1 is "nuts." That said, I'd worry a little about code that has to go indirect 3 times too.
I think your coworker is either inexperienced, some sort of neophobe, or just plain ol' clueless. You're going to find that the unanimous choice is to use the -> syntax.
Syntax for dereferencing a pointer in C (or C++)
[ "", "c++", "c", "syntax", "pointers", "" ]
I have an upgraded 3rd party library and there used to be an object called Foo and now its an interface called IFoo what is the best way to change all usages and declarations of Foo to IFoo i tried doing Find / Replace but this also affected FooBar to IFooBar (which i dont want) thoughts?
It definitely works with R# 4.5. 1. Right click on your Foo class. 2. Select Refactor/Use Base Type where Possible..
As stated by others, ReSharper can do what you are asking for. As an aside, be sure to get, and print out, the ReSharper Keyboard shortcuts. There are two variations: [Visual Studio scheme](http://www.jetbrains.com/resharper/docs/ReSharper40DefaultKeymap.pdf), and the [IDEA scheme](http://www.jetbrains.com/resharper/docs/ReSharper40DefaultKeymap2.pdf) (most guys I know use the IDEA scheme). But there are only two keyboard combination you really need to know: Refactor this: Ctrl+alt+R Navigate from here: Ctrl+alt+G or Alt+' (depending on keyboard scheme) That will get you to a lot of the most valuable ReSharper functionality.
Resharper change object to interface
[ "", "c#", "visual-studio", "refactoring", "" ]
I'm writing code in python for some sort of daemon that has to execute a specific action at a certain instance in time defined by a crontab string. Is there a module I can use? If not, can someone paste/link an algorithm I can use to check whether the instance of time defined by the crontab has occured in the time from when the previous check was done. Thanks.
[sched](http://docs.python.org/library/sched.html) ftw
[Kronos](http://www.razorvine.net/download/kronos.py) is another option. Here is a similar SO [question](https://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python).
crontab in python
[ "", "python", "cron", "" ]
I having a bit of a quandry trying to come up with a good algorithm to navigate the following graph. [alt text http://www.archimedesinc.biz/images/StackOverflow/Tree.jpg](http://www.archimedesinc.biz/images/StackOverflow/Tree.jpg) If a user chooses "Table 21" as a starting point, I need to be able to get the path to any other table from that starting table. EX: If the user chooses "Table 21" as a start and then adds a value from "Table 8", I need to create the following path "**Table 21** -> **Table 12** -> **Table 9** -> **Table 6** -> **Table 8**", all of the weights between the tables are the same. I seem to have forgotten my skills in dealing with directed graphs, and can't think of a good algorithm. I'm not asking for a solution, but just a push in the right direction. Thank you!
Breadth-first search will find a shortest path: <http://en.wikipedia.org/wiki/Breadth-first_search>
Since you said the edges are all of the same weight, [Dijkstra's algorithm](http://en.wikipedia.org/wiki/Dijkstra's_algorithm) (my usual first choice for this sort of thing) will just degrade to [breadth first search](http://en.wikipedia.org/wiki/Breadth-first_search) so I suggest using that for simplicity.
Graph navigation with C#
[ "", "c#", "algorithm", "graph-theory", "traversal", "directed-graph", "" ]
I've heard the phrase "deploying applications" which sounds much better/easier/more reliable than uploading individual changed files to a server, but I don't know where to begin. I have a Zend Framework application that is under version control (in a Subversion repository). How do I go about "deploying" my application? What should I do if I have an "uploads" directory that I don't want to overwrite? I host my application through a third party, so I don't know much other than FTP. If any of this involves logging into my server, please explain the process.
Automatic deploy + run of tests to a staging server is known as continuous integration. The idea is that if you check in something that breaks the tests, you would get notified right away. For PHP, you might want to look into [Xinc](http://code.google.com/p/xinc/) or [phpUnderControl](http://www.phpundercontrol.org/) You'd generally *not* want to automatically deploy to production though. The normal thing to do is to write some scripts that automates the task, but that you still need to manually initiate. You can use frameworks such as [Phing](http://phing.info/) or other build-tools for this (A popular choice is [Capistrano](http://www.capify.org/)), but you can also just whisk a few shell-scripts together. Personally I prefer the latter. The scripts themselves could do different things, depending on your application and setup, but a typical process would be: * ssh to production server. The rest of the commands are run at the production server, through ssh. * run `svn export svn://path/to/repository/tags/RELEASE_VERSION /usr/local/application/releases/TIMESTAMP` * stop services (Apache, daemons) * run `unlink /usr/local/application/current && ln -s /usr/local/application/releases/TIMESTAMP /usr/local/application/current` * run `ln -s /usr/local/application/var /usr/local/application/releases/TIMESTAMP/var` * run `/usr/local/application/current/scripts/migrate.php` * start services (Assuming you have your application in `/usr/local/application/current`)
I wouldn't recommend automatic updating. Just because your unit tests pass doesn't mean your application is 100% working. What if someone checks in a random new feature without any new unit tests, and the feature doesn't work? Your existing unit tests might pass, but the feature could be broken anyway. Your users might see something that's half-done. With automatic deployment from a check-in, you might not notice for a few hours if something made it live that shouldn't have. Anyhow, it wouldn't be that difficult to get an automatic deployment going if you really wanted. You'd need a post-check-in hook, and really the steps would be: 1) Do an export from the latest check-in 2) Upload export to production server 3) Unpack/config the newly uploaded export I've always performed the last steps manually. Generally it's as simple as SVN export, zip, upload, unzip, configure, and the last two steps I just alias a couple of bash commands together to perform. Then I swap out the root app directory with the new one, ensuring I keep the old one around as a backup, and it's good to go. If you're confident in your ability to catch errors before they'd automatically go live, then you could look at automating that procedure. It gives me the jibbly-jibblies though.
How to get started deploying PHP applications from a subversion repository?
[ "", "php", "svn", "zend-framework", "deployment", "setup-deployment", "" ]
What is the best way to build the table that will represent the tree? I want to implement a select ,insert ,update and delete that will work well with big data. The select for example will have to support "Expand ALL" - getting all the children (and there children) for a given node.
Use `CTE`'s. Given the tree-like table structure: ``` id parent name 1 0 Electronics 2 1 TV 3 1 Hi-Fi 4 2 LCD 5 2 Plasma 6 3 Amplifiers 7 3 Speakers ``` , this query will return `id`, `parent` and depth level, ordered as a tree: ``` WITH v (id, parent, level) AS ( SELECT id, parent, 1 FROM table WHERE parent = 0 UNION ALL SELECT id, parent, v.level + 1 FROM v JOIN table t ON t.parent = v.id ) SELECT * FROM v id parent name 1 0 Electronics 2 1 TV 4 2 LCD 5 2 Plasma 3 1 Hi-Fi 6 3 Amplifiers 7 3 Speakers ``` Replace `parent = 0` with `parent = @parent` to get only a branch of a tree. Provided there's an index on `table (parent)`, this query will efficiently work on a very large table, since it will recursively use `INDEX LOOKUP` to find all chilrden for each parent. To update a certain branch, issue: ``` WITH v (id, parent, level) AS ( SELECT id, parent, 1 FROM table WHERE parent = 0 UNION ALL SELECT id, parent, v.level + 1 FROM v JOIN table t ON t.parent = v.id ) UPDATE table t SET column = newvalue WHERE t.id IN ( SELECT id FROM v ) ``` where `@parent` is the root of the branch.
You have to ask yourself these questions first : 1) What is ratio of modifications vs reads ? (= mostly static tree or changing constantly?) 2) How deep and how large do you expect the tree to grow ? Nested sets are great for mostly-static trees where you need operations on whole branches. It handles deep trees without problems. Materialized path works well for dynamic (changing) trees with constrained/predictable depth. Recursive CTEs are ideal for very small trees, but the branch operations ("get all children in this branch..") get very costly with deep / large tree.
How to implement high performance tree view in SQL Server 2005
[ "", "sql", "sql-server", "database", "tree", "" ]
I've written a loop in C++ to give me 6 random numbers and store them in an array. What I would like to do is to sum the elements of the array until I get a value larger than a number, "x", but I would like to do this without necessarily adding all the elements. The objective is to find the first elements which sum to the value of x. For example, array is `[1,2,3,4,5,6]`, and `x = 6`, so what I would be looking for are the elements `[1,2,3]`. I've looked at the standard library and have tried using the sum function from "valarray" but this just gives the sum of all the elements. Any ideas on how to code this successfully would be greatly appreciated.
Write a functor that does the addition. ``` #include <algorithm> struct SumToo { SumToo(int val):m_val(val),m_sum(0) {} int m_val; int m_sum; bool operator()(int next) { m_sum += next; return m_sum >= m_val; } }; int main() { int data[] = {1,2,3,4,5,6}; int* find = std::find_if(data,data+6,SumToo(6)); } ```
I'm assuming you just want the first X elements in the array, up until their sum meets or exceeds a threshold (the question was a little vague there). If so, I don't know how to do that without your own loop: ``` int sum = 0; int i = 0; for( ; i < len; ++i ) { sum += array[i]; if( sum >= 6 ) { break; } } ``` Now "i" contains the index at which the sum met or exceeded your threshold.
Find the elements of an array based on minimum sum
[ "", "c++", "arrays", "sum", "subset-sum", "" ]
I'm still new to delegates and I've been playing with the Delegate-based Data Access Layer described in Steven John Metsker's "Design Patterns in C#" book (an excellent read!). It defines the data access delegate like this: ``` public delegate object BorrowReader(IDataReader reader); ``` The result of using this is code that looks like one of these: ``` var result = Foo.Bar(new BorrowReader(DoFooBarMagic)); var result = Foo.Bar(DoFooBarMagic); ``` However, since the delegate's return type is "object", you need to cast to get whatever the method ("DoFooBarMagic" in this example) really returns. So if "DoFooBarMagic" returns List, you'd need to do something like this: ``` var result = Foo.Bar(DoFooBarMagic) as List<string>; ``` What I'd like is to be able to skip the cast and have the return type of the delegate inferred from the return type of the delegate method. My thought was maybe there's a way to use a Type parameter to inference the return type. Something like one of these: ``` public delegate T BorrowReader<T>(IDataReader reader); List<string> result = Foo.Bar(new BorrowReader(DoFooBarMagic)); //Look, Ma, no cast! var result2 = Foo.Bar(DoFooBarMagic); ``` Where the type of the return is inferred from the return type of the delegate method, but that appears not to work. Instead you have to do this: ``` public delegate T BorrowReader<T>(IDataReader reader); var result = Foo.Bar(new BorrowReader<List<string>>(DoFooBarMagic)); ``` Which hardly seems better than the cast. So is there a way to infer the return type of the delegate from the return type of the delegate method? **Edit to Add:** I can change the signature of Foo.Bar if need be. The current signature is essentially this: ``` public static T Bar<T>(string sprocName, DbParameter[] params, BorrowReader<T> borrower); ``` Note: that signature is the result of the current state, which is using this delegate definition: ``` public delegate T BorrowReader<T>(IDataReader reader); ```
How about: ``` public static T Bar2<T>(Func<IDataReader,T> func) where T : class { BorrowReader borrower = new BorrowReader(func); return (T) Foo.Bar(borrower); } ``` I know it's still doing the cast anyway, which is ugly, but it should work. (I originally thought you could get away with an implicit conversion from `func`, but apparently not. At least not before C# 4.0.) Of course, if you can change the signature of `Foo.Bar` to be generic, you're laughing... EDIT: To answer the comment: if the signature of the method is changed to take a generic delegate, e.g. ``` public static T Bar<T>(Func<IDataReader, T> func) ``` then the calling code can *nearly* just be: ``` var result = Foo.Bar(DoFooBarMagic); ``` Unfortunately, type inference doesn't work with method groups so you have to use either: ``` Func<IDataReader, List<string>> func = DoFooBarMagic; var result = Foo.Bar(func); ``` or (nicer, if *slightly* less efficient) ``` var result = Foo.Bar(reader => DoFooBarMagic(reader)); ``` So you're right - this answer didn't quite get the OP to exactly what was required, but presumably it came close enough to get acceptance. Hopefully this edit is helpful to explain the rest :)
It's ugly, but you can use an out parameter. From my enum parser: ``` public static T Parse<T>(string value) { // return a value of type T } public static void Parse<T>(string value, out T eValue) { // do something and set the out parameter } // now can be called via either SomeEnum blah = Enums.Parse<SomeEnum>("blah"); // OR SomeEnum blah; Enums.Parse("blah", out blah); ``` The second one will infer the type, but like I said, it's ugly.
Delegates with return value type inference (C#)
[ "", "c#", ".net", "delegates", "type-inference", "" ]
I have a JTable that is within a `JScrollPane.` Rows are added to the table at runtime based on events that happen in my application. I want to have the scoll pane scroll to the bottom of the table when a new row is added to the table. For JLists There is the `[ensureIndexIsVisible][1]()` that forces a particular index in the list to be visible. I'm looking for the same thing but for a JTable. It looks like I might have to manually move the scrolling view on the scroll pane but I figured there had to be an easier way.
See this example : <http://www.exampledepot.com/egs/javax.swing.table/Vis.html> update: the link is now obsolete, here is the code (from <http://smi-protege.stanford.edu/repos/protege/protege-core/trunk/src/edu/stanford/smi/protege/util/ComponentUtilities.java> ) ``` public static void scrollToVisible(JTable table, int rowIndex, int vColIndex) { if (!(table.getParent() instanceof JViewport)) { return; } JViewport viewport = (JViewport)table.getParent(); // This rectangle is relative to the table where the // northwest corner of cell (0,0) is always (0,0). Rectangle rect = table.getCellRect(rowIndex, vColIndex, true); // The location of the viewport relative to the table Point pt = viewport.getViewPosition(); // Translate the cell location so that it is relative // to the view, assuming the northwest corner of the // view is (0,0) rect.setLocation(rect.x-pt.x, rect.y-pt.y); table.scrollRectToVisible(rect); // Scroll the area into view //viewport.scrollRectToVisible(rect); } ```
It's very easy, JTable has scrollRectToVisible method too. If you want, you can try something like this to make scrollpane go to to the bottom if a new record is added : ``` jTable1.getSelectionModel().setSelectionInterval(i, i); jTable1.scrollRectToVisible(new Rectangle(jTable1.getCellRect(i, 0, true))); ``` Where ***i*** is last added record.
JTable Scrolling to a Specified Row Index
[ "", "java", "swing", "jtable", "jscrollpane", "" ]
I've been trying to solve this for ages (3 days) now and I just cannot figure it out. I will try to explain the problem comprehensively because it is a bit more complex. My school assignment is to create a simple text game using OOP in C# Visual Studio 2008 (should be built on a library the teacher provided for us). It should only use console. I have a decent experience with OOP from PHP and C++ but I still cannot figure this out. 80% of the text game is already working so I won't bore you with classes and stuff that already works and is not related to the problem. Ok let's get started: Each command in the game (what you can type into the console and hit enter) is represented by a single class both extending an abstract class and an interface from the library I am supposed to built the game on. Bellow is a class Use which represents a command for using items (e.g. you type "use sword" into the console and the game will look for an item called sword and call its use method): ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Game.Commands { class Use : TextGame.Commands.ACommand, TextGame.Commands.ICommand { private string name; public new string Name { set { this.name = value; } get { return this.name; } } private string description; public new string Description { set { this.description = value; } get { return this.description; } } private string parameters; public new string Params { set { this.parameters = value; } get { return this.parameters; } } public Use(string name, string description) : base(name, description) { this.name = name; this.description = description; } private TextGame.Core.GameState gameState; public TextGame.Core.GameState Execute(TextGame.Core.IGame game) { // This is just a test because it appears the problem is // with the parameters property. There should be a command // you have typed in the console but its always null // Note that I have not yet coded the body of this method. // I will do that once I solve the problem. if (this.parameters == null) { Console.WriteLine("is null"); } else { Console.WriteLine(this.parameters); } return this.gameState; } } } ``` There are two other classes that are used. The Parser class and the Game class. There are a bit longer so I will only post snippets of relevant stuff from them. Parser class: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; // ArrayList, Dictionary, Hashtable using System.Text.RegularExpressions; // regex engine using Game.Commands; namespace Game { class Parser { private ArrayList commands = new ArrayList(); // All commands that are available in the game so far are // initialized here in the constructor (and added to the arraylist)... // skip to the other method this is not important public Parser() { this.commands.Add(new North("^north", "Go north")); this.commands.Add(new South("^south", "Go south")); this.commands.Add(new East("^east", "Go east")); this.commands.Add(new West("^west", "Go west")); this.commands.Add(new Use("^use\\s\\w+", "Try to use the selected item")); this.commands.Add(new Quit("^quit", "Quit the game")); } // This method takes as an argument a string representing // a command you type in the console. It then searches the arraylist // via the regex. If the command exists, it returns an the command object // from the arraylist // This works fine and returns right objects (tested) public TextGame.Commands.ACommand GetCommand(string command) { TextGame.Commands.ACommand ret = null; foreach (TextGame.Commands.ACommand c in this.commands) { Regex exp = new Regex(@c.Name, RegexOptions.IgnoreCase); MatchCollection MatchList = exp.Matches(command); if (MatchList.Count > 0) { ret = c; } } return ret; } } } ``` Now a snippet from the Game class where I'm using both above classes: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using TextGame.Core; using System.Collections; using Game.Items; using Game.Commands; namespace Game { class Game : TextGame.Core.IGame { public void Play() { // Here I read commands from the console in a loop and // call the ProcessCommand() method. No problem here. while (true) { string command = Console.ReadLine(); this.ProcessCommand(command); } } // This is the IMPORTANT method so take a closer look private TextGame.Core.GameState gameState; public TextGame.Core.GameState ProcessCommand(string command) { Parser parser = new Parser(); TextGame.Commands.ACommand c = parser.GetCommand(command); if (c != null) { // HERE I ADD THE COMMAND FROM THE CONSOLE TO THE C OBJECT // I ADD IT VIA THE SETTER TO THE PARAMETERS PROPERTY // OF THE COMMAND c.Params = command; // AND I CALL THE COMMAND'S EXECUTE() METHOD - SEE THE FIRST CLASS - // USE - WHERE I TEST FOR THE PARAMS PROPERTY BUT IT IS STILL NULL this.gameState = ((TextGame.Commands.ICommand)c).Execute(this); } } } } ``` I have added comments to the snippets to describe where is the problem. I hope I have explained it well. Anyone has any ideas? I've been working on this projects for about 3 weeks now and most of the stuff went smoothly when 3 days ago I came across this problem and since then I've been trying to get my head around this problem.
Your problem is with the 'new' keyword. Here's where you're using it in the 'Use' class: ``` private string parameters; public new string Params { set { this.parameters = value; } get { return this.parameters; } } ``` You're creating a different property that just happens to have the same name as a property on the type you are inheriting from. The 'new' keyword tells the compiler you meant to do that. Basically, this means that if you do the following: ``` var x = new Use(); x.Params = "abcd"; ((ACommand)x).Params = "wxyz"; Console.Writeline("direct: " + x.Params); Console.Writeline("ACommand: " + ((ACommand)x).Params); ``` You'll get this output: > direct: abcd > > ACommand: wxyz You probably want to remove the definition of 'Params' entirely from Use and just inherit the one from ACommand. Probably from Name and Description as well, but you should be able to figure out from here if you want that or not.
Without seeing the code for the ACommand class... Try removing the "new" operator in the Params declaration of the Use class. When your setting the property c.Params = command; is actually setting the property of the base class, in the Execute method your checking this.parameters instead of base.Params.
Property is null, even after being set in code
[ "", "c#", "visual-studio", "oop", "console", "" ]
I'm looking for a way to temporarily turn off all DB's constraints (eg table relationships). I need to copy (using INSERTs) one DB's tables to another DB. I know I can achieve that by executing commands in proper order (to not break relationships). But it would be easier if I could turn off checking constraints temporarily and turn it back on after the operation's finish. Is this possible?
You can disable FK and CHECK constraints only in SQL 2005+. See [ALTER TABLE](http://msdn.microsoft.com/en-us/library/ms190273(SQL.90).aspx) ``` ALTER TABLE foo NOCHECK CONSTRAINT ALL ``` or ``` ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column ``` Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.
``` -- Disable the constraints on a table called tableName: ALTER TABLE tableName NOCHECK CONSTRAINT ALL -- Re-enable the constraints on a table called tableName: ALTER TABLE tableName WITH CHECK CHECK CONSTRAINT ALL --------------------------------------------------------- -- Disable constraints for all tables in the database: EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' -- Re-enable constraints for all tables in the database: EXEC sp_msforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL' --------------------------------------------------------- ```
Turn off constraints temporarily (MS SQL)
[ "", "sql", "sql-server", "sql-server-2005", "constraints", "entity-relationship", "" ]
My requirement was to build an utility which could record voice (through mic) and save on disk .wav files as desktop and web app. for specific users so i chose activeX technology as i didn't find any other better way (may be you know and can guide me.. would be more than welcome) I used winmm.dll (aka Media control interface (MCI)) and it is working perfectly fine but on specific computers like when i run it on vista, it works fine and on win server 2008 but on windows 2003 and xp it's not working .. just working is there any prereq.. which needs to be there or what i should do to make it work on other flavors of windows. I don't mind in using DirectSound if some1 recommends with some sample code to record/save/play sample :)
I would use DirectShow to capture the audio. Since you added a C# tag to the question, I recommend using the [DirectShow.NET library](http://directshownet.sourceforge.net/). Make sure you also download the [samples](http://sourceforge.net/project/showfiles.php?group%5Fid=136334&package%5Fid=188409&release%5Fid=529095) and look at the PlayCap and CapWMV samples in the Capture folder. You may also want to checkout the [Audio Capture article](http://www.codeproject.com/KB/audio-video/cac.aspx) at CodeProject. As for why some OS versions are working, have you confirmed on those systems that the audio input works with other programs? Are you allowing the user to select an audio device or just using the default audio device? Are you getting an error message or just not audio? Per this [forum](http://www.directorforum.de/showthread.php?t=44632), make sure you wrap your filename in double quotes.
Actually no error, no exception and not even output wav files i am creating, whereas it works fine on vista and 2k8 but not prior versions. m using default sound card not setting any explicitly using following code ``` [DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback); ``` to record ``` mciSendString("open new Type waveaudio Alias recsound", "", 0, 0); mciSendString("record recsound", "", 0, 0); ``` to stop and save ``` mciSendString(@"save recsound " + OuputFolderName + FileName + ".wav", "", 0, 0); mciSendString("close recsound ", "", 0, 0); ```
voice record (winmm.dll) using C#.net
[ "", "c#", "activex", "" ]
I have the following function: ``` //Function to get random number public static int RandomNumber(int min, int max) { Random random = new Random(); return random.Next(min, max); } ``` How I call it: ``` byte[] mac = new byte[6]; for (int x = 0; x < 6; ++x) mac[x] = (byte)(Misc.RandomNumber((int)0xFFFF, (int)0xFFFFFF) % 256); ``` If I step that loop with the debugger during runtime I get different values (which is what I want). However, if I put a breakpoint two lines below that code, all members of the `mac` array have equal value. Why does that happen?
Every time you do `new Random()` it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single [Random](https://learn.microsoft.com/en-us/dotnet/api/system.random?view=netframework-4.8) instance and keep using [Next](https://learn.microsoft.com/en-us/dotnet/api/system.random.next?view=netframework-4.8#System_Random_Next) on the **same** instance. ``` //Function to get a random number private static readonly Random random = new Random(); private static readonly object syncLock = new object(); public static int RandomNumber(int min, int max) { lock(syncLock) { // synchronize return random.Next(min, max); } } ``` --- Edit (see comments): why do we need a `lock` here? Basically, `Next` is going to change the internal state of the `Random` instance. If we do that at the same time from multiple threads, you *could* argue "we've just made the outcome even more random", but what we are *actually* doing is potentially breaking the internal implementation, and we could also start getting the same numbers from different threads, which *might* be a problem - and might not. The guarantee of what happens internally is the bigger issue, though; since `Random` does **not** make any guarantees of thread-safety. Thus there are two valid approaches: * Synchronize so that we don't access it at the same time from different threads * Use different `Random` instances per thread Either can be fine; but mutexing a **single** instance from multiple callers at the same time is just asking for trouble. The `lock` achieves the first (and simpler) of these approaches; however, another approach might be: ``` private static readonly ThreadLocal<Random> appRandom = new ThreadLocal<Random>(() => new Random()); ``` this is then per-thread, so you don't need to synchronize.
For ease of re-use throughout your application a static class may help. ``` public static class StaticRandom { private static int seed; private static ThreadLocal<Random> threadLocal = new ThreadLocal<Random> (() => new Random(Interlocked.Increment(ref seed))); static StaticRandom() { seed = Environment.TickCount; } public static Random Instance { get { return threadLocal.Value; } } } ``` You can use then use static random instance with code such as ``` StaticRandom.Instance.Next(1, 100); ```
Random number generator only generating one random number
[ "", "c#", "random", "" ]
How can I map a Map in JPA without using Hibernate's classes?
Does not the following work for you? ``` @ManyToMany(cascade = CascadeType.ALL) Map<String,EntityType> entitytMap = new HashMap<String, EntityType>(); ``` `EntityType` could be any entity type, including a `String`.
Although answer given by Subhendu Mahanta is correct. But `@CollectionOfElements` is deprecated. You can use `@ElementCollection` instead: ``` @ElementCollection @JoinTable(name="ATTRIBUTE_VALUE_RANGE", joinColumns=@JoinColumn(name="ID")) @MapKeyColumn (name="RANGE_ID") @Column(name="VALUE") private Map<String, String> attributeValueRange = new HashMap<String, String>(); ``` There is no need to create a separate Entity class for the `Map` field. It will be done automatically.
JPA Map<String,String> mapping
[ "", "java", "hibernate", "mapping", "persistence", "" ]
I'm a newbie who is creating a lightweight photo showcase site written on the cake php framework with RoR.i plan to use effects from the scriptalicious library, as well as jquery for photo display & transition effects. As the site will be very photo-rich, what programming steps can i take to ensure that all photos and other pages load quickly?
i think you're mixing things up a bit. ror mixing with php/cake? so, about performance. it mostly depends on how many users do you think you'll have, who those user are and what they do. 10 per hour or 100 per second? do they look at an image for a long time or are they rapidly hopping from page to page? here are some tips that are not too technical. no server configuration optimizing, no memcached and so on. start thinking about performance with common sense - it's not the holy grail! * **is your site/application too slow?** most often, that's not the case. it never hurts speeding it up, but often, people care about performance *too much*. always remember: it's not about being fast, it's about being *fast enough*. nobody notices some extra milliseconds. a speedup of 50% is noticeable if your page needs a second to load, but mostly irrelevant if it takes only 100ms. * to find out if your site is slow, **benchmark** it. there are a lot of methods to do this, one is automated, like `ab` (apache benchmark). it simulates lots of users connecting to your site and gives you a nice summary how long it took to respond. the other is: use it. and not in the local network! if you feel it's to slow, then do something. * a photo showcase heavily depends on the images. images are big. so make sure your server has enough **bandwidth** to deliver them fast. * if you scale the images (that's very probable), don't resize the image on every page request, **cache** the scaled image! cache the thumbnails too. cache everything. processing and delivering a static file is a lot cheaper than constantly doing all the processing. * think about the quality of the image. is fast delivery more important than high image quality? play around with the **image size** - better compression means lower file size, lower quality and faster delivery. * think about **usability**. if there is no thumbnails page, people have to sequentially navigate through your library, looking at a lot of photos they don't want to see. if they already see the image, they can jump straight to those that matter (lowering bandwith usage and requests per second). think about flickr: the size of the images shown ... they're like stamps - 500 pixel wide, and people are still happy. if they need a bigger version, they click on the "all sizes" link anyway. * **tricks, tricks, tricks**: earlier, when users surfed with modes, sometimes low resolution/high compression images were transfered, so the user had something after a short amount of time. only after the first image was loaded, the bigger version startet. it's not common anymore, because today most users have broadband, so sending an additional image is just additional workload. * think about **the audience**. are they gonna visit your site with 14.4k modems or broadband? are they used to slow loading sites (photographers probably are)? check your statistics to find out about them. * your *backend scripting language* is most probably not your problem. php is not really fast, ruby is not really fast - compared to, say, c or java or ocaml. frameworks are slower than hand-crafted, optimized code. debug your code to see where the slow parts are. my guess? image resizing and database access. that won't change when switching to another language or optimizing your code. ### regarding the speed of websites there are a lot of factors involved. some of them are: 1. serverside processing: is your application fast, is your hardware fast? 2. delivery: how fast are the requests and files transfered from the client to the server and vice versa? (depending on bandwidth) 3. client side rendering: how fast is their browser, how much work has to be done? 4. user haibts: do the client even need speed? sometimes, slow pages are no problem, e.g. if they spend a long time there without clicking around. think about flash game sites: if you spend an hour playing a flash game, you'll probably won't even notice if the page loads in 3 or 5 seconds. the percieved speed - a mixture of all four - is the important metric. if you've confirmed you are really too slow, be sure to optimize the right part. optimizing the server side scripts is useless if the server is fast enough, but the page takes ages to render on the browser. no need to optimize rendering time if your bandwidth is clogged. ### regarding optimization performance is an integral part when building an application. if you really need something fast, you have to plan for speed from the very beginning. if it's not designed for speed, effective optimization is often not possible. that's not really true for web apps all the time, because they easily scale horizontally, meaning: throw hardware at it. all things cost money, and if money is important to you (or your boss), don't forget about it. how much do two weeks of optimising an application cost? say, optimising costs you (or your boss) X € (i'm european) in salary. now, think about buying another server: that costs Y € (including setup). if Y < X, just buy the server and you'll be fine. ### random buzzwords last but not least i'll throw some random (unordered) buzzwords at you, maybe there is something that might help. just google, that should help ... content delivery networks, (intel) SSDs, sprites (combining images to save requests), page compression (gzip, deflate), memcached, APC (bytecode cache for PHP), minifying and merging of multiple CSS and JS files, conscious handling of HTTP status codes (not changed), separation of static and dynamic content (different servers & domains), step-by-step loading via AJAX (important content first), ... now i'm out of ideas. ### edit/update things/techniques i forgot: * implement a progress bar or something comparable, so users at least feel something's going on. you can't use progress bars if working only with javascript, but at least show some kind of animated hourglass or clock. if you use flash, you can show a real progress bar. * you can skip complete page reloads by working with AJAX or flash - just load the data you need. you often see this implemented in flash image galleries. just load the image and the description. * preloading: if users look at one image for an extended period of time, you can already start loading the next image, so it's browser-cached if the user continues. ### disclaimer i never implemented performance critical apps (with 2 exceptions), so most of what i've written above is speculation and the experience of others. today you read stories about successfull startups and how they coped (performance-wise) with going from 100 to a bazillion users a day, and how they used nifty tricks to solve all those problems all the time. but is that going to happen to you? probably not. everyone talks about it, almost nobody really needs it *(but i admit, it's still good to know)*. my real world experience (yes, i like writing long answers): once i did parts of a website with several thousand of unique visitors a day, powered by a cms (typo3) and running on a single dedicated samp-server (think of used, decade old solaris servers, *not ghz*!). you could search for flats, and the form told you how many results you'll have (e.g. 20-40m²: 400 hits, 30-60m²: 600 hits) by reloading an iframe *ON-CLICK*. it was very, very slow (but users still used it). constantly 100% load. it was my job to solve that problem. what did i do? first, find out why it was so slow. my first guess was right, the on-click request *also* used typo3 (w/o caching, of course). by replacing this single action with a custom script that just queried the database directly, bypassing typo3, the problem was solved. load went down to almost nothing. took me about 2 hours. the other project had about 1500 unique visitors a day, displaying data serverd by an oracle database with millions of rows and complicated joins that took forever (=several seconds) to run. i didn't have much experience in optimizing oracle, but i knew: the database was updated only once or twice a week. my solution: i just cached the contents by writing the html to the filesystem. after updating (in the middle of the night) i cleared the cache and began rebuilding it. so, instead of expensive queries i had just cheap filesystem reads. problem solved. both examples taught me that performance in web developement is *not* rocket science. most of the time the solution is simple. and: there are other parts that are way more important 99% of the time: **developer cost** and **security**.
The question is pretty vague. Most of the time spent getting a page is usually getting static content. Here are some rules of thumb for speeding up load times independent of language or framework: 1. Install the [YSlow plug-in](http://developer.yahoo.com/yslow/) for firefox 2. Use CSS Sprites 3. Have a light weight http server for static content, [nginx](http://nginx.net/) or [lighttpd](http://www.lighttpd.net/) 4. Serve static content on a different domain or sub domain, this allows more simultaneous http requests 5. Minify javascript and css 6. Cache pages as much as you can 7. Keep the number of http requests low 8. Run [pngcrush](http://pmt.sourceforge.net/pngcrush/) or jpegtran on your images Naturally, this is just the tip of the iceberg. These are good first steps.
how to optimise site load times in ruby?
[ "", "php", "ruby-on-rails", "ruby", "cakephp", "rubygems", "" ]
I'm writing a simple distributed java rmi application and I have a bunch of methods that each need to iterate through a map of client interfaces in order to call various other methods on those interfaces, like so: ``` public void methodX (arg1, arg2) { Iterator<String> itr = clients.keySet().iterator; while (itr.hasNext()) { String name = itr.next(); if (!"mod".equals(name)) { try { clients.get(name).methodXX(arg1, arg2); } catch(RemoteException ex) { // do something } } } } public void methodY (arg1, arg2, arg3) { Iterator<String> itr = clients.keySet().iterator; while (itr.hasNext()) { String name = itr.next(); if (!"mod".equals(name)) { try { clients.get(name).methodYY(arg1, arg2, arg3); } catch(RemoteException ex) { // do something } } } } ``` Now I modified these so that instead they each call a single method doAll by passing a new argument called MESSAGE\_TYPE, like so: ``` public void methodX (arg1, arg2) { doAll(MESSAGE_TYPE.METHODX, arg1, arg2, null); } public void methodY (arg1, arg2, arg3) { doAll(MESSAGE_TYPE_METHODY, arg1, arg2, arg3); } ``` And the doAll method: ``` public void doAll(msg_type, arg1, arg2, arg3) { Iterator<String> itr = clients.keySet().iterator; while (itr.hasNext()) { String name = itr.next(); if (!"mod".equals(name)) { try { switch(msg_type) { case METHODX: clients.get(name).methodXX(arg1, arg2); break; case METHODY: clients.get(name).methodYY(arg1, arg2, arg3); break; } } catch(RemoteException ex) { // do something } } } } ``` Now there are many more methods like this, and so my doAll method needs to take a bunch of args and each methodXX that calls it pass a bunch of nulls to it. Can I rewrite this so it's more concise? If so, can you provide an example?
For one thing, I'd use the enhanced for loop, and iterate over entries instead of keys, as suggested in the comments: ``` public void doAll(arg1, arg2, arg3) { for (Map.Entry<String,Client> entry : clients.entrySet()) { if (!"mod".equals(entry.getKey())) { try { switch(MESSAGE_TYPE) { case METHODX: entry.getValue().methodXX(arg1, arg2); break; case METHODY: entry.getValue().methodYY(arg1, arg2, arg3); break; } } catch(RemoteException ex) { // do something } } } } ``` I think I'd then refactor it to pass in an "action" to call on each client, and use an anonymous inner class from the call sites: ``` public interface RemoteAction { public void execute(Client client) throws RemoteException; } public void doAll(RemoteAction action) { for (Map.Entry<String,Client> entry : clients.entrySet()) { if (!"mod".equals(entry.getKey())) { try { action.execute(entry.getValue()); } catch(RemoteException ex) { // do something } } } } public void methodX (final arg1, final arg2) { doAll(new Action() { @Override public void execute(Client client) throws RemoteException { client.methodX(arg1, arg2); } }); } public void methodY (final arg1, final arg2, final arg3) { doAll(new Action() { @Override public void execute(Client client) throws RemoteException { client.methodY(arg1, arg2, arg3); } }); } ``` It's not as nice as it would be in a language which supported lambda expressions, but it's nicer than a switch statement.
Use generics ``` Iterator<String> itr = clients.keySet().iterator; while (itr.hasNext()) { String name = itr.next(); ``` becomes ``` for(String name: clients.keySet()){ ``` Also, replacing methods with a switch/case is not so good, especially if you need to pass in dummy parameters for unused values. Keep the separate methods.
What's the most concise / best way to write this java code?
[ "", "java", "" ]
Just finished reading Crockford's "**[JavaScript: The Good Parts](http://oreilly.com/catalog/9780596517748/)**" and I have a question concerning his stance on the psuedo-classical vs. prototypal approaches. Actually I'm not really interested in his stance; I just want to understand his argument so I can establish a stance of my own. In the book, Crockford seems to infer that constructor functions and "all that jazz" shouldn't be used in JavaScript, he mentions how the 'new' keyword is badly implemented - i.e. non-Constructor functions can be called with the 'new' keyword and vice versa (potentially causing problems). I thought I understood where he was coming from but I guess I don't. When I need to create a new module I would normally start of like this: ``` function MyModule(something) { this.something = something || {}; } ``` And then I would add some methods to its prototype: ``` MyModule.prototype = { setSomething : function(){}, getSomething : function(){}, doSomething : function(){} } ``` I like this model; it means I can create a new instance whenever I need one and it has its own properties and methods: ``` var foo = new MyModule({option1: 'bar'}); // Foo is an object; I can do anything to it; all methods of the "class" // are available to this instance. ``` **My question is**: How do I achieve the above using an approach more suited to JavaScript? In other words, if "JavaScript" were a person, what would she suggest? Also: What does Crockford mean when he says a particular design pattern "is more expressive" then another?
### See: [Is JavaScript's “new” Keyword Considered Harmful?](https://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful) It's important to remember that Crockford, like so many other JavaScript programmers, first approached the language with an eye toward "fixing" it - making it more like other (so-called "classical") OO languages. So a large amount of structural code was written, libraries and frameworks built, and... then they started to realize that it wasn't really necessary; if you approach JS on its own terms, you can get along just fine.
The prototypal variant for the example you have looks like the following in my understanding: ``` Object.beget = function (o) { /* Crockfords replacement for the new */ } var myModule = { something : null, getSomething : function () {}, setSomething : function () {}, doSomething : function () {} }; ``` And then you can do: ``` var foo = Object.beget(myModule); foo.something = bar; ``` **UPDATE:** You can also use the builder pattern to replace a constructor like this: ``` var myModuleBuilder = { buildMyModule : function (something) { var m = Object.beget(myModule); m.something = something || {}; return m; } } ``` so then you can do: ``` var foo = myModuleBuilder.buildMyModule(something); ```
Pseudo-classical vs. "The JavaScript way"
[ "", "javascript", "" ]
if i use this query thath creates a table(look Table1), But VisitingGap column is not correct format. i used cast method to give format. But not working correctly.i need ### Table2 ``` declare @date1 nvarchar(100) , @date2 nvarchar(100) , @countgap int,@count int set @date1='2009-05-12' set @date2 = '2009-05-13' set @countgap = 30 set @count=48 CREATE TABLE #Temp (VisitingCount int, [Time] int, [Date] datetime ) DECLARE @DateNow DATETIME,@i int,@Time int, @Date datetime set @DateNow='00:00' set @i=1; while(@i<@count) begin set @DateNow = DATEADD(minute, @countgap, @DateNow) set @Time = (datepart(hour,@DateNow)*60+datepart(minute,@DateNow))/@countgap set @Date = CONVERT(VARCHAR(5),@DateNow, 108) insert into #Temp(VisitingCount,[Time],[Date]) values(0,@Time,@Date ) set @i=@i+1 end select Sum(VisitingCount) as VisitingCount, [Time], Cast([Time]*@countgap/60 as nvarchar(50)) +':'+Cast( [Time]*@countgap%60 as nvarchar(50)) from ( select 0 as VisitingCount, [Time] from #Temp Union All select count(page) as VisitingCount, (datepart(hour,Date)*60+datepart(minute,Date))/@countgap as [Time] from scr_SecuristLog where Date between @date1 and @date2 GROUP BY (datepart(hour,Date)*60+datepart(minute,Date))/@countgap ) X group by [Time] order by 2 asc ``` --- ### Table 1 : --- ``` . . . VCount Time VisitingGap 0 1 0:30 0 2 1:0 0 3 1:30 0 4 2:0 0 5 2:30 0 6 3:0 0 7 3:30 0 8 4:0 0 9 4:30 0 10 5:0 . . . ``` --- ### Table 2 : i need below table !!!! --- ``` . . . VCount Time VisitingGap 0 1 00:30 0 2 01:00 0 3 01:30 0 4 02:00 0 5 02:30 0 6 03:00 0 7 03:30 0 8 04:00 0 9 04:30 0 10 05:00 . . . ``` ### Look please! i think problem the cast method Cast([Time]\*@countgap/60 as nvarchar(50)) +':'+Cast( [Time]\*@countgap%60 as nvarchar.........
when you do the math, you lose the leading zeros, this will add them back when you form the string **EDIT** ``` original code--> Cast([Time]*@countgap/60 as nvarchar(50)) +':'+ Cast( [Time]*@countgap%60 as nvarchar(50)) changed code--->RIGHT('00'+Cast([Time]*@countgap/60 as varchar(2) ),2) +':'+RIGHT('00'+Cast( [Time]*@countgap%60 as varchar(2) ),2) ```
Instead of casting numerics to strings, try converting to dates and the dates to strings: ``` CONVERT(CHAR(5), DATEADD(mi, [Time], '1900-01-01'), 108) ```
How can i change dataset cell format
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I've used two PHP email scripts and routing it through my SMTP server, when I do this though it sends two of the same email. When I use mail() this doesn't happen, but I'd much rather use SMTP. Any ideas why this may be occuring?
So if you're only using PHPMailer without editing it's code, it's not your script's fault. Maybe check your SMTP server's configuration?
If you're setting the 'To' and/or 'Recipient' header multiple times, the SMTP server could interpret that as separate e-mail address, thus you'll receive the multiple e-mails. I'd recommend using the PEAR Mail class. Very simple to use, and handles much of the work for you. It supports multiple backends including SMTP. Likewise, if you want to expand your class to send HTML emails, the Mail\_Mime class handles this very nicely, providing methods to set the plain-text body and the HTML body (in case the recipient doesn't support HTML).
Two emails when sent via SMTP
[ "", "php", "email", "smtp", "" ]
I have a list of items that I wish to display with a separator between them in C#. Using a normal iterator I would end up with an extra separator at the beginning or the end: ``` string[] sa = {"one", "two", "three", "four"}; string ns = ""; foreach(string s in sa) { ns += s + " * "; } // ns has a trailing *: // one * two * three * four * ``` Now I can solve this using a for loop like so: ``` ns = ""; for(int i=0; i<sa.Length; i++) { ns += sa[i]; if(i != sa.Length-1) ns += " * "; } // this works: // one * two * three * four ``` Although the second solution works it doesn't look very elegant. Is there a better way to do this?
You need the built-in [`String.Join`](http://msdn.microsoft.com/en-us/library/system.string.join.aspx) method: ``` string ns = string.Join(" * ", sa); ``` If you want to do the same with other collection types, then you can still use `String.Join` if you create an array first using LINQ's [`ToArray`](http://msdn.microsoft.com/en-us/library/bb298736.aspx) method: ``` string ns = string.Join(" * ", test.ToArray()); ```
In addition to elegance you might want to consider speed and reusability across types other than String. For elegance I would suggest using an extension method to abstract away the details so that the common usage would look something like: ``` ns = sa.Join(" * "); ``` For speed consider the following variant tests including some of the solutions proposed by other people who have answered the question: ``` public void Test_variants() { const string item = "a"; const int numberOfTimes = 100000; const string delimiter = ", "; string[] items = new List<string>(Enumerable.Repeat(item, numberOfTimes)).ToArray(); string expected = String.Join(delimiter, items); Time(StringJoin, items, delimiter, expected); Time(Aggregate, items, delimiter, expected); Time(CheckForEndInsideLoop_String, items, delimiter, expected); Time(CheckForBeginningInsideLoop_String, items, delimiter, expected); Time(RemoveFinalDelimiter_String, items, delimiter, expected); Time(CheckForEndInsideLoop_StringBuilder, items, delimiter, expected); Time(RemoveFinalDelimiter_StringBuilder, items, delimiter, expected); } private static void Time(Func<string[], string, string> func, string[] items, string delimiter, string expected) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); string result = func(items, delimiter); stopwatch.Stop(); bool isValid = result == expected; Console.WriteLine("{0}\t{1}\t{2}", stopwatch.Elapsed, isValid, func.Method.Name); } private static string CheckForEndInsideLoop_String(string[] items, string delimiter) { string result = ""; for (int i = 0; i < items.Length; i++) { result += items[i]; if (i != items.Length - 1) { result += delimiter; } } return result; } private static string RemoveFinalDelimiter_String(string[] items, string delimiter) { string result = ""; for (int i = 0; i < items.Length; i++) { result += items[i] + delimiter; } return result.Substring(0, result.Length - delimiter.Length); } private static string CheckForBeginningInsideLoop_String(string[] items, string delimiter) { string result = ""; foreach (string s in items) { if (result.Length != 0) { result += delimiter; } result += s; } return result; } private static string CheckForEndInsideLoop_StringBuilder(string[] items, string delimiter) { StringBuilder result = new StringBuilder(); for (int i = 0; i < items.Length; i++) { result.Append(items[i]); if (i != items.Length - 1) { result.Append(delimiter); } } return result.ToString(); } private static string RemoveFinalDelimiter_StringBuilder(string[] items, string delimiter) { StringBuilder result = new StringBuilder(); for (int i = 0; i < items.Length; i++) { result.Append(items[i]); result.Append(delimiter); } result.Length = result.Length - delimiter.Length; return result.ToString(); } private static string StringJoin(string[] items, string delimiter) { return String.Join(delimiter, items); } private static string Aggregate(string[] items, string delimiter) { return items.Aggregate((c, s) => c + delimiter + s); } ``` The results on my box are as follows: ``` 00:00:00.0027745 True StringJoin 00:00:24.5523967 True Aggregate 00:00:47.8091632 True CheckForEndInsideLoop_String 00:00:47.4682981 True CheckForBeginningInsideLoop_String 00:00:23.7972864 True RemoveFinalDelimiter_String 00:00:00.0076439 True CheckForEndInsideLoop_StringBuilder 00:00:00.0052803 True RemoveFinalDelimiter_StringBuilder ``` This means your best option, if you are only working with string arrays, is String.Join followed closely by the StringBuilder variants. Note that checking for the last item inside the loop makes a much larger difference when working with strings than it does when working with a StringBuilder. Performance for the String based implementations also improves quite a bit when the list of items to be delimited is small. I ran the same tests with numberOfItems set to 10 and received the following results: ``` 00:00:00.0001788 True StringJoin 00:00:00.0014983 True Aggregate 00:00:00.0001666 True CheckForEndInsideLoop_String 00:00:00.0002202 True CheckForBeginningInsideLoop_String 00:00:00.0002061 True RemoveFinalDelimiter_String 00:00:00.0002663 True CheckForEndInsideLoop_StringBuilder 00:00:00.0002278 True RemoveFinalDelimiter_StringBuilder ``` The next thing you might want to consider is reusability. If you wanted to build a string from a list of integers separated by a delimiter String.Join would only be an option after you ran .ToString() on each the integers and created a string array (because String.Join cannot act upon an IEnumerable<string>). So, to conclude, you might consider using an extension method along the following lines to get a good combination of elegance, speed, and reusability: ``` public static string Join<T>([CanBeNull] this IEnumerable<T> items, [CanBeNull] string delimiter) { StringBuilder result = new StringBuilder(); if (items != null && items.Any()) { delimiter = delimiter ?? ""; foreach (T item in items) { result.Append(item); result.Append(delimiter); } result.Length = result.Length - delimiter.Length; } return result.ToString(); } ``` usage: ``` ns = sa.Join(" * "); ```
Adding a separator to a list of items for display
[ "", "c#", "algorithm", "" ]
Is there a way to determine if a LINQ object has not yet been inserted in the database (new) or has been changed since the last update (dirty)? I plan on binding my UI to LINQ objects (using WPF) and need it to behave differently depending whether or not the object is already in the database. ``` MyDataContext context = new MyDataContext(); MyObject obj; if (new Random().NextDouble() > .5) obj = new MyObject(); else obj = context.MyObjects.First(); // How can I distinguish these two cases? ``` The only *simple* solution I can think of is to set the primary key of new records to a negative value (my PKs are an identity field and will therefore be set to a positive integer on `INSERT`). This will only work for detecting new records. It also requires identity PKs, and requires control of the code creating the new object. Is there a better way to do this? It seems like LINQ must be internally tracking the status of these objects so that it can know what to do on `context.SubmitChanges()`. Is there some way to access that "object status"? **Clarification** Apparently my initial question was confusing. I'm not looking for a way to insert or update records. I'm looking for a way, given any LINQ object, to determine if that object has not been inserted (new) or has been changed since its last update (dirty).
ChangeSet changes = context.GetChangeSet(); If changes.Inserts.Contains(yourObject) then it is new and will be inserted when SubmitChanges is called If changes.Updates.Contains(yourObject), it's already in the database, and will be updated on SubmitChanges()
I create a partial class for each object LINQ creates (Data Objects) and have each object Implement IDataObject interface ``` /// <summary> /// This interface is used to implement IsNew in all LINQ objects so a Generic Save method /// can be used. /// </summary> public interface IDataObject { #region Properties #region IsNew /// <summary> /// Is this a new object /// </summary> bool IsNew { get; } #endregion #endregion } #endregion ``` In each data object I implement the IsNew Property to return true if the PrimaryKey has been set: ``` /// <summary> /// Is this a new object /// </summary> public bool IsNew { get { // initial value bool isNew = (this.CustomerID > 0); // return value return isNew; } } ``` Then in my DataContext I cast the ojbect to be saved as an IDataObject and if it is new I call InsertOnSubmit() before calling SubmitChanges(). This might not be the simplest way but it allows all objects to be saved generically. It takes a few minutes for each table to implement the Interface but it allows for a Generic Save() method to be called.
LINQ to SQL - Tracking New / Dirty Objects
[ "", "c#", "linq", "linq-to-sql", "" ]
How can I detect if a system supports hardware virtualization via code? (Preferably in C# or C++). I tried using WMI and ManagementObjectSearcher, and could not find a property that seemed to represent if virtualization support was present or not in the machine. Bonus question: Is it possible to tell if the CPU supports HW virtualization, but disabled in BIOS?
I think the original poster is asking how to detect that the computer hardware supports virtualisation, not that it is running inside a virtual machine. See [this question](https://stackoverflow.com/questions/20658/determine-if-my-pc-supports-hw-virtualization) for a possible answer. Also, it might be worth seeing if you can check the CPU flags, as there will either be the Intel `vmx` flag or the AMD `svm` flag if the processor supports virtualisation extensions. I can't say I know how this should be done under Windows, but the information is available in `/proc/cpuinfo` on Linux.
I do not have a C-ish answer, but here's a PowerShell approach -- it's just a simple WMI query -- that can help. Query Win32\_Processor; there are flags "SecondLevelAddressTranslationExtensions" and "VirtualizationFirmwareEnabled." They seem to answer the questions for me. In PoSH, it's (GWMI Win32\_Processor).VirtualizationFirmwareEnabled and (GWMI Win32\_Processor).SecondLevelAddressTranslationExtensions I hope this helps. Mark Minasi
How to determine if hardware virtualization is available via code? (C#, C++)
[ "", "c#", "windows", "windows-7", "virtualization", "" ]
Is there a way to implement lazy loading with Swing's JList?
In a way, yes. You can create a custom [`ListModel`](http://java.sun.com/javase/6/docs/api/javax/swing/ListModel.html) which uses the [`getElementAt(int index)`](http://java.sun.com/javase/6/docs/api/javax/swing/ListModel.html#getElementAt(int)) method to load the correct value if it hasn't already been loaded. See the example in the Javadocs for [`JList`](http://java.sun.com/javase/6/docs/api/javax/swing/JList.html): ``` // This list model has about 2^16 elements. Enjoy scrolling. ListModel bigData = new AbstractListModel() { public int getSize() { return Short.MAX_VALUE; } public Object getElementAt(int index) { return "Index " + index; } }; ```
I solved it. I had missed the solution discussed at the top of the JList API documentation. In the example source code I posted in another answer on this topic, add this line (and comment) after creating the JList: ``` // Tell JList to test rendered size using this one value rather // than every item in ListModel. (Much faster initialization) myList.setPrototypeCellValue("Index " + Short.MAX_VALUE); ``` The problem is that JList, by default, is accessing every item in the entire ListModel to determine at runtime the necessary display size. The line added above overrides that default, and tells JList to examine just the one value as passed. That one value acts as a template (prototype) for sizing the display of the JList. See: <http://java.sun.com/javase/6/docs/api/javax/swing/JList.html#prototype_example>
Is there a lazy loading implementation of JList?
[ "", "java", "swing", "jlist", "" ]
Say I have 2 models: ``` class Poll(models.Model): category = models.CharField(u"Category", max_length = 64) [...] class Choice(models.Model): poll = models.ForeignKey(Poll) [...] ``` Given a Poll object, I can query its choices with: ``` poll.choice_set.all() ``` But, is there a utility function to query all choices from a set of Poll? Actually, I'm looking for something like the following (which is not supported, and I don't seek how it could be): ``` polls = Poll.objects.filter(category = 'foo').select_related('choice_set') for poll in polls: print poll.choice_set.all() # this shouldn't perform a SQL query at each iteration ``` I made an (ugly) function to help me achieve that: ``` def qbind(objects, target_name, model, field_name): objects = list(objects) objects_dict = dict([(object.id, object) for object in objects]) for foreign in model.objects.filter(**{field_name + '__in': objects_dict.keys()}): id = getattr(foreign, field_name + '_id') if id in objects_dict: object = objects_dict[id] if hasattr(object, target_name): getattr(object, target_name).append(foreign) else: setattr(object, target_name, [foreign]) return objects ``` which is used as follow: ``` polls = Poll.objects.filter(category = 'foo') polls = qbind(polls, 'choices', Choice, 'poll') # Now, each object in polls have a 'choices' member with the list of choices. # This was achieved with 2 SQL queries only. ``` Is there something easier already provided by Django? Or at least, a snippet doing the same thing in a better way. How do you handle this problem usually?
**Update**: Since Django 1.4, this feature is built in: see [prefetch\_related](https://docs.djangoproject.com/en/stable/ref/models/querysets/#prefetch-related). First answer: don't waste time writing something like qbind until you've already written a working application, profiled it, and demonstrated that N queries is actually a performance problem for your database and load scenarios. But maybe you've done that. So second answer: qbind() does what you'll need to do, but it would be more idiomatic if packaged in a custom QuerySet subclass, with an accompanying Manager subclass that returns instances of the custom QuerySet. Ideally you could even make them generic and reusable for any reverse relation. Then you could do something like: ``` Poll.objects.filter(category='foo').fetch_reverse_relations('choices_set') ``` For an example of the Manager/QuerySet technique, see [this snippet](http://www.djangosnippets.org/snippets/1079/), which solves a similar problem but for the case of Generic Foreign Keys, not reverse relations. It wouldn't be too hard to combine the guts of your qbind() function with the structure shown there to make a really nice solution to your problem.
Time has passed and this functionality is now available in Django 1.4 with the introduction of the [prefetch\_related()](https://docs.djangoproject.com/en/1.4/ref/models/querysets/#prefetch-related) QuerySet function. This function effectively does what is performed by the suggested `qbind` function. ie. Two queries are performed and the join occurs in Python land, but now this is handled by the ORM. The original query request would now become: ``` polls = Poll.objects.filter(category = 'foo').prefetch_related('choice_set') ``` As is shown in the following code sample, the `polls` QuerySet can be used to obtain all `Choice` objects per `Poll` without requiring any further database hits: ``` for poll in polls: for choice in poll.choice_set: print choice ```
Django ORM: Selecting related set
[ "", "python", "django", "orm", "" ]
How do i update mysql database with ajax and php with no page refresh
Here is a [good example](http://www.w3schools.com/PHP/php_ajax_database.asp), it shows a `SELECT` statement but it should be straight forward and easy to update the script to what you need. **HTML from the example page:** ``` <html> <head> <script src="selectuser.js"></script> </head> <body> <form> Select a User: <select name="users" onchange="showUser(this.value)"> <option value="1">Peter Griffin</option> <option value="2">Lois Griffin</option> <option value="3">Glenn Quagmire</option> <option value="4">Joseph Swanson</option> </select> </form> <p> <div id="txtHint"><b>User info will be listed here.</b></div> </p> </body> </html> ``` **javaScript:** ``` var xmlHttp; function showUser(str) { xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { alert ("Browser does not support HTTP Request"); return; } var url="getuser.php"; url=url+"?q="+str; url=url+"&sid="+Math.random(); xmlHttp.onreadystatechange=stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById("txtHint").innerHTML=xmlHttp.responseText; } } function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { //Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } ``` **PHP called by Ajax:** ``` <?php $q = $_GET["q"]; $con = mysql_connect('localhost', 'peter', 'abc123'); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ajax_demo", $con); $sql = "SELECT * FROM user WHERE id = '" . $q . "'"; $result = mysql_query($sql); echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> <th>Hometown</th> <th>Job</th> </tr>"; while ($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; echo "<td>" . $row['Hometown'] . "</td>"; echo "<td>" . $row['Job'] . "</td>"; echo "</tr>"; } echo "</table>"; mysql_close($con); ?> ```
You can use the [JQuery](http://docs.jquery.com/Ajax/jQuery.ajax#options) library and do something like ``` $.ajax({ type: "POST", url: "some.php", data: "name=John&location=Boston", success: function(msg){ alert( "Data Saved: " + msg ); } }); ``` In your some.php file have something like this: ``` <?php $name = $_POST['name']; $location = $_POST['location']; $query("your insert query"); $result = mysql_query($query); ?> ``` ?>
How do i update mysql database with ajax and php in innerhtml
[ "", "php", "mysql", "database", "ajax", "" ]
I use `BackgroundWorker` most of the time in the win form apps to show progress as I'm getting data. I was under impression that `Work_completed` is guaranteed to be executed on Main UI thread but it's not. If we create a thread and call the `worker.RunWorkerAsync` within it, it breaks if we try to update any gui control. Here is an example ``` private void StartButton_Click(object sender, EventArgs e) { Thread thread1 = new Thread(new ThreadStart(PerformWorkerTask)); _worker = new BackgroundWorker(); thread1.Start(); } public void PerformWorkerTask() { _worker.DoWork += delegate { for (int i = 0; i < 10; i++) { Thread.Sleep(100); } }; _worker.RunWorkerCompleted += delegate { // this throws exception MessageLabel.Text = "Completed"; }; _worker.RunWorkerAsync(); } ``` How can we make backgroundworker work in this case?
`RunWorkerAsync` does its thread-synchronization magic by getting the [`SynchronizationContext`](http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx) from the thread that it is called on. It then guarantees that the events will be executed on the correct thread according to the semantics of the `SynchronizationContext` it got. In the case of the [`WindowsFormsSynchronizationContext`](http://msdn.microsoft.com/en-us/library/system.windows.forms.windowsformssynchronizationcontext.aspx), which is what is automatically used if you're using WinForms, the events are synchronized by posting to the message queue of the thread that started the operation. Of course, this is all transparent to you until it breaks. EDIT: You MUST call `RunWorkerAsync` from the UI thread for this to work. If you can't do it any other way, your best bet is to invoke the beginning of the operation on a control so that the worker is started on the UI thread: ``` private void RunWorker() { _worker = new BackgroundWorker(); _worker.DoWork += delegate { // do work }; _worker.RunWorkerCompleted += delegate { MessageLabel.Text = "Completed"; }; _worker.RunWorkerAsync(); } // ... some code that's executing on a non-UI thread ... { MessageLabel.Invoke(new Action(RunWorker)); } ```
From your example it's hard to see what good the Thread (thread1) is, but if you really do need this thread1 then I think your only option is to use `MainForm.Invoke()` to execute `RunWorkerAsync()` (or a small method around it) on the main thread. **Added:** You can use something like this: ``` Action a = new Action(_worker.RunWorkerAsync); this.Invoke(a); ```
BackgroundWorkerThread access in a thread
[ "", "c#", "windows", "winforms", "" ]
Well I have a series of sps that are running a data warehousing solution that we have developed in house. While on the most part it runs pretty good, there is one stored procedure that runs really slow. It takes about 30 minutes on average to execute. I know exactly where the bottle neck is, I just don't know how to fix it. Basically what the stored procedure does is create a series of variable temp tables and insert into those tables. no problem there. it then joins the temp tables and inserts into another temp table, twice (the second one is a little different). this is the statement that joins the tables and inserts into the temp table, and is the part that takes forever. any help would be greatly appreciated. ``` ; with Requested as ( select distinct PONUMBER as PONumber, min(REQSTDBY) as RequestedBy from dw.POP10110 where REQSTDBY <>'' group by PONUMBER ) insert into @tblTableA ( PONumber, ReceiptNumber, ReceiptLineNumber, VendorID, POType, QuantityShipped, QuantityInvoiced, ItemNumber, ItemDescription, UofM, UnitCost, ExtendedCost, SiteID, ProjectNumber, AccountID, RequestedBy, GLPostDate, VendorName, CostCategoryID ) select a.PONUMBER, a.POPRCTNM, a.RCPTLNNM, a.VENDORID, a.POPTYPE, a.QTYSHPPD, a.QTYINVCD, b.ITEMNMBR, b.ITEMDESC, b.UOFM, b.UNITCOST, b.EXTDCOST, b.LOCNCODE, b.ProjNum, case i.CostCategoryID when 'MISC' then isnull(i.AccountID,'N/A') else case j.CostCategoryID when 'MISC' then isnull(j.AccountID,'N/A') else isnull(c.PurchaseAccount,'N/A') end end as AccountID, d.RequestedBy, coalesce(e.GLPOSTDT, f.GLPOSTDT, '') as GLPostDate, coalesce(e.VENDNAME, f.VENDNAME, '') as VENDNAME, case i.CostCategoryID when 'MISC' then i.CostCategoryID else case j.CostCategoryID when 'MISC' then j.CostCategoryID else coalesce(g.CostCategoryID, h.CostCategoryID, '') end end as CostCategoryID from dw.POP10500 a inner join dw.POP30310 b on a.PONUMBER=b.PONUMBER and a.POPRCTNM=b.POPRCTNM and a.RCPTLNNM=b.RCPTLNNM left outer join @gl00100 c on b.INVINDX=c.ActID left outer join Requested d on b.PONUMBER = d.PONumber left outer join dw.POP30300 e on b.POPRCTNM=e.POPRCTNM left outer join dw.POP10300 f on b.POPRCTNM=f.POPRCTNM left outer join @pop31310 g on b.POPRCTNM=g.ReceiptNumber left outer join @pop11310 h on b.POPRCTNM=h.ReceiptNumber left outer join @pop30390 i on a.POPRCTNM=i.ReceiptNumber left outer join @pop10390 j on a.POPRCTNM=j.ReceiptNumber ``` As far as i am aware the appropriate indexes are in place.
added statistics to some of the tables and an index and it cut the time down from 25 minutes to 9 minutes.
How many rows are in your temp tables/table variables? It looks like you are using table variables, but if they have a lot of rows, consider using temp tables instead (tables with name starting with #). You can add extra indexes to these tables, whereas Table Variables can only have a single clustered index. i.e. convert your table variables @pop31310, @pop11310, @pop30390, @pop10390 into temp tables, and give each one an index on the ReceiptNumber column.
Can I make this faster?
[ "", "sql", "sql-server-2005", "performance", "" ]
I have a structure named WaveSize to represent both an amount of samples or an amount of time, but I'm also using this structure to represent a position or an offset within a wave. While it's pretty common to represent both sizes and positions within a coordinate system with a Vector2d type, I'm unable to find a good name abstract enough to represent wave lengths and wave positions/offsets. I find odd to see something like: ``` public WaveSize Size { get; } public WaveSize Offset { get; } ``` I'd rather come up with a good name than creating empty classes or using 'using'. Any suggestions will be much appreciated. Thanks in advance. EDIT: As Reed Copsey & Marc Gravel suggested it makes a lot of sense to have two different classes since they are two different concepts, so, any similarities in code should be seen as mere coincidences.
I would have two separate structs, and make conversions easy between them. You're trying to represent two concepts here, one for position, and one for size. Since these are two conceptually distinct ideas, I'd make them two structs. I also agree with [Marc Gravell's answer](https://stackoverflow.com/questions/853219/how-to-name-a-struct-that-represents-both-a-size-and-a-position/853256#853256) regarding the BCL's Point/Size structs. I think they're a good model to follow.
You could compare to the winforms `Point` and `Size` structures... they decided that even if they are similar, to keep them separate. It makes sense at the algebraic sense: ``` Point - Point = Size Point + Size = Point Size + Size = Size Point + Piont = ???? error (no defined operator) ``` etc
How to name a struct that represents both a size and a position?
[ "", "c#", "data-structures", "naming-conventions", "size", "position", "" ]
I set up this test page up on my server. Please tell me why the `$_POST` array does not contain anything even when I submit the form. I have tried this in three different browsers and nothing happens. ``` <?php print_r($_POST);?> <form method="post"> <p><label>Email: </label> <input type="text" id="login_email" /> </p> <p><label>Password: </label> <input type="password" id="login_password" /> </p> <p><label>Remember Me?: </label> <input type="checkbox" id="login_remember" /> </p> <p> <input type="submit" value="Login" /> </p> </form> ``` I have been writing PHP for years and this has never happened before. What is wrong with this code?
Your input elements do not have name attributes. Should be: ``` <input type="text" id="login_email" name="login_email" /> ``` If an input element does not have a name attribute, it is not sent as part of the POST data.
Well, you don't have an action for the form tag? It should be the script name: ``` <form method="post" action="scriptname.php"> ``` ...and you're also not setting the names for each form input - the browser doesn't submit the ID as the element name.
$_POST is empty after form submission
[ "", "php", "html", "forms", "post", "" ]
I generate some png charts and excel files using a mysql database. I display the charts as images in my webapplication, but from time to time IE users don;t have acces to the last version of the files because IE keeps showing to them the previous loaded datas(charts and excel files) How to prevent happening that? On the client side what can be done? My web-application is written in PHP. What approach should i use in order to force IE to load the new files?
Another approach you can use is to add a unique query string to the images you're showing. On the image handler, you can ignore the data that is actually passed on the query string, but IE will treat URLs with different query strings as being unique and therefore require loading each one anew without using a cached version. For example, changing: ``` <img src="mychart.png> ``` to: ``` <img src="mychart.png?timestamp=0512200911090000"> ``` will get you to avoid the IE cache.
``` <HTML><HEAD> <META HTTP-EQUIV="Pragma" CONTENT="no-cache"> <META HTTP-EQUIV="Expires" CONTENT="-1"> </HEAD><BODY> </BODY> </HTML> ```
IE history
[ "", "php", "internet-explorer", "caching", "" ]
How can i reference a class property knowing only a string? ``` class Foo { public $bar; public function TestFoobar() { $this->foobar('bar'); } public function foobar($string) { echo $this->$$string; //doesn't work } } ``` what is the correct way to eval the string?
You only need to use one $ when referencing an object's member variable using a string variable. ``` echo $this->$string; ```
If you want to use a property value for obtaining the name of a property, you need to use "{" brackets: ``` $this->{$this->myvar} = $value; ``` Even if they're objects, they work: ``` $this->{$this->myobjname}->somemethod(); ```
dynamic class property $$value in php
[ "", "php", "class", "dynamic", "variables", "properties", "" ]
I've got an app written in PHP, and there are a number of configurable variables. We're implementing a feature where the user can create sets of configurations and easily switch between them. How should I store my configs? as XML? in a .ini file? in multiple .ini files? in a db? What's going to provide the most flexibility if we add fields down the road? Coding convenience? If I use a db, I'll have to use a separate one from the app's main one for reasons that aren't worth going into, which has made me shy away from that. (Also, we're using .mdb files for our db.) I've been going down the xml route, but I'm having problems with adding and editing configs using SimpleXML. Also, the app has to be compatible with php 5.1.6, and I'm a little nervous about some of the functionality. Never really dealt with creating custom ini files.... A small clarification: the users won't touch the files -- they're non-techie. So setting up the initial files will be done by us, but then we're writing a tool that is going to writie out their configuration(s) to whatever format we choose.
Storing the settings for one DB in a different DB does not make much sense, IMO. I would choose either an ini file, an xml file, or a php file, as proposed by [jmucchiello](https://stackoverflow.com/questions/798654/how-to-store-configurations-for-php-app-xml-or-ini-or-db/798708#798708). Each option has it's pros and cons. As for xml versus ini, xml offers more flexibility but is more difficult to maintain (less readable). If your needs are covered by ini, stick with the simpler solution. Use xml only if you need more than ini files can offer you. As for the php solution, I would rate the readability somewhere between ini and xml, but it would be more difficult to save the current settings. So as much as I like the approach, for your current scenarion I would not recommend it.
I would store the configurations items in a PHP file. This is the most flexible method *I* have used. ``` $config['website_url'] = 'google.com'; ``` I then have the following file structure ``` - config/development - config/production ``` I have a constant defined early in the software named **IN\_PRODUCTION**, when this is **TRUE** it loads up the production configuration items and vice versa. This is simple and easily maintainable. -Mathew
how to store configurations for php app -- xml or ini or db
[ "", "php", "configuration", "" ]
How do I embed an external executable inside my C# Windows Forms application? Edit: I need to embed it because it's an external free console application (made in C++) from which I read the output values to use in my program. It would be nice and more professional to have it embedded. Second reason is a requirement to embed a Flash projector file inside a .NET application.
Here is some sample code that would roughly accomplish this, minus error checking of any sort. Also, please make sure that the license of the program to be embedded allows this sort of use. ``` // extracts [resource] into the the file specified by [path] void ExtractResource( string resource, string path ) { Stream stream = GetType().Assembly.GetManifestResourceStream( resource ); byte[] bytes = new byte[(int)stream.Length]; stream.Read( bytes, 0, bytes.Length ); File.WriteAllBytes( path, bytes ); } string exePath = "c:\temp\embedded.exe"; ExtractResource( "myProj.embedded.exe", exePath ); // run the exe... File.Delete( exePath ); ``` The only tricky part is getting the right value for the first argument to `ExtractResource`. It should have the form "namespace.name", where namespace is the default namespace for your project (find this under Project | Properties | Application | Default namespace). The second part is the name of the file, which you'll need to include in your project (make sure to set the build option to "Embedded Resource"). If you put the file under a directory, e.g. Resources, then that name becomes part of the resource name (e.g. "myProj.Resources.Embedded.exe"). If you're having trouble, try opening your compiled binary in Reflector and look in the Resources folder. The names listed here are the names that you would pass to `GetManifestResourceStream`.
Simplest way, leading on from what [Will said](https://stackoverflow.com/questions/798655/embedding-an-external-executable-inside-a-c-sharp-program/9719279#comment3659796_799015): 1. Add the .exe using Resources.resx 2. Code this: ``` string path = Path.Combine(Path.GetTempPath(), "tempfile.exe"); File.WriteAllBytes(path, MyNamespace.Properties.Resources.MyExecutable); Process.Start(path); ```
Embedding an external executable inside a C# program
[ "", "c#", "windows", "embed", "executable", "" ]
Django has a number of open source projects that tackle one of the framework's more notable [missing features](http://code.djangoproject.com/wiki/SchemaEvolution): model "evolution". Ruby on Rails has native support for [migrations](http://api.rubyonrails.org/classes/ActiveRecord/Migration.html), but I'm curious if anyone can recommend one of the following Django "evolution" projects: * [South](http://south.aeracode.org/) * [django-evolution](http://code.google.com/p/django-evolution/) * [dmigrations](http://code.google.com/p/dmigrations/)
South has the most steam behind it. dmigrations is too basic IMO. django-evolution screams if you ever touch the db outside of it. South is the strongest contender by far. With the model freezing and auto-migrations it's come a long way.
South and django-evolution are certainly the best options. South's model-freezing and auto-hinting are still quite fragile in my experience (django-evolution's hinting is much more robust in edge cases), but django-evolution's development seems to have mostly stalled since last summer. If I were starting now I'd probably pick South, mostly for that reason.
How can you migrate Django models similar to Ruby on Rails migrations?
[ "", "python", "django", "migration", "" ]
I have created a [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) application in .NET 2 using C# that runs continuously. For most accounts I am pleased with it, but it has been reported to me that it has failed occasionally. I am able to monitor its performance for 50% of the time and I have never noticed a failure. At this point I am concerned that perhaps the program is using too many resources and is not disposing of resources when they are no longer required. What are the best practices for properly disposing created objects that have created timers and graphical objects like graphics paths, SQL connections, etc. or can I rely on the dispose method to take care of all garbage collection? Also: Is there a way that I could monitor resources used by the application?
Best practice is to make sure that all objects implementing the [IDisposable](http://msdn.microsoft.com/en-us/library/system.idisposable.aspx) interface is called Dispose on as soon as the object is no longer required. This can be accomplished either with the [using](http://msdn.microsoft.com/en-us/library/yh598w02.aspx) keyword or [try/finally](http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx) constructs. Within a WinForms form that has resources allocated for the lifetime of the form, a somewhat different approach is necessary. Since the form itself implements IDisposable this is an indication that at some point in time Dispose will be called on this form. You want to make sure that your disposable resources gets disposed at the same time. To do this you should override the forms [Dispose(bool disposing)](http://msdn.microsoft.com/en-us/library/a4zkb31d.aspx) method. The implementation should look something like this: ``` protected override void Dispose(bool disposing) { if (disposing) { // dispose managed resources here } // dispose unmanaged resources here } ``` A note on Components in forms: if your object implements the [IComponent](http://msdn.microsoft.com/en-us/library/system.componentmodel.icomponent.aspx) interface you can place the instance in the forms [Container](http://msdn.microsoft.com/en-us/library/system.componentmodel.component.container.aspx). The container will take care of disposing components when the container itself is disposed.
In addition to what's already been said, if you're using COM components it's a very good idea to make sure that they are fully released. I have a snippet that I use all the time for COM releases: ``` private void ReleaseCOMObject(object o) { Int32 countDown = 1; while(countDown > 0) countDown = System.Runtime.InteropServices.Marshal.ReleaseCOMObject(o); } ```
How do I ensure that objects are disposed of properly in .NET?
[ "", "c#", ".net", "" ]
I want to create edit , delete link in display tag with struts2. How can i do so ? If anybody knows please help me .... i am doing this. ``` <display:column property="id" title="ID" href="details.jsp" paramId="id" /> ``` but the link is not going to details.jsp .It doesn't go anywhere . what can be the possible reason
It is done by the following code. ``` <display:column title="Edit"> <s:url id="updateUrl" action="marketing/update.action"> <s:param name="id" value="#attr.countrylist.id" /> </s:url> <s:a href="%{updateUrl}" theme="ajax" targets="countrylist">Update</s:a> </display:column> ``` Thanks for all the answers
You can write your stuff within the tag like this: ``` <display:table id="row" > <display:column property="id" title="ID" paramId="id" > <a href="details.jsp?${row.id}">Details</a> </display:column> </display:table> ```
How can i create a link in displaytag?
[ "", "java", "struts2", "displaytag", "" ]
I am a newbie to Java Web Application development. So far all I have used are plain old servlets, jdbc and jsps. I started to read about all the frameworks and I am totally confused and lost in the swarm of frameworks? So here are some questions I have: 1. Are EJB3 and Hibernate competing technologies or can they be used together. 2. If I used JBoss Seam, do I still need to use Hibernate for my ORM needs or Seam + EJB3 takes care of that? 3. What are the typical frameworks I will need to learn if I have to develop a webapp using JBoss Seam? Is it some or all of the following: Seam (ofcourse) JSF EJB3 Hibernate Spring Inversion of control container 4. Can I use JBoss Seam to develop an application on JBoss Portal? thanks Vikas
*1. Are EJB3 and Hibernate competing technologies or can they be used together.* They have competing APIs (JPA is different from Hibernate's API) but Hibernate can be plugged in underneath JPA, just don't expect interoperability with things coded for Hibernate - notably jBPM (3.2) does not entirely interoperate even under Seam (2.1.1). *2. If I used JBoss Seam, do I still need to use Hibernate for my ORM needs or Seam + EJB3 takes care of that?* As I understabnd it, you can do either. *3. What are the typical frameworks I will need to learn if I have to develop a webapp using JBoss Seam? Is it some or all of the following: Seam (ofcourse) JSF EJB3 Hibernate Spring Inversion of control container* JSF - essential for Seam to really make sense afaict - I recommend focusing on facelets as a primary way of creating JSF pages. The syntax is nice and familiar - plain old namespace qualified XHTML with server side components sitting within separate namespaces. Utterly trivial and clean, unlike pretty much anything else I've tried. EJB3 - if you like, or not, up to you. Heading this way drags you into Java EE which still scares me a little, though it has many benefits. Hibernate - if you like, up to you. JPA entity managers provide the alternative. Spring IoC, er... yeah sure if you like, again its up to you. Seam takes care of stateful session and conversation scoped beans (generally part of your presentation logic tier) and Spring is best for the stateless context, such as interfaces to back end services such as databases and any SOA clients. I've found Seam + JSF (facelets) + Hibernate + Spring to be quite a good combination for creating UIs over jBPM and also on another project for delivering content pages, though that is not really what Seam is for. 4. Can I use JBoss Seam to develop an application on JBoss Portal? Sorry, can't help you there.
1. EJB3 and Hibernate are complementing technologies. EJB3 defines JPA (API) and Hibernate can be used as persistence provider for JPA. 2. You still need to use one of persistence providers which could be Hibernate, OpenJPA, etc. 3. JSF and EJB3. 4. Regarding Seam and Portal development: better question would be is how well JSF and Portal work together? They do work together of course - here is relevant tutorial: [Developing Portlets using JSF, Ajax, and Seam](http://www.infoq.com/articles/jsf-ajax-seam-portlets-pt-1)
How do various Java frameworks for web application design tie together
[ "", "java", "jakarta-ee", "frameworks", "seam", "" ]
If I have a class that looks something like this: ``` public class MyClass<T extends Enum<T>> { public void setFoo(T[] foos) { .... } } ``` How would I go about declaring this as a bean in my context xml so that I can set the Foo array assuming I know what T is going to be (in my example, let's say T is an enum with the values ONE and TWO)? At the moment, having something like this is not enough to tell spring what the type T is: ``` <bean id="myClass" class="example.MyClass"> <property name="foo"> <list> <value>ONE</value> <value>TWO</value> </list> </property> </bean> ``` Edit: Forgot the list tag.
Spring has no generic support for that case, but the compiler just creates a class cast in this case. So the right solution is: ``` <bean id="myClass" class="example.MyClass"> <property name="foo"> <list value-type="example.MyEnumType"> <value>ONE</value> <value>TWO</value> </list> </property> </bean> ```
Consider working example. ``` <bean id="simpleInt" class="org.nipr.gateway.service.transaction_assistant.GenericSimple"> <constructor-arg> <!-- this can be any full path to a class --> <value>java.lang.Integer</value> </constructor-arg> </bean> ``` and ``` <bean id="simpleString" class="org.nipr.gateway.service.transaction_assistant.GenericSimple"> <constructor-arg> <value>java.lang.String</value> </constructor-arg> </bean> ``` Simple generic class: ``` public class GenericSimple<T> { private Class<T> type; public GenericSimple(Class<T> type) { this.type = type; } public T get( T t) { return t; } } ``` And finally, the test method (using factory): ``` public void testGeneric(){ Factory factory = new Factory(new String[]{"config/beanForGenericTest.xml"}); GenericSimple<Integer> simpleInt = (GenericSimple<Integer>)factory.getClass("simpleInt"); System.out.println(simpleInt.get(Integer.valueOf(100))); Assert.assertTrue(simpleInt.get(Integer.valueOf(100)).equals(100)); GenericSimple<String> simpleString = (GenericSimple<String>)factory.getClass("simpleString"); System.out.println(simpleString.get(new String("Rockets go fast."))); Assert.assertTrue(simpleString.get("Rockets go fast.") .equals("Rockets go fast.")); } ```
Defining spring bean using a class with generic parameters
[ "", "java", "generics", "spring", "" ]
I'm completely new to databinding in WPF, and I'm trying to bind an object property to a textbox. My object is ``` public class TestObj { private m_Limit; public string Limit { get { return m_Limit; } set { m_Limit = value; } } ``` My XAML looks like ``` <Window x:Class="NECSHarness2.UpdateJobParameters" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:tools="clr-namespace:ManagementObjects;assembly=Core" DataContext="{Binding RelativeSource={RelativeSource Self}}" Title="Update Job Parameters" Height="320" Width="460"> <Grid> <TextBox Text ="{Binding Path = Limit, Mode = TwoWay}" Height="20" HorizontalAlignment="Right" Margin="0,48,29,0" Name="textBox3" VerticalAlignment="Top" Width="161" /> </Grid> ``` Now, obviously I'm not setting the source anywhere, and I'm very confused. I got this to work with a listview, but now I'm stumped. Thanks for any help.
You need to set the DataContext. Either in the code behind: ``` textBox3.DataContext = instanceOfTestObj; ``` Or using an object data provider ``` <Window.Resources> <src:TestObj x:Key="theData" Limit="Wibble" /> </Window.Resources> <TextBox Text="{Binding Source={StaticResource theData}..../> ``` There is a nice introduction to databinding in more depth [here](http://www.wrox.com/WileyCDA/Section/Windows-Presentation-Foundation-WPF-Data-Binding-with-C-2005.id-305562.html).
If you don't specify binding's Source, RelativeSource or ElementName the Binding uses control's DataContext. The DataContext is passed through the visual tree from upper element (e.g. Window) to the lower ones (TextBox in your case). So WPF will search for the Limit property in your Window class (because you've bound the window's DataContext to the window itself). Also, you may want to read basics about DataBinding in WPF: <http://msdn.microsoft.com/en-us/library/ms750612.aspx>
DataBind to a textbox in WPF
[ "", "c#", "wpf", "data-binding", "textbox", "" ]
I my working on the site that will have image gallery. Designer idea was to make buttons that switch photos be above the photos a bit. Like this [Example http://img57.imageshack.us/img57/1253/showq.png](http://img57.imageshack.us/img57/1253/showq.png) Currently I've made a javascript solution to this - it gets position of photo and applies absolute positioning to the button divs. There are some drawbacks - it works unstable in Opera and IE. Also I had to make some dirty haxx to make it stay in position after zooming. I wonder if there is a better way to do this, preferably without javascript.
you mean like [here](http://bivakbenoordenhout.nl/) ? (dutch website, see photo browser in the center column at the top) browser zooming works fine in browsers like firefox and safari because they zoom all the content and recorrect pixel-values. To make zooming work in ie(6) you'd need to style all in em's. But browser zooming is crappy for pixel data anyways… Absolute positioning of the buttons (left 0 and right 0) is not a problem as long as the container element is positioned relative.
If I understand you correctly, you're trying to center those arrow buttons vertically in relation to the image. This is pretty easily accomplished with just CSS (no javascript required). Here's an [example](http://www.jakpsatweb.cz/css/css-vertical-center-solution.html). The basic idea is that you're using a couple of divs plus some absolute/relative positioning. There's an outer div that drops the top of the whole thing to the center of the parent element and then an inner div that pulls up your content so that the content is centered and not the top of the element.
Making overlay <div> that stays in position after zoom-resize using HTML-CSS only
[ "", "javascript", "html", "css", "" ]
I want to manage a Transaction in my persistence layer, But when I try to fetch the results lazily I get this error: > org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role Can I use LockMode or any other way to solve this problem? Can a find a Object by its id without any Transaction?
Your problem is that the Hibernate session is already closed when you try to access the content. Hibernate cannot load the content without a session. There are usually two ways to mitigate this problem: 1. Don't close the session until you are done with the page. This pattern is called "session in view" and can for example be implemented with a servlet filter. 2. Initialize all contents that you'll need before closing the session. If you want to initialize the whole object you can use Hibernate.initialize(object). edit: You cannot do anything outside of an transaction in Hibernate.
You can also look at the official solution from hibernate at <http://www.hibernate.org/43.html>
hibernate lazy initialization issue: LazyInitializationException: failed to lazily initialize a collection of role
[ "", "java", "hibernate", "lazy-initialization", "" ]
The current implementation of [Remy Sharp's jQuery tag suggestion plugin](http://remysharp.com/2007/12/28/jquery-tag-suggestion/) only checks for matches at the beginning of a tag. For example, typing "Photoshop" will not return a tag named "Adobe Photoshop". By default, the search is case-sensitive. I have slightly modified it to trim excess spaces and ignore case: ``` for (i = 0; i < tagsToSearch.length; i++) { if (tagsToSearch[i].toLowerCase().indexOf(jQuery.trim(currentTag.tag.toLowerCase())) === 0) { matches.push(tagsToSearch[i]); } } ``` What I have tried to do is modify this again to be able to return "Adobe Photoshop" when the user types in "Photoshop". I have tried using `match`, but I can't seem to get it to work when a variable is present in the pattern: ``` for (i = 0; i < tagsToSearch.length; i++) { var ctag = jQuery.trim(currentTag.tag); if (tagsToSearch[i].match("/" + ctag + "/i")) { // this never matches, presumably because of the variable 'ctag' matches.push(tagsToSearch[i]); } } ``` What is the correct syntax to perform a regex search in this manner?
If you want to do regex dynamically in JavaScript, you have to use the [RegExp object](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp). I believe your code would look like this (haven't tested, not sure, but right general idea): ``` for (i = 0; i < tagsToSearch.length; i++) { var ctag = jQuery.trim(currentTag.tag); var regex = new RegExp(ctag, "i") if (tagsToSearch[i].match(regex)) { matches.push(tagsToSearch[i]); } } ```
Instead of ``` "/" + ctag + "/i" ``` Use ``` new RegExp(ctag, "i") ```
How do I perform a Javascript match with a pattern that depends on a variable?
[ "", "javascript", "regex", "autocomplete", "match", "" ]
I'm trying to add a directory to the classpath of an application run profile If I override by using -cp x:target/classes in the VM settings, I get the following error: ``` java.lang.NoClassDefFoundError: com/intellij/rt/execution/application/AppMain ``` Any idea on how to add a directory to the classpath for my project?
In Intellij 13, it looks it's slightly different again. Here are the instructions for Intellij 13: 1. click on the Project view or unhide it by clicking on the "1: Project" button on the left border of the window or by pressing Alt + 1 2. find your project or sub-module and click on it to highlight it, then press F4, or right click and choose "Open Module Settings" (on IntelliJ 14 it became F12) 3. click on the dependencies tab 4. Click the "+" button on the right and select "Jars or directories..." 5. Find your path and click OK 6. In the dialog with "Choose Categories of Selected File", choose `Classes` (even if it's properties), press OK and OK again 7. You can now run your application and it will have the selected path in the class path
It appears that IntelliJ 11 has changed the method, and the checked answer no longer works for me. In case anyone else arrives here via a search engine, here's how I solved it in IntelliJ 11: 1. Go to the Project Structure, click on Modules, and click on your Module 2. Choose the "Dependencies" tab 3. Click the "+" button on the right-hand side and select "Jars or directories..." 4. Add the directory(ies) you want (note you can multi-select) and click OK 5. In the dialog that comes up, select "classes" and NOT "jar directory" 6. Make sure you're using that Module in your run target Note that step 5 seems to be the key difference. If you select "jar directory" it will look exactly the same in the IDE but won't include the path at runtime. There appears to be no way to determine whether you've previously selected "classes" or "jar directory" after the fact.
How to add directory to classpath in an application run profile in IntelliJ IDEA?
[ "", "java", "intellij-idea", "classpath", "" ]
I've confused myself nicely here. My scenario is as follows: ``` function DesignPad() { function EditBar() { ... this.removeHandler = function() { **// how do I call Dragger.removeAsset** } } function Dragger(){ ... this.removeAsset = function() {} } this.init = function() { this.editBar = new EditBar(); this.dragger = new Dragger(); } } var dp = new DesignPad(); ... ``` I can't seem to call `Dragger.RemoveAsset`. I understand the why, my question is how do I call it? I'm trying to keep like-things separated (e.g. Dragger / EditBar) but I seem to get all sorts of mixed up in my event handlers. Any suggestions, good reading materials, etc. on this stuff?
I found [Douglas Crockford's Javascript](http://www.crockford.com/javascript/) to be the best introduction to JavaScript. Especialy videos for Yahoo, like: [The JavaScript Programming Language](http://yuiblog.com/blog/2007/01/24/video-crockford-tjpl/) where you can learn how exactly are objects created and inherited in JS. Solution to you problem is: ``` function DesignPad() { var that = this; function EditBar() { this.removeHandler = function() { print("RemoveHandler"); that.dragger.removeAsset(); } } function Dragger() { this.removeAsset = function() { print("RemoveAsset"); } } this.init = function() { this.editBar = new EditBar(); this.dragger = new Dragger(); } } var dp = new DesignPad(); dp.init(); dp.editBar.removeHandler(); ``` But as others noticed you could refactor some things :).
To me it just looks like you should refactor that code to make it simpler. I think that your issue comes from the fact that a nested function is private, so you can't access it from outside.
Javascript Object Confusion
[ "", "javascript", "dom-events", "" ]
I am wondering the "how it works" and "how it should be designed and implemented" side of the basic drag & drop functionality. I have never yet implemented such functionality. I am planning to do so for one of my projects and I do have some ideas on how to implement it. I wanted to make sure I am on the right path and that you people most probably have something to say about the matter too... Let's imagine I have 5 elements listed as following and grabbed from a database; ``` <div id="1">this is content for 1</div> <div id="2">this is content for 2</div> <div id="3">this is content for 3</div> <div id="4">this is content for 4</div> <div id="5">this is content for 5</div> ``` since this is pulled off from a database we know that it has a field called "sequence" or "order" to distinguish the order we are going to output. Let's also imagine currently the "sequence" column values are the same as the IDs of the divs. so: `1`, `2`, `3`, `4` and `5` respectively. My question and thoughts; If I drag div `4` and drop it between `1` and `2`; what are the steps from there on? E.g: 1. determine the id of the div that is being dragged (let's call this `div-a`) 2. determine the id of the div that `div-a` is being inserted after (or before) in this case after and therefore after div `id` `1` (let's call this `div-b`) 3. Update `div-a`'s sequence in DB and set it to the current sequence of `div-b` After this step, I am all confused... Do I count all the divs and according to whichever order the divs are, do I update the DB accordingly? Or am I completely wrong and is there another way? --- thanks for the answers but I know there are plugins and other stuff to get this done but I am only interested in the logic part of it.
I believe jquery gives you a way to grab their order based on id? The way I've been doing it is every time an action occurs, grab the current order, send it back to my app via ajax. Then my app just parses out the ids from what it was given and updates every item's order value.
<http://jqueryui.com/demos/sortable/> ``` $("#col1").sortable({ placeholder: "top", forcePlaceholderSize: true, revert: true, update: function() { $.ajax({ type: "GET", url: "/request.php", data: "data="+$(this).sortable("toArray")+"", success: function(msg){ } }); } }); ``` toArray is a sequence of your divs ids
Logic behind drag and drop
[ "", "javascript", "jquery", "drag-and-drop", "client-side", "" ]
I have a problem when I'm trying to delete an image file. I always get an error that says: IOExeption was unhandled. Acces denied because the file is beining used by another process. I do'nt know what process that could be and how to solve it. ``` private void comboBox3_SelectedIndexChanged(object sender, EventArgs e) { Album album = GetAlbum(comboBox1.SelectedIndex); Photo photo = GetPhoto(comboBox1.SelectedIndex, comboBox3.SelectedIndex); txtPhotoPath.Text = Directory.GetCurrentDirectory() + "\\" + photo.SPath; lblExtention.Text = photo.SExtention; txtPhotoTitle.Text = photo.STitle; pctrbFoto.Image = Image.FromFile(foto.SPath).GetThumbnailImage(GetWitdth(photo.SPath, GetHeight(photo.SPath, 150)), GetfHeight(photo.SPath, 150), null, new IntPtr()); } private void btnChangePhoto_Click(object sender, EventArgs e) { Album album = GetAlbum(comboBox1.SelectedIndex); Photo photo = GetPhoto(comboBox1.SelectedIndex, comboBox3.SelectedIndex); File.Delete("Albums\\Images\\" + photo.STitle + foto.SExtention); photo.SExtention = lblExtention.Text; photo.STitle = txtPhotoTitel.Text; Photo.SPath = txtPath.Text; File.Copy(photo.SPath, "Albums\\Images\\" + photo.STitle + photo.SExtention); } ``` Thanks, Vinzcent --- Thanks to all for the help. I used this and it works very well now --- your process is the one that uses file , you need to set image to null use something like this : var img = Image.FromFile(foto.SPath).GetThumbnailImage(GetWitdth(photo.SPath, GetHeight(photo.SPath, 150)), GetfHeight(photo.SPath, 150), null, new IntPtr()); pctrbFoto.Image = img; img = null; GC.Collect();
your process is the one that uses file , you need to set image to null use something like this : ``` using(var img = Image.FromFile(foto.SPath).GetThumbnailImage(GetWitdth(photo.SPath, GetHeight(photo.SPath, 150)), GetfHeight(photo.SPath, 150), null, new IntPtr())) pctrbFoto.Image = img; ```
The first area I would look is in your GetPhoto method. Do you have a StreamReader that hasn't been closed? Make sure that if you're doing any sort of I/O on the file prior to the delete that you close those connections first. What does the GetPhoto() method do?
C# File.Delete, file being used by another process
[ "", "c#", "error-handling", "" ]
I was debugging a multi-threaded application and found the internal structure of `CRITICAL_SECTION`. I found data member `LockSemaphore` of CRITICAL\_SECTION an interesting one. It looks like `LockSemaphore` is an auto-reset event (not a semaphore as the name suggests) and operating system creates this event silently when first time a thread waits on `Critcal Section` which is locked by some other thread. Now, I am wondering is Critical Section always faster? Event is a kernel object and each Critical section object is associated with event object then how `Critical Section` can be faster compared to other kernel objects like Mutex? Also, how does internal event object actually affects the performance of Critical section ? Here is the structure of the `CRITICAL_SECTION`: ``` struct RTL_CRITICAL_SECTION { PRTL_CRITICAL_SECTION_DEBUG DebugInfo; LONG LockCount; LONG RecursionCount; HANDLE OwningThread; HANDLE LockSemaphore; ULONG_PTR SpinCount; }; ```
When they say that a critical section is "fast", they mean "it's cheap to acquire one when it isn't already locked by another thread". [Note that if it *is* already locked by another thread, then it doesn't matter nearly so much how fast it is.] The reason why it's fast is because, before going into the kernel, it uses the equivalent of `InterlockedIncrement` on one of those `LONG` field (perhaps on the the `LockCount` field) and if it succeeds then it considers the lock aquired without having gone into the kernel. The `InterlockedIncrement` API is I think implemented in user mode as a "LOCK INC" opcode ... in other words you can acquire an uncontested critical section without doing any ring transition into the kernel at all.
In performance work, few things fall into the "always" category :) If you implement something yourself that is similar to an OS critical section using other primitives then odds are that will be slower in most cases. The best way to answer your question is with performance measurements. How OS objects perform is *very* dependent on the scenario. For example, critical sections are general considered 'fast' if contention is low. They are also considered fast if the lock time is less than the spin count time. The most important thing to determine is if contention on a critical section is the first order limiting factor in your application. If not, then simply use a critical section normaly and work on your applications primary bottleneck (or necks). If critical section performance is critical, then you can consider the following. 1. Carefully set the spin lock count for your 'hot' critical sections. If performance is paramount, then the work here is worth it. Remember, while the spin lock does avoid the user mode to kernel transition, it consumes CPU time at a furious rate - while spinning, nothing else gets to use that CPU time. If a lock is held for long enough, then the spinning thread will actual block, freeing up that CPU to do other work. 2. If you have a reader/writer pattern then consider using the [Slim Reader/Writer (SRW) locks](http://msdn.microsoft.com/en-us/library/aa904937(VS.85).aspx). The downside here is they are only available on Vista and Windows Server 2008 and later products. 3. You may be able to use [condition variables](http://msdn.microsoft.com/en-us/library/ms682052(VS.85).aspx) with your critical section to minimize polling and contention, waking threads only when needed. Again, these are supported on Vista and Windows Server 2008 and later products. 4. Consider using [Interlocked Singly Linked Lists](http://msdn.microsoft.com/en-us/library/ms684121(VS.85).aspx) (SLIST)- these are efficient and 'lock free'. Even better, they are supported on XP and Windows Server 2003 and later products. 5. Examine your code - you may be able to break up a 'hot' lock by refactoring some code and using an interlocked operation, or SLIST for synchronization and communication. In summary - tuning scenarios that have lock contention can be challenging (but interesting!) work. Focus on measuring your applications performance and understanding where your hot paths are. The xperf tools in the [Windows Performance Tool kit](http://msdn.microsoft.com/en-us/library/cc305187.aspx) is your friend here :) We just released version 4.5 in the Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1 ([ISO is here](http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=6db1f17f-5f1e-4e54-a331-c32285cdde0c), [web installer here](http://www.microsoft.com/downloads/details.aspx?familyid=F75F2CA8-C1E4-4801-9281-2F5F28F12DBD&displaylang=en)). You can find the forum for the xperf tools [here](http://social.msdn.microsoft.com/Forums/en-US/wptk_v4/threads). V4.5 fully supports Win7, Vista, Windows Server 2008 - all versions.
Is Critical Section always faster?
[ "", "c++", "winapi", "synchronization", "critical-section", "" ]
Is it possible to declarate optional parameters in methods? In delphi,for example,I can do something like: ``` procedure Test(p1:integer;p2:integer;p3:integer = 2;p4:integer = 4) ``` When I call that function I can call it with four parameters or with two parameters: ``` Test(2,3); //p3 = 2,p4 = 4. Test(2,3,4,5); //p3 = 4,p4 = 5; ``` How is that possible in C#?
I'm afraid this isn't possible in C# 1 to 3. However, the good news is that because it's been a much-demanded feature (though there are certainly some who would rather not see it), Microsoft have finally decided to add it to C# 4. The C# 4 syntax goes as follows: ``` public static void SayHello(string s = "Hello World!") { Console.WriteLine(s); } ``` Usage: ``` SayHello(); // Prints "Hello World!" SayHello("Hello."); // Prints "Hello." SayHello(s: "Hello."); // Prints "Hello." ``` (The last example uses a named argument, which really isn't necessary in this case, but helps when you have multiple optional parameters.) You can read more about that subject on [this blog post](http://bartdesmet.net/blogs/bart/archive/2008/10/31/c-4-0-feature-focus-part-1-optional-parameters.aspx).
You'll either have to wait for [C# 4.0](http://channel9.msdn.com/posts/mike+ormond/C-40-New-Features-Optional-Parameters/), which supports optional parameters, or use standard overloading mechanisms: ``` void Test(int p1, int p2, int p3, int p4) { } void Test(int p1, int p2) { Test(p1, p2, 2, 4); } ```
How do I put optional parameters in methods?
[ "", "c#", "methods", "" ]
Does anyone know what the complexity is for the SQL `LIKE` operator for the most popular databases?
Let's consider the three core cases separately. This discussion is MySQL-specific, but might also apply to other DBMS due to the fact that indexes are typically implemented in a similar manner. **`LIKE 'foo%'` is quick if run on an indexed column.** MySQL indexes are a variation of B-trees, so when performing this query it can simply descend the tree to the node corresponding to `foo`, or the first node with that prefix, and traverse the tree forward. All of this is very efficient. **`LIKE '%foo'` can't be accelerated by indexes and will result in a full table scan.** If you have other criterias that can by executed using indices, it will only scan the the rows that remain after the initial filtering. *There's a trick though*: If you need to do suffix matching - searching for file names with extension `.foo`, for instance - you can achieve the same performance by adding a column with the same contents as the original one but with the characters in reverse order. ``` ALTER TABLE my_table ADD COLUMN col_reverse VARCHAR (256) NOT NULL; ALTER TABLE my_table ADD INDEX idx_col_reverse (col_reverse); UPDATE my_table SET col_reverse = REVERSE(col); ``` Searching for rows with `col` ending in `.foo` then becomes: ``` SELECT * FROM my_table WHERE col_reverse LIKE 'oof.%' ``` **Finally, there's `LIKE '%foo%'`, for which there are no shortcuts.** If there are no other limiting criterias which reduces the amount of rows to a feasible number, it'll cause a hard performance hit. You might want to consider a full text search solution instead, or some other specialized solution.
Depends on the RDBMS, the data (and possibly size of data), indexes and how the LIKE is used (with or without prefix wildcard)! You are asking too general a question.
SQL `LIKE` complexity
[ "", "sql", "database", "complexity-theory", "sql-like", "" ]
A 64-bit double can represent integer +/- 253 exactly. Given this fact, I choose to use a double type as a single type for all my types, since my largest integer is an unsigned 32-bit number. But now I have to print these pseudo integers, but the problem is they are also mixed in with actual doubles. So how do I print these doubles nicely in Java? I have tried `String.format("%f", value)`, which is close, except I get a lot of trailing zeros for small values. Here's an example output of of `%f` ``` 232.00000000 0.18000000000 1237875192.0 4.5800000000 0.00000000 1.23450000 ``` What I want is: ``` 232 0.18 1237875192 4.58 0 1.2345 ``` Sure I can write a function to trim those zeros, but that's lot of performance loss due to string manipulation. Can I do better with other format code? --- The answers by Tom E. and Jeremy S. are unacceptable as they both arbitrarily rounds to two decimal places. Please understand the problem before answering. --- Please note that `String.format(format, args...)` is ***locale-dependent*** (see answers below).
If the idea is to print integers stored as doubles as if they are integers, and otherwise print the doubles with the minimum necessary precision: ``` public static String fmt(double d) { if(d == (long) d) return String.format("%d",(long)d); else return String.format("%s",d); } ``` Produces: ``` 232 0.18 1237875192 4.58 0 1.2345 ``` And does not rely on string manipulation.
``` String.format("%.2f", value); ```
How to nicely format floating numbers to string without unnecessary decimal 0's
[ "", "java", "string", "floating-point", "format", "double", "" ]
I'd like to compare some large objects representing trees and cache ***something*** to avoid comparing each time the new object with one already existing... The question is what would be the best something ? (a compromise between performance and collisions...). On the one hand, I have a regular hashCode function based on the value of various fields (following the chapter 3 of [effective Java](http://java.sun.com/developer/Books/effectivejava/). But I'm not able to evaluate the potential collisions entailed by such an approach. On the other hand, I have the MessageDigest approach from the standard java distribution with SHA-1 algorithm. I presume it's not going to be efficient but I may have less collision. Am I right ? Is it a correct solution in my context or am I completely wrong ? The thing is that I don't know what would be the size of the objects. Please also note that the value computed is not going to be used in a HashTable. thx...
See the following: * <http://www.javapractices.com/topic/TopicAction.do?Id=28> * <https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode--> * <http://www.ibm.com/developerworks/java/library/j-jtp05273.html> Keep in mind the following: * An object may be unequal, yet have the same hash code * Your collisions potential depends on how many objects you encounter. * How useful hash codes will be depends on how you implement checking Generally, you can determine the chance of a collision based upon the number of expected objects and the number of possible hashes (max hash value). See <http://en.wikipedia.org/wiki/Birthday_paradox> for the detailed explanation. Personally? Java objects (instantiated classes) < 10,000? Hash code. Representing files / blobs / lots of data? SHA-1. I use SHA-1 hashing in my database to keep people from doing ETL work on the same file more than once. I then use SHA-1 hashing again at a second level to keep people from ETLing the same section in more than once file (e.g., different files but the same order shows up twice).
Personally I would use `hashCode()` for the objects until it's been proven that any possible collisions are an actual problem to avoid preemptively optimizing a problem which you might not actually have.
HashCode vs SHA-1
[ "", "java", "hashcode", "" ]
`std::map<any, string>` is not working so I wonder if there's another approach to have arbritary keys?
I think the issue is not with `Boost::Any`, but rather with the fact that you are not specifying a custom comparator. Since `map` is a sorted associative container, you need to have a comparator. The following works for me: tailor it according to your purposes: ``` #include <iostream> #include <map> #include <boost/any.hpp> using namespace std; struct cmp { bool operator()(const boost::any& l, const boost::any& r) { try { int left = boost::any_cast<int>(l); int right = boost::any_cast<int>(r); return left < right; } catch(const boost::bad_any_cast &) { return false; } return false; } }; int main() { map<boost::any, string, cmp> ma; boost::any to_append = 42; ma.insert(std::make_pair(to_append, "int")); if (ma.find(42) != ma.end()) { cout << "hurray!\n"; } return 0; } ```
You might want to look at `boost::variant` rather than `boost::any`, so you can be sure all the types you are using are comparable. Using visitors would be the best way to provide a comparison operator for `variant`s.
Is it possible to use boost.any as a key in a std::map(or something similiar)?
[ "", "c++", "boost", "" ]
I have a table like so ``` <table> <tr id="trRow1" runat="server" style="display: none"> <td>First Name:</td> <td><asp:Label id="lblFirstName" runat="server"></asp:Label></td> </tr> <tr> <td>Last Name:</td> <td><asp:Label id="lblLastName" runat="server"></asp:Label></td> </tr> </table> ``` As you can see, initially the first row is not being displayed. When the user clicks a certain radio button on the page an asynchronous postback occurs, and at that time I set the style of trRow1 to "inline". Nothing fancy; nothing new. It works just great. Or at least up until I try to do the following in a javascript function. ``` function Test() { var obj = trRow1.getElementsByTagName("select"); alert(obj.length); } ``` At the point I call Test(), I get an error that says "Microsoft JScript runtime error: 'trRow1' is undefined." My guess is it has something to do with the fact that I'm messing with setting the Display style using AJAX, and for whatever reason the DOM can't find trRow1 even after I set it's display to "inline". Can anyone throw me a bone on this one? I'm stuck.
The object *trDegree* is not defined, by your naming conventions looks like *trDegree i*s a table row element, I think that you're trying to do something like this: ``` function WTF() { var trDegree = document.getElementById('trDegree'); // Locate the element var obj = trDegree.getElementsByTagName("select"); alert(obj.length); } ``` Further Reference: * [element.getElementsByTagName](https://developer.mozilla.org/en/DOM/element.getElementsByTagName)
I don't see any variable for trDegree in your sample. You would need to have trDegree loaded before calling getElementsByTagName. For example: ``` function WTF() { var trDegree = document.getElementById('trDegree'); var obj = trDegree.getElementsByTagName("select"); alert(obj.length); } ``` or you could just load the tags from the document level. I'm not sure if this is the effect you want though. ``` function WTF() { var obj = document.getElementsByTagName("select"); alert(obj.length); } ```
Odd behavior in javascript
[ "", "asp.net", "javascript", "" ]
I have a PHP script on a server that generates the XML data on the fly, say with Content-Disposition:attachment or with simple echo, doesn't matter. I'll name this file www.something.com/myOwnScript.php On another server, in another PHP script I want to be able to get this file (to avoid "saving file to disk") as a string (using the path www.something.com/myOwnScript.php) and then manipulate XML data that the script generates. Is this possible without using web services? security implications? Thanks
Simple answer, yes: ``` $output = file_get_contents('http://www.something.com/myOwnScript.php'); echo '<pre>'; print_r($output); echo '</pre>'; ```
If you want more control over how you request the data (spoof headers, send post fields etc.) you should look into cURL. [link text](http://php.net/curl)
Download contents of the PHP generated page from another PHP script
[ "", "php", "code-generation", "download", "content-disposition", "" ]
For some reason, ldap and directory services does not work when the computer is not joined to the domain. The error messages from .net is domain not available. Anyone know what needs to be done? the basic... ``` domainAndUsername = domain + @"\" + username; entry = new DirectoryEntry(_path, domainAndUsername, pwd); entry.AuthenticationType = FindAuthTypeMicrosoft(authType); ``` ... doesn't seem to work when logged in locally to the machine when trying to supply testdomain.com to the code above. Even though I can ping testdomain.com without an issue. What is different or the problem?
This code has worked for me in the past (though I admit I am not in a position to test it right now): ``` DirectoryEntry entry = new DirectoryEntry("LDAP://server-name/DC=domainContext,DC=com"); entry.Username = @"DOMAIN\account"; entry.Password = "..."; DirectorySearcher searcher = new DirectorySearcher(entry); searcher.Filter = "(&(objectClass=user)(sn=Jones))"; SearchResultCollection results = searcher.FindAll(); ``` The hardest part (for me anyway) is figuring out the "connection string" details. I generally rely on [ADSI Edit](http://www.google.com/search?q=adsi+edit) and [AD Explorer](http://technet.microsoft.com/en-us/sysinternals/bb963907.aspx) to help me figure out what the correct values are. [Softerra LDAP Browser](http://www.ldapbrowser.com/) - the free version is a bit older, v2.6 and tucked away in their download section.
Directory services rely on an ActiveDirectory. So you need to add the machine to an Domain or explicitly supply the domain controller. Note that domain does not mean a domain name from the domain name system. It means a ActiveDirectory Domain.
how to authenticate ldap when not joined to a domain in Microsoft Active Directory using c#
[ "", "c#", ".net", ".net-2.0", "ldap", "" ]
I've been trying to read a bit of the C++ standard to figure out how enum's work. There's actually more there than I originally thought. For a scoped enumeration, it's clear that the underlying type is `int` unless otherwise specified with an enum-base clause (it can be any integral type). ``` enum class color { red, green, blue}; // these are int ``` For unscoped enumerations, it seems like the underlying type can be any integral type that will work and that it won't be bigger than an int, unless it needs to be. ``` enum color { red, green, blue}; // underlying type may vary ``` Since the underlying type of unscoped enumarations are not standardized, what's the best way of dealing with serializing instances of one? So far, I've been converting to `int` when writing then serializing into an `int` and setting my `enum` variable in a switch when reading, but it seems a bit clunky. Is there a better way? ``` enum color { red, green, blue }; color c = red; // to serialize archive << (int)c; // to deserialize int i; archive >> i; switch(i) { case 0: c = red; break; case 1: c = green; break; case 2: c = blue; break; } ```
I haven't read any C++0x stuff so I couldn't comment on that. As for serializing, you don't need the switch when reading the enum back in - just cast it to the enum type. However, I don't cast when writing to the stream. This is because I often like to write an operator<< for the enum so I can catch bad values being written, or I can then decide to write out a string instead. ``` enum color { red, green, blue }; color c = red; // to serialize archive << c; // Removed cast // to deserialize int i; archive >> i; c = (color)i; // Removed switch ```
*enum class* is a [C++0x](http://en.wikipedia.org/wiki/C++0x#Strongly_typed_enumerations) feature, it is not present in C++03. > In standard C++, enumerations are not type-safe. They are effectively integers, even when the enumeration types are distinct. This allows the comparison between two enum values of different enumeration types. The only safety that C++03 provides is that an integer or a value of one enum type does not convert implicitly to another enum type. Additionally, the underlying integral type, the size of the integer, cannot be explicitly specified; it is implementation defined. Lastly, enumeration values are scoped to the enclosing scope. Thus, it is not possible for two separate enumerations to have matching member names. > C++0x will allow a special classification of enumeration that has none of these issues. This is expressed using the enum class declaration Examples (from the wikipedia article): ``` enum Enum1; //Illegal in C++ and C++0x; no size is explicitly specified. enum Enum2 : unsigned int; //Legal in C++0x. enum class Enum3; //Legal in C++0x, because enum class declarations have a default type of "int". enum class Enum4: unsigned int; //Legal C++0x. enum Enum2 : unsigned short; //Illegal in C++0x, because Enum2 was previously declared with a different type. ``` As for the serialization part (which I think was not part of the original question), I prefer to create a helper class that translates enum items into their string equivalent (and back), as the names are usually more stable than the integer values they represent, as enum items can be (and sometimes are) reordered without changing the code behavior.
Underlying type of a C++ enum in C++0x
[ "", "c++", "enums", "c++11", "" ]
How can I access Microsoft Access databases in Python? With SQL? I'd prefere a solution that works with Linux, but I could also settle for Windows. I only require read access.
I've used [PYODBC](https://pypi.python.org/pypi/pyodbc/) to connect succesfully to an MS Access db - **on Windows though**. Install was easy, usage is fairly simple, you just need to set the right connection string (the one for MS Access is given in the list) and off you go with the examples.
On Linux, MDBTools is your only chance as of now. [[disputed]](https://stackoverflow.com/questions/853370/#comment53931912_15400363) On Windows, you can deal with mdb files with pypyodbc. To create an Access mdb file: ``` import pypyodbc pypyodbc.win_create_mdb( "D:\\Your_MDB_file_path.mdb" ) ``` [Here is an Hello World script](https://code.google.com/p/pypyodbc/wiki/pypyodbc_for_access_mdb_file) that fully demostate pypyodbc's Access support functions. Disclaimer: I'm the developer of pypyodbc.
What do I need to read Microsoft Access databases using Python?
[ "", "python", "linux", "ms-access", "python-module", "" ]
I would like to create a sql query that reports the percentage of results in a particular range. for instance 20% of the values between 10 to 20 40% of the values between 20 to 32.5 Server - MSSQL
``` SELECT B.Description, Total = COUNT(*) / CONVERT(money, (SELECT COUNT(*) FROM Target T2)) FROM Target T JOIN ( SELECT Description = '0 to 10', LBound = 0, UBound = 10 UNION ALL SELECT Description = '10 to 20', LBound = 10, UBound = 20 ) B ON T.Value >= LBound AND T.Value < B.UBound GROUP BY B.Description ```
``` GROUP BY CASE WHEN VALUE >= 10 AND VALUE <= 20 THEN '20%' WHEN VALUE > 20 AND VALUE <= 32.5 THEN '40%' ELSE '0' END ``` You need to cover *all* possible values, hence the ELSE 0. You'll probably want to do something a little different there, but it should give you a start. --- Based on Joel Gauvreau's comment: ``` SUM(CASE WHEN VALUE >=10 AND VALUE <= 20 THEN 1.0 ELSE 0.0 END) / COUNT(*), SUM(CASE WHEN VALUE > 20 AND VALUE <= 32.5 THEN 1.0 ELSE 0.0 END) / COUNT(*) ``` Or at the end of the query use the [`COMPUTE`](http://msdn.microsoft.com/en-us/library/ms181708.aspx) statement.
How do I create an SQL query that groups by value ranges
[ "", "sql", "sql-server", "" ]
This is a question that I've always wanted to know the answer, but never really asked. How does code written by one language, particularly an interpreted language, get called by code written by a compiled language. For example, say I'm writing a game in C++ and I outsource some of the AI behavior to be written in Scheme. How does the code written in Scheme get to a point that is usable by the compiled C++ code? How is it used by the C++ source code, and how is it used by the C++ compiled code? Is there a difference in the way it's used? ### Related > [How do multiple-languages interact in one project?](https://stackoverflow.com/questions/636841/how-do-multiple-languages-interact-in-one-project/636851)
There is no single answer to the question that works everywhere. In general, the answer is that the two languages must agree on "something" -- a set or rules or a "calling protocol". In a high level, any protocol needs to specify three things: * "discovery": how to find about each other. * "linking": How to make the connection (after they know about each other). * "Invocation": How to actually make requests to each other. The details depend heavily on the protocol itself. Sometimes the two languages conspire to work together. Sometimes the two languages agree to support some outside-defined protocol. These days, the OS or the "runtime environment" (.NET and Java) is often involved as well. Sometimes the ability only goes one way ("A" can call "B", but "B" cannot call "A"). Notice that this is the same problem that any language faces when communicating with the OS. The Linux kernel is not written in Scheme, you know! Let's see some typical answers from the world of Windows: * **C with C++**: C++ uses a contorted ("mangled") variation of the "C protocol". C++ can call into C, and C can call into C++ (although the names can be quite messy sometimes and it might need external help translating the names). This is not just Windows; it's generally true in all platforms that support both. Most popular OS's use a "C protocol" as well. * **VB6 vs. most languages**: VB6's preferred method is the "COM protocol". Other languages must be able to write COM objects to be usable from VB6. VB6 can produce COM objects too (although not every possible variation of COM objects). VB6 can also talk a very limited variation of the "C protocol", and then only to make calls outside: it cannot create objects that can be talked to directly via the "C protocol". * **.NET languages**: All .NET languages communicate compile to the same low-level language (IL). The runtime manages the communication and from that point of view, they all look like the same language. * **VBScript vs. other languages**: VBScript can only talk a subset of the COM protocol. One more note: SOAP "Web Services" is really a "calling protocol" as well, like many other web-based protocol that are becoming popular. After all, it's all about talking to code written in a different language (and running in a different box at that!)
Typically the C++ code will invoke an interpreter for the scripting language. The degree of interaction between the compiled and scripting code is dependent on the interpreter but there's always a way to pass data between the two. Depending on the interpreter, it may be possible to manipulate the objects on one side from the other side, such as a C++ function calling a method on a Ruby object. There may even be a way to control execution of one from the other.
How does code written in one language get called from another language
[ "", "c++", "programming-languages", "scheme", "compilation", "interpreter", "" ]
I'm on a foreign linux system and need to determine the user that apache runs on (and so does php). The aim: I need to get the owner of the script (this is no problem as I can use SplFileInfo) and compare it to the owner of the apache process. I'm open to any alternative proposals. Regards, Mario Edit: Additional info: The script is a thumbnail generator, that uses an XML file to generate thumbs from larger images. The script needs to create folders and write files. As I cannot influence the php configuration and I do not have any shell access, this has to be done very silently. The creation process stopps via exception and sends a mail on failue. As most of php's function cannot throw exceptions on failue, I need some manual checks to determine the environment I'm in. Therefore I need the apache user to compare it to some directory or fileowner.
You can call the php [exec](http://php.net/exec) function to execute *whoami*: ``` <?php echo exec('whoami'); ?> ```
see posix\_getuid() and posix\_getpwuid()
Get apache linux user from php
[ "", "php", "apache", "" ]
I am working on a small project that is receiving XML data in string form from a long running application. I am trying to load this string data into an `XDocument` (`System.Xml.Linq.XDocument`), and then from there do some XML Magic and create an xlsx file for a report on the data. On occasion, I receive the data that has invalid XML characters, and when trying to parse the string into an `XDocument`, I get this error. > [System.Xml.XmlException] > Message: '?', hexadecimal value 0x1C, is an invalid character. Since I have no control over the remote application, you could expect ANY kind of character. I am well aware that XML has a way where you can put characters in it such as `&#x1C` or something like that. If at all possible I would SERIOUSLY like to keep ALL the data. If not, than let it be. --- I have thought about editing the response string programatically, then going back and trying to re-parse should an exception be thrown, but I have tried a few methods and none of them seem successful. Thank you for your thought. Code is something along the line of this: ``` TextReader tr; XDocument doc; string response; //XML string received from server. ... tr = new StringReader (response); try { doc = XDocument.Load(tr); } catch (XmlException e) { //handle here? } ```
XML can handle just about any character, but there are ranges, [control codes and such](http://www.w3.org/TR/xml/#NT-Char), that it won't. Your best bet, if you can't get them to fix their output, is to sanitize the raw data you're receiving. You need replace illegal characters with the character reference format you noted. (You can't even resort to CDATA, as there is no way to escape these characters there.)
You can use the *XmlReader* and set the *XmlReaderSettings.CheckCharacters* property to *false*. This will let you to read the XML file despite the invalid characters. From there you can import pass it to a XmlDocument or XDocument object. You can read a little more about in my [blog](http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx). To load the data to a *System.Xml.Linq.XDocument* it will look a little something like this: ``` XDocument xDocument = null; XmlReaderSettings xmlReaderSettings = new XmlReaderSettings { CheckCharacters = false }; using (XmlReader xmlReader = XmlReader.Create(filename, xmlReaderSettings)) { xmlReader.MoveToContent(); xDocument = XDocument.Load(xmlReader); } ``` More information can be found [here](http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx).
XML Exception: Invalid Character(s)
[ "", "c#", "xml", "linq-to-xml", "" ]
I have the following Regex to match all link tags on a page generated from our custom cms ``` <a\s+((?:(?:\w+\s*=\s*)(?:\w+|"[^"]*"|'[^']*'))*?\s*href\s*=\s*(?<url>\w+|"[^"]*"|'[^']*')(?:(?:\s+\w+\s*=\s*)(?:\w+|"[^"]*"|'[^']*'))*?)>.+?</a> ``` We are using c# to loop through all matches of this and add an onclick event to each link (for tracking software) before rendering the page content. I need to parse the link and add a parameter to the onclick function which is the "link name". I was going to modify the regex to get the following subgroups * The title attribute of the link * If the link contains an image tag get the alt text of the image * The text of the link I can then check the match of each subgroup to aqquire the relevant name of the link. How would I modify the above regex to do this or could I achieve the same think using c# code?
Regexes are fundamentally bad at parsing HTML (see [Can you provide some examples of why it is hard to parse XML and HTML with a regex?](https://stackoverflow.com/questions/701166) for why). What you need is an HTML parser. See [Can you provide an example of parsing HTML with your favorite parser?](https://stackoverflow.com/questions/773340) for examples using a variety of parsers. In particular you may be interested in the [HTMLAgilityPack answer](https://stackoverflow.com/questions/773340/can-you-provide-an-example-of-parsing-html-with-your-favorite-parser/773769#773769).
Try this: ``` Regex reg = new Regex("<a[^>]*?title=\"([^\"]*?\"[^>]*?>"); ``` A couple of gotchas: * This will match is case-sensitive, you may want to adjust that * This expects the title attribute both exists and is quoted + Of course, if the title attribute doesn't exist, you probably don't want the match anyway? To Extract, use the groups collection: ``` reg.Match("<a href=\"#\" title=\"Hello\">Howdy</a>").Groups[1].Value ```
Get "Title" attribute from html link using Regex
[ "", "c#", ".net", "html", "regex", "" ]
I'd like to be able to swap two variables without the use of a temporary variable in C#. Can this be done? ``` decimal startAngle = Convert.ToDecimal(159.9); decimal stopAngle = Convert.ToDecimal(355.87); // Swap each: // startAngle becomes: 355.87 // stopAngle becomes: 159.9 ```
First of all, swapping without a temporary variable in a language as C# is a **very bad idea**. But for the sake of answer, you can use this code: ``` startAngle = startAngle + stopAngle; stopAngle = startAngle - stopAngle; startAngle = startAngle - stopAngle; ``` Problems can however occur with rounding off if the two numbers differ largely. This is due to the nature of floating point numbers. If you want to hide the temporary variable, you can use a utility method: ``` public static class Foo { public static void Swap<T> (ref T lhs, ref T rhs) { T temp = lhs; lhs = rhs; rhs = temp; } } ```
[C# 7 introduced **tuples**](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#tuples) which enables swapping two variables without a temporary one: ``` int a = 10; int b = 2; (a, b) = (b, a); ``` This assigns `b` to `a` and `a` to `b`.
Swap two variables without using a temporary variable
[ "", "c#", "algorithm", "swap", "" ]
I was bored and playing around with the ipython console and came upon the following behaviour I don't really understand ``` In [1]: 2**2 Out[1]: 4 In [2]: 2**2**2 Out[2]: 16 In [3]: 2**2**2**2 Out[3]: 65536 In [4]: 2**2**2**2**2 ``` The answer to [4] is *not* 4294967296L, it's a very long number, but I can't really figure out why. The number can be found here: <http://pastie.org/475714> (Ubuntu 8.10, python 2.5.2, ipython 0.8.4) (Mac OS X 10.5.6, Python 2.5.1)
Python is going right to left on the mathematical power operation. For example, IN[2] is doing: 2\*\*(4) = 16 IN[3] = 2**2**2**2 = 2**2\*\*(4) = 2\*\*16 = 65536 You would need parenthesis if you want it to calculate from left to right. The reason OUT[4] is not outputting the answer you want is because the number is astronomical and Python cannot print it out. 2^65536 = extremely huge
The precedence of the \*\* operator makes the evaluation goes from right-to-left (instead of the expected left-to-right). In other words: ``` 2**2**2**2 == (2**(2**(2**2))) ```
Strange python behaviour
[ "", "python", "ipython", "" ]
I was asked this question and could not come up with the answer. Is there a way to find the entry at the first row and first column in a table? (In matrix notation, that would be the `[1,1]th` location)
There were a lot of good feedback related to the "first row" part of thge question. But as far as the "first column" goes, you can try one of the following options: 1. You can use database data dictionary to get the first column of the table. In Oracle, for example the query would be: > ``` > select column_name > from user_tab_columns > where table_name='YOUR_TABLE_NAME' > and column_id=1 > ``` 2. If you use JDBC or some other database access API, most of these APIS would allow you to do `"select *"` and then you could get first column by accessing zero (or first) element of you result set.
In a couple of words: a relational table is not a matrix. In relational world, `1'st row` makes sense only when you define some order on your dataset. There is no such thing as "implicitly first record". Assuming you order your rows on the values of the first column, it's this: ``` SELECT column1 FROM table ORDER BY column1 LIMIT 1 ``` Also note that different columns in the table belong to different `domains`. The point of having the table is to define some `relation` between these `domains`, that's why the whole thing is called "relational database", and the tables themselves are sometimes called "relations". The column order also has no special meaning in a relational table. It's assumed you always refer to the column by name. If replacing the order of a column affects the result of your query, it is considered a poor design. There are things like `SELECT *` and `ORDER BY 1`, but they generally should be avoided.
How to find a first column and first row in a table using SQL
[ "", "sql", "mysql", "database", "oracle", "" ]
I am working on a Django application which allows a user to upload files. I need to perform some server-side processing on these files before sending them on to [Amazon S3](http://aws.amazon.com/s3/). After reading the responses to [this question](https://stackoverflow.com/questions/219329/django-fastcgi-how-to-manage-a-long-running-process) and [this blog post](http://iraniweb.com/blog/?p=56) I decided that the best manner in which to handle this is to have my view handler invoke a method on [Pyro](http://pyro.sourceforge.net/) remote object to perform the processing asynchronously and then immediately return an Http 200 to the client. I have this prototyped and it seems to work well, however, I would also like to store the state of the processing so that the client can poll the application to see if the file has been processed and uploaded to S3. I can handle the polling easily enough, but I am not sure where the appropriate location is to store the process state. It needs to be writable by the Pyro process and readable by my polling view. * I am hesitant to add columns to the database for data which should really only persist for 30 to 60 seconds. * I have considered using Django's [low-level cache API](http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api) and using a file id as the key, however, I don't believe this is really what the cache framework is designed for and I'm not sure what unforeseen problems there might be with going this route. * Lastly, I have considered storing state in the Pyro object doing the processing, but then it still seems like I would need to add a boolean "processing\_complete" database column so that the view knows whether or not to query state from the Pyro object. Of course, there are also some data integrity concerns with decoupling state from the database (what happens if the server goes down and all this data is in-memory?). I am to hear how more seasoned web application developers would handle this sort of stateful processing.
We do this by having a "Request" table in the database. When the upload arrives, we create the uploaded File object, and create a Request. We start the background batch processor. We return a 200 "we're working on it" page -- it shows the Requests and their status. Our batch processor uses the Django ORM. When it finishes, it updates the Request object. We can (but don't) send an email notification. Mostly, we just update the status so that the user can log in again and see that processing has completed. --- Batch Server Architecture notes. It's a WSGI server that waits on a port for a batch processing request. The request is a REST POST with an ID number; the batch processor looks this up in the database and processes it. The server is started automagically by our REST interface. If it isn't running, we spawn it. This makes a user transaction appear slow, but, oh well. It's not supposed to crash. Also, we have a simple crontab to check that it's running. At most, it will be down for 30 minutes between "are you alive?" checks. We don't have a formal startup script (we run under Apache with mod\_wsgi), but we may create a "restart" script that touches the WSGI file and then does a POST to a URL that does a health-check (and starts the batch processor). When the batch server starts, there may be unprocessed requests for which it has never gotten a POST. So, the default startup is to pull ALL work out of the Request queue -- assuming it may have missed something.
I know this is an old question but someone may find my answer useful even after all this time, so here goes. You can of course use database as queue but there are solutions developed exactly for that purpose. [AMQP](http://www.amqp.org/) is made just for that. Together with [Celery](http://ask.github.com/celery/introduction.html) or [Carrot](http://github.com/ask/carrot) and a broker server like [RabbitMQ](http://www.rabbitmq.com/) or [ZeroMQ](http://www.zeromq.org/). That's what we are using in our latest project and it is working great. For your problem Celery and RabbitMQ seems like a best fit. RabbitMQ provides persistency of your messages, and Celery exposes easy views for polling to check the status of processes run in parallel. You may also be interested in [octopy](http://code.google.com/p/octopy/).
How should I store state for a long-running process invoked from Django?
[ "", "python", "django", "asynchronous", "amazon-s3", "pyro", "" ]
I have the following need I have a logging table which logs som leads generated each day. Now I need to pull a report over the amount of leads for each day over the last 10 days. Lets say the table looks like this: ``` tbl_leads id int, first_name nvarchar(100), last_name nvarchar(100), created_date datetime ``` And I need to count the number of leads for each day, 10 days total. SO the result set should look something like this: ``` counted_leads | count_date 5 | 2009-04-30 7 | 2009-04-29 5 | 2009-04-28 7 | 2009-04-27 ``` ... and so on Anyone know how to do this the best possible way? My current solution is iterating with a foreach in c# but I would very much like to hand it on the sql server instead in a sp.
You can use: ``` Select count(created_date) as counted_leads, created_date as count_date from table group by created_date ```
Your created\_date field is `datetime`, so you'll need to strip off the time before the grouping will work if you want to go by date: ``` SELECT COUNT(created_date), created_date FROM table WHERE DATEDIFF(created_date, getdate()) < 10 GROUP BY convert(varchar, created_date, 101) ```
SQL Count for each date
[ "", "sql", "t-sql", "" ]
I know you can do this, because I've seen it done once before, but I forget where and up until now I haven't need to do it. I have a table called Employees, and it has various employee data (duh). I need a query that will do a select on the first and last name of all rows in the table, and then contenate all of them into a comma delimited string. For example, I have a few rows (a lot more than that actually, but for the sake of this question just assume two) of data that look like: ``` FName LName ------- ----- Richard Prescott Jill Sentieri Carol Winger ``` I need to a select that can return the aforementioned data in this form: ``` Richard Prescott, Jill Sentieri, Carol Winger ```
Use coalesce. Something like this: ``` DECLARE @Names varchar(1000) SELECT @Names = COALESCE(@Names + ', ', '') + Name FROM Employees ```
This is the most efficient method I've found. It requires SQL Server, but it sounds like that's what you're using. ``` select stuff(( select ', ' + fName + ' ' + lName from Employees order by lName, fName /* Optional */ for xml path('') ), 1, 2, ''); ``` The idea is that you can take advantage of the ability to use an empty tag name with for xml path('') to get string concatenation across rows. The stuff(...,1,2,'') just removes the leading comma. This is REALLY fast.
Concatenate a selected column in a single query?
[ "", "sql", "sql-server", "select", "concatenation", "" ]
Is there any way, in Python, to programmatically *change* the CAPS LOCK/NUM LOCK/SCROLL LOCK states? This isn't really a joke question - more like a real question for a joke program. I intend to use it for making the lights do funny things...
If you're using windows you can use [SendKeys](https://pypi.python.org/pypi/SendKeys/) for this I believe. [http://www.rutherfurd.net/python/sendkeys](https://web.archive.org/web/20121125032946/http://www.rutherfurd.net/python/sendkeys) ``` import SendKeys SendKeys.SendKeys(""" {CAPSLOCK} {SCROLLOCK} {NUMLOCK} """) ```
On Linux here's a Python program to blink all the keyboard LEDs on and off: ``` import fcntl import os import time KDSETLED = 0x4B32 SCR_LED = 0x01 NUM_LED = 0x02 CAP_LED = 0x04 console_fd = os.open('/dev/console', os.O_NOCTTY) all_on = SCR_LED | NUM_LED | CAP_LED all_off = 0 while 1: fcntl.ioctl(console_fd, KDSETLED, all_on) time.sleep(1) fcntl.ioctl(console_fd, KDSETLED, all_off) time.sleep(1) ```
Change keyboard locks in Python
[ "", "python", "windows", "" ]
Is there a good way to determine how many pages the twitter search api has returned or is there a way to determine how many values were returned and divide that by the number of twits per page?
No. The API does not expose this; not because it's not a useful feature, but because of the performance aspects of providing it. In order to get a complete count of results, it is necessary for the search algorithm to completely iterate its index for each query. Then when you went back for the second page, it would have to iterate its index from page 2 onward to give you the count again. This means that getting all the data would be O(n^2) (because returning each of the N pages requires scanning all the later pages) instead of the expected O(n). Because most requestors only want a few pages of results, it's a common optimization for the query to return only partial results, with just a pointer into the index to allow the search to continue at the point it left off. Most high-scale paginated APIs behave in a similar fashion for these reasons. To get an accurate count, you'll have to force the query to completely iterate its index by looping through the pages. This comes with a high cost to the remote service, and making you come back many times allows the service to appropriately throttle your query so it does not negatively impact other users.
So you could potentially run a loop through the pages until your provided with an empty query result.
Determine how many pages Twitter Search Api returned
[ "", "php", "twitter", "" ]
I'm using curl to retrieve information from wikipedia. So far I've been successful in retrieving basic text information but I really would want to retrieve it in HTML. Here is my code: ``` $s = curl_init(); $url = 'http://boss.yahooapis.com/ysearch/web/v1/site:en.wikipedia.org+'.$article_name.'?appid=myID'; curl_setopt($s,CURLOPT_URL, $url); curl_setopt($s,CURLOPT_HEADER,false); curl_setopt($s,CURLOPT_RETURNTRANSFER,1); $rs = curl_exec($s); $rs = Zend_Json::decode($rs); $rs = ($rs['ysearchresponse']['resultset_web']); $rs = array_shift($rs); $article= str_replace('http://en.wikipedia.org/wiki/', '', $rs['url']); $url = 'http://en.wikipedia.org/w/api.php?'; $url.='format=json'; $url.=sprintf('&action=query&titles=%s&rvprop=content&prop=revisions&redirects=1', $article); curl_setopt($s,CURLOPT_URL, $url); curl_setopt($s,CURLOPT_HEADER,false); curl_setopt($s,CURLOPT_RETURNTRANSFER,1); $rs = curl_exec($s); //curl_close( $s ); $rs = Zend_Json::decode($rs); $rs = array_pop(array_pop(array_pop($rs))); $rs = array_shift($rs['revisions']); $articleText = $rs['*']; ``` However the text retrieved this way isnt well enough to be displayed :( its all in this kind of format > '''Aix-les-Bains''' is a [[Communes of > France|commune]] in the [[Savoie]] > [[Departments of France|department]] > in the [[Rhône-Alpes]] [[regions of > France|region]] in southeastern > [[France]]. > > It lies near the [[Lac du Bourget]], > {{convert|9|km|mi|abbr=on}} by rail > north of [[Chambéry]]. > > ==History== ''Aix'' derives from [[Latin]] ''Aquae'' (literally, > "waters"; ''cf'' [[Aix-la-Chapelle]] > (Aachen) or [[Aix-en-Provence]]), and > Aix was a bath during the [[Roman > Empire]], even before it was renamed > ''Aquae Gratianae'' to commemorate the > [[Emperor Gratian]], who was > assassinated not far away, in > [[Lyon]], in [[383]]. Numerous Roman > remains survive. [[Image:IMG 0109 Lake > Promenade.jpg|thumb|left|Lac du > Bourget Promenade]] How do I get the HTML of the wikipedia article? --- **UPDATE:** Thanks but I'm kinda new to this here and right now I'm trying to run an xpath query [albeit for the first time] and can't seem to get any results. I actually need to know a couple of things here. 1. How do I request just a part of an article? 2. How do I get the HTML of the article requested. I went through this [url](http://www.slideshare.net/neilcrosby/mining-wikipedia-for-awesome-data-presentation) on data mining from wikipedia - it put an idea to make a second request to wikipedia api with the retrieved wikipedia text as parameters and that would retrieve the html - although it hasn't seemed to work so far :( - I don't want to just grab the whole article as a mess of html and dump it. Basically my application what it does is that you have some locations and cities pin pointed on the map - you click on the city marker and it would request via ajax details of the city to be shown in an adjacent div. This information I wish to get from wikipedia dynamically. I'll worry about about dealing with articles that don't exist for a particular city later on just need to make sure its working at this point. Does anyone know of a nice working example that does what I'm looking for i.e. read and parse through selected portions of a wikipedia article. --- According to the url provided - it says I should post the wikitext to the wikipedia api location for it to return parsed html. The issue is that if I post the information I get no response and instead an error that I'm denied access - however if I try to include the wikitext as GET it parses with no issue. But it fails of course when I have waaaaay too much text to parse. Is this a problem with the wikipedia api? Because I've been hacking at it for two days now with no luck at all :(
The simplest solution would probably be to grab the page itself (e.g. <http://en.wikipedia.org/wiki/Combination> ) and then extract the content of `<div id="content">`, potentially with an xpath query.
As far as I understand it, the Wikipedia software converts the Wiki markup into HTML when the page is requested. So using your current method, you'll need to deal with the results. A good place to start is the [Mediawiki API](http://www.mediawiki.org/wiki/API). You can also use <http://pear.php.net/package/Text_Wiki> to format the results retrieved via cURL.
Getting info from Wikipedia - how do I get HTML form?
[ "", "php", "zend-framework", "wikipedia", "" ]
I have a dataGrid(not dataGridView) in which i need to add Checkbox dynamically at the first column. How can i do this.?
In the ItemDataBound event, which fires for each row of the DataGrid, you could dynamically add a control to the first cell. Easier to use a TemplateColumn, but if you want to do it dynamically as you asked, this is how I'd do it. ``` private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) { if ((e.Item.ItemType == ListItemType.AlternatingItem) || (e.Item.ItemType == ListItemType.Item)) { CheckBox chk = new Checkbox(); e.Item.Cells[0].Controls.Add(chk); } ```
The following woprks with a GridView, and I believe that it's also the same for a DataGrid. Just add a Template Column. (You can do that in source or via the GUI). Then add a checkbod to the ItemTemplate: ``` <Columns> <asp:TemplateField> <HeaderTemplate> Retry </HeaderTemplate> <ItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" /> </ItemTemplate> </asp:TemplateField> </Columns> ``` ps. Might want to consider dropping in a GridView if you're on 2.0+
Adding checkbox dynamically to dataGrid in C# Visual studio 2005
[ "", "c#", "asp.net", "" ]
I think I've come across this requirement for a dozen times. But I could never find a satisfying solution. For instance, there are a collection of string which I want to serialize (to disk or through network) through a channel where only plain string is allowed. I almost always end up using "split" and "join" with ridiculous separator like > ":::==--==:::". like this: ``` public static string encode(System.Collections.Generic.List<string> data) { return string.Join(" :::==--==::: ", data.ToArray()); } public static string[] decode(string encoded) { return encoded.Split(new string[] { " :::==--==::: " }, StringSplitOptions.None); } ``` But this simple solution apparently has some flaws. The string cannot contains the separator string. And consequently, the encoded string can no longer re-encoded again. AFAIK, the comprehensive solution should involve escaping the separator on encoding and unescaping on decoding. While the problem sound simple, I believe the complete solution can take significant amount of code. I wonder if there is any trick allowed me to build encoder & decoder in very few lines of code ?
You shouldn't need to do this manually. As the other answers have pointed out, there are plenty of ways, built-in or otherwise, to serialize/deserialize. However, if you did decide to do the work yourself, it doesn't require *that* much code: ``` public static string CreateDelimitedString(IEnumerable<string> items) { StringBuilder sb = new StringBuilder(); foreach (string item in items) { sb.Append(item.Replace("\\", "\\\\").Replace(",", "\\,")); sb.Append(","); } return (sb.Length > 0) ? sb.ToString(0, sb.Length - 1) : string.Empty; } ``` This will delimit the items with a comma (`,`). Any existing commas will be escaped with a backslash (`\`) and any existing backslashes will also be escaped. ``` public static IEnumerable<string> GetItemsFromDelimitedString(string s) { bool escaped = false; StringBuilder sb = new StringBuilder(); foreach (char c in s) { if ((c == '\\') && !escaped) { escaped = true; } else if ((c == ',') && !escaped) { yield return sb.ToString(); sb.Length = 0; } else { sb.Append(c); escaped = false; } } yield return sb.ToString(); } ```
Add a reference and `using` to System.Web, and then: ``` public static string Encode(IEnumerable<string> strings) { return string.Join("&", strings.Select(s => HttpUtility.UrlEncode(s)).ToArray()); } public static IEnumerable<string> Decode(string list) { return list.Split('&').Select(s => HttpUtility.UrlDecode(s)); } ``` Most languages have a pair of utility functions that do Url "percent" encoding, and this is ideal for reuse in this kind of situation.
What's the simplest way to encoding List<String> into plain String and decode it back?
[ "", "c#", "serialization", "" ]
After reading "[Java concurrent in practice](http://jcip.net/)" and "[OSGI in practice](http://neilbartlett.name/blog/osgibook/)" I found a specific subject very interesting; Safe Publication. The following is from JCIP: > To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by: > > * Initializing an object reference from a *static* initializer. > * Storing a reference to it into a *volatile* field. > * Storing a reference to it into a *final* field. > * Storing a reference to it into a field that is properly guarded by a (*synchronized*) lock. My first question: how many java developers are aware of this (problem)? How many real world java applications are really following this, AND is this really a real problem? I have a feeling that 99% of the implemented JVMs out there are not that "evil", i.e. a thread is not guaranteed (in fact its practical (almost) "impossible") to see stale data just because the reference is not following the "safe publication idiom" above.
Proportionally, it's probably fair to say that very few programmers sufficiently understand synchronization and concurrency. Who knows how many server applications there are out there right now managing financial transactions, medical records, police records, telephony etc etc that are full of synchronization bugs and essentially work by accident, or very very occasionally fail (never heard of anybody get a phantom phone call added to their telephone bill?) for reasons that are never really looked into or gotten to the bottom of. Object publication is a particular problem because it's often overlooked, and it's a place where it's quite reasonable for compilers to make optimisations that could result in unexpected behaviour if you don't know about it: in the JIT-compiled code, storing a pointer, then incrementing it and storing the data is a very reasonable thing to do. You might think it's "evil", but at a low level, it's really how you'd expect the JVM spec to be. (Incidentally, I've heard of real-life programs running in JRockit suffering from this problem-- it's not purely theoretical.) If you know that your application has synchronization bugs but isn't misbehaving in your current JVM on your current hardware, then (a) congratulations; and (b), now is the time to start "walking calmly towards the fire exit", fixing your code and educating your programmers before you need to upgrade too many components.
"is this really a real problem?" Yes absolutely. Even the most trivial web application has to confront issues surrounding concurrency. Servlets are accessed by multiple threads, for example. The other issue is that threading and concurrency is very hard to handle correctly. It is almost too hard. That is why we are seeing trends emerge like transactional memory, and languages like Clojure that hopefully make concurrency easier to deal with. But we have a ways to go before these become main stream. Thus we have to do the best with what we have. Reading JCiP is a very good start.
Java multi-threading & Safe Publication
[ "", "java", "multithreading", "safe-publication", "" ]
I have recently discovered that when I have pointers within a class, I need to specify a Copy constructor. To learn that, I have made the following simple code. It compiles, but gives me runtime error when performing the copy constructor. I am trying to copy just the value from the pointer of the copied object, but avoiding assigning the same address. So, what's wrong here? ``` class TRY{ public: TRY(); ~TRY(); TRY(TRY const &); int *pointer; void setPointer(int); }; void TRY::setPointer(int a){ *pointer = a; return; } TRY::TRY(){} TRY::~TRY(){} TRY::TRY(TRY const & copyTRY){ int a = *copyTRY.pointer; *pointer = a; } int main(){ TRY a; a.setPointer(5); TRY b = a; b.setPointer(8); cout << "Address of object a = " << &a << endl; cout << "Address of object b = " << &b << endl; cout << "Address of a.pointer = " << a.pointer << endl; cout << "Address of b.pointer = " << b.pointer << endl; cout << "Value in a.pointer = " << *a.pointer << endl; cout << "Value in b.pointer = " << *b.pointer << endl; return 0; } ``` I'll be using this concept for other classes with lots of pointers in it, where I need to copy all values from on object to the other. Copying is initially necessary for this code, so I would like to keep the copying possibility (I won't be hiding the copy constructor as private). Besides, the real class I need to implement has like 10 pointers, and it might be changing with time. Isn't there a somewhat smarter way to have a deep copy constructor in C++?...
With the statement `int* pointer` you have just defined a pointer but has not allocated any memory. First you should make it point to a proper memory location by allocating some memory like this: `int* pointer = new int`. Then in the copy constructor again you have to allocate the memory for the copied object. Also, don't forget to release the memory using delete in the destructor. I hope this example helps: ``` class B { public: B(); B(const B& b); ~B(); void setVal(int val); private: int* m_p; }; B::B() { //Allocate the memory to hold an int m_p = new int; *m_p = 0; } B::B(const B& b) { //Allocate the memory first m_p = new int; //Then copy the value from the passed object *m_p = *b.m_p; } B::~B() { //Release the memory allocated delete m_p; m_p = NULL; } void B::setVal(int val) { *m_p = val; } ```
> I have recently discovered that when I > have pointers within a class, I need > to specify a Copy constructor. It is not completely true. When you have pointers in your class and allocate the memory using `new` then you have to worry about copy constructor. Also, don't forget the assignment operator and destructor. You have to delete the memory allocated using `delete`. It's called [Law Of The Big Three](http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)). Example: ``` ~Matrix(); //Destructor Matrix(const Matrix& m); //Copy constructor Matrix& operator= (const Matrix& m); //Assignment operator ```
Copy constructor with pointers
[ "", "c++", "pointers", "copy-constructor", "" ]
Is it possible to check if a char has been passed into a method that requires an int? For example, if you have some function foo(int bar) and someone uses that function like foo('t'), are you able to find out that a char was inputted and not an int? I know that the char is converted into an int but I am trying to limit anything other than pure integers getting through the function. Cheers
You can use Integer instead of int. ``` void foo(Integer bar) { } ``` If you try to invoke foo('A') you will get a compiler error.
No, it's impossible because Java itself upgrades the `char` to an `int` if it can. You could make an overload of your function that takes a `char` parameter instead of an `int` which might throw an exception, but that won't stop anyone from casting the `char` to an `int` and calling the `int` version. There is absolutely no difference at all between the character constant `'A'` cast to an integer and the integer 65, so it would be completely impossible to distinguish the cases. **Update from Pax:** I would argue that explicit casting is NOT passing a `char`, it's the caller converting a `char` to an `int` then passing the `int`. This solution catches the inadvertent passing of a `char`. Pinching someone's code from another answer, that would be: ``` public class Test { private static void someMethod(char c) throws Exception { throw new Exception("I don't think so, matey!"); } private static void someMethod(int i) { System.out.println(i); } public static void main(String[] args) throws Exception { someMethod(100); someMethod('d'); } } ``` This results in: ``` 100 Exception in thread "main" java.lang.Exception: I don't think so, matey! at Test.someMethod(Test.java:4) at Test.main(Test.java:13) ```
how to check if a char is passed as an int
[ "", "java", "" ]
I am writing a function and intended to use a dictionary key and its value as parameters. For example: ``` testDict={'x':2,'xS':4} def newFunct(key,testDict['key']): newvalue=key+str(testDict['key']) return newValue for key in testDict: newValue=newFunct(key,testDict[key]) print newValue ``` I get a SyntaxError: invalid syntax when I hit the return button after typing the semicolon. I am guessing this is telling me I can't pass a dictionary value in that form. Presumably I can define a new variable ``` for key in testDict: xdixt=testDict[key] newValue=newFunct(key,xdixt) ``` and def the function using xdixt but I am hoping there is some trick that I am missing. I Googled and found some reference to unpacking a dictionary but that didn't seem to work. This Python stuff is really cool. My question was came about because I am trying to use some values I stored in a dictionary to create a new directory. Based on the material I read from Stephan's answer I wondered about how to generalize the information I learned. My directory name has five different pieces to it, each piece is the result of processing the values from myDict. The expression to create the directory name was getting too complicated and in my opinion too complicated to easily read. so I wondered if I could use the same approach to put the pieces into a list and then unpack them when it came time to create the directory name and it worked! ``` def createDirectory(myKey,**myDict): pathList=[] pathList.append(myDict['subKey1']) pathList.append(myDict['subKey2'].lstrip('0')) pathList.append(myDict['subKey3']) etc myPath=os.path.join(*myList) os.makedirs(myPath) return(myPath) ```
Not sure why we are bringing in kwargs, this is much simpler than that. You said you're new to Python, I think you just need some Python fundamentals here. ``` def newFunct(key,testDict['key']): ``` Should be: ``` def newFunct(key, val): ``` There's no reason to use any special syntax on your second parameter to indicate that it's coming from a dictionary. It's just a parameter, you just happen to be passing the value from a dictionary item into it. Further, once it's in the function, there's no reason to treat it in a special way either. At this point it's just a value. Which means that: ``` newvalue=key+str(testDict[key]) ``` Can now just be: ``` newvalue=key+str(val) ``` So when you call it like this (as you did): ``` newValue=newFunct(key,testDict[key]) ``` testDict[key] resolves to the value at 'key', which just becomes "val" in the function. --- An alternate way, if you see it fit for whatever reason (and this is just something that's good to know), you could define the function thusly: ``` def newFunct(key, testDict): ``` Again, the second parameter is just a parameter, so we use the same syntax, but now we're expecting it to be a dict, so we should use it like one: ``` newvalue=key+str(testDict[key]) ``` (Note: don't put quotes around 'key' in this case. We're referring to the variable called 'key', not a key called 'key'). When you call the function, it looks like this: ``` newValue=newFunct(key,testDict) ``` So unlike the first case where you're just passing one variable from the dictionary, you're passing a reference to the whole dictionary into the function this time. Hope that helps.
Is this what you want? ``` def func(**kwargs): for key, value in kwargs.items(): pass # Do something func(**myDict) # Call func with the given dict as key/value parameters ``` (See the [documentation](http://docs.python.org/tutorial/controlflow.html#keyword-arguments) for more about keyword arguments. The keys in `myDict` must be strings.) --- **Edit**: you edited your question to include the following: > I think the \*\* notation in front of myDict instructs the function to expect a dictionary and to unpack the key (the first \*) and the value, the second \* This is not correct. To understand what is happening, you must consider the following: * A function can have multiple *formal parameters* (`a` and `b` in this case): ``` def f1(a, b): pass ``` * We can pass *positional arguments* to such function (like in most other languages): ``` f1(2, 3) ``` * We can also pass *keyword arguments*: ``` f1(a=2, b=3) ``` * We can also mix these, *but the positional arguments must come first*: ``` f1(2, b=3) f1(a=2, 3) # SyntaxError: non-keyword arg after keyword arg ``` * There is a way to let a function accept an arbitrary number of positional arguments, which it can access as a tuple (`args` in this case): ``` def f2(*args): assert isinstance(args, tuple) ``` * Now we can call `f2` using separately specified arguments, or using a list whose contents first need to be *unpacked*, using a syntax similar to the notation used for `*args`: ``` f2(2, 3) f2(*[2, 3]) ``` * Likewise, an arbitrary number of keyword arguments may be accepted: ``` def f3(**kwargs): pass ``` * Note that `f3` *does not* ask for a single argument of type `dict`. This is the kind of invocations it expects: ``` f3(a=2, b=3) f3(**{'a': 2, 'b': 3}) ``` * All arguments to `f3` must be named: ``` f3(2, 3) # TypeError: f3() takes exactly 0 arguments (2 given) ``` Putting all of this together, and remembering that positional arguments must come first, we may have: ``` >>> def f4(a, b, *args, **kwargs): ... print('%r, %r' % (args, kwargs)) ... >>> f4(2, 3) (), {} >>> f4(2, 3, 4, 5) (4, 5), {} >>> f4(2, 3, x=4, y=5) (), {'y': 5, 'x': 4} >>> f4(2, 3, 4, 5, x=6, y=7) (4, 5), {'y': 7, 'x': 6} >>> f4(2, *[3, 4, 5], **{'x': 6, 'y': 7}) (4, 5), {'y': 7, 'x': 6} ``` Pay special attention to the following two errors: ``` >>> f4(2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: f4() takes at least 2 arguments (1 given) >>> f4(2, 3, a=4) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: f4() got multiple values for keyword argument 'a' ``` The second error should help you explain this behavior: ``` >>> f4(**{'foo': 0, 'a': 2, 'b': 3, 'c': 4}) (), {'c': 4, 'foo': 0} ```
Can I Pass Dictionary Values/Entry and Keys to function
[ "", "python", "function", "dictionary", "" ]
Lets say you created a little Java Desktop app with a jar and some dependencies and possibly a license text file. I know there are plenty of Ant tasks that can generate installers, executables and proper Mac OS X applications including packaging them as ".dmg" files. Examples would be [JarBundler](http://www.informagen.com/JarBundler/) and [Launch4j](http://launch4j.sourceforge.net/index.html) Does similar things exist for Maven? Thanks
[OSX appbundle plugin](http://mojo.codehaus.org/osxappbundle-maven-plugin/)
I also think launch4j has a maven plugin
Can Maven generate exe files and mac os x apps?
[ "", "java", "windows", "macos", "maven-2", "" ]
Let's consider the two following lines in C# (using framework .NET 3.5) ``` Regex regex = new Regex(@"^((E|e)t )?(M|m)oi (?<NewName>[A-Za-z]\.?\w*((\-|\s)?[A-Za-z]?\w{1,})+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); Match m = regex.Match("moi aussi jaimerai etre un ordinateur pour pas m'énnerver "); ``` (sorry it's a french program :)) When they are executed, the process gets stuck in the `Match()` method and never exits. I guess there is some problem with the white space in the regex pattern but what I would like to do is not changing the pattern (actually it is set outside the program, by the end users of my tool) but being able to stop the process (with a timeout for instance). Does someone know if this is well-known problem with the .NET Regular Expression and if there is an easy way to work around it or do I have to thread these lines and abort them if needed (definitely I wouldn't like to do that).
I think you should simply launch the Regex match on a separate thread and allow it to be aborted if a certain maximum time limit is reached.
If I enter the expression in Regexbuddy, it presents following message > The match attempt was aborted early > because the regular expression is too > complex. The regex engine you plan to > use it with may not be able to handle > it at all and crash. Look up > "catastrophic backtracking" in the > help file to learn how to avoid this > situation. Looking up **catastrophic backtracking** gives the following explanation > **Runaway Regular Expressions: Catastrophic Backtracking** > Consider the regular expression (x+x+)+y. > Before you scream in horror and say > this contrived example should be > written as xx+y to match exactly the > same without those terribly nested > quantifiers: just assume that each "x" > represents something more complex, > with certain strings being matched by > both "x". See the section on HTML > files below for a real example. > > Let's see what happens when you apply > this regex to xxxxxxxxxxy. The first > x+ will match all 10 x characters. The > second x+ fails. The first x+ then > backtracks to 9 matches, and the > second one picks up the remaining x. > The group has now matched once. The > group repeats, but fails at the first > x+. Since one repetition was > sufficient, the group matches. y > matches y and an overall match is > found. The regex is declared > functional, the code is shipped to the > customer, and his computer explodes. > Almost. > > The above regex turns ugly when the y > is missing from the subject string. > When y fails, the regex engine > backtracks. The group has one > iteration it can backtrack into. The > second x+ matched only one x, so it > can't backtrack. But the first x+ can > give up one x. The second x+ promptly > matches xx. The group again has one > iteration, fails the next one, and the > y fails. Backtracking again, the > second x+ now has one backtracking > position, reducing itself to match x. > The group tries a second iteration. > The first x+ matches but the second is > stuck at the end of the string. > Backtracking again, the first x+ in > the group's first iteration reduces > itself to 7 characters. The second x+ > matches xxx. Failing y, the second x+ > is reduced to xx and then x. Now, the > group can match a second iteration, > with one x for each x+. But this > (7,1),(1,1) combination fails too. So > it goes to (6,4) and then (6,2)(1,1) > and then (6,1),(2,1) and then > (6,1),(1,2) and then I think you start > to get the drift. > > If you try this regex on a 10x string > in RegexBuddy's debugger, it'll take > 2558 steps to figure out the final y > is missing. For an 11x string, it > needs 5118 steps. For 12, it takes > 10238 steps. Clearly we have an > exponential complexity of O(2^n) here. > At 21x the debugger bows out at 2.8 > million steps, diagnosing a bad case > of catastrophic backtracking. > > **RegexBuddy is forgiving in that it > detects it's going in circles**, and > aborts the match attempt. **Other regex > engines (like .NET) will keep going > forever**, while others will crash with > a stack overflow (like Perl, before > version 5.10). Stack overflows are > particularly nasty on Windows, since > they tend to make your application > vanish without a trace or explanation. > Be very careful if you run a web > service that allows users to supply > their own regular expressions. People > with little regex experience have > surprising skill at coming up with > exponentially complex regular > expressions. I assume you are going to have to handle it in code. I'd suggest you contact the author of [Regexbuddy](http://www.regexbuddy.com/) and ask what is needed to detect this scenario.
How to handle neverending matches from user-submitted regexes
[ "", "c#", ".net", "regex", "user-input", "" ]
Because the float data type in PHP is inaccurate, and a FLOAT in MySQL takes up more space than an INT (and is inaccurate), I always store prices as INTs, multipling by 100 before storing to ensure we have exactly 2 decimal places of precision. However I believe PHP is misbehaving. Example code: ``` echo "<pre>"; $price = "1.15"; echo "Price = "; var_dump($price); $price_corrected = $price*100; echo "Corrected price = "; var_dump($price_corrected); $price_int = intval(floor($price_corrected)); echo "Integer price = "; var_dump($price_int); echo "</pre>"; ``` Produced output: ``` Price = string(4) "1.15" Corrected price = float(115) Integer price = int(114) ``` I was surprised. When the final result was lower than expected by 1, I was expecting the output of my test to look more like: ``` Price = string(4) "1.15" Corrected price = float(114.999999999) Integer price = int(114) ``` which would demonstrate the inaccuracy of the float type. But why is floor(115) returning 114??
Try this as a quick fix: ``` $price_int = intval(floor($price_corrected + 0.5)); ``` The problem you are experiencing is not PHP's fault, all programming languages using real numbers with floating point arithmetics have similar issues. The general rule of thumb for monetary calculations is to never use floats (neither in the database nor in your script). You can avoid all kinds of problems by always storing the cents instead of dollars. The cents are integers, and you can freely add them together, and multiply by other integers. Whenever you display the number, make sure you insert a dot in front of the last two digits. The reason why you are getting 114 instead of 115 is that `floor` rounds down, towards the nearest integer, thus floor(114.999999999) becomes 114. The more interesting question is why 1.15 \* 100 is 114.999999999 instead of 115. The reason for that is that 1.15 is not exactly 115/100, but it is a very little less, so if you multiply by 100, you get a number a tiny bit smaller than 115. Here is a more detailed explanation what `echo 1.15 * 100;` does: * It parses 1.15 to a binary floating point number. This involves rounding, it happens to round down a little bit to get the binary floating point number nearest to 1.15. The reason why you cannot get an exact number (without rounding error) is that 1.15 has infinite number of numerals in base 2. * It parses 100 to a binary floating point number. This involves rounding, but since 100 is a small integer, the rounding error is zero. * It computes the product of the previous two numbers. This also involves a little rounding, to find the nearest binary floating point number. The rounding error happens to be zero in this operation. * It converts the binary floating point number to a base 10 decimal number with a dot, and prints this representation. This also involves a little rounding. The reason why PHP prints the surprising `Corrected price = float(115)` (instead of 114.999...) is that `var_dump` doesn't print the exact number (!), but it prints the number rounded to `n - 2` (or `n - 1`) digits, where n digits is the precision of the calculation. You can easily verify this: ``` echo 1.15 * 100; # this prints 115 printf("%.30f", 1.15 * 100); # you 114.999.... echo 1.15 * 100 == 115.0 ? "same" : "different"; # this prints `different' echo 1.15 * 100 < 115.0 ? "less" : "not-less"; # this prints `less' ``` If you are printing floats, remember: *you don't always see all digits when you print the float*. See also the big warning near the beginning of the [PHP float](http://www.php.net/float) docs.
The other answers have covered the cause and a good workaround to the problem, I believe. To aim at fixing the problem from a different angle: For storing price values in MySQL, you should probably look at the [DECIMAL type](http://dev.mysql.com/doc/refman/5.1/en/numeric-types.html), which lets you store exact values with decimal places.
php intval() and floor() return value that is too low?
[ "", "php", "floating-accuracy", "rounding-error", "" ]
I made an anagram machine and I have an array of positive matches. The trouble is they are all in a different order, I want to be able to sort the array so the longest array values appear first. Anybody have any ideas on how to do this?
Use <https://www.php.net/manual/en/function.usort.php> with this custom function ``` function sortByLength($a,$b){ return strlen($b)-strlen($a); } usort($array,'sortByLength'); ``` Use uasort if you want to keep the old indexes, use usort if you don't care. Also, I believe that my version is better because usort is an unstable sort. ``` $array = array("bbbbb", "dog", "cat", "aaa", "aaaa"); // mine [0] => bbbbb [1] => aaaa [2] => aaa [3] => cat [4] => dog // others [0] => bbbbb [1] => aaaa [2] => dog [3] => aaa [4] => cat ```
If you'd like to do it the PHP 5.3 way, you might want to create something like this: ``` usort($array, function($a, $b) { return strlen($b) - strlen($a); }); ``` This way you won't pollute your global namespace. But do this only if you need it at a single place in your source code to keep things DRY.
PHP: Sort an array by the length of its values?
[ "", "php", "arrays", "" ]
I have a scenario that my load balancer translates port 80 from outside into port 801 which is local. And When it comes to server, server obviously sees port 801 and in Response.Redirect it tries to inject port 801 into the URL it redirects to but this is not the desired solution for me. What I am thinking is to: 1. Overwrite Response.Redirect so that I remove the port from it. 2. Have some kind of configuration in web.config to ignore that port. 3. The most nasty way of fixing the problem is to change the whole application to use full URL's inside Response.Redirect which is a big pain. Is there a good solution to this problem? Environment: Windows Vista, Windows 2003 Server, Windows 2008 Server IIS 6, IIS 7 ASP.NET C# & VB.NET
Ok, I got the answer myself. I hope this solution will be useful for others too. Well, the answer is within the web.config. Under ``` <system.web> <httpRuntime useFullyQualifiedRedirectUrl="false" maxRequestLength="2526" requestLengthDiskThreshold="2526"/> </system.web> ``` where the important part is the following to be false. ``` useFullyQualifiedRedirectUrl="false" ``` This is true by default.
Do you need it to be a redirect, or can you just use Server.Transfer()?
How to overwrite Response.Redirect to prevent port coming with it
[ "", "c#", "asp.net", "windows", "iis", "response.redirect", "" ]
sometimes when i want a winforms control to be docked also to the right or bottom of the parent container (usually a UserControl), it's borders are extended way beyond the parent's right or bottom border, so that a part of it is not visible anymore. even though the anchor is set to right. this only happens when the application is run. as long as i am in the designer view everything looks fine. all i do is set the "Anchor" property of the control to "Right" for example. is there a way to avoid this? in this screenshot you can see the groupbox "Transition" extends way over it's parents extends to the right. <http://www.deviantsart.com/upload/08ffe2f5e7f4d33044840e68e0619152.png> thanks!
If you use Anchor then you cannot use Dock (and vice versa). > The Anchor and Dock properties are > mutually exclusive. Only one can be > set at a time, and the last one set > takes precedence. I would check if your controls' parent is actually the control you think it is (it could be its parent :-) ). Also check `Margin` property on the control and `Padding` property on the parent control. Then check `AutoSize` property.
Check your parent (UserControl) dock and anchor properties. It appears to me that they have not been set and the UserControl not the items in the UserControl are extending past the borders.
C#/winforms layout: element with anchor right or bottom vanishes under parent container
[ "", "c#", "winforms", "" ]
Say that I have LINQ query such as: ``` var authors = from x in authorsList where x.firstname == "Bob" select x; ``` Given that `authorsList` is of type `List<Author>`, how can I delete the `Author` elements from `authorsList` that are returned by the query into `authors`? Or, put another way, how can I delete all of the firstname's equalling Bob from `authorsList`? Note: This is a simplified example for the purposes of the question.
Well, it would be easier to exclude them in the first place: ``` authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList(); ``` However, that would just change the value of `authorsList` instead of removing the authors from the previous collection. Alternatively, you can use [`RemoveAll`](http://msdn.microsoft.com/en-us/library/wdka673a.aspx): ``` authorsList.RemoveAll(x => x.FirstName == "Bob"); ``` If you really need to do it based on another collection, I'd use a HashSet, RemoveAll and Contains: ``` var setToRemove = new HashSet<Author>(authors); authorsList.RemoveAll(x => setToRemove.Contains(x)); ```
It'd be better to use [List<T>.RemoveAll](http://msdn.microsoft.com/en-us/library/wdka673a.aspx) to accomplish this. ``` authorsList.RemoveAll((x) => x.firstname == "Bob"); ```
Using LINQ to remove elements from a List<T>
[ "", "c#", ".net", "linq", "list", "" ]
I would like to create pop-up windows (of a fixed size) like this: [![pop-up windows](https://i.stack.imgur.com/RMdfF.png)](https://i.stack.imgur.com/RMdfF.png) in my application using C#. I've looked into NativeWindow but I am not sure if this is the right way to do it. I want a window to behave exactly like the volume control or "connect to" window in Windows 7. How can I accomplish this?
I was able to accomplish this: ``` if (m.Msg == 0x84 /* WM_NCHITTEST */) { m.Result = (IntPtr)1; return; } base.WndProc(ref m); ```
Using WinForms, create a form and set the following: ``` Text = ""; FormBorderStyle = Sizable; ControlBox = false; MaximizeBox = false; MinimizeBox = false; ShowIcon = false; ``` **Edit:** This does require the window be sizable, but you can cheat at that a little. Set the MinimumSize and MaximumSize to the desired size. This will prevent the user from resizing. As Jeff suggested, you can also do this in CreateParams: ``` protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; unchecked { cp.Style |= (int)0x80000000; // WS_POPUP cp.Style |= 0x40000; // WS_THICKFRAME } return cp; } } ``` In both cases, however, you'll still get a sizing cursor when you hover over the edges. I'm not sure how to prevent that from happening.
Aero Glass borders on popup windows in C#
[ "", "c#", "popup", "border", "aero", "" ]
I need to write some sql that will allow me to query all objects in our Oracle database. Unfortunately the tools we are allowed to use don't have this built in. Basically, I need to search all tables, procedures, triggers, views, everything. I know how to search for object names. But I need to search for the contents of the object. i.e. SELECT \* FROM DBA\_OBJECTS WHERE object\_name = '%search string%'; Thanks, Glenn
i'm not sure if i understand you, but to query the source code of your triggers, procedures, package and functions you can try with the "user\_source" table. ``` select * from user_source ```
I'm not sure I quite understand the question but if you want to search objects on the database for a particular search string try: ``` SELECT owner, name, type, line, text FROM dba_source WHERE instr(UPPER(text), UPPER(:srch_str)) > 0; ``` From there if you need any more info you can just look up the object / line number. For views you can use: ``` SELECT * FROM dba_views WHERE instr(UPPER(text_vc), UPPER(:srch_str)) > 0 ```
SQL to search objects, including stored procedures, in Oracle
[ "", "sql", "oracle", "search", "full-text-search", "" ]
Hmmm... the Java `Iterator<T>` has a `remove()` method but not a `replace(T replacement)` method. Is there an efficient way to replace selected items in a List? I can use a for-loop to call get(i) and set(i) which is fine for ArrayList, but would suck for a linked list.
[`ListIterator.set`](http://java.sun.com/javase/6/docs/api/java/util/ListIterator.html#set(E)) as returned by [`List.listIterator()`](http://java.sun.com/javase/6/docs/api/java/util/List.html#listIterator()) or [`List.listIterator(int)`](http://java.sun.com/javase/6/docs/api/java/util/List.html#listIterator(int)) (`set` wouldn't make any sense for, say, a `Set` iterator.)
You need a [`ListIterator`](http://java.sun.com/javase/6/docs/api/java/util/ListIterator.html) instead of an `Iterator` ([`listIterator()`](http://java.sun.com/javase/6/docs/api/java/util/List.html#listIterator()) gives you one). Then use the [`set`](http://java.sun.com/javase/6/docs/api/java/util/ListIterator.html#set(E)) method.
iterator for replacing list members in Java?
[ "", "java", "list", "iterator", "" ]
Probably missing something completely obvious here, but here goes. I'm starting out with Spring MVC. I have a form controller to process inbound requests to /share/edit.html. When I hit this url from my browser, I get the following error: ``` The requested resource (/inbox/share/share/edit) is not available. ``` Here is my applicationContext-mvc.xml: ``` <bean id="publicUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" > <property name="mappings" > <value> /share/edit.html=shareFormController /share/list.html=shareController /share/view.html=shareController /folders.json=foldersController /studies.json=studiesController </value> </property> </bean> <bean id="internalPathMethodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver" /> <bean id="shareFormController" class="com.lifeimage.lila.controller.ShareFormController" /> <bean id="shareController" class="com.lifeimage.lila.controller.ShareController" > <property name="methodNameResolver" ref="internalPathMethodNameResolver" /> </bean> ``` and my form Controller: ``` public class ShareFormController extends SimpleFormController { public ShareFormController() { setCommandClass( Share.class ); } @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { //controller impl... } } ```
I think I've resolved this issue. There were two problems: 1) Implementations of SimpleFormController require a form and success view; which I had not configured here. As this is a server method for an AJAX client, I added a Spring-JSON view as follows: ``` <?xml version="1.0" encoding="UTF-8"?> ``` http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" default-lazy-init="false" default-autowire="no" default-dependency-check="none"> ``` <bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView"> <property name="jsonErrors"> <list> <ref bean="statusError" /> <ref bean="modelflagError" /> </list> </property> </bean> <bean name="statusError" class="org.springframework.web.servlet.view.json.error.HttpStatusError"> <property name="errorCode"><value>311</value></property> </bean> <bean name="modelflagError" class="org.springframework.web.servlet.view.json.error.ModelFlagError"> <property name="name"><value>failure</value></property> <property name="value"><value>true</value></property> </bean> ``` which can be used for all controllers that return JSON. 2) I switched from a SimpleURLHandlerMapping to ControllerClassNameHandlerMapping and relied on Spring naming conventions ( controllerClassName/method.html ), which fixed the routing issue. Might not be a long term solution, but got me through the task.
You should look at your view resolver. Make sure that it is resolving the logical name in your controller as you think it should. Looks like the name it is resolving it to does not exist currently
Spring MVC - Form Mapping
[ "", "java", "spring", "spring-mvc", "" ]
I've made a simple C# DLL (that's part of a much larger project) using VS2005. I need to use the DLL in Excel via VBA code so I am using COM Interop on the assembly. I am **trying to make the build process automatically generate the necessary TLB file** so that I don't need to go to the command line and use regasm after every build. My problem is that although the DLL compiles and builds fine, it does not generate a TLB file. Instead, the error in the title prints out in the output box. I've gotten other DLLs to build TLB files by going to the project's properties in VS2005 -> Build -> Output -> Check *"Register for COM interop"*. Also I have *[assembly: ComVisible(true)] in the AssemblyInfo.cs*. Here's the summary of the source for the problem DLL and the DLL that it references for a return type: ``` using System; using System.IO; using System.Runtime.InteropServices; using SymbolTable; namespace ProblemLibrary { public class Foo { public Foo(string filename) { ... } // method to read a text file into a SymbolTable public SymbolTable BuildDataSet(string[] selected) { ... } } } ``` Here is a summary of SymbolTable.dll. It holds a return type that ProblemLibrary uses. ``` using System; using System.Collections.Generic; namespace SymbolTable { public class SymbolTable { readonly Dictionary<SymbolInfoStub, string> _symbols = new Dictionary<SymbolInfoStub, string>(); /*methods that interact with Dictionary snipped*/ } } ```
1. You need to have ctor without any params. 2. You should have [GuidAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.guidattribute.aspx) and [ProgIdAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.progidattribute.aspx) around the classes. 3. Its better to mark the assembly as ComVisible(false) and mark explicitly the classes that need export. 4. Use interfaces for your classes. 5. Make sure the you have GuidAttribute in the assembly level. ``` [Guid("<PUT-GUID-HERE-1>")] [ComVisible(true)] interface IFoo { void DoFoo(); } [Guid("<PUT-GUID-HERE-2>")] [ComVisible(true)] [ProgId("ProgId.Foo")] class Foo : IFoo { public void DoFoo() { } } ```
In the AssemblyInfo.cs file, make sure you have the following: ``` // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(true)] ``` **UPDATE:** Read: [How can I make use of .NET objects from within Excel VBA?](https://stackoverflow.com/questions/179452/how-can-i-make-use-of-net-objects-from-within-excel-vba) Which links to: <http://richnewman.wordpress.com/2007/04/15/a-beginner%E2%80%99s-guide-to-calling-a-net-library-from-excel/>
warning MSB3391: <DLL> does not contain any types that can be unregistered for COM Interop
[ "", "c#", "visual-studio", "com-interop", "typelib", "comvisible", "" ]
I am trying to pass a structure from C# into C++ library. I pass structure as an object, and C++ function expects it as a pointer (void \*). I am having problem passing the structure. ``` [DllImport("MockVadavLib.dll", CharSet = CharSet.Ansi)] public static extern IntPtr TheFunction([MarshalAs(UnmanagedType.LPStruct)] UserRec userRec); ``` Here is the run-time exception text I get: > "Cannot marshal 'parameter #1': Invalid managed/unmanaged type combination (this value type must be paired with Struct)." Though I found an MSDN article that uses LPStruct in exactly this context. This is my structure I'm trying to marshal: ``` [StructLayout(LayoutKind.Sequential)] public struct UserRec { [MarshalAs(UnmanagedType.I4)] public int userParam1; } ``` This is C++ function: ``` MOCKVADAVLIB_API tVDACQ_CallBackRec * TheFunction(void * userParams) {... ```
Try passing the structure as a ref parameter. ``` [DllImport("MockVadavLib.dll", CharSet = CharSet.Ansi)] public static extern IntPtr TheFunction(ref UserRec userRec); ``` When you use a ref combined with a structure, it conceptually passes the address.
Incidentally, `UnmanagedType.LPStruct` is rarely, if ever, the correct `MarshalAs` argument. [A quote from Adam Nathan](http://blogs.msdn.com/b/adam_nathan/archive/2003/04/23/56635.aspx) who is a Microsoft employee: > UnmanagedType.LPStruct is only supported for one specific case: **treating a System.Guid value type as an unmanaged GUID with an extra level of indirection.**
How do I marshal a structure as a pointer to a structure?
[ "", "c#", "pinvoke", "" ]
``` string x; foreach(var item in collection) { x += item+","; } ``` can I write something like this with lambdas?
``` string[] text = new string[] { "asd", "123", "zxc", "456" }; var result = texts.Aggregate((total, str) => total + "," + str); ``` Shorter syntax, thanks to Earwicker
Assuming C#, have you tried String.Join()? Or is using lambdas mandatory? Example: ``` string[] myStrings = ....; string result = String.Join(",", myStrings); ``` **EDIT** Although the original title (and example) was about concatenating strings with a separator (to which `String.Join()` does the best job in my opinion), the original poster seems to ask about the broader solution: how to apply a custom format a list of strings. My answer to that is write your own method. String.Join has a purpose, reflected by its name (joins some strings). It's high chance that your format logic has a meaning in your project, so write it, give it a proper name and use it. For instance, if you want to output `<li>text</li>` for every item, make something as this: ``` string FormatAsListItems(string[] myStrings) { StringBuilder sb = new StringBuilder(); foreach (string myString in myStrings) { sb.Append("<li>").Append(myString).Append("</li>"); } } ``` I think the intent is clearer, and you also don't take the performance hit of concatenating strings in a loop.
convert a string[] to string with out using foreach
[ "", "c#", "lambda", "" ]
I have a function that generates a BouncyCastle RSA key pair. I need to encrypt the private key and then store the encrypted private and public keys into separate SQL2008 database fields. I am using the following to get the keypair: ``` private static AsymmetricCipherKeyPair createASymRandomCipher() { RsaKeyPairGenerator r = new RsaKeyPairGenerator(); r.Init(new KeyGenerationParameters(new SecureRandom(), 1024)); AsymmetricCipherKeyPair keys = r.GenerateKeyPair(); return keys; } ``` This is returning the keys fine, but I am not sure how I can then encrypt the private key and subsequently store it in the database. This is what I am currently using the encrypt the data (incorrectly?): ``` public static byte[] encBytes2(AsymmetricKeyParameter keyParam, byte[] Key, byte[] IV) { MemoryStream ms = new MemoryStream(); Rijndael rjdAlg = Rijndael.Create(); rjdAlg.Key = Key; rjdAlg.IV = IV; CryptoStream cs = new CryptoStream(ms, rjdAlg.CreateEncryptor(), CryptoStreamMode.Write); byte[] keyBytes = System.Text.Encoding.Unicode.GetBytes(keyParam.ToString()); cs.Write(keyBytes, 0, keyBytes.Length); cs.Close(); byte[] encryptedData = ms.ToArray(); return encryptedData; } ``` Obviously the keyBytes setting where I am converting keyParam.ToString() is not correct as it only converts the KeyParameter name, not the actual value. I am submitting to this function the previous key pair return of keys.Private. The other question is as I am not encrypting the Public Key what format should I be storing this in the SQL2008 database, nvarchar(256) or other? Any help would be greatly appreciated.
For reasons that should be clear, default (and perhaps inadvertent) serialization does not play well with private keys which should only be written out in very limited situations. BouncyCastle has support for PKCS#8, which is the relevant standard for "serializing" private keys. There are ASN.1 structures called PrivateKeyInfo and EncryptedPrivateKeyInfo. Since they are in ASN.1 there are standard ways to serialize/deserialize them. As the name suggests, one stores the key in plaintext, the other encrypts the key based on a password. For the public keys - these would not ordinarily be encrypted. BC supports the X.509 standard format of SubjectPublicKeyInfo for serializing them. In the C# build, the high-level classes to look at would be: * Org.BouncyCastle.Security.PrivateKeyFactory * Org.BouncyCastle.Security.PublicKeyFactory * Org.BouncyCastle.Pkcs.EncryptedPrivateKeyInfoFactory * Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory * Org.BouncyCastle.X509.SubjectPublicKeyInfoFactory
As long as the object is marked as serializable, one way to convert an object to a byte array is to use the BinaryFormatter class in .Net. You will need to add this using statement to your code file: ``` using System.Runtime.Serialization.Formatters.Binary; ``` A binary formatter can output your class to a stream. As you intend to convert your object to a byte array, you can use a System.IO.MemoryStream as temporary storage. ``` MemoryStream memStream = new MemoryStream(); ``` You can then create a new binary formatter. ``` BinaryFormatter formatter = new BinarryFomatter(); ``` and use this to serialize your object. ``` formatter.Serialize(memStream, someObject); ``` To get the bytes you can use: ``` return memStream.ToArray(); ``` To deserialize the byte array you need to write the bytes to a memory stream. ``` memStream.Write(arrBytes, 0, arrBytes.Length); ``` Return to the beginning of the stream. ``` memStream.Seek(0, SeekOrigin.Begin); ``` Then use the formatter to recreate the object. ``` Object obj = (Object)formatter.Deserialize(memStream); ``` If you are already using encryption functions you should be able to encrypt the created byte array quite easily before storing it in the database. Hopefully that will help you in the right direction. If you are lucky, the BouncyCastle objects will be marked as serializable, if not you will need some extra code. Later, I will get a chance to look at the BouncyCastle librarys to be able to test this and will post more code if necessary. --- ... I have never used BouncyCastle before. After some testing, it appears that the public and private key objects are not serializable, so you will need to convert these objects into something that is! It appears that the public and private keys expose properties as various BouncyCastle.Math.BigInteger values. (The keys can also be constructed from these BigIntegers). Further, BigIntegers have a ToByteArray() function and can also be constructed from a byte array. Very useful.. Knowing that you can break each key into BigIntegers and these in turn to a byte array and that the reverse is also possible, you a way to store all these in a serializable object. A simple struct or class would do e.g. ``` [Serializable] private struct CipherPrivateKey { public byte[] modulus; public byte[] publicExponent; public byte[] privateExponent; public byte[] p; public byte[] q; public byte[] dP; public byte[] dQ; public byte[] qInv; } [Serializable] private struct CipherPublicKey { public bool isPrivate; public byte[] modulus; public byte[] exponent; } ``` This gives us a pair of easy to use serializable objects. The AsymmetricCipherKeyPair exposes the Public and Private keys as AsymmetricKeyParameter objects. To get at the more detailed properties you will need to cast these to the following: keyPair.Public to BouncyCastle.Crypto.Parameters.RsaKeyParameters keyPair.Private to BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters The following functions will convert these to the structs to declared earlier: ``` private static CipherPublicKey getCipherPublicKey(Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters cPublic) { CipherPublicKey cpub = new CipherPublicKey(); cpub.modulus = cPublic.Modulus.ToByteArray(); cpub.exponent = cPublic.Exponent.ToByteArray(); return cpub; } private static CipherPrivateKey getCipherPrivateKey(Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters cPrivate) { CipherPrivateKey cpri = new CipherPrivateKey(); cpri.dP = cPrivate.DP.ToByteArray(); cpri.dQ = cPrivate.DQ.ToByteArray(); cpri.modulus = cPrivate.Modulus.ToByteArray(); cpri.p = cPrivate.P.ToByteArray(); cpri.privateExponent = cPrivate.Exponent.ToByteArray(); cpri.publicExponent = cPrivate.PublicExponent.ToByteArray(); cpri.q = cPrivate.Q.ToByteArray(); cpri.qInv = cPrivate.QInv.ToByteArray(); return cpri; } ``` Using the binary formatter mentioned earlier, we can convert the serializable objects we have just created to a byte array. ``` CipherPublicKey cpub = getCipherPublicKey((Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)keypair.Public); MemoryStream memStream = new MemoryStream(); BinaryFormatter formatter = new BinarryFomatter(); formatter.Serialize(memStream, cpub); return memStream.ToArray(); ``` Desierializing is then just the inverse as described earlier. Once you have either the public or private structs deserialized you can use the BouncyCastle contructors to recreate the keys. These functions demonstrate this. ``` private static Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters recreateASymCipherPublicKey(CipherPublicKey cPublicKey) { Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters key; key = new Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters( cPublicKey.isPrivate, createBigInteger(cPublicKey.modulus), createBigInteger(cPublicKey.exponent)); return key; } private static Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters recreateASymCipherPrivateKey(CipherPrivateKey cPrivateKey) { Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters key; key = new Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters( createBigInteger(cPrivateKey.modulus), createBigInteger(cPrivateKey.publicExponent), createBigInteger(cPrivateKey.privateExponent), createBigInteger(cPrivateKey.p), createBigInteger(cPrivateKey.q), createBigInteger(cPrivateKey.dP), createBigInteger(cPrivateKey.dQ), createBigInteger(cPrivateKey.qInv)); return key; } ``` If you need to recreate the original key pair for any reason: ``` AsymmetricKeyParameter publ = (AsymmetricKeyParameter)recreateASymCipherPublicKey(cKeyPair.publicKey); AsymmetricKeyParameter priv = (AsymmetricKeyParameter)recreateASymCipherPrivateKey(cKeyPair.privateKey); AsymmetricCipherKeyPair keyPair = new AsymmetricCipherKeyPair(publ, priv); ``` Hopefully that all makes sense! The code samples should help you on your way.
Encrypting a BouncyCastle RSA Key Pair and storing in a SQL2008 database
[ "", "c#", ".net", "sql-server", "bouncycastle", "private-key", "" ]
How can i prevent duplicate rows being selected in a select query? I have a table with the following fields: * name * type * user1 * user2 * user3 * date My query requires me to select data for a particular user only at a time which is entered by the user at front end.. Say user enters 1, then the select query should retreive data for user1 only. I am currently doing it like this: ``` select name,type,date from table1 order by user1; ``` But I'm getting redundant rows in the result?? what i am doing wrong? How to avoid these duplicate rows? Please help...
You have two options SELECT DISTINCT or use a GROUP BY clause. You also have a date column and in Oracle that also means there is time so to be safe you should truncate the date column. Even if you know time is no part of the insert truncate anyways. It good practice that when you see date you consider it has time. The next issue you'll encounter is you can not have an ORDER BY on a column that is not part of the SELECT. My recommendation is a GROUP BY. ``` SELECT user1, name, type, TRUNC(date) date FROM Table1 GROUP BY user1, name, type, TRUNC(date) ORDER BY user1 ```
I don't know if I get your question completely. But I will try anyway: 1. If you want to filter on certain user based on user input try: select name, type, "date" from table1 where user = [WHATEVER YOUR USER INPUTS] order by name 2. If you want to pick a different column (user1, user2, user3) depending on user input try: select name, type, "date", decode(YOUR\_USER\_INPUT, 1, user1, 2, user2, 3, user3) from table1 order by name 3. If you **just** want different results, try **select distinct** select distinct name, type, "date", user1, user2, user3 from table1 Please **do** provide an example so we can help accordingly. Good luck, *gudluck*.
Duplicate rows in Oracle
[ "", "sql", "oracle", "distinct", "" ]
My project includes a jar file because it is listed as a transitive dependency. However, I have verified not only that I don't need it but it causes problems because a class inside the jar files shadows a class I need in another jar file. How do I leave out a single jar file from my transitive dependencies?
You can exclude a dependency in the following manner: ``` <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.6</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> ```
The correct way is to use the exclusions mechanism, however sometimes you may prefer to use the following hack instead to avoid adding a large number of exclusions when lots of artifacts have the same transitive dependency which you wish to ignore. Rather than specifying an exclusion, you define an additional dependency with a scope of "provided". This tells Maven that you will manually take care of providing this artifact at runtime and so it will not be packaged. For instance: ``` <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.6</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> <scope>provided</scope> </dependency> ``` Side effect: you must specify *a* version of the artifact-to-be-ignored, and its POM will be retrieved at build-time; this is not the case with regular exclusions. This might be a problem for you if you run your private Maven repository behind a firewall.
Maven: remove a single transitive dependency
[ "", "java", "maven-2", "dependencies", "" ]
I need to upload a massive (16GB, 65+ million records) CSV file to a single table in a SQL server 2005 database. Does anyone have any pointers on the best way to do this? **Details** I am currently using a C# console application (.NET framework 2.0) to split the import file into files of 50000 records, then process each file. I upload the records into the database from the console application using the SqlBulkCopy class in batches of 5000. To split the files takes approximately 30 minutes, and to upload the entire data set (65+ million records) takes approximately 4.5 hours. The generated file size and the batch upload size are both configuration settings, and I am investigating increasing the value of both to improve performance. To run the application, we use a quad core server with 16GB RAM. This server is also the database server. **Update** Given the answers so far, please note that prior to the import: * The database table is truncated, and all indexes and constraints are dropped. * The database is shrunk, and disk space reclaimed. After the import has completed: * The indexes are recreated If you can suggest any different approaches, or ways we can improve the existing import application, I would appreciate it. Thanks. **Related Question** The following question may be of use to others dealing with this problem: * [Potential Pitfalls of inserting millions of records into SQL Server 2005 from flat file](https://stackoverflow.com/questions/141556/potential-pitfalls-of-inserting-millions-of-records-into-sql-server-2005-from-fla) **Solution** I have investigated the affect of altering batch size, and the size of the split files, and found that batches of 500 records, and split files of 200,000 records work best for my application. Use of the `SqlBulkCopyOptions.TableLock` also helped. See the answer to this [question](https://stackoverflow.com/questions/779690/what-is-the-recommended-batch-size-for-sqlbulkcopy/869202#869202) for further details. I also looked at using a SSIS DTS package, and a `BULK INSERT` SQL script. The SSIS package appeared quicker, but did not offer me the ability to record invalid records, etc. The `BULK INSERT` SQL script whilst slower than the SSIS package, was considerably faster than the C# application. It did allow me to record errors, etc, and for this reason, I am accepting the `BULK INSERT` answer from [ConcernedOfTunbridgeWells](https://stackoverflow.com/users/15401/concernedoftunbridgewells) as the solution. I'm aware that this may not be the best answer for everyone facing this issue, but it answers my immediate problem. Thanks to everyone who replied. Regards, MagicAndi
`BULK INSERT` is run from the DBMS itself, reading files described by a bcp control file from a directory on the server (or mounted on it). Write an application that splits the file into smaller chunks, places them in an appropriate directory executes a wrapper that executes a series of `BULK INSERTS`. You can run several threads in parallel if necessary. This is probably about as fast as a bulk load gets. Also, if there's a suitable partitioning key available in the bulk load file, put the staging table on a partition scheme. Also, if you're bulk loading into a table with a clustered index, make sure the data is sorted in the same order as the index. Merge sort is your friend for large data sets.
Have you tried SSIS (SQL Server Integration Services).
Upload a Massive CSV File to SQL Server Database
[ "", "c#", ".net", "sql-server", ".net-2.0", "csv", "" ]
I have a TreeView control in a Winforms app, and basically the objective is to display a form that contains a TreeView control, and I want to display the form with a node opened (easy - EnsureVisible) and selected. The problem that I'm running into is that when I set the TreeView control's SelectedNode property, the node isn't highlighted and the AfterSelect event isn't firing as I would expect it to. The AfterSelect thing is easy to code around, but the lack of highlighting is annoying.
Is it because the TreeView doesn't have focus? Does setting the TreeView's HideSelection property to False change the behavior you're seeing?
After you set the SelectedNode. Try selecting the treeView. Worked for me anyway. ``` private void button1_Click(object sender, EventArgs e) { this.treeView1.SelectedNode = this.treeView1.Nodes[1]; this.treeView1.Select(); } ```
How can I programmatically click a TreeView TreeNode so it appears highlighted in the list and fires the AfterSelect event?
[ "", "c#", "winforms", "treeview", "" ]
I edited the question so it would make more sense. I have a function that needs a couple arguments - let's call it `fc()`. I am passing that function as an argument through other functions (lets call them `fa()` and `fb()`). Each of the functions that `fc()` passes through add an argument to `fc()`. How do I pass `fc()` to each function without having to pass `fc()`'s arguments separately? Below is how I want it to work. ``` function fa(fc){ fc.myvar=something fb(fc) } function fb(fc){ fc.myothervar=something fc() } function fc(){ doessomething with myvar and myothervar } ``` Below is how I do it now. As I add arguments, it's getting confusing because I have to add them to preceding function(s) as well. `fb()` and `fc()` get used elsewhere and I am loosing some flexibility. ``` function fa(fc){ myvar=something fb(fc,myvar) } function fb(fc,myvar){ myothervar=something fc(myvar,myothervar) } function fc(myvar,myothervar){ doessomething with myvar and myothervar } ``` Thanks for your help --- **Edit 3 - The code** I updated my code using JimmyP's solution. I'd be interested in Jason Bunting's non-hack solution. Remember that each of these functions are also called from other functions and events. From the HTML page ``` <input type="text" class="right" dynamicSelect="../selectLists/otherchargetype.aspx,null,calcSalesTax"/> ``` Set event handlers when section is loaded ``` function setDynamicSelectElements(oSet) { /************************************************************************************** * Sets the event handlers for inputs with dynamic selects **************************************************************************************/ if (oSet.dynamicSelect) { var ySelectArgs = oSet.dynamicSelect.split(','); with (oSet) { onkeyup = function() { findListItem(this); }; onclick = function() { selectList(ySelectArgs[0], ySelectArgs[1], ySelectArgs[2]) } } } } ``` `onclick` event builds list ``` function selectList(sListName, sQuery, fnFollowing) { /************************************************************************************** * Build a dynamic select list and set each of the events for the table elements **************************************************************************************/ if (fnFollowing) { fnFollowing = eval(fnFollowing)//sent text function name, eval to a function configureSelectList.clickEvent = fnFollowing } var oDiv = setDiv(sListName, sQuery, 'dynamicSelect', configureSelectList); //create the div in the right place var oSelected = event.srcElement; if (oSelected.value) findListItem(oSelected)//highlight the selected item } ``` Create the list ``` function setDiv(sPageName, sQuery, sClassName, fnBeforeAppend) { /************************************************************************************** * Creates a div and places a page in it. **************************************************************************************/ var oSelected = event.srcElement; var sCursor = oSelected.style.cursor; //remember this for later var coords = getElementCoords(oSelected); var iBorder = makeNumeric(getStyle(oSelected, 'border-width')) var oParent = oSelected.parentNode if (!oParent.id) oParent.id = sAutoGenIdPrefix + randomNumber()//create an ID var oDiv = document.getElementById(oParent.id + sWindowIdSuffix)//see if the div already exists if (!oDiv) {//if not create it and set an id we can use to find it later oDiv = document.createElement('DIV') oDiv.id = oParent.id + sWindowIdSuffix//give the child an id so we can reference it later oSelected.style.cursor = 'wait'//until the thing is loaded oDiv.className = sClassName oDiv.style.pixelLeft = coords.x + (iBorder * 2) oDiv.style.pixelTop = (coords.y + coords.h + (iBorder * 2)) XmlHttpPage(sPageName, oDiv, sQuery) if (fnBeforeAppend) { fnBeforeAppend(oDiv) } oParent.appendChild(oDiv) oSelected.style.cursor = ''//until the thing is loaded//once it's loaded, set the cursor back oDiv.style.cursor = '' } return oDiv; } ``` Position and size the list ``` function configureSelectList(oDiv, fnOnClick) { /************************************************************************************** * Build a dynamic select list and set each of the events for the table elements * Created in one place and moved to another so that sizing based on the cell width can * occur without being affected by stylesheet cascades **************************************************************************************/ if(!fnOnClick) fnOnClick=configureSelectList.clickEvent if (!oDiv) oDiv = configureSelectList.Container; var oTable = getDecendant('TABLE', oDiv) document.getElementsByTagName('TABLE')[0].rows[0].cells[0].appendChild(oDiv)//append to the doc so we are style free, then move it later if (oTable) { for (iRow = 0; iRow < oTable.rows.length; iRow++) { var oRow = oTable.rows[iRow] oRow.onmouseover = function() { highlightSelection(this) }; oRow.onmouseout = function() { highlightSelection(this) }; oRow.style.cursor = 'hand'; oRow.onclick = function() { closeSelectList(0); fnOnClick ? fnOnClick() : null }; oRow.cells[0].style.whiteSpace = 'nowrap' } } else { //show some kind of error } oDiv.style.width = (oTable.offsetWidth + 20) + "px"; //no horiz scroll bars please oTable.mouseout = function() { closeSelectList(500) }; if (oDiv.firstChild.offsetHeight < oDiv.offsetHeight) oDiv.style.height = oDiv.firstChild.offsetHeight//make sure the list is not too big for a few of items } ```
Okay, so - where to start? :) Here is the partial function to begin with, you will need this (now and in the future, if you spend a lot of time hacking JavaScript): ``` function partial(func /*, 0..n args */) { var args = Array.prototype.slice.call(arguments, 1); return function() { var allArguments = args.concat(Array.prototype.slice.call(arguments)); return func.apply(this, allArguments); }; } ``` I see a lot of things about your code that make me cringe, but since I don't have time to really critique it, and you didn't ask for it, I will suggest the following if you want to rid yourself of the hack you are currently using, and a few other things: ## The setDynamicSelectElements() function In this function, you can change this line: ``` onclick = function() { selectList(ySelectArgs[0], ySelectArgs[1], ySelectArgs[2]) } ``` To this: ``` onclick = function() { selectList.apply(null, ySelectArgs); } ``` ## The selectList() function In this function, you can get rid of this code where you are using eval - don't ever use eval unless you have a good reason to do so, it is very risky (go read up on it): ``` if (fnFollowing) { fnFollowing = eval(fnFollowing) configureSelectList.clickEvent = fnFollowing } ``` And use this instead: ``` if(fnFollowing) { fnFollowing = window[fnFollowing]; //this will find the function in the global scope } ``` Then, change this line: ``` var oDiv = setDiv(sListName, sQuery, 'dynamicSelect', configureSelectList); ``` To this: ``` var oDiv = setDiv(sListName, sQuery, 'dynamicSelect', partial(configureSelectListAlternate, fnFollowing)); ``` Now, in that code I provided, I have "configureSelectListAlternate" - that is a function that is the same as "configureSelectList" but has the parameters in the reverse order - if you can reverse the order of the parameters to "configureSelectList" instead, do that, otherwise here is my version: ``` function configureSelectListAlternate(fnOnClick, oDiv) { configureSelectList(oDiv, fnOnClick); } ``` ## The configureSelectList() function In this function, you can eliminate this line: ``` if(!fnOnClick) fnOnClick=configureSelectList.clickEvent ``` That isn't needed any longer. Now, I see something I don't understand: ``` if (!oDiv) oDiv = configureSelectList.Container; ``` I didn't see you hook that Container property on in any of the other code. Unless you need this line, you should be able to get rid of it. The setDiv() function can stay the same. --- Not too exciting, but you get the idea - your code really could use some cleanup - are you avoiding the use of a library like jQuery or [**MochiKit**](http://www.mochikit.com) for a good reason? It would make your life a lot easier...
A function's properties are not available as variables in the local scope. You must access them as properties. So, within 'fc' you could access 'myvar' in one of two ways: ``` // #1 arguments.callee.myvar; // #2 fc.myvar; ``` Either's fine...
Javascript function objects
[ "", "javascript", "dhtml", "" ]