text stringlengths 8 267k | meta dict |
|---|---|
Q: Getting started with mobile programming. What is a good platform? What is a good mobile programming platform to go with for a c++ developer?
Is learning android a good option?
A: If you already know C++ then Symbian has the largest install base, and isn't sandboxed like java/android vm/iphone.
Whilst the iPhone and Andriod may seem interesting, if you actually look at the figures Symbian really is the only option when looking at market share. Despite apple's advertising behemoth and cult following, it is far from being anywhere near the 200+ million Symbian smart phones out there. (there are approx 5 million iphone users).
Added to the fact that "java" on mobiles doesn't always mean the same thing. Different phones include different versions so unlike the PC environment, java on mobiles is not as "write once, run anywhere" as it makes out.
A: I have started playing with Android with the latest SDK. It is super easy to develop because of the coolness of Java, richness of android platform and eclipse IDE is very easy to use. I think Android is going to make a big difference in the moile application side.
UPDATE : Now you have the option of Windows Phone 7 too, which is my favorite at this point because I am a .NET developer for many years. Just get the WP7SDK and start coding in your visual studio itself.
A: Java ME will give you the widest choice of deployment options and market share, because most mobile phones support it. Going from C++ to Java is quite easy, since Java has fewer gotchas than C++. As a positive side effect you will also get to learn Java on a platform whose footprint is a lot smaller and manageable than Java SE.
A: I would advice the .NET Compact Framework for easy and fast development. The included emulator in Visual Studio makes it that much easier to develop.
But I also think that it depends on your intended application, I would for instance not advice the compact framework for writing a game with demanding graphics.
The downside of using the .NET Compact Framework is that you'll get limited on your target hardware, because it will only run on Microsoft Windows CE versions (and I thought on SymbianOS).
A: Personally, I started out with the Windows Mobile platform and Microsoft Embedded C++.
It was a natural shift because I'd come from the MSVC compiler/Visual Studio 6 environment, so I was already quite familiar with aspects of the compiler and the IDE.
In fact, because I was so familiar with those other tools, picking up the emulator and (notably) the oddities of working with ActiveSync became much easier. I also found the OS to be easy to use (including the familiar File Explorer and system design).
So, to more accurately answer your question, I think it depends on which platform you are familiar with previously and how confident you feel with the tools available. Especially for debugging and emulating!
A: in Symbian you can reach all the phone functionality == do really cool things, but Symbian is a bitch when you are trying to learn it from scratch - it's complicated.
JavaME - popular, very quick to start, light API, but sandboxed, access to different phone areas varies from vendor to vendor, from model to model. You can do stuff like connect to net, draw graphics and display menus on pretty every phone, but access to phone book, camera, sms messaging varies greatly
Sometimes it takes time to get app working exactly the same on different phone models (i don't know exactly, but i think this would be a problem on all the mobile platforms)
A: You surely need to check out Windows Phone 7, it is C# and have great tool support with VS2010 and Expression blend to develop quick Windows Phone applications. Not only this will benefit you in Phone. The same dev-skill set can be used to make Silverlight as well as WPF applications easily.
A: You can try to use StartJava which illustrate Android application creation.
http://www.en.assoft.ru/startjava
https://play.google.com/store/apps/details?id=com.assoft.StartJava
A: I want suggest you android is best technology among all now a days android phones are increasing tremendously so the development are also increasing like wise and it can be learn any developer...on the internet many tutorials are available to teach you android programming....so i would like to suggest you is that android is the best option...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Qt context menu breaking selection in QTreeView I have a QTreeView class with a context menu installed as follows:
m_ui.tree->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_ui.tree, SIGNAL(customContextMenuRequested(const QPoint&)),
this, SLOT(ShowTreeContextMenu(const QPoint&)));
...
void ShowTreeContextMenu(const QPoint& point)
{
m_treeContextMenu->exec(m_ui.tree->viewport()->mapToGlobal(point));
}
However when the context menu is being displayed the QTreeView will no longer respond to mouse clicks. Clicking on an item in the QTreeView while the context menu is displayed will remove the context menu but does not select the clicked item.
This is especially disorientating when right clicking on a new item, as the context menu pops up over the new item, but as the item was not selected the contents of the context menu are referring to the previously selected item.
A: A possible solution which I haven't verified would be to capture the click event of the right click, manually make the selection in the tree view and then invoking the parent click event which will in turn activate the context menu.
A: Subclass the QTreeView and add the protected method void contextMenuEvent(QContextMenuEvent *event); In this method you execute a QMenu:
class TreeView : public QTreeView{
Q_OBJECT
public:
TreeView(QWidget *parent);
~TreeView();
protected:
void contextMenuEvent(QContextMenuEvent *event);
};
void TreeView::contextMenuEvent(QContextMenuEvent *event){
QMenu menu(this);
menu.addAction(action1);
menu.addAction(action2);
//...
menu.addAction(actionN);
menu.exec(event->globalPos());
}
A: You don't say which version of Qt you are using, but we found the same problem in Qt4.4.0, it worked in 4.3. We reported this to Trolltech as a bug 225615
This is still marked as pending, so in the meantime I would follow Shy's suggestion of intercepting the right click and making the selection yourself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Best Windows Installation file Creator? I'm not the best programmer so I found it was much easier to write a program as several separate executables, which occasionally call each other. But now I need an easy way to actually run them without writing detailed instructions like Run file one, wait until its completed and no longer in process manager before running file two, file three can be executed 15 seconds after file two has been created. Then Add a key to your registry. Etc. I figure there must be a good software out there where I can just drop all my exes in, tell it when to run them, and output one file for my clients to run. Any ideas?
A: Yes, two ideas:
*
*If you're looking for a way to statically put files, registry keys, start menu shortcuts, et cetera on your customer's systems, you should be looking for an installer solution. Many of these exist, and choosing the best one mostly comes down to features and pricing. I happen to like Caphyon's Advanced Installer, and it does have a freeware version that looks like it might meet your needs, except for the ability to run executables at scheduled times (which would require the Windows Task Scheduler support only found in the Enterprise edition, which is in the ultra-expensive price range, comparable to InstallShield...)
*If controlling the flow of events on your customer's systems is more important than getting the executables on the system, you may want to look into Automise, which is basically an ultra-friendly UI for creating scripts, which makes things like scheduling tasks quite easy.
Anyway, you can download trial editions of both pieces of software, to see which one (or possibly both) will allow you to do what you want in the easiest way, or at least give you some ideas on how to best serve your customers. It may turn out that simply adding a new, 'supervisor' executable to take care of registry keys, scheduling, etc. could solve the problem without any third-party add-ons...
A: Inno Setup is easy to use, free, open source and scriptable if you need it.
A: If you don't have any specific requirements apart from being able to install a few executables, then basically anyone will do. I'd recommend NSIS, not because it is particularly easy to work with (it has a cumbersome assembly-like language which isn't to practical to do more complex things in), but because it is free, has a large and active community, and it generates fast installers with very low overhead. As an extra bonus, you can run the compiler (i.e. the tool which generates the installer) on Linux.
Edit: ...and whatever you do, do NOT use InstallShield.
A: WixEdit is an open source (install shield like) authoring tool that uses the Wix Runtime from Microsoft.
Wix Tutorials
A: The ones I've worked with are:
*
*InstallShield
*NSIS
*INNO Setup
*Custom created installer
My preference is INNO Setup. It's free, it's easy.
A: I've always had a good experience with NSIS
*
*It's open source
*It has a big community (and hence lots of plugins)
*For simple things, its script-based approach is nice and easy
*It's lightweight and fast
On the downside, if you want to do something more sophisticated, you need to use something that looks a bit like assembly language - very odd, and not particularly pleasant. Thanks for the comments about that - I'd forgotten all about it!
A: Inno Setup is simple, light-weight and covers a lot of ground. I've used it for 5-6 apps over the last 5 years and it never let me down. Highly recommended!
Before that I used InstallShield, which is one of these systems that are so complicated that they "offer" you to "utilize" their "professional services" to create your installations. In other words it's kind of a hack that only managed to build a customer base in the childhood of Windows because there was no competition. It's a bit like a 747 that runs like a Trabant.
The worst, by far, installer product I've worked with is "WISE for Windows Installer". This had me literally smash my mouse in the office floor in frustration. It is (or at least was, 4 years ago) utter crap and should be avoided at all costs. This is exactly the kind of software that those pesky license agreements are there for, else the publisher would be sued into oblivion...
A: I heart wix, MSFT's open source, declarative (XML) based toolkit for building MSIs.
It's ace.
If you want to install binaries, add reg keys and even run "custom actions" (have your own code execure during install) you should have a look at it. Then you'll have a one-click (msi) solution. Good eh?
A: Definately Wix. :)
Wix allows you to do the most things with ease and the difficult things without hacks, it's free and open-source.
You can use Wix within Visual Studio (using Votive) or you can use it using the .Net SDK, MSBuild and your favorite XML editor. Wix supports creating MSI installers, MSP patches, MSM Merge modules, Wix libraries and much more.
A: You should take a look at InstallJammer. Not only is it free, it's cross-platform and very easy to use. Most common actions don't require any scripting at all, but with a powerful scripting language underneath the hood, you can make an install do just about anything you want.
If all you want is a basic installer to install your application, you can have it built in a matter of minutes from the first time you start it up. If you want something more powerful, the capabilities and documentation are excellent.
A: If you're not after an installer (which is doesn't sound like you are) Why not just write a program to do what you need?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: What does a db table created by the Rails framework look like? I don't have a Rails environment set up and this is actually quite hard to find a quick answer for, so I'll ask the experts.
When Rails creates a table based on your "model" that you have set up, does Rails create a table that mirrors this model exactly, or does it add in more fields to the table to help it work its magic? If so, what other fields does it add and why? Perhaps you could cut and paste the table structure, or simply point me to a doc or tutorial section that addresses this.
A: If you're building a completely new application, including a new database, then you can build the whole back end with migrations. Running
ruby script/generate model User name:string
produces both a user.rb file for the model and a migration:
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :name
t.timestamps
end
end
def self.down
drop_table :users
end
end
You can see that by default the generate script adds "timestamps" for (created and last updated) and they're managed automatically if allowed to remain present.
Not visible, but important, is that an extra column, "id", is created to be the single primary key. It's not complusory, though - you can specify your own primary key in the model, which is useful if you're working with a legacy schema. Assuming you retain id as the key, then Rails will use whatever RDBMS-specific features are available for new key values.
A: In ActiveRecord, models are created from database tables, not the other way around.
You may also want to look into Migrations, which is a way of describing and creating the database from Ruby code. However, the migration is not related to the model; the model is still created at runtime based on the shape of the database.
There are screencasts related to ActiveRecord and Migrations on the Rails site: http://www.rubyonrails.org/screencasts
A: Here's the official documentation for ActiveRecord. It agrees with Brad. You might have seen either a different access method or a migration (which alters the tables and thus the model)
A: I have had a little experience moving legacy databases into Rails and accessing Rails databases from outside scripts. That sounds like what you're trying to do. My experience is in Rails databases built on top of MySQL, so your mileage may vary.
The one hidden field is the most obvious --- the "id" field (an integer) that Rails uses as its default primary key. Unless you specify otherwise, each model in Rails has an "id" field that is a unique, incremented integer primary key. This "id" field will appear automatically in any model generated within Rails through a migration, unless you tell Rails not to do so (by specifying a different field to be the primary key). If you work with Rails databases from outside Rails itself, you should be careful about this value.
The "id" field is a key part of the Rails magic because it is used to define Rails' associations. Say you relate two tables together --- Group and Person. The Group model will have an "id" field, and the Person model should have both its own "id" field and a "group_id" field for the relationship. The value in "group_id" will refer back to the unique id of the associated Group. If you have built your models in a way that follows those conventions of Rails, you can take advantage of Rails' associations by saying that the Group model "has_many :people" and that the Person model "belongs_to :group".
Rails migrations also, by default, want to add "created_at" and "updated_at" fields (the so-called "timestamps"), which are datetime fields. By default, these take advantage of the "magic" in the database --- not in Rails itself --- to automatically update whenever a record is created or modified. I don't think these columns will trip you up, because they should be taken care of at the database level, not by any special Rails magic.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What's in your Utility Toolkit? Some of the most efficient engineers, developers and IT professionals I know usually carry around a common "toolkit" of useful programs, add-ins or utilities which help them for day-to-day debugging, developing or designing.
The question is:
What is in your utility toolkit.. What tools couldn't you live without?
A: Ack
Its like grep, but better, faster, and does more what you want to generally do with large source collections. Written in Perl, and does complete PCRE because of this. Recursive traversal is default, and it intelligently skips files that are unlikely to match using file-type identification to short cut.
( This means it automatically avoids traversing .svn/.hg/.git directories and thus gives massive speedups )
ack "function\s+foo\s*\(" --php
# find the definition of "foo" in all php files
# decendant of the current directory
A: Total Commander (GREP, FTP, ZIP, it's all here...I'm not even starting on this one)
Notepad++
WinMerge
A: Python. Seriously. I use it for a lot of small stuff. I also like to use the command line module for creating easy little project specific "shells" that I drop in frequently used queries etc. (show all tables in the projects db, search for stored procedures etc. - yeah, doing a lot of t-sql lately...)
I tend to accompany big c#/t-sql projects with a little python script that extends the cmd.Cmd class to give me a small collection of helpful queries etc. that I can use to poke around in the database.
Also, I often use python to modify input data (often csv files, but any junk will do) into insert statements etc. Or do plausibility tests on that data.
A: Currently on my thumbdrive (not ALL software):
*
*Notepad++
*.NET Reflector
*develop (incase I need a quick IDE setup on a different computer)
*C# Default Keybindings pdf
*Math tables pdf
*Boo Primer pdf
*MSDN C# & VB Example projects
A: My Utility toolkit would have:
1.) Hex Editor - XVI32, or any other
2.) Beyond Compare - Comparison of files
3.) Cygwin shell installable complete with perl, gcc,gprof,gcov,gdb and related tools,bash,vim, development/debugging tools
4.) A model makefile for *nix platform
5.) Winzip utility
6.) Source insight or any other good code browsing tool
7.) Ghostscript and GSView
8.) PDF reader
9.) Good quick antivirus tool/exe
-AD
A: Currently in Thumbdrive\Tools.
"Edit Plus 3" - lightweight editor that I've been using for ages.
"F# - 1.9.6.2" - great for when I need to throw something togheter since it's usable without an IDE, also a great language for many tasks.
"ildasm"
"Sysinternal Procmon" - great for debugging and getting a feel for what the machine is really doing.
A: I have the following tools on my USB thumd drive:
*
*SysInternals Suite All their great troubleshooting tools in one download, in case I might need a tool that I didn't download before
*WireShark setup
*VNC binaries (so I can run the viewer directly from USB) and setup
*A couple of Portable Apps:
*
*Notepad++ Portable
*Putty Portable
*FileZilla Portable
*7-zip Portable
*Sumatra PDF Portable
*WinMerge Portable
A: I use/carry with me:
*
*.Net Reflector
*The SysInternals
*Suite (particularly Process Explorer, Debug View etc)
*Exescope
*Orca (Windows Installer)
*Depends
*Spy++ OleView
*Resourcer
*Ethereal
*IE Dev toolbar
*Depends .Net
*DocView
*LDP (For LDAP)
Just to name a few
A: I do a full install of cygwin. It gives me 95% of the stuff I need and hard drive space is cheep. It's a lot easier to install everything then get emacs, gcc, gdb, perl, utilitys such as grep and awk, not to mention the servers it comes with like Apache and MySQL if you want to try something out quick.
A: Unix Utilities for Windows
A: grep gives you the biggest bang for the buck. You can use it to search on any type code and many forms of data. It is fast, and very powerful. In code it can locate what you're looking for in variables and function names, but also in comments. You can also pipe results into it, and can thus enhance the utility of many tools available on site.
With some clever hints you can easily make grep search for a specific type of an identifier. For instance, "^function_name" will often find in C code a function's definition, because these start with the name of the function at the beginning of the line. If a search pattern gives you too many false matches, you can filter those out, by piping the result through grep -v.
Many years ago I was stranded debugging COBOL programs on a 1970s-era Perkin Elmer machine running OS/32. The machine lacked programming tools, but had an ancient C compiler (so old, it would accept =+ as the original form of the += operator). I ended up writing a rudimentary grep program, which immensely improved my productivity.
A: *
*Notepad ++
*FF + Firebug
*Jquery + bunch of plugins
*DBManager
*Cygwin for error tracking
*Google for help
*Docs in CHM & Cheatsheets
A: I always seem to have a bootable Linux Distro on me in SOME form or other. Whether it be the bootable Pen Drive I keep attached to my Keys, or the multitude of LiveCDs I have for various "diagnostics" - I find that if I am in a situation, generally, where I'd need some sort of tools... a reboot into a Live environment provides me with near enough everything I need, and more
A: *
*PE Explorer
*FAR Manager (great file manager especially when working with lots of ftp sites)
*FlexHex
*Ida
*OllyDbg
A: Emacs. It's my "does list of things" tool, helpful with quick calculations, with mangling configuration files (I work as a network engineer, there is an awful lot of configuration to be done, lots of it bordering on trivial to generate with either small snippets of code or careful use of keyboard macros).
A: Here's the tools I use to make Sharepoint solutions:
*
*Visual Studio Team Suite 2008
*VSTS Database Edition GDR
*Sandcastle
*DocProject for Sandcastle
*.net Reflector
*GhostDoc
*CSS Vista
*Sharepoint Inspector
*Sharepoint Explorer
*EditPadPro
*CodeSmith 2.6 Freeware (with my own .net 3.5 SP1 gui)
*Indigo Rose MSI Factory
*Wix
*Nmap
*Wireshark
*Fiddler
*Adobe Photoshop CS3
*Expresso (Regex tool)
*VMRCPlus
*Powershell 2 CTP
*Quest PowerGui for Powershell
*IIS Resource Kit
*HyperV
A: Tools I use because you do not have to install, just drop on system and use:
*
*Agent Ransack
*7-zip
*PSPad
*Robocopy : Need to extract from Windows 2003 resource kit (just grab the .exe)
A: Fast image viewer that has been around for a long time and proven to work.
IrfanView
A: ide: visual studio / netbeans (zip file!, almost portable)
editor: notepad++ (portable) with monaco font
file comparison: winmerge (portable)
source control: subversion, tortoise
ticket control: redmine
file manager: free commander (portable)
explorer: IE, FF (portable), chrome (portable), iron (chrom without google crap, also portable), qtweb, arora,
FF plugins: firebug, web developer, xmarks
imclient: pidgin
mail client: gmail
download manager: free download manager (portable)
sites: STACKOVERFLOW!!!, gotapi... and google, all the time...
miscelaneous: launchy (can't live without it!)
virtualization: virtual box (I have a machine image for every environment)
office: openoffice (portable)
lamp stack: xammp (portable!)
disk usage: windirstat (portable), scanner (portable)
pdf viewer: foxit (portable), sumatrapdf (portable)
uncompressor: 7-zip portable
M$ sql comparison tool: sql delta
M$ sql management: visual studio sql manager
mysql
mysql management: phpmyadmin, manager provided with mysql
uninstaller utility: revo unistaller (portable)
registry cleaner: ccleaner (portable)
ftp: filezilla (portable)
as you may have noticed, I have a special predilection for portable applications...
A: *
*gVim
*VS2010 Express
*Firefox + Firebug
A: System Rescue CD
*
*A collection of very useful utilities on a Live CD
A: There are two tools I simply can't work without
*
*PowerShell
*GVim (or really any vim style program)
These tools are so heavily ingrained into my daily routine and greatly increase my productivity.
A: Since I'm often working on different workstations, I've got into the habit of tagging the stuff that I install on delicious:
http://delicious.com/DavidSchmitt/stdsw
A: wc.exe (from http://unxutils.sourceforge.net/) so handy.
A: WinRAR and puTTY. That is all I need (i'm assuming internet doesn't count).
A: *
*.Net Reflector
*Powershell
*Stackoverflow.Com
A: I like to program in Python so I have created a portable Python programming environment on a thumbdrive.
*
*Portable Python 1.0
*SPE Python editor
*wxPython in Action ebook
*Python How to Program ebook
*Several Python ebooks from O'Reilly
*Various tutorials for Python tools I don't use often
A: I use Espresso (I got it with the MacHeist bundle!), and Firebug for coding. I use Photoshop if I need any images.
I manage my projects with The Hit List.
A: Development Tools
*
*Subversion
*Tortoise SVN
Useful tools/utils
*
*Virtual Cd Control Tool
*Linq Pad
*Reflector
*Subversion Commit Monitor
*BGInfo
*SourceGear Diff Merge
*Unlocker
*MWSnap
*Paint.NET
*WinRar
FireFox Add Ons
*
*Firebug
*ColorZilla
Visual Studio Add Ins
*
*GhostDoc
A: The utility toolkit or the Tools List that every developer should have described in the following link from Scott Hanselman:
Scott Hanselman's Ultimate Developer and Power Users Tool List for Windows
A: Architag XRay XML Editor - I test XSLT snippets with this nice lightweight tool.
A: Here's list of tools, utils and progs I use for my .NET software development projects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How to decrypt a password from SQL server? I have this query in sql server 2000:
select pwdencrypt('AAAA')
which outputs an encrypted string of 'AAAA':
0x0100CF465B7B12625EF019E157120D58DD46569AC7BF4118455D12625EF019E157120D58DD46569AC7BF4118455D
How can I convert (decrypt) the output from its origin (which is 'AAAA')?
A: You shouldn't really be de-encrypting passwords.
You should be encrypting the password entered into your application and comparing against the encrypted password from the database.
Edit - and if this is because the password has been forgotten, then setup a mechanism to create a new password.
A: The SQL Server password hashing algorithm:
hashBytes = 0x0100 | fourByteSalt | SHA1(utf16EncodedPassword+fourByteSalt)
For example, to hash the password "correct horse battery staple". First we generate some random salt:
fourByteSalt = 0x9A664D79;
And then hash the password (encoded in UTF-16) along with the salt:
SHA1("correct horse battery staple" + 0x9A66D79);
=SHA1(0x63006F007200720065006300740020006200610074007400650072007900200068006F00720073006500200073007400610070006C006500 0x9A66D79)
=0x6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
The value stored in the syslogins table is the concatenation of:
[header] + [salt] + [hash]
0x0100 9A664D79 6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
Which you can see in SQL Server:
SELECT
name, CAST(password AS varbinary(max)) AS PasswordHash
FROM sys.syslogins
WHERE name = 'sa'
name PasswordHash
==== ======================================================
sa 0x01009A664D796EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
*
*Version header: 0100
*Salt (four bytes): 9A664D79
*Hash: 6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3 (SHA-1 is 20 bytes; 160 bits)
Validation
You validate a password by performing the same hash:
*
*grab the salt from the saved PasswordHash: 0x9A664D79
and perform the hash again:
SHA1("correct horse battery staple" + 0x9A66D79);
which will come out to the same hash, and you know the password is correct.
What once was good, but now is weak
The hashing algorithm introduced with SQL Server 7, in 1999, was good for 1999.
*
*It is good that the password hash salted.
*It is good to append the salt to the password, rather than prepend it.
But today it is out-dated. It only runs the hash once, where it should run it a few thousand times, in order to thwart brute-force attacks.
In fact, Microsoft's Baseline Security Analyzer will, as part of it's checks, attempt to bruteforce passwords. If it guesses any, it reports the passwords as weak. And it does get some.
Brute Forcing
To help you test some passwords:
DECLARE @hash varbinary(max)
SET @hash = 0x01009A664D796EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
--Header: 0x0100
--Salt: 0x9A664D79
--Hash: 0x6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
DECLARE @password nvarchar(max)
SET @password = 'password'
SELECT
@password AS CandidatePassword,
@hash AS PasswordHash,
--Header
0x0100
+
--Salt
CONVERT(VARBINARY(4), SUBSTRING(CONVERT(NVARCHAR(MAX), @hash), 2, 2))
+
--SHA1 of Password + Salt
HASHBYTES('SHA1', @password + SUBSTRING(CONVERT(NVARCHAR(MAX), @hash), 2, 2))
SQL Server 2012 and SHA-512
Starting with SQL Server 2012, Microsoft switched to using SHA-2 512-bit:
hashBytes = 0x0200 | fourByteSalt | SHA512(utf16EncodedPassword+fourByteSalt)
Changing the version prefix to 0x0200:
SELECT
name, CAST(password AS varbinary(max)) AS PasswordHash
FROM sys.syslogins
name PasswordHash
---- --------------------------------
xkcd 0x02006A80BA229556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38
*
*Version: 0200 (SHA-2 512-bit)
*Salt: 6A80BA22
*Hash (64 bytes): 9556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38
This means we hash the UTF-16 encoded password, with the salt suffix:
*
*SHA512("correct horse battery staple"+6A80BA22)
*SHA512(63006f0072007200650063007400200068006f0072007300650020006200610074007400650072007900200073007400610070006c006500 + 6A80BA22)
*9556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38
A: I believe pwdencrypt is using a hash so you cannot really reverse the hashed string - the algorithm is designed so it's impossible.
If you are verifying the password that a user entered the usual technique is to hash it and then compare it to the hashed version in the database.
This is how you could verify a usered entered table
SELECT password_field FROM mytable WHERE password_field=pwdencrypt(userEnteredValue)
Replace userEnteredValue with (big surprise) the value that the user entered :)
A: You realise that you may be making a rod for your own back for the future. The pwdencrypt() and pwdcompare() are undocumented functions and may not behave the same in future versions of SQL Server.
Why not hash the password using a predictable algorithm such as SHA-2 or better before hitting the DB?
A: You cannot decrypt this password again but there is another method named "pwdcompare". Here is a example how to use it with SQL syntax:
USE TEMPDB
GO
declare @hash varbinary (255)
CREATE TABLE tempdb..h (id_num int, hash varbinary (255))
SET @hash = pwdencrypt('123') -- encryption
INSERT INTO tempdb..h (id_num,hash) VALUES (1,@hash)
SET @hash = pwdencrypt('123')
INSERT INTO tempdb..h (id_num,hash) VALUES (2,@hash)
SELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 2
SELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison
SELECT * FROM tempdb..h
INSERT INTO tempdb..h (id_num,hash)
VALUES (3,CONVERT(varbinary (255),
0x01002D60BA07FE612C8DE537DF3BFCFA49CD9968324481C1A8A8FE612C8DE537DF3BFCFA49CD9968324481C1A8A8))
SELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 3
SELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison
SELECT * FROM tempdb..h
DROP TABLE tempdb..h
GO
A: A quick google indicates that pwdencrypt() is not deterministic, and your statement select pwdencrypt('AAAA') returns a different value on my installation!
See also this article http://www.theregister.co.uk/2002/07/08/cracking_ms_sql_server_passwords/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: How should I express fractions like 15/16ths in HTML? I know there are HTML entities for 1/2, 1/4, and 3/4, but are there others? Like 1/3 or 1/8? Is there a good way to encode arbitrary fractions?
A: how about 15β16? (<sup>15</sup>⁄<sub>16</sub>)
A: 1/2 β ½ or ½
1/4 β ¼ or ¼
3/4 β ¾ or ¾
1/8 β ⅛ or ⅛
3/8 β ⅜ or ⅜
5/8 β ⅝ or ⅝
7/8 β ⅞ or ⅞
1/3 β ⅓
2/3 β ⅔
1/5 β ⅕
2/5 β ⅖
3/5 β ⅗
4/5 β ⅘
1/6 β ⅙
5/6 β ⅚
...but you could also encode them as decimals: 15/16 = 0.9375 ;)
A: For the existing fractions as Unicode codepoints (which are mapped to by HTML entities), search for "vulgar fraction" in the Unicode Character Names Index.
Now, for generic fractions, which work in HTML but also work in plain text, use the super- and subscript digits (see Unicode Codepoint Chart, search for "Superscripts") separated by the fraction slash character.
Your example implemented as above:
ΒΉβ΅βββ
A: Isn't just 15/16ths alright? Or even 15/16ths (15/16<sup>ths</sup>)?
A: For more complex scenarios there is also MathML. The support for this is slowly getting better. Internet Explorer seems to lag behind with this as well.
A: This would depend on your exact needs and audience.
For most purposes many methods would be appropriate.
15/16, 15 parts of 16, 93.75%, 15/16 all mean the same,
you might even use symbols like
++++++++++++++-
For some more complex scenarios you will need more complex solutions more like LaTeX than html. I believe there are also server side components that take LaTeX descriptions and create images that are browser compatible, such as described here: http://www.fauskes.net/nb/htmleqII/
A: There is also a standard called MathML. But is for XML unfortunately. However if you have more expressions you might consider switching to basic XML.
A: In HTML, this can be done with Unicode code 2044, preceded by &#x and ending with a semicolon. The whole thing is placed between the numerator and the denominator.
For instance, with this solution, 15 divided by 16 in HTML is rendered like this: 15β16
This works for combinations of integers acting as numerators and denominators.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: SMS alerting to respond to error situations faster What is the easiest way to set up an SMS alerting system so that I will receive notification if my server doesn't respond or a GET query doesn't return correct content?
A: You can completely outsource the monitoring and alerting, for example by subscribing to Pingdom. The most basic Pingdom plan will monitor up to 5 services (including using HTTP GETs with optional content pattern matching) and send an SMS after a configurable amount of downtime.
If you want to roll your own solution, the first thing to get right is the monitoring software. Many, many third party solutions exist for this, from the free to the outrageously expensive. Of course, rolling your own "try a GET and do something if it doesn't work" script is always an option, but as with all software, feature creep may mean that you're just re-implementing existing solutions soon...
For the SMS notification, using an e-mail-to-SMS gateway might work for you, if you're in a territory well-served by such services. Most US providers, for example, provide free gateways, whereas in Europe they tend to be run by third parties and pay-only. As already suggested, Google is your friend here. Also, your monitoring tool may support sending notifications directly using a cellphone/GSM modem attached to the monitoring server.
A: Often I've found that what you need is a SMS modem attached directly to your monitoring server. What if the problem is the network connection?
A: You can get a service like http://www.serviceuptime.com/ and the send an email to your-number@a-domain-your-provider-gives They usually have the exact domains for the providers on their respective websites but you could just try @t-mobile.com if your provider is t-mobile for example.
If you want to write your own tool should be pretty straightforward - send GET request if you dont get the expected response send email. You should run it from 2 different locations from 2 different ISPs tho because if there are routing problems and the request doesnt go through you'll get smsed
A: What you want is an SMS gateway. There are surely some service providers local to you. Unfortunately, they are a bit hard to find. Try asking Google...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Which database implementations allow sandboxing users in separate databases? Can anyone tell me if there are RDBMSs that allow me to create a separate database for every user so that there is full separation of users' data?
Are there any?
I know I can add UID to every table but this solution has its own problems (for example per user database schema changes are impossible).
A: Doesnt MySQL, PostgreSQL, Oracle and so on and so on allow you to do that?. There's the grant statements to control ACLs
A: I would imagine most (all?) databases allow you to create a user which you could then grant database level access to? SQL server certainly does.
A: Another simple solution if you don't need the databases to be massive or scalable, say for teaching SQL to students or having many testers work against their own database to isolate problems is SQLite, that way the whole database is a single file (per user), and each user cannot possibly screw up or interfere with other users.
They can even mail you the databases, or install them anywhere, say at home and at work with no internet required.
A: MS SQLServer2005 is one which can be used for multiple users.An instance can be created
if you have any, run the previlegs and use one user per instance
A: Oracle lets you create a separate schema (set of tables, indexes, functions, etc) for individual users. This is good if they should have separate different tables. Creating a new user could be a very expensive operation as you would be making new tables. Updating is a nightmare as well, as you need to update the model for each user.
If you want everyone to have the same set of tables, but only able to view their own records then you could use Fine Grain Access Control or Virtual Private Database features to do this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you free a wrapped C++ object when associated Javascript object is garbage collected in V8? V8's documentation explains how to create a Javascript object that wraps a C++ object. The Javascript object holds on to a pointer to a C++ object instance. My question is, let's say you create the C++ object on the heap, how can you get a notification when the Javascript object is collected by the gc, so you can free the heap allocated C++ object?
A: The trick is to create a Persistent handle (second bullet point from the linked-to API reference: "Persistent handles are not held on a stack and are deleted only when you specifically remove them. ... Use a persistent handle when you need to keep a reference to an object for more than one function call, or when handle lifetimes do not correspond to C++ scopes."), and call MakeWeak() on it, passing a callback function that will do the necessary cleanup ("A persistent handle can be made weak, using Persistent::MakeWeak, to trigger a callback from the garbage collector when the only references to an object are from weak persistent handles." -- that is, when all "regular" handles have gone out of scope and when the garbage collector is about to delete the object).
The Persistent::MakeWeak method signature is:
void MakeWeak(void* parameters, WeakReferenceCallback callback);
Where WeakReferenceCallback is defined as a pointer-to-function taking two parameters:
typedef void (*WeakReferenceCallback)(Persistent<Object> object,
void* parameter);
These are found in the v8.h header file distributed with V8 as the public API.
You would want the function you pass to MakeWeak to clean up the Persistent<Object> object parameter that will get passed to it when it's called as a callback. The void* parameter parameter can be ignored (or the void* parameter can point to a C++ structure that holds the objects that need cleaning up):
void CleanupV8Point(Persistent<Object> object, void*)
{
// do whatever cleanup on object that you're looking for
object.destroyCppObjects();
}
Parameter<ObjectTemplate> my_obj(ObjectTemplate::New());
// when the Javascript part of my_obj is about to be collected
// we'll have V8 call CleanupV8Point(my_obj)
my_obj.MakeWeak(NULL, &CleanupV8Point);
A: In general, if a garbage-collected language can hold references to resources outside of the language engine (files, sockets, or in your case C++ objects), you should provide a 'close' method to release that resource ASAP, no point waiting until the GC thinks it's worthwhile to destroy your object.
it gets worse if your C++ object is memory-hungry and the garbage-collected object is just a reference: you might allocate thousands of objects, and the GC only sees a few KB's of tiny objects, not enough to trigger collection; while the C++ side is struggling with tens of megabytes of stale objects.
A: Do all your work in some closed scope (of object or function).
Then you can safely remove the C++ object when you went out of scope. GC doesn't check pointers for existence of pointed objects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: How do you deal with large dependencies in Boost? Boost is a very large library with many inter-dependencies -- which also takes a long time to compile (which for me slows down our CruiseControl response time).
The only parts of boost I use are boost::regex and boost::format.
Is there an easy way to extract only the parts of boost necessary for a particular boost sub-library to make compilations faster?
EDIT: To answer the question about why we're re-building boost...
*
*Parsing the boost header files still takes a long time. I suspect if we could extract only what we need, parsing would happen faster too.
*Our CruiseControl setup builds everything from scratch. This also makes it easier if we update the version of boost we're using. But I will investigate to see if we can change our build process to see if our build machine can build boost when changes occur and commit those changes to SVN. (My company has a policy that everything that goes out the door must be built on the "build machine".)
A: First, you can use the bcp tool (can be found in the tools subfolder) to extract the headers and files you are using. This won't help with compile times, though. Second, you don't have to rebuild Boost every time. Just pre-build the lib files once and at every version change, and copy the "stage" folder at build time.
A: Unless you are patching the boost libraries themselves, there is no reason to recompile it every time you do a build.
A: We're using Boost, but we only include object files for those types that we actually use. I.e., we build our own static library with a bunch of home-grown utilities and include those parts of Boost that we find useful. Our CMakeLists.txt looks something like this (you should be able to load this in CMake, if you adjust SOURCES accordingly.)
project( MyBoost )
set(SOURCES
boost/regex/src/c_regex_traits.cpp
boost/regex/src/cpp_regex_traits.cpp
boost/regex/src/cregex.cpp
boost/regex/src/fileiter.cpp
boost/regex/src/icu.cpp
boost/regex/src/instances.cpp
boost/regex/src/posix_api.cpp
boost/regex/src/regex.cpp
boost/regex/src/regex_debug.cpp
boost/regex/src/regex_raw_buffer.cpp
boost/regex/src/regex_traits_defaults.cpp
boost/regex/src/static_mutex.cpp
boost/regex/src/usinstances.cpp
boost/regex/src/w32_regex_traits.cpp
boost/regex/src/wc_regex_traits.cpp
boost/regex/src/wide_posix_api.cpp
boost/regex/src/winstances.cpp
)
add_library( MyBoost STATIC ${SOURCES})
A: Precompiled headers are the word of the day! Include the boost headers you need in your precompiled header - tada!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Has anyone built web-apps that can run totally off-line? I'm building an app that authors would (hopefully) use to help them, uh.. author things.
Think of it like a wiki but just for one person, but cooler. I wish to make it as accessible as possible to my (potential) adoring masses, and so I'm thinking about making it a web-app.
It certainly doesn't have to be, there is no integration with other sites, no social features. It involve typing information into forms however, so for rapid construction the web would probably be the best.
However, I don't really want to host it myself. I couldn't afford it for one, but it's mostly that people who use this may not want their data stored elsewhere. This is private information about what they are writing and I wouldn't expect them to trust me with it, and so I'm thinking about making it a thick-client app.
And therein lies the problem, how to make a application that focuses mainly on form data entry available easily to potential users (yay web apps) but also offline so they know they are in full control of their data (yay thick-client apps).
I see the following solutions:
*
*Build it as a thick-client Java app and run a cutdown version on the net as an applet that people can play with before downloading the full thing.
*Build it as a Flex app for online and an Air app for offline (same source different build scripts basically).
*Build it as a standard web-app (HTML, JS etc) but have a downloadable version that somehow runs the site totally on their computer. It wouldn't touch the net at all.
Ignoring 1 and 2 (I'm looking into them separately), I think 3 would involve:
*
*Packaging up an install that contains a tiny webserver that has my code on it, ready to run.
*Remapping the DB from something like mySQL to something like SQLite.
*Creating some kind of convience app that ran the server and opened your browser to the right location, possibly using something like Prism to hide the whole broswer thing.
So, have you ever done something like this before?
If so, what problems did you encounter?
Finally, is there another solution I haven't thought of?'
(also, Joyent Slingshot was a suggestion on another question, but it's RoR (which I have no experience in) and I'm 99% sure it doesn't run under linux, so It's not right for me.)
A: I think you should look at tiddlywiki for inspiration.
It's a wiki written in JavaScript entirely self-contained in a single html file. You load it into your browser as a file:/// URL, so there is no need for a server.
I use it as a personal wiki to keep notes on various subjects.
A: Google Gears is used to offer a few of the google apps offline (Google Reader, Gmail, Docs and more).
What is Google Gears?
Gears is an open source browser extension that lets developers create
web applications that can run offline.
Gears provides three key features:
*
*A local server, to cache and serve application resources (HTML,
JavaScript, images, etc.) without
needing to contact a server
*A database, to store and access data from within the browser
*A worker thread pool, to make web applications more
responsive
by performing expensive operations in
the background
Gears is currently an early-access developers' release. It is not yet intended for use by real users in production applications at this time.
If you're a developer interested in using Gears with your application, visit the Gears Developer Page.
If you wish to install Gears on your computer, visit the Gears Home Page. Please note, however, that Gears is not yet intended for general use.
But as you read it's still in early stages.
A: There is an additional option, and that is to use the new HTML5 offline application features, namely the Application Cache, Client-Side Databases, and Local Storage APIs.
Currently I believe that Safari is the only shipping browser to support any of these, and i believe it only supports the client side databases and local storage parts. The webkit nightlies support all of these features, the firefox nightlies support many of them (maybe all now?)
[Edit (olliej): Correction, Firefox 3 supports the Application cache, but alas not the client side DB]
A: We are using something similar to your third option to test our websites locally. Works just fine.
Our packaged webserver is not small enough to accomplish what you need, but then again we've not been trying to keep it small either. If you can package your webserver code into a small enough package I don't see why this approach would'nt work.
A: I think AIR is the way to go..
A: Have you checked into google gears?
A: Some pointers for solution 3:
*
*for the GUI part, ExtJS seems really nice.
*for the storage part, there is a nice javascript library that abstracts different storage backends: PersistJS.
Supported backends for PersistJS:
*
*flash: Flash 8 persistent storage.
*gears: Google Gears-based persistent storage.
*localstorage: HTML5 draft storage.
*whatwg_db: HTML5 draft database storage.
*globalstorage: HTML5 draft storage (old spec).
*ie: Internet Explorer userdata behaviors.
*cookie: Cookie-based persistent storage.
A: Also, I think the moin moin wiki software has a desktop version that includes its own webserver. This stuff is easy in python, since batteries are included.
You might want to check out how they do it?
A: You could make a dedicated client using Webkit or Firefox's backbone. Some games use that solution for UI for example.
Or you could make a little webserver (I have a little webserver in Lua that I use for similar purposes, just a few megas with libaries and all). However if you take this route the biggest issue to consider is you don't want your webserver to depend on environmental variables, you want it to be totally autonomous. You should try to isolate all variables t o a config file and be done with it (bundle style)
Or you could use a Java client application to display the webpage
Or GoogleGears, but that's the same (almost) as Flex+Air. so choose Flex+Air if that's what you are familiar with
A: You didn't specify a language but I looked at Karigell a few years ago. It's Python web framework, similar to Django or TurboGears, but it doesn't have the overhead of those frameworks.
From my messing around with it, it seems like it would work for your purposes. It has a built-in web server (though you can use pretty much any server you want) and you can use any database that Python supports.
Plus, Python works well with Linux. :)
A: If you made the app a regular web app heavily reliant on client-side technologies (using DHTML and the likes of Google Gears to store data offline as already suggested) so once opened, there wasn't much interaction with the server, you could probably host the thing on a basic shared hosting account which wouldn't cost that much. That might be your easiest starting point as you wouldn't have to worry about all the issues with desktop apps such as compatibility with different operating systems, packaging up an install etc, yet you wouldn't need massive server resources behind it either.
A: You can use HTML, JS and whatever else in Adobe AIR and you'll have plenty of options of saving data locally, too.
A: in java world you could use jetty for a server, implement web app using your favorite framework and use hsqldb as a database - it lives entirely in your container (jetty). you can deploy preview app on the web and package downloadable offline version.
A: There's a portable distribution of Apache/MySQL/PHP (to place on USB keys):
http://portableapps.com/apps/development/xampp
This should be easily adapted to your needs.
A: You could also consider using XULRunner or Prism
They're the opensource technology that FireFox, Thunderbird and Joost are built on, and allows you to develop apps in XML and javascript essentially against the same rich api that FireFox itself has. And of course this is cross platform too, so it'd work on Mac/Linux/Windows...
Check here for more info:
https://developer.mozilla.org/en/XULRunner
A: I was thinking of doing something like this myself. My plan was to write app using django and write script that starts django's testing server and opens default browser on specified port. My plan was to use SQLite...
Also, it would be nice to pack it into one package, so users without django installed can run app without any dependecies...
A: My suggestion, as you pointed above, is to use a Wiki system to solve your problem. Now the question could be: Wich one?
You can use Trac, it is very simple and you can customize its GUI. But, if you prefer something more advanced please use MoinMoin. I used it for years, and IMO it is a very good and strong wiki system.
Depiste wich wiki you will choose, forget to write your web-app from scratch. According to yor question the best approach is to pick something that works and customize/modify it to fit your needs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Nhibernate 2.0.1 with mono I've build my WinForm app on windows machine and the app is working
ok. When I user nhibernate 1.2.1 the app also worked on linux machine
using mono, but now when i upgraded app to nhibernate 2.0.1 it works
only in windows.
I've get error:
NHibernate.InvalidProxyTypeException: The following types may not be
used as proxies:
xxxx.Data.Dao.Credit : method obj_address should be virtual
......
Can anyone help me with this problem?
A: You can try and disable the NHibernate Config proxy validator. it seems to not work with mono.
You can do this by adding:
<property name="use_proxy_validator">false</property> in your app/web.config nhibernate section.
For an example config with this property set, see here:
http://www.mail-archive.com/nhusers@googlegroups.com/msg02109.html
or modify this:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="hibernate-configuration"
type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<!--
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=YOUR_DB_SERVER;Database=Northwind;User ID=YOUR_USERNAME;Password=YOUR_PASSWORD;</property>
<property name="connection.isolation">ReadCommitted</property>
<property name="default_schema">Northwind.dbo</property>
-->
<!--
<property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SQLiteDriver</property>
<property name="connection.connection_string">Data Source=nhibernate.db;Version=3</property>
<property name="query.substitutions">true=1;false=0</property>
-->
<!-- mysql
<property name="dialect">NHibernate.Dialect.MySQLDialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
<property name="connection.connection_string">Database=test</property>
-->
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.NpgsqlDriver</property>
<property name="connection.connection_string">Server=localhost;database=test;User id=jrwren;password=yourpasswordhere.</property>
<property name="dialect">NHibernate.Dialect.PostgreSQLDialect</property>
<property name="use_proxy_validator">false</property>
<!-- HBM Mapping Files -->
<mapping assembly="Test.exe" />
</session-factory>
</hibernate-configuration>
</configuration>
A: This might be of interest:
http://softwaredevscott.spaces.live.com/blog/cns!1A9E939F7373F3B7!251.entry
A: I'm also on mono trying to use NHibernate. Most forums seem to say setting the string to virtual will fix the problem, but this hasn't worked for me. What is curious is that my error is almost identical -
"" method obj_address should be virtual
This makes me think the proxy "address" is reserved for something else. Try changing the name of this column?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: What is the best installation tool for java? Depends on your experience could you recommend something?
I've use izpack, and it's very nice tool, is there any other, better tool?
A: for Windows there's AdvancedInstaller, it was very easy to use and created standard .msi files. It has some extra features for Java installs.
A: I am happy with install4j. (even run it from my ant scripts)
A: I would like to suggest our cross platform installation tool, BitRock InstallBuilder. Although it is not Java-based, it is commonly used to package Java applications. It can be easily integrated with Ant and you can build Windows installers from Unix/Linux/Mac and the other way around. Because the generated installers are native, they do not require a self-extraction step or bundling a JRE, which means smaller installers and saves you some headaches. I also would like to mention we have free licenses for open source projects
A: In MS Windows NSIS is great and it's free & OSS
Ref: Java Launcher with automatic JRE installation
A: We are using IZPack for quit a while and are very satisfied. You can build installers for nearly all platforms and it integrates well with your build tools like maven.
A: sun has come out with a new version : https://openinstaller.dev.java.net/ -- this is open source and sun will be using this to launch most of their server side products/projects.
A: Since no one has mentioned it yet, I'll go ahead and plug InstallAnywhere. We use it at work for all our products and I can't say we've really had any problems with it (that weren't caused by mistakes in our own scripts at least!). It's a cross-platform GUI installer which is a nice feature if you expect to have different desktop environments in play, and it also supports console installers, silent installs, etc.
I googled around a bit and here's a review of InstallAnywhere you might find helpful. It's from a first time user, rather than a publication or thinly veiled press release, which probably makes it less biased and a better indicator of what your experience using it might be like.
A: I'd suggest InstallJammer. It's not written in Java, but it's cross-platform and provides capabilities to handle Java-based applications during installation. Being that it's not based on Java, it doesn't actually require any version of the JRE to be installed on the target system, which is kind of nice, but you can still use actions within your installer to locate versions of the JRE for your application. The installers are small and completely self-contained.
It's also free and open source, if that matters to you. It does to some. :)
A: I know you said installer, but I think it is worth mentioning JSmooth. It's a launcher that generates an exe file for Windows. The reason it is worth mentioning is because it performs the job of location a JVM and can also download and install it for the user. This is often left up to the installer to do. Doing it dynamically like this is nicer though since Java gets updated quite often and JSmooth will always use the latest version JVM it can find (within your parameters).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Example of using Service Exists MSBuild task in Microsoft.Sdc.Tasks? I'm trying to use the Microsoft.Sdc.Tasks.ServiceProcess.Exists to check whether or not a service exists. There is no example of using it in the documentation though. Anyone have one?
A: This is how we check if service exists, stop it if so, do something, and start service again (if there was one and it was started).
Helper target:
<target name="service_exists">
<script language="C#">
<references>
<include name="System.ServiceProcess.dll" />
</references>
<code><![CDATA[
public static void ScriptMain(Project project) {
String serviceName = project.Properties["service.name"];
project.Properties["service.exists"] = "false";
project.Properties["service.running"] = "false";
System.ServiceProcess.ServiceController[] scServices;
scServices = System.ServiceProcess.ServiceController.GetServices();
foreach (System.ServiceProcess.ServiceController scTemp in scServices)
{
if (String.Compare(scTemp.ServiceName.ToUpper(), serviceName.ToUpper()) == 0)
{
project.Properties["service.exists"] = "true";
project.Log(Level.Info, "Service " + serviceName + " exists");
if (scTemp.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Running))
project.Properties["service.running"] = "true";
project.Log(Level.Info, "Service " + serviceName + " is running: " + project.Properties["service.running"]);
return;
}
}
project.Log(Level.Info, "Service " + serviceName + " doesn't exist");
}
]]></code>
</script>
</target>
Usage:
<property name="service.name" value="Selection.Service" />
<call target="service_exists" />
<servicecontroller action="Stop" service="${service.name}" machine="${host}" timeout="60000" if="${service.exists}"/>
<!-- Do something -->
<servicecontroller action="Start" service="${service.name}" machine="${host}" timeout="60000" if="${bool::parse(service.exists) and bool::parse(service.running) == true}"/>
Hope I did not miss anything - our build admin keeps everything in one msbuild file which is now over 3600 lines :|
A: I've not actually used this in production myself, and I'm not sure which version you have (I have a copy of Release 2.1.3155.0) and according to the accompanying .chm help file the Task has the following properties:
*
*DoesExist Returns TRUE if the service specified exists
*IsDisabled Returns TRUE if the service is disabled
*ServiceName The short name that identifies the service to the system.
The ServiceName needs to be set to "The short name that identifies the service to the system, e.g. 'W3SVC'".
You might want to give it a try with a well known service (e.g. mssqlserver) and check the result of the other two properties (DoesExist/IsDisabled).
Update: Here's a sample (works):
Import the tasks, then call (e.g.)
< Microsoft.Sdc.Tasks.ServiceProcess.Exists
ServiceName="Server">
< Output TaskParameter="DoesExist" PropertyName="Exists" />
< /Microsoft.Sdc.Tasks.ServiceProcess.Exists >
< Message Text="Service exists? $(Exists)" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to check if PHP array is associative or sequential? PHP treats all arrays as associative, so there aren't any built in functions. Can anyone recommend a fairly efficient way to check if an array "is a list" (contains only numeric keys starting from 0)?
Basically, I want to be able to differentiate between this:
$sequentialArray = [
'apple', 'orange', 'tomato', 'carrot'
];
and this:
$assocArray = [
'fruit1' => 'apple',
'fruit2' => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot'
];
A: One way to approach this is to piggyback on json_encode, which already has its own internal method of differentiating between an associative array and an indexed array in order to output the correct JSON.
You can do this by checking to see if the first character returned after encoding is a { (associative array) or a [ (indexed array).
// Too short :)
function is_assoc($arr) {
ksort($arr);
return json_encode($arr)[0] === '{';
}
A: Many commenters in this question don't understand how arrays work in PHP. From the array documentation:
A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.
In other words, there is no such thing as an array key of "8" because it will always be (silently) converted to the integer 8. So trying to differentiate between integers and numeric strings is unnecessary.
If you want the most efficient way to check an array for non-integer keys without making a copy of part of the array (like array_keys() does) or all of it (like foreach does):
function keyedNext( &$arr, &$k){
$k = key($arr);
return next($arr);
}
for ($k = key(reset($my_array)); is_int($k); keyedNext($my_array,$k))
$onlyIntKeys = is_null($k);
This works because key() returns NULL when the current array position is invalid and NULL can never be a valid key (if you try to use NULL as an array key it gets silently converted to "").
A: function array_is_assoc(array $a) {
$i = 0;
foreach ($a as $k => $v) {
if ($k !== $i++) {
return true;
}
}
return false;
}
Fast, concise, and memory efficient. No expensive comparisons, function calls or array copying.
A: You have asked two questions that are not quite equivalent:
*
*Firstly, how to determine whether an array has only numeric keys
*Secondly, how to determine whether an array has sequential numeric keys, starting from 0
Consider which of these behaviours you actually need. (It may be that either will do for your purposes.)
The first question (simply checking that all keys are numeric) is answered well by Captain kurO.
For the second question (checking whether the array is zero-indexed and sequential), you can use the following function:
function isAssoc(array $arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
var_dump(isAssoc(['a', 'b', 'c'])); // false
var_dump(isAssoc(["0" => 'a', "1" => 'b', "2" => 'c'])); // false
var_dump(isAssoc(["1" => 'a', "0" => 'b', "2" => 'c'])); // true
var_dump(isAssoc(["a" => 'a', "b" => 'b', "c" => 'c'])); // true
A: This function can handle:
*
*array with holes in index (e.g. 1,2,4,5,8,10)
*array with "0x" keys: e.g. key '08' is associative while key '8' is sequential.
the idea is simple: if one of the keys is NOT an integer, it is associative array, otherwise it's sequential.
function is_asso($a){
foreach(array_keys($a) as $key) {if (!is_int($key)) return TRUE;}
return FALSE;
}
A: There are many answers already, but here is the method that Laravel relies on within its Arr class:
/**
* Determines if an array is associative.
*
* An array is "associative" if it doesn't have sequential numerical keys beginning with zero.
*
* @param array $array
* @return bool
*/
public static function isAssoc(array $array)
{
$keys = array_keys($array);
return array_keys($keys) !== $keys;
}
Source: https://github.com/laravel/framework/blob/5.4/src/Illuminate/Support/Arr.php
A: I noticed two popular approaches for this question: one using array_values() and other using key(). To find out which is faster, I wrote a small program:
$arrays = Array(
'Array #1' => Array(1, 2, 3, 54, 23, 212, 123, 1, 1),
'Array #2' => Array("Stack", 1.5, 20, Array(3.4)),
'Array #3' => Array(1 => 4, 2 => 2),
'Array #4' => Array(3.0, "2", 3000, "Stack", 5 => "4"),
'Array #5' => Array("3" => 4, "2" => 2),
'Array #6' => Array("0" => "One", 1.0 => "Two", 2 => "Three"),
'Array #7' => Array(3 => "asdf", 4 => "asdf"),
'Array #8' => Array("apple" => 1, "orange" => 2),
);
function is_indexed_array_1(Array &$arr) {
return $arr === array_values($arr);
}
function is_indexed_array_2(Array &$arr) {
for (reset($arr), $i = 0; key($arr) === $i++; next($arr))
;
return is_null(key($arr));
}
// Method #1
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
foreach ($arrays as $array) {
$dummy = is_indexed_array_1($array);
}
}
$end = microtime(true);
echo "Time taken with method #1 = ".round(($end-$start)*1000.0,3)."ms\n";
// Method #2
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
foreach ($arrays as $array) {
$dummy = is_indexed_array_2($array);
}
}
$end = microtime(true);
echo "Time taken with method #1 = ".round(($end-$start)*1000.0,3)."ms\n";
Output for the program on PHP 5.2 on CentOS is as follows:
Time taken with method #1 = 10.745ms
Time taken with method #2 = 18.239ms
Output on PHP 5.3 yielded similar results. Obviously using array_values() is much faster.
A: Most answers have sub-optimal time/space complexity or are changing semantics. So, here is another answer with the fastest and most functionally correct solution:
function is_sequential_array(Array &$a) {
$n = count($a);
for($i=0; $i<$n; $i++) {
if(!array_key_exists($i, $a)) {
return false;
}
}
return true;
}
This answer has following advantages over other answers:
*
*Space complexity of O(1) (many answers here use O(n) space!)
*Does not apply equality on keys (which is an unwanted and expensive operation)
*Treats input array as immutable (many answers have implicitly created a copy by applying mutating functions)
*Uses function array_key_exists instead of isset (remember, isset additionally checks for 'is not null', thereby changing semantics)
*Worst-case time complexity is O(n) (many answers here have best-case time complexity of O(n))
A: To merely check whether the array has non-integer keys (not whether the array is sequentially-indexed or zero-indexed):
function has_string_keys(array $array) {
return count(array_filter(array_keys($array), 'is_string')) > 0;
}
If there is at least one string key, $array will be regarded as an associative array.
A: As stated by the OP:
PHP treats all arrays as associative
it is not quite sensible (IMHO) to write a function that checks if an array is associative. So first thing first: what is a key in a PHP array?:
The key can either be an integer or a string.
That means there are 3 possible cases:
*
*Case 1. all keys are numeric / integers.
*Case 2. all keys are strings.
*Case 3. some keys are strings, some keys are numeric / integers.
We can check each case with the following functions.
Case 1: all keys are numeric / integers.
Note: This function returns true for empty arrays too.
//! Check whether the input is an array whose keys are all integers.
/*!
\param[in] $InputArray (array) Input array.
\return (bool) \b true iff the input is an array whose keys are all integers.
*/
function IsArrayAllKeyInt($InputArray)
{
if(!is_array($InputArray))
{
return false;
}
if(count($InputArray) <= 0)
{
return true;
}
return array_unique(array_map("is_int", array_keys($InputArray))) === array(true);
}
Case 2: all keys are strings.
Note: This function returns true for empty arrays too.
//! Check whether the input is an array whose keys are all strings.
/*!
\param[in] $InputArray (array) Input array.
\return (bool) \b true iff the input is an array whose keys are all strings.
*/
function IsArrayAllKeyString($InputArray)
{
if(!is_array($InputArray))
{
return false;
}
if(count($InputArray) <= 0)
{
return true;
}
return array_unique(array_map("is_string", array_keys($InputArray))) === array(true);
}
Case 3. some keys are strings, some keys are numeric / integers.
Note: This function returns true for empty arrays too.
//! Check whether the input is an array with at least one key being an integer and at least one key being a string.
/*!
\param[in] $InputArray (array) Input array.
\return (bool) \b true iff the input is an array with at least one key being an integer and at least one key being a string.
*/
function IsArraySomeKeyIntAndSomeKeyString($InputArray)
{
if(!is_array($InputArray))
{
return false;
}
if(count($InputArray) <= 0)
{
return true;
}
return count(array_unique(array_map("is_string", array_keys($InputArray)))) >= 2;
}
It follows that:
*
*If the value is not an array, all 3 functions return false.
*If the value is an empty array, all 3 functions return true
(which is by definition, as in "the empty set is a subset of any set A because all its elements belong to A").
*If the value is a non-empty array, exactly 1 function returns true.
Now, for an array to be a "genuine" array that we are all accustomed to, meaning:
*
*Its keys are all numeric / integers.
*Its keys are sequential (i.e. increasing by step 1).
*Its keys start from zero.
We can check with the following function.
Case 3a. keys are numeric / integers, sequential, and zero-based.
Note: This function returns true for empty arrays too.
//! Check whether the input is an array whose keys are numeric, sequential, and zero-based.
/*!
\param[in] $InputArray (array) Input array.
\return (bool) \b true iff the input is an array whose keys are numeric, sequential, and zero-based.
*/
function IsArrayKeyNumericSequentialZeroBased($InputArray)
{
if(!is_array($InputArray))
{
return false;
}
if(count($InputArray) <= 0)
{
return true;
}
return array_keys($InputArray) === range(0, count($InputArray) - 1);
}
Caveats / Pitfalls (or, even more peculiar facts about array keys in PHP)
Integer keys
The keys for these arrays are integers:
array(0 => "b");
array(13 => "b");
array(-13 => "b"); // Negative integers are also integers.
array(0x1A => "b"); // Hexadecimal notation.
String keys
The keys for these arrays are strings:
array("fish and chips" => "b");
array("" => "b"); // An empty string is also a string.
array("stackoverflow_email@example.com" => "b"); // Strings may contain non-alphanumeric characters.
array("stack\t\"over\"\r\nflow's cool" => "b"); // Strings may contain special characters.
array('$tΞ±β¬kβΓΈvβrflΓΆwβ' => "b"); // Strings may contain all kinds of symbols.
array("functΡon" => "b"); // You think this looks fine? Think again! (see https://stackoverflow.com/q/9246051/1402846)
array("γΎλ§θ½θ½¬ΠΕ" => "b"); // How about Japanese/Korean/Chinese/Russian/Polish?
array("fi\x0sh" => "b"); // Strings may contain null characters.
array(file_get_contents("https://www.google.com/images/nav_logo114.png") => "b"); // Strings may even be binary!
Integer keys that look like strings
If you think the key in array("13" => "b") is a string, you are wrong. From the doc here:
Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
For example, the key for these arrays are integers:
array("13" => "b");
array("-13" => "b"); // Negative, ok.
But the key for these arrays are strings:
array("13." => "b");
array("+13" => "b"); // Positive, not ok.
array("-013" => "b");
array("0x1A" => "b"); // Not converted to integers even though it's a valid hexadecimal number.
array("013" => "b"); // Not converted to integers even though it's a valid octal number.
array("18446744073709551616" => "b"); // Not converted to integers as it can't fit into a 64-bit integer.
What's more, according to the doc,
The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except for Windows, which is always 32 bit. PHP does not support unsigned integers.
So the key for this array may or may not be an integer - it depends on your platform.
array("60000000000" => "b"); // Array key could be integer or string, it can fit into a 64-bit (but not 32-bit) integer.
Even worse, PHP tends to be buggy if the integer is near the 231 = 2,147,483,648 boundary (see bug 51430, bug 52899). For example, on my local environment (PHP 5.3.8 on XAMPP 1.7.7 on Windows 7), var_dump(array("2147483647" => "b")) gives
array(1) {
[2147483647]=>
string(1) "b"
}
but on this live demo on codepad (PHP 5.2.5), the same expression gives
array(1) {
["2147483647"]=>
string(1) "b"
}
So the key is an integer in one environment but a string in another, even though 2147483647 is a valid signed 32-bit integer.
A: PHP 8.1 adds a built-in function to determine whether an array is a list with those semantics, or not. the function is array_is_list:
$list = ["a", "b", "c"];
array_is_list($list); // true
$notAList = [1 => "a", 2 => "b", 3 => "c"];
array_is_list($notAList); // false
$alsoNotAList = ["a" => "a", "b" => "b", "c" => "c"];
array_is_list($alsoNotAList); // false
reference
A: After some local benchmarking, debugging, compiler probing, profiling, and abusing 3v4l.org to benchmark across more versions (yes, I got a warning to stop) and
comparing against every variation I could find...
I give you an organically derived best-average-worst-case scenario associative array test function that is at worst roughly as good as or better than all other average-case scenarios.
/**
* Tests if an array is an associative array.
*
* @param array $array An array to test.
* @return boolean True if the array is associative, otherwise false.
*/
function is_assoc(array &$arr) {
// don't try to check non-arrays or empty arrays
if (FALSE === is_array($arr) || 0 === ($l = count($arr))) {
return false;
}
// shortcut by guessing at the beginning
reset($arr);
if (key($arr) !== 0) {
return true;
}
// shortcut by guessing at the end
end($arr);
if (key($arr) !== $l-1) {
return true;
}
// rely on php to optimize test by reference or fast compare
return array_values($arr) !== $arr;
}
From https://3v4l.org/rkieX:
<?php
// array_values
function method_1(Array &$arr) {
return $arr === array_values($arr);
}
// method_2 was DQ; did not actually work
// array_keys
function method_3(Array &$arr) {
return array_keys($arr) === range(0, count($arr) - 1);
}
// foreach
function method_4(Array &$arr) {
$idx = 0;
foreach( $arr as $key => $val ){
if( $key !== $idx )
return FALSE;
++$idx;
}
return TRUE;
}
// guessing
function method_5(Array &$arr) {
global $METHOD_5_KEY;
$i = 0;
$l = count($arr)-1;
end($arr);
if ( key($arr) !== $l )
return FALSE;
reset($arr);
do {
if ( $i !== key($arr) )
return FALSE;
++$i;
next($arr);
} while ($i < $l);
return TRUE;
}
// naieve
function method_6(Array &$arr) {
$i = 0;
$l = count($arr);
do {
if ( NULL === @$arr[$i] )
return FALSE;
++$i;
} while ($i < $l);
return TRUE;
}
// deep reference reliance
function method_7(Array &$arr) {
return array_keys(array_values($arr)) === array_keys($arr);
}
// organic (guessing + array_values)
function method_8(Array &$arr) {
reset($arr);
if ( key($arr) !== 0 )
return FALSE;
end($arr);
if ( key($arr) !== count($arr)-1 )
return FALSE;
return array_values($arr) === $arr;
}
function benchmark(Array &$methods, Array &$target, $expected){
foreach($methods as $method){
$start = microtime(true);
for ($i = 0; $i < 2000; ++$i) {
//$dummy = call_user_func($method, $target);
if ( $method($target) !== $expected ) {
echo "Method $method is disqualified for returning an incorrect result.\n";
unset($methods[array_search($method,$methods,true)]);
$i = 0;
break;
}
}
if ( $i != 0 ) {
$end = microtime(true);
echo "Time taken with $method = ".round(($end-$start)*1000.0,3)."ms\n";
}
}
}
$true_targets = [
'Giant array' => range(0, 500),
'Tiny array' => range(0, 20),
];
$g = range(0,10);
unset($g[0]);
$false_targets = [
'Large array 1' => range(0, 100) + ['a'=>'a'] + range(101, 200),
'Large array 2' => ['a'=>'a'] + range(0, 200),
'Tiny array' => range(0, 10) + ['a'=>'a'] + range(11, 20),
'Gotcha array' => $g,
];
$methods = [
'method_1',
'method_3',
'method_4',
'method_5',
'method_6',
'method_7',
'method_8'
];
foreach($false_targets as $targetName => $target){
echo "==== Benchmark using $targetName expecing FALSE ====\n";
benchmark($methods, $target, false);
echo "\n";
}
foreach($true_targets as $targetName => $target){
echo "==== Benchmark using $targetName expecting TRUE ====\n";
benchmark($methods, $target, true);
echo "\n";
}
A: Speed-wise:
function isAssoc($array)
{
return ($array !== array_values($array));
}
Memory-wise:
function isAssoc($array)
{
$array = array_keys($array); return ($array !== array_keys($array));
}
A: I know it's a bit pointless adding an answer to this huge queue, but here's a readable O(n) solution that doesn't require duplicating any values:
function isNumericArray($array) {
$count = count($array);
for ($i = 0; $i < $count; $i++) {
if (!isset($array[$i])) {
return FALSE;
}
}
return TRUE;
}
Rather than check the keys to see if they are all numeric, you iterate over the keys that would be there for a numeric array and make sure they exist.
A: By using xarray PHP extension
You can do this very fast (about 30+ times faster in PHP 5.6):
if (array_is_indexed($array)) { }
Or:
if (array_is_assoc($array)) { }
A: answers are already given but there's too much disinformation about performance.
I wrote this little benchmark script that shows that the foreach method is the fastest.
Disclaimer: following methods were copy-pasted from the other answers
<?php
function method_1(Array &$arr) {
return $arr === array_values($arr);
}
function method_2(Array &$arr) {
for (reset($arr), $i = 0; key($arr) !== $i++; next($arr));
return is_null(key($arr));
}
function method_3(Array &$arr) {
return array_keys($arr) === range(0, count($arr) - 1);
}
function method_4(Array &$arr) {
$idx = 0;
foreach( $arr as $key => $val ){
if( $key !== $idx )
return FALSE;
$idx++;
}
return TRUE;
}
function benchmark(Array $methods, Array &$target){
foreach($methods as $method){
$start = microtime(true);
for ($i = 0; $i < 1000; $i++)
$dummy = call_user_func($method, $target);
$end = microtime(true);
echo "Time taken with $method = ".round(($end-$start)*1000.0,3)."ms\n";
}
}
$targets = [
'Huge array' => range(0, 30000),
'Small array' => range(0, 1000),
];
$methods = [
'method_1',
'method_2',
'method_3',
'method_4',
];
foreach($targets as $targetName => $target){
echo "==== Benchmark using $targetName ====\n";
benchmark($methods, $target);
echo "\n";
}
results:
==== Benchmark using Huge array ====
Time taken with method_1 = 5504.632ms
Time taken with method_2 = 4509.445ms
Time taken with method_3 = 8614.883ms
Time taken with method_4 = 2720.934ms
==== Benchmark using Small array ====
Time taken with method_1 = 77.159ms
Time taken with method_2 = 130.03ms
Time taken with method_3 = 160.866ms
Time taken with method_4 = 69.946ms
A: A lot of the solutions here are elegant and pretty, but don't scale well, and are memory intensive or CPU intensive. Most are creating 2 new data points in memory with this solution from both sides of the comparison. The larger the array the harder and longer the process and memory used, and you lose the benefit of short circuit evaluation. I Did some testing with a few different ideas. Trying to avoid array_key_exists as it is costly, and also avoiding creating new large datasets to compare. I feel this is a simple way to tell if an array is sequential.
public function is_sequential( $arr = [] ){
if( !is_array( $arr ) || empty( $arr ) ) return false;
$i = 0;
$total = count( $arr );
foreach( $arr as $key => $value ) if( $key !== $i++ ) return false;
return true;
}
You run a single count on the main array and store a single integer. You then loop through the array and check for an exact match while iterating the counter. You should have from 1 to count. If it fails it will short circuit out which gives you performance boost when it is false.
Originally I did this with a for loop and checking for isset( $arr[$i] ) but this will not detect null keys which requires array_key_exists, and as we know that is the worst function to use for speed.
Constantly updating variables via foreach to check along with the iterator never growing past it's integer size let's PHP use it's built in memory optimization, caching and garbage collection to keep you at very low resource usage.
Also, I will argue that using array_keys in a foreach is silly when you can simply run $key => $value and check the key. Why create the new data point? Once you abstract away the array keys you've consumed more memory immediately.
A: For those using Laravel:
Arr::isAssoc returns true if the given array is an associative array. An array is considered "associative" if it doesn't have sequential numerical keys beginning with zero:
use Illuminate\Support\Arr;
$isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]);
// true
$isAssoc = Arr::isAssoc([1, 2, 3]);
// false
https://laravel.com/docs/8.x/helpers#method-array-isassoc
A: Actually the most efficient way is thus:
function is_assoc($array){
$keys = array_keys($array);
return $keys !== array_keys($keys);
}
This works because it compares the keys (which for a sequential array are always 0,1,2 etc) to the keys of the keys (which will always be 0,1,2 etc).
Laravel use this approach.
A: function checkAssoc($array){
return ctype_digit( implode('', array_keys($array) ) );
}
A: Could this be the solution?
public static function isArrayAssociative(array $array) {
reset($array);
return !is_int(key($array));
}
The caveat is obviously that the array cursor is reset but I'd say probably the function is used before the array is even traversed or used.
A: Here's the method I use:
function is_associative ( $a )
{
return in_array(false, array_map('is_numeric', array_keys($a)));
}
assert( true === is_associative(array(1, 2, 3, 4)) );
assert( false === is_associative(array('foo' => 'bar', 'bar' => 'baz')) );
assert( false === is_associative(array(1, 2, 3, 'foo' => 'bar')) );
Note that this doesn't account for special cases like:
$a = array( 1, 2, 3, 4 );
unset($a[1]);
assert( true === is_associative($a) );
Sorry, can't help you with that. It's also somewhat performant for decently sized arrays, as it doesn't make needless copies. It is these little things that makes Python and Ruby so much nicer to write in... :P
A: <?php
function is_list($array) {
return array_keys($array) === range(0, count($array) - 1);
}
function is_assoc($array) {
return count(array_filter(array_keys($array), 'is_string')) == count($array);
}
?>
Both of these examples, which scored the most points do not work correctly with arrays like $array = array('foo' => 'bar', 1)
A: This would work too (demo):
function array_has_numeric_keys_only(array $array)
{
try {
SplFixedArray::fromArray($array, true);
} catch (InvalidArgumentException $e) {
return false;
}
return true;
}
Please note that the main point of this answer is to inform you about the existence of SplFixedArray and not to encourage you to use Exceptions for these kinds of tests.
A: I think the definition of a scalar array will vary by application. That is, some applications will require a more strict sense of what qualifies as a scalar array, and some applications will require a more loose sense.
Below I present 3 methods of varying strictness.
<?php
/**
* Since PHP stores all arrays as associative internally, there is no proper
* definition of a scalar array.
*
* As such, developers are likely to have varying definitions of scalar array,
* based on their application needs.
*
* In this file, I present 3 increasingly strict methods of determining if an
* array is scalar.
*
* @author David Farrell <DavidPFarrell@gmail.com>
*/
/**
* isArrayWithOnlyIntKeys defines a scalar array as containing
* only integer keys.
*
* If you are explicitly setting integer keys on an array, you
* may need this function to determine scalar-ness.
*
* @param array $a
* @return boolean
*/
function isArrayWithOnlyIntKeys(array $a)
{
if (!is_array($a))
return false;
foreach ($a as $k => $v)
if (!is_int($k))
return false;
return true;
}
/**
* isArrayWithOnlyAscendingIntKeys defines a scalar array as
* containing only integer keys in ascending (but not necessarily
* sequential) order.
*
* If you are performing pushes, pops, and unsets on your array,
* you may need this function to determine scalar-ness.
*
* @param array $a
* @return boolean
*/
function isArrayWithOnlyAscendingIntKeys(array $a)
{
if (!is_array($a))
return false;
$prev = null;
foreach ($a as $k => $v)
{
if (!is_int($k) || (null !== $prev && $k <= $prev))
return false;
$prev = $k;
}
return true;
}
/**
* isArrayWithOnlyZeroBasedSequentialIntKeys defines a scalar array
* as containing only integer keys in sequential, ascending order,
* starting from 0.
*
* If you are only performing operations on your array that are
* guaranteed to either maintain consistent key values, or that
* re-base the keys for consistency, then you can use this function.
*
* @param array $a
* @return boolean
*/
function isArrayWithOnlyZeroBasedSequentialIntKeys(array $a)
{
if (!is_array($a))
return false;
$i = 0;
foreach ($a as $k => $v)
if ($i++ !== $k)
return false;
return true;
}
A: My solution:
function isAssociative(array $array)
{
return array_keys(array_merge($array)) !== range(0, count($array) - 1);
}
array_merge on a single array will reindex all integer keys, but not other. For example:
array_merge([1 => 'One', 3 => 'Three', 'two' => 'Two', 6 => 'Six']);
// This will returns [0 => 'One', 1 => 'Three', 'two' => 'Two', 2 => 'Six']
So if a list (a non-associative array) is created ['a', 'b', 'c'] then a value is removed unset($a[1]) then array_merge is called, the list is reindexed starting from 0.
A: One more fast from source.
Fit encoding of json_encode (and bson_encode). So has javascript Array compliance.
function isSequential($value){
if(is_array($value) || ($value instanceof \Countable && $value instanceof \ArrayAccess)){
for ($i = count($value) - 1; $i >= 0; $i--) {
if (!isset($value[$i]) && !array_key_exists($i, $value)) {
return false;
}
}
return true;
} else {
throw new \InvalidArgumentException(
sprintf('Data type "%s" is not supported by method %s', gettype($value), __METHOD__)
);
}
}
A: I've used both array_keys($obj) !== range(0, count($obj) - 1) and array_values($arr) !== $arr (which are duals of each other, although the second is cheaper than the first) but both fail for very large arrays.
This is because array_keys and array_values are both very costly operations (since they build a whole new array of size roughly that of the original).
The following function is more robust than the methods provided above:
function array_type( $obj ){
$last_key = -1;
$type = 'index';
foreach( $obj as $key => $val ){
if( !is_int( $key ) || $key < 0 ){
return 'assoc';
}
if( $key !== $last_key + 1 ){
$type = 'sparse';
}
$last_key = $key;
}
return $type;
}
Also note that if you don't care to differentiate sparse arrays from associative arrays you can simply return 'assoc' from both if blocks.
Finally, while this might seem much less "elegant" than a lot of "solutions" on this page, in practice it is vastly more efficient. Almost any associative array will be detected instantly. Only indexed arrays will get checked exhaustively, and the methods outlined above not only check indexed arrays exhaustively, they duplicate them.
A: Here is another simple but powerful logic ( which is also used by great Laravel framework in it's internal mechanism )
/**
* Determines if an array is associative.
* @param array $array
* @return bool
*/
function isAssoc(array $array)
{
$keys = array_keys($array);
return array_keys($keys) !== $keys;
}
A: Surely this is a better alternative.
<?php
$arr = array(1,2,3,4);
$isIndexed = array_values($arr) === $arr;
A: I think the following two functions are the best way to go for checking 'if an array is associative or numeric'. Since 'numeric' could mean only numeric keys or only sequential numeric keys, two functions are listed below that check either condition:
function is_indexed_array(&$arr) {
for (reset($arr); is_int(key($arr)); next($arr));
return is_null(key($arr));
}
function is_sequential_array(&$arr, $base = 0) {
for (reset($arr), $base = (int) $base; key($arr) === $base++; next($arr));
return is_null(key($arr));
}
The first function checks if each key is an integer value. The second function checks if each key is an integer value and in addition checks if all keys are sequential starting at $base, which defaults to 0 and thus can be omitted if you do not need to specify another base value. key($my_array) returns null if the read pointer is moved past the end of the array, which is what ends the for loop and makes the statement after the for loop return true if all keys were integer. If not, the loop ends prematurely because a key is of type string, and the statement after the for loop will return false. The latter function in addition adds one to $base after each compare, to be able to check if the next key is of the correct value. The strict compare makes it also check if the key is of type integer. The $base = (int) $base part in the first section of the for loop can be left out when $base is omitted or if you make sure it is only called using an integer. But since I can't be sure for everybody, I left it in. The statement is executed only once, anyway. I think these are the most efficient solutions:
*
*Memory wise: No copying of data or key ranges. Doing an array_values or array_keys may seem shorter (less code) but keep in mind what goes on in the background once you make that call. Yes there are more (visible) statements than in some other solutions, but that is not what counts, is it?
*Time wise: Besides the fact that copying/extracting data and/or keys also takes time, this solution is more efficient than doing a foreach. Again a foreach may seem more efficient to some because it is shorter in notation, but in the background foreach also calls reset, key and next to do it's looping. But in addition it also calls valid to check the end condition, which is avoided here due to the combination with the integer check.
Remember that an array key can only be an integer or a string, and a strictly numeric string such as "1" (but not "01") will be translated into an integer. Which is what makes checking for an integer key the only needed operation besides counting if you want the array to be sequential. Naturally, if is_indexed_array returns false the array can be seen as associative. I say 'seen', because in fact they all are.
A: Or you can just use this:
Arr::isAssoc($array)
which will check if array contains any non-numeric key or:
Arr:isAssoc($array, true)
to check if array is strictly sequencial (contains auto generated int keys 0 to n-1)
using this library.
A: This question is actually useless when it comes to array of php because with the nature of php an array should not have to be fully associative or indexing, it can be combination of both, the way user have define and assigned the value an array can be a combination of both. see the example below
$y= array(5);
$y["0x"]="n";
$y["vbg"]="12132";
$y[1] = "k";
var_dump($y); //this will output 4 element array
echo "</br>" .$y["0x"]."</br>".$y[0];
for($x=0;$x<sizeof($y);$x++){ // this will output all index elements & gives error after that
echo "</br> index elements ".$y[$x];
}
so the correct question that has to ask is , is all the element in array are associative or index. if you really know that it will only be either associative or indexing not a combination of these two, you can just simply use this method to find wether it is an index or associative array.
function AssocTest(&$arr){
if(is_array($arr)){
reset($arr); // reset pointer to first element of array
if(gettype(key($arr)) == "string"){ //get the type(nature) of first element key
return true;
}else{
return false;
}
}else{
return false;
}
}
you can use it as normal function
echo(AssocTest($y)? "Associative array": "Not an Associative array/ Not an array at all");
and important thing to remember evan you have initialize an array as associative but the names that you have gave the associative array is just numbers it will treat as an index array when it being read by php if you have not explicitly gave the string names. take a look at the example below.
$y["0"]="n";
$y["1"]="12132";
$y["22"] = "k";
//both will get the same output
echo "<br/> s0 ".$y["22"];
echo "<br/> s0 ".$y[22];
for($x=0;$x<count($y);$x++){
echo "<br/> arr ".$y[$x]; // this will output up to 2nd element and give an error after
}
so if you need to be sure all the elements of the array to be exactly indexed or either associative , there is no other way but go true all the elements and check each and every element key by generated index array as post by many people here.
function fullAssocTest(&$arr)
{
if(is_array($arr)){
return (array_keys($arr) !== range(0, count($arr) - 1));
}
}
its less coding, but this thing is really process intensive and really un-necessary work.
A: Sometimes you can get away with only checking if the first array's Key is 0.
$isSequential = array_keys($arr)[0] === 0
, or, faster, but more verbose version:
reset($arr); $isSequential = key($arr) === 0
A: Just adding my two cents, and I think it should be pretty efficient based on @nonsensei 's benchmarks as well as being clearly legible:
function is_associative(array $array): bool
{
foreach ($array as $key => $value)
{
if (!is_string($key)) return false;
}
return true;
}
A: Unless PHP has a builtin for that, you won't be able to do it in less than O(n) - enumerating over all the keys and checking for integer type. In fact, you also want to make sure there are no holes, so your algorithm might look like:
for i in 0 to len(your_array):
if not defined(your-array[i]):
# this is not an array array, it's an associative array :)
But why bother? Just assume the array is of the type you expect. If it isn't, it will just blow up in your face - that's dynamic programming for you! Test your code and all will be well...
A: function is_associative($arr) {
return (array_merge($arr) !== $arr || count(array_filter($arr, 'is_string', ARRAY_FILTER_USE_KEY)) > 0);
}
A: Yet another way to do this.
function array_isassociative($array)
{
// Create new Array, Make it the same size as the input array
$compareArray = array_pad(array(), count($array), 0);
// Compare the two array_keys
return (count(array_diff_key($array, $compareArray))) ? true : false;
}
A: I compare the difference between the keys of the array and the keys of the result of array_values() of the array, which will always be an array with integer indices. If the keys are the same, it's not an associative array.
function isHash($array) {
if (!is_array($array)) return false;
$diff = array_diff_assoc($array, array_values($array));
return (empty($diff)) ? false : true;
}
A: Modification on the most popular answer.
This takes a little more processing, but is more accurate.
<?php
//$a is a subset of $b
function isSubset($a, $b)
{
foreach($a =>$v)
if(array_search($v, $b) === false)
return false;
return true;
//less effecient, clearer implementation. (uses === for comparison)
//return array_intersect($a, $b) === $a;
}
function isAssoc($arr)
{
return !isSubset(array_keys($arr), range(0, count($arr) - 1));
}
var_dump(isAssoc(array('a', 'b', 'c'))); // false
var_dump(isAssoc(array(1 => 'a', 0 => 'b', 2 => 'c'))); // false
var_dump(isAssoc(array("0" => 'a', "1" => 'b', "2" => 'c'))); // false
//(use === in isSubset to get 'true' for above statement)
var_dump(isAssoc(array("a" => 'a', "b" => 'b', "c" => 'c'))); // true
?>
A: I've come up with next method:
function isSequential(array $list): bool
{
$i = 0;
$count = count($list);
while (array_key_exists($i, $list)) {
$i += 1;
if ($i === $count) {
return true;
}
}
return false;
}
var_dump(isSequential(array())); // false
var_dump(isSequential(array('a', 'b', 'c'))); // true
var_dump(isSequential(array("0" => 'a', "1" => 'b', "2" => 'c'))); // true
var_dump(isSequential(array("1" => 'a', "0" => 'b', "2" => 'c'))); // true
var_dump(isSequential(array("1a" => 'a', "0b" => 'b', "2c" => 'c'))); // false
var_dump(isSequential(array("a" => 'a', "b" => 'b', "c" => 'c'))); // false
*Note empty array is not considered a sequential array, but I think it's fine since empty arrays is like 0 - doesn't matter it's plus or minus, it's empty.
Here are the advantages of this method compared to some listed above:
*
*It does not involve copying of arrays (someone mentioned in this gist https://gist.github.com/Thinkscape/1965669 that array_values does not involve copying - what!?? It certainly does - as will be seen below)
*It's faster for bigger arrays and more memory friendly at the same time
I've used benchmark kindly provided by Artur Bodera, where I changed one of the arrays to 1M elements (array_fill(0, 1000000, uniqid()), // big numeric array).
Here are the results for 100 iterations:
PHP 7.1.16 (cli) (built: Mar 31 2018 02:59:59) ( NTS )
Initial memory: 32.42 MB
Testing my_method (isset check) - 100 iterations
Total time: 2.57942 s
Total memory: 32.48 MB
Testing method3 (array_filter of keys) - 100 iterations
Total time: 5.10964 s
Total memory: 64.42 MB
Testing method1 (array_values check) - 100 iterations
Total time: 3.07591 s
Total memory: 64.42 MB
Testing method2 (array_keys comparison) - 100 iterations
Total time: 5.62937 s
Total memory: 96.43 MB
*Methods are ordered based on their memory consumption
**I used echo " Total memory: " . number_format(memory_get_peak_usage()/1024/1024, 2) . " MB\n"; to display memory usage
A: /**
* check is assoc array
*
* @param array $array
*
* @return bool
*/
private function isAssoc(array $array): bool
{
if(empty($array)) {
return false;
}
return empty(array_diff(array_keys($array), range(0, count($array) - 1)));
}
A: If your looking for just non-numeric keys (no matter the order) then you may want to try
function IsAssociative($array)
{
return preg_match('/[a-z]/i', implode(array_keys($array)));
}
A: I just use the key() function. Observe:
<?php
var_dump(key(array('hello'=>'world', 'hello'=>'world'))); //string(5) "hello"
var_dump(key(array('world', 'world'))); //int(0)
var_dump(key(array("0" => 'a', "1" => 'b', "2" => 'c'))); //int(0) who makes string sequetial keys anyway????
?>
Thus, just by checking for false, you can determine whether an array is associative or not.
A:
function is_assoc(array $array): bool
{
foreach ($array as $iValue) {
if (is_array($iValue)) {
return true;
}
}
return false;
}
$d= is_assoc(["id",2,3]);
var_dump($d);
A: One cheap and dirty way would be to check like this:
isset($myArray[count($myArray) - 1])
...you might get a false positive if your array is like this:
$myArray = array("1" => "apple", "b" => "banana");
A more thorough way might be to check the keys:
function arrayIsAssociative($myArray) {
foreach (array_keys($myArray) as $ind => $key) {
if (!is_numeric($key) || (isset($myArray[$ind + 1]) && $myArray[$ind + 1] != $key + 1)) {
return true;
}
}
return false;
}
// this will only return true if all the keys are numeric AND sequential, which
// is what you get when you define an array like this:
// array("a", "b", "c", "d", "e");
or
function arrayIsAssociative($myArray) {
$l = count($myArray);
for ($i = 0; $i < $l, ++$i) {
if (!isset($myArray[$i])) return true;
}
return false;
}
// this will return a false positive on an array like this:
$x = array(1 => "b", 0 => "a", 2 => "c", 4 => "e", 3 => "d");
A: function isAssoc($arr)
{
$a = array_keys($arr);
for($i = 0, $t = count($a); $i < $t; $i++)
{
if($a[$i] != $i)
{
return false;
}
}
return true;
}
A: Another variant not shown yet, as it's simply not accepting numerical keys, but I like Greg's one very much :
/* Returns true if $var associative array */
function is_associative_array( $array ) {
return is_array($array) && !is_numeric(implode('', array_keys($array)));
}
A: Best function to detect associative array (hash array)
<?php
function is_assoc($arr) { return (array_values($arr) !== $arr); }
?>
A: Simple and performance friendly solution which only checks the first key.
function isAssoc($arr = NULL)
{
if ($arr && is_array($arr))
{
foreach ($arr as $key => $val)
{
if (is_numeric($key)) { return true; }
break;
}
}
return false;
}
A: In simple way you can check is array is associative or not by below steps
*
*convert all keys of array into one array by using array_keys()
*filter out non numeric key from array using array_filter() and
is_numeric()
*compare number of elements in filtered array and actual array, If number of elements are not equals in both array then it is associative array.
Function for above step is as below.
function isAssociative(array $array)
{
return count(array_filter(array_keys($array), function($v){return is_numeric($v);})) !== count($array));
}
A: I met this problem once again some days ago and i thought to take advantage of the array_merge special property:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
So why not to use:
function Is_Indexed_Arr($arr){
$arr_copy = $arr;
if((2*count($arr)) == count(array_merge($arr, $arr_copy))){
return 1;
}
return 0;
}
A: My solution is to get keys of an array like below and check that if the key is not integer:
private function is_hash($array) {
foreach($array as $key => $value) {
return ! is_int($key);
}
return false;
}
It is wrong to get array_keys of a hash array like below:
array_keys(array(
"abc" => "gfb",
"bdc" => "dbc"
)
);
will output:
array(
0 => "abc",
1 => "bdc"
)
So, it is not a good idea to compare it with a range of numbers as mentioned in top rated answer. It will always say that it is a hash array if you try to compare keys with a range.
A: Actually, I found myself in a similar situation trying to take an array and parse it into XML. XML element names cannot begin with numbers -- and the code snippets I found did not correctly deal with arrays with numeric indexes.
Details on my particular situation are below
The answer provided above by @null ( http:// stackoverflow .com/a/173589/293332 ) was actually pretty darn close. I was dismayed that it got voted down tho: Those who do not understand regex lead very frustrating lives.
Anyway, based upon his answer, here is what I ended up with:
/**
* Checks if an array is associative by utilizing REGEX against the keys
* @param $arr <array> Reference to the array to be checked
* @return boolean
*/
private function isAssociativeArray( &$arr ) {
return (bool)( preg_match( '/\D/', implode( array_keys( $arr ) ) ) );
}
See the PCRE Escape Sequences and PCRE Syntax pages for further details.
My Particular Situation
Here is an example array that I am dealing with:
Case A
return array(
"GetInventorySummary" => array(
"Filters" => array(
"Filter" => array(
array(
"FilterType" => "Shape",
"FilterValue" => "W",
),
array(
"FilterType" => "Dimensions",
"FilterValue" => "8 x 10",
),
array(
"FilterType" => "Grade",
"FilterValue" => "A992",
),
),
),
"SummaryField" => "Length",
),
);
The catch is that the filter key is variable. For example:
Case B
return array(
"GetInventorySummary" => array(
"Filters" => array(
"Filter" => array(
"foo" => "bar",
"bar" => "foo",
),
),
"SummaryField" => "Length",
),
);
Why I Need Assoc. Array Checker
If the array I am transforming is like Case A, what I want returned is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<GetInventorySummary>
<Filters>
<Filter>
<FilterType>Shape</FilterType>
<FilterValue>W</FilterValue>
</Filter>
<Filter>
<FilterType>Dimensions</FilterType>
<FilterValue>8 x 10</FilterValue>
</Filter>
<Filter>
<FilterType>Grade</FilterType>
<FilterValue>A992</FilterValue>
</Filter>
</Filters>
<SummaryField>Length</SummaryField>
</GetInventorySummary>
... However, if the array I am transforming is like Case B, what I want returned is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<GetInventorySummary>
<Filters>
<Filter>
<foo>bar</foo>
<bar>foo</bar>
</Filter>
</Filters>
<SummaryField>Length</SummaryField>
</GetInventorySummary>
A: function is_array_assoc($foo) {
if (is_array($foo)) {
return (count(array_filter(array_keys($foo), 'is_string')) > 0);
}
return false;
}
A: Improvement from Mark Amery
function isAssoc($arr)
{
// Is it set, is an array, not empty and keys are not sequentialy numeric from 0
return isset($arr) && is_array($arr) && count($arr)!=0 && array_keys($arr) !== range(0, count($arr) - 1);
}
This tests if variable exists, if it is an array, if it is not an empty array and if the keys are not sequential from 0.
To see if the array is associative
if (isAssoc($array)) ...
To see if it numeric
if (!isAssoc($array)) ...
A: Checking if array has all assoc-keys. With using stdClass & get_object_vars ^):
$assocArray = array('fruit1' => 'apple',
'fruit2' => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot');
$assoc_object = (object) $assocArray;
$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object)));
var_dump($isAssoc); // true
Why? Function get_object_vars returns only accessible properties (see more about what is occuring during converting array to object here). Then, just logically: if count of basic array's elements equals count of object's accessible properties - all keys are assoc.
Few tests:
$assocArray = array('apple', 'orange', 'tomato', 'carrot');
$assoc_object = (object) $assocArray;
$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object)));
var_dump($isAssoc); // false
//...
$assocArray = array( 0 => 'apple', 'orange', 'tomato', '4' => 'carrot');
$assoc_object = (object) $assocArray;
$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object)));
var_dump($isAssoc); // false
//...
$assocArray = array('fruit1' => 'apple',
NULL => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot');
$assoc_object = (object) $assocArray;
$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object)));
var_dump($isAssoc); //false
Etc.
A: This is my function -
public function is_assoc_array($array){
if(is_array($array) !== true){
return false;
}else{
$check = json_decode(json_encode($array));
if(is_object($check) === true){
return true;
}else{
return false;
}
}
}
Some examples
print_r((is_assoc_array(['one','two','three']))===true?'Yes':'No'); \\No
print_r(is_assoc_array(['one'=>'one','two'=>'two','three'=>'three'])?'Yes':'No'); \\Yes
print_r(is_assoc_array(['1'=>'one','2'=>'two','3'=>'three'])?'Yes':'No'); \\Yes
print_r(is_assoc_array(['0'=>'one','1'=>'two','2'=>'three'])?'Yes':'No'); \\No
There was a similar solution by @devios1 in one of the answers but this was just another way using the inbuilt json related functions of PHP. I haven't checked how this solution fairs in terms of performance compared to other solutions that have been posted here. But it certainly has helped me solve this problem. Hope this helps.
A: /*
iszba - Is Zero Based Array
Detects if an array is zero based or not.
PARAMS:
$chkvfnc
Callback in the loop allows to check the values of each element.
Signature:
bool function chkvfnc($v);
return:
true continue looping
false stop looping; iszba returns false too.
NOTES:
β assert: $array is an array.
β May be memory efficient;
it doesn't get extra arrays via array_keys() or ranges() into the function.
β Is pretty fast without a callback.
β With callback it's ~2.4 times slower.
*/
function iszba($array, $chkvfnc=null){
$ncb = !$chkvfnc;
$i = 0;
foreach($array as $k => $v){
if($k === $i++)
if($ncb || $chkvfnc($v))
continue;
return false;
}
return true;
}
β’ Without callback it is ~30% faster than current leading answer,
and possibly more memory efficient.
β’ Just negate the answer to know if the array should be considered associative.
A: I'm surprised no one has mentioned array_key_first()
For your test cases:
$sequentialArray = array('apple', 'orange', 'tomato', 'carrot');
$isIndexedArray = is_int( array_key_first($sequentialArray) ); // true
whereas
$assocArray = array('fruit1' => 'apple',
'fruit2' => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot');
$isIndexedArray = is_int( array_key_first($assocArray) ); // false
Read more about this function here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "895"
} |
Q: How can I find the execution time of a section of my program in C? I'm trying to find a way to get the execution time of a section of code in C. I've already tried both time() and clock() from time.h, but it seems that time() returns seconds and clock() seems to give me milliseconds (or centiseconds?) I would like something more precise though. Is there a way I can grab the time with at least microsecond precision?
This only needs to be able to compile on Linux.
A: Have a look at gettimeofday,
clock_*, or get/setitimer.
A: Try "bench.h"; it lets you put a START_TIMER; and STOP_TIMER("name"); into your code, allowing you to arbitrarily benchmark any section of code (note: only recommended for short sections, not things taking dozens of milliseconds or more). Its accurate to the clock cycle, though in some rare cases it can change how the code in between is compiled, in which case you're better off with a profiler (though profilers are generally more effort to use for specific sections of code).
It only works on x86.
A: You referred to clock() and time() - were you looking for gettimeofday()?
That will fill in a struct timeval, which contains seconds and microseconds.
Of course the actual resolution is up to the hardware.
A: For what it's worth, here's one that's just a few macros:
#include <time.h>
clock_t startm, stopm;
#define START if ( (startm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define STOP if ( (stopm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define PRINTTIME printf( "%6.3f seconds used by the processor.", ((double)stopm-startm)/CLOCKS_PER_SEC);
Then just use it with:
main() {
START;
// Do stuff you want to time
STOP;
PRINTTIME;
}
From http://ctips.pbwiki.com/Timer
A: You want a profiler application.
Search keywords at SO and search engines: linux profiling
A: You might want to google for an instrumentation tool.
A: You won't find a library call which lets you get past the clock resolution of your platform. Either use a profiler (man gprof) as another poster suggested, or - quick & dirty - put a loop around the offending section of code to execute it many times, and use clock().
A: gettimeofday() provides you with a resolution of microseconds, whereas clock_gettime() provides you with a resolution of nanoseconds.
int clock_gettime(clockid_t clk_id, struct timespec *tp);
The clk_id identifies the clock to be used. Use CLOCK_REALTIME if you want a system-wide clock visible to all processes. Use CLOCK_PROCESS_CPUTIME_ID for per-process timer and CLOCK_THREAD_CPUTIME_ID for a thread-specific timer.
A: If you are developing on x86 or x64 why not use the Time Stamp Counter: RDTSC.
It will be more reliable then Ansi C functions like time() or clock() as RDTSC is an atomic function. Using C functions for this purpose can introduce problems as you have no guarantee that the thread they are executing in will not be switched out and as a result the value they return will not be an accurate description of the actual execution time you are trying to measure.
With RDTSC you can better measure this. You will need to convert the tick count back into a human readable time H:M:S format which will depend on the processors clock frequency but google around and I am sure you will find examples.
However even with RDTSC you will be including the time your code was switched out of execution, while a better solution than using time()/clock() if you need an exact measurement you will have to turn to a profiler that will instrument your code and take into account when your code is not actually executing due to context switches or whatever.
A: It depends on the conditions.. Profilers are nice for general global views however if you really need an accurate view my recommendation is KISS. Simply run the code in a loop such that it takes a minute or so to complete. Then compute a simple average based on the total run time and iterations executed.
This approach allows you to:
*
*Obtain accurate results with low resolution timers.
*Not run into issues where instrumentation interferes with high speed caches (l2,l1,branch..etc) close to the processor. However running the same code in a tight loop can also provide optimistic results that may not reflect real world conditions.
A: Don't know which enviroment/OS you are working on, but your timing may be inaccurate if another thread, task, or process preempts your timed code in the middle. I suggest exploring mechanisms such as mutexes or semaphores to prevent other threads from preemting your process.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Developing a scheduled task for Windows I have to develop an application using C#.net that has to be run once a day. It only runs for at most one minute, so developing a Windows service is overkill and a scheduled task is the appropriate way.
However, I have a few questions about how the application can communicate its results:
*
*How do I indicate to the task scheduler that the task has failed? Is this via the program's exit code?
*How do I log output information? Is console output automatically captured or do I have to write to the event viewer explicitly?
A: In answer to your questions -
*
*If a task fails because it threw an unchecked exception you'll see that in the Sheduled Task viewer, there will be a 'Last Result' with a value something like 0xe0434f4d. Alternatively if you return an exit code that will be also be shown in the Last Result column of the Scheduled Task viewer.
*Writing to the console e.g. Console.WriteLine("blah"); won't show up anywhere. You'd need to write to the event log or to a log file.
A: If you go the Log File way, you can still use Console.WriteLine("blah");. The trick is to redirect the standard Out and Error streams:
StreamWriter mylog = new StreamWriter("mylog.log");
Console.SetOut(mylog);
Console.SetError(mylog);
You also need to flush the buffers often, to make sure the log file contains current information.
Console.Out.Flush();
This is quick and dirty, you really should use the Windows Event Log or log4net.
A: AFAIK the scheduler just kicks off a process. You can use the event log or another logging system to record the information you need to refer to later.
A: Log4net is a very good, complete logging framework. I can highly recommend it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How to fix DWMAPI.DLL delay-load dependency under WinXP? I have built a .dll under WinXP that claims it can't find DWMAPI.DLL when it's loaded. The problem is that this DLL is a Vista DLL, and this a known issue for XP users that have IE7 installed. The recommendation is to uninstall IE7 or repair the .NET Framework via Add/Remove programs. I did the repair, and nothing changed. I'm not about to uninstall IE7 since there must be a better solution that's not the equivalent of "reinstall windows".
I've read bad things about people who attempted to uninstall IE7, so I'm reluctant to go that route.
I am using C++ under Visual Studio 2003 (7.1). I don't see an option where I may have forced delay loading at application launch. I just used default settings when I created the DLL project. I did just now find an interesting option, Linker->Input->Delay Loaded DLLs, so I put DWMAPI.DLL in there to force it to be delay-loaded. However, I get this when linking:
LINK : warning LNK4199: /DELAYLOAD:dwmapi.dll ignored; no imports found from dwmapi.dll
.. and it of course didn't change a thing when trying to load my DLL. For the heck of it, I added the whole tree of DLLs that lead to DWMAPI.DLL, and I get the same message. (For the record, it's foundation.dll->shell32.dll->shdocvw.dll->mshtml.dll->ieframe.dll->dwmapi.dll .)
To be more specific about what I'm doing, I am writing a Maya plugin and get the always-helpful text in the script editor:
// Error: Unable to dynamically load : D:/blahblahblah/mydll.mll
The specified module could not be found.
//
// Error: The operation completed successfully.
//
// Error: The operation completed successfully.
(mydll) //
I used Dependency Walker to initially track down the problem, and that's what lead me to DWMAPI.DLL. These are the message depends gives me, and DWMAPI.DLL is the only thing that has a yellow question mark next to it:
Warning: At least one delay-load dependency module was not found.
Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.
Gerald is right. Maya is, in fact, using a different PATH than the Dependency Walker. My plug-in loads another DLL (for image processing) that lives in the Maya plug-ins directory and depends found it with no problem, but Maya didn't. I had to add ";plug-ins" to the PATH in Maya.env.
Seeing as this problem wasn't related to DWMAPI.DLL after all, but DWMAPI is a common problem, I'll post the best link I found about the DWMAPI issue on Novell's website here. Basically, most programs will have this warning in depends.exe, but if there is a delay-load icon next to it, and you are sure that the program won't directly or indirectly call DWMAPI, then it's fine. The problem is elsewhere. If the delay-load icon isn't present, then you have to look at the /DELAY and /DELAYLOAD options in Visual Studio. The fact that depends gave me a "warning" and not an "error" was a clue to the fact that DWMAPI is not being loaded automatically.
A: Based on your updated problem, DWMAPI.dll is probably not your problem. Dependency walker will always give you that error whenever you are linking to mshtml as it always checks delay loaded DLLs.
At this point my best guess is that you have your project set to dynamically load the runtime libraries and the search path for DLLs is being changed by Maya. So it may be unable to find the MSVC runtime DLL(s). I haven't developed Maya plugins in a long time, but I've had that problem with other apps that have plugin DLLs recently.
Try changing your setting in C/C++->Code Generation->Runtime Library to Multi-Threaded rather than Multi-Threaded DLL.
Aside from that you can try fiddling with Dependency Walker to make it use the same search paths as Maya and see if you can come up with another dependency problem.
As a last resort you can launch Maya in a debugger and set a breakpoint on LoadLibrary and find out which library is not being loaded that way.
A: This is a tricky one. There's really 2 main ways you will get this error.
1) You have your project set to force delay loaded DLLs to load at application launch. DWMAPI.dll is a delay-loaded DLL and thus normally will not be loaded unless one of it's functions is called. That won't happen on XP unless you're trying to do it in your DLL. But it's possible to set a compiler option to force your app to load the delay loaded DLLs anyway. If you're doing that, don't.
2) It's often a false error that you will get from depends.exe when there is another problem. Run your DLL through dependency walker and see if there are any other dependency problems. If all else fails, try uninstalling IE7 and see if the problem persists. If it is a false error, after you install IE7 you will see the real error. You can install IE7 again afterwards.
A: I had exactly this problem.
Sneaky problem that took hours to solve.
Anyway. I compiled my managed C++ application on the release machine. Got complaints from customers that could not run it, worked like a charm on all of our machines.
It turned out that the release machine was automatically patched one night a month ago with the ATL vulnerability fix, and so was all other machines also, except one XP machine.
That particulare XP machine could not run the application either. Installed the ATL fix (see link below), and voilΓ‘, every thing worked just like before.
http://www.microsoft.com/downloads/details.aspx?familyid=766A6AF7-EC73-40FF-B072-9112BAB119C2&displaylang=en
So lesson learned, always check your intermediate manifests (found the in debug or release directory), that will tell you what version of the DLL that the program have been linked against.
Hope it helps anyone.
A: Try changing your setting in C/C++->Code Generation->Runtime Library to Multi-Threaded rather than Multi-Threaded DLL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: MinGW library converted to Windows library gives odd link in VC++6 I used the MinGW .a to Windows .lib transformation process as detailed in a
thread on the gmp-discuss list, as below (acting against a library created with --disable-shared --enable-static.)
cp libgmp.a gmp.a
ranlib gmp.a
mv gmp.a gmp.lib
I now have a .lib file against which VC++6 seems to have no difficulty linking. What concerns me now is warning messages I'm getting from the link phase:
LINK : warning LNK4049: locally defined symbol "___mb_cur_max" imported
LINK : warning LNK4049: locally defined symbol "__pctype" imported
LINK : warning LNK4049: locally defined symbol "__iob" imported
At this point in the proceedings these make no difference to the running of
my DLL (which wraps certain GMP functionality). But is that good enough?
Will having these three symbols from libgmp.a linked in to my Windows DLL
end up biting me later on?
A: Someone else had a similar problem and the fix was relatively simple.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Track completed downloads from glassfish I want to be able to track completed downloads served by my glassfish server. I couldn't find a 100% correct solution using servlet life cycle listeners.
Does anyone have a better idea?
A: Put a try-catch on IOException while serving the file download. If it's thrown, then serving the file download has failed.
E.g. in a custom file servlet:
try {
response.getOutputStream().write(...);
// Success!
} catch (IOException e) {
// Fail!
throw e;
}
Or in a servlet filter which is mapped on the appropriate URL pattern matching file downloads:
try {
chain.doFilter(request, response);
// Success!
} catch (IOException e) {
// Fail!
throw e;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Using Microsoft.Sdc.Tasks.ServiceProcess.ControlService how do I check if a service exists on a remote machine? I'm trying to check if a service exists on a remote machine using the Microsoft.Sdc.Tasks.ServiceProcess.ControlService task.
<ControlService MachineName="$(TargetMachineName)" Action="Exists" ServiceName="w3svc">
<Output PropertyName="W3ServiceExists" TaskParameter="ServiceExists" />
</ControlService>
When I use the above task declaration I get this output from MSBUILD.
(42,54): error MSB4065: The "ServiceExists" parameter is not marked for output by the "ControlService" task.
Is there a way to use the ControlService class to get whether or not a service exists on a remote machine?
A: The answer was to pull the code and recompile with the ServiceExists property properly marked with the [Output] attribute.
Would recommend anyone that finds this answer look at the MS Build Extension Pack instead as this problem doesn't exist in that set of MS Build tasks and it is more actively developed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Learning Windows Forms vs. Windows Presentation Foundation So I've been thinking of going for Microsoft certification and I have to make a choice (for now) between Windows Forms and WPF for developing Windows applications. I have had good exposure to Windows Forms but never tried WPF before. Furthermore, most of the job postings where I live seem to be WinForms-oriented. That might change in the next few years, so I was wondering if I should get started on learning WPF or stick to the tried and true Forms.
Any insight?
A: *
*Although most current dev.positions will focus on WinForms (or ASP.NET for that matter), WPF is starting to get accepted as a 'serious' platform. With serious I mean that
people are starting to think about using it for LOB-applications. With the release of Prism it's clear that Microsoft is starting to promote WPF in other ways than just the
'eye-candy' features. This means WPF is going to be presented as a WinForms alternative pretty soon.
*Learning WPF will mean you'll also learn Silverlight at the same time. So you have two modern technologies at your disposal.
[Added] -WPF has more to offer than just the eye-candy and you can benefit from it a lot without being a creative genius. The API is intuitive (and fun) and can offer a lot of improved productivity.
In short, I'd say if you want to be 'future-proof' learn WPF.
A: In "enterprise" programming, I don't see an immediate need for WPF development. The reasons for this:
*
*Companies are not running on the newest hardware, and tend to migrate to remote desktops (RDP/Citrix).
*A developer can design a decent interface using Windows.Forms controls. In WPF, you need a designer. In large companies there are designers, in most companies I know, the IT department is staffed with programmers and system-engineers, no designers.
Software for the "home market" is another story.
A: If you want to go the certification route to learn then WPF is a good choice. It will take a few years before it will really take over from winforms but It's a safe bet it will so it's a good investment to learn.
If you're more of a self learner and just want to get certified to improve your chances on the job market then I'd go with winforms for the certification. You can pick up WPF when you need it. By the time you really need to have a WPF certification it will probably be easier for you because you've already used it.
A: WPF leverages XAML for the design/visual experience this is the same technology that Silverlight uses and in the future will be leveraged heavily by other aspects of .NET 4.0, specifically, WCF (web services) and WF (workflow).
I would highly recommend learning it if you have the cycles, however for certification purposes it might be easier to just go ahead and do the WinForms exam as WPF is quite different and in my experience had a bit of a learning curve (because of how different it is from WinForms).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Positioning flash content using CSS I have a generated HTML page with flash content in it. I am trying to reposition the flash content and make it "absolute". I have tried to wrap the object tags with a div tag, but to no avail. Can anyone tell me how to do this? Removing the generated positioning attributes does not work.
See relevant code below (it is not very neat, but this is how it is generated. I have removed most irrelevant code):
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>* welcome *</title>
<script language="javascript">AC_FL_RunContent = 0;</script>
<script src="AC_RunActiveContent.js" language="javascript"></script>
</head>
<body bgcolor="#000000">
<script language="javascript">
if (AC_FL_RunContent == 0) {
alert("This page requires AC_RunActiveContent.js.");
} else {
AC_FL_RunContent(
'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
'width', '430',
'height', '200',
'src', 'bar',
'quality', 'high',
'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
'align', 'right',
'play', 'true',
'loop', 'true',
'scale', 'showall',
'wmode', 'transparent',
'devicefont', 'false',
'id', 'bar',
'bgcolor', '#000000',
'name', 'bar',
'menu', 'true',
'allowFullScreen', 'false',
'allowScriptAccess','sameDomain',
'movie', 'bar',
'salign', ''
); //end AC code
}
</script>
<noscript>
<div style = "position: absolute">
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="430" height="200" id="bar" align="right">
<param name="allowScriptAccess" value="sameDomain" />
<param name="allowFullScreen" value="false" />
<param name="movie" value="bar.swf" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><param name="bgcolor" value="#000000" />
</object>
</div>
</noscript>
Thanks in advance!
A: Since your div is wrapped in noscript it will only be shown if javascript is turned off, are you sure that is the behaviour you want?
A: you should place the JS script that actually creates you object inside your div not before it.
A: @Fuzzy76 & @epeleg.blogspot.com is right
@pypmanetjies -> Your code must be like this (shortened):
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>* welcome *</title>
<script language="javascript">AC_FL_RunContent = 0;</script>
<script src="AC_RunActiveContent.js" language="javascript"></script>
</head>
<body bgcolor="#000000">
<div style = "position: absolute">
<script language="javascript">
if (AC_FL_RunContent == 0) {
alert("This page requires AC_RunActiveContent.js.");
} else {
AC_FL_RunContent(
...
); //end AC code
}
</script>
<noscript>
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="430" height="200" id="bar" align="right">
<param name="allowScriptAccess" value="sameDomain" />
<param name="allowFullScreen" value="false" />
<param name="movie" value="bar.swf" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><param name="bgcolor" value="#000000" />
</object>
</noscript>
</div>
A: You might have to set a width and height on your as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Does anyone have experience with PyS60 mobile development I am in the position of having to make a technology choice early in a project which is targetted at mobile phones. I saw that there is a python derivative for S60 and wondered whether anyone could share experiences, good and bad, and suggest appropriate IDE's and emulators.
Please don't tell me that I should be developing on Windows Mobile, I have already decided not to do that so will mark those answers down.
A: PyS60 -- its cool :)
I worked quite a lot on PyS60 ver 1.3 FP2. It is a great language to port your apps on
Symbian Mobiles and Powerful too. I did my Major project in PyS60, which was a GSM locator(its not the latest version) app for Symbian phones.
There is also a very neat py2sis utility which converts your py apps to portabble sis apps that can be installed on any Sumbian phones. The ease of use of Python scripting laanguage and a good set of warapped APIs for Mobile functions just enables you to do anything very neatly and quickly.
The latest Video and Camera APIs let you do neary everything that can be done with the phone. I'd suggest you few very good resources to start with
*
*Forum Nokia
*Nokia OpenSource Resource
center
*A very good tutorial (for beginners)
Just access these, download the Emulator, and TAKE OFF for a ride with PyS60. M sure you'll love it.
P.S. : as the post is so old, I believe u must already be either loving it or finished off with it. But I just cudn't resist answering. :)
A: Have you checked out the Mobile Python Book?
This practical hands-on book effectively teaches how to program your own powerful and fun applications easily on Nokia smartphones based on Symbian OS and the S60 platform.
(source: mobilenin.com)
A: I've just started to look into this myself. I've purchased the Mobile Python book above. It looks good so far.
This site has a few tutorials as well:
http://croozeus.com/tutorials.htm
I'm using putools to code/sync over bluetooth from linux:
http://people.csail.mit.edu/kapu/symbian/python.html
There are advantages/disadvantages to the python dev on S60. Obviously, using Python is a major plus. There are some extra tricks you need in order to get your app built into a distributed form where you don't need to require the end user to first go download the python runtime for their phone.
The other disadvantage is simply in UI. You have three forms of ui available via the appuifw API. Let's say you want to draw images on the screen as well as have a text entry field in the ui, you really can't. You'll have to split the ui into parts that fit what the python api gives you.
As for IDE/Emulator, I'm just using VIM on Ubuntu with the bluetooth sync tools in putools. I've seen that you can get the C++ or Java environments, and then use the emulators in them, but not seen how it works since it seems to be a windows only option at this point.
A: I've seen here a mobile IDE for pyS60..
http://circuitdesolator.blogspot.com/2010/12/ped-mobile-phyton-ide-for-pys60.html
It's called PED and i've been using it in the past months..
A: I've written a calculator, that I'd like to have, and made a simple game.
I wrote it right on the phone. I was writing in text editor then switched to Python and ran a script. It is not very comfortable, but it's ok. Moreover, I was writing all this when I hadn't PC nearby.
It was a great experience!
A: I have some J2ME experience and now I decided to write a couple of useful apps for my phone so I decided to use PyS60 to study Python by the way:)
Some things I don't like about the platform are:
*
*You can't invoke any graphical functions (module appuifw) from non-main thread.
*Python script model is not well-suited for ui applications because the script must contain explicit while loop or semaphore to prevent main thread from exit
*There function sys.exit() is not available.
Again, I'm a newbie to PyS60 so if the issues given above do have nice workarounds don't hesitate to write them as comments. I would be very grateful.
A: There is a nice little IDE called PED for S60 phones which gives you some extra features and makes it easier to code. It's not really that advanced yet, but it's better than manually switching between text editor and python all the time.
HTH
Kage
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Problems with shutting down JBoss in Eclipse if I change JNDI port 1st phase
I have a problem shutting down my running JBoss instance under Eclipse since I changed
the JNDI port of JBoss. Of course I can shut it down from the console view but not with
the stop button (it still searches JNDI port at the default 1099 port). I'm looking
forward to any solutions. Thank you!
Used environment:
*
*JBoss 4.0.2 (using default)
*Eclipse 3.4.0. (using JBoss Tools 2.1.1.GA)
Default ports: 1098, 1099
Changed ports: 11098, 11099
I changed the following part in jbosspath/server/default/conf/jboss-service.xml:
<!-- ==================================================================== -->
<!-- JNDI -->
<!-- ==================================================================== -->
<mbean code="org.jboss.naming.NamingService"
name="jboss:service=Naming"
xmbean-dd="resource:xmdesc/NamingService-xmbean.xml">
<!-- The call by value mode. true if all lookups are unmarshalled using
the caller's TCL, false if in VM lookups return the value by reference.
-->
<attribute name="CallByValue">false</attribute>
<!-- The listening port for the bootstrap JNP service. Set this to -1
to run the NamingService without the JNP invoker listening port.
-->
<attribute name="Port">11099</attribute>
<!-- The bootstrap JNP server bind address. This also sets the default
RMI service bind address. Empty == all addresses
-->
<attribute name="BindAddress">${jboss.bind.address}</attribute>
<!-- The port of the RMI naming service, 0 == anonymous -->
<attribute name="RmiPort">11098</attribute>
<!-- The RMI service bind address. Empty == all addresses
-->
<attribute name="RmiBindAddress">${jboss.bind.address}</attribute>
<!-- The thread pool service used to control the bootstrap lookups -->
<depends optional-attribute-name="LookupPool"
proxy-type="attribute">jboss.system:service=ThreadPool</depends>
</mbean>
<mbean code="org.jboss.naming.JNDIView"
name="jboss:service=JNDIView"
xmbean-dd="resource:xmdesc/JNDIView-xmbean.xml">
</mbean>
Eclipse setup:
About my JBoss Tools preferences:
I had a previous version, I got this problem, I read about some bugfix in JbossTools, so updated to 2.1.1.GA. Now the buttons changed, and I've got a new preferences view, but I cannot modify anything...seems to be abnormal as well:
Error dialog:
The stacktrace:
javax.naming.CommunicationException: Could not obtain connection to any of these urls: localhost:1099 [Root exception is javax.naming.CommunicationException: Failed to connect to server localhost:1099 [Root exception is javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]]]
at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1385)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:579)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:572)
at javax.naming.InitialContext.lookup(InitialContext.java:347)
at org.jboss.Shutdown.main(Shutdown.java:202)
Caused by: javax.naming.CommunicationException: Failed to connect to server localhost:1099 [Root exception is javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]]
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:254)
at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1370)
... 4 more
Caused by: javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:228)
... 5 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
at java.net.Socket.connect(Socket.java:452)
at java.net.Socket.connect(Socket.java:402)
at java.net.Socket.<init>(Socket.java:309)
at java.net.Socket.<init>(Socket.java:211)
at org.jnp.interfaces.TimedSocketFactory.createSocket(TimedSocketFactory.java:69)
at org.jnp.interfaces.TimedSocketFactory.createSocket(TimedSocketFactory.java:62)
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:224)
... 5 more
Exception in thread "main"
2nd phase:
After creating a new Server in File/new/other/server, it did appear in the preferences tab. Now the stop button is working (the server receives the shutdown messages without any additional modification of the jndi port -- there is no opportunity for it now) but it still throws an error message, though different, it's without exception stack trace: "Server JBoss 4.0 Server failed to stop."
A: Here is a detailed fix for this problem:
The Eclipse WTP server connector won't shut down JBoss when the jndi port is remapped.
This is because the default server connector profiles don't use their own alias for the jndiPort. This problem is also discussed at eclipse.org:
http://www.eclipse.org/forums/index.php?t=msg&goto=489439&S=0db4920aab0a501c80a626edff84c17d#msg_489439
The solution comes from the .serverdef files in eclipse:
<eclipse>\plugins\org.eclipse.jst.server.generic.jboss_1.5.105.v200709061325\servers\jboss*.serverdef
They declare an xml property for the jndi port:
<property id="jndiPort"
label="%jndiPort"
type="string"
context="server"
default="1099" />
This simply needs to be used where the serverdef has the STOP command coded:
So this:
<stop>
<mainClass>org.jboss.Shutdown</mainClass>
<workingDirectory>${serverRootDirectory}/bin</workingDirectory>
<programArguments>-S</programArguments>
<vmParameters></vmParameters>
<classpathReference>jboss</classpathReference>
</stop>
becomes this:
<stop>
<mainClass>org.jboss.Shutdown</mainClass>
<workingDirectory>${serverRootDirectory}/bin</workingDirectory>
<programArguments>-s jnp://${serverAddress}:${jndiPort}</programArguments>
<vmParameters></vmParameters>
<classpathReference>jboss</classpathReference>
</stop>
The philosophy for this can be verified by comparison to the definition for the jndi connection:
<jndiConnection>
<providerUrl>jnp://${serverAddress}:${jndiPort}</providerUrl>
<initialContextFactory>org.jnp.interfaces.NamingContextFactory</initialContextFactory>
<jndiProperty>
<name></name>
<value></value>
</jndiProperty>
</jndiConnection>
Credit for the inspiration for this general case fix goes to: Moisa Laurentiu Florin. It was their contribution that got me to look for a way of substituting in the ${jndiPort} instead of a hard coded value.
This fix corrects both plain Eclipse WTP server connector. I'm still investigating the JBOss IDE connector
A: Open jboss-path\bin\shutdown.jar
example: jboss-4.2.3.GA\bin\shutdown.jar
and open jboss-path\bin\shutdown.jar\jndi.properties
and change
java.naming.provider.url=jnp://localhost:1099 to java.naming.provider.url=jnp://localhost:11099
A: OK, what you have to do is File->New->Other->Server, and set up your JBoss server there. It will then appear in Preferences->JBossTools->Servers.
Convoluted.
A: In MyEclipse server configuration, you find the field "Optional Shutdown Argument", which is filled with the default value
--shutdown
Change it to
-s jnp://localhost:11099 --shutdown
Edited:
Sorry, this answer is related to MyEclipse. However, there must be some place where you can specify the JBoss shutdown command in your environment as well.
Maybe you take a look at the "Run..." configurations?
A: you should modify in the file "/home/fmoisa/workspace/eclipse/plugins/org.eclipse.jst.server.generic.jboss_1.5.206.v20090115/servers/jboss42.serverdef" this:
org.jboss.Shutdown
${serverRootDirectory}/bin
-S
-Djboss.boot.loader.name=shutdown.bat
jboss.shutdown
to this:
org.jboss.Shutdown
${serverRootDirectory}/bin
-S -sjnp://localhost:11099
-Djboss.boot.loader.name=shutdown.bat
jboss.shutdown
gl all ;)
A: Use the server adapter provided by JBoss tools and not the one that comes default from Eclipse WTP.
Then you can simply double click on the server and you can edit the JNDI port (which btw. is automatically picked up from the XML configuration if you don't do any thing). You can also do the trick about setting the JNDI port via command line arguments in the Launch Configuration but that is more trouble than just setting the port values.
A: This was changed in JBoss 6.0.0M3.
The stop command is now:
"- s service:jmx:rmi:///jndi/rmi://localhost:1090/jmxrmi"
Note that the port also changed: It is no longer the JNDI port at 1099, but RMI/JMX port 1090. So, you will need another config parameter in the server definition.
I don't know whether the "JNDI port" parameter is required at all for JBoss 6.0.0M3 servers.
I have a modified eclipse plugin at http://www.cs.hs-rm.de/~knauf/public/ which contains a server definition for 6.0.0M3 including this change. This site also links to a JBoss forum thread with more details about this change.
Best regards
Wolfgang Knauf
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Create destinations for all bookmarks in a PDF file with iText API I'd like to write some (java) code that takes a PDF document, and creates named destinations from all of the bookmarks. I think the iText API is the easiest way of doing this, but I have never used the API before.
How would you go about writing this sort of code with the iText API? Can iText do the parsing needed to manipulate existing PDFs by itself? The kind of manipulations I am thinking of are:
*
*Open,
*Find bookmarks,
*Create destinations,
*Save,
*Close.
Or is there a different API that would be better?
A: Followup: I submitted a patch to iText a few months ago (it has now been accepted and is part of HEAD) that adds text parsing capabilities to iText. PdfBox (mentioned below) has (had?) problems with reading newer PDFs that use xref streams instead of the older xref table format.
Another library that is very good at parsing existing PDF files is PdfBox It can also be used for modifying an existing PDF. FYI - this is the text parser that Lucene uses.
I will also mention that iText does have the ability to parse a PDF file, it's just not great at parsing the text content on each page. If you are looking at accessing the PDF higher level constructs (Dictionaries, etc...) that are used for storing bookmarks, etc... and you don't mind getting your hands a little dirty with reading the PDF spec, you can absolutely do what you are asking about (we do it quite a bit ourselves).
The PDF Spec is big, but readable for the most part, and you don't have to worry about the bulk of it (which is geared towards actual page content and rendering) if all you are trying to do is extract bookmarks.
A: I'll just warn you up front that you may be disappointed with this. iText isn't really intended to be used as a parser. It's really more for creating entirely new PDF documents, but you can take a whack at it.
To start, using iText, you won't be able to modify the existing PDF document. What you can do, though, is to make a copy with the additional features that you want. (If somebody else knows better, please let me know, this drives me crazy.)
What you will want to do is create a PdfReader object from an input stream on your source file. Then create a PdfCopy object (which is just an extended PdfWriter that makes getting data from an existing source more convenient) for your destination.
As far as I can tell, the bookmarks cannot be obtained from iText at all. Another library may be needed. I think jpedal may have the ability to extract them (it can get them as an XML document, which you may then have to parse to get what you want.) However you get them, you can then add them to a java.util.List, and set that list as outline on the PDFCopy. The bookmarks themselves are just HashMaps with a particular set of keys. I'm not sure what all of the values are, but they include "Title", "Action" (which seems to be where you'd specify that this is a named destination, though I don't know what that value would be), and "URI" (which is used if this is an external link -- I suspect that this would specify the name of the named destination that you're linking to). Again, the specifics are hard to find.
Then iterate over the pages of the reader, importing each page to the PdfCopy. this page may help you.
Sorry I'm not more helpful to you. Good luck.
P.S. If anybody else knows of a better tool that's either (L)GPL or BSD licensed, I'd love to hear about it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Code syntax formatter for posting code on webpages Is there a utility that will generate html or css for blocks of code (.net c#) when you post it on a website?
I have seen several websites with very nicely formatted code and I dont believe they do this manually.
A: Google prettify -
http://code.google.com/p/google-code-prettify/
A: I prefer Syntax Highlighter implementations (I'm using Wordpress plugin implementation for my blog).
Advantages
*
*It is based on JavaScript and does
not care about what you have on the
server.
*Posts with this formatting display
properly on different RSS feeds and
can be copied to clipboard.
*It is trivial to extend syntax
rules. I'm using that to highlight
custom operators in Boo-based DSL (see sample post)
*Multiple languages are supported
out-of-the-box
(source: googlecode.com)
A: CopySourceAsHtml is an add-in for Microsoft Visual Studio 2005 that allows you to copy source code, syntax highlighting, and line numbers as HTML.
http://copysourceashtml.codeplex.com
It's highly configurable, and works much better than the download page would make you expect! Don't know if there is something similar for VS 2008
If you don't have the ability to add the google prettifier CSS reference, this would be a better way to go, as what you get is a complete HTML with the required style. I use it all the time on our developers wiki, and loving it.
A: You can get JavaScript syntax-highlighting scripts, such as this one by Dean Edwards.
This is also a jQuery version apparently based on it which looks good.
A: An even better solution, if you don't want to bother installing anything, is to just use the little web app I wrote called BlogTrog CodeWindow:
http://www.blogtrog.com
It's easy to use. Just paste your code and embed the results.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: C# open source NMEA parser Am looking for C# open source NMEA parser.
A: Well, I'm not familiar with it myself, but some quick searches show one on CodeProject, which links to 2 other such, here and here. Any of those help?
A: check out sharpGPS . there are several other gps and nmea related projects o codeplex too
A: FWIW, it's not hard (10-40 LOC) to parse the basic ones your self. If you find you need to do this, here is a link with some useful info.
A: One more (support several devices)
http://www.codeproject.com/Articles/279647/NMEA-sentence-parser-builder
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Using PHP to take the first line of a CSV file and create a MySQL Table with the data I am trying to take a rather large CSV file and insert it into a MySQL database for referencing in a project. I would like to use the first line of the file to create the table using proper data types and not varchar for each column. The ultimate goal is to automate this process as I have several similar files but the each has different data and a different amount of "columns" in CSV files. The problem that I am having is gettype() is returning 'string' for each column instead of int, float and string as I would like it to.
Platform is PHP 5, OS is ubuntu 8.04
here is my code so far:
<?php
// GENERATE TABLE FROM FIRST LINE OF CSV FILE
$inputFile = 'file.csv';
$tableName = 'file_csv';
$fh = fopen($inputFile, 'r');
$contents = fread($fh, 5120); // 5KB
fclose($fh);
$fileLines = explode("\n", $contents); // explode to make sure we are only using the first line.
$fieldList = explode(',', $fileLines[0]); // separate columns, put into array
echo 'CREATE TABLE IF NOT EXISTS `'.$tableName.'` ('."<br/>\n";
for($i = 0; $i <= count($fieldList); $i++)
{
switch(gettype($fieldList[$i])) {
case 'integer':
$typeInfo = 'int(11)';
break;
case 'float':
$typeInfo = 'float';
break;
case 'string':
$typeInfo = 'varchar(80)';
break;
default:
$typeInfo = 'varchar(80)';
break;
}
if(gettype($fieldList[$i]) != NULL) echo "\t".'`'.$i.'` '.$typeInfo.' NOT NULL, --'.gettype($fieldList[$i]).' '.$fieldList[$i]."<br/>\n";
}
echo ' PRIMARY KEY (`0`)'."<br/>\n";
echo ') ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;';
Example First line:
1,0,0,0,0,0,0,0,0,0,0,0,0.000000,0.000000,0,0,0,,0,0,1,0,50,'Word of Recall (OLD)',
A: Building on Nouveau's code you could do this
for($i = 0; $i <= count($fieldList); $i++)
{
if (is_numeric($fieldList[$i]))
{
if (strpos($fieldList[$i],'.') !== false){
$fieldList[$i] = (int)$fieldList[$i];
}else{
$fieldList[$i] = (float)$fieldList[$i];
}
}
switch(gettype($fieldList[$i])) {
case 'integer':
$typeInfo = 'int(11)';
break;
case 'float':
case 'double':
$typeInfo = 'float';
break;
case 'string':
$typeInfo = 'varchar(80)';
break;
default:
$typeInfo = 'varchar(80)';
break;
}
if(gettype($fieldList[$i]) != NULL) echo "\t".'`'.$i.'` '.$typeInfo.' NOT NULL, --'.gettype($fieldList[$i]).' '.$fieldList[$i]."<br/>\n";
}
That works, note the addition of "case 'double':" in the switch, but there may be a better way to do the int/float check as they would only work with standard uk/us numbers.
A: Try casting the value and comparing it with the original one:
define('DECIMAL_SEPARATOR', '.');
switch ($fieldList[$i])
{
case (string)(int)$fieldList[$i]:
$typeInfo = (strpos($fieldList[$i], DECIMAL_SEPARATOR) === false) ? 'int(11)' : 'float';
break;
case (string)(float)$fieldList[$i]:
$typeInfo = 'float';
break;
default:
$typeInfo = 'varchar(80)';
break;
}
Additionaly, check for the presence of decimal separator in the first case for numbers that are round, yet they have the decimal fraction part.
A: <?php
// GENERATE TABLE FROM FIRST LINE OF CSV FILE
$inputFile = 'file.csv';
$tableName = 'file_csv';
$fh = fopen($inputFile, 'r');
$contents = fread($fh, 5120); // 5KB
fclose($fh);
$fileLines = explode("\n", $contents);
$fieldList = explode(',', $fileLines[0]);
echo 'CREATE TABLE IF NOT EXISTS `'.$tableName.'` ('."<br/>\n";
for($i = 0; $i <= count($fieldList); $i++)
{
if(strlen($fieldList[$i]) == 0) $typeInfo = 'varchar(80)';
if(preg_match('/[0-9]/', $fieldList[$i])) $typeInfo = 'int(11)';
if(preg_match('/[\.]/', $fieldList[$i])) $typeInfo = 'float';
if(preg_match('/[a-z\\\']/i', $fieldList[$i])) $typeInfo = 'varchar(80)';
echo "\t".'`'.$i.'` '.$typeInfo.' NOT NULL, -- '.gettype($fieldList[$i]).' '.$fieldList[$i]."<br/>\n";
}
echo ' PRIMARY KEY (`0`)'."<br/>\n";
echo ') ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;';
A: Using regular expressions will give you a flexible solution. If you need to detect date fields then this is the way to go.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to generate pdf files _with_ utf-8 multibyte characters using Zend Framework I've got a "little" problem with Zend Framework Zend_Pdf class. Multibyte characters are stripped from generated pdf files. E.g. when I write aΔ
bcΔdeΔ it becomes abcd with lithuanian letters stripped.
I'm not sure if it's particularly Zend_Pdf problem or php in general.
Source text is encoded in utf-8, as well as the php source file which does the job.
Thank you in advance for your help ;)
P.S. I run Zend Framework v. 1.6 and I use FONT_TIMES_BOLD font. FONT_TIMES_ROMAN does work
A: Zend_Pdf supports UTF-8 in version 1.5 of Zend Framework. However, the standard PDF fonts support only the Latin1 character set. This means you can't use Zend_Pdf_Font::FONT_TIMES_BOLD or any other "built-in" font. To use special characters you must load another TTF font that includes characters from other character sets.
I use Mac OS X, so I tried the following code and it produces a PDF document with the correct characters.
$pdfDoc = new Zend_Pdf();
$pdfPage = $pdfDoc->newPage(Zend_Pdf_Page::SIZE_LETTER);
// load TTF font from Mac system library
$font = Zend_Pdf_Font::fontWithPath('/Library/Fonts/Times New Roman Bold.ttf');
$pdfPage->setFont($font, 36);
$unicodeString = 'aΔ
bcΔdeΔ';
$pdfPage->drawText($unicodeString, 72, 720, 'UTF-8');
$pdfDoc->pages[] = $pdfPage;
$pdfDoc->save('utf8.pdf');
See also this bug log: http://framework.zend.com/issues/browse/ZF-3649
A: I believe Zend_Pdf got UTF-8 support in 1.5 - What version of Zend Framework are you running?
Also - what font are you trying to render with? Have you tried alternate fonts?
A: Have you made sure that you are setting the character encoding as this example from the manual?
// Draw the string on the page
$pdfPage->drawText($unicodeString, 72, 720, 'UTF-8');
If you're stuck into having to use a bold font, maybe try one of the other bold fonts?
Zend_Pdf_Font::FONT_COURIER_BOLD
Zend_Pdf_Font::FONT_TIMES_BOLD
Zend_Pdf_Font::FONT_HELVETICA_BOLD
A: ZF v. 1.6, TIMES_BOLD (as I understand thats the only way to make text bold?)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Why use Glassfish instead of Apache? What's it strengths and weaknesses? Sorry for my ignorance here, but when I hear the word webserver, I immediately imagine Apache, although I know people use Microsoft's IIS too. However since I've been hanging out here at Stackoverflow I've noticed lots of people use Glassfish.
Which made me wonder, why would I want to use Glassfish (in the sense that I'm interested, but I don't really understand why it might make my life easier). From what I read it's Sun's open-source derivate of Apache's Tomcat, thus I imagine it's a good (or great) quality product. But since I don't know its strengths and weaknesses, I don't know when it would be wise to choose Glassfish over another server. Could anyone elaborate ?
A: GlassFish is an Application Server which can also be used as a Web Server (Http Server).
A web Server means: Handling HTTP requests (usually from browsers).
A Servlet Container (e.g. Tomcat) means: It can handle servlets & JSP.
An Application Server (e.g. GlassFish) means: It can manage Java EE applications (usually both servlet/JSP and EJBs).
You should use GlassFish for Java EE enterprise applications.
A: The need for a seperate Web server is mostly needed in a production environment. You would normally find a Application server to be suffice most of your development needs. A web server is capable of holding larger number of active sessions and connections, thus providing the necessary balance without performance costs.
Stick to a simple web server if you are only working with servlets/jsps. It is also to be noted that in a netbeans environment, glassfish has better support than other App servers. In the context of eclipse though, WSAD and JBoss seem to the preferred options.
A: Glassfish will soon release the modular kernel.
This means that the containers you need start up and shutdown as you need them. I.e no EAR deployed, EJB container won;t start up. This seems to have made it very good for development as it can start and stop very quickly. This takes it a lot closer to development environments like Rails (where redeployment is a massive part of your development)
A: I have used GlassFish server for developing Web Services.
It provides a very interactive Admin Console where admin can test the Web Services.
I really find it helpful while developing Web Services
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "62"
} |
Q: How can I change the 259 char limit inside WinForms Treeview LabelEdit? My VB.Net Winforms app is a tool to allow hierarchical data to be edited in a tree, then stored in a database. I am using a treeview control.
Content is drag-dropped from other documents onto the treenodes, or the nodes can be edited directly.
if I edit the database field directly, and enter a bit of content (a thousand characters long or more!), the treeview will happily display it.. but, when I drag drop, the data is being truncated at 259 characters. If I edit directly, the maximum edit 'window' is also 259 characters.
259 seems like a really strange number to stop at, so I am wondering - where does this size come from, and can I change it programmatically?
A: I would recommend taking a different approach. You probably don't want to show your users all 10000 or characters of a document anyway in their TreeNode, so create an custom data storage class
with properties like Name and Content to store the document and it's title. Add your content to the Content property and a title or something meaningful to the Name property then add the object to the Tag property of the TreeNode object.
Dim mynode As New TreeNode
Dim SomeBigCustomObject as New MyContentStorageObject(name,content)
mynode.Text = SomeBigCustomObject.Name
mynode.Tag = SomeBigCustomObject
TreeView1.Nodes.Add(mynode)
You can then get the object back when a node is selected (using the AfterSelect event) like this:
dim ContentStorageObject As MyContentStorageObject = CType(e.Node.Tag, MyContentStorageObject)
dim content as string = ContentStorageObject.Content
If you need to edit the text, I would then either pop up a editor dialog or send the data that is stored in Content to an textbox on your form for editing. Your users will probably appreciate not having to type it all in the treeview node editor.
That's a real quick and dirty explanation, but the essence is "use the .Tag property". Good luck.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Creating a new rrd database based on an existing one I have some old rrdtool databases, for which the exact creation recipe has long been since lost. I need to create a new database with the same characteristics as the current ones. I've dumped a couple of old databases and pored over the contents but I'm not sure how to interpret the metadata. I think it appears in the following stanzas
<cf> AVERAGE </cf>
<pdp_per_row> 360 </pdp_per_row> <!-- 1800 seconds -->
<xff> 5.0000000000e-01 </xff>
There are four such stanzas, which correspond to the way I recall the round-robin cascading was set up. Has anyone already done this, or can give me pointers as to how to clone a new empty rrd database from an existing one? Or show me where I missed this in the documentation.
A: I use the command rrdcreate. It can create a new rrd based in an existing one. The -t parameter indicate a existing rrd as template.
rrdcreate new.rrd -t existing.rrd
A: rrdtools' rrdinfo is your friend!
It will tell you how the rrd file's data source(s) and archive(s) were created. Example
$ rrdtool info random.rrd
filename = "random.rrd"
rrd_version = "0001"
step = 300
last_update = 955892996
ds[a].type = "GAUGE"
ds[a].minimal_heartbeat = 600
ds[a].min = NaN
ds[a].max = NaN
ds[a].last_ds = "UNKN"
ds[a].value = 2.1824421548e+04
ds[a].unknown_sec = 0
ds[b].type = "GAUGE"
ds[b].minimal_heartbeat = 600
ds[b].min = NaN
ds[b].max = NaN
ds[b].last_ds = "UNKN"
ds[b].value = 3.9620838224e+03
ds[b].unknown_sec = 0
rra[0].cf = "AVERAGE"
rra[0].pdp_per_row = 1
rra[0].cdp_prep[0].value = nan
rra[0].cdp_prep[0].unknown_datapoints = 0
rra[0].cdp_prep[1].value = nan
rra[0].cdp_prep[1].unknown_datapoints = 0
A: You can try use the clone script described here. It's very basic but it works for simple rrd files. I used it to figure out a schema that was generated by munin. I needed to insert old data into munin so I reverse engineered the schema, set the --start to a date prior to the start of my old data and re-imported data into the rrd.
$ python rrdinfo-parser.py -f test.rrd
rrdtool create test.rrd --start 920804400 --step 300 \
DS:speed:COUNTER:600:U:U \
RRA:AVERAGE:0.5:1:24 \
RRA:AVERAGE:0.5:6:10 \
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Flush disk write cache When the policy for a disk in Windows XP and Vista is set to enable write caching on the hard disk, is there a way to flush a file that has just been written, and ensure that it has been committed to disk?
I want to do this programmatically in C++.
Closing the file does perform a flush at the application level, but not at the operating system level. If the power is removed from the PC after closing the file, but before the operating system has flushed the disk write cache, the file is lost, even though it was closed.
A: .NET FileStream.Flush() will NOT flush the Windows cache for that file content; Flush() only flushes the .NET internal file buffer. In .NET 4.0, Microsoft fixed the problem by adding an optional parameter to Flush() which if set true causes FlushFileSystemBuffers to be called. In .NET 3.5 and below your only choice is to call FlushFileBuffers via pinvoke. See MSDN'sFileStream.Flush community comment for how to do this.
A: You should not fix this at the time you close the file. Windows will cache, unless you open the file passing FILE_FLAG_WRITE_THROUGH to CreateFile().
You may also want to pass FILE_FLAG_NO_BUFFERING; this tells Windows not to keep a copy of the bytes in cache.
This is more efficient than FlushFileBuffers(), according to the CreateFile documentation on MSDN.
See also file buffering and file caching on MSDN.
A: You haven't specified the development environment, so:
.Net
IO streams have a .Flush method that does what you want.
Win32 API
There is the FlushFileBuffers call, which takes a file handle as argument.
EDIT (based on a comment from the OA): FlushFileBuffers does not need administrative privileges; it does only if the handle passed to it is the handle for a volume, not for a single file.
A: You should also note, that your data might not get flushed to the actual disk, even when invoking a flush method of your frameworks API.
Calling the flush method will only tell the kernel to flush its pages to disk. However, if you have the disk write-cache turned on, it is allowed to delay the actual writing process indefinitely.
In order to ensure that your data gets written to the physical layer you have to turn of the write cache in your operating system. This most often comes with a performance penalty up to one or two orders of magnitude when dealing with a lot of small io-operations.
Battery based support (UPS) or disks that accept commands to flush the disk write-cache are another option to deal with this problem.
A: From the microsoft documents you would use _flushall and link in COMMODE.OBJ to ensure that all buffers were committed to disk.
A: See here: https://jeffpar.github.io/kbarchive/kb/066/Q66052/
When you initially open your file using fopen, include the "c" mode option as the LAST OPTION:
fopen( path, "wc") // w - write mode, c - allow immediate commit to disk
Then when you want to force a flush to disk, call
_flushall()
We made this call before calling
fclose()
We experienced the exact issue you described and this approach fixed it.
Note that this approach does NOT required Administrative rights, which FlushFileBuffers does require, as others have mentioned.
From that above site:
"Microsoft C/C++ version 7.0 introduces the "c" mode option for the fopen()
function. When an application opens a file and specifies the "c" mode, the
run-time library writes the contents of the file buffer to disk when the
application calls the fflush() or _flushall() function. "
A: You can open/create the file with the FileOptions.WriteThrough flag, which will cause the file to write directly into the disk, bypassing any caches.
E.g.
var file = File.Open(
"1.txt",
new FileStreamOptions
{
Options = FileOptions.WriteThrough
});
// - OR -
var file = new FileStream(
"1.txt",
FileMode.Create,
FileAccess.Write,
FileShare.None,
4096,
FileOptions.WriteThrough)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Open port 8080 (APACHE) in ISA Server 2006 Im using APACHE as my web server and using port 8080. Ive create a site called
(e.g. http://test.domain.com:8080). I have a Firewall (ISA Server 2006).
How am I suppose to establish "http://test.domain.com:8080"in ISA Server?
Will I just add "http://test.domain.com" as its public name or with this "http://test.domain.com:8080"?
any suggestion will be appreciated.
Thanks. :D
A: Create a rule and related listner rule to listen on port 80 for the domain test.domain.com
Then on the bridging tab of the rule, redirect to port 8080.
(That's if you want users to use port 80 rather then 8080).
It's public name would be test.domain.com
A: Thanks a lot Bravax!
Here's the step Ive done so far... first Ive created a web publishing rule, its public name
was (e.g. test.domain.com) then after establishing new web rule I went to its properties and
go to the bridging tab... I change the "Redirect request to http port" from 80 to 8080.
Then I created an "Access Rule", opening the "Http8080" protocol.
Did I made the correct setuo?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to use the LoginView control in combitation with the server session in ASP.NET? Is it possible to use the LoginView control in combitation with the server session in ASP.NAT?
A: Yes, it can use the session automatically. You can just set a username field or authenticated field in session so you know. Like Session("username") = curUser
Or what are you looking to do?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to pass mouse events to applications behind mine in C#/Vista? I am writing a very specialized app in C# that floats as a mostly transparent window over the entire desktop. I want to be able to create and pass mouse events to applications behind mine, and have them appear to operate "normally", responding to those events. It would also be preferable if the window manager could respond.
I am not a Windows guru, and am unsure of how to best accomplish this.
From this page:
http://bytes.com/forum/thread270002.html
it would appear that mouse_event would be good, except that since my app is floating over everything else, I'm guessing my generated events would never make it to the other apps underneath.
It seems the alternative is SendMessage, but that requires a fair amount of manual manipulation of windows, and the mouse events generated aren't "authentic."
Any thoughts on the best way to approach this?
A: Sounds like you want to do something like filtering user input.
Maybe you just need an keyboard/mouse hook.
You maybe want to take a look at the windows API call SetWindowsHookEx.
There should also be enough samples how to do that in C# available, the first thing i found was this link (maybe not the best article but should give you the idea).
A: After looking at System hooks and other low level solutions I found a much simpler method.
First, set the TransparencyKey and BackColor of the form to be the same. This didn't make any visual difference to me as my form was visually transparent already, but this will help in letting mouse events through.
Second, the following code will let mouse events "fall" through your form.
protected override CreateParams CreateParams
{
get
{
CreateParams createParams = base.CreateParams;
createParams.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT
return createParams;
}
}
Lastly, set TopMost to be true.
Your form will now float on top of everything visually, but will give up focus to all other apps.
A: If you disable the control and return you're able to pass the MouseDown event to the parent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I restore a windows size and position in a wxRuby app? Does anyone know of any sample code for restoring a window's position and size in wxRuby?
A: YAML would be a better choice to serialize the prefs, but here I just store a comma-delimited string in the prefs.txt file.
require "rubygems"
require "wx"
include Wx
class MyApp < App
def on_init
left, top, width, height = *prefs
position = Point.new(left, top)
size = Size.new(width, height)
main = Frame.new(nil, -1, "Title", position, size)
#when the window closes, save the location
main.evt_close do |event|
save_window_location(event.get_event_object)
event.skip
end
main.show()
end
private
def save_window_location(frame)
self.prefs = [
frame.position.x,
frame.position.y,
frame.size.width,
frame.size.height
]
end
#load the prefs and return them as an array
def prefs
location = []
begin
location = File.read(prefs_filename).split(',').map{|s| s.to_i}
rescue Exception
#file didn't exist, or read failed
end
location = [100, 100, 300, 300] if location.size != 4
return location
end
#save the prefs as a comma-delimited string
def prefs=(prefs_array)
File.open(prefs_filename, 'w') do |prefs_file|
prefs_file << prefs_array.join(",")
end
end
def prefs_filename
'prefs.txt'
end
end
MyApp.new.main_loop
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: TFS: comparing shelveset files with local version When viewing files in a shelveset, I would like the option of comparing the files to my current local version. Unfortunately, the only options available are "With Unmodified", "With Workspace" (I guess this one would be the answer, if it wasn't disabled) and "With Latest".
Any ideas?
A: In VS2015 Update 3:
*
*Go to Pending Changes > Actions > Find Shelvesets
*Select the Shelveset you want to compare to, right click and choose View
Shelveset Details
*Right Click on the file, choose Open
*Right Click on the tab, choose Copy Full Path
*In Solution Explorer, right click file, choose Compare...
*Paste the full path into Source Path and click OK
A: Export Shelveset to a local folder using Team Foundation Sidekicks and use file comparison tool to compare with local version.
A: Up to How can I easily diff/compare 2 shelvesets in TFS?
Use VS2013 ShelvesetComparer or VS2012 ShelvesetComparer, shelve local version into another shelveset, then compare between two shelvesets...
Though this will make another unneeded shelveset, and you can't edit local in file compare editor.
A: I don't think that it is possible to compare a shelved version with a local version in Visual Studio, however I'll be very happily corrected on the matter.
A: Although this isn't the ideal way to do it, depending on your comparison tool you may be able to tell it to compare the shelved version to a local version (workspace). I use Beyond Compare, and this allows you to open a file to compare to. So from the shelveset I do a compare to Latest, and then replace the 'latest' with my local workspace version.
Unfortunately I've just checked the built in comparison tool and it doesn't provide this option.
A: Here's a simple hack that works:
*
*Click on 'Unshelve'
*Select proper shelveset
*Click on the 'Details' button
*Right click on the file you wish to compare
*Click on 'View'
*This opens up in your text editor, save it to your desktop or wherever you like.
*Open your file diff program and compare the saved version to your local version.
In a nutshell, save a copy of the shelved version you retrieve from the server and just do a manual compare using your diff tool.
A: I have been looking for a way to do this for quite some time. I wonder how hard it would be to create a vs.net plugin to do this for you.
A: In TFS, create a new (temporary) workspace, and map it onto a new local folder.
get latest version into the new workspace, then unshleve the sheleveset into the new workspace.
This gives you a temporary local copy of the source with the sheleveset applied.
Then change back to the orignal workspace, click on file => source control => compare. Then enter the local folder paths of the original workspace and the new temprary workspace, to compare your original local version with the lcoal shelevest version.
A: This is a little laborious but it does the job:
*
*Right click any file in Solution
Explorer and select 'Unshelve
Pending Changes...' from the context
menu.
*Double click the relevant shelveset in the Unshelve dialog.
*Double click the file that you want to compare. This will open the sheleveset version of the file in notepad.
*Save the file somewhere on your local machine.
*Close all the dialogs.
*Right click the local workspace version of your file in Solution Explorer and select 'Compare' from the context menu.
*Change the target path to that of the file that you saved earlier and click OK.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
} |
Q: How to catch Control-V in C# app? I've tried to override WndProc, but no message show up on paste event.
Then I tried to create custom filter and using method PreFilterMessage I was able to catch message with value 257 (KEYUP event), but that's not enough...
A: You can do this by:
*
*Intercepting the Ctrl+V in KeyDown (or KeyUp) of your form
*Creating a menu in your form that contains a Paste option that has the Ctrl+V shortcut (this would maybe be better since you will have users looking for the options)
*Intercepting the KEYDOWN message like you described in the question and checking whether Ctrl is pressed at that time (I think this is the hardest of all 3).
Personally I would go for using a menu option.
A: Use:
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
MessageBox.Show("Hello world");
}
base.OnKeyDown(e);
}
Make sure your form KeyPreview = true.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to map caller memory in a Windows CE device driver past the end of a call to XXX_IOControl? I'm implementing a ioctl in a Windows CE device driver that takes a pointer to a large chunk of application memory to perform asynchronous I/O initiated through an application call to DeviceIoControl.
When using MapCallerPtr(), the pointer gets unmapped when the XXX_IOControl function returns; when the pointer is used in the IST it is no longer mapped leading to a crash.
What is the best way to map the pointer beyond the end of the call to XXX_IOControl? The application guarantees that the memory will remain valid until it has received an indication from the driver that the driver has finished with it.
This is on Windows CE 5.0.
A: Answering my own question:
In XXX_IOControl, map the pointer using MapPtrToProcess() and save the thread's permissions using GetCurrentPermissions(). In the thread that will use the mapped pointer, call SetProcPermissions() with the saved return value from GetCurrentPermissions(), dereference pointers, and then restore the thread permissions when finished.
DWORD saved_perms = SetProcPermissions(caller_perms);
... Do stuff ...
SetProcPermissions(saved_perms);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you structure your NUnit tests on a large project? I am interested in seeing if I can improve the way we use NUnit in a Visual Studio solution containing 30+ projects.
First, would you have one assembly of tests for every assembly in the solution, or would you try to keep the number of test assemblies down? I started off creating many test assemblies, but I think this is costing us a lot in terms of build time.
Second, what strategy do you use for managing those tests that are long-running, or require special environment configuration? I would like to write an MSBuild script that automates the running of our unit tests, but it needs to skip over the tests that would take too long or would not work on the build machine.
A: To answer your first question:
You can use categories to keep everything organised in a single assembly if that's how you want to go. As to whether it would cut down on build time, I would hazard a guess at perhaps, I don't think it'd be a huge amount overall though.
To answer your second:
You can use categories and the [Explicit] and [Ignore] attribute to tell NUnit which tests to run, and which tests you have to tell it to run before it will. You might also want to look at [Platform] or some of the other attributes, depending on what exactly your requirements on 'environment' are.
For instance, you could add an Explicit tag to all your long running tests. Then you would have to run these tests explicitly, NUnit won't run them automatically. Or add all these tests to a category, then when you run NUnit, tell it to explicitly not run that category.
A: For your case I would put it down to a few options:
*
*Consolidate your existing projects to fewer ones, consequently consolidating corresponding test projects for them - Try to think if you really need 30 projects (e.g., 30 assemblies) or if it is better to simply combine them to ease the number of dependencies and build time.
*Put your tests in their corresponding project - While this may elicit a violent reaction, think about it: considering the huge number of tests involved the overhead of getting a slightly larger assembly might be worth the reduced overhead of managing twice the number of projects you actually need.
*Combine all the unit tests into a few projects - If you're adamant about keeping each assembly clean and separate, you can just opt to combine all the unit tests, probably in terms of relevance with each other.
Consequently you could also make solution configurations that do not include unit tests - if build time is so much of a concern to you. This is especially useful if you're just running tests on demand. If you're using continuous integration, it shouldn't be a problem: you can have multiple CI configurations, some which include building tests, some that do not.
A: This a great question and raises some concerns that I have about managing large set of unit tests for long running, large projects.
My strategy is to have one unit test project for each project in your solution that is business or framework related. Unit tests are poorly suited to testing the UI aspects of a project and I generally leave this to scipted testing. The project is built using a continous integration (CI) server that is fired every time a developer commits a chunk of work. The CI server also runs all of the unit test as well generating unit test coverage statistics. The CI environment uses MSBuild to build the solution.
Over time it is worth assessing whether all of your unit tests are necessary. A lot of the regression testing effort will shift to scripted testing and the overhead of maintaining unit tests can be costly. Ideally I would like all unit tests to be maintained over the life of the project but the maintenance overhead can sometimes be prohibitive. As a rule of thumb unit tests are maintained for business rules and the solution framework but not for UI, reporting or workflow. Obviously this will depend on the particulars of your project.
A: Just as an aside, we find TestDriven.Net to be an excellent VisualStudio add-in front end for NUnit, free for open source use / students.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Calling JS from Applet: MalformedURLException: unknown protocol: javascript I read that you could call JavaScript code from a Java Applet by calling
JApplet.getAppletContext().showDocument( "javascript:alert('Hello World');" );
However, when I do this i get the following error:
java.net.MalformedURLException: unknown protocol: javascript
How do I work around this?
A: I get the same exception as you do because of that the URL class does not accept javascript: as a valid protocol.
There is a workaround though; supply an URLStreamHandler to the URL constructor.
Example:
final URLStreamHandler streamHandler = new URLStreamHandler() {
@Override
protected URLConnection openConnection(URL u)
throws IOException {
return null;
}
};
try {
getAppletContext().showDocument(
new URL(null, "javascript:alert('It works!');", streamHandler));
} catch (MalformedURLException me) {
//log or whatever
}
A: try {
this.getAppletContext().showDocument(new URL("javascript:alert('hello world');"));
}catch(Exception e) {
e.printStackTrace();
}
Works !!
Maybe the browser does not have javascript enabled.. just a guess
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is there a portable equivalent to DebugBreak()/__debugbreak? In MSVC, DebugBreak() or __debugbreak cause a debugger to break. On x86 it is equivalent to writing "_asm int 3", on x64 it is something different. When compiling with gcc (or any other standard compiler) I want to do a break into debugger, too. Is there a platform independent function or intrinsic? I saw the XCode question about that, but it doesn't seem portable enough.
Sidenote: I mainly want to implement ASSERT with that, and I understand I can use assert() for that, but I also want to write DEBUG_BREAK or something into the code.
A: A method that is portable to most POSIX systems is:
raise(SIGTRAP);
A: This seems to be a very good, portable solution to this question:
https://github.com/scottt/debugbreak
The header provided in the repository cited (debugbreak.h) encapsulates MSVC's
__debugbreak,
and
__asm__ volatile("int $0x03");
on i386 and x86_64, and on ARM it implements
__asm__ volatile(".inst 0xe7f001f0");
as well as documenting some workarounds for problems noted in the header for single-stepping past the breakpoint in GDB plus a Python script for extending GDB on those platforms where stepi or cont get stuck. The script adds debugbreak-step and debugbreak-continue to GDB.
A: I just added a module to portable-snippets (a collection of public domain snippets of portable code) to do this. It's not 100% portable, but it should be pretty robust:
*
*__builtin_debugtrap for some versions of clang (identified with __has_builtin(__builtin_debugtrap))
*On MSVC and Intel C/C++ Compiler: __debugbreak
*For ARM C/C++ Compiler: __breakpoint(42)
*For x86/x86_64, assembly: int3
*For ARM Thumb, assembly: .inst 0xde01
*For ARM AArch64, assembly: .inst 0xd4200000
*For other ARM, assembly: .inst 0xe7f001f0
*For Alpha, assembly: bpt
*For non-hosted C with GCC (or something which masquerades as it), __builtin_trap
*Otherwise, include signal.h and
*
*If defined(SIGTRAP) (i.e., POSIX), raise(SIGTRAP)
*Otherwise, raise(SIGABRT)
In the future the module in portable-snippets may expand to include other logic and I'll probably forget to update this answer, so you should look there for updates. It's public domain (CC0), so feel free to steal the code.
A: If you consider assert(x) portable enough, assert(false) seems to be the obvious portable solution to your problem.
A: What about defining a conditional macro based on #ifdef that expands to different constructs based on the current architecture or platform.
Something like:
#ifdef _MSC_VER
#define DEBUG_BREAK __debugbreak()
#else
...
#endif
This would be expanded by the preprocessor the correct debugger break instruction based on the platform where the code is compiled. This way you always use DEBUG_BREAK in your code.
A: GCC has a builtin function named __builtin_trap which you can see here, however it is assumed that code execution halts once this is reached.
you should ensure that the __builtin_trap() call is conditional, otherwise no code will be emitted after it.
this post fueled by all of 5 minutes of testing, YMMV.
A: This looks like an appropriate compat library https://github.com/scottt/debugbreak
A: FWIW, none of these solutions worked on a nRF9160 using the NRF Connect SDK. That's a SEGGER Embedded Studio for ARM (Nordic Edition) environment, using the arm-none-eabi-gcc compiler.
The debug-trap.h, debugbreak.h and __builtin_trap() mentioned in other answers all resulted in "undefined opcode" and a hard-fault (or a debug monitor fault, but the result is the same) and there no useful program counter, stack frame or other debuggable information.
In the end, this alternate did work. I derived it from some other mysterious Nordic library, where it is referred to as NRF_BREAKPOINT:
#if defined(__GNUC__)
__asm__("BKPT 0");
#else
__BKPT(0)
#endif
At build time, it is the __GNUC__ path which gets included, so __asm__("BKPT 0") is all that is required.
A: #define __debugbreak() \
do \
{ static bool b; \
while (!b) \
sleep(1); \
b = false; \
} while (false)
When the process is sleeping, you can attach a debugger to the process, change the variable b to break the loop and do your thing. This code might not work in an optimized build!
A: Instead of using 'normal' debug breaks, why not use one of the following, like a divide by zero:
int iCrash = 13 / 0;
or dereference a NULL pointer:
BYTE bCrash = *(BYTE *)(NULL);
At least this is portable accross many platforms/architectures.
In many debuggers you can specify what action you want to perform on what exceptions so you can act accordingly when one of the above is hit (like pause execution, ala an "int 3" instruction) and an exception is generated.
A: If you are trying to debug a crash-related condition, good old fashioned abort() will give you a call stack on most platforms. Downside is that you can't continue from the current PC, which you probably don't want to do anyway.
http://www.cplusplus.com/reference/cstdlib/abort/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "80"
} |
Q: Is it possible to make git svn "relocate" branch files on checkout? Our svn repository has lots of branches that are branches off of sub-trees. This works OK with svn because I can check out that sub-tree in the correct spot in my working copy. However, if I check out the same branch using git, I get a working copy with only the branch sub-tree. Is it possible to make git relocate the branch so that my working copy structure is identical whether I am on trunk or a branch?
I realize that our svn practices clash with git's philosophy of always working on the whole tree. How do people deal with this?
A: If possible, fix it on the server side: Subversion doesn't copy data when branching (svn copy), it just hardlinks, so there's really no obvious reason to branch out only a subtree.
If that's not feasible, you should have a look at http://help.github.com/subtree-merge/ -- it may do the trick, but I haven't tried it myself. He's basically describing an alternative to git submodules, where you just automatically merge the remote (in this case your Subversion branch) into a subdirectory instead of the root directory of the repository.
A: I've never used svn like this, and if the silence you've gotten is any indication then it's kind of a rare practice. Could you give some rationale for doing things this way, maybe by describing what problem it solves? That way we can better judge what would be an acceptable solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Where can I find sample uses of LWJGL? I have seen the official demos on lwjgl.org but I would like to see some more tutorial level examples.
A: Google "import org.lwjgl" to find lots of examples, as all code that uses LWJGL must contain that string to import parts of the package.
A: If it still does matter: http://nehe.gamedev.net/
All tutorials are ported to LWJGL too.
A: The LWJGL wiki contains several examples with explanations. Since most work in LWJGL directly reflects OpenGL (e.g. 'glBegin()'), you could just look up some OpenGL tutorials.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: What Oracle driver should I install in my MS SQL server to be able to use DTS to copy data from the Oracle server to the MS SQL server? I have an Oracle server (version 9, I believe) and a MS SQL server (version 2000). The MS SQL server is running MS Windows Server 2003.
I would like to use DTS to extract some data from the Oracle server and pour it into the MS SQL server. I'm having problems finding out what driver I should install on my MS SQL server for it to be able to communicate with the Oracle server. (I don't really care if it's ODBC or a "native" Oracle driver.)
When I looked at this a while back I was stunned by the sheer number of different Oracle drivers and versions out there. Any help with a direct link to the exact Oracle driver recommended would be greatly appreciated, and I wouldn't mind any other helpful tips you could provide either. :) (Apart from upgrading the server/OS, that's not going to happen any time soon...)
I understand that it's the Instant Client that I'm being recommended to install, but more specifically for my situation, on the page http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/winsoft.html, are these the two packages I should install?
Version 11.1.0.6.0
Because it's the latest version, and it should be able to connect to Oracle 9.
Instant Client Package - Basic: All files required to run OCI, OCCI, and JDBC-OCI applications
Because "all installations REQUIRE the Basic package", per information at the bottom of the Oracle webpage.
Instant Client Package - ODBC: Additional libraries for enabling ODBC applications
Because I need to use ODBC.
Have I understood this correct?
A: My first choice would be the Instant Client: http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/winsoft.html
Although this was not available for 9i, the 10g client will certainly connect to 9i without any problems, and the 11g probably would also.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I see Debug.WriteLine statements when using TestDriven.Net? I'm trying to use TestDriven.Net not only to test my code, but to call a function on my code whose purpose is to print out the internal state of the code to the Debug window.
Here's a very simplified example of what I'm trying to do..
<TestFixture()> _
Public Class UnitTest
<Test()> _
Public Sub TestDebug()
Dim oClass1 As New Class1
Assert.AreEqual(True, oClass1.IsTrue)
Debug.WriteLine("About to call .PrintDebug()")
oClass1.PrintToDebug()
End Sub
End Class
Public Class Class1
Private _IsTrue As Boolean = True
Public ReadOnly Property IsTrue() As Boolean
Get
Return _IsTrue
End Get
End Property
Public Sub PrintToDebug()
Debug.WriteLine("Internal state of Class1: " & _IsTrue)
End Sub
End Class
I'm trying to test the Public interface of Class1, and somehow view the output from the Class1.PrintToDebug() function.
I've looked through the TestDriven.Net quickstart, which shows examples of using the Debug.WriteLine in a unit test, but strangely this doesn't work for me either - i.e. the only Output in my 'Test' window is:
------ Test started: Assembly: ClassLibrary1.dll ------
1 passed, 0 failed, 0 skipped, took 1.19 seconds.
I've tried looking in the other windows (Debug and Build), the Debug window has the 'Program Output' and 'Exception Messages' options enabled.
I've looked for options or preferences and can't find any!
Thanks for your help!
Edit: I'm using VB.Net 2.0, TestDriven.Net 2.14.2190 and NUnit 2.4.8.0
A: Trace.WriteLine() appears to be the answer :o)
Here's the output for the example from my question, using Trace instead of Debug:
------ Test started: Assembly: ClassLibrary1.dll ------
Internal state of Class1: True
1 passed, 0 failed, 0 skipped, took 0.61 seconds.
One thing I've found though.. execution is halted at the first failing unit test assertion, meaning that Trace statements aren't executed if an Assert() above them fails.
A: Try using Trace.WriteLine(...) instead. The call to Debug.WriteLine(...) will only be made when DEBUG is defined. By default new Visual Studio projects no longer define DEBUG, but they do define TRACE.
I should really change the quickstart example to use Trace instead.
Regards,
Jamie.
A: I found that while Debug.Writeline() doesn't work with unit tests, Console.WriteLine() does.
The reason is that when you run tests, the debugger process isn't invoked, and Debug.WriteLine() is ignored. However, if you use "Test with Debugger", I think (haven't tried) Debug.WriteLine() will work.
A: You might want to know that 2.16 (the current beta version) includes:
1587: Always display console
output/error and test runner messages
Test runner generated messages and
console output will now be displayed
when running all tests in a
project/solution.
1588: Optionally display trace/debug
output when running all tests in
project/solution
By default trace/debug output isn't
displayed when executing all tests in
a project/solution. This behaviour can
be modified via the TesDriven.Net
options pane.
So it seems that it will work in the next version.
A: IIRC, this output is only shown in the output window when running an individual test. Try right-clicking in the test method to run just that test...?
A: "Run Tests..." picks up whatever setting you currently have to build your solution/project.
You have to make sure that the current build settings for your solution/project are set to "Debug" and not to "Release" (otherwise Debug.Write*() calls are conditionally removed by the compiler).
A: CTRL + ALT + I shows you the immediate window
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How do I get a list of files that have been added to the SVN since a certain date? I only want a list of files that have been added (not ones that have been modified) since a certain date. Is there an easy way to do this?
Answer: Here's what ended up working for me, thanks guys!
svn log -v -r{2008-10-1}:HEAD svn://path.to.repo/ | grep "^Β Β Β A" | grep ".java" | sort -u
A: svn log -v -r{2008-10-1}:HEAD | grep "^ A"
A: If you use 'svn log -v -q' you get the filename and no log messages. This is a little bit faster over http:// and svn:// as the log messages are not transferred to you.
svn log --xml -v -q gives you the same information but in easy to parse xml. (This handles all corner cases on strange file names for you).
A: Something like
svn log -v -r {"2008-01-01"}:HEAD . | grep ' A ' | sort -u
should get you going...
A: you can try following command,
svn log -r '{2013-09-09}:HEAD'
Here you get all the revision details from date 9/9/2013
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Version control for video editing work I am looking into improving the backup process a group of animators use. Currently they back up their work into external hard drives or DVDs manually, taking full copies of everything. The data consists of thousands of high resolution images, project files of various video editing software and sound files. Basically everything is binary data and nothing should ever be merged on checkin.
Should I investigate version control systems that I would use as a software developer (Subversion, GIT etc.), or is there a class of version control systems intended for non-SW data that would suit these needs better?
A: You could also check out AlienBrain. Its a project asset management system designed for artists.
A: If your scope is just "backup" then I'd say stick to backup solutions.
But if you are thinking about the whole lifecycle of the animator's work, then the type of use typically falls into the "Digital Asset Management" category for the very reasons you mention: huge data volumes; binary formats.
Since version control (SCM) software is usually designed for text files that can be diff'd and merged, they tend not to do so well with binary formats in high volume. While your average web graphics are not going to be an issue for (software) version control tools, you mention video, which puts you in another league.
The bad news (maybe - depends on your business) is that DAM is dominated by the big end of town. @Atmospherian has mentioned AlienBrain which is a good representative of niche offering for artists. At the other end of the spectrum you have more general purpose offerings like Oracle's UCM (formerly Stellent). Make sure you check the price tags though.
There must be open source or lower cost alternatives available - but I don't know them, sorry.
What does seem to be very common are custom inhouse solutions. Unlike managing code, where changes to the files themselves have their own significance, managing digital assets tends to focus on the metadata (the image/video is just an associated blob). And since since many shops have their own particular production workflow, it makes the territory ripe for some skunkworks programming (if that's your bent - go for it!).
So while I'm not recommending any particular products, I suggest if you think "digital asset management" rather than "version control" when scouting for solutions you will probably find answers more suited to your needs.
A: Your question is a little unclear - you seem to have conflated version control and backup.
If what you want is version control, then take a look at the list on wikipedia: Comparison of revision control software. That shows most of the widely known version control systems, and their basic features. You're looking for something where you can set it up to force user's to checkout before they edit. Be aware that commercial solutions range in price from moderately expensive up to 'You want HOW much?'
If what you want is backup software, then I'd start at List of backup software in wikipedia. There's a lot more choices in the backup software arena, and there are a lot of price points.
Either way, figure in the creation of a admin position (either as part of someone's job or a new person altogether, if you're big enough). I've worked with backup and version control systems that didn't have an admin and it's a problem. Either no one takes care of problems, or everyone gets their fingers in there and really screws things up. Either way, making it part of someone's job (officially) is the best way to limit damage.
A: I think Clearcase would work for you.The reason being everything is VOB(VersionedObject) no matter what it is ! Check once
A: From your description, it sounds like you would do pretty well with some basic backup software such as Retrospect. Using daily backups of workstations, only changed data would be backed up and it would be easy to roll back to an earlier version of a file if needed.
What you don't get from such a setup is the ability to check out / check in files and get warnings about conflicts.
A: Vidyatel has an editing software that can compere video content and find the difference between the video versions leaning on the video only.
The result is in - EDL/TC.
It might help.
A: You should take a look at boar. It is exactly what you want, "version control and backup for photos, videos and other binary files". It is version control designed for large binary files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Can I Define Exceptions to Eclipse cleanup rules? Most often the cleanup rules (Preferences > Java > Code Style > Clean Up) in Eclipse work perfectly and create nice-looking code.
But sometimes, especially with comments and concatenated string snippets (like inline SQL queries), the cleanup just messes things up, and destroys my formatting.
Is there a way to say to Eclipse "Don't touch this block of text! I have formatted it just the way I like, and you would make it just less readable"?
A: I assume you do not really mean βClean Upβ, but the βFormat source codeβ option hidden within. It is configured in Preferences > Java > Code Style > Formatter. And, indeed, there is an option called βOn/Off Tagsβ. Sadly, itβs off by default. You would now write it like so:
// @formatter:off
StringBuilder sql = new StringBuilder()
.append("SELECT whatever \n")
.append("FROM some_table");
// @formatter:on
It may well be possible that the accepted answer was correct at the time of writing, however, this was introduced in Eclipse 3.5, if Iβm not mistaken.
A: I have experienced the same problem, and while I don't have a solution, I can tell you how I work around the problem.
Because of how formatting works, I deliberately avoid lines of code that are excessively long. In general, when I keep lines short, it makes better decisions as to how to format the code. This can even work with SQL statements, for example:
public static final String SELECT_SOMETHING = "SELECT"
+ "OBJECTID, THIS, THAT, THEOTHER, THING"
+ " FROM DBNAME.DBSCHEMA.TABLE_T"
+ " WHERE ID = ?";
This statement formats reasonably, because where possible items were split apart and concatenated together. When I don't do this, I get unpredictable results:
public static final String SELECT_SOMETHING = "SELECT OBJECTID, SOMETHING FROM DBNAME.DBSCHEMA.TABLE_T WHERE ID = ?";
For comments, I place them all on a single line when possible, and allow it to word wrap when it does the formatting.
Also, it is possible to change the style using the code formatter to make things work better for your coding style. You may want everyone on the team to use the same format, just to avoid conflicts. Because it is easier to compare changes with other developers, or prior versions using your source control tool, even if it makes parts of your code less readable, using the formatter has still been to my advantage.
Still, I understand your frustration when the formatter makes bad decisions!
A: Feeling iffy about replying to my own question, but there's a workaround I currently do (note: I have these cleanup rules as a save-action):
Save (with Ctrl/Cmd-S, don't know if it matters how you save) the code, and let Eclipse mess up your formatting. Then just press Ctrl/Cmd-Z to undo, and immediately re-save. The format reverts back to its original format and seems to be saved as intended.
A: For SQL statements in code, you can put a single-line comment character at the end of each line. Then the formatter can't reformat it. It's uglier than not having to do it, but it's prettier than if Eclipse formats it.
StringBuffer sql = new StringBuffer() //
.append("SELECT whatever \n") //
.append("FROM some_table");
A: No. (To the best of my knowledge, and I have had the same problem and have looked many times hard and long...)
A: (for Javadoc comments only)
If I have a block of text that formatted just the way I like, I enclose them by the <pre></pre> tags.
A: if you don't want a field to become final (i.i: because you want to change it while debugging), you just assign it to itself on the constructor. This would get an eclipse warning, but your field will stay non-final.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How do I make modal dialog for a Page in my WPF-application? I have a WPF Window which has a among other controls hosts a Frame. In that frame I display different pages. Is there way to make a dialog modal to only a page? When I'm showing the dialog it should not be possible to click on any control on the page but it should be possible to click on a control on the same window that is not on the page.
A: I have a project on github which is a custom FrameworkElement that allows you to display modal content over the primary content.
The control can be used like this:
<c:ModalContentPresenter IsModal="{Binding DialogIsVisible}">
<TabControl Margin="5">
<Button Margin="55"
Padding="10"
Command="{Binding ShowModalContentCommand}">
This is the primary Content
</Button>
</TabItem>
</TabControl>
<c:ModalContentPresenter.ModalContent>
<Button Margin="75"
Padding="50"
Command="{Binding HideModalContentCommand}">
This is the modal content
</Button>
</c:ModalContentPresenter.ModalContent>
</c:ModalContentPresenter>
Features:
*
*Displays arbitrary content.
*Does not disable the primary content whilst the modal content is being displayed.
*Disables mouse and keyboard access to the primary content whilst the modal content is displayed.
*Is only modal to the content it is covering, not the entire application.
*can be used in an MVVM friendly way by binding to the IsModal property.
A: If I am correct in interpreting your message, you want something that works similar to what
Billy Hollis demonstrates in his StaffLynx application.
I recently built a similar control and it turns out that this sort of idea is relatively simple to implement in WPF. I created a custom control called DialogPresenter. In the control template for the custom control, I added markup similar to the following:
<ControlTemplate TargetType="{x:Type local=DialogPresenter}">
<Grid>
<ContentControl>
<ContentPresenter />
</ContentControl>
<!-- The Rectangle is what simulates the modality -->
<Rectangle x:Name="Overlay" Visibility="Collapsed" Opacity="0.4" Fill="LightGrey" />
<Grid x:Name="Dialog" Visibility="Collapsed">
<!-- The template for the dialog goes here (borders and such...) -->
<ContentPresenter x:Name="PART_DialogView" />
</Grid>
</Grid>
<ControlTemplate.Triggers>
<!-- Triggers to change the visibility of the PART_DialogView and Overlay -->
</ControlTemplate.Triggers>
</ControlTemplate>
I also added a Show(Control view) method, which finds the the 'PART_DialogView', and adds the passed in view to the Content property.
This then allows me to use the DialogPresenter as follows:
<controls:DialogPresenter x:Name="DialogPresenter">
<!-- Normal parent view content here -->
<TextBlock>Hello World</TextBlock>
<Button>Click Me!</Button>
</controls:DialogPresenter>
To the buttons event handler (or bound command), I simply call the Show() method of the DialogPresenter.
You can also easily add ScaleTransform markup to the DialogPresenter template to get scaling effects shown in the video. This solution has neat and tidy custom control code, and a very simple interface for your UI programming team.
Hope this helps!
A: Why not just use nested message pumps to create modal controls
http://deanchalk.com/wpf-modal-controls-via-dispatcherframe-nested-message-pumps/
A: You are not looking for a modal dialog here. You need a function that will disable the "page" control, show a dialog, and re-enable it when the dialog closes.
I'm not too sure whether you understand what a modal dialog is meant to do though?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: How to disable right click menu in external launched application Good day.
I have a program thats launches an external application. That external app has a right click sub menu on it which I need to disable. Is it possible (without modifying the external app) to disable the right click? Maybe permission or group policies and etc.
Thanks.
A: I wasn't sure I wanted to post as I don't have a huge amount of scope on the matter, but it's definatley possible.
If you have a handle to the application (if not you can get one) you can use that to disable right click within the application.
http://www.codeguru.com/forum/showthread.php?t=190440
http://support.microsoft.com/kb/318804
seems like the most helpful links, it just goes on about how you should hook and then disregard WM_RBUTTONDOWN and WM_RBUTTONUP.
I'll try and write up a better thing later with an example.
More links/edits
This link could be useful as it explains that you're going to need to use unmanaged c/c++ to hook using setWindowsHookEx.
http://social.msdn.microsoft.com/Forums/en-US/clr/thread/8dd657b5-647b-443b-822d-ebe03ca4033c/
Hope this helps
[EDIT]
I think this can actually be done in a C# application completely. I will post a solution tonight
[/EDIT]
A: It's a win32 api FAQ.
see news://194.177.96.26/comp.os.ms-windows.programmer.win32
where it has often been discussed
A: I know a brutal solution for Windows. Make a hook on mouse and filter all messages, going to the external program window. It can slow down a whole system a little though.
It's not that comlicated. Here's a tutorial: http://win32assembly.online.fr/tut24.html
Nevermind assembler, it works the same way in any language.
A: <script type="text/javascript">
$(function () {
$(document).bind("contextmenu", function (e) {
e.preventDefault();
});
});
</script>
Use this code in script to disable right click
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is there no RAII in .NET? Being primarily a C++ developer the absence of RAII (Resource Acquisition Is Initialization) in Java and .NET has always bothered me. The fact that the onus of cleaning up is moved from the class writer to its consumer (by means of try finally or .NET's using construct) seems to be markedly inferior.
I see why in Java there is no support for RAII since all objects are located on the heap and the garbage collector inherently doesn't support deterministic destruction, but in .NET with the introduction of value-types (struct) we have the (seemingly) perfect candidate for RAII. A value type that's created on the stack has a well defined scope and C++ destructor semantics can be used. However the CLR does not permit a value-type to have a destructor.
My random searches found one argument that if a value-type is boxed it falls under the jurisdiction of the garbage collector and therefore its destruction becomes non-deterministic.
I feel that this argument isn't strong enough, the benefits of RAII are big enough to say that a value-type with a destructor cannot be boxed (or used as a class member).
To cut a long story short my question is: are there any other reasons value types can not be used in order to introduce RAII to .NET? (or do you think my argument about RAII's obvious advantages are flawed?)
Edit: I must have not phrased the question clearly since the first four answers have missed the point. I know about Finalize and its non-deterministic characteristics, I know about the using construct and I feel these two options are inferior to RAII. using is one more thing the consumer of a class must remember (how many people forgot to put a StreamReader in a using block?). My question is a philosophical one about the language design, why is it the way it is and can it be improved?
For instance with a generic deterministically destructible value-type I can make the using and lock keywords redundant (achievable by library classes):
public struct Disposer<T> where T : IDisposable
{
T val;
public Disposer(T t) { val = t; }
public T Value { get { return val; } }
~Disposer() // Currently illegal
{
if (val != default(T))
val.Dispose();
}
}
I can't help but end with a apropos quotation which I once saw but can't currently find its origin.
You can take my deterministic destruction when my cold dead hand goes out of scope. --Anon
A: A better title would be "Why is there no RAII in C#/VB". C++/CLI (The evolution of the abortion that was Managed C++) has RAII in the exact same sense as C++. It's all just syntax sugar for the same finalisation pattern that the rest of the CLI languages use (Destructors in managed objects for C++/CLI are effectively finalisers), but it is there.
You might like http://blogs.msdn.com/hsutter/archive/2004/07/31/203137.aspx
A: Excellent question and one that has bothered me greatly. It appears that the benefits of RAII are perceived very differently. In my experience with .NET, the lack of deterministic (or at least reliable) resource collection is one of the major drawbacks. In fact, .NET has forced me several times to employ whole architectures to deal with unmanaged resources that might (but might not) require explicit collecting. Which, of course, is a huge drawback because it makes the overall architecture more difficult and directs the client's attention away from the more central aspects.
A: Brian Harry has a nice post about the rationales here.
Here is an excerpt:
What about deterministic finalization and value types (structs)?
-------------- I've seen a lot of questions about structs having
destructors, etc. This is worth
comment. There are a variety of
issues for why some languages don't
have them.
(1) composition - They don't give you
deterministic lifetime in the general
case for the same kinds of composition
reasons described above. Any
non-deterministic class containing one
would not call the destructor until it
was finalized by the GC anyway.
(2) copy constructors - The one place
where it would really be nice is in
stack allocated locals. They would be
scoped to the method and all would be
great. Unfortunately, in order to get
this to really work, you also have to
add copy constructors and call them
every time an instance is copied.
This is one of the ugliest and most
complex things about C++. You end up
getting code executing all over the
place where you don't expect it. It
causes bunches of language problems.
Some language designers have chosen to
stay away from this.
Let's say we created structs with
destructors but added a bunch of
restrictions to make their behavior
sensible in the face of the issues
above. The restrictions would be
something like:
(1) You can only declare them as local
variables.
(2) You can only pass them
by-ref
(3) You can't assign them, you
can only access fields and call
methods on them.
(4) You can't box
them.
(5) Problems using them through
Reflection (late binding) because that
usually involves boxing.
maybe more,
but that's a good start.
What use would these things be? Would
you actually create a file or a
database connection class that can
ONLY be used as a local variable? I
don't believe anybody really would.
What you would do instead is create a
general purpose connection and then
create an auto destructed wrapper for
use as a scoped local variable. The
caller would then pick what they
wanted to use. Note the caller made a
decision and it is not entirely
encapsulated in the object itself.
Given that you could use something
like the suggestions coming up in a
couple of sections.
The replacement for RAII in .NET is the using-pattern, which works almost as well once you get used to it.
A: The closest you get to that is the very limited stackalloc operator.
A: There's some similar threads if you search for them but basicly what it boils down to is that if you want to RAII on .NET simply implement an IDisposable type and use the "using" statement to get deterministic Disposal. That way many of the same ideoms can be implemented and used in only a slightly more wordy manner.
A: IMHO, the big things that VB.net and C# need are:
*
*a "using" declaration for fields, which would cause the compiler to generate code to dispose of all fields thus tagged. The default behavior should be for the compiler to make a class implement IDisposable if it does not, or insert disposal logic before the start of the main disposal routine for any of a number of common IDisposal implementation patterns, or else use an attribute to specify that the disposal stuff should go in a routine with a particular name.
*a means of deterministically disposing of objects whose constructors and/or field initializers throw an exception, either by a default behavior (calling the default disposal method) or a custom behavior (calling a method with a particular name).
*For vb.net, an auto-generated method to null out all WithEvent fields.
All of those can be kludged pretty well in vb.net, and somewhat less well in C#, but first-class support for them would improve both languages.
A: You can do a form of RAII in .net and java using finalize() methods. A finalize() overload is called before the class is cleaned up by the GC and so can be used to clean up any resources that absolutely shouldn't be kept by the class (mutexes, sockets, file handles, etc). It still isn't deterministic though.
With .NET you can do some of this deterministically with the IDisposable interface and the using keyword, but this does have limitations (using construct when used required for deterministic behaviour, still no deterministic memory deallocation, not automatically used in classes, etc).
And yes, I feel there is a place for RAII ideas to be introduced into .NET and other managed languages, although the exact mechanism could be debated endlessly. The only other alternative I could see would be to introduce a GC that could handle arbitrary resource cleanup (not just memory) but then you have issues when said resources absolutely have to be released deterministically.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "66"
} |
Q: String literals inside functions: automatic variables or allocated in heap? Are the string literals we use inside functions automatic variables? Or are they allocated in heap which we have to free manually?
I've a situation like the code shown below wherein I'm assigning a string literal to a private field of the class (marked as ONE in the code) and retrieving it much later in my program and using it (marked as TWO). Am I assigning a variable in the stack to a field in ONE? Can the code be referencing to a dangling pointer which in this case worked because the program was small enough?
I've compiled and ran it, it worked fine but I'm having a strange crash in my actual program where I'm assigning string literals to fields of the class like this and I suspect the case I mentioned above.
#include <iostream>
using namespace std;
class MemoryLeak
{
private:
char *s;
public:
MemoryLeak() {}
void store()
{
s = "Storing a string"; // ONE
}
char *retrieve()
{
return s;
}
};
int main()
{
MemoryLeak *obj = new MemoryLeak();
obj->store();
cout << obj->retrieve() << endl; // TWO
delete obj;
return 0;
}
Should I be declaring the variable "s" as a char array instead of a pointer? I'm planning to use std::string, but I'm just curious about this.
Any pointers or help is, as always, much appreciated :) Thanks.
A: String literals will be placed in the initialized data or text (code) segment of your binary by the compiler, rather than residing in (runtime allocated) memory or the stack. So you should be using a pointer, since you're going to be referencing the string literal that the compiler has already produced for you. Note that modifying this (which would require changing memory protection typically) will change all uses of this literal.
A: It is undefined behaviour to modify a string literal, and is most likely the cause of the crash in your program (ISO C++: 2.13.4/2). The standard allows for a conversion from a string literal to char* for backwards compatibility to C and you should only have that conversion in your code if you absolutely need it.
If you wish to treat the string literal as a constant, then you can change the type of your member to a const char *.
If your design requires that s can be modified, then I would recommend changing its type to std::string.
A: Thank you Cody and Richard.
I found the cause of the bug. It was because I was doing a delete on an object which was already delete'd. I was doing:
if (obj != NULL) delete obj;
I changed it to:
if (obj != NULL)
{
delete obj;
obj = NULL;
}
Learning C++ is definitely fun :)
A: Maybe the cause of the crash is that you did not 0-terminate the string?
A: Lets have a look at your options.
There are also a couple of things you should do:
/*
* Should initialize s to NULL or a valid string in constructor */
MemoryLeak()
{
store();
}
void store()
{
// This does not need to be freed because it is a string literal
// generated by the compiler.
s = "Storing a string"; // ONE
// Note this is allowed for backward compatibility but the string is
// really stored as a const char* and thus unmodifiable. If somebody
// retrieves this C-String and tries to change any of the contents the
// code could potentially crash as this is UNDEFINED Behavior.
// The following does need to be free'd.
// But given the type of s is char* this is more correct.
s = strdup("Storing a string");
// This makes a copy of the string on the heap.
// Because you allocated the memory it is modifiable by anybody
// retrieving it but you also need to explicitly de-allocate it
// with free()
}
What you are doing is using C-Strings. These should not be confused with C++ std::string. The C++ std::string is auto-initialized to the empty string. Any memory allocated is de-allocated correctly. It can easily be returned as both a modifiable and non modifiable version. It is also easy to manipulate (i.e. grow shrink change). If you grow a C-String you need to re-allocate memory and copy the string to the new memory etc (it is very time consuming an error prone).
To cope with dynamically allocating your object I would learn about smart pointers.
See this article for more details on smart pointers.
Smart Pointers or who owns you Baby
std::auto_ptr<MemoryLeak> obj(new MemoryLeak());
obj->store();
std::cout << obj->retrieve() << std::endl; // TWO
// No need to delete When object goes out of scope it auto deletes the memory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is it possible to pass arguments into event bindings? I haven't found an answer elsewhere and this doesn't appear to have been asked yet on SO.
When creating an event binding in wxPython, is it possible to pass additional arguments to the event? For example, this is the normal way:
b = wx.Button(self, 10, "Default Button", (20, 20))
self.Bind(wx.EVT_BUTTON, self.OnClick, b)
def OnClick(self, event):
self.log.write("Click! (%d)\n" % event.GetId())
But is it possible to have another argument passed to the method? Such that the method can tell if more than one widget is calling it but still return the same value?
It would greatly reduce copy & pasting the same code but with different callers.
A: You can always use a lambda or another function to wrap up your method and pass another argument, not WX specific.
b = wx.Button(self, 10, "Default Button", (20, 20))
self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, 'somevalue'), b)
def OnClick(self, event, somearg):
self.log.write("Click! (%d)\n" % event.GetId())
If you're out to reduce the amount of code to type, you might also try a little automatism like:
class foo(whateverwxobject):
def better_bind(self, type, instance, handler, *args, **kwargs):
self.Bind(type, lambda event: handler(event, *args, **kwargs), instance)
def __init__(self):
self.better_bind(wx.EVT_BUTTON, b, self.OnClick, 'somevalue')
A: The nicest way would be to make a generator of event handlers, e.g.:
def getOnClick(self, additionalArgument):
def OnClick(event):
self.log.write("Click! (%d), arg: %s\n"
% (event.GetId(), additionalArgument))
return OnClick
Now you bind it with:
b = wx.Button(self, 10, "Default Button", (20, 20))
b.Bind(wx.EVT_BUTTON, self.getOnClick('my additional data'))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Can I change the Visual Studio text editor's cursor? The tiny text entry cursor in the Visual Studio 2005's editor is driving me nuts. I'd ideally like to be able to highlight (say in yellow) the entire line that I'm currently on, but I'll settle for just making the cursor bigger and/or a different colour. Any help gratefully received!
A: CodeKana allows you to highlight the current line among other nice features. AFAIK Visual Studio has no built-in support for highlighting or otherwise making the current line obvious.
A: Under Control Panel, Personalization, Choose Mouse Pointers, try different color schemes/pointers for the Text Select cursor, "Windows Inverted (system scheme)" seems to work very well for me.
I found this solution here:
http://social.msdn.microsoft.com/forums/en-US/vssetup/thread/3b131a04-9a51-42c9-b69e-73e6e70c15a7
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How do I develop for both Portrait and Landscape display formats? I'm currently developing for a handheld device running Windows XP Professional (not Tablet PC edition). The device allows users to switch from the standard widescreen landscape display format to a portrait one. I would like to know if there are any VB.NET code snippets to help me along with this task.
A: The way to determine the current orientation is with the System.Windows.Forms.SystemInformation.ScreenOrientation property.
To get the actual size of the screen, check System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height (and .Width)
You can declare an event handler (with the AddHandler statement) for Microsoft.Win32.SystemEvents.DisplaySettingsChanged as a trigger your app can respond to, and then check the screen orientation to see if you need to adjust your GUI layout.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I delete a specific node within a XML file by using vbscript I am having the problem that I cannot select a specific XML node which needs to be deleted. I have already tried to select the node by using the XPath which works fine for some XML files but I cannot figure out the correct XPath for a node in a more complex file.
Does anybody know a freeware tool which can load a XML file so that the user can select a specific node and receives the accurate XPath without having an enumeration in the path?
/root/anything[2] <-- unfortunatly I cannot use such a statement because the number of the element might change. I need an expression that is based on an attribute.
In case that there is no freeware tool for this operation, does anybody know another way how I can select the needed node?
XML Sample:
Root Node: SmsFormData
Attributes: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" FormatVersion="1.0" xmlns="http://schemas.microsoft.com/SystemsManagementServer/2005/03/ConsoleFramework"
Child node: Form
Attributes: Id="some GUID" CustomData="Some data" FormType="some type" ForceRefresh="false"
Child/Child node: Pages
Child/Child/Child node: Page
Attributes: VendorId="VendorName" Id="some GUID" Assembly="dll File name" Namespace="some Namespace" Type="some Type" HelpID="">
My xPath expression to select this specific page would now be:
xPath = /SmsFormData/Form/Pages/Page[@Id="some Guid"]
To do the selection I am using the following vbscript code:
Set objDOM = CreateObject("Msxml2.DOMDocument.4.0")
objDOM.async = false
objDOM.load(file)
set objNode = objDOM.selectSingleNode(xPath)
The problem is now that the objNode object is empty. The node is not selected, but why?
A: This is a default namespace issue. Try including the following code after you load in the XML:
objDom.SetProperty "SelectionNamespaces", "xmlns:cf=""http://schemas.microsoft.com/SystemsManagementServer/2005/03/ConsoleFramework"""
You then use this cf prefix in your XPath eg:
objDom.SelectSingleNode("/cf:SmsFormData/cf:Form/cf:Pages/cf:Page[@Id='Some Guid']")
Whilst this may seem a bit quirky, it is intentional behaviour. Take a look at http://support.microsoft.com/kb/288147 for more information, and you may find http://msdn.microsoft.com/en-us/library/ms950779.aspx useful as well.
A: Given the following XML:
<root>
<anything foo="bar">value1</anything>
<anything foo="qux">value2</anything>
</root>
...you can obtain the value of the second anything node using the XPath expression:
/root/anything[@foo="qux"]
(so, instead of the numbered index, you use @property="value" as the selector).
As for a tool to generate queries like this automagically, the aptly named Visual XPath should do the trick, and it's free (it even comes with C# source code).
Edit, after followup by poster: this form of XPath selection works as well for 'simple cases' as it does for the most complicated documents. You do have to make sure your XPath expression is correct, of course, and although Visual XPath will indeed use numeric indexes, it at least gives you the rest of the expression, and you can easily substitute the @property="value" selector for the number, and test the result.
Given the example XML above, this VBscript:
objDOM.selectSingleNode("/root/anything[@foo=""qux""]/text()").nodeValue
...returns the string "value2": depending on your needs, you may need to tweak things a little bit (again, tools like Visual XPath, or any good XPath reference will help you with that).
A: Thanks for your fast reply! This surely works in simple cases but this does not work in my specific case :(
So therefore lets go into the details:
Root Node: SmsFormData
Attributes: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" FormatVersion="1.0" xmlns="http://schemas.microsoft.com/SystemsManagementServer/2005/03/ConsoleFramework"
Child node: Form
Attributes: Id="some GUID" CustomData="Some data" FormType="some type" ForceRefresh="false"
Child/Child node:
Pages
Child/Child/Child node: Page
Attributes: VendorId="VendorName" Id="some GUID" Assembly="dll File name" Namespace="some Namespace" Type="some Type" HelpID="">
My xPath expression to select this specific page would now be:
xPath = "/SmsFormData/Form/Pages/Page[@Id="some Guid"]"
To do the selection I am using the following vbscript code:
Set objDOM = CreateObject("Msxml2.DOMDocument.4.0")
objDOM.async = false
objDOM.load(file)
set objNode = objDOM.selectSingleNode(xPath)
The problem is now that the objNode object is empty. The node is not selected, but why?
Oh and by the way: Thanks for the Visual XPath tip! I have tried using it but unfortunately it does the enumeration way :/
A: You need to set the Selection Language to XPath using
objDOM.SetProperty "SelectionLanguage", "XPath"
Once you have set this property you can then use full XPath to access any elements you want
A: If you have the Firefox browser, you can simply install the DOM Inspector (required only for Firefox 3.0), and the XPather extensions. Then, you can traverse to the node you want in the DOM Inspector window, and the corresponding XPath will be displayed in the XPather toolbar in the same window.
DOM Inspector: https://addons.mozilla.org/en-US/firefox/addon/6622
XPather: https://addons.mozilla.org/en-US/firefox/addon/1192?id=1192
The XPather seems to use attributes (and not enumeration) whenever possible to identify nodes (atleast that's what I found in my little experimentation...).
Hope that helps...
A: Hm,... I get the impression that the problem must be file based.
Even if I set the property for the SelectionLanguage and if I use an enumerated XPath (which I got by using the FireFox XPather) the node Object still remains empty.
Does anybody has an idea what could be wrong? The xml file comes with an Microsoft application and therefore should be valid. At least I don't have any problems while opening the file or using it within the application so the syntax should be ok.
Or does maybe somebody have a vbscript function that iterates through the whole xml file to find the needed node in order to delete it?
A: You problem is that you have a default namespace. XPaths default name space is always the 'no name' name space.
You need:-
sNamespaces = "xmlns:cf='http://schemas.microsoft.com/SystemsManagementServer/2005/03/ConsoleFramework'"
objDOM.setProperty "SelectionNamespaces", sNamespaces
Now you can use in your XPath:-
xPath = "/cf:SmsFormData/cf:Form/cf:Pages/cf:Page[@Id=""some Guid""]"
A: Not sure if it is any use to you, but I had a similar problem.
I had an app generated XML file that I needed to manage. It was of the format:
<LoginData>
<GeneralData>
<LoginMask>65537</LoginMask>
</GeneralData>
<UserData>
<User>
<Username>TEST0</Username>
...
</User>
<User>
<Username>TEST1</Username>
...
</User>
</UserData>
</LoginData>
I needed to match on a Username and remove the other User tags.
Took me (being a complete XML noob) ages to work it out, but in the end I hit on matching on a node, and deleting the child of the parent node:
for each x in oXmlDoc.documentElement.selectSingleNode("UserData").childNodes
if x.getElementsByTagName("Username").item(0).text = "TEST1" then
set exx = x.getElementsByTagName("Username").item(0)
wscript.echo(x.getElementsByTagName("Username").item(0).text)
wScript.echo(x.nodename & ": " & x.text)
x.parentNode.removeChild(x)
end if
next
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inline editing in a winforms textbox at design time I'm using a custom winforms 2.0 designer (i.e. my apps hosting the designer) which is being used for a small internal project.
So far all the controls have their properties edited via the property grid - but I'd like to make it a little more user-friendly by allowing in-line editing - does anyone know of an example of how to implement in-line editing within the windows forms designer (just for typing plain text at this stage).
A: You will need to create a designer that supports this behavior. For an example, use Reflector to look at the designer the ListView uses for resizing its columns. This should give you an idea of the work involved and what you need to do. There is MSDN documentation on some of this, but it isn't as helpful as you may like it to be.
The ListViewDesigner, in System.Design.dll, provides the column sizing by turning mouse operations in the designer into windows messages that manipulate the underlying list view. Your designer for the textbox will need to do something similar with keyboard events.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQL Server: Copying column within table What is the easiest way to copy the all the values from a column in a table to another column in the same table?
A: With a single statement (if the columns have the same datatype)
UPDATE <tablename>
SET <destination column name> = <source column name>
A: This script will update ALL values in the field1 with the values from the field2 in the corresponding row
UPDATE table SET field1 = field2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: When and why are database joins expensive? I'm doing some research into databases and I'm looking at some limitations of relational DBs.
I'm getting that joins of large tables is very expensive, but I'm not completely sure why. What does the DBMS need to do to execute a join operation, where is the bottleneck?
How can denormalization help to overcome this expense? How do other optimization techniques (indexing, for example) help?
Personal experiences are welcome! If you're going to post links to resources, please avoid Wikipedia. I know where to find that already.
In relation to this, I'm wondering about the denormalized approaches used by cloud service databases like BigTable and SimpleDB. See this question.
A: Denormalising to improve performance? It sounds convincing, but it doesn't hold water.
Chris Date, who in company with Dr Ted Codd was the original proponent of the relational data model, ran out of patience with misinformed arguments against normalisation and systematically demolished them using scientific method: he got large databases and tested these assertions.
I think he wrote it up in Relational Database Writings 1988-1991 but this book was later rolled into edition six of Introduction to Database Systems, which is the definitive text on database theory and design, in its eighth edition as I write and likely to remain in print for decades to come. Chris Date was an expert in this field when most of us were still running around barefoot.
He found that:
*
*Some of them hold for special cases
*All of them fail to pay off for general use
*All of them are significantly worse for other special cases
It all comes back to mitigating the size of the working set. Joins involving properly selected keys with correctly set up indexes are cheap, not expensive, because they allow significant pruning of the result before the rows are materialised.
Materialising the result involves bulk disk reads which are the most expensive aspect of the exercise by an order of magnitude. Performing a join, by contrast, logically requires retrieval of only the keys. In practice, not even the key values are fetched: the key hash values are used for join comparisons, mitigating the cost of multi-column joins and radically reducing the cost of joins involving string comparisons. Not only will vastly more fit in cache, there's a lot less disk reading to do.
Moreover, a good optimiser will choose the most restrictive condition and apply it before it performs a join, very effectively leveraging the high selectivity of joins on indexes with high cardinality.
Admittedly this type of optimisation can also be applied to denormalised databases, but the sort of people who want to denormalise a schema typically don't think about cardinality when (if) they set up indexes.
It is important to understand that table scans (examination of every row in a table in the course of producing a join) are rare in practice. A query optimiser will choose a table scan only when one or more of the following holds.
*
*There are fewer than 200 rows in the relation (in this case a scan will be cheaper)
*There are no suitable indexes on the join columns (if it's meaningful to join on these columns then why aren't they indexed? fix it)
*A type coercion is required before the columns can be compared (WTF?! fix it or go home) SEE END NOTES FOR ADO.NET ISSUE
*One of the arguments of the comparison is an expression (no index)
Performing an operation is more expensive than not performing it. However, performing the wrong operation, being forced into pointless disk I/O and then discarding the dross prior to performing the join you really need, is much more expensive. Even when the "wrong" operation is precomputed and indexes have been sensibly applied, there remains significant penalty. Denormalising to precompute a join - notwithstanding the update anomalies entailed - is a commitment to a particular join. If you need a different join, that commitment is going to cost you big.
If anyone wants to remind me that it's a changing world, I think you'll find that bigger datasets on gruntier hardware just exaggerates the spread of Date's findings.
For all of you who work on billing systems or junk mail generators (shame on you) and are indignantly setting hand to keyboard to tell me that you know for a fact that denormalisation is faster, sorry but you're living in one of the special cases - specifically, the case where you process all of the data, in-order. It's not a general case, and you are justified in your strategy.
You are not justified in falsely generalising it. See the end of the notes section for more information on appropriate use of denormalisation in data warehousing scenarios.
I'd also like to respond to
Joins are just cartesian products with some lipgloss
What a load of bollocks. Restrictions are applied as early as possible, most restrictive first. You've read the theory, but you haven't understood it. Joins are treated as "cartesian products to which predicates apply" only by the query optimiser. This is a symbolic representation (a normalisation, in fact) to facilitate symbolic decomposition so the optimiser can produce all the equivalent transformations and rank them by cost and selectivity so that it can select the best query plan.
The only way you will ever get the optimiser to produce a cartesian product is to fail to supply a predicate: SELECT * FROM A,B
Notes
David Aldridge provides some important additional information.
There is indeed a variety of other strategies besides indexes and table scans, and a modern optimiser will cost them all before producing an execution plan.
A practical piece of advice: if it can be used as a foreign key then index it, so that an index strategy is available to the optimiser.
I used to be smarter than the MSSQL optimiser. That changed two versions ago. Now it generally teaches me. It is, in a very real sense, an expert system, codifying all the wisdom of many very clever people in a domain sufficiently closed that a rule-based system is effective.
"Bollocks" may have been tactless. I am asked to be less haughty and reminded that math doesn't lie. This is true, but not all of the implications of mathematical models should necessarily be taken literally. Square roots of negative numbers are very handy if you carefully avoid examining their absurdity (pun there) and make damn sure you cancel them all out before you try to interpret your equation.
The reason that I responded so savagely was that the statement as worded says that
Joins are cartesian products...
This may not be what was meant but it is what was written, and it's categorically untrue. A cartesian product is a relation. A join is a function. More specifically, a join is a relation-valued function. With an empty predicate it will produce a cartesian product, and checking that it does so is one correctness check for a database query engine, but nobody writes unconstrained joins in practice because they have no practical value outside a classroom.
I called this out because I don't want readers falling into the ancient trap of confusing the model with the thing modelled. A model is an approximation, deliberately simplified for convenient manipulation.
The cut-off for selection of a table-scan join strategy may vary between database engines. It is affected by a number of implementation decisions such as tree-node fill-factor, key-value size and subtleties of algorithm, but broadly speaking high-performance indexing has an execution time of k log n + c. The C term is a fixed overhead mostly made of setup time, and the shape of the curve means you don't get a payoff (compared to a linear search) until n is in the hundreds.
Sometimes denormalisation is a good idea
Denormalisation is a commitment to a particular join strategy. As mentioned earlier, this interferes with other join strategies. But if you have buckets of disk space, predictable patterns of access, and a tendency to process much or all of it, then precomputing a join can be very worthwhile.
You can also figure out the access paths your operation typically uses and precompute all the joins for those access paths. This is the premise behind data warehouses, or at least it is when they're built by people who know why they're doing what they're doing, and not just for the sake of buzzword compliance.
A properly designed data warehouse is produced periodically by a bulk transformation out of a normalised transaction processing system. This separation of the operations and reporting databases has the very desirable effect of eliminating the clash between OLTP and OLAP (online transaction processing ie data entry, and online analytical processing ie reporting).
An important point here is that apart from the periodic updates, the data warehouse is read only. This renders moot the question of update anomalies.
Don't make the mistake of denormalising your OLTP database (the database on which data entry happens). It might be faster for billing runs but if you do that you will get update anomalies. Ever tried to get Reader's Digest to stop sending you stuff?
Disk space is cheap these days, so knock yourself out. But denormalising is only part of the story for data warehouses. Much bigger performance gains are derived from precomputed rolled-up values: monthly totals, that sort of thing. It's always about reducing the working set.
ADO.NET problem with type mismatches
Suppose you have a SQL Server table containing an indexed column of type varchar, and you use AddWithValue to pass a parameter constraining a query on this column. C# strings are Unicode, so the inferred parameter type will be NVARCHAR, which doesn't match VARCHAR.
VARCHAR to NVARCHAR is a widening conversion so it happens implicitly - but say goodbye to indexing, and good luck working out why.
"Count the disk hits" (Rick James)
If everything is cached in RAM, JOINs are rather cheap. That is, normalization does not have much performance penalty.
If a "normalized" schema causes JOINs to hit the disk a lot, but the equivalent "denormalized" schema would not have to hit the disk, then denormalization wins a performance competition.
Comment from original author: Modern database engines are very good at organising access sequencing to minimise cache misses during join operations. The above, while true, might be miscontrued as implying that joins are necessarily problematically expensive on large data. This would lead to cause poor decision-making on the part of inexperienced developers.
A: What most commenters fail to note is the wide range of join methodologies available in a complex RDBMS, and the denormalisers invariably gloss over the higher cost of maintaining denormalised data. Not every join is based on indexes, and databases have a lot of optimised algotithms and methodologies for joining that are intended to reduce join costs.
In any case, the cost of a join depends on its type and a few other factors. It needn't be expensive at all - some examples.
*
*A hash join, in which bulk data is equijoined, is very cheap indeed, and the cost only become significant if the hash table cannot be cached in memory. No index required. Equi-partitioning between the joined data sets can be a great help.
*The cost of a sort-merge join is driven by the cost of the sort rather than the merge -- an index-based access method can virtually eliminate the cost of the sort.
*The cost of a nested loop join on an index is driven by the height of the b-tree index and the access of the table block itself. It's fast, but not suitable for bulk joins.
*A nested loop join based on a cluster is much cheaper, with fewer logicAL IO'S required per join row -- if the joined tables are both in the same cluster then the join becomes very cheap through the colocation of joined rows.
Databases are designed to join, and they're very flexible in how they do it and generally very performant unless they get the join mechanism wrong.
A: I think the whole question is based on a false premise. Joins on large tables are not necessarily expensive. In fact, doing joins efficiently is one of the main reasons relational databases exist at all. Joins on large sets often are expensive, but very rarely do you want to join the entire contents of large table A with the entire contents of large table B. Instead, you write the query such that only the important rows of each table are used and the actual set kept by the join remains smaller.
Additionally, you have the efficiencies mentioned by Peter Wone, such that only the important parts of each record need be in memory until the final result set is materialized. Also, in large queries with many joins you typically want to start with the smaller table sets and work your way up to the large ones, so that the set kept in memory remains as small as possible as long as possible.
When done properly, joins are generally the best way to compare, combine, or filter on large amounts of data.
A: The order in which you're joining the tables is extremely important. If you have two sets of data try to build the query in a way so the smallest will be used first to reduce the amount of data the query has to work on.
For some databases it does not matter, for example MS SQL does know the proper join order most of the time.
For some (like IBM Informix) the order makes all the difference.
A: The bottleneck is pretty much always disk I/O, and even more specifically - random disk I/O (by comparison, sequential reads are fairly fast and can be cached with read ahead strategies).
Joins can increase random seeks - if you're jumping around reading small parts of a large table. But, query optimizers look for that and will turn it into a sequential table scan (discarding the unneeded rows) if it thinks that'd be better.
A single denormalized table has a similar problem - the rows are large, and so less fit on a single data page. If you need rows that are located far from another (and the large row size makes them further apart) then you'll have more random I/O. Again, a table scan may be forced to avoid this. But, this time, your table scan has to read more data because of the large row size. Add to that the fact that you're copying data from a single location to multiple locations, and the RDBMS has that much more to read (and cache).
With 2 tables, you also get 2 clustered indexes - and can generally index more (because of less insert/update overhead) which can get you drastically increased performance (mainly, again, because indexes are (relatively) small, quick to read off disk (or cheap to cache), and lessen the amount of table rows you need to read from disk).
About the only overhead with a join comes from figuring out the matching rows. Sql Server uses 3 different types of joins, mainly based on dataset sizes, to find matching rows. If the optimizer picks the wrong join type (due to inaccurate statistics, inadequate indexes, or just an optimizer bug or edge case) it can drastically affect query times.
*
*A loop join is farily cheap for (at least 1) small dataset.
*A merge join requires a sort of both datasets first. If you join on an indexed column, though, then the index is already sorted and no further work needs to be done. Otherwise, there is some CPU and memory overhead in sorting.
*The hash join requires both memory (to store the hashtable) and CPU (to build the hash). Again, this is fairly quick in relation to the disk I/O. However, if there's not enough RAM to store the hashtable, Sql Server will use tempdb to store parts of the hashtable and the found rows, and then process only parts of the hashtable at a time. As with all things disk, this is fairly slow.
In the optimal case, these cause no disk I/O - and so are negligible from a performance perspective.
All in all, at worst - it should actually be faster to read the same amount of logical data from x joined tables, as it is from a single denormalized table because of the smaller disk reads. To read the same amount of physical data, there could be some slight overhead.
Since query time is usually dominated by I/O costs, and the size of your data does not change (minus some very miniscule row overhead) with denormalization, there's not a tremendous amount of benefit to be had by just merging tables together. The type of denormalization that tends to increase performance, IME, is caching calculated values instead of reading the 10,000 rows required to calculate them.
A: Deciding on whether to denormalize or normalize is fairly a straightforward process when you consider the complexity class of the join. For instance, I tend to design my databases with normalization when the queries are O(k log n) where k is relative to the desired output magnitude.
An easy way to denormalize and optimize performance is to think about how changes to your normalize structure affect your denormalized structure. It can be problematic however as it may require transactional logic to work on a denormalized structured.
The debate for normalization and denormalization isn't going to end since the problems are vast. There are many problems where the natural solution requires both approaches.
As a general rule, I've always stored a normalized structure and denormalized caches that can be reconstructed. Eventually, these caches save my ass to solve the future normalization problems.
A: Elaborating what others have said,
Joins are just cartesian products with some lipgloss. {1,2,3,4}X{1,2,3} would give us 12 combinations (nXn=n^2). This computed set acts as a reference on which conditions are applied. The DBMS applies the conditions (like where both left and right are 2 or 3) to give us the matching condition(s). Actually it is more optimised but the problem is the same. The changes to size of the sets would increase the result size exponentially. The amount of memory and cpu cycles consumed all are effected in exponential terms.
When we denormalise, we avoid this computation altogether, think of having a colored sticky, attached to every page of your book. You can infer the information with out using a reference. The penalty we pay is that we are compromising the essence of DBMS (optimal organisation of data)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "394"
} |
Q: How to save encrypted data in cookie (using php)? I would like to save data in cookies (user name, email address, etc...) but I don't the user to easily read it or modify it. I need to be able able to read the data back. How can I do that with php 5.2+?
It would be used for "welcome back bob" kind of feature. It is not a replacement for persistence or session storage.
A: We use mcrypt in our projects to achieve encryption. Below is a code sample based on content found on the internet:
<?php
class MyProjCrypt {
private $td;
private $iv;
private $ks;
private $salt;
private $encStr;
private $decStr;
/**
* The constructor initializes the cryptography library
* @param $salt string The encryption key
* @return void
*/
function __construct($salt) {
$this->td = mcrypt_module_open('rijndael-256', '', 'ofb', ''); // algorithm
$this->ks = mcrypt_enc_get_key_size($this->td); // key size needed for the algorithm
$this->salt = substr(md5($salt), 0, $this->ks);
}
/**
* Generates a hex string of $src
* @param $src string String to be encrypted
* @return void
*/
function encrypt($src) {
srand(( double) microtime() * 1000000); //for sake of MCRYPT_RAND
$this->iv = mcrypt_create_iv($this->ks, MCRYPT_RAND);
mcrypt_generic_init($this->td, $this->salt, $this->iv);
$tmpStr = mcrypt_generic($this->td, $src);
mcrypt_generic_deinit($this->td);
mcrypt_module_close($this->td);
//convert the encrypted binary string to hex
//$this->iv is needed to decrypt the string later. It has a fixed length and can easily
//be seperated out from the encrypted String
$this->encStr = bin2hex($this->iv.$tmpStr);
}
/**
* Decrypts a hex string
* @param $src string String to be decrypted
* @return void
*/
function decrypt($src) {
//convert the hex string to binary
$corrected = preg_replace("[^0-9a-fA-F]", "", $src);
$binenc = pack("H".strlen($corrected), $corrected);
//retrieve the iv from the encrypted string
$this->iv = substr($binenc, 0, $this->ks);
//retrieve the encrypted string alone(minus iv)
$binstr = substr($binenc, $this->ks);
/* Initialize encryption module for decryption */
mcrypt_generic_init($this->td, $this->salt, $this->iv);
/* Decrypt encrypted string */
$decrypted = mdecrypt_generic($this->td, $binstr);
/* Terminate decryption handle and close module */
mcrypt_generic_deinit($this->td);
mcrypt_module_close($this->td);
$this->decStr = trim($decrypted);
}
}
A: I suggest you not only encrypt but also sign the data. If you don't sign the data, you won't be able to tell reliably whether the user modified the data. Also, to avoid replay you may want to add some timestamp/validity period information into the data.
A: If you don't want your users to read it don't put it in a cookie;
In stead use Session's with a cookie that stays for a longer time. This way the data stays on the server and not at the computer of the user.
See this article about persistant sessions
A: For encryption example see "symmetric encryption" section in http://www.osix.net/modules/article/?id=606.
To prevent unauthorized modification, use HMAC: http://php.net/hash-hmac, and about hmac in general: http://en.wikipedia.org/wiki/HMAC, http://en.wikipedia.org/wiki/Message_authentication_code
And if you don't have to, don't store sensitive data in a cookie, even encrypted. You may want to read more about "data indirection".
A: If you absolutely must do this then you can use the symmetric encryption functionality in mcrypt.
http://php.net/mcrypt
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why does Installshield 2008 not roll back XML Changes? I am using Installshield 2008 Premier to edit some XML files which are already on the targetsystem. This process does work fine with the "XML file changes" function.
My problem is, that Installshield does not remove these changes on uninstall. I have set the "Remove element on uninstall" checkbox within the added element but InstallShield seems to consequently ignore this.
Has anybody an idea how to solve this problem?
A: Unfortunately, it doesn't appear solvable. Basically, the xml changes made during the install dont appear to be "finalized" until the installation actually completes.
Because of this, the xml file appears to get left with the "readonly" and "hidden" attributes set.
In my experience with IS2009, I've had to write an installScript to manually handle the changes (and removal).
There is a quite a lot of people with this issue over on the IS community forums, but sadly no official answer or acknowledgement..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get the count of null value columns per row in a return set? I'm looking for a query which will return me an extra column at the end of my current query which is the count of all columns within the return set which contain a null column. For example:
Col 1 - Col 2 - Col 3
A B 0
A NULL 1
NULL NULL 2
Is there a simple way to get this return set based on the row values rather than having to requery all the criteria which fetches the original rows?
A: Ugly solution:
select Col1, Col2,
case when Col1 is null then 1 else 0 end
+ case when Col2 is null then 1 else 0 end
as Col3
from (
select 'A' as Col1, 'B' as Col2
union select 'A', NULL
union select NULL, NULL
) z
This returns
Col1 Col2 Col3
NULL NULL 2
A NULL 1
A B 0
A: Oracle has a function NVL2() which makes this easy.
select col1,
col2,
col3,
...
NVL2(col1,0,1)
+NVL2(col2,0,1)
+NVL2(col3,0,1) coln
from whatever
A: select count(*) - count(ColumnName) as NumberOfNulls from yourTable
returns number of nulls in specific column. if you do this for every column you can get that data.
A: As in a similar post, SQL is not very suited to work across different columns within a row, but muach better on working across rows.
I'd suggest to turn the table into 'individual' facts about a row, e.g.
select <key>, col1 as value From aTable
UNION
select <key>, col2 as value From aTable
UNION
... and so on for the other columns to be summed.
This can be turned into a view i.e.
create view aView as (select as above).
Then the correct answer is just
select key, count(*)
from aView
where value is null
Group By key
A: create table TEST
(
a VARCHAR2(10),
b VARCHAR2(10),
c VARCHAR2(10)
);
insert into TEST (a, b, c)
values ('jas', 'abhi', 'shail');
insert into TEST (a, b, c)
values (null, 'abhi', 'shail');
insert into TEST (a, b, c)
values ('jas', null, 'shail');
insert into TEST (a, b, c)
values ('jas', 'abhi', null);
insert into TEST (a, b, c)
values ('jas', 'abhi', 'abc|xyz');
insert into TEST (a, b, c)
values ('jas', 'abhi', 'abc|xyz');
insert into TEST (a, b, c)
values ('jas', 'abhi', 'abc|xyz');
insert into TEST (a, b, c)
values (null, 'abhi', 'abc|xyz');
commit;
select sum(nvl2(a,null,1)),sum(nvl2(b,null,1)),sum(nvl2(c,null,1)) from test
where a is null
or b is null
or c is null
order by 1,2,3
A: If there isnt a very good reason you need to do this in the SQL, you should just do a for loop through the result set and count the NULL vlues then.
The cost goes from n^n to n..
A: You can use computed column:
CREATE TABLE testTable(
col1 nchar(10) NULL,
col2 nchar(10) NULL,
col3 AS (case when col1 IS NULL then (1) else (0) end+case when col2 IS NULL then (1) else (0) end)
)
It is not a pretty solution, but should work.
If you are dealing with a big number of columns and many of them you expect to be NULL then you could use sparse columns (available in SQL Server 2008). It will be optimised for NULL and it can automatically generate XML representation for each row of data in the table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is the best / easiest way to talk to SQLite from .NET? Question says it all, really.
My application is a time tracker. It's currently written as a spreadsheet, but there's just too much data and I would like to impose a bit more structure on it.
SQLite seems like a neat way to go.
I would be open to other suggestions, too.
A: There are some providers available:
http://sqlite.phxsoftware.com/
http://sourceforge.net/projects/sqlite-dotnet2
And you can get up and running in just three minutes according to this chap:
http://www.mikeduncan.com/sqlite-on-dotnet-in-3-mins/
Updated Jan 5 2009: We actually have this rolled out to our shared (partial trust) hosting environment and it works really well according to early customer feedback.
A: The current (april 2011) links seem to be here System.Data.SQLite 1.0.70.0 (3.7.6)
But there seems to be some problem with the installer. The doen't install SQLite.Interop.dll properly to GAC.
I did not install it in GAC and load it with absolut path and that works fine for me.
Just noted, that the ticket is open again. Check there for new work arounds and solutions.
A: If you are working on an open source application and want a lightweight interop layer to SQLite, then the SQLite code in Media Portal may be of interest (see SQLiteClient.cs)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Apache uses excessive CPU We run a medium-size site that gets a few hundred thousand pageviews a day. Up until last weekend we ran with a load usually below 0.2 on a virtual machine. The OS is Ubuntu.
When deploying the latest version of our application, we also did an apt-get dist-upgrade before deploying. After we had deployed we noticed that the load on the CPU had spiked dramatically (sometimes reaching 10 and stopping to respond to page requests).
We tried dumping a full minute of Xdebug profiling data from PHP, but looking through it revealed only a few somewhat slow parts, but nothing to explain the huge jump.
We are now pretty sure that nothing in the new version of our website is triggering the problem, but we have no way to be sure. We have rolled back a lot of the changes, but the problem still persists.
When look at processes, we see that single Apache processes use quite a bit of CPU over a longer period of time than strictly necessary. However, when using strace on the affected process, we never see anything but
accept(3,
and it hangs for a while before receiving a new connection, so we can't actually see what is causing the problem.
The stack is PHP 5, Apache 2 (prefork), MySQL 5.1. Most things run through Memcached. We've tried APC and eAccelerator.
So, what should be our next step? Are there any profiling methods we overlooked/don't know about?
A: Seeing an accept() call from your Apache process isn't at all unusual - that's the webserver waiting for a new request.
First of all, you want to establish what the parameters of the load are. Something like
vmstat 1
will show you what your system is up to. Look in the 'swap' and 'io' columns. If you see anything other than '0' in the 'si' and 'so' columns, your system is swapping because of a low memory condition. Consider reducing the number of running Apache children, or throwing more RAM in your server.
If RAM isn't an issue, look at the 'cpu' columns. You're interested in the 'us' and 'sy' columns. These show you the percentage of CPU time spent in either user processes or system. A high 'us' number points the finger at Apache or your scripts - or potentially something else on the server.
Running
top
will show you which processes are the most active.
Have you ruled out your database? The most common cause of unexpectedly high load I've seen on production LAMP stacks come down to database queries. You may have deployed new code with an expensive query in it; or got to the point where there are enough rows in your dataset to cause previously cheap queries to become expensive.
During periods of high load, do
echo "show full processlist" | mysql | grep -v Sleep
to see if there are either long-running queries, or huge numbers of the same query operating at once. Other mysql tools will help you optimise these.
You may find it useful to configure and use mod_status for Apache, which will allow you to see what request each Apache child is serving and for how long it has been doing so.
Finally, get some long-term statistical monitoring set up. Something like zabbix is straightforward to configure, and will let you monitor resource usage over time, such that if things get slow, you have historical baselines to compare against, and a better ieda of when problems started.
A: The answer ended up being not-Apache related. As mentioned, we were on a virtual machine. Our user sessions are pretty big (think 500kB per active user), so we had a lot of disk IO. The disk was nearly full, meaning that Ubuntu spent a lot of time moving things around (or so we think). There was no easy way to extend the disk (because it was not set up properly for VMWare). This completely killed performance, and Apache and MySQL would occasionally use 100% CPU (for a very short time), and the system would be so slow to update the CPU usage meters that it seemed to be stuck there.
We ended up setting up a new VM (which also gave us the opportunity to thoroughly document everything on the server). On the new VM we allocated plenty of disk space, and moved sessions into memory (using memcached). Our load dropped to 0.2 on off-peak use and around 1 near peak use (on a 2-CPU VM). Moving the sessions into memcached took a lot of disk IO away (we were constantly using about 2MB/s of disk IO, which is very bad).
Conclusion; sometimes you just have to start over... :)
A: Perhaps you where using worker MPM before and now you are not?
I know PHP5 does not work with the Worker MPM. On my Ubuntu server, PHP5 can only be installed with the Prefork MPM. It seems that PHP5 module is not compatible with multithreading version of Apache.
I found a link here that will show you how to get better performance with mod_fcgid
To see what worker MPM is see here.
A: I'd use dTrace to solve this mystery... if it was running on Solaris or Mac... but since Linux doesn't have it you might want to try their Systemtap, however I can't say anything about its usability since I haven't used it.
With dTrace you could easily sniff out the culprits within a day, and would hope with Systemtap it would be similiar
A: Another option that I can't assure you will do any good, but it's more than worth the effort. Is to read the detailed changelog for the new version, and review what might have changed that could remotely affect you.
Going through the changelogs has saved me more than once. Especially when some config options have changed and when something got deprecated. Worst case is it'll give you some clues as to where to look next
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Coverity for Java static analysis I'd like to get comments from people who have used or evaluated Coverity for statically analysing Java-code. I know it's popular in C/C++ world, but is it worth spending the money for Java analysis or am I better off with PMD, Findbugs and other Open Source tools?
A: I'll chip in with a somewhat relevant answer. I've used Klocwork for the both Java and C code. Klocwork is a close competitor of Coverity... cost-wise they are about the same ( look carefully, Klocwork looks cheaper until you actually buy what you need ), and feature-wise they fight back and forth.
For C/C++, it's great. For Java.... well, it helped find a lot of resource leaks ( #$@^#ing Java developers seem to forget that resources like file handles aren't garbage collected ), but it doesn't seem to find many "critical" bugs. It's probably because the language itself does help protect against some of the more basic but hard to find errors ( array overflows, pointer corruption, etc ).
Get Coverity in to run a demo, they are more than happy to. See what sort of things they find.
A: I'll add a limited me-too to the preceding answers, somewhat restricted by the Coverity NDA I'm bound by. Coverity Prevent has an impressive public track record for finding bugs in open source C/C++ code, but their Java product is a lot newer. (Coverity has a press release on my former employer, so I can say that it did help find and fix lots of bugs in our C/C++ code, more than I'd found in all my previous career in bug hunting.) FindBugs does an impressive job on Java code, and you can't beat the price. But the big point has already been made: try out both of them on your real code before you buy. There's no substitute for reality, and the conventional wisdom in static analysis is that there's surprisingly little overlap in what the tools discover.
A: If you aren't using anything today, I would start off with Findbugs and PMD. They are easy to install and use. Concentrate on reviewing and fixing correctness errors with Findbugs first - they recommend starting with High and Medium severity correctness errors as the checkers have very low false positives and you will get a good return on your time. Get developers to use PMD to cleanup the code, and the Findbugs plugin in Eclipse to review new code. Working incrementally will get the developers to understand and buy-in to the usefulness of these tools.
Coverity's Java checkers are still weak compared to their C/C++ checkers. We use Findbugs, PMD, Coverity and Klocwork because they all have different strengths and we are paranoid. If you aren't paranoid, you could stick with open source tools and get a lot of value. Or if you need security checking: then Klocwork or especially Fortify should do a more thorough job for you.
A: As others have said, the best way to decide is to try all these tools out.
Coverity recently announced a hosted static-analysis-as-a-service product called Code Spotter (https://code-spotter.com/), currently in beta. It's using the same analysis engine as the Coverity enterprise product, but it is wrapped in a different (simplified) user interface. Since this is a hosted service, it is very easy to play with it to get a sense of the Coverity analysis capabilities.
At the time of this writing, Code Spotter is Java-only, but other Coverity supported languages should be coming soon.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Is .NET memory management faster in managed code than in native code? I would have thought that it would be clear cut whether memory allocation is faster in managed code than in native code - but there seems to be some controversy. Perhaps memory management under a Virtual Machine be faster because of no context-swapping calls to the OS, but then I see that the VM would itself need to make periodic calls to the OS for more memory, and it has the management overheads the memory itself rather than the OS.
Rather than making unsubstantiated assertions like I have, please provide links to references that support your position.
A: Take a read of http://msdn.microsoft.com/en-us/library/ms973852.aspx
It goes into some details on how memory allocation works in .NET and briefly compares it to the C++ model.
In summary, memory allocation in .NET involves grabbing the current stack point as the object's address and adding the object's data size to the stack pointer. C++ by comparison has to search through a list of freed pointers for an area of the heap large enough for the object. In most cases therefore, .NET will be faster.
A: Listen to Jeff Richter of Wintellect, he's an authority on the subject:
http://www.dotnetrocks.com/default.aspx?showNum=361
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: What ways are there of drawing 3D trees using Java and OpenGL? I know how to draw basic objects using JOGL or LWJGL to connect to OpenGL. What I would like is something that can generate some kind of geometry for trees, similar to what SpeedTree is famous for. Obviously I don't expect the same quality as SpeedTree.
I want the trees to not look repetitive. Speed is not a concern, I do not expect to need more than 100 trees on screen at one time.
Are there free tree-drawing libraries available in Java? Or sample code or demos?
Is there anything in other languages which I could port or learn from?
A: http://arbaro.sourceforge.net/
http://www.propro.ru/go/Wshop/povtree/povtree.html
Non java: http://www.aust-manufaktur.de/austt.html
A: There are thousands of methods. A better question would define 'best' in a more confined way. Are we talking 'best' as in speed of drawing (suitable for thousands or millions of trees)? Best as in best-looking? etc.
A: 2D or 3D?
In 2D, a common way is to use L-systems.
I also tried an OO approach, defining objects for trunk, branches, leaves, all extending an abstract class and implementing a Genotype interface (to vary the kind of trees).
Not sure if it is efficient (lot of objects created, particularly if I animate the tree) but interesting to do.
A: Here are a couple resources that may be helpful:
*
*gamedev thread on the subject - contains some useful advice/suggestions
*ngPlant - an open-source procedural plant generation tool. It is not written in Java, but you may be able to find ideas in its algorithms.
A: If you are using eclipse/SWT, try Draw 2D.
A: If you're serious about getting good-looking, fast trees, there's a commercial C++ library SpeedTree. Lots of big-time games use it (e.g., GTA, Elder Scrolls).
A: A combination of OpenSceneGraph and SpeedTree has worked for me.
A: I know of two libraries that enable the usage of OpenGl with java.
LWJGL (Light Weight Java Gaming Library), which imo is the better one due to its simplicity and its similarity to using opengl with c/c++.
JOGL If you want to mix swing components with opengl this may be the better choice, I've never used it but several years ago it was known to be pretty buggy, I don't know if its matured since then.
As for drawing trees, there are many ways to do so like the other poster said, you might want to be more specific.
edit: I guess I misunderstood the question a bit, oh well : / You can load in a 3d model of a tree and display that.
A: http://www.codeplex.com/LTrees has some source code on that. it's c++ though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Is SVN 1.5 Merge-tracking ready for prime-time? I'm already using SVN 1.5, both sever(VisualSVN 1.5.1) and client-side(TortoiseSVN 1.5.1) but we are using a fairly lengthy SVN Branch-Merge dance.
How ready is the Merge-Tracking facility of SVN 1.5.x and is it yet possible to use it from TortoiseSVN?
A: Subversion releases are generally pretty solid, version 1.5 has been in the works for 2 years. That being said, there are always some known issues.
A: It is productive. You can see the merged revision in the Log-Dialog and the reintegrate merge works fine.
However, there is no graphical representation of the merges inside revision graph and according to stephan KΓΌng there will be no merge info in revision graph due to performance reasons.
The merge algorithm will change in future releases to catch some edge-cases better, but it is working real fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How can I iterate recursively though a sharepoint list using webservices? in sharepoint webservices, I can use getListItems() to obtain the child elements of a list.
In a document library, sometimes the element is a folder.
"ows_FSObjType = 1"
Is there any way to ask SP for the child elements of this folder?
Querying with getListItems() using the folder ID gives me a SOAP Exception.
Edit:
I found that this webservice has got more method
Site Data Webservice
There is an "enumerate folder" method, which has got a "isFolder" property, but no method to recurse its contents.
Thank you, Sam. :)
A: On the GetListItems method, one of the optional parameters is an XMLNode called "QueryOptions". One of the elements you can put in that node is <Folder>.
So you should be able to pass in something like:
<QueryOptions>
<Folder>/My/Path/Here</Folder>
</QueryOptions>
I may be off a bit syntatically (didn't try to build and run a query when making this post), but the general idea should be sound. You can see more details on this in the MSDN GetListItems Reference.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I stop a UIScrollView from bouncing horizontally? I have a UIScrollView that shows vertical data, but where the horizontal component is no wider than the screen of the iPhone. The problem is that the user is still able to drag horizontally, and basically expose blank sections of the UI. I have tried setting:
scrollView.alwaysBounceHorizontal = NO;
scrollView.directionalLockEnabled = YES;
Which helps a little, but still doesn't stop the user from being able to drag horizontally. Surely there is a way to fix this easily?
A: That works for me in Swift:
scrollView.alwaysBounceHorizontal = false
scrollView.bounces = false
A: Try setting scrollView.bounces to NO and scrollView.alwaysBounceVertical to YES.
A: scrollView.bounces = NO;
Worked for me.
A: Whether or not a view scrolls (and bounces) horizontally depends on three things:
*
*The content size
*The left and right content insets
*The width of the scroll view -
If the scroll view can fit the content size plus the insets then it doesn't scroll or bounce.
Avoid horizontal bouncing like so:
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width - scrollView.contentInset.left - scrollView.contentInset.right, height);
I am adding this answer because the previous ones did not take contentInset into account.
A: That's strange, because whenever I create a scroll view with frame and content size within the bounds of the screen on either dimension, the scroll view does not scroll (or bounce) in that direction.
// Should scroll vertically but not horizontally
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
scrollView.contentSize = CGSizeMake(320, 1000);
Are you sure the frame fits completely within the screen and contentSize's width is not greater than the scroll view's width?
A: The checkbox for bounce vertically in storyboard-scrollview can simply help...
A: Make sure the UIScrollView's contentSize is not wider than the UIScrollView itself. In my own apps this was enough to avoid horizontal scrolling, except in cases where I got really crazy swiping in random directions (e.g., starting a scroll while the view was still decelerating).
A: If anyone developing for OS X is looking here, as of OS X 10.7, the solution is to set the horizontalScrollElasticity property to false/NO on the scroll view, like this:
Swift:
scrollView.horizontalScrollElasticity = false
Objective-C:
scrollView.horizontalScrollElasticity = NO
A: Something to keep in mind: You know there's nothing extra to see horizontally, but will your users know that? You may want a little horizontal bounce, even if there's no extra content to show horizontally. This let's the user know that their attempts to scroll horizontally are not being ignored, there's just nothing there for them to see. But, yeah, often you really don't want the bounce.
A: My version for webViews, a common solution:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[webView.scrollView setContentSize: CGSizeMake(webView.frame.size.width, webView.scrollView.contentSize.height)];
}
A: You can disable horizontal bounces like this:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView.contentOffset.x < 0) {
scrollView.contentOffset = CGPointMake(0, scrollView.contentOffset.y);
} else if (scrollView.contentOffset.x > scrollView.contentSize.width) {
scrollView.contentOffset = CGPointMake(scrollView.contentSize.width, scrollView.contentOffset.y);
}
}
It resets the contentOffset.x manually and won't affect the vertical bounces. It works...
A: In my case, i just need to set this line:
collectionView.bounces = false
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Java: Serializing unknown Arraysize If I safe an Array and reload it, is there a possibility to get the size if its unknown?
Thanks
A: What do you mean by "unknown"? You can get the length of any java array with the length field.
int[] myArray = deserializeSomeArray();
int size = myArray.length;
A: It sounds like you're serializing and storing the individual objects in the array (after much reading between the lines). Use the ObjectOutputStream to store the array itself. If the objects stored in the array are serializable, they'll be stored too. When you deserialize you'll get the entire array back intact.
A: I think you need to supply some more information. How are you saving the array? Using an ObjectOutputStream?
A: No because the length of the array is just the size of memory allocated divided by the size of the object stored in it, and since no objects have a size of 0 you will always have a proper length, (which could be 0)
A: If you use ObjectInputStream.readObject() to read the saved array, it will be reconstituted with the proper length and you can just read the size with array.length.
A: Attempting to read between the lines...
If you are actually reading array, then (unlike C) all arrays know their length. Java is a safe language, so the length is necessary for bounds checking.
MyType[] things = (MyType[])in.readObject();
int len = things.length;
Perhaps your difficulty is that you are doing custom (de)serialisation and are writing out individual elements of the array (hint: don't - use an array). In the case you need to catch OptionDataException to detect the end of the enclosing object's custom data:
private static final MyType[] NOTHING = new MyType[0];
private transient MyType[] things = NOTHING;
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject(); // Do not forget this call!
for (MyType thing : things) {
out.writeObject(thing);
}
}
private void readObject(
ObjectInputStream in
) throws IOException, ClassNotFoundException {
in.defaultReadObject(); // Do not forget this call!
List<MyType> things = new ArrayList<MyType>();
try {
for (;;) {
things.add((MyType)in.readObject();
}
} catch (OptionalDataException exc) {
// Okay - end of custom data.
}
this.things = things.toArray(NOTHING);
}
If you are going to do that sort of thing, it's much better to write out the number of objects you are going to read as an int before the actual data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: AutoPostback with TextBox loses focus A TextBox is set to AutoPostback as changing the value should cause a number of (display-only) fields to be recalculated and displayed.
That works fine.
However, when the field is tabbed out of, the focus briefly moves on to the next field, then disappears when the page is redrawn so there is no focus anywhere.
I want the focus to be on the new field, not the textbox I've just changed.
Is there a way to work out which field had the focus and force it to have it again when the page is redrawn?
A: This is "by design". If you are using ASP.NET 2.0+ you can try calling the Focus method of your TextBox once the postback occurs (preferably in the TextChanged event of the TextBox).
I am not sure if there is any built-in way to track focus but I found this article in CodeProject which should do the trick.
A: You could also consider refresh display-only fields using AJAX UpdatePanel. This way you won't lose focus from the new field.
Also I have proposed pure server-side solution based on WebControl.Controls.TabIndex analysis, you can use it, if you like.
A: This is what is happening:
1) TAB on a field - client event
2) Focus on next field - client event
3) Postback - server event
4) Page redrawn - client event new page overrides preious client events
The solution of your problem is to:
a) get the element that has gained focus BEFORE postback
<script>
var idSelected;
$("input").focusin(function () {
idSelected = this.id;
});
</script>
b) store the ClientID (actually in var idSelected) somewhere (i.e. an hidden Textbox, vith ViewState = true) BEFORE postback
** b) get ClientID ** (extract from hidden TextBox and put it in var idSelected) AFTER postback
d) get the element with ClientID and set focus AFTER postback
<script>
$(document).ready(function () {
if (idSelected != null) {
$("#" + idSelected).focus();
idSelected = null;
});
});
</script>
Note: this sample scripts use JQuery.
Remember to put Jquery.js in your solution and a reference in your page
<form id="form1" runat="server" enctype="multipart/form-data" method="post">
<asp:ScriptManager runat="server" >
<Scripts>
<asp:ScriptReference Path="~/Scripts/jquery.js" ScriptMode="Auto" />
....
Note2: this solution works without AJAX.
Look at this answer: to make Javascript work over Ajax you must use code like this:
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function EndRequestHandler(sender, args)
{
MyScript();
}
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Should exceptions be in a different project When structuring a visual studio solution I tend to structure it so that various components are in different project (As I would assume most people do) I tend to have a bunch of User defined exceptions.
The Question is should these exceptions be in a separate project to the (for example) Model classes?
I tend to put them in a sub-namespace of the model, and organise them in a directory within the Model project. but should they be in a separate project all together?
A: It depends on how you imagine them being used and how you deploy your application.
As a rule of thumb - never create more packages/assemblies than needed.
There's one strong case for putting Exceptions and Interface classes in their own assembly and that's when they're supposed to be shared among clients that not necesarily need to "full" package, one common scenario is when using remoting another is when building plugin architechtures.
A: Depends on how they're used I guess. If the exception is confined to a single project, put it there. If several projects use it, put it in a separate project.
A: I wouldn't bother as long as the message strings are configurable (properties file/xml). Having a generic top level interface would definitely help though, if the exceptions were to span across projects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using ALTER to drop a column if it exists in MySQL How can ALTER be used to drop a column in a MySQL table if that column exists?
I know I can use ALTER TABLE my_table DROP COLUMN my_column, but that will throw an error if my_column does not exist. Is there alternative syntax for dropping the column conditionally?
I'm using MySQL version 4.0.18.
A: For MySQL, there is none: MySQL Feature Request.
Allowing this is arguably a really bad idea, anyway: IF EXISTS indicates that you're running destructive operations on a database with (to you) unknown structure. There may be situations where this is acceptable for quick-and-dirty local work, but if you're tempted to run such a statement against production data (in a migration etc.), you're playing with fire.
But if you insist, it's not difficult to simply check for existence first in the client, or to catch the error.
MariaDB also supports the following starting with 10.0.2:
DROP [COLUMN] [IF EXISTS] col_name
i. e.
ALTER TABLE my_table DROP IF EXISTS my_column;
But it's arguably a bad idea to rely on a non-standard feature supported by only one of several forks of MySQL.
A: Chase Seibert's answer works, but I'd add that if you have several schemata you want to alter the SELECT thus:
select * from information_schema.columns where table_schema in (select schema()) and table_name=...
A: There is no language level support for this in MySQL. Here is a work-around involving MySQL information_schema meta-data in 5.0+, but it won't address your issue in 4.0.18.
drop procedure if exists schema_change;
delimiter ';;'
create procedure schema_change() begin
/* delete columns if they exist */
if exists (select * from information_schema.columns where table_schema = schema() and table_name = 'table1' and column_name = 'column1') then
alter table table1 drop column `column1`;
end if;
if exists (select * from information_schema.columns where table_schema = schema() and table_name = 'table1' and column_name = 'column2') then
alter table table1 drop column `column2`;
end if;
/* add columns */
alter table table1 add column `column1` varchar(255) NULL;
alter table table1 add column `column2` varchar(255) NULL;
end;;
delimiter ';'
call schema_change();
drop procedure if exists schema_change;
I wrote some more detailed information in a blog post.
A: I know this is an old thread, but there is a simple way to handle this requirement without using stored procedures. This may help someone.
set @exist_Check := (
select count(*) from information_schema.columns
where TABLE_NAME='YOUR_TABLE'
and COLUMN_NAME='YOUR_COLUMN'
and TABLE_SCHEMA=database()
) ;
set @sqlstmt := if(@exist_Check>0,'alter table YOUR_TABLE drop column YOUR_COLUMN', 'select ''''') ;
prepare stmt from @sqlstmt ;
execute stmt ;
Hope this helps someone, as it did me (after a lot of trial and error).
A: You can use this script, use your column, schema and table name
IF EXISTS (SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName'
AND TABLE_SCHEMA = SchemaName)
BEGIN
ALTER TABLE TableName DROP COLUMN ColumnName;
END;
A: I just built a reusable procedure that can help making DROP COLUMN idempotent:
-- column_exists:
DROP FUNCTION IF EXISTS column_exists;
DELIMITER $$
CREATE FUNCTION column_exists(
tname VARCHAR(64),
cname VARCHAR(64)
)
RETURNS BOOLEAN
READS SQL DATA
BEGIN
RETURN 0 < (SELECT COUNT(*)
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA` = SCHEMA()
AND `TABLE_NAME` = tname
AND `COLUMN_NAME` = cname);
END $$
DELIMITER ;
-- drop_column_if_exists:
DROP PROCEDURE IF EXISTS drop_column_if_exists;
DELIMITER $$
CREATE PROCEDURE drop_column_if_exists(
tname VARCHAR(64),
cname VARCHAR(64)
)
BEGIN
IF column_exists(tname, cname)
THEN
SET @drop_column_if_exists = CONCAT('ALTER TABLE `', tname, '` DROP COLUMN `', cname, '`');
PREPARE drop_query FROM @drop_column_if_exists;
EXECUTE drop_query;
END IF;
END $$
DELIMITER ;
Usage:
CALL drop_column_if_exists('my_table', 'my_column');
Example:
SELECT column_exists('my_table', 'my_column'); -- 1
CALL drop_column_if_exists('my_table', 'my_column'); -- success
SELECT column_exists('my_table', 'my_column'); -- 0
CALL drop_column_if_exists('my_table', 'my_column'); -- success
SELECT column_exists('my_table', 'my_column'); -- 0
A: Perhaps the simplest way to solve this (that will work) is:
*
*CREATE new_table AS SELECT id, col1, col2, ... (only the columns you actually want in the final table)
FROM my_table;
*RENAME my_table TO old_table, new_table TO my_table;
*DROP old_table;
Or keep old_table for a rollback if needed.
This will work but foreign keys will not be moved. You would have to re-add them to my_table later; also foreign keys in other tables that reference my_table will have to be fixed (pointed to the new my_table).
Good Luck...
A: I realise this thread is quite old now, but I was having the same problem.
This was my very basic solution using the MySQL Workbench, but it worked fine...
*
*get a new sql editor and execute SHOW TABLES to get a list of your tables
*select all of the rows, and choose copy to clipboard (unquoted) from the context menu
*paste the list of names into another editor tab
*write your query, ie ALTER TABLE x DROP a;
*do some copying and pasting, so you end up with separate query for each table
*Toggle whether the workbench should stop when an error occurs
*Hit execute and look through the output log
any tables which had the table now haven't
any tables which didn't will have shown an error in the logs
then you can find/replace 'drop a' change it to 'ADD COLUMN b INT NULL' etc and run the whole thing again....
a bit clunky, but at last you get the end result and you can control/monitor the whole process and remember to save you sql scripts in case you need them again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "119"
} |
Q: How to get the function name while in a function for debug strings? I want to output the function name each time it is called, I can easily copy and paste the function name, however I wondered if there was a shortcut that would do the job for me?
At the moment I am doing:
SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
qDebug("lynxThreeFile::readSlideInfoHeader");
}
but what I want is something generic:
SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
qDebug(this.className() + "::" + this.functionName());
}
A: If you are using gcc you may find __PRETTY_FUNCTION__ more to your liking.
A: __func__ is c99 ( which does in turn mean it might not work with visual studio - but hey it's standard :o) )
__FUNCTION__ works pretty much everywhere
__PRETTY_FUNCTION__ is gnu specific and returns the full qualified name with (namespaces?), classname, returntype, functionname, parameterslist
A: If you check out boost there is a macro BOOST_CURRENT_FUNCTION that is portable across platforms. In the C99 standard there is a compiler variable __func__ that has the desired effect. I believe has been accepted into the C++0x standard. A reasonable number of compilers will already support this.
A: "__FUNCTION__" is supported by both MSVC and GCC and should give you the information you need.
A: I see from your example that you are using Qt. In which case your best bet is to use Q_FUNC_INFO found in <QGlobal>. Here's the description:
Expands to a string that describe the
function the macro resides in. How
this string looks more specifically is
compiler dependent. With GNU GCC it is
typically the function signature,
while with other compilers it might be
the line and column number.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: JavaScript, inputstream and DIB? Is there any useful way to load DIB into inputstream and get a handle to it and all that in JavaScript (js) ?
A: Assuming DIB means Device Independent Bitmap...
If the DIB is on the client side in a browser, then I don't think you can do this with just the JS in the browser. You would need some java or flash or something else, because javascript in the browser has no way to read stuff from the filesystem.
If the DIB is on the server, you can use an ajax request to fetch it. In the callback, copy the returned data into an object where you can then manipulate the data as needed.
Once you are done manipulating the image data, you can use a canvas or an img tag to display it.
http://developer.mozilla.org/en/Canvas_tutorial/Using_images
I hadn't tried this until I saw your question, but an img tag with a data url is pretty interesting. Using the data url in the img src doesn't work in IE, but it does in FF and Opera. IE doesn't have a canvas tag, but they do have something similar. Some smart guys at google wrote a javascript library to enable the canvas tag in IE by translating into something IE understands.
http://code.google.com/p/explorercanvas/
I hope this helps. If not, maybe it is at least interesting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting the schema for a table Given an SQLConnection object how can you get a schema for a single table?
I seemed to be able to get the schema from a DataSet which I'd gotten from running a query, but all the schema info I could get from the connection seemed to be related to what tables were available and not the actual details on the tables.
A: This code will do what you want (obviously change the table name, server name etc):
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
string query = "SELECT * FROM t where 1=0";
string connectionString = "initial catalog=test;data source=localhost;Trusted_Connection=Yes";
DataTable tblSchema;
using (SqlConnection cnn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = cnn.CreateCommand())
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cnn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.KeyInfo))
{
tblSchema = rdr.GetSchemaTable();
}
cnn.Close();
}
}
int numColumns = tblSchema.Columns.Count;
foreach (DataRow dr in tblSchema.Rows)
{
Console.WriteLine("{0}: {1}", dr["ColumnName"], dr["DataType"]);
}
Console.ReadLine();
}
}
}
A: I think accessing the schema from the query (via GetSchemaTable) is the only way to do it.
You can run a query which returns no rows (select * from table where 1=2) if the schema is all you're interested in.
You should use the KeyInfo CommandBehaviour to execute the source query, as otherwise not all the information returned is guaranteed to be accurate
Command.ExecuteReader(CommandBehavior.KeyInfo)
A: SQL Server - query the catalog views... sysobjects, syscolumns etc if SQL 2000 or earlier... sys.objects, sys.columns etc if SQL 2005 or higher. (although the older views are still available it is advisable to use the newer ones)
Complete reference here:
http://msdn.microsoft.com/en-us/library/ms189783.aspx
Example:
select so.name, sc.*
from sys.objects as so
inner join sys.columns as sc on sc.object_id = so.object_id
where so.name='some_table'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Showing a loader while Spry XMLDataset loads the data I am using Spry (SpryData.js,xpath.js)
var ds1 = new Spry.Data.XMLDataSet("_db/db.xml", "bildiriler/bildiri",{useCache:false});
// load the xml tree
....
<!-- use it in a loop -
Sometimes the page use "ds1.loadData();" to refresh the data -->
<div spry:region="ds1" spry:repeatchildren="ds1">
<a href="#">{author}</a></div>
So how can I show a loader animation or "Loading text" while XML data is loading
(It takes a long time -about 2 sec from a slow CD-. My XML file is big 100KB )
A: I am not quite good at Spry, but can't you add a css background to the div placeholder (<div spry:region="ds1" ...) which will be shown at all time (and probably can be replaced through an observer that sets the background-image of the placeholder when the rows are loaded)...
A: Yes. I found it (strangely, not from the docs of Spry on http://labs.adobe.com/technologies/spry)
I found it from this example -> http://www.infoaccelerator.net/blog/archives.cfm/date/2006/7
i put this line into the div tag (spry:region) :
<p spry:state ="loading"> Loading ( text or an image ) </p>
A: <div align="center" spry:region="dsmain" spry:state="loading" >
<img src="../icon/Loader/1.gif" />
<br />please wait ...
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Twin Slider control .net Has anyone seen a good twin slider control for .Net (Win forms or WPF).
I'm looking for something that will allow me to select a range from within a set so the first slider would be the start of the range and the second would be the end.
I remember seeing a Swing double slider but it was 6 years ago and I can't for the life of me remember who made it. It was open source though.
A: Devexpress have a good one:
The RangeTrackBarControl control extends the functionality provided by the TrackBarControl enabling end-users to select a range of values. Two sliders can be used to set the minimum and maximum values:
alt text http://www.devexpress.com/Help/XtraEditors/img/RangeTrackBarControl.png
you can get them free from:
http://www.devexpress.com/Products/Free/WebRegistration/
hope this helps!
A: For some reason, I cannot comment on the previous answer. DevExpress does not appear to offer any free controls any more; only a free 30-day trial.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to do dynamic URL redirects in Struts 2? I'm trying to have my Struts2 app redirect to a generated URL. In this case, I want the URL to use the current date, or a date I looked up in a database. So /section/document becomes /section/document/2008-10-06
What's the best way to do this?
A: Here's how we do it:
In Struts.xml, have a dynamic result such as:
<result name="redirect" type="redirect">${url}</result>
In the action:
private String url;
public String getUrl()
{
return url;
}
public String execute()
{
[other stuff to setup your date]
url = "/section/document" + date;
return "redirect";
}
You can actually use this same technology to set dynamic values for any variable in your struts.xml using OGNL. We've created all sorts of dynamic results including stuff like RESTful links. Cool stuff.
A: If anyone wants to redirect directly in ActionClass:
public class RedirecActionExample extends ActionSupport {
HttpServletResponse response=(HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
url="http://localhost:8080/SpRoom-1.0-SNAPSHOT/"+date;
response.sendRedirect(url);
return super.execute();
}
Edit: Added a missing quote.
A: I ended up subclassing Struts' ServletRedirectResult and overriding it's doExecute() method to do my logic before calling super.doExecute(). it looks like this:
public class AppendRedirectionResult extends ServletRedirectResult {
private DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
@Override
protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
String date = df.format(new Date());
String loc = "/section/document/"+date;
super.doExecute(loc, invocation);
}
}
I'm not sure if this is the best way to do it, but it works.
A: One can also use annotations and the Convention plug-in to avoid repetitive configuration in struts.xml:
@Result(location="${url}", type="redirect")
The ${url} means "use the value of the getUrl method"
A: You can redirect to another action using annotation -
@Result(
name = "resultName",
type = "redirectAction",
params = { "actionName", "XYZAction" }
)
A: One can redirect directly from an interceptor without regard to which action is involved.
In struts.xml
<global-results>
<result name="redir" type="redirect">${#request.redirUrl}</result>
</global-results>
In Interceptor
@Override
public String intercept(ActionInvocation ai) throws Exception
{
final ActionContext context = ai.getInvocationContext();
HttpServletRequest request = (HttpServletRequest)context.get(StrutsStatics.HTTP_REQUEST);
request.setAttribute("redirUrl", "http://the.new.target.org");
return "redir";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: What is the canonical way to determine commandline vs. http execution of a PHP script? I have a PHP script that needs to determine if it's been executed via the command-line or via HTTP, primarily for output-formatting purposes. What's the canonical way of doing this? I had thought it was to inspect SERVER['argc'], but it turns out this is populated, even when using the 'Apache 2.0 Handler' server API.
A: The documentation page for php_sapi_name clearly states how it works:
Returns a lowercase string that describes the type of interface (the Server API, SAPI) that PHP is using....
Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.
I'm not sure why hop doesn't think that PHP is for serious programmers (I'm a serious programmer, and I use PHP daily), but if he wants to help clarify the documentation then perhaps he can audit all possible web servers that PHP can run on and determine the names of all possible interface types for each server. Just make sure to keep that list updated as new web servers and interfaces are added.
Also, Bobby said:
I'm intrigued as to why the doc. example inspects the first 3 characters, whilst the description states the string should be exactly "CGI"
The description for the example states:
This example checks for the substring cgi because it may also be cgi-fcgi.
A: Use the php_sapi_name() function.
if (php_sapi_name() == "cli") {
// In cli-mode
} else {
// Not in cli-mode
}
Here are some relevant notes from the docs:
php_sapi_name β Returns the type of interface between web server and PHP
Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.
In PHP >= 4.2.0, there is also a predefined constant, PHP_SAPI, that has the same value as php_sapi_name().
A: This will always work. (If the PHP version is 4.2.0 or higher)
define('CLI', PHP_SAPI === 'cli');
Which makes it easy to use at the top of your scripts:
<?php PHP_SAPI === 'cli' or die('not allowed');
A: Here is Drupal 7 implementation: drupal_is_cli():
function drupal_is_cli() {
return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
}
However Drupal 8 recommends using PHP_SAPI === 'cli'
A: I think
$_SERVER['REMOTE_ADDR']
will not be populated from the CLI.
Also, all the HTTP_* keys in the $_SERVER superglobal won't be populated from the CLI, or do it the right way hop just mentioned :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "166"
} |
Q: jQuery: Problem with windowed controls in IE6 I have a web page which contains a select box. When I open a jQuery Dialog it is displayed partly behind the select box.
How should I approach this problem? Should I hide the select box or does jQuery offer some kind of 'shim' solution. (I have Googled but didn't find anything)
Here is some code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>testJQuery</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="Rational Application Developer">
<link rel="stylesheet" href="theme/smooth/theme.css" type="text/css" media="screen" />
</head>
<body>
<a class="pop" href="nix">Click me</a>
<p/>
<select size="20">
<option>s jl fjlkdjfldjf l*s ldkjsdlfkjsdl fkdjlfks dfldkfjdfkjlsdkf jdksdjf sd</option>
<option>s jl fjlkdjfldjf l*s ldkjsdlfkjsdl fkdjlfks dfldkfjdfkjlsdkf jdksdjf sd</option>
<option>s jl fjlkdjfldjf l*s ldkjsdlfkjsdl fkdjlfks dfldkfjdfkjlsdkf jdksdjf sd</option>
<option>s jl fjlkdjfldjf l*s ldkjsdlfkjsdl fkdjlfks dfldkfjdfkjlsdkf jdksdjf sd</option>
<option>s jl fjlkdjfldjf l*s ldkjsdlfkjsdl fkdjlfks dfldkfjdfkjlsdkf jdksdjf sd</option>
</select>
<div id="xyz" class="flora hiddenAsset">
<div id="dialog" title="Edit Link">
<p>Enter the link details:</p>
<table width="80%" border="1">
<tr><td>URL</td><td><input id="url" style="width:100%" maxlength="200" value="{url}"/></td></tr>
<tr><td>Title</td><td><input id="title" style="width:100%" maxlength="200" value="{title}"/></td></tr>
<tr><td>Target</td><td><input id="target" size="20" maxlength="200" value="{target}"/></td></tr>
</table>
</div>
</div>
<script type="text/javascript" src="../script/firebug/firebug.js"></script>
<script type="text/javascript" src="jquery-1.2.6.js"></script>
<script type="text/javascript" src="jquery-ui-1.5.2.js"></script>
<script type="text/javascript" src="jqSOAPClient.js"></script>
<script type="text/javascript">
(function($){
$(document).ready(function(){
console.debug('ready');
$('.hiddenAsset').hide();
$('a.pop').bind('click', showDialog);
console.debug('ready - done');
});
var showDialog = function(){
console.debug('show');
$('#dialog').dialog({
modal: true,
overlay: {
backgroundColor: '#666',
opacity: '.3',
filter: 'alpha(opacity=30)'
},
width: '400px',
height: '300px',
buttons: {
Ok: function() {
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
});
console.debug('show-done');
return false;
};
})(jQuery);
</script>
</body>
</html>
A: This doesn't have anything to do with jQuery in particular. This is a known bug in IE 6 - Windows-native select boxes always appear on top of other elements. The only thing you can do is hide the select boxes when they're covered up - usually replacing them with something that looks like the select box.
A: I eventually found a plug-in which helps - bgiframe Strange that it is available as a plug-in. Why isn't it integrated in the main UI?!
Tried it out but, unfortunately, it screws up my dialog! The dialog contents are all shifted left by 30-40 pixels :-( . Next problem...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to get a file's extension in PHP? This is a question you can read everywhere on the web with various answers:
$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);
$exts = split("[/\\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];
etc.
However, there is always "the best way" and it should be on Stack Overflow.
A: The simplest way to get file extension in PHP is to use PHP's built-in function pathinfo.
$file_ext = pathinfo('your_file_name_here', PATHINFO_EXTENSION);
echo ($file_ext); // The output should be the extension of the file e.g., png, gif, or html
A: You can try also this (it works on PHP 5.* and 7):
$info = new SplFileInfo('test.zip');
echo $info->getExtension(); // ----- Output -----> zip
Tip: it returns an empty string if the file doesn't have an extension
A: There is also SplFileInfo:
$file = new SplFileInfo($path);
$ext = $file->getExtension();
Often you can write better code if you pass such an object around instead of a string. Your code is more speaking then. Since PHP 5.4 this is a one-liner:
$ext = (new SplFileInfo($path))->getExtension();
A: The "best" way depends on the context and what you are doing with that file extension.
However,
pathinfo in general is the best when you consider all the angles.
pathinfo($file, PATHINFO_EXTENSION)
It is not the fastest, but it is fast enough. It is easy to read, easy to remember and reuse everywhere. Anyone can understand it at a glance and remove PATHINFO_EXT flag if they need more info about the file.
β strrpos method. described in several answers is faster yes but requires additional safety checks which, in turn, requires you to wrap it inside a function, to make it easily reusable.
Then you must take the function with you from project to project or look it up.
Wrapping it in a function call with extra checks also makes it slower and if you need any other info about the file you now have other methods to call and at that point, you lose the speed advantage anyway whilst having a solution that's harder to read.
The potential for speed is there but is not worth it unless you need to address such a bottleneck.
β I'd also rule out any ideas using substr, explode, and most other manual manipulations for the same reasons mentioned above.
βSplFileInfo is very cool but takes up much more brain space with a lot of interfaces that you no doubt waste time learning only to look them up again next time. I'd only use it in specific cases where you will find the extra interfaces worth someone learning Spl when they come back to add/edit your code later.
β I would not consider preg_replace at all as any regex function in PHP is on average 3 times slower than any other function, is harder to read, and is in most cases can easily be done with something simpler. Regex is powerful and it has its place in those specific situations where it can replace several method calls and condition checks in one line.
Getting a file extension this way is like using an anvil to hammer in a nail.
While of course "the best" would come down to public opinion, I'd argue that other methods are only "the best" in specialized cases.
For example, if you just want to check for a specific type then I wouldn't use any of the suggested methods as stripos would be the fastest case insensitive comparison to use.
if (stripos('/here/is/sOme.fiLe.PdF', '.pdf', -4) !== false )
{
//its a pdf file
}
But again pathinfo would still be nicer to read and probably worth the performance cost.
But what about https://ome.Com.///lica.ted?URLS ?
Extracting paths from URLs is a separate concern that is outside the scope of the question and will require an extra step in any case where a simple one-time string comparison won't do.
A: Here is an example. Suppose $filename is "example.txt",
$ext = substr($filename, strrpos($filename, '.', -1), strlen($filename));
So $ext will be ".txt".
A: pathinfo is an array. We can check directory name, file name, extension, etc.:
$path_parts = pathinfo('test.png');
echo $path_parts['extension'], "\n";
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['filename'], "\n";
A: substr($path, strrpos($path, '.') + 1);
A: A quick fix would be something like this.
// Exploding the file based on the . operator
$file_ext = explode('.', $filename);
// Count taken (if more than one . exist; files like abc.fff.2013.pdf
$file_ext_count = count($file_ext);
// Minus 1 to make the offset correct
$cnt = $file_ext_count - 1;
// The variable will have a value pdf as per the sample file name mentioned above.
$file_extension = $file_ext[$cnt];
A: Do it faster!
In other words, if you only work with a filename, please stop using pathinfo.
I mean, sure if you have a full pathname, pathinfo makes sense because it's smarter than just finding dots: the path can contain dots and filename itself may have none. So in this case, considering an input string like d:/some.thing/myfile, pathinfo and other fully equipped methods are a good choice.
But if all you have is a filename, with no path, it's simply pointless to make the system work a lot more than it needs to. And this can give you a 10x speed boost.
Here's a quick speed test:
/* 387 ns */ function method1($s) {return preg_replace("/.*\./","",$s);} // edge case problem
/* 769 ns */ function method2($s) {preg_match("/\.([^\.]+)$/",$s,$a);return $a[1];}
/* 67 ns */ function method3($s) {$n = strrpos($s,"."); if($n===false) return "";return substr($s,$n+1);}
/* 175 ns */ function method4($s) {$a = explode(".",$s);$n = count($a); if($n==1) return "";return $a[$n-1];}
/* 731 ns */ function method5($s) {return pathinfo($s, PATHINFO_EXTENSION);}
/* 732 ns */ function method6($s) {return (new SplFileInfo($s))->getExtension();}
// All measured on Linux; it will be vastly different on Windows
Those nanosecond values will obviously differ on each system, but they give a clear picture about proportions. SplFileInfo and pathinfo are great fellas, but for this kind of job it's simply not worth it to wake them up. For the same reason, explode() is considerably faster than regex. Very simple tools tend to beat more sophisticated ones.
Conclusion
This seems to be the Way of the Samurai:
function fileExtension($name) {
$n = strrpos($name, '.');
return ($n === false) ? '' : substr($name, $n+1);
}
Remember this is for simple filenames only. If you have paths involved, stick to pathinfo or deal with the dirname separately.
A: I found that the pathinfo() and SplFileInfo solutions works well for standard files on the local file system, but you can run into difficulties if you're working with remote files as URLs for valid images may have a # (fragment identifiers) and/or ? (query parameters) at the end of the URL, which both those solutions will (incorrect) treat as part of the file extension.
I found this was a reliable way to use pathinfo() on a URL after first parsing it to strip out the unnecessary clutter after the file extension:
$url_components = parse_url($url); // First parse the URL
$url_path = $url_components['path']; // Then get the path component
$ext = pathinfo($url_path, PATHINFO_EXTENSION); // Then use pathinfo()
A: You can try also this:
pathinfo(basename($_FILES["fileToUpload"]["name"]), PATHINFO_EXTENSION)
A: IMO, this is the best way if you have filenames like name.name.name.ext (ugly, but it sometimes happens):
$ext = explode('.', $filename); // Explode the string
$my_ext = end($ext); // Get the last entry of the array
echo $my_ext;
A: Use substr($path, strrpos($path,'.')+1);. It is the fastest method of all compares.
@Kurt Zhong already answered.
Let's check the comparative result here: https://eval.in/661574
A: As long as it does not contain a path you can also use:
array_pop(explode('.', $fname))
Where $fname is a name of the file, for example: my_picture.jpg.
And the outcome would be: jpg
A: E-satis's response is the correct way to determine the file extension.
Alternatively, instead of relying on a files extension, you could use the fileinfo to determine the files MIME type.
Here's a simplified example of processing an image uploaded by a user:
// Code assumes necessary extensions are installed and a successful file upload has already occurred
// Create a FileInfo object
$finfo = new FileInfo(null, '/path/to/magic/file');
// Determine the MIME type of the uploaded file
switch ($finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME)) {
case 'image/jpg':
$im = imagecreatefromjpeg($_FILES['image']['tmp_name']);
break;
case 'image/png':
$im = imagecreatefrompng($_FILES['image']['tmp_name']);
break;
case 'image/gif':
$im = imagecreatefromgif($_FILES['image']['tmp_name']);
break;
}
A: This will work
$ext = pathinfo($filename, PATHINFO_EXTENSION);
A: You can get all file extensions in a particular folder and do operations with a specific file extension:
<?php
$files = glob("abc/*.*"); // abc is the folder all files inside folder
//print_r($files);
//echo count($files);
for($i=0; $i<count($files); $i++):
$extension = pathinfo($files[$i], PATHINFO_EXTENSION);
$ext[] = $extension;
// Do operation for particular extension type
if($extension=='html'){
// Do operation
}
endfor;
print_r($ext);
?>
A: ltrim(strstr($file_url, '.'), '.')
this is the best way if you have filenames like name.name.name.ext (ugly, but it sometimes happens
A: $ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $fileName);
preg_replace approach we using regular expression search and replace. In preg_replace function first parameter is pattern to the search, second parameter $1 is a reference to whatever is matched by the first (.*) and third parameter is file name.
Another way, we can also use strrpos to find the position of the last occurrence of a β.β in a file name and increment that position by 1 so that it will explode string from (.)
$ext = substr($fileName, strrpos($fileName, '.') + 1);
A: In one line:
pathinfo(parse_url($url,PHP_URL_PATH),PATHINFO_EXTENSION);
A: People from other scripting languages always think theirs is better because they have a built-in function to do that and not PHP (I am looking at Pythonistas right now :-)).
In fact, it does exist, but few people know it. Meet pathinfo():
$ext = pathinfo($filename, PATHINFO_EXTENSION);
This is fast and built-in. pathinfo() can give you other information, such as canonical path, depending on the constant you pass to it.
Remember that if you want to be able to deal with non ASCII characters, you need to set the locale first. E.G:
setlocale(LC_ALL,'en_US.UTF-8');
Also, note this doesn't take into consideration the file content or mime-type, you only get the extension. But it's what you asked for.
Lastly, note that this works only for a file path, not a URL resources path, which is covered using PARSE_URL.
Enjoy
A: pathinfo()
$path_info = pathinfo('/foo/bar/baz.bill');
echo $path_info['extension']; // "bill"
A: 1) If you are using (PHP 5 >= 5.3.6)
you can use SplFileInfo::getExtension β Gets the file extension
Example code
<?php
$info = new SplFileInfo('test.png');
var_dump($info->getExtension());
$info = new SplFileInfo('test.tar.gz');
var_dump($info->getExtension());
?>
This will output
string(3) "png"
string(2) "gz"
2) Another way of getting the extension if you are using (PHP 4 >= 4.0.3, PHP 5) is pathinfo
Example code
<?php
$ext = pathinfo('test.png', PATHINFO_EXTENSION);
var_dump($ext);
$ext = pathinfo('test.tar.gz', PATHINFO_EXTENSION);
var_dump($ext);
?>
This will output
string(3) "png"
string(2) "gz"
// EDIT: removed a bracket
A: Example URL: http://example.com/myfolder/sympony.mp3?a=1&b=2#XYZ
A) Don't use suggested unsafe PATHINFO:
pathinfo($url)['dirname'] 'http://example.com/myfolder'
pathinfo($url)['basename'] 'sympony.mp3?a=1&b=2#XYZ' // <------- BAD !!
pathinfo($url)['extension'] 'mp3?a=1&b=2#XYZ' // <------- BAD !!
pathinfo($url)['filename'] 'sympony'
B) Use PARSE_URL:
parse_url($url)['scheme'] 'http'
parse_url($url)['host'] 'example.com'
parse_url($url)['path'] '/myfolder/sympony.mp3'
parse_url($url)['query'] 'aa=1&bb=2'
parse_url($url)['fragment'] 'XYZ'
BONUS: View all native PHP examples
A: Sometimes it's useful to not to use pathinfo($path, PATHINFO_EXTENSION). For example:
$path = '/path/to/file.tar.gz';
echo ltrim(strstr($path, '.'), '.'); // tar.gz
echo pathinfo($path, PATHINFO_EXTENSION); // gz
Also note that pathinfo fails to handle some non-ASCII characters (usually it just suppresses them from the output). In extensions that usually isn't a problem, but it doesn't hurt to be aware of that caveat.
A: Sorry... "Short Question; But NOT Short Answer"
Example 1 for PATH
$path = "/home/ali/public_html/wp-content/themes/chicken/css/base.min.css";
$name = pathinfo($path, PATHINFO_FILENAME);
$ext = pathinfo($path, PATHINFO_EXTENSION);
printf('<hr> Name: %s <br> Extension: %s', $name, $ext);
Example 2 for URL
$url = "//www.example.com/dir/file.bak.php?Something+is+wrong=hello";
$url = parse_url($url);
$name = pathinfo($url['path'], PATHINFO_FILENAME);
$ext = pathinfo($url['path'], PATHINFO_EXTENSION);
printf('<hr> Name: %s <br> Extension: %s', $name, $ext);
Output of example 1:
Name: base.min
Extension: css
Output of example 2:
Name: file.bak
Extension: php
References
*
*https://www.php.net/manual/en/function.pathinfo.php
*https://www.php.net/manual/en/function.realpath.php
*https://www.php.net/manual/en/function.parse-url.php
A: If you are looking for speed (such as in a router), you probably don't want to tokenize everything. Many other answers will fail with /root/my.folder/my.css
ltrim(strrchr($PATH, '.'),'.');
A: Although the "best way" is debatable, I believe this is the best way for a few reasons:
function getExt($path)
{
$basename = basename($path);
return substr($basename, strlen(explode('.', $basename)[0]) + 1);
}
*
*It works with multiple parts to an extension, eg tar.gz
*Short and efficient code
*It works with both a filename and a complete path
A: Actually, I was looking for that.
<?php
$url = 'http://example.com/myfolder/sympony.mp3?a=1&b=2#XYZ';
$tmp = @parse_url($url)['path'];
$ext = pathinfo($tmp, PATHINFO_EXTENSION);
var_dump($ext);
A: I tried one simple solution it might help to someone else to get just filename from the URL which having get parameters
<?php
$path = "URL will be here";
echo basename(parse_url($path)['path']);
?>
Thanks
A: Use
str_replace('.', '', strrchr($file_name, '.'))
for a quick extension retrieval (if you know for sure your file name has one).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "842"
} |
Q: Why can't c++ ifstreams read from devices? I knew I should never have started using c++ io, the whole "type safety" argument is a red herring (does anyone really find that it's one of their most pressing problems?). Anyhow, I did, and discovered a strange difference between ifstreams and FILE*s and plain old file descriptors: ifstreams cannot read from a device. Can anyone think of a reason why?
const char* path = "/dev/disk3";
char b;
// this works
FILE* f= fopen(path, "rb");
int i = fread(&b, 1, 1, f); // returns 1, success!
// this does not work
ifstream cf(path, ios::binary);
cf.read(&b, 1);
bool good = cf.good(); // returns false, failure.
A: Works fine for me, its not a problem inherent to c++ stream file I/O as you seem to think.
Maybe try adding ios::in to the openmode flags. According to 27.8.1.6 of the standard, it is required to or with ios::in so this probably won't do anything.
Try checking which bit is actually set - instead of calling good(), try checking bad(), eof(), and fail() individually. This might give a clue as to what the error was.
A: The device is unbuffered and must be read from in 512 byte multiples. ifstream does it's own buffering and strangely decided to read 1023 bytes ahead, which fails with "Invalid argument". Interestingly, this ifstream is implemented on top of a FILE*. However, FILE* left to its own devices was reading ahead using a nicer, rounder number of bytes.
Thanks to dtrace for vital clues. I guess we'll never know if the folk who thought they knew answer but didn't want to say were right.
A: I have found random issues like this in C++ I/O for years. It has always seemed like a backwards step to me.
I haven't tried it, but you might want to look at what Boost has to offer:
http://www.boost.org/doc/libs/1_36_0/libs/iostreams/doc/index.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do you protect code from leaking outside? Besides open-sourcing your project and legislation, are there ways to prevent, or at least minimize the damages of code leaking outside your company/group?
We obviously can't block Internet access (to prevent emailing the code) because programmer's need their references. We also can't block peripheral devices (USB, Firewire, etc.)
The code matters most when it has some proprietary algorithms and in-house developed knowledge (as opposed to regular routine code to draw GUIs, connect to databases, etc.), but some applications (like accounting software and CRMs) are just that: complex collections of routine code that are simple to develop in principle, but will take years to write from scratch. This is where leaked code will come in handy to competitors.
As far as I see it, preventing leakage relies almost entirely on human process. What do you think? What precautions and measures are you taking? And has code leakage affected you before?
A: The code does not leak out on itself. It takes people to take it. There are obviously some security measures you might use like traffic analysis and lock-down on the repositories so only authorized developers can connect to it.
But by the end of the day your best option is to make sure that no one WANTS to steal from you. Your team has to be happy, they have to be proud to work for your they have to be loyal to the company and to each other. If you have such team it's a simple question of explaining to everyone that the code has to be protected from outsiders. It will not stop a dedicated mole but will prevent accidents.
P.S. And yes, proper clauses in the contracts would not harm as well, at least they will make sure that the developers are AWARE that taking code outside is morally wrong.
A: Follow these guidelines and it shouldn't matter if the contents of your entire source code repository is posted all over stackoverflow:
http://geocities.com/mdetting/unmaintainable.html
Oh, and show your developers that you don't trust them by blocking access to parts of the source code, scanning outgoing/incoming email etc. That is a surefire way to make them want to stay around... ...nothing improves morale like a bit of mistrust in the workplace.
Another cool way is to tell one half that they are "team a" and name the other half as the untrustworthy "team b". Then reverse it and say the same thing to the "team b" members. Encourage them to keep an eye on the "bad guys" in the other team and to report any signs of illoyalty to you. Sprinkle a few "conflict inducers" (e.g. tell "Joe": 'do you know what Ed says about you behind your back?') etc. Works wonders if you set up the developers against each other and create a few [invented-by-you] conflicts here and there...
(Eh, and no, I don't actually recommend any of the above. Just kidding. But I have seen people use all of the tactics above. And it didn't work.)
A: Okay, I am going to be a little practical here.
*
*Being nice to everybody and hoping they won't hurt you doesn't work.
Every programmer knows from the day he joins a company that he'll not stay there forever. He will change when he's learned enough to get a better opportunity.
The programmers who write the code believe that they have the ownership to it even if they wrote it on the time they rented out to somebody else. So many of them will usually try to get their hands on the source-code even if they don't intend to hurt anybody.
Once they leave the company and they've carried the source code with them and lost contact with their colleagues, the conscience settles down and goes on a vacation and after a while bits and pieces from the code start showing up everywhere.
That's what I KNOW happens cause I've witnessed it happen to my company.
So what does one do?
*
*Sign a NDA which specifically mentions that they programmer WILL not take copies.
*Distribute your product between programmers, and if possible get modules coded individually and integrated by a chief whose responsibility is that all programmers do nt get all the code.
*At the time of termination get a written undertaking from the coders that they do not possess any IP of the company and they understand the penalties of violation.
*If somebody violates your IP, sue the man! No exceptions. It'll work as an example for the present team.
Do I sound extreme?
A: You can't stop it getting out. So two solutions - stop people wanting to hurt you, and have legal precautions. To stop people hating you treat them right (saying more is probably off topic for stack overflow).
I'm not a lawyer, but to give yourself legal protection, if you believe in it, patent the ideas, put a copyright notice in the code, and make sure the contracts for your programmers specify carefully intellectual property rights.
But at the end of the day, the answer is run quicker than the competition.
A: I remember this happening to Valve when they were developing HL-2. Interesting link here: http://www.shacknews.com/onearticle.x/28619
A: Most of the answers are based on Moral and ethical values. I wonder if Google, Facebook etc. just rely on their employees good will. Give me a break, that's totally utopian. Don't be a fool. Be realistic.
YES, it is possible to prevent code leaking:
Using a virtual server hosting virtual machines, programmers can only access locally to these virtual machines (intranet) via Remote Desktop. Repository is managed locally. private keys are required to access the repository. Copy/paste from virtual machine to client is disabled. only copy/paste from client to virtual is allowed.
Companies like facebook do that.
The only way to still code is by taking pictures to the actual code, which is totally not practical and feasible at all, and since there are surveillance cameras everywhere, you will have to go to the bathroom to take those pictures.
A: Unless you're working with something highly classified and given that you can't block email and USB devices I guess you aren't there's really not to much damage to be had even if the source code leaks. The thing is, what is the code, or parts of it worth without the knowledge of how it works and the organization around it.
In general the value of "source" is much less than is commonly touted, basicly the source without the people or the organization isn't worth the storage it occupies for a competitor.
Also, you're missing the most likely attack vector, and it's also the one you can't stop no matter what. If someone really really want's to know how you made your magic then they'll try to hire your developers away, and since you can't stop them from having information inside their skull and even if they turn in all their possesions ther knowledge and domain expertise is leaving with them. Basicly employee retention and trust is the only way. Sorry.
A: I don't know how much actual help this is going to be, but:
*
*Don't p*ss your programmers off. Don't get them in a position where they want to give the source to a competitor. Most places undervalue their developers. Given where you are (SO), I guess you are less likely to. Nothing got to me more than seeing the sales folks out for games of golf - paid, and paid for, by the company - while we had to fight to get pizza once a month.
*Really, if your direct competitors got your code today, what would it do? Is your product or vertical market that stagnant that you wouldn't release newer, better versions before they could react? Is there no room for innovation? Most companies overvalue their "proprietary algorithms and in-house developed knowledge". Sure, it may cut some time off, but it's only about 10% of the problem.
*If you got all the source for all your competitors products, how much actual use would it be? I'd guess it would set you back months. Not forward. Back.
If you had a clean system, and little external/internal knowledge, how long would it take you to get your own product into a buildable state? How long would it take to drill down into the code and workout what is going on? How much time and money would you waste trying to work something out, rather than spending time and money on how to make your product work better?
I've actually been in the position of having all the source - 1million lines+ of code - to a competitor's product. We did nothing with it - aside from a bit of a poke-around and then delete it, which was more than I was comfortable with - but I would expect that we'd have chewed up months of time just to get to where they were then.
So we nuked it, slapped the id10t who got it (yes, a developer/PM who came over from the other company), and thought about how to make our product kick so much butt that it didn't matter what they did. Much better use of time. Worked well, too. We had differentiators, not just re-hashing the same features in the same way they did them.
Sorry, but there is no way you can stop people getting stuff out, and still be able to actually work. You can stop them wanting to do it, or make it so there is no value to them having it.
We were worried about people decompiling our code too. We stopped worrying when we realised that WE had enough trouble working out what was going on inside 500K+ lines of C#, C++ and HTML code talking to MAPI/Exchange. If someone can decompile it and work it out, then we want to hire them......
BTW, for clarity, and given who I now work for, I should point out this is not my current employer. This was quite a while ago.
A: I've worked somewhere where there was a real culture of secrecy about this sort of thing (historically there had been a number of times when the company was small where "customers" had, shall we say, abused their access to our product).
While at the top the management were very protective, I see it slightly differently. I think our code, while not entirely irrelevant, isn't as key as you'd expect it to be in a software company.
The reason that we are successful is:
1) The code is essentially the solution to a bunch of problems. If you get our code you get those solutions but we still have the smart people who solved those problems. They understand those problems better than you do and are better able to solve the next set of problems better than you are.
2) Because they really understand the problems (and the solutions) we can do things faster than our competitors which translates to cheaper (or more profitable).
3) Also because of those people and the attitude within the company we've delivered well to our clients and provided good support.
4) And because of that we have a good reputation and reference-able customers.
A small number of companies have code which is genuinely worth keeping secret - proprietary algorithms and that sort of thing - but for a vast majority of us our products are very easily replicable by smart people.
What I'm saying is do the basics - write it into people's contracts that they can't take it, keep it secure and so on - but don't obsess over it. Unless you're in a very specific market it's unlikely to be what's really going to make your business succeed or fail.
A: The best step starts from reruting guys with strong ethical behaviour.
Various other steps can be taken like all communication being scanned. There are places where email and all information going out is scanned. The desktop/laptop does not have hard-disk or the access is restricted and all work is on network folders, even when working from home, one has to get connected to internet. The offline work gets synchronized. The USB and drives are disconnected.
The other policies are to provide access only on need basis.
These will only slow down and hinder to some extent, but is one is very determined then he would find ways to get around this.
The other way is if the code is really very important, then have the idea copywrite protected legaly.
A: To be honest it's almost impossible. If I wanted to suggest what a company that would shortly appear on the Daily WTF would do:
*
*Disconnect the "work computer" from the internet, bt because they need internet access for reference buy everyone a wbbook.
*Stuff the developers USB slots with epoxy and require that they load/unload everything from a centralised server, which scans all the data that goes through it for code like syntax.
Or you could just trust your employees and make them sign an NDA...
A: I personally never tested on any real case, but I would suggest using code fragmentation:
basically you split your project in a number of libraries, define interfaces and unit tests for each of them, then you separate SVN repositories so that each group have access to a limited part of your precious source code.
This is also a good practice no matter what and should help if you are outsourcing abroad.
A: The previous answers all seem to center on building trust and employing ethical people.
Another possibility might be to create your own domain specific language and tools. That will make any leaked code harder to use. It might still be possible to steal useful ideas from it, but it would not be possible to simply compile a competing product unless the whole toolchain is leaked.
A: Trust your developers. People tend to live up or down to expectations. Treat them well, and remember that loyalty goes both ways. After all, if you can't cut off thumb drives, you can't stop anybody from leaking code, no matter how much you don't trust them.
That being said, find yourself a lawyer with trade secret expertise, probably expertise in other parts of IP law, and ask how to legally safeguard stuff. You do want to make sure that, if a competitor gets your stuff, it's not legal for the competitor to benefit from it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Multiple instances of a java web application sharing a resource I have a web service, that takes an input xml message, transforms it, and then forwards it to another web service.
The application is deployed to two web logic app servers for performance, and resilience reasons.
I would like a single website monitoring page that allows two things
*
*ability to stop/ start forwarding of messages
*ability to monitor throughput of number of messages in the last hour etc. Number of different senders into the webservice etc.
I was wondering what the best way to implement this was.
My current idea is to have an in memory database (eg Debry or HSQL) replicating data to share the information between the two (or more) instances of my application that are running in different instances of the app server. I imagine I would have to setup some sort of master/ slave configuration.
I would love a link to an article that discusses how to solve this problem.
(Note, this is a simple spring application using spring MVC)
thanks,
David.
A: This sounds like a good match for Java Management Extensions (JMX)
*
*JMX allows you to expose certain operations (eg: start/stop forwarding messages)
*JMX allows you to monitor certain performance indicators (eg: moving average of messages processed)
Spring has good support for exposing beans as JMX MBeans. See here for more information.
Then you could use an open-source web-based JMX console, such as jManage
Hope this helps.
A: Sounds like you are looking for a Message Queue, some MDBs and a configurable design would let you do all these. Spring has support for JMS Queues if I'm not wrong
A: I think you are looking for a message queue. If you need additional monitoring, using a web service as the end point may not suffice - with regards to stop/start or forwarding of messages; monitoring http requests to web service is more cumbersome than tracking messages to a queue (even though you can do it).
If you are exposing this service to third party, then the web service will sit on top of the message queue and delegate to to it.
In my experience, RabbitMQ is a fine messaging queue service with a relatively simple learning curve.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ParseFloat function in JavaScript When I am adding two textbox values that are 1.001 and 0.001 and then I do a parseFloat I get 1.0019999999. I want it 1.002 . Can you help me?
A: This is a known problem: see accuraty problem
and the minimisation of the accuracy problem: minimisation
A: The javascript methods Number.toFixed() and Number.toPrecision() can help here, but they return a String. A possible solution is as follows:
var x = parseFloat(parseFloat("1.0019999999").toPrecision(3));
A: The Javascript Number class has a toFixed() function that will get you what you want.
So you could do parseFloat("1.0019999").toFixed(3) and that would give you 1.002.
The parameter (3 in this case) is the number of digits to show after the decimal point
A: 0.002 cannot be accurately represented as a base 2 number. Similar to the way that 1/3 can't be represented in base 10.
1/3 = 0.33333... recuring. To represent the number accurately in base 10, you would need an infinite number of decimal digits.
0.002 is a number that can be accurately represented in base 10 (as we see here), but not in base 2, as used by computers. To represent this number accurately, would take an infinite number of binary digits.
A: If you want to a quick fix you can round to the nearest thousandth
Math.round((1.001+0.001)*1000)/1000
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Overriding serialization for a particular .NET type Please consider this example class:
[Serializable]
public class SomeClass
{
private DateTime _SomeDateTime;
public DateTime SomeDateTime
{
get { return _SomeDateTime; }
set { _SomeDateTime = value; }
}
}
I would like to alter the serialization of any DateTime declared in the class according to my own rules. The members of this class will change frequently and I don't want to maintain a custom serializer for every change. Also I would like this behaviour to be inherited by subclasses and not code a custom serializer for every one. The serialization is being output by a web service. Thanks for any help!
A: Have you thought about simply using a Nullable date time
public DateTime? SomeDateTime {get; set;}
This way you can actually have a null value as a legitimate value in your class. Typically you want to avoid custom serialization whenever possible. Once you do custom serialization such as implementing ISerializable, then you are stuck with it, and all other derived classes are stuck with it.
Remember what a pain in the butt it is to have to always override the ISerializable members for custom exceptions? This is because System.Exception implements ISerializable and therefore all derived exceptions (that means everything) must implement those members if you ever expect them to cross AppDomains.
A: look at the OnSerializing and OnDeserializing attributes to call custom methods when your objects are serialized. you can impelment some custom logic in there and decouple the serializing process from the actual datatypes.
A: Well, you can use a "bool ShouldSerializeSomeDateTime()" method to enable/disable serialization of individual members, but I don't think that is quite what you need. Another common option is to add a member that does the format itself:
public string SomeDateTimeFormatted {
get { return theField == DateTime.MinValue ? "" : theField.ToString("R");} // or whatever format
set { ... opposite ...}
}
It is nicer to stick with the inbuilt serialization if you can, though - in part to reduce the amount of code you need to write. Josh's suggestion for a nullable DateTime (DateTime?) is a good one, although it might still not be quite empty-string vs formatted-string - I expect it would use the xsi:nil markup.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Performance issue with "new ReportDocument()" I have a C# application where I create a Crystal Reports ReportDocument, with the line
CrystalDecisions.CrystalReports.Engine.ReportDocument document =
new CrystalDecisions.CrystalReports.Engine.ReportDocument();
This line takes 3-4 seconds to execute. This seems very slow, especially since the
document.Load(file)
line following it (which actually does the major part of the work of reading in a report file and creating the report's object model) executes extremely quickly.
What are things I should keep in mind that might improve performance here?
A: Unfortunately, according to https://www.sdn.sap.com/irj/sdn/message?messageID=5898122 3-4 seconds fΓ³r this constructor call is "quite normal".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Checkstyle's PackageHtml-rule ignores package-info.java I use checkstyle to analyze my code. A useful rule is PackageHtml, that checks, if a package contains a Javadoc-description. But with newer java-version it's recommended to use package-info.java instead of package.html. Problem is, checkstyle ignores the package-info.java and reports a rule violation. How can checkstyle be configured to check for package-documentation, but accepts package.html and package-info.java?
A: What version of CheckStyle are you using ?
It seems to be an old bug closed late 2007.
Actually, the documentation mentions package-info as being the default!...
but only with CheckStyle 5.x, not 4.4
The announce for CheckStyle5.0 beta1 is here.
CheckStyle 4.4 is the last one compatible with jdk1.4
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is anyone running a production ASP.NET site on top of Mono? I'm trying to do an informal feasibility study for work on if Mono/Apache/Linux is realistically 'ready' and in any way comparable to a more traditional .NET/IIS/Windows stack.
Any comparison of performance would be helpful too.
A: http://Fiducial.Biz, a financial company in France is running on Mono with ASP.NET
A: We're running a website/bunch of webservices on Mono/Apache/FreeBSD platform for one of our customers. The setup works great.
A: Take a look at companies using Mono.
It even says that Wikipedia uses Mono for its search facilities.
A: One thing to remember is 2.0 of Mono is out soon (I think this week) and it is even better now. So if you do any testing make sure you at least use the 2.0 RC
A: I am running a couple sites off ASP.NET over Mono. I am targeting 2.0 of the framework.
I haven't had Digg numbers, but I have also never had an issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How do I blink/control Macbook keyboard LEDs programmatically? Do you know how I can switch on/off (blink) Macbook keyboard led (caps lock,numlock) under Mac OS X (preferably Tiger)?
I've googled for this, but have got no results, so I am asking for help.
I would like to add this feature as notifications (eg. new message received on Adium, new mail received).
I would prefer applescript, python, but if it's impossible, any code would be just fine.
I will appreciate any kind of guidance.
A: http://googlemac.blogspot.com/2008/04/manipulating-keyboard-leds-through.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Is there a "theirs" version of "git merge -s ours"? When merging topic branch "B" into "A" using git merge, I get some conflicts. I know all the conflicts can be solved using the version in "B".
I am aware of git merge -s ours. But what I want is something like git merge -s theirs.
Why doesn't it exist? How can I achieve the same result after the conflicting merge with existing git commands? (git checkout every unmerged file from B)
The "solution" of just discarding anything from branch A (the merge commit point to B version of the tree) is not what I am looking for.
A: It is not entirely clear what your desired outcome is, so there is some confusion about the "correct" way of doing it in the answers and their comments. I try to give an overview and see the following three options:
Try merge and use B for conflicts
This is not the "theirs version for git merge -s ours" but the "theirs version for git merge -X ours" (which is short for git merge -s recursive -X ours):
git checkout branchA
# also uses -s recursive implicitly
git merge -X theirs branchB
This is what e.g. Alan W. Smith's answer does.
Use content from B only
This creates a merge commit for both branches but discards all changes from branchA and only keeps the contents from branchB.
# Get the content you want to keep.
# If you want to keep branchB at the current commit, you can add --detached,
# else it will be advanced to the merge commit in the next step.
git checkout branchB
# Do the merge an keep current (our) content from branchB we just checked out.
git merge -s ours branchA
# Set branchA to current commit and check it out.
git checkout -B branchA
Note that the merge commits first parent now is that from branchB and only the second is from branchA. This is what e.g. Gandalf458's answer does.
Use content from B only and keep correct parent order
This is the real "theirs version for git merge -s ours". It has the same content as in the option before (i.e. only that from branchB) but the order of parents is correct, i.e. the first parent comes from branchA and the second from branchB.
git checkout branchA
# Do a merge commit. The content of this commit does not matter,
# so use a strategy that never fails.
# Note: This advances branchA.
git merge -s ours branchB
# Change working tree and index to desired content.
# --detach ensures branchB will not move when doing the reset in the next step.
git checkout --detach branchB
# Move HEAD to branchA without changing contents of working tree and index.
git reset --soft branchA
# 'attach' HEAD to branchA.
# This ensures branchA will move when doing 'commit --amend'.
git checkout branchA
# Change content of merge commit to current index (i.e. content of branchB).
git commit --amend -C HEAD
This is what Paul Pladijs's answer does (without requiring a temporary branch).
Special cases
If the commit of branchB is an ancestor of branchA, git merge does not work (it just exits with a message like "Already up to date.").
In this or other similar/advanced cases the low-level command git commit-tree can be used.
A: To really properly do a merge which takes only input from the branch you are merging you can do
git merge --strategy=ours ref-to-be-merged
git diff --binary ref-to-be-merged | git apply --reverse --index
git commit --amend
There will be no conflicts in any scenario I know of, you don't have to make additional branches, and it acts like a normal merge commit.
This doesn't play nice with submodules however.
A: I used the answer from Paul Pladijs since now. I found out, you can do a "normal" merge, conflicts occur, so you do
git checkout --theirs <file>
to resolve the conflict by using the revision from the other branch. If you do this for each file, you have the same behaviour as you would expect from
git merge <branch> -s theirs
Anyway, the effort is more than it would be with the merge-strategy! (This was tested with git version 1.8.0)
A: See Junio Hamano's widely cited answer: if you're going to discard committed content, just discard the commits, or at any rate keep it out of the main history. Why bother everyone in the future reading commit messages from commits that have nothing to offer?
But sometimes there are administrative requirements, or perhaps some other reason. For those situations where you really have to record commits that contribute nothing, you want:
(edit: wow, did I manage to get this wrong before. This one works.)
git update-ref HEAD $(
git commit-tree -m 'completely superseding with branchB content' \
-p HEAD -p branchB branchB:
)
git reset --hard
A: This one uses a git plumbing command read-tree, but makes for a shorter overall workflow.
git checkout <base-branch>
git merge --no-commit -s ours <their-branch>
git read-tree -u --reset <their-branch>
git commit
# Check your work!
git diff <their-branch>
A: A possible and tested solution for merging branchB into our checked-out branchA:
# in case branchA is not our current branch
git checkout branchA
# make merge commit but without conflicts!!
# the contents of 'ours' will be discarded later
git merge -s ours branchB
# make temporary branch to merged commit
git branch branchTEMP
# get contents of working tree and index to the one of branchB
git reset --hard branchB
# reset to our merged commit but
# keep contents of working tree and index
git reset --soft branchTEMP
# change the contents of the merged commit
# with the contents of branchB
git commit --amend
# get rid off our temporary branch
git branch -D branchTEMP
# verify that the merge commit contains only contents of branchB
git diff HEAD branchB
To automate it you can wrap it into a script using branchA and branchB as arguments.
This solution preserves the first and second parent of the merge commit, just as you would expect of git merge -s theirs branchB.
A:
When merging topic branch "B" in "A" using git merge, I get some conflicts. I >know all the conflicts can be solved using the version in "B".
I am aware of git merge -s ours. But what I want is something like git merge >-s their.
I'm assuming that you created a branch off of master and now want to merge back into master, overriding any of the old stuff in master. That's exactly what I wanted to do when I came across this post.
Do exactly what it is you want to do, Except merge the one branch into the other first. I just did this, and it worked great.
git checkout Branch
git merge master -s ours
Then, checkout master and merge your branch in it (it will go smoothly now):
git checkout master
git merge Branch
A: I solved my problem using
git checkout -m old
git checkout -b new B
git merge -s ours old
A: The equivalent(which keep parent order) to 'git merge -s theirs branchB'
Before merge:
!!! Make sure you are in clean state !!!
Do the merge:
git commit-tree -m "take theirs" -p HEAD -p branchB 'branchB^{tree}'
git reset --hard 36daf519952 # is the output of the prev command
What we did ?
We created a new commit which two parents ours and theirs and the contnet of the commit is branchB - theirs
After merge:
More precisely:
git commit-tree -m "take theirs" -p HEAD -p 'SOURCE^{commit}' 'SOURCE^{tree}'
A: This answer was given by Paul Pladijs. I just took his commands and made a git alias for convenience.
Edit your .gitconfig and add the following:
[alias]
mergetheirs = "!git merge -s ours \"$1\" && git branch temp_THEIRS && git reset --hard \"$1\" && git reset --soft temp_THEIRS && git commit --amend && git branch -D temp_THEIRS"
Then you can "git merge -s theirs A" by running:
git checkout B (optional, just making sure we're on branch B)
git mergetheirs A
A: If you are on branch A do:
git merge -s recursive -X theirs B
Tested on git version 1.7.8
A: A similar alternative is the --strategy-option (short form -X) option, which accepts theirs. For example:
git checkout branchA
git merge -X theirs branchB
However, this is more equivalent to -X ours than -s ours. The key difference being that -X performs a regular recursive merge, resolving any conflicts using the chosen side, whereas -s ours changes the merge to just completely ignore the other side.
In some cases, the main problem using -X theirs instead of the hypothetical -s theirs is deleted files. In this case, just run git rm with the name of any files that were deleted:
git rm {DELETED-FILE-NAME}
After that, the -X theirs may work as expected.
Of course, doing the actual removal with the git rm command will prevent the conflict from happening in the first place.
A: Older versions of git allowed you to use the "theirs" merge strategy:
git pull --strategy=theirs remote_branch
But this has since been removed, as explained in this message by Junio Hamano (the Git maintainer). As noted in the link, instead you would do this:
git fetch origin
git reset --hard origin
Beware, though, that this is different than an actual merge. Your solution is probably the option you're really looking for.
A:
Why doesn't it exist?
While I mention in "git command for making one branch like another" how to simulate git merge -s theirs, note that Git 2.15 (Q4 2017) is now clearer:
The documentation for '-X<option>' for merges was misleadingly
written to suggest that "-s theirs" exists, which is not the case.
See commit c25d98b (25 Sep 2017) by Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 4da3e23, 28 Sep 2017)
merge-strategies: avoid implying that "-s theirs" exists
The description of -Xours merge option has a parenthetical note
that tells the readers that it is very different from -s ours,
which is correct, but the description of -Xtheirs that follows it
carelessly says "this is the opposite of ours", giving a false
impression that the readers also need to be warned that it is very
different from -s theirs, which in reality does not even exist.
-Xtheirs is a strategy option applied to recursive strategy. This means that recursive strategy will still merge anything it can, and will only fall back to "theirs" logic in case of conflicts.
That debate for the pertinence or not of a theirs merge strategy was brought back recently in this Sept. 2017 thread.
It acknowledges older (2008) threads
In short, the previous discussion can be summarized to "we don't want '-s theirs' as it encourages the wrong workflow".
It mentions the alias:
mtheirs = !sh -c 'git merge -s ours --no-commit $1 && git read-tree -m -u $1' -
Yaroslav Halchenko tries to advocate once more for that strategy, but Junio C. Hamano adds:
The reason why ours and theirs are not symmetric is because you are you and not them---the control and ownership of our history and their history is not symmetric.
Once you decide that their history is the mainline, you'd rather want to treat your line of development as a side branch and make a merge in that direction, i.e. the first parent of the resulting merge is a commit on their history and the second parent is the last bad one of your history. So you would end up using "checkout their-history && merge -s ours your-history" to
keep the first-parenthood sensible.
And at that point, use of "-s ours" is no longer a workaround for lack of "-s theirs".
It is a proper part of the desired semantics, i.e. from the point of view of the surviving canonical history line, you want to preserve what it did, nullifying what the other line of history did.
Junio adds, as commented by Mike Beaton:
git merge -s ours <their-ref> effectively says 'mark commits made up to <their-ref> on their branch as commits to be permanently ignored';
and this matters because, if you subsequently merge from later states of their branch, their later changes will be brought in without the ignored changes ever being brought in.
A: I think what you actually want is:
git checkout -B mergeBranch branchB
git merge -s ours branchA
git checkout branchA
git merge mergeBranch
git branch -D mergeBranch
This seems clumsy, but it should work. The only think I really dislike about this solution is the git history will be confusing... But at least the history will be completely preserved and you won't need to do something special for deleted files.
A: This will merge your newBranch in existing baseBranch
git checkout <baseBranch> // this will checkout baseBranch
git merge -s ours <newBranch> // this will simple merge newBranch in baseBranch
git rm -rf . // this will remove all non references files from baseBranch (deleted in newBranch)
git checkout newBranch -- . //this will replace all conflicted files in baseBranch
A: Revisiting this old question, as I just found a solution that is both
short and β since it uses only porcelain commands β easy to understand.
To be clear, I want to answer the problem stated in the title of the
question (implement git merge -s theirs), not the question body. In
other words, I want to create a merge commit with a tree identical to
the tree of its second parent:
# Start from the branch that is going to receive the merge.
git switch our_branch
# Create the merge commit, albeit with the wrong tree.
git merge -s ours their_branch
# Replace our working tree and our index with their tree.
git restore --source=their_branch --worktree --staged :/
# Put their tree in the merge commit.
git commit --amend
Caveat: git restore is a fairly new command, introduced in git
2.23. git help restore warns that
THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.
I did test this method with multiple versions of git (2.25.1, 2.30.2,
2.31.1, 2.34.1 and 2.35.1), and it worked as expected.
A: This doesn't necessarily answer the original poster's question, but I landed here in a situation where I had already attempted a merge but ended up with conflicts. Usually I manage conflicts in an IDE, but when I don't have access to that, the following REGEX can be used to find and replace differences with the "theirs" content:
Replce <<<<<<< HEAD\n[^β’>]+\n=======\n([^β’>]+)>>>>>>> .+\n with \1
(Just in case anyone else lands on this page for the same reason I did).
A: I just recently needed to do this for two separate repositories that share a common history. I started with:
*
*Org/repository1 master
*Org/repository2 master
I wanted all the changes from repository2 master to be applied to repository1 master, accepting all changes that repository2 would make. In git's terms, this should be a strategy called -s theirs BUT it does not exist. Be careful because -X theirs is named like it would be what you want, but it is NOT the same (it even says so in the man page).
The way I solved this was to go to repository2 and make a new branch repo1-merge. In that branch, I ran git pull git@gitlab.com:Org/repository1 -s ours and it merges fine with no issues. I then push it to the remote.
Then I go back to repository1 and make a new branch repo2-merge. In that branch, I run git pull git@gitlab.com:Org/repository2 repo1-merge which will complete with issues.
Finally, you would either need to issue a merge request in repository1 to make it the new master, or just keep it as a branch.
A: A simple and intuitive (in my opinion) two-step way of doing it is
git checkout branchB .
git commit -m "Picked up the content from branchB"
followed by
git merge -s ours branchB
(which marks the two branches as merged)
The only disadvantage is that it does not remove files which have been deleted in branchB from your current branch. A simple diff between the two branches afterwards will show if there are any such files.
This approach also makes it clear from the revision log afterwards what was done - and what was intended.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1081"
} |
Q: Displaying a Desktop Shortcut for a device having windows ce 4.2 (VS 2003) I have developed a Windows CE 4.2 Application in VS 2003. When i deploy the CAB file in the device having X86 has its processor, a short cut for the application is created in Start >> Program >> Application. But I want a short cut for the application on the
desktop.
I modified the INF file to add a new shortcut that points to the desktop folder inside windows folder but it didn't work. Also, If i replace the default shortcut created when I build the CAB file with the location of desktop it still creates a short cut in the Programs and not on the desktop.
Does anyone has a solution for this ?
A: I would check out the link: http://msdn.microsoft.com/en-us/library/ms938387.aspx
That should get you well on your way. Basically shortcuts in CE are just ASCII files of the format:
21#\Windows\solitare.exe
Where 21# is the number of characters in that path. Here's another link to MSDN with more info on that: http://msdn.microsoft.com/en-us/embedded/aa731295.aspx
Hope that helps!
A: After modifying the INF file, how did you regenrate the CAB? You must not use the menu item in Studio (can't recall if '03 had that option) as it will overwrite your INF.
If you're manually generating the CAB with CABWIZ, then show us your INF file, as you likely have something wrong there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Incorporating shareware restrictions in C++ software I wish to implement my software on a shareware basis, so that the user is
given a maximum trial period of (say) 30 days with which to try out the software. On purchase I intend the user to be given a randomly-generated key, which when entered
enables the software again.
I've never been down this route before, so any advice or feedback or pointers to 'standard' ways of how this is done would be much appreciated.
I do not anticipate users cheating by changing the system date or anything like that, though this is probably worth considering. Apologies if this topic has appeared before.
A: With regards to a random-generated key, how will you verify a key is legit or if a key is bogus if it is actually random? Have a look at the article "Implementing a Partial Serial Number Verification System" as it is quite good and is easy to implement in any language.
With regards to time trials, as basic solution would be to compare your main executable files creation time to the current system time and act on the difference. This assumes your installer sets the files creation time to the time of install as opposed to preserving the time you compiled it! :)
A: If your software is really useful, you'll certainly find cracked copies on P2P before you see your first order. This will happen no matter how sophisticated is the license enforcement code you are going to implement.
That said, just store first-run date somewhere (may be registry, if on Windows) and after 30 days refuse to start, or just open a reminder window.
Don't worry about cheaters, they'll find a way around your restrictions no matter what. Worry about your honest customers and try hard not to make their life harder.
Eric Sink has written more about this here (section 4).
A: Also watch out for the time changing radically, if the current date is magically less than the install date and such.
One way to get around this type of datelock is to change your date before you install to be years in the future. So you should check that the date today is not less that the install date.
A: On the first start, you can store the actual date somewhere.
Each following start, you look for the stored date, if it exist you read it an if it is more than 30 days after the first start, you stop the program.
A: Please see this library.
Description:
Convert any application into time-limited shareware. Generate serial numbers to register it. A function library offering a flexible locking system with solid encryption. Easy to implement. Support for VB, C++, Delphi, other languages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: HTML newspaper columns I'm trying to create newspaper style columns using a block of text. I would like the text to be evenly spread out across 2 columns which could react to change of length in the text.
Is this possible using just HTML/CSS, if not could javascript be used?
Thanks
A: If you decide to do this, it is already possible in Mozilla and WebKit (and Prince) with only CSS:
selector {
-moz-column-count: 2;
-webkit-column-count: 2;
column-count: 2;
}
A: It's in the CSS3 spec, and Moz/Webkit already have it implemented with vendor prefixes. Use the column-count and column-gap properties:
#container {
-moz-column-count: 2;
-moz-column-gap: 20px;
-webkit-column-count: 2;
-webkit-column-gap: 20px;
column-count: 2;
column-gap: 20px;
}
Note that, of course, these are not supported by any version of IE that anyone uses. CanIUse.com claims IE 10 will support it as part of CSS3.
A: CSS3 provides a way of turning any HTML node's content into any number of columns. There are properties for controlling the number of columns as well as their width, relative height ("fill," or how the content is divided across the existing columns), gutter between columns, "rule" (dividing line or border), etc.
As a starting point, see the w3schools.com CSS3 Multiple Columns reference page.
However, as usual, IE alone among widely used browsers does not support the column- CSS3 properties.
One cross-browser solution is the Columnizer jQuery Plugin.
A: Two notes:
*
*What works for a printed medium isn't good for a display medium. Having to scroll up to continue to read doesn't seem like a good idea for me. After all, Web pages aren't limited in length...
*You cannot do that with CSS2. I think that CSS3 has support for that (not sure), I doubt it is supported by most browsers.
So I suppose JS is your best bet, but it won't work for users with disabled JS, of course.
A: CSS3 will allow you to do this with their multicolumn support, but at the moment, you probably can't rely on very many browsers to support it, so you'll probably need to rely on an alternate method.
A: Here's a simple (not CSS friendly) javascript function that will do this:
function Newspaperize(elem)
{
var halflength = elem.innerText.length / 2;
var col1 = elem.innerText.substring(0, halflength);
var col2 = elem.innerText.substring(halflength);
elem.innerHTML = '<TABLE WIDTH=100%><TR>' +
'<TD WIDTH=50% VALIGN=TOP>' + col1 + '</TD>' +
'<TD VALIGN=TOP>' + col2 + '</TD>' +
'</TR></TABLE>';
}
Put your text in a regular element somewhere, and call Newspaperize(yourelement) when the page loads.
Note: this function just splits the text in half. To really work properly, you'd want to find a space or hyphen nearest the midpoint and split the text there.
A: I agree with PhiLho. If you still want to try it the js code dividing your content into two columns is quite simple if the columns have fixed widths. The tricky bit is deciding where to split the content. You probably don't want to split in the middle of a word etc.
You could try with the following scenario: Add two columns into your page. Put your text into the first column (this allows non js browsers to still display your content). Get the text with js (eg. from onload event). Find the next index of "." (or if you have paragraphs "< /p>") starting from the middle. Use that index to split the text and put the first part back in the first column and so on...
A: The IHT has a nice implementation of a 3 colums format. It however seems to be calculated server side, I guess by counting words.
A: As others have said - not something that's possible with vanilla CSS/XHTML (at least - not until we get widespread CSS3 :-)
However, wearing my user experience hat, I'd be interested in your use case for wanting this on a web page (assuming that it's a normal web page that you're targeting). Unlike print splitting a block of text over two columns can make it harder to read. If it's longer than a screen then the user has to do a lot of scrolling up and down to scan/read everything.
So - even if you can do it with some JS hacking - might be better to come up with an alternate design that doesn't need it.
A: So i was looking for an answer for this question, sadly at first i didn't really found one, now 3 hours later i did.
I found a JavaScript lib which uses the css3 attributes (if i understood it right, only tried to make it work and it did, gonna read in the js later )
lib found here: http://www.csscripting.com/wiki/index.php?title=CSS3_Multi_Column
only disadvantage is that the text you want to have multicolumned HAS to be between two tags ( i prefer using <p> tag, as it also supports multiple <p> tags.)
tested it in ff 3.6, ie 8, opera 10.51 and chrome 4.1.
Im not in the position to test for older browsers, so i recommend someone does that soon ;P
cheers!
A: I managed to do something like this but again, not in CSS, I used PHP to count words and split the text. Unfortunately counting words is a pretty bad way of going about doing it, since some words are longer than others and the columns don't match up. My design was inspired by the IHT website. It's not very hard to implement in PHP.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/173934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.