text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Multijoin queries in Django What's the best and/or fastest method of doing multijoin queries in Django using the ORM and QuerySet API?
A: If you are trying to join across tables linked by ForeignKeys or ManyToManyField relationships then you can use the double underscore syntax. For example if you have the following models:
class Foo(models.Model):
name = models.CharField(max_length=255)
class FizzBuzz(models.Model):
bleh = models.CharField(max_length=255)
class Bar(models.Model):
foo = models.ForeignKey(Foo)
fizzbuzz = models.ForeignKey(FizzBuzz)
You can do something like:
Fizzbuzz.objects.filter(bar__foo__name = "Adrian")
A: Don't use the API ;-) Seriously, if your JOIN are complex, you should see significant performance increases by dropping down in to SQL rather than by using the API. And this doesn't mean you need to get dirty dirty SQL all over your beautiful Python code; just make a custom manager to handle the JOINs and then have the rest of your code use it rather than direct SQL.
Also, I was just at DjangoCon where they had a seminar on high-performance Django, and one of the key things I took away from it was that if performance is a real concern (and you plan to have significant traffic someday), you really shouldn't be doing JOINs in the first place, because they make scaling your app while maintaining decent performance virtually impossible.
Here's a video Google made of the talk:
http://www.youtube.com/watch?v=D-4UN4MkSyI&feature=PlayList&p=D415FAF806EC47A1&index=20
Of course, if you know that your application is never going to have to deal with that kind of scaling concern, JOIN away :-) And if you're also not worried about the performance hit of using the API, then you really don't need to worry about the (AFAIK) miniscule, if any, performance difference between using one API method over another.
Just use:
http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships
Hope that helps (and if it doesn't, hopefully some true Django hacker can jump in and explain why method X actually does have some noticeable performance difference).
A: Use the queryset.query.join method, but only if the other method described here (using double underscores) isn't adequate.
A: Caktus blog has an answer to this: http://www.caktusgroup.com/blog/2009/09/28/custom-joins-with-djangos-queryjoin/
Basically there is a hidden QuerySet.query.join method that allows adding custom joins.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can you use CMFCVisualManager with a dialog based application? Can you use CMFCVisualManager with a dialog based application to change the applications appearance? If so how is it done?
The idea is to change the shape, colour etc. of controls such as push buttons using the MFC Feature Pack released with MSVC 2008.
A: No, can't be done, at least not if you're talking about the Feature Pack version. Version 10 of the BCGSoft libraries do have this functionality, see for example: http://www.bcgsoft.com/bcgcontrolbarpro-versions.htm and http://www.bcgsoft.com/images/SkinnedBuiltInDlgs.jpg. The MFC feature pack is more or less the previous version of the BCGSoft libraries, MS bought a license from them.
A: You need to add the Common Controls manifest to your project resources. Here is the code for the manifest file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
version="1.0.0.0"
processorArchitecture="X86"
name="Program Name"
type="win32"
/>
<description>Description of Program</description>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="X86"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
</assembly>
A: I think you can have some MFC-feature-pack features by implementing OnApplicationLook on your base CDialog (check Step 4 on this page). It might be better to implement the whole OnApplicationLook method, but you can test your application simply by adding this to OnInitDialog:
CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Silver);
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2007));
CDockingManager::SetDockingMode(DT_SMART);
RedrawWindow(NULL, NULL, RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW | RDW_FRAME | RDW_ERASE);
A: This is the least amount of code to enable the Visual Styles. You should be able to pop your CDialog into the frame easily. The IDR_MAINFRAME is a menu resource.
class CMFCApplication2Dlg : public CFrameWndEx
{
CMFCMenuBar bar;
public:
CMFCApplication2Dlg() : CFrameWndEx()
{
LoadFrame(IDR_MAINFRAME);
bar.Create(this);
}
};
class CMFCApplication2App : public CWinAppEx
{
public:
virtual BOOL InitInstance()
{
CWinAppEx::InitInstance();
CMFCVisualManagerOffice2007::SetStyle(
CMFCVisualManagerOffice2007::Office2007_ObsidianBlack);
CMFCVisualManager::SetDefaultManager(
RUNTIME_CLASS(CMFCVisualManagerOffice2007));
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
m_pMainWnd = new CMFCApplication2Dlg();
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
return TRUE;
}
};
CMFCApplication2App theApp;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Making a C#/Winform application cross-platform - should I use AIR, Mono, or something else? I have an app that I've written in C#/WinForms (my little app). To make it cross-platform, I'm thinking of redoing it in Adobe AIR. Are there any arguments in favor of WinForms as a cross-platform app? Is there a cross-platform future for Winforms (e.g., Mono, etc.)? Suggestions for cross-platform UI development?
By cross-platform I mean, currently, Mac OSX, Windows and Linux.
This question was asked again and answered with better success.
A: As far as my experience in Flex/AIR/Flash actionscripting goes, Adobe AIR development environment and coding/debugging toolsets are far inferior to the Visual Studio and .NET SDK as of the moment. The UI toolsets are superior though.
But as you already have a working C# code, porting it to ActionScript might requires a redesign due to ActionScript having a different way of thinking/programming, they use different primitive data types, for example, they use just a Number instead of int float double etc. and the debugging tools are quiet lacking compared to VS IMO.
And I heard that Mono's GtkSharp is quiet a decent platform.
But if you don't mind the coding/debugging tooling problems, then AIR is a great platform. I like how Adobe integrates the Flash experience into it e.g. you can start an installation of AIR application via a button click in a flash movieclip, that kind of integration.
A:
I'm thinking of redoing it in Adobe AIR
Not having spent much time with AIR, my personal opinion is that it is best for bringing a webapp to the desktop and provide a shell to it or run your existing flash/flex project on the desktop.
Btw, if you don't know ActionScript, I mean its details, quirks, etc, don't forget to factor in the time it will take googling for answers.
Are there any arguments in favor of WinForms as a cross-platform app?
Is there a cross-platform future for Winforms (e.g., Mono, etc.)?
It's always hard to predict what will happen, but there is at least one project (Plastic SCM) I know of which uses Mono Winforms on Win, Mac and Linux, so it is certainly doable. However, they say they built most of their controls from the ground up (and claim they want to release them as open source, but not sure if or when), so you will need to put in some work to make things look "pretty".
I played with Winforms on non-windows platforms and unfortunately, it isn't exactly "mature" (especially on Mac). So what you get out of the box may or may not be sufficient for your needs.
If you decide a desktop app is not the best way to provide a cross-platform solution, you can always take your business logic written in C# and create either a full-blown webapp with ASP.NET or go with Silverlight, so many other options exist with C#.
A: WinForms are fully supported by Mono, so they are cross-platform.
A: Why would you go with Air?
Use GTK#, and you have a cross platform forms engine and you get to keep your C# code.
A: Well I think the only way to for cross-platform reliably with C# is Microsoft Silverlight, but is not really WinForms, and browser-based. Other than that, yes Mono is a chance.
A: If you want to use the .net Framework, Microsoft Silverlight is a good (the only?) choice. The browser does a good job as a shell, but you could also write your own application shell for it. For example, Scott Handelman mentions the NY Times Reader written in Silverlight and hostet on Cocoa on a Mac.
A: I don't think there is a future for WinForms at all. Since it appears to have been a stop-gap solution even in MSFT world ( a very thin wrapper around Win32). And virtually no changes seem to have been made to System.Windows.Forms in both .NET 3.0 and 3.5
</speculation>
I would use Java or Air.
A: I think that as long as you make sure that the business logic code you write is cross-platform (i.e. using backslashes in paths only works on Windows - forward slashes works on all OS's), then Mono shouldn't have major problems running an unmodified WinForms program. Just make sure you test for graphical glitches.
A: I asked a similar question last week. I've been using Mono all along, and have had no issues running the applications I compile to IL to run on SuSE linux (I usually run KDE) or windows, however, I've not gone out and got a mac yet to test it on. I will be soon, though, probably with in a couple weeks. But all and all development in Mono has been very good at creating application that will run on multiple platforms.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Temp tables and SQL SELECT performance Why does the use of temp tables with a SELECT statement improve the logical I/O count? Wouldn't it increase the amount of hits to a database instead of decreasing it. Is this because the 'problem' is broken down into sections? I'd like to know what's going on behind the scenes.
A: There's no general answer. It depends on how the temp table is being used.
The temp table may reduce IO by caching rows created after a complex filter/join that are used multiple times later in the batch. This way, the DB can avoid hitting the base tables multiple times when only a subset of the records are needed.
The temp table may increase IO by storing records that are never used later in the query, or by taking up a lot of space in the engine's cache that could have been better used by other data.
Creating a temp table to use all of its contents once is slower than including the temp's query in the main query because the query optimizer can't see past the temp table and it forces a (probably) unnecessary spool of the data instead of allowing it to stream from the source tables.
A: I'm going to assume by temp tables you mean a sub-select in a WHERE clause. (This is referred to as a semijoin operation and you can usually see that in the text execution plan for your query.)
When the query optimizer encounter a sub-select/temp table, it makes some assumptions about what to do with that data. Essentially, the optimizer will create an execution plan that performs a join on the sub-select's result set, reducing the number of rows that need to be read from the other tables. Since there are less rows, the query engine is able to read less pages from disk/memory and reduce the amount of I/O required.
A: AFAIK, at least with mysql, tmp tables are kept in RAM, making SELECTs much faster than anything that hits the HD
A: There are a class of problems where building the result in a collection structure on the database side is much preferable to returning the result's parts to the client, roundtripping for each part.
For example: arbitrary depth recursive relationships (boss of)
There's another class of query problems where the data is not and will not be indexed in a manner that makes the query run efficiently. Pulling results into a collection structure, which can be indexed in a custom way, will reduce the logical IO for these queries.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How do I invoke an exe that is an embedded resource in a .Net assembly? I have a non-.Net executable file that is included in my .net assembly as an embedded resource. Is there a way to run this executable that does not involve writing it out to disk and launching it?
This is .Net 2.0.
A: You might try injecting your exe into a suspended process and then awakening the hijacked process, but this seems like a recipe for disaster.
A: You can load a .NET assembly from a byte array using an overload of Assembly.Load.
However, there are implications for the security model that need to be considered which make things more complex. See the discussion here, and also this thread.
If your embedded executable is not .NET then I think you will have to write it out to disk first.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Embed data in a C++ program I've got a C++ program that uses SQLite. I want to store the SQL queries in a separate file -- a plain-text file, not a source code file -- but embed that file in the executable file like a resource.
(This has to run on Linux, so I can't store it as an actual resource as far as I know, though that would be perfect if it were for Windows.)
Is there any simple way to do it, or will it effectively require me to write my own resource system for Linux? (Easily possible, but it would take a lot longer.)
A: Use macros. Technically that file would be source code file but it wouldn't look like this.
Example:
//queries.incl - SQL queries
Q(SELECT * FROM Users)
Q(INSERT [a] INTO Accounts)
//source.cpp
#define Q(query) #query,
char * queries[] = {
#include "queries.incl"
};
#undef Q
Later on you could do all sorts of other processing on that file by the same file, say you'd want to have array and a hash map of them, you could redefine Q to do another job and be done with it.
A: You can always write a small program or script to convert your text file into a header file and run it as part of your build process.
A: You can use objcopy to bind the contents of the file to a symbol your program can use. See, for instance, here for more information.
A: Here's a sample that we used for cross-platform embeddeding of files.
It's pretty simplistic, but will probably work for you.
You may also need to change how it's handling linefeeds in the escapeLine function.
#include <string>
#include <iostream>
#include <fstream>
#include <cstdio>
using namespace std;
std::string escapeLine( std::string orig )
{
string retme;
for (unsigned int i=0; i<orig.size(); i++)
{
switch (orig[i])
{
case '\\':
retme += "\\\\";
break;
case '"':
retme += "\\\"";
break;
case '\n': // Strip out the final linefeed.
break;
default:
retme += orig[i];
}
}
retme += "\\n"; // Add an escaped linefeed to the escaped string.
return retme;
}
int main( int argc, char ** argv )
{
string filenamein, filenameout;
if ( argc > 1 )
filenamein = argv[ 1 ];
else
{
// Not enough arguments
fprintf( stderr, "Usage: %s <file to convert.mel> [ <output file name.mel> ]\n", argv[0] );
exit( -1 );
}
if ( argc > 2 )
filenameout = argv[ 2 ];
else
{
string new_ending = "_mel.h";
filenameout = filenamein;
std::string::size_type pos;
pos = filenameout.find( ".mel" );
if (pos == std::string::npos)
filenameout += new_ending;
else
filenameout.replace( pos, new_ending.size(), new_ending );
}
printf( "Converting \"%s\" to \"%s\"\n", filenamein.c_str(), filenameout.c_str() );
ifstream filein( filenamein.c_str(), ios::in );
ofstream fileout( filenameout.c_str(), ios::out );
if (!filein.good())
{
fprintf( stderr, "Unable to open input file %s\n", filenamein.c_str() );
exit( -2 );
}
if (!fileout.good())
{
fprintf( stderr, "Unable to open output file %s\n", filenameout.c_str() );
exit( -3 );
}
// Write the file.
fileout << "tempstr = ";
while( filein.good() )
{
string buff;
if ( getline( filein, buff ) )
{
fileout << "\"" << escapeLine( buff ) << "\"" << endl;
}
}
fileout << ";" << endl;
filein.close();
fileout.close();
return 0;
}
A: It's slightly ugly, but you can always use something like:
const char *query_foo =
#include "query_foo.txt"
const char *query_bar =
#include "query_bar.txt"
Where query_foo.txt would contain the quoted query text.
A: I have seen this to be done by converting the resource file to a C source file with only one char array defined containing the content of resource file in a hexadecimal format (to avoid problems with malicious characters). This automatically generated source file is then simply compiled and linked to the project.
It should be pretty easy to implement the convertor to dump C file for each resource file also as to write some facade functions for accessing the resources.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: SharePoint Content Query Web Part I have a content query web part that queries by content type against a site collection. I have grouped it by content type so I have:
-- Agenda (Content Type)
----Agenda #1
----Agenda #2
-- Report (Content Type)
----Report #1
----Report #2
I would like to show a second grouping for site, so:
-- Agenda (Content Type)
----This Site
------Agenda #1
----That Site
------Agenda #2
-- Report (Content Type)
----This Site
------Report #1
------Report #2
Does anyone know the best way to achieve this?
All the best
Kieran
A: You have full access to change the xslt for the content query webpart. I reccomend exporting the webpart, saving the inline xslt into the style library and changing the webpart from using inline xslt to using a link to the file in the style library. This allows you to edit the xslt file using sharepoint designer which is much easier.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: "Could not find file" when using Isolated Storage I save stuff in an Isolated Storage file (using class IsolatedStorageFile). It works well, and I can retrieve the saved values when calling the saving and retrieving methods in my DAL layer from my GUI layer. However, when I try to retrieve the same settings from another assembly in the same project, it gives me a FileNotFoundException. What do I do wrong? This is the general concept:
public void Save(int number)
{
IsolatedStorageFile storage = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFileStream fileStream =
new IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, storage);
StreamWriter writer = new StreamWriter(fileStream);
writer.WriteLine(number);
writer.Close();
}
public int Retrieve()
{
IsolatedStorageFile storage = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filename, FileMode.Open, storage);
StreamReader reader = new StreamReader(fileStream);
int number;
try
{
string line = reader.ReadLine();
number = int.Parse(line);
}
finally
{
reader.Close();
}
return number;
}
I've tried using all the GetMachineStoreFor* scopes.
EDIT: Since I need several assemblies to access the files, it doesn't seem possible to do with isolated storage, unless it's a ClickOnce application.
A: When you instantiated the IsolatedStorageFile, did you scope it to IsolatedStorageScope.Machine?
Ok now that you have illustrated your code style and I have gone back to retesting the behaviour of the methods, here is the explanation:
*
*GetMachineStoreForAssembly() - scoped to the machine and the assembly identity. Different assemblies in the same application would have their own isolated storage.
*GetMachineStoreForDomain() - a misnomer in my opinion. scoped to the machine and the domain identity on top of the assembly identity. There should have been an option for just AppDomain alone.
*GetMachineStoreForApplication() - this is the one you are looking for. I have tested it and different assemblies can pick up the values written in another assembly. The only catch is, the application identity must be verifiable. When running locally, it cannot be properly determined and it will end up with exception "Unable to determine application identity of the caller". It can be verified by deploying the application via Click Once. Only then can this method apply and achieve its desired effect of shared isolated storage.
A: When you are saving, you are calling GetMachineStoreForDomain, but when you are retrieving, you are calling GetMachineStoreForAssembly.
GetMachineStoreForAssembly is scoped to the assembly that the code is executing in, while the GetMachineStoreForDomain is scoped to the currently running AppDomain and the assembly where the code is executing. Just change your these calls to GetMachineStoreForApplication, and it should work.
The documentation for IsolatedStorageFile can be found at http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile_members.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: What is the best way to process all versions of MS Excel spreadsheets with php on a non-Windows machine I am importing data from MS Excel spreadsheets into a php/mySQL application. Several different parties are supplying the spreadsheets and they are in formats ranging from Excel 4.0 to Excel 2007.
The trouble is finding a technique to read ALL versions.
More info:
- I am currently using php-ExcelReader.
- A script in a language other than php that can convert Excel to CSV would be an acceptable solution.
A: Depending on the nature of your data and the parties that upload the excel files, you might want to consider having them save the data in .csv format. It will be much easier to parse on your end.
Assuming that isn't an option a quick google search turned up http://sourceforge.net/projects/phpexcelreader/ which might suit your needs.
A: The open-source ETL tool Talend (http://wwww.talend.com) will generate Java or Perl code and package such code with the necessary 3rd party libraries.
Talend should be able to handle all versions of Excel and output the result set in any format you require (including loading it directly into a database if need be).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Should I use a state machine or a sequence workflow in WF? I have a repeatable business process that I execute every week as part of my configuration management responsibilities. The process does not change: I download change details into Excel, open the spreadsheet and copy out details based on a macro, create a Word document from an agenda template, update the agenda with the Excel data, create PDFs from the Word document, and email them out.
This process is very easily represented in a sequence workflow and that's how I have it so far, with COM automation to handle the Excel and Word pieces automatically. The wrench in the gears is that there is a human step between "create agenda" and "send it out," wherein I review the change details and formulate questions about them, which are added to the agenda. I currently have a Suspend activity to suspend the workflow while I manually do this piece of the process.
My question is, should I rewrite my workflow to make it a state machine to follow a best practice for human interaction in a business process, or is the Suspend activity a reasonable solution?
A: No, I don't think that you have to use a state machine for this workflow. But, I propose to change the Suspend activity because:
The SuspendActivity activity
temporarily stops the execution of the
current workflow. Typically, you use
the SuspendActivity activity to
reflect an error condition that
requires attention by an
administrator.
When a workflow
instance is suspended, an error is
logged. You can specify a message
string to accompany the error to help
the administrator diagnose the problem
with the SuspendActivity Error
property. A suspended workflow
instance can still receive messages
that are queued up until the workflow
is restarted. All the state
information for the workflow instance
is saved and is reinstated when the
instance is resumed (using Resume).
Source: MSDN
The typical way for adding a human task in a workflow (either sequence or state machine) is to define an External Data Exchange interface and use a HandleExternalEvent activity (and possibly a CallExternalMethod activity). For more details, please see the following articles:
*
*Building State Machines with Windows Workflow Foundation
*Simple Human Workflow with Windows Workflow Foundation
A: Update: Panos makes a good point about Suspend Activity. I agree it has a different purpose in the workflow automaton.
If you feel you are worrying more about workflow transitioning between various states, then state machine workflow is ideal. Otherwise, sequence is just fine.
The main problem you should be trying to solve is that the workflow should not tie up a thread while waiting for the human interaction (thread agility). If the workflow is idled and persisted during that time (like using SqlWorkflowPersistenceService), it should not be a problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to create batch file in Windows using "start" with a path and command with spaces I need to create a batch file which starts multiple console applications in a Windows .cmd file. This can be done using the start command.
However, the command has a path in it. I also need to pass paramaters which have spaces as well. How to do this?
E.g. batch file
start "c:\path with spaces\app.exe" param1 "param with spaces"
A: start "" "c:\path with spaces\app.exe" "C:\path parameter\param.exe"
When I used above suggestion, I've got:
'c:\path' is not recognized a an internal or external command, operable program or batch file.
I think second qoutation mark prevent command to run. After some search below solution save my day:
start "" CALL "c:\path with spaces\app.exe" "C:\path parameter\param.exe"
A: Actually, his example won't work (although at first I thought that it would, too). Based on the help for the Start command, the first parameter is the name of the newly created Command Prompt window, and the second and third should be the path to the application and its parameters, respectively. If you add another "" before path to the app, it should work (at least it did for me). Use something like this:
start "" "c:\path with spaces\app.exe" param1 "param with spaces"
You can change the first argument to be whatever you want the title of the new command prompt to be. If it's a Windows app that is created, then the command prompt won't be displayed, and the title won't matter.
A: Escaping the path with apostrophes is correct, but the start command takes a parameter containing the title of the new window. This parameter is detected by the surrounding apostrophes, so your application is not executed.
Try something like this:
start "Dummy Title" "c:\path with spaces\app.exe" param1 "param with spaces"
A: Interestingly, it seems that in Windows Embedded Compact 7, you cannot specify a title string. The first parameter has to be the command or program.
A: You are to use something like this:
start /d C:\Windows\System32\calc.exe
start /d "C:\Program Files\Mozilla
Firefox" firefox.exe start /d
"C:\Program Files\Microsoft
Office\Office12" EXCEL.EXE
Also I advice you to use special batch files editor - Dr.Batcher
A: Surrounding the path and the argument with spaces inside quotes as in your example should do. The command may need to handle the quotes when the parameters are passed to it, but it usually is not a big deal.
A: I researched successfully and it is working fine for me. My requirement is to sent an email using vbscript which needs to be call from a batch file in windows. Here is the exact command I am using with no errors.
START C:\Windows\System32\cscript.exe "C:\Documents and Settings\akapoor\Desktop\Mail.vbs"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "78"
}
|
Q: Is there an inverse function of *SysUtils.Format* in Delphi Has anyone written an 'UnFormat' routine for Delphi?
What I'm imagining is the inverse of SysUtils.Format and looks something like this
UnFormat('a number %n and another %n',[float1, float2]);
So you could unpack a string into a series of variables using format strings.
I've looked at the 'Format' routine in SysUtils, but I've never used assembly so it is meaningless to me.
A: I know it tends to scare people, but you could write a simple function to do this using regular expressions
'a number (.*?) and another (.*?)
If you are worried about reg expressions take a look at www.regexbuddy.com and you'll never look back.
A: This is called scanf in C, I've made a Delphi look-a-like for this :
function ScanFormat(const Input, Format: string; Args: array of Pointer): Integer;
var
InputOffset: Integer;
FormatOffset: Integer;
InputChar: Char;
FormatChar: Char;
function _GetInputChar: Char;
begin
if InputOffset <= Length(Input) then
begin
Result := Input[InputOffset];
Inc(InputOffset);
end
else
Result := #0;
end;
function _PeekFormatChar: Char;
begin
if FormatOffset <= Length(Format) then
Result := Format[FormatOffset]
else
Result := #0;
end;
function _GetFormatChar: Char;
begin
Result := _PeekFormatChar;
if Result <> #0 then
Inc(FormatOffset);
end;
function _ScanInputString(const Arg: Pointer = nil): string;
var
EndChar: Char;
begin
Result := '';
EndChar := _PeekFormatChar;
InputChar := _GetInputChar;
while (InputChar > ' ')
and (InputChar <> EndChar) do
begin
Result := Result + InputChar;
InputChar := _GetInputChar;
end;
if InputChar <> #0 then
Dec(InputOffset);
if Assigned(Arg) then
PString(Arg)^ := Result;
end;
function _ScanInputInteger(const Arg: Pointer): Boolean;
var
Value: string;
begin
Value := _ScanInputString;
Result := TryStrToInt(Value, {out} PInteger(Arg)^);
end;
procedure _Raise;
begin
raise EConvertError.CreateFmt('Unknown ScanFormat character : "%s"!', [FormatChar]);
end;
begin
Result := 0;
InputOffset := 1;
FormatOffset := 1;
FormatChar := _GetFormatChar;
while FormatChar <> #0 do
begin
if FormatChar <> '%' then
begin
InputChar := _GetInputChar;
if (InputChar = #0)
or (FormatChar <> InputChar) then
Exit;
end
else
begin
FormatChar := _GetFormatChar;
case FormatChar of
'%':
if _GetInputChar <> '%' then
Exit;
's':
begin
_ScanInputString(Args[Result]);
Inc(Result);
end;
'd', 'u':
begin
if not _ScanInputInteger(Args[Result]) then
Exit;
Inc(Result);
end;
else
_Raise;
end;
end;
FormatChar := _GetFormatChar;
end;
end;
A: I tend to take care of this using a simple parser. I have two functions, one is called NumStringParts which returns the number of "parts" in a string with a specific delimiter (in your case above the space) and GetStrPart returns the specific part from a string with a specific delimiter. Both of these routines have been used since my Turbo Pascal days in many a project.
function NumStringParts(SourceStr,Delimiter:String):Integer;
var
offset : integer;
curnum : integer;
begin
curnum := 1;
offset := 1;
while (offset <> 0) do
begin
Offset := Pos(Delimiter,SourceStr);
if Offset <> 0 then
begin
Inc(CurNum);
Delete(SourceStr,1,(Offset-1)+Length(Delimiter));
end;
end;
result := CurNum;
end;
function GetStringPart(SourceStr,Delimiter:String;Num:Integer):string;
var
offset : integer;
CurNum : integer;
CurPart : String;
begin
CurNum := 1;
Offset := 1;
While (CurNum <= Num) and (Offset <> 0) do
begin
Offset := Pos(Delimiter,SourceStr);
if Offset <> 0 then
begin
CurPart := Copy(SourceStr,1,Offset-1);
Delete(SourceStr,1,(Offset-1)+Length(Delimiter));
Inc(CurNum)
end
else
CurPart := SourceStr;
end;
if CurNum >= Num then
Result := CurPart
else
Result := '';
end;
Example of usage:
var
st : string;
f1,f2 : double;
begin
st := 'a number 12.35 and another 13.415';
ShowMessage('Total String parts = '+IntToStr(NumStringParts(st,#32)));
f1 := StrToFloatDef(GetStringPart(st,#32,3),0.0);
f2 := StrToFloatDef(GetStringPart(st,#32,6),0.0);
ShowMessage('Float 1 = '+FloatToStr(F1)+' and Float 2 = '+FloatToStr(F2));
end;
These routines work wonders for simple or strict comma delimited strings too. These routines work wonderfully in Delphi 2009/2010.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How to remove these kind of symbols (junk) from string? Imagine I have String in C#: "I Don’t see ya.."
I want to remove (replace to nothing or etc.) these "’" symbols.
How do I do this?
A: "I Don’t see ya..".Replace( "’", string.Empty);
How did that junk get in there the first place? That's the real question.
A: By removing any non-latin character you'll be intentionally breaking some internationalization support.
Don't forget the poor guy who's name has a "â" in it.
A: This looks disturbingly familiar to a character encoding issue dealing with the Windows character set being stored in a database using the standard character encoding. I see someone voted Will down, but he has a point. You may be solving the immediate issue, but the combinations of characters are limitless if this is the issue.
A: If you really have to do this, regular expressions are probably the best solution.
I would strongly recommend that you think about why you have to do this, though - at least some of the characters your listing as undesirable are perfectly valid and useful in other languages, and just filtering them out will most likely annoy at least some of your international users. As a swede, I can't emphasize enough how much I hate systems that can't handle our å, ä and ö characters correctly.
A: That 'junk' looks a lot like someone interpreted UTF-8 data as ISO 8859-1 or Windows-1252, probably repeatedly.
’ is the sequence C3 A2, E2 82 AC, E2 84 A2.
*
*UTF-8 C3 A2 = U+00E2 = â
*UTF-8 E2 82 AC = U+20AC = €
*UTF-8 E2 84 A2 = U+2122 = ™
We then do it again: in Windows 1252 this sequence is E2 80 99, so the character should have been U+2019, RIGHT SINGLE QUOTATION MARK (’)
You could make multiple passes with byte arrays, Encoding.UTF8 and Encoding.GetEncoding(1252) to correctly turn the junk back into what was originally entered. You will need to check your processing to find the two places that UTF-8 data was incorrectly interpreted as Windows-1252.
A: Consider Regex.Replace(your_string, regex, "") - that's what I use.
A: Test each character in turn to see if it is a valid alphabetic or numeric character and if not then remove it from the string. The character test is very simple, just use...
char.IsLetterOrDigit;
Please there are various others such as...
char.IsSymbol;
char.IsControl;
A: Regex.Replace("The string", "[^a-zA-Z ]","");
That's how you'd do it in C#, although that regular expression ([^a-zA-Z ]) should work in most languages.
[Edited: forgot the space in the regex]
A: The ASCII / Integer code for these characters would be out of the normal alphabetic Ranges. Seek and replace with empty characters. String has a Replace method I believe.
A: Either use a blacklist of stuff you do not want, or preferably a white list (set). With a white list you iterate over the string and only copy the letters that are in your white list to the result string. You said remove, and the way you do that is having two pointers one you read from (R) and one you write to (W):
I Donââ‚
W R
if comma is in your whitelist then you would in this case read the comma and write it where à is then advance both pointers. UTF-8 is a multi-byte encoding, so you advancing the pointer may not just be adding to the address.
With C an easy to way to get a white list by using one of the predefined functions (or macros): isalnum, isalpha, isascii, isblank, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, isxdigit. In this case you send up with a white list function instead of a set of course.
Usually when I see data like you have I look for memory corruption, or evidence to suggest that the encoding I expect is different than the one the data was entered with.
/Allan
A: If String having the any Junk date , This is good to way remove those junk date
string InputString = "This is grate kingdom¢Ã‚¬â";
string replace = "’";
string OutputString= Regex.Replace(InputString, replace, "");
//OutputString having the following result
It's working good to me , thanks for looking this review.
A: I had the same problem with extraneous junk thrown in by adobe in an EXIF dump. I spent an hour looking for a straight answer and trying numerous half-baked suggestions which did not work here.
This thread more than most I have read was replete with deep, probing questions like 'how did it get there?', 'what if somebody has this character in their name?', 'are you sure you want to break internationalization?'.
There were some impressive displays of erudition positing how this junk could have gotten here and explaining the evolution of the various character encoding schemes. The person wanted to know how to remove it, not how it came to be or what the standards orgs are up to, interesting as this trivia may be.
I wrote a tiny program which gave me the right answer. Instead of paraphrasing the main concept, here is the entire, self-contained, working (at least on my system) program and the output I used to nuke the junk:
#!/usr/local/bin/perl -w
# This runs in a dos window and shows the char, integer and hex values
# for the weird chars. Install the HEX values in the REGEXP below until
# the final test line looks normal.
$str = 's: “Brian'; # Nuke the 3 werid chars in front of Brian.
@str = split(//, $str);
printf("len str '$str' = %d, scalar \@str = %d\n",
length $str, scalar @str);
$ii = -1;
foreach $c (@str) {
$ii++;
printf("$ii) char '$c', ord=%03d, hex='%s'\n",
ord($c), unpack("H*", $c));
}
# Take the hex characters shown above, plug them into the below regexp
# until the junk disappears!
($s2 = $str) =~ s/[\xE2\x80\x9C]//g; # << Insert HEX values HERE
print("S2=>$s2<\n"); # Final test
Result:
M:\new\6s-2014.1031-nef.halloween>nuke_junk.pl
len str 's: GÇ£Brian' = 11, scalar @str = 11
0) char 's', ord=115, hex='73'
1) char ':', ord=058, hex='3a'
2) char ' ', ord=032, hex='20'
3) char 'G', ord=226, hex='e2'
4) char 'Ç', ord=128, hex='80'
5) char '£', ord=156, hex='9c'
6) char 'B', ord=066, hex='42'
7) char 'r', ord=114, hex='72'
8) char 'i', ord=105, hex='69'
9) char 'a', ord=097, hex='61'
10) char 'n', ord=110, hex='6e'
S2=>s: Brian<
It's NORMAL!!!
One other actionable, working suggestion I ran across:
iconv -c -t ASCII < 6s-2014.1031-238246.halloween.exf.dif > exf.ascii.dif
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there a name for this anti-pattern/code smell? Let me start by saying that I do not advocate this approach, but I saw it recently and I was wondering if there was a name for it I could use to point the guilty party to. So here goes.
Now you have a method, and you want to return a value. You also want to return an error code. Of course, exceptions are a much better choice, but for whatever reason you want an error code instead. Remember, I'm playing devil's advocate here. So you create a generic class, like this:
class FunctionResult<T>
{
public T payload;
public int result;
}
And then declare your functions like this:
FunctionResult<string> MyFunction()
{
FunctionResult<string> result;
//...
return result;
}
One variation on this pattern is to use an enum for the error code instead of a string. Now, back to my question: is there a name for this, and if so what is it?
A: I usually pass the payload as (not const) reference and the error code as a return value.
I'm a game developer, we banish exceptions
A: Konrad is right, C# uses dual return values all the time. But I kind of like the TryParse, Dictionary.TryGetValue, etc. methods in C#.
int value;
if (int.TryParse("123", out value)) {
// use value
}
instead of
int? value = int.TryParse("123");
if (value != null) {
// use value
}
...mostly because the Nullable pattern does not scale to non-Value return types (i.e., class instances). This wouldn't work with Dictionary.TryGetValue(). And TryGetValue is both nicer than a KeyNotFoundException (no "first chance exceptions" constantly in the debugger, arguably more efficient), nicer than Java's practice of get() returning null (what if null values are expected), and more efficient than having to call ContainsKey() first.
But this is still a little bit screwy -- since this looks like C#, then it should be using an out parameter. All efficiency gains are probably lost by instantiating the class.
(Could be Java except for the "string" type being in lowercase. In Java of course you have to use a class to emulate dual return values.)
A: I am not sure this is an anti-pattern. I have commonly seen this used instead of exceptions for performance reasons, or perhaps to make the fact that the method can fail more explicit. To me, it seems to be a personal preference rather than an anti-pattern.
A: I agree with those that say this is not an anti-pattern. Its a perfectly valid pattern in certain contexts. Exceptions are for exceptional situations, return values (like in your example) should be used in expected situations. Some domains expect valid and invalid results from classes, and neither of those should be modeled as exceptions.
For example, given X amount of gas, can a car get from A to B, and if so how much gas is left over? That kind of question is ideal for the data structure you provided. Not being able to make the trip from A to B is expected, hence an exception should not be used.
A: This approach is actually much better than some others that I have seen. Some functions in C, for example, when they encounter an error they return and seem to succeed. The only way to tell that they failed is to call a function that will get the latest error.
I spent hours trying to debug semaphore code on my MacBook before I finally found out that sem_init doesn't work on OSX! It compiled without error and ran without causing any errors - yet the semaphore didn't work and I couldn't figure out why. I pity the people that port an application that uses POSIX semaphores to OSX and must deal with resource contention issues that have already been debugged.
A: I'd agree that this isn't specifically an antipattern. It might be a smell depending upon the usage. There are reasons why one would actually not want to use exceptions (e.g. the errors being returned are not 'exceptional', for starters).
There are instances where you want to have a service return a common model for its results, including both errors and good values. This might be wrapped by a low level service interaction that translates the result into an exception or other error structure, but at the level of the service, it lets the service return a result and a status code without having to define some exception structure that might have to be translated across a remote boundary.
This code may not necessarily be an error either: consider an HTTP response, which consists of a lot of different data, including a status code, along with the body of the response.
A: It is called "Replace Error Code with Exception"
A: Well, it's not an antipattern. The C++ standard library makes use of this feature and .NET even offers a special FunctionResult class in the .NET framework. It's called Nullable. Yes, this isn't restricted to function results but it can be used for such cases and is actually very useful here. If .NET 1.0 had already had the Nullable class, it would certainly have been used for the NumberType.TryParse methods, instead of the out parameter.
A: How about the "Can't decide whether this is an error or not" pattern. Seems like if you really had an exception but wanted to return a partial result, you'd wrap the result in the exception.
A: If you don't want to use exceptions, the cleanest way to do it is to have the function return the error/success code and take either a reference or pointer argument that gets filled in with the result.
I would not call it an anti-pattern. It's a very well proven workable method that's often preferable to using exceptions.
A: If you expect your method to fail occasionally, but don't consider that exceptional, I prefer this pattern as used in the .NET Framework:
bool TryMyFunction(out FunctionResult result){
//...
result = new FunctionResult();
}
A: Debates about smells and anti-patterns remind me the "Survivor" TV shows, where you have various programming constructs trying to vote each other off the island. I'd prefer to see "construct X has such-and-so pros and cons", rather than a continually evolving list of edicts of what should and should not be done.
A: In defense of the anti-pattern designation, this code lends itself to being used in a few ways:
*
*Object x = MyFunction().payload; (ignoring the return result - very bad)
*int code = MyFunction().result; (throwing away the payload - may be okay if that's the intended use.)
*FunctionResult x = MyFunction(); //... (a bunch of extra FunctionResult objects and extra code to check them all over the place)
If you need to use return codes, that's fine. But then use return codes. Don't try to pack an extra payload in with it. That's what ref and out parameters (C#) are for. Nullable types might be an exception, but only because there's extra sugar baked in the language to support it.
If you still disagree with this assessment, DOWNVOTE this answer (not the whole question). If you do think it's an anti-pattern, then UPVOTE it. We'll use this answer to see what the community thinks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Which is generally best to use — StringComparison.OrdinalIgnoreCase or StringComparison.InvariantCultureIgnoreCase? I have some code like this:
If key.Equals("search", StringComparison.OrdinalIgnoreCase) Then
DoSomething()
End If
I don't care about the case. Should I use OrdinalIgnoreCase, InvariantCultureIgnoreCase, or CurrentCultureIgnoreCase?
A: It all depends
Comparing unicode strings is hard:
The implementation of Unicode string
searches and comparisons in text
processing software must take into
account the presence of equivalent
code points. In the absence of this
feature, users searching for a
particular code point sequence would
be unable to find other visually
indistinguishable glyphs that have a
different, but canonically equivalent,
code point representation.
see: http://en.wikipedia.org/wiki/Unicode_equivalence
If you are trying to compare 2 unicode strings in a case insensitive way and want it to work EVERYWHERE, you have an impossible problem.
The classic example is the Turkish i, which when uppercased becomes İ (notice the dot)
By default, the .Net framework usually uses the CurrentCulture for string related functions, with a very important exception of .Equals that uses an ordinal (byte by byte) compare.
This leads, by design, to the various string functions behaving differently depending on the computer's culture.
Nonetheless, sometimes we want a "general purpose", case insensitive, comparison.
For example, you may want your string comparison to behave the same way, no matter what computer your application is installed on.
To achieve this we have 3 options:
*
*Set the culture explicitly and perform a case insensitive compare using unicode equivalence rules.
*Set the culture to the Invariant Culture and perform case insensitive compare using unicode equivalence rules.
*Use OrdinalIgnoreCase which will uppercase the string using the InvariantCulture and then perform a byte by byte comparison.
Unicode equivalence rules are complicated, which means using method 1) or 2) is more expensive than OrdinalIgnoreCase. The fact that OrdinalIgnoreCase does not perform any special unicode normalization, means that some strings that render in the same way on a computer screen, will not be considered identical. For example: "\u0061\u030a" and "\u00e5" both render å. However in a ordinal compare will be considered different.
Which you choose heavily depends on the application you are building.
*
*If I was writing a line-of-business app which was only used by Turkish users, I would be sure to use method 1.
*If I just needed a simple "fake" case insensitive compare, for say a column name in a db, which is usually English I would probably use method 3.
Microsoft has their set of recommendations with explicit guidelines. However, it is really important to understand the notion of unicode equivalence prior to approaching these problems.
Also, please keep in mind that OrdinalIgnoreCase is a very special kind of beast, that is picking and choosing a bit of an ordinal compare with some mixed in lexicographic aspects. This can be confusing.
A: I guess it depends on your situation. Since ordinal comparisons are actually looking at the characters' numeric Unicode values, they won't be the best choice when you're sorting alphabetically. For string comparisons, though, ordinal would be a tad faster.
A: Newer .Net Docs now has a table to help you decide which is best to use in your situation.
From MSDN's "New Recommendations for Using Strings in Microsoft .NET 2.0"
Summary: Code owners previously using the InvariantCulture for string comparison, casing, and sorting should strongly consider using a new set of String overloads in Microsoft .NET 2.0. Specifically, data that is designed to be culture-agnostic and linguistically irrelevant should begin specifying overloads using either the StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase members of the new StringComparison enumeration. These enforce a byte-by-byte comparison similar to strcmp that not only avoids bugs from linguistic interpretation of essentially symbolic strings, but provides better performance.
A: It depends on what you want, though I'd shy away from invariantculture unless you're very sure you'll never want to localize the code for other languages. Use CurrentCulture instead.
Also, OrdinalIgnoreCase should respect numbers, which may or may not be what you want.
A: The very simple answer is, unless you are using Turkish, you don't need to use InvariantCulture.
See the following link:
In C# what is the difference between ToUpper() and ToUpperInvariant()?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "199"
}
|
Q: Is it better to join two fields together, or to compare them each to the same constant? For example which is better:
select * from t1, t2 where t1.country='US' and t2.country=t1.country and t1.id=t2.id
or
select * from t1, t2 where t1.country'US' and t2.country='US' and t1.id=t2.id
better as in less work for the database, faster results.
Note: Sybase, and there's an index on both tables of country+id.
A: I don't think there is a global answer to your question. It depends on the specific query. You would have to compare the execution plans for the two queries to see if there are significant differences.
I personally prefer the first form:
select * from t1, t2 where t1.country='US' and t2.country=t1.country and t1.id=t2.id
because if I want to change the literal there is only one change needed.
A: There are a lot of factors at play here that you've left out. What kind of database is it? Are those tables indexed? How are they indexed? How large are those tables?
(Premature optimization is the root of all evil!)
It could be that if "t1.id" and "t2.id" are indexed, the database engine joins them together based on those fields, and then uses the rest of the WHERE clause to filter out rows.
They could be indexed but incredibly small tables, and both fit in a page of memory. In which case the database engine might just do a full scan of both rather than bother loading up the index.
You just don't know, really, until you try.
A: The correct answer probably depends on your SQL engine. For MS SQL Server, the first approach is clearly the better because the statistical optimizer is given an additional clue which may help it find a better (more optimal) resolution path.
A: I think it depends on the library and database engine. Each one will execute the SQL differently, and there's no telling which one will be optimized.
A: I had a situation similar to this and this was the solution I resorted to:
Select *
FROM t1
INNER JOIN t2 ON t1.id = t2.id AND t1.country = t2.country AND t1.country = 'US'
I noticed that my query ran faster in this scenario. I made the assumption that joining on the constant saved the engine time because the WHERE clause will execute at the end. Joining and then filtering by 'US' means you still pulled all the other countries from your table and then had to filter out the ones you wanted. This method pulls less records in the end, because it will only find US records.
A: I'd lean towards only including your constant in the code once. There might be a performance advantage one way or the other, but it's probably so small the maintenance advantage of only one parameter trumps it.
A: If you ever wish to make the query more general, perhaps substituting a parameter for the target country, then I'd go with your first example, as it requires only a single change. That's less to worry about getting wrong in the future.
A: I suspect this is going to depend on the tables, the data and the meta-data. I expect I could work up examples that would show results both ways - benchmark!
A: The extressions should be equivalent with any decent optimizer, but it depends on which database you're using and what indexes are defined on your table.
I would suggest using the EXPLAIN feature to figure out which of expressions is the most optimal.
A: I think a better SQL would be:
select * from t1, t2 where t1.id=t2.id
and t1.country ='US'
There's no need to use the second comparison to 'US' unless it's possisble that the country in t2 could be different than t1 for the same id.
A: Rather than use an implicit inner join, I would explicitly join the tables.
Since you want both the id fields and country fields to be the same, and you mentioned that both are indexed (I'm presuming in the same index), I would include both columns in the join so you can make use of an index seek instead of a scan. Finally, add your where clause.
SELECT *
FROM t1
JOIN t2 ON t1.id = t2.id AND t1.country = t2.country
WHERE t1.country = 'US'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Can a SVN repository include/link-to an external git repository? I have a svn repository, R, that depends on a library, l, in another repository.
The goal is that when someone checks out R, they also check out l. We want l to still be in its own repository so that l can be updated without dependence on R.
I don't know much about external svn links, but I believe that when depending on a svn-based library one can link to it externally, 'ext'.
If l is in a git repository, can I do something similar? I'd like to preserve the goal stated above.
A: svn:externals is the way svn can be made to check out sources from more than one repository into one working copy. But it is only meant for dealing with svn repositories - it doesn't know how to check out a git repository.
You might be able to do it the other way 'round, by including an svn repository inside a git repository, using something like 'git svn'.
A: I suggest using a script wrapper for svn co.
#!/bin/sh
svn co path://server/R svn-R
git clone path://server/l git-l
Or similar.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How do I get TextMate style quotes in Emacs? In textmate, when there's a current selection, I hit the " key and the selection gets surrounded by quotes. The same thing happens with other balanced characters like (, {, [ and '.
Am I missing something obvious in Emacs configuration that would enable similar behaviour when using transient mark mode, or do I need to break out elisp and write something?
A: wrap-region.el from this guy's blog post will do what you're looking for.
Paredit will complete the TextMate-style quoting. When you type one part of a matched pair (quotes, brackets, parentheses, etc), the second will be inserted and the insertion point is moved between them, much like TextMate.
A: Try http://autopair.googlecode.com
A: You should check out these older, very similar, questions:
Automatically closing braces in Emacs?
Emacs typeover skeleton-pair-insert-maybe
Although the correct answer is Joao's above; I'm about to go and change my answer to those questions, to point to autopair.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How do you detect Credit card type based on number? I'm trying to figure out how to detect the type of credit card based purely on its number. Does anyone know of a definitive, reliable way to find this?
A: In javascript:
function detectCardType(number) {
var re = {
electron: /^(4026|417500|4405|4508|4844|4913|4917)\d+$/,
maestro: /^(5018|5020|5038|5612|5893|6304|6759|6761|6762|6763|0604|6390)\d+$/,
dankort: /^(5019)\d+$/,
interpayment: /^(636)\d+$/,
unionpay: /^(62|88)\d+$/,
visa: /^4[0-9]{12}(?:[0-9]{3})?$/,
mastercard: /^5[1-5][0-9]{14}$/,
amex: /^3[47][0-9]{13}$/,
diners: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,
discover: /^6(?:011|5[0-9]{2})[0-9]{12}$/,
jcb: /^(?:2131|1800|35\d{3})\d{11}$/
}
for(var key in re) {
if(re[key].test(number)) {
return key
}
}
}
Unit test:
describe('CreditCard', function() {
describe('#detectCardType', function() {
var cards = {
'8800000000000000': 'UNIONPAY',
'4026000000000000': 'ELECTRON',
'4175000000000000': 'ELECTRON',
'4405000000000000': 'ELECTRON',
'4508000000000000': 'ELECTRON',
'4844000000000000': 'ELECTRON',
'4913000000000000': 'ELECTRON',
'4917000000000000': 'ELECTRON',
'5019000000000000': 'DANKORT',
'5018000000000000': 'MAESTRO',
'5020000000000000': 'MAESTRO',
'5038000000000000': 'MAESTRO',
'5612000000000000': 'MAESTRO',
'5893000000000000': 'MAESTRO',
'6304000000000000': 'MAESTRO',
'6759000000000000': 'MAESTRO',
'6761000000000000': 'MAESTRO',
'6762000000000000': 'MAESTRO',
'6763000000000000': 'MAESTRO',
'0604000000000000': 'MAESTRO',
'6390000000000000': 'MAESTRO',
'3528000000000000': 'JCB',
'3589000000000000': 'JCB',
'3529000000000000': 'JCB',
'6360000000000000': 'INTERPAYMENT',
'4916338506082832': 'VISA',
'4556015886206505': 'VISA',
'4539048040151731': 'VISA',
'4024007198964305': 'VISA',
'4716175187624512': 'VISA',
'5280934283171080': 'MASTERCARD',
'5456060454627409': 'MASTERCARD',
'5331113404316994': 'MASTERCARD',
'5259474113320034': 'MASTERCARD',
'5442179619690834': 'MASTERCARD',
'6011894492395579': 'DISCOVER',
'6011388644154687': 'DISCOVER',
'6011880085013612': 'DISCOVER',
'6011652795433988': 'DISCOVER',
'6011375973328347': 'DISCOVER',
'345936346788903': 'AMEX',
'377669501013152': 'AMEX',
'373083634595479': 'AMEX',
'370710819865268': 'AMEX',
'371095063560404': 'AMEX'
};
Object.keys(cards).forEach(function(number) {
it('should detect card ' + number + ' as ' + cards[number], function() {
Basket.detectCardType(number).should.equal(cards[number]);
});
});
});
});
A: The credit/debit card number is referred to as a PAN, or Primary Account Number. The first six digits of the PAN are taken from the IIN, or Issuer Identification Number, belonging to the issuing bank (IINs were previously known as BIN — Bank Identification Numbers — so you may see references to that terminology in some documents). These six digits are subject to an international standard, ISO/IEC 7812, and can be used to determine the type of card from the number.
Unfortunately the actual ISO/IEC 7812 database is not publicly available, however, there are unofficial lists, both commercial and free, including on Wikipedia.
Anyway, to detect the type from the number, you can use a regular expression like the ones below: Credit for original expressions
Visa: ^4[0-9]{6,}$ Visa card numbers start with a 4.
MasterCard: ^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$ Before 2016, MasterCard numbers start with the numbers 51 through 55, but this will only detect MasterCard credit cards; there are other cards issued using the MasterCard system that do not fall into this IIN range. In 2016, they will add numbers in the range (222100-272099).
American Express: ^3[47][0-9]{5,}$ American Express card numbers start with 34 or 37.
Diners Club: ^3(?:0[0-5]|[68][0-9])[0-9]{4,}$ Diners Club card numbers begin with 300 through 305, 36 or 38. There are Diners Club cards that begin with 5 and have 16 digits. These are a joint venture between Diners Club and MasterCard and should be processed like a MasterCard.
Discover: ^6(?:011|5[0-9]{2})[0-9]{3,}$ Discover card numbers begin with 6011 or 65.
JCB: ^(?:2131|1800|35[0-9]{3})[0-9]{3,}$ JCB cards begin with 2131, 1800 or 35.
Unfortunately, there are a number of card types processed with the MasterCard system that do not live in MasterCard’s IIN range (numbers starting 51...55); the most important case is that of Maestro cards, many of which have been issued from other banks’ IIN ranges and so are located all over the number space. As a result, it may be best to assume that any card that is not of some other type you accept must be a MasterCard.
Important: card numbers do vary in length; for instance, Visa has in the past issued cards with 13 digit PANs and cards with 16 digit PANs. Visa’s documentation currently indicates that it may issue or may have issued numbers with between 12 and 19 digits. Therefore, you should not check the length of the card number, other than to verify that it has at least 7 digits (for a complete IIN plus one check digit, which should match the value predicted by the Luhn algorithm).
One further hint: before processing a cardholder PAN, strip any whitespace and punctuation characters from the input. Why? Because it’s typically much easier to enter the digits in groups, similar to how they’re displayed on the front of an actual credit card, i.e.
4444 4444 4444 4444
is much easier to enter correctly than
4444444444444444
There’s really no benefit in chastising the user because they’ve entered characters you don't expect here.
This also implies making sure that your entry fields have room for at least 24 characters, otherwise users who enter spaces will run out of room. I’d recommend that you make the field wide enough to display 32 characters and allow up to 64; that gives plenty of headroom for expansion.
Here's an image that gives a little more insight:
UPDATE (2016): Mastercard is to implement new BIN ranges starting Ach Payment.
A: Here is a php class function returns CCtype by CCnumber.
This code not validates the card or not runs Luhn algorithm only try to find credit card type based on table in this page. basicly uses CCnumber length and CCcard prefix to determine CCcard type.
<?php
class CreditcardType
{
public static $creditcardTypes = [
[
'Name' => 'American Express',
'cardLength' => [15],
'cardPrefix' => ['34', '37'],
], [
'Name' => 'Maestro',
'cardLength' => [12, 13, 14, 15, 16, 17, 18, 19],
'cardPrefix' => ['5018', '5020', '5038', '6304', '6759', '6761', '6763'],
], [
'Name' => 'Mastercard',
'cardLength' => [16],
'cardPrefix' => ['51', '52', '53', '54', '55'],
], [
'Name' => 'Visa',
'cardLength' => [13, 16],
'cardPrefix' => ['4'],
], [
'Name' => 'JCB',
'cardLength' => [16],
'cardPrefix' => ['3528', '3529', '353', '354', '355', '356', '357', '358'],
], [
'Name' => 'Discover',
'cardLength' => [16],
'cardPrefix' => ['6011', '622126', '622127', '622128', '622129', '62213','62214', '62215', '62216', '62217', '62218', '62219','6222', '6223', '6224', '6225', '6226', '6227', '6228','62290', '62291', '622920', '622921', '622922', '622923','622924', '622925', '644', '645', '646', '647', '648','649', '65'],
], [
'Name' => 'Solo',
'cardLength' => [16, 18, 19],
'cardPrefix' => ['6334', '6767'],
], [
'Name' => 'Unionpay',
'cardLength' => [16, 17, 18, 19],
'cardPrefix' => ['622126', '622127', '622128', '622129', '62213', '62214','62215', '62216', '62217', '62218', '62219', '6222', '6223','6224', '6225', '6226', '6227', '6228', '62290', '62291','622920', '622921', '622922', '622923', '622924', '622925'],
], [
'Name' => 'Diners Club',
'cardLength' => [14],
'cardPrefix' => ['300', '301', '302', '303', '304', '305', '36'],
], [
'Name' => 'Diners Club US',
'cardLength' => [16],
'cardPrefix' => ['54', '55'],
], [
'Name' => 'Diners Club Carte Blanche',
'cardLength' => [14],
'cardPrefix' => ['300', '305'],
], [
'Name' => 'Laser',
'cardLength' => [16, 17, 18, 19],
'cardPrefix' => ['6304', '6706', '6771', '6709'],
],
];
public static function getType($CCNumber)
{
$CCNumber = trim($CCNumber);
$type = 'Unknown';
foreach (CreditcardType::$creditcardTypes as $card) {
if (! in_array(strlen($CCNumber), $card['cardLength'])) {
continue;
}
$prefixes = '/^(' . implode('|', $card['cardPrefix']) . ')/';
if (preg_match($prefixes, $CCNumber) == 1) {
$type = $card['Name'];
break;
}
}
return $type;
}
}
A: Compact javascript version
var getCardType = function (number) {
var cards = {
visa: /^4[0-9]{12}(?:[0-9]{3})?$/,
mastercard: /^5[1-5][0-9]{14}$/,
amex: /^3[47][0-9]{13}$/,
diners: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,
discover: /^6(?:011|5[0-9]{2})[0-9]{12}$/,
jcb: /^(?:2131|1800|35\d{3})\d{11}$/
};
for (var card in cards) {
if (cards[card].test(number)) {
return card;
}
}
};
A: Anatoliy's answer in PHP:
public static function detectCardType($num)
{
$re = array(
"visa" => "/^4[0-9]{12}(?:[0-9]{3})?$/",
"mastercard" => "/^5[1-5][0-9]{14}$/",
"amex" => "/^3[47][0-9]{13}$/",
"discover" => "/^6(?:011|5[0-9]{2})[0-9]{12}$/",
);
if (preg_match($re['visa'],$num))
{
return 'visa';
}
else if (preg_match($re['mastercard'],$num))
{
return 'mastercard';
}
else if (preg_match($re['amex'],$num))
{
return 'amex';
}
else if (preg_match($re['discover'],$num))
{
return 'discover';
}
else
{
return false;
}
}
A: The first numbers of the credit card can be used to approximate the vendor:
*
*Visa: 49,44 or 47
*Visa electron: 42, 45, 48, 49
*MasterCard: 51
*Amex:34
*Diners: 30, 36, 38
*JCB: 35
A: In Card Range Recognition (CRR), a drawback with algorithms that use a series of regex or other hard-coded ranges, is that the BINs/IINs do change over time in my experience. The co-branding of cards is an ongoing complication. Different Card Acquirers / merchants may need you treat the same card differently, depending on e.g. geolocation.
Additionally, in the last few years with e.g. UnionPay cards in wider circulation, existing models do not cope with new ranges that sometimes interleave with broader ranges that they supersede.
Knowing the geography your system needs to cover may help, as some ranges are restricted to use in particular countries. For example, ranges 62 include some AAA sub-ranges in the US, but if your merchant base is outside the US, you may be able to treat all 62 as UnionPay.
You may be also asked to treat a card differently based on merchant location. E.g. to treat certain UK cards as debit domestically, but as credit internationally.
There are very useful set of rules maintained by one major Acquiring Bank. E.g. https://www.barclaycard.co.uk/business/files/BIN-Rules-EIRE.pdf and https://www.barclaycard.co.uk/business/files/BIN-Rules-UK.pdf. (Valid links as of June 2017, thanks to the user who provided a link to updated reference.) But be aware of the caveat that, while these CRR rules may represent the Card Issuing universe as it applies to the merchants acquired by that entity, it does not include e.g. ranges identified as CUP/UPI.
These comments apply to magnetic stripe (MagStripe) or PKE (Pan Key Entry) scenarios. The situation is different again in the ICC/EMV world.
Update: Other answers on this page (and also the linked WikiPedia page) have JCB as always 16 long. However, in my company we have a dedicated team of engineers who certify our POS devices and software across multiple acquiring banks and geographies. The most recent Certification Pack of cards this team have from JCB, had a pass case for a 19 long PAN.
A: Do not try to detect credit card type as part of processing a payment. You are risking of declining valid transactions.
If you need to provide information to your payment processor (e.g. PayPal credit card object requires to name the card type), then guess it from the least information available, e.g.
$credit_card['pan'] = preg_replace('/[^0-9]/', '', $credit_card['pan']);
$inn = (int) mb_substr($credit_card['pan'], 0, 2);
// @see http://en.wikipedia.org/wiki/List_of_Bank_Identification_Numbers#Overview
if ($inn >= 40 && $inn <= 49) {
$type = 'visa';
} else if ($inn >= 51 && $inn <= 55) {
$type = 'mastercard';
} else if ($inn >= 60 && $inn <= 65) {
$type = 'discover';
} else if ($inn >= 34 && $inn <= 37) {
$type = 'amex';
} else {
throw new \UnexpectedValueException('Unsupported card type.');
}
This implementation (using only the first two digits) is enough to identify all of the major (and in PayPal's case all of the supported) card schemes. In fact, you might want to skip the exception altogether and default to the most popular card type. Let the payment gateway/processor tell you if there is a validation error in response to your request.
The reality is that your payment gateway does not care about the value you provide.
A: Updated: 15th June 2016 (as an ultimate solution currently)
Please note that I even give vote up for the one is top voted, but to make it clear these are the regexps actually works i tested it with thousands of real BIN codes. The most important is to use start strings (^) otherwise it will give false results in real world!
JCB ^(?:2131|1800|35)[0-9]{0,}$ Start with: 2131, 1800, 35 (3528-3589)
American Express ^3[47][0-9]{0,}$ Start with: 34, 37
Diners Club ^3(?:0[0-59]{1}|[689])[0-9]{0,}$ Start with: 300-305, 309, 36, 38-39
Visa ^4[0-9]{0,}$ Start with: 4
MasterCard ^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$ Start with: 2221-2720, 51-55
Maestro ^(5[06789]|6)[0-9]{0,}$ Maestro always growing in the range: 60-69, started with / not something else, but starting 5 must be encoded as mastercard anyway. Maestro cards must be detected in the end of the code because some others has in the range of 60-69. Please look at the code.
Discover ^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$ Discover quite difficult to code, start with: 6011, 622126-622925, 644-649, 65
In javascript I use this function. This is good when u assign it to an onkeyup event and it give result as soon as possible.
function cc_brand_id(cur_val) {
// the regular expressions check for possible matches as you type, hence the OR operators based on the number of chars
// regexp string length {0} provided for soonest detection of beginning of the card numbers this way it could be used for BIN CODE detection also
//JCB
jcb_regex = new RegExp('^(?:2131|1800|35)[0-9]{0,}$'); //2131, 1800, 35 (3528-3589)
// American Express
amex_regex = new RegExp('^3[47][0-9]{0,}$'); //34, 37
// Diners Club
diners_regex = new RegExp('^3(?:0[0-59]{1}|[689])[0-9]{0,}$'); //300-305, 309, 36, 38-39
// Visa
visa_regex = new RegExp('^4[0-9]{0,}$'); //4
// MasterCard
mastercard_regex = new RegExp('^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$'); //2221-2720, 51-55
maestro_regex = new RegExp('^(5[06789]|6)[0-9]{0,}$'); //always growing in the range: 60-69, started with / not something else, but starting 5 must be encoded as mastercard anyway
//Discover
discover_regex = new RegExp('^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$');
////6011, 622126-622925, 644-649, 65
// get rid of anything but numbers
cur_val = cur_val.replace(/\D/g, '');
// checks per each, as their could be multiple hits
//fix: ordering matter in detection, otherwise can give false results in rare cases
var sel_brand = "unknown";
if (cur_val.match(jcb_regex)) {
sel_brand = "jcb";
} else if (cur_val.match(amex_regex)) {
sel_brand = "amex";
} else if (cur_val.match(diners_regex)) {
sel_brand = "diners_club";
} else if (cur_val.match(visa_regex)) {
sel_brand = "visa";
} else if (cur_val.match(mastercard_regex)) {
sel_brand = "mastercard";
} else if (cur_val.match(discover_regex)) {
sel_brand = "discover";
} else if (cur_val.match(maestro_regex)) {
if (cur_val[0] == '5') { //started 5 must be mastercard
sel_brand = "mastercard";
} else {
sel_brand = "maestro"; //maestro is all 60-69 which is not something else, thats why this condition in the end
}
}
return sel_brand;
}
Here you can play with it:
http://jsfiddle.net/upN3L/69/
For PHP use this function, this detects some sub VISA/MC cards too:
/**
* Obtain a brand constant from a PAN
*
* @param string $pan Credit card number
* @param bool $include_sub_types Include detection of sub visa brands
* @return string
*/
public static function getCardBrand($pan, $include_sub_types = false)
{
//maximum length is not fixed now, there are growing number of CCs has more numbers in length, limiting can give false negatives atm
//these regexps accept not whole cc numbers too
//visa
$visa_regex = "/^4[0-9]{0,}$/";
$vpreca_regex = "/^428485[0-9]{0,}$/";
$postepay_regex = "/^(402360|402361|403035|417631|529948){0,}$/";
$cartasi_regex = "/^(432917|432930|453998)[0-9]{0,}$/";
$entropay_regex = "/^(406742|410162|431380|459061|533844|522093)[0-9]{0,}$/";
$o2money_regex = "/^(422793|475743)[0-9]{0,}$/";
// MasterCard
$mastercard_regex = "/^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$/";
$maestro_regex = "/^(5[06789]|6)[0-9]{0,}$/";
$kukuruza_regex = "/^525477[0-9]{0,}$/";
$yunacard_regex = "/^541275[0-9]{0,}$/";
// American Express
$amex_regex = "/^3[47][0-9]{0,}$/";
// Diners Club
$diners_regex = "/^3(?:0[0-59]{1}|[689])[0-9]{0,}$/";
//Discover
$discover_regex = "/^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$/";
//JCB
$jcb_regex = "/^(?:2131|1800|35)[0-9]{0,}$/";
//ordering matter in detection, otherwise can give false results in rare cases
if (preg_match($jcb_regex, $pan)) {
return "jcb";
}
if (preg_match($amex_regex, $pan)) {
return "amex";
}
if (preg_match($diners_regex, $pan)) {
return "diners_club";
}
//sub visa/mastercard cards
if ($include_sub_types) {
if (preg_match($vpreca_regex, $pan)) {
return "v-preca";
}
if (preg_match($postepay_regex, $pan)) {
return "postepay";
}
if (preg_match($cartasi_regex, $pan)) {
return "cartasi";
}
if (preg_match($entropay_regex, $pan)) {
return "entropay";
}
if (preg_match($o2money_regex, $pan)) {
return "o2money";
}
if (preg_match($kukuruza_regex, $pan)) {
return "kukuruza";
}
if (preg_match($yunacard_regex, $pan)) {
return "yunacard";
}
}
if (preg_match($visa_regex, $pan)) {
return "visa";
}
if (preg_match($mastercard_regex, $pan)) {
return "mastercard";
}
if (preg_match($discover_regex, $pan)) {
return "discover";
}
if (preg_match($maestro_regex, $pan)) {
if ($pan[0] == '5') { //started 5 must be mastercard
return "mastercard";
}
return "maestro"; //maestro is all 60-69 which is not something else, thats why this condition in the end
}
return "unknown"; //unknown for this system
}
A: Swift 2.1 Version of Usman Y's answer.
Use a print statement to verify so call by some string value
print(self.validateCardType(self.creditCardField.text!))
func validateCardType(testCard: String) -> String {
let regVisa = "^4[0-9]{12}(?:[0-9]{3})?$"
let regMaster = "^5[1-5][0-9]{14}$"
let regExpress = "^3[47][0-9]{13}$"
let regDiners = "^3(?:0[0-5]|[68][0-9])[0-9]{11}$"
let regDiscover = "^6(?:011|5[0-9]{2})[0-9]{12}$"
let regJCB = "^(?:2131|1800|35\\d{3})\\d{11}$"
let regVisaTest = NSPredicate(format: "SELF MATCHES %@", regVisa)
let regMasterTest = NSPredicate(format: "SELF MATCHES %@", regMaster)
let regExpressTest = NSPredicate(format: "SELF MATCHES %@", regExpress)
let regDinersTest = NSPredicate(format: "SELF MATCHES %@", regDiners)
let regDiscoverTest = NSPredicate(format: "SELF MATCHES %@", regDiscover)
let regJCBTest = NSPredicate(format: "SELF MATCHES %@", regJCB)
if regVisaTest.evaluateWithObject(testCard){
return "Visa"
}
else if regMasterTest.evaluateWithObject(testCard){
return "MasterCard"
}
else if regExpressTest.evaluateWithObject(testCard){
return "American Express"
}
else if regDinersTest.evaluateWithObject(testCard){
return "Diners Club"
}
else if regDiscoverTest.evaluateWithObject(testCard){
return "Discover"
}
else if regJCBTest.evaluateWithObject(testCard){
return "JCB"
}
return ""
}
A: Stripe has provided this fantastic javascript library for card scheme detection. Let me add few code snippets and show you how to use it.
Firstly Include it to your web page as
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.payment/1.2.3/jquery.payment.js " ></script>
Secondly use the function cardType for detecting the card scheme.
$(document).ready(function() {
var type = $.payment.cardType("4242 4242 4242 4242"); //test card number
console.log(type);
});
Here are the reference links for more examples and demos.
*
*Stripe blog for jquery.payment.js
*Github repository
A: In swift you can create an enum to detect the credit card type.
enum CreditCardType: Int { // Enum which encapsulates different card types and method to find the type of card.
case Visa
case Master
case Amex
case Discover
func validationRegex() -> String {
var regex = ""
switch self {
case .Visa:
regex = "^4[0-9]{6,}$"
case .Master:
regex = "^5[1-5][0-9]{5,}$"
case .Amex:
regex = "^3[47][0-9]{13}$"
case .Discover:
regex = "^6(?:011|5[0-9]{2})[0-9]{12}$"
}
return regex
}
func validate(cardNumber: String) -> Bool {
let predicate = NSPredicate(format: "SELF MATCHES %@", validationRegex())
return predicate.evaluateWithObject(cardNumber)
}
// Method returns the credit card type for given card number
static func cardTypeForCreditCardNumber(cardNumber: String) -> CreditCardType? {
var creditCardType: CreditCardType?
var index = 0
while let cardType = CreditCardType(rawValue: index) {
if cardType.validate(cardNumber) {
creditCardType = cardType
break
} else {
index++
}
}
return creditCardType
}
}
Call the method CreditCardType.cardTypeForCreditCardNumber("#card number") which returns CreditCardType enum value.
A: My solution with jQuery:
function detectCreditCardType() {
var type = new Array;
type[1] = '^4[0-9]{12}(?:[0-9]{3})?$'; // visa
type[2] = '^5[1-5][0-9]{14}$'; // mastercard
type[3] = '^6(?:011|5[0-9]{2})[0-9]{12}$'; // discover
type[4] = '^3[47][0-9]{13}$'; // amex
var ccnum = $('.creditcard').val().replace(/[^\d.]/g, '');
var returntype = 0;
$.each(type, function(idx, re) {
var regex = new RegExp(re);
if(regex.test(ccnum) && idx>0) {
returntype = idx;
}
});
return returntype;
}
In case 0 is returned, credit card type is undetected.
"creditcard" class should be added to the credit card input field.
A: I searched around quite a bit for credit card formatting and phone number formatting. Found lots of good tips but nothing really suited my exact desires so I created this bit of code. You use it like this:
var sf = smartForm.formatCC(myInputString);
var cardType = sf.cardType;
A: A javascript improve of @Anatoliy answer
function getCardType (number) {
const numberFormated = number.replace(/\D/g, '')
var patterns = {
VISA: /^4[0-9]{12}(?:[0-9]{3})?$/,
MASTER: /^5[1-5][0-9]{14}$/,
AMEX: /^3[47][0-9]{13}$/,
ELO: /^((((636368)|(438935)|(504175)|(451416)|(636297))\d{0,10})|((5067)|(4576)|(4011))\d{0,12})$/,
AURA: /^(5078\d{2})(\d{2})(\d{11})$/,
JCB: /^(?:2131|1800|35\d{3})\d{11}$/,
DINERS: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,
DISCOVERY: /^6(?:011|5[0-9]{2})[0-9]{12}$/,
HIPERCARD: /^(606282\d{10}(\d{3})?)|(3841\d{15})$/,
ELECTRON: /^(4026|417500|4405|4508|4844|4913|4917)\d+$/,
MAESTRO: /^(5018|5020|5038|5612|5893|6304|6759|6761|6762|6763|0604|6390)\d+$/,
DANKORT: /^(5019)\d+$/,
INTERPAYMENT: /^(636)\d+$/,
UNIONPAY: /^(62|88)\d+$/,
}
for (var key in patterns) {
if (patterns[key].test(numberFormated)) {
return key
}
}
}
console.log(getCardType("4539 5684 7526 2091"))
A:
Swift 5+
extension String {
func isMatch(_ Regex: String) -> Bool {
do {
let regex = try NSRegularExpression(pattern: Regex)
let results = regex.matches(in: self, range: NSRange(self.startIndex..., in: self))
return results.map {
String(self[Range($0.range, in: self)!])
}.count > 0
} catch {
return false
}
}
func getCreditCardType() -> String? {
let VISA_Regex = "^4[0-9]{6,}$"
let MasterCard_Regex = "^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$"
let AmericanExpress_Regex = "^3[47][0-9]{5,}$"
let DinersClub_Regex = "^3(?:0[0-5]|[68][0-9])[0-9]{4,}$"
let Discover_Regex = "^6(?:011|5[0-9]{2})[0-9]{3,}$"
let JCB_Regex = "^(?:2131|1800|35[0-9]{3})[0-9]{3,}$"
if self.isMatch(VISA_Regex) {
return "VISA"
} else if self.isMatch(MasterCard_Regex) {
return "MasterCard"
} else if self.isMatch(AmericanExpress_Regex) {
return "AmericanExpress"
} else if self.isMatch(DinersClub_Regex) {
return "DinersClub"
} else if self.isMatch(Discover_Regex) {
return "Discover"
} else if self.isMatch(JCB_Regex) {
return "JCB"
} else {
return nil
}
}
}
Use.
"1234123412341234".getCreditCardType()
A: public string GetCreditCardType(string CreditCardNumber)
{
Regex regVisa = new Regex("^4[0-9]{12}(?:[0-9]{3})?$");
Regex regMaster = new Regex("^5[1-5][0-9]{14}$");
Regex regExpress = new Regex("^3[47][0-9]{13}$");
Regex regDiners = new Regex("^3(?:0[0-5]|[68][0-9])[0-9]{11}$");
Regex regDiscover = new Regex("^6(?:011|5[0-9]{2})[0-9]{12}$");
Regex regJCB = new Regex("^(?:2131|1800|35\\d{3})\\d{11}$");
if (regVisa.IsMatch(CreditCardNumber))
return "VISA";
else if (regMaster.IsMatch(CreditCardNumber))
return "MASTER";
else if (regExpress.IsMatch(CreditCardNumber))
return "AEXPRESS";
else if (regDiners.IsMatch(CreditCardNumber))
return "DINERS";
else if (regDiscover.IsMatch(CreditCardNumber))
return "DISCOVERS";
else if (regJCB.IsMatch(CreditCardNumber))
return "JCB";
else
return "invalid";
}
Here is the function to check Credit card type using Regex , c#
A: Check this out:
http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CC70060A01B
function isValidCreditCard(type, ccnum) {
/* Visa: length 16, prefix 4, dashes optional.
Mastercard: length 16, prefix 51-55, dashes optional.
Discover: length 16, prefix 6011, dashes optional.
American Express: length 15, prefix 34 or 37.
Diners: length 14, prefix 30, 36, or 38. */
var re = new Regex({
"visa": "/^4\d{3}-?\d{4}-?\d{4}-?\d",
"mc": "/^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/",
"disc": "/^6011-?\d{4}-?\d{4}-?\d{4}$/",
"amex": "/^3[47]\d{13}$/",
"diners": "/^3[068]\d{12}$/"
}[type.toLowerCase()])
if (!re.test(ccnum)) return false;
// Remove all dashes for the checksum checks to eliminate negative numbers
ccnum = ccnum.split("-").join("");
// Checksum ("Mod 10")
// Add even digits in even length strings or odd digits in odd length strings.
var checksum = 0;
for (var i = (2 - (ccnum.length % 2)); i <= ccnum.length; i += 2) {
checksum += parseInt(ccnum.charAt(i - 1));
}
// Analyze odd digits in even length strings or even digits in odd length strings.
for (var i = (ccnum.length % 2) + 1; i < ccnum.length; i += 2) {
var digit = parseInt(ccnum.charAt(i - 1)) * 2;
if (digit < 10) { checksum += digit; } else { checksum += (digit - 9); }
}
if ((checksum % 10) == 0) return true;
else return false;
}
A: // abobjects.com, parvez ahmad ab bulk mailer
use below script
function isValidCreditCard2(type, ccnum) {
if (type == "Visa") {
// Visa: length 16, prefix 4, dashes optional.
var re = /^4\d{3}?\d{4}?\d{4}?\d{4}$/;
} else if (type == "MasterCard") {
// Mastercard: length 16, prefix 51-55, dashes optional.
var re = /^5[1-5]\d{2}?\d{4}?\d{4}?\d{4}$/;
} else if (type == "Discover") {
// Discover: length 16, prefix 6011, dashes optional.
var re = /^6011?\d{4}?\d{4}?\d{4}$/;
} else if (type == "AmEx") {
// American Express: length 15, prefix 34 or 37.
var re = /^3[4,7]\d{13}$/;
} else if (type == "Diners") {
// Diners: length 14, prefix 30, 36, or 38.
var re = /^3[0,6,8]\d{12}$/;
}
if (!re.test(ccnum)) return false;
return true;
/*
// Remove all dashes for the checksum checks to eliminate negative numbers
ccnum = ccnum.split("-").join("");
// Checksum ("Mod 10")
// Add even digits in even length strings or odd digits in odd length strings.
var checksum = 0;
for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
checksum += parseInt(ccnum.charAt(i-1));
}
// Analyze odd digits in even length strings or even digits in odd length strings.
for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
var digit = parseInt(ccnum.charAt(i-1)) * 2;
if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
}
if ((checksum % 10) == 0) return true; else return false;
*/
}
jQuery.validator.addMethod("isValidCreditCard", function(postalcode, element) {
return isValidCreditCard2($("#cardType").val(), $("#cardNum").val());
}, "<br>credit card is invalid");
Type</td>
<td class="text"> <form:select path="cardType" cssclass="fields" style="border: 1px solid #D5D5D5;padding: 0px 0px 0px 0px;width: 130px;height: 22px;">
<option value="SELECT">SELECT</option>
<option value="MasterCard">Mastercard</option>
<option value="Visa">Visa</option>
<option value="AmEx">American Express</option>
<option value="Discover">Discover</option>
</form:select> <font color="#FF0000">*</font>
$("#signupForm").validate({
rules:{
companyName:{required: true},
address1:{required: true},
city:{required: true},
state:{required: true},
zip:{required: true},
country:{required: true},
chkAgree:{required: true},
confPassword:{required: true},
lastName:{required: true},
firstName:{required: true},
ccAddress1:{required: true},
ccZip:{
postalcode : true
},
phone:{required: true},
email:{
required: true,
email: true
},
userName:{
required: true,
minlength: 6
},
password:{
required: true,
minlength: 6
},
cardNum:{
isValidCreditCard : true
},
A: Just a little spoon feeding:
$("#CreditCardNumber").focusout(function () {
var regVisa = /^4[0-9]{12}(?:[0-9]{3})?$/;
var regMasterCard = /^5[1-5][0-9]{14}$/;
var regAmex = /^3[47][0-9]{13}$/;
var regDiscover = /^6(?:011|5[0-9]{2})[0-9]{12}$/;
if (regVisa.test($(this).val())) {
$("#CCImage").html("<img height='40px' src='@Url.Content("~/images/visa.png")'>");
}
else if (regMasterCard.test($(this).val())) {
$("#CCImage").html("<img height='40px' src='@Url.Content("~/images/mastercard.png")'>");
}
else if (regAmex.test($(this).val())) {
$("#CCImage").html("<img height='40px' src='@Url.Content("~/images/amex.png")'>");
}
else if (regDiscover.test($(this).val())) {
$("#CCImage").html("<img height='40px' src='@Url.Content("~/images/discover.png")'>");
}
else {
$("#CCImage").html("NA");
}
});
A: Here is an example of some boolean functions written in Python that return True if the card is detected as per the function name.
def is_american_express(cc_number):
"""Checks if the card is an american express. If us billing address country code, & is_amex, use vpos
https://en.wikipedia.org/wiki/Bank_card_number#cite_note-GenCardFeatures-3
:param cc_number: unicode card number
"""
return bool(re.match(r'^3[47][0-9]{13}$', cc_number))
def is_visa(cc_number):
"""Checks if the card is a visa, begins with 4 and 12 or 15 additional digits.
:param cc_number: unicode card number
"""
# Standard Visa is 13 or 16, debit can be 19
if bool(re.match(r'^4', cc_number)) and len(cc_number) in [13, 16, 19]:
return True
return False
def is_mastercard(cc_number):
"""Checks if the card is a mastercard. Begins with 51-55 or 2221-2720 and 16 in length.
:param cc_number: unicode card number
"""
if len(cc_number) == 16 and cc_number.isdigit(): # Check digit, before cast to int
return bool(re.match(r'^5[1-5]', cc_number)) or int(cc_number[:4]) in range(2221, 2721)
return False
def is_discover(cc_number):
"""Checks if the card is discover, re would be too hard to maintain. Not a supported card.
:param cc_number: unicode card number
"""
if len(cc_number) == 16:
try:
# return bool(cc_number[:4] == '6011' or cc_number[:2] == '65' or cc_number[:6] in range(622126, 622926))
return bool(cc_number[:4] == '6011' or cc_number[:2] == '65' or 622126 <= int(cc_number[:6]) <= 622925)
except ValueError:
return False
return False
def is_jcb(cc_number):
"""Checks if the card is a jcb. Not a supported card.
:param cc_number: unicode card number
"""
# return bool(re.match(r'^(?:2131|1800|35\d{3})\d{11}$', cc_number)) # wikipedia
return bool(re.match(r'^35(2[89]|[3-8][0-9])[0-9]{12}$', cc_number)) # PawelDecowski
def is_diners_club(cc_number):
"""Checks if the card is a diners club. Not a supported card.
:param cc_number: unicode card number
"""
return bool(re.match(r'^3(?:0[0-6]|[68][0-9])[0-9]{11}$', cc_number)) # 0-5 = carte blance, 6 = international
def is_laser(cc_number):
"""Checks if the card is laser. Not a supported card.
:param cc_number: unicode card number
"""
return bool(re.match(r'^(6304|670[69]|6771)', cc_number))
def is_maestro(cc_number):
"""Checks if the card is maestro. Not a supported card.
:param cc_number: unicode card number
"""
possible_lengths = [12, 13, 14, 15, 16, 17, 18, 19]
return bool(re.match(r'^(50|5[6-9]|6[0-9])', cc_number)) and len(cc_number) in possible_lengths
# Child cards
def is_visa_electron(cc_number):
"""Child of visa. Checks if the card is a visa electron. Not a supported card.
:param cc_number: unicode card number
"""
return bool(re.match(r'^(4026|417500|4508|4844|491(3|7))', cc_number)) and len(cc_number) == 16
def is_total_rewards_visa(cc_number):
"""Child of visa. Checks if the card is a Total Rewards Visa. Not a supported card.
:param cc_number: unicode card number
"""
return bool(re.match(r'^41277777[0-9]{8}$', cc_number))
def is_diners_club_carte_blanche(cc_number):
"""Child card of diners. Checks if the card is a diners club carte blance. Not a supported card.
:param cc_number: unicode card number
"""
return bool(re.match(r'^30[0-5][0-9]{11}$', cc_number)) # github PawelDecowski, jquery-creditcardvalidator
def is_diners_club_carte_international(cc_number):
"""Child card of diners. Checks if the card is a diners club international. Not a supported card.
:param cc_number: unicode card number
"""
return bool(re.match(r'^36[0-9]{12}$', cc_number)) # jquery-creditcardvalidator
A: recently I needed such functionality, I was porting Zend Framework Credit Card Validator to ruby.
ruby gem: https://github.com/Fivell/credit_card_validations
zend framework: https://github.com/zendframework/zf2/blob/master/library/Zend/Validator/CreditCard.php
They both use INN ranges for detecting type. Here you can read about INN
According to this you can detect credit card alternatively (without regexps,but declaring some rules about prefixes and possible length)
So we have next rules for most used cards
######## most used brands #########
visa: [
{length: [13, 16], prefixes: ['4']}
],
mastercard: [
{length: [16], prefixes: ['51', '52', '53', '54', '55']}
],
amex: [
{length: [15], prefixes: ['34', '37']}
],
######## other brands ########
diners: [
{length: [14], prefixes: ['300', '301', '302', '303', '304', '305', '36', '38']},
],
#There are Diners Club (North America) cards that begin with 5. These are a joint venture between Diners Club and MasterCard, and are processed like a MasterCard
# will be removed in next major version
diners_us: [
{length: [16], prefixes: ['54', '55']}
],
discover: [
{length: [16], prefixes: ['6011', '644', '645', '646', '647', '648',
'649', '65']}
],
jcb: [
{length: [16], prefixes: ['3528', '3529', '353', '354', '355', '356', '357', '358', '1800', '2131']}
],
laser: [
{length: [16, 17, 18, 19], prefixes: ['6304', '6706', '6771']}
],
solo: [
{length: [16, 18, 19], prefixes: ['6334', '6767']}
],
switch: [
{length: [16, 18, 19], prefixes: ['633110', '633312', '633304', '633303', '633301', '633300']}
],
maestro: [
{length: [12, 13, 14, 15, 16, 17, 18, 19], prefixes: ['5010', '5011', '5012', '5013', '5014', '5015', '5016', '5017', '5018',
'502', '503', '504', '505', '506', '507', '508',
'6012', '6013', '6014', '6015', '6016', '6017', '6018', '6019',
'602', '603', '604', '605', '6060',
'677', '675', '674', '673', '672', '671', '670',
'6760', '6761', '6762', '6763', '6764', '6765', '6766', '6768', '6769']}
],
# Luhn validation are skipped for union pay cards because they have unknown generation algoritm
unionpay: [
{length: [16, 17, 18, 19], prefixes: ['622', '624', '625', '626', '628'], skip_luhn: true}
],
dankrot: [
{length: [16], prefixes: ['5019']}
],
rupay: [
{length: [16], prefixes: ['6061', '6062', '6063', '6064', '6065', '6066', '6067', '6068', '6069', '607', '608'], skip_luhn: true}
]
}
Then by searching prefix and comparing length you can detect credit card brand. Also don't forget about luhn algoritm (it is descibed here http://en.wikipedia.org/wiki/Luhn).
UPDATE
updated list of rules can be found here https://raw.githubusercontent.com/Fivell/credit_card_validations/master/lib/data/brands.yaml
A: Here's Complete C# or VB code for all kinds of CC related things on codeproject.
*
*IsValidNumber
*GetCardTypeFromNumber
*GetCardTestNumber
*PassesLuhnTest
This article has been up for a couple years with no negative comments.
A:
The first six digits of a card number (including the initial MII
digit) are known as the issuer identification number (IIN). These
identify the card issuing institution that issued the card to the card
holder. The rest of the number is allocated by the card issuer. The
card number's length is its number of digits. Many card issuers print
the entire IIN and account number on their card.
Based on the above facts I would like to keep a snippet of JAVA code to identify card brand.
Sample card types
public static final String AMERICAN_EXPRESS = "American Express";
public static final String DISCOVER = "Discover";
public static final String JCB = "JCB";
public static final String DINERS_CLUB = "Diners Club";
public static final String VISA = "Visa";
public static final String MASTERCARD = "MasterCard";
public static final String UNKNOWN = "Unknown";
Card Prefixes
// Based on http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29
public static final String[] PREFIXES_AMERICAN_EXPRESS = {"34", "37"};
public static final String[] PREFIXES_DISCOVER = {"60", "62", "64", "65"};
public static final String[] PREFIXES_JCB = {"35"};
public static final String[] PREFIXES_DINERS_CLUB = {"300", "301", "302", "303", "304", "305", "309", "36", "38", "39"};
public static final String[] PREFIXES_VISA = {"4"};
public static final String[] PREFIXES_MASTERCARD = {
"2221", "2222", "2223", "2224", "2225", "2226", "2227", "2228", "2229",
"223", "224", "225", "226", "227", "228", "229",
"23", "24", "25", "26",
"270", "271", "2720",
"50", "51", "52", "53", "54", "55"
};
Check to see if the input number has any of the given prefixes.
public String getBrand(String number) {
String evaluatedType;
if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_AMERICAN_EXPRESS)) {
evaluatedType = AMERICAN_EXPRESS;
} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_DISCOVER)) {
evaluatedType = DISCOVER;
} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_JCB)) {
evaluatedType = JCB;
} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_DINERS_CLUB)) {
evaluatedType = DINERS_CLUB;
} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_VISA)) {
evaluatedType = VISA;
} else if (StripeTextUtils.hasAnyPrefix(number, PREFIXES_MASTERCARD)) {
evaluatedType = MASTERCARD;
} else {
evaluatedType = UNKNOWN;
}
return evaluatedType;
}
Finally, The Utility method
/**
* Check to see if the input number has any of the given prefixes.
*
* @param number the number to test
* @param prefixes the prefixes to test against
* @return {@code true} if number begins with any of the input prefixes
*/
public static boolean hasAnyPrefix(String number, String... prefixes) {
if (number == null) {
return false;
}
for (String prefix : prefixes) {
if (number.startsWith(prefix)) {
return true;
}
}
return false;
}
Reference
*
*Stripe Card Builder
A: Try this for kotlin. Add Regex and add to the when statement.
private fun getCardType(number: String): String {
val visa = Regex("^4[0-9]{12}(?:[0-9]{3})?$")
val mastercard = Regex("^5[1-5][0-9]{14}$")
val amx = Regex("^3[47][0-9]{13}$")
return when {
visa.matches(number) -> "Visa"
mastercard.matches(number) -> "Mastercard"
amx.matches(number) -> "American Express"
else -> "Unknown"
}
}
A: The regular expression rules that match the respective card vendors:
*
*(4\d{12}(?:\d{3})?) for VISA.
*(5[1-5]\d{14}) for MasterCard.
*(3[47]\d{13}) for AMEX.
*((?:5020|5038|6304|6579|6761)\d{12}(?:\d\d)?) for Maestro.
*(3(?:0[0-5]|[68][0-9])[0-9]{11}) for Diners Club.
*(6(?:011|5[0-9]{2})[0-9]{12}) for Discover.
*(35[2-8][89]\d\d\d{10}) for JCB.
A: follow Luhn’s algorithm
private boolean validateCreditCardNumber(String str) {
int[] ints = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
for (int i = ints.length - 2; i >= 0; i = i - 2) {
int j = ints[i];
j = j * 2;
if (j > 9) {
j = j % 10 + 1;
}
ints[i] = j;
}
int sum = 0;
for (int i = 0; i < ints.length; i++) {
sum += ints[i];
}
if (sum % 10 == 0) {
return true;
} else {
return false;
}
}
then call this method
Edittext mCreditCardNumberEt;
mCreditCardNumberEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int cardcount= s.toString().length();
if(cardcount>=16) {
boolean cardnumbervalid= validateCreditCardNumber(s.toString());
if(cardnumbervalid) {
cardvalidtesting.setText("Valid Card");
cardvalidtesting.setTextColor(ContextCompat.getColor(context,R.color.green));
}
else {
cardvalidtesting.setText("Invalid Card");
cardvalidtesting.setTextColor(ContextCompat.getColor(context,R.color.red));
}
}
else if(cardcount>0 &&cardcount<16) {
cardvalidtesting.setText("Invalid Card");
cardvalidtesting.setTextColor(ContextCompat.getColor(context,R.color.red));
}
else {
cardvalidtesting.setText("");
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
A: Another api solution at rapidapi Bank Card Bin Num Check there are 250K+ issued card type.
Only one GET rest api request and get card issuer info like:
{ "bin_number": 535177, "bank": "Finansbank A.S.", "scheme": "MASTERCARD", "type": "Debit", "country": "Turkey" }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "586"
}
|
Q: Static libraries with managed code issue Problem (simplified to make things clearer):
*
1. there is one statically-linked static.lib that has a function that increments:
extern int CallCount = 0;
int TheFunction()
{
void *p = &CallCount;
printf("Function called");
return CallCount++;
}
2. static.lib is linked into a managed C++/CLI managed.dll that wraps TheFunction method:
int Managed::CallLibFunc()
{
return TheFunction();
}
3. Test app has a reference to managed.dll and creates multiple domains that call C++/CLI wrapper:
static void Main(string[] args)
{
Managed c1 = new Managed();
int val1 = c1.CallLibFunc();
// value is zero
AppDomain ad = AppDomain.CreateDomain("NewDomain");
Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;
int val2 = c.CallLibFunc();
// value is one
}
Question:
Based on what I have read in Essential .NET Vol1 The CLR by Don Box, I would expect val2 to be zero since a brand new copy of managed.dll/static.lib is loaded when CreateInstanceAndUnwrap is called. Am I misunderstanding what is happening? The static library does not seem to be respecting the appdomain boundaries since it's unmanaged code. Is there a way to get around this issue other than by creating a brand new process for instantiating Managed?
Thank you very much everyone!
A: My hunch was that, as you suspected, unmanaged DLLs are loaded in the context of the process and not in the context of the AppDomain, so any static data in unmanaged code is shared among AppDomains.
This link shows someone with the same problem you have, still not 100% verification of this, but probably this is the case.
This link is about creating a callback from unmanaged code into an AppDomain using a thunking trick. I'm not sure this can help you but maybe you'll find this useful to create some kind of a workaround.
A: After you call
Managed c1 = new Managed();
Your managed.dll wrapper will be loaded into main app domain of you application. Till it will be there domain unmanaged stuff from static.lib will be shared with other domains.
Instead of creating separate process you just need to be sure (before each call) that managed.dll is not loaded into any application domain.
Compare with that
static void Main(string[] args)
{
{
AppDomain ad = AppDomain.CreateDomain("NewDomain");
Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;
int val2 = c.CallLibFunc();
// Value is zero
AppDomain.Unload(ad)
}
{
AppDomain ad = AppDomain.CreateDomain("NewDomain");
Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;
int val2 = c.CallLibFunc();
// I think value is zero
AppDomain.Unload(ad)
}
}
`
IMPORTANT and : If you add just one line JIT compiler will load managed.dll and the magic disappears.
static void Main(string[] args)
{
{
AppDomain ad = AppDomain.CreateDomain("NewDomain");
Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;
int val2 = c.CallLibFunc();
// Value is zero
AppDomain.Unload(ad)
}
{
AppDomain ad = AppDomain.CreateDomain("NewDomain");
Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;
int val2 = c.CallLibFunc();
// I think value is one
AppDomain.Unload(ad)
}
Managed c1 = new Managed();
}
If you don't want to depend on such lines you can create another one wrapper ManagedIsolated.dll that will reference managed.dll and will make each call in separate domain with domain unload just after the call. Main application will depend only on ManagedIsolated.dll types and Managed.dll will not be loaded into main app domain.
That looks like a trick but may be it will be usefull for somebody.
`
A: In short, maybe. AppDomains are purely a managed concept. When an AppDomain is instantiated it doesn't map in new copies of the underlying DLLs, it can reuse the code already in memory (for example, you wouldn't expect it to load up new copies of all the System.* assemblies, right?)
Within the managed world all static variables are scoped by AppDomain, but as you point out this doesn't apply in the unmanaged world.
You could do something complex that forces a load of a unique managed.dll for each app domain, which would result in a new version of the static lib being brought along for the ride. For example, maybe using Assembly.Load with a byte array would work, but I don't know how the CLR will attempt to deal with the collision in types if the same assembly is loaded twice.
A: I don't think we're getting to the actual issue here - see this DDJ article.
The default value of the loader optimization attribute is SingleDomain, which "causes the AppDomain to load a private copy of each necessary assembly's code". Even if it were one of the Multi domain values "every AppDomain always maintains a distinct copy of static fields".
'managed.dll' is (as its name implies) is a managed assembly. The code in static.lib has been statically compiled (as IL code) into 'managed.dll', so I would expect the same behaviour as Lenik expects....
... unless static.lib is a static export library for an unmanaged DLL. Lenik says this is not the case, so I'm still unsure what's going on here.
A: Have you tried running in separate processes? A static library should not share memory instances outside of it's own process.
This can be a pain to manage, I know. I'm not sure what your other options would be in this case though.
Edit: After a little looking around I think you could do everything you needed to with the System.Diagnostics.Process class. You would have a lot of options at this point for communication but .NET Remoting or WCF would probably be good and easy choices.
A: These are the best two articles I found on the subject
*
*http://blogs.msdn.com/cbrumme/archive/2003/04/15/51317.aspx
*http://blogs.msdn.com/cbrumme/archive/2003/06/01/51466.aspx
The important part is:
RVA-based static fields are process-global. These are restricted to scalars and value types, because we do not want to allow objects to bleed across AppDomain boundaries. That would cause all sorts of problems, especially during AppDomain unloads. Some languages like ILASM and MC++ make it convenient to define RVA-based static fields. Most languages do not.
Ok, so if you control the code in the .lib, I'd try
class CallCountHolder {
public:
CallCountHolder(int i) : count(i) {}
int count;
};
static CallCountHolder cc(0);
int TheFunction()
{
printf("Function called");
return cc.count++;
}
Since he said that RVA-based static fields are limited to scalars and value types. An int array might also work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Creating SharePoint 2007 list items via the Web Dav interface SharePoint 2007 (both Moss and Wss) exposes document libraries via web dav, allowing you to create documents via essentially file system level activities (e.g. saving documents to a location).
SharePoint also seems to expose lists via the same web dav interface, as directories but they are usually empty. Is it possible to create or manipulate a list item somehow via this exposure?
A: In short: No.
Longer answer: Kinda. Any item stored in sharepoint is in a list, including files. But not all lists have files. A document library is a list with each element being a file+metadata. Other lists (like announcments) are just metadata. Only lists that contain files are exposed via webdav, and even then you are limited to mucking around with the file - there is no way to use webdav (afaik) to edit the metadata.
Hope this helps.
Oisin.
A: Agreed. The only thing exposed to webdav is a list item's attachment (or a library's documents). Even if you bring up a file's properties in explorer, there's no options for list data.
If you're working with Office 2007 documents, you can create a document information panel that can be tied into sharepoint.
A: No, but in my experience most things looking to speak WebDAV to something are pretty much expecting to work with files or documents of some sort. Since non-library lists in SharePoint don't really have an associated file (yeah, they can have attachments, but that's not the same), then effectively the primary construct WebDAV is built around (document) is missing. What would you be Authoring and Versioning?
If you are writing your own client, there are robust web services for interacting with lists (both the library and non-library varieties)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Change app icon in Visual Studio 2005? I'd like to use a different icon for the demo version of my game, and I'm building the demo with a different build config than I do for the full verison, using a preprocessor define to lockout some content, use different graphics, etc. Is there a way that I can make Visual Studio use a different icon for the app Icon in the demo config but continue to use the regular icon for the full version's config?
A: According to this page you may use preprocessor directives in your *.rc file. You should write something like this
#ifdef _DEMO_VERSION_
IDR_MAINFRAME ICON "demo.ico"
#else
IDR_MAINFRAME ICON "full.ico"
#endif
A: What I would do is setup a pre-build event (Project properties -> Configuration Properties -> Build Events -> Pre-Build Event). The pre-build event is a command line. I would use this to copy the appropriate icon file to the build icon.
For example, let's say your build icon is 'app.ico'. I would make my fullicon 'app_full.ico' and my demo icon 'app_demo.ico'. Then I would set my pre-build events as follows:
Full mode pre-build event:
del app.ico | copy app_full.ico app.ico
Demo mode pre-build event:
del app.ico | copy app_demo.ico app.ico
I hope that helps!
A: This will get you halfway there: http://www.codeproject.com/KB/dotnet/embedmultipleiconsdotnet.aspx
Then you need to find the Win32 call which will set the displayed icon from the list of embedded icons.
A: I don't know a way in visual studio, because the application settings are bound to the hole project. But a simple way is to use a PreBuild event and copy the app.demo.ico to app.ico or the app.release.ico to app.ico demanding on the value of the key $(ConfigurationName) and refer to the app.ico in your project directory.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Trigger update on DataTable bound to DataGridView In my .NET/Forms app I have a DataGridView which is bound to a DataTable. The user selects a row of the DataGridView by double-clicking and does some interaction with the app. After that the content of the row is updated programmatically.
When the user selects a new row the changes on the previous one are automagically propagated to the DataTable by the framework. How can I trigger this update from my code so the user does not have to select a new row?
A: I just had the same issue, and found the answer here:
When the user navigates away from the
row, the control commits all row
changes. The user can also press
CTRL+ENTER to commit row changes
without leaving the row. To commit row
changes programmatically, call the
form's Validate method. If your data
source is a BindingSource, you can
also call BindingSource.EndEdit.
Calling Validate() worked for me.
A: I guess it depends on what triggers the update to take place, if it is in a validation routine you could simply call that after the user clicks OK on editing the data. Your question is vague it would be easier to answer with more information. What is this interaction? Is it a dialog? What actually updates the data?
A: Here is the process to clarify this:
*
*user doubleclicks row
*app fetches data from db, processes fetched data and fills controls on the same form as the DataGridView
*user interacts with controls and finally presses apply button on the same form
*app processes state of controls, writes data to db and writes data to DataGridView
*IF user moves selection on DataGridView
*THEN changes are propagated to the bound DataTable
I would like to trigger 6 instantly after modifying the DataGridView from my code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Qt or Delphi... If you were to choose one over the other? If you had a differential of either venturing into Delphi land or Qt land which would you choose? I know they are not totally comparable. I for one have Windows development experience with Builder C++ (almost Delphi) and MFC (almost Qt), with a bit more time working with Builder C++. Please take out the cross platform ability of Qt in your analysis.
I'm hoping for replies of people who have worked with both and how he or she would compare the framework, environment, etc.?
Thank you in advance for your replies.
A: It really depends on your needs and experience. I have worked with both (though have to say that the last Delphi version I really worked with was Delphi 6, and I'm currently working with Qt 4.4).
The language
C++ pros:
*
*C++ is more "standard", e.g. you will find more code, libraries, examples etc., and you may freely use the STL and boost, while Object Pascal is more of an exotic language
*Qt compiles on different platforms and compilers (Kylix is based on Qt, BTW)
Object Pascal pros:
*
*some dynamic properties are build right into the language, no ugly workarounds like the MOC are needed
*the compiler is highly optimized for the language and indeed very fast
*the language is less complex than C++ and therefore less error prone
The IDE
Qt pros:
*
*Strictly spoken, there is no IDE for Qt besides the Designer, but it integrates nicely into your preferred IDE (at least Visual Studio and Eclipse)
*the designer does a better job with layouts than Delphi forms (Note: this is based on
Delphi 6 experience and may not be true with current versions)
Delphi pros:
*
*The IDE is really polished and easy to use now, and it beats Visual Studio clearly IMO (I have no experience with Eclipse)
*there is no point 2... but if I had to assign the buzzword "integrated" I would assign it to the Delphi IDE
The framework
I will leave a comparison to others, as I don't know the newest VCL good enough. I have some remarks:
*
*both frameworks cover most of the needed functionality
*both have the source code available, which is a must IMO
*both have a more or less consistent structure - I prefer Qt, but this depends on your preferences (remark: I would never say that Qt is almost MFC - I have used MFC for a long time, and both Qt and Delphi - and .NET, for that matter - are way better)
*the VCL has more DB-oriented functionality, especially the connection with the visual components
*Qt has more painting (2D / 3D / OpenGL) oriented functionality
Other reasons that speak for Qt IMO are the very good support and the licensing, but that depends on your needs. There are large communities for both frameworks,
A: A big difference between Delphi and Qt is the Qt signal/slots system, which makes it really easy to create N-to-N relationship between objects and avoid tight coupling.
I don't think such a thing exists in Delphi (at least there was no such thing when I used to use it).
A: I just started experimenting with Qt/C++/Qt Creator and I must admit I was surprised that this "little cute bastard" was just below my nose for some many years and I pay attention to it just now.
It (the framework) looks neat, feature-complete (even was stuff that .NET lacks such as inbuld XQuery support).
Seems that most of the Qt applications written are dealing with 2D/3D/Games.
I believe the downsides are only: having to know C++ and the lack of DevExpress goodies like QuantumGrid.
I am seriously considering porting one of my simple applications (a picture viewer like ThumbsView).
And it REALLY runs from same codebase. FOR REAL!
Forget about Kylix, Mono, Lazarus, Free Pascal. This Qt thing beats them all in 10 times.
Qt Creator is far from IDE. But I hope in the future they will add a more powerfull debugger, code insight and refactoring (at least the "Rename" one) and more meaningful compiler errors.
I would seriously recommend to someone without experience in Pascal/C++ to take the Qt learning curve.
A: If you are talking UI frameworks, then you should be comparing Qt with the VCL, not the IDE (Delphi in this case). I know I'm being a stickler, but Delphi is the IDE, Object-Pascal is the language, and VCL is the graphical framework.
That being said, I don't think there is anything that even comes close to matching the power and simplicity of the VCL. Qt is great, but it is no VCL.
A: I would pick Delphi, but that is probably because I have programmed it before. It seems there are still a number of companies which use it, and almost everyone who has 8+ years expierence has encountered it somewhere. It seems that most programmers can relate to using it or at least learning Pascal. Not to mention the fact that newer languages (C#) are based on it (at least partially).
A: Pick Delphi if your concern are native Win32 speed, a first class RAD environment and executable size. Pick QT if you need a truly cross-platform framework coupled with a now-flexible licensing policy and don't mind slightly bloated code.
I ported an old Delphi program under QT/C++, and I must say that QT is the framework that comes closest to VCL in terms of ease of use and power (IMHO)
A: Edit: This answer was written in 2008. It probably is no longer so apt, though probably it is not entirely useless. Take with salt.
I have used both and have ended up going the Qt route. These are the reasons:
*
*Trolltech offer quick and one-to-one support via email
*Qt innovates, and introduces powerful new features regularly
*The Qt documentation is amazing, and in the rare cases where it isn't, you can read the source code
*Having the source code for Qt also allows you to debug inside your base libraries, which has been a life saver for me on many an occasion
*The API is very consistent and well designed. We have put new people on the project and within a month they show deep knowledge of the toolkit and can learn new classes very quickly
*It has bindings to other languages, eg. Ruby and Python.
C++ is somewhat of a downside, eg. compile times, packaging, and a less integrated IDE. However Qt does make C++ feel more like a higher level language. QStrings take all the pain out of string handling for example. Thus the additional issues with C++ that you would normally face, eg. more buggy code, are less prevalent in my experience when using Qt.
Also, there are more libraries for Delphi than for Qt, but this is mitigated due to the fact you can just use a c or c++ library in a Qt project, and also because Qt is so fully featured you often don't have to look any further.
It would be a strange situation where I would choose Delphi over Qt for a new project.
A: I would pick Delphi. Of course you ask any pascalholic and he is sure to answer just the same. ;)
Qt again is fine, but the VCL just feels more polished. But then that could be my years of working with it so it just feels right. My experience with Qt was limited to a short lived project that ended up being rewritten in Delphi after it was determined that cross platform was not really needed thanks to the power of GoGlobal which can make any win32 app a web application, and therefore run on any platform.
A: I'd choose delphi. Only because I have more experience with it. I don't think that there is other reasonabl criterias.
A: Qt is cross-platform, Delphi not much if we count Kylix. Lazarus is cross-platform, but not quite feature-complete yet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: WSDL Generation Tools Can anyone recommend a good (preferably open source) tool for creating WSDL files for some soap web services?
I've tried playing around with some of the eclipse plug ins available and was less than impressed with what I found.
A: As mentioned above, probably the easiest thing to do is use Apache CXF or Apache Axis2 to automatically generate your WSDL for you.
If you have downloaded the Java EE version of Eclipse, you should be able to create a Dynamic Web Project with the Axis2 facets. If you create a simple Java class in the project, you should be able to right-click on it, and choose Web Services->Create Web Service. That should automatically create an Axis2 service for you.
WSDL would then be available from some URL like: http://localhost/axis/{yourservice}?WSDL
A: One of the more interesting tools for bypassing all the associated headaches with WSDL is the XSLT script created by Arjen Poutsma (the lead developer of Spring Web Services):
http://blog.springframework.com/arjen/archives/2006/07/27/xslt-that-transforms-from-xsd-to-wsdl/
Basically it allows you to develop simple schemas that correspond to your desired operations (i.e. <BuyItem> and <BuyItemResponse>) and then generate all the associated WSDL crap from the XSD. I highly recommend it if you are interested in 'contract-first' web-services but the idea of using a WSDL as the starting point for that contract makes you feel green.
A: I am tired of generating massive amounts of files on the filesystem just to transport over SOAP. Now I use Apache CXF for both WS producers and consumers and let it handle the WSDL/stubs generation dynamically.
A: Depends on which language you're working in, but if you're active in Java then I'd recommend looking at Apache CXF. It's a pretty solid framework for publishing java code as a SOAP web service. It also includes a tool for directly generating WSDL files: java2wsdl
A: Nice tool can be found as SAAS solution at www.cofiq.com. Its strong point is the datamodel repository from which WSDL and REST JSON can be generated and impact analysis on datamodel changes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How do I capitalize first letter of first name and last name in C#? Is there an easy way to capitalize the first letter of a string and lower the rest of it? Is there a built in method or do I need to make my own?
A: Mc and Mac are common surname prefixes throughout the US, and there are others. TextInfo.ToTitleCase doesn't handle those cases and shouldn't be used for this purpose. Here's how I'm doing it:
public static string ToTitleCase(string str)
{
string result = str;
if (!string.IsNullOrEmpty(str))
{
var words = str.Split(' ');
for (int index = 0; index < words.Length; index++)
{
var s = words[index];
if (s.Length > 0)
{
words[index] = s[0].ToString().ToUpper() + s.Substring(1);
}
}
result = string.Join(" ", words);
}
return result;
}
A: ToTitleCase() should work for you.
http://support.microsoft.com/kb/312890
A: The most direct option is going to be to use the ToTitleCase function that is available in .NET which should take care of the name most of the time. As edg pointed out there are some names that it will not work for, but these are fairly rare so unless you are targeting a culture where such names are common it is not necessary something that you have to worry too much about.
However if you are not working with a .NET langauge, then it depends on what the input looks like - if you have two separate fields for the first name and the last name then you can just capitalize the first letter lower the rest of it using substrings.
firstName = firstName.Substring(0, 1).ToUpper() + firstName.Substring(1).ToLower();
lastName = lastName.Substring(0, 1).ToUpper() + lastName.Substring(1).ToLower();
However, if you are provided multiple names as part of the same string then you need to know how you are getting the information and split it accordingly. So if you are getting a name like "John Doe" you an split the string based upon the space character. If it is in a format such as "Doe, John" you are going to need to split it based upon the comma. However, once you have it split apart you just apply the code shown previously.
A: String test = "HELLO HOW ARE YOU";
string s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test);
The above code wont work .....
so put the below code by convert to lower then apply the function
String test = "HELLO HOW ARE YOU";
string s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test.ToLower());
A: CultureInfo.CurrentCulture.TextInfo.ToTitleCase ("my name");
returns ~ My Name
But the problem still exists with names like McFly as stated earlier.
A: I use my own method to get this fixed:
For example the phrase: "hello world. hello this is the stackoverflow world." will be "Hello World. Hello This Is The Stackoverflow World.". Regex \b (start of a word) \w (first charactor of the word) will do the trick.
/// <summary>
/// Makes each first letter of a word uppercase. The rest will be lowercase
/// </summary>
/// <param name="Phrase"></param>
/// <returns></returns>
public static string FormatWordsWithFirstCapital(string Phrase)
{
MatchCollection Matches = Regex.Matches(Phrase, "\\b\\w");
Phrase = Phrase.ToLower();
foreach (Match Match in Matches)
Phrase = Phrase.Remove(Match.Index, 1).Insert(Match.Index, Match.Value.ToUpper());
return Phrase;
}
A: TextInfo.ToTitleCase() capitalizes the first character in each token of a string.
If there is no need to maintain Acronym Uppercasing, then you should include ToLower().
string s = "JOHN DOE";
s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
// Produces "John Doe"
If CurrentCulture is unavailable, use:
string s = "JOHN DOE";
s = new System.Globalization.CultureInfo("en-US", false).TextInfo.ToTitleCase(s.ToLower());
See the MSDN Link for a detailed description.
A: The suggestions to use ToTitleCase won't work for strings that are all upper case. So you are gonna have to call ToUpper on the first char and ToLower on the remaining characters.
A: This class does the trick. You can add new prefixes to the _prefixes static string array.
public static class StringExtensions
{
public static string ToProperCase( this string original )
{
if( String.IsNullOrEmpty( original ) )
return original;
string result = _properNameRx.Replace( original.ToLower( CultureInfo.CurrentCulture ), HandleWord );
return result;
}
public static string WordToProperCase( this string word )
{
if( String.IsNullOrEmpty( word ) )
return word;
if( word.Length > 1 )
return Char.ToUpper( word[0], CultureInfo.CurrentCulture ) + word.Substring( 1 );
return word.ToUpper( CultureInfo.CurrentCulture );
}
private static readonly Regex _properNameRx = new Regex( @"\b(\w+)\b" );
private static readonly string[] _prefixes = {
"mc"
};
private static string HandleWord( Match m )
{
string word = m.Groups[1].Value;
foreach( string prefix in _prefixes )
{
if( word.StartsWith( prefix, StringComparison.CurrentCultureIgnoreCase ) )
return prefix.WordToProperCase() + word.Substring( prefix.Length ).WordToProperCase();
}
return word.WordToProperCase();
}
}
A: There are some cases that CultureInfo.CurrentCulture.TextInfo.ToTitleCase cannot handle, for example : the apostrophe '.
string input = CultureInfo.CurrentCulture.TextInfo.ToTitleCase("o'reilly, m'grego, d'angelo");
// input = O'reilly, M'grego, D'angelo
A regex can also be used \b[a-zA-Z] to identify the starting character of a word after a word boundary \b, then we need just to replace the match by its upper case equivalence thanks to the Regex.Replace(string input,string pattern,MatchEvaluator evaluator) method :
string input = "o'reilly, m'grego, d'angelo";
input = Regex.Replace(input.ToLower(), @"\b[a-zA-Z]", m => m.Value.ToUpper());
// input = O'Reilly, M'Grego, D'Angelo
The regex can be tuned if needed, for instance, if we want to handle the MacDonald and McFry cases the regex becomes : (?<=\b(?:mc|mac)?)[a-zA-Z]
string input = "o'reilly, m'grego, d'angelo, macdonald's, mcfry";
input = Regex.Replace(input.ToLower(), @"(?<=\b(?:mc|mac)?)[a-zA-Z]", m => m.Value.ToUpper());
// input = O'Reilly, M'Grego, D'Angelo, MacDonald'S, McFry
If we need to handle more prefixes we only need to modify the group (?:mc|mac), for example to add french prefixes du, de : (?:mc|mac|du|de).
Finally, we can realize that this regex will also match the case MacDonald'S for the last 's so we need to handle it in the regex with a negative look behind (?<!'s\b). At the end we have :
string input = "o'reilly, m'grego, d'angelo, macdonald's, mcfry";
input = Regex.Replace(input.ToLower(), @"(?<=\b(?:mc|mac)?)[a-zA-Z](?<!'s\b)", m => m.Value.ToUpper());
// input = O'Reilly, M'Grego, D'Angelo, MacDonald's, McFry
A: CultureInfo.CurrentCulture.TextInfo.ToTitleCase("hello world");
A: If your using vS2k8, you can use an extension method to add it to the String class:
public static string FirstLetterToUpper(this String input)
{
return input = input.Substring(0, 1).ToUpper() +
input.Substring(1, input.Length - 1);
}
A: To get round some of the issues/problems that have ben highlighted I would suggest converting the string to lower case first and then call the ToTitleCase method. You could then use IndexOf(" Mc") or IndexOf(" O\'") to determine special cases that need more specific attention.
inputString = inputString.ToLower();
inputString = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(inputString);
int indexOfMc = inputString.IndexOf(" Mc");
if(indexOfMc > 0)
{
inputString.Substring(0, indexOfMc + 3) + inputString[indexOfMc + 3].ToString().ToUpper() + inputString.Substring(indexOfMc + 4);
}
A: I like this way:
using System.Globalization;
...
TextInfo myTi = new CultureInfo("en-Us",false).TextInfo;
string raw = "THIS IS ALL CAPS";
string firstCapOnly = myTi.ToTitleCase(raw.ToLower());
Lifted from this MSDN article.
A: Hope this helps you.
String fName = "firstname";
String lName = "lastname";
String capitalizedFName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(fName);
String capitalizedLName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(lName);
A: public static string ConvertToCaptilize(string input)
{
if (!string.IsNullOrEmpty(input))
{
string[] arrUserInput = input.Split(' ');
// Initialize a string builder object for the output
StringBuilder sbOutPut = new StringBuilder();
// Loop thru each character in the string array
foreach (string str in arrUserInput)
{
if (!string.IsNullOrEmpty(str))
{
var charArray = str.ToCharArray();
int k = 0;
foreach (var cr in charArray)
{
char c;
c = k == 0 ? char.ToUpper(cr) : char.ToLower(cr);
sbOutPut.Append(c);
k++;
}
}
sbOutPut.Append(" ");
}
return sbOutPut.ToString();
}
return string.Empty;
}
A: Like edg indicated, you'll need a more complex algorithm to handle special names (this is probably why many places force everything to upper case).
Something like this untested c# should handle the simple case you requested:
public string SentenceCase(string input)
{
return input(0, 1).ToUpper + input.Substring(1).ToLower;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "142"
}
|
Q: Can I suppress FX Cop code analysis violations globally? When you use Visual Studio's code analysic (FxCop), and want to suppress a message there are 3 options.
*
*Suppress a violation in code.
*Suppress a violation in a GlobalSupression.cs file.
*Disable the violation check in the project file (via Project -> Properties -> Code Analysic).
The later is very hard to review when checking in to Source Control, and it is hard to get an overview of all disabled violations. So we would like to use option 2.
The problem with option 1 and 2 is that you get one suppression line for each violation. E.g like:
[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Company.Project.Namespace2")]
[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Company.Project.Namespace1")]
We would love to do something like this ing GlobalSuppressions.cs:
[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes")]
But is this possible?
A: Suppressing multiple violations with a single SuppressMessage attribute is officially not supported. Apparently, this is by design.
I agree, it might be annoying at times, but I can't say I disagree with the decision, since the attribute is their way to force you to say, "Yes, I know what I am doing", which should be evaluated in a case-by-case basis.
A: I think things have changed since this question was posted and answered. For Visual Studio 2010 and 2012 you can create a custom "rule set" file where you can specify which code analysis rules you want to suppress.
http://msdn.microsoft.com/en-us/library/dd380660.aspx
So what I've done is to create a single custom rule set file which is in the top level folder of my repository source collection, and I reference this file in each Visual Studio project. This means I have one central place where I can suppress the code analysis rules that I simply can't stand. But if I ever change my mind, or decide I should reconsider my bad coding habits, I can very simply reenable the rule and see how many code analysis messages I get.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: How to do relative imports in Python? Imagine this directory structure:
app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
I'm coding mod1, and I need to import something from mod2. How should I do it?
I tried from ..sub2 import mod2 but I'm getting an "Attempted relative import in non-package".
I googled around but found only "sys.path manipulation" hacks. Isn't there a clean way?
Edit: all my __init__.py's are currently empty
Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (sub1, subX, etc.).
Edit3: The behaviour I'm looking for is the same as described in PEP 366 (thanks John B)
A: As @EvgeniSergeev says in the comments to the OP, you can import code from a .py file at an arbitrary location with:
import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
This is taken from this SO answer.
A: Take a look at http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports. You could do
from .mod1 import stuff
A: "Guido views running scripts within a package as an anti-pattern" (rejected
PEP-3122)
I have spent so much time trying to find a solution, reading related posts here on Stack Overflow and saying to myself "there must be a better way!". Looks like there is not.
A: This is solved 100%:
*
*app/
*
*main.py
*settings/
*
*local_setings.py
Import settings/local_setting.py in app/main.py:
main.py:
import sys
sys.path.insert(0, "../settings")
try:
from local_settings import *
except ImportError:
print('No Import')
A: Everyone seems to want to tell you what you should be doing rather than just answering the question.
The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.
From PEP 328:
Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
In Python 2.6, they're adding the ability to reference modules relative to the main module. PEP 366 describes the change.
Update: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.
A: explanation of nosklo's answer with examples
note: all __init__.py files are empty.
main.py
app/ ->
__init__.py
package_a/ ->
__init__.py
fun_a.py
package_b/ ->
__init__.py
fun_b.py
app/package_a/fun_a.py
def print_a():
print 'This is a function in dir package_a'
app/package_b/fun_b.py
from app.package_a.fun_a import print_a
def print_b():
print 'This is a function in dir package_b'
print 'going to call a function in dir package_a'
print '-'*30
print_a()
main.py
from app.package_b import fun_b
fun_b.print_b()
if you run $ python main.py it returns:
This is a function in dir package_b
going to call a function in dir package_a
------------------------------
This is a function in dir package_a
*
*main.py does: from app.package_b import fun_b
*fun_b.py does from app.package_a.fun_a import print_a
so file in folder package_b used file in folder package_a, which is what you want. Right??
A: def import_path(fullpath):
"""
Import a file with full path specification. Allows one to
import from anywhere, something __import__ does not do.
"""
path, filename = os.path.split(fullpath)
filename, ext = os.path.splitext(filename)
sys.path.append(path)
module = __import__(filename)
reload(module) # Might be out of date
del sys.path[-1]
return module
I'm using this snippet to import modules from paths, hope that helps
A: From Python doc,
In Python 2.5, you can switch import‘s behaviour to absolute imports using a from __future__ import absolute_import directive. This absolute- import behaviour will become the default in a future version (probably Python 2.7). Once absolute imports are the default, import string will always find the standard library’s version. It’s suggested that users should begin using absolute imports as much as possible, so it’s preferable to begin writing from pkg import string in your code
A: Here is the solution which works for me:
I do the relative imports as from ..sub2 import mod2
and then, if I want to run mod1.py then I go to the parent directory of app and run the module using the python -m switch as python -m app.sub1.mod1.
The real reason why this problem occurs with relative imports, is that relative imports works by taking the __name__ property of the module. If the module is being directly run, then __name__ is set to __main__ and it doesn't contain any information about package structure. And, thats why python complains about the relative import in non-package error.
So, by using the -m switch you provide the package structure information to python, through which it can resolve the relative imports successfully.
I have encountered this problem many times while doing relative imports. And, after reading all the previous answers, I was still not able to figure out how to solve it, in a clean way, without needing to put boilerplate code in all files. (Though some of the comments were really helpful, thanks to @ncoghlan and @XiongChiamiov)
Hope this helps someone who is fighting with relative imports problem, because going through PEP is really not fun.
A: main.py
setup.py
app/ ->
__init__.py
package_a/ ->
__init__.py
module_a.py
package_b/ ->
__init__.py
module_b.py
*
*You run python main.py.
*main.py does: import app.package_a.module_a
*module_a.py does import app.package_b.module_b
Alternatively 2 or 3 could use: from app.package_a import module_a
That will work as long as you have app in your PYTHONPATH. main.py could be anywhere then.
So you write a setup.py to copy (install) the whole app package and subpackages to the target system's python folders, and main.py to target system's script folders.
A: This is unfortunately a sys.path hack, but it works quite well.
I encountered this problem with another layer: I already had a module of the specified name, but it was the wrong module.
what I wanted to do was the following (the module I was working from was module3):
mymodule\
__init__.py
mymodule1\
__init__.py
mymodule1_1
mymodule2\
__init__.py
mymodule2_1
import mymodule.mymodule1.mymodule1_1
Note that I have already installed mymodule, but in my installation I do not have "mymodule1"
and I would get an ImportError because it was trying to import from my installed modules.
I tried to do a sys.path.append, and that didn't work. What did work was a sys.path.insert
if __name__ == '__main__':
sys.path.insert(0, '../..')
So kind of a hack, but got it all to work!
So keep in mind, if you want your decision to override other paths then you need to use sys.path.insert(0, pathname) to get it to work! This was a very frustrating sticking point for me, allot of people say to use the "append" function to sys.path, but that doesn't work if you already have a module defined (I find it very strange behavior)
A: Let me just put this here for my own reference. I know that it is not good Python code, but I needed a script for a project I was working on and I wanted to put the script in a scripts directory.
import os.path
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
A: I found it's more easy to set "PYTHONPATH" enviroment variable to the top folder:
bash$ export PYTHONPATH=/PATH/TO/APP
then:
import sub1.func1
#...more import
of course, PYTHONPATH is "global", but it didn't raise trouble for me yet.
A: On top of what John B said, it seems like setting the __package__ variable should help, instead of changing __main__ which could screw up other things. But as far as I could test, it doesn't completely work as it should.
I have the same problem and neither PEP 328 or 366 solve the problem completely, as both, by the end of the day, need the head of the package to be included in sys.path, as far as I could understand.
I should also mention that I did not find how to format the string that should go into those variables. Is it "package_head.subfolder.module_name" or what?
A: You have to append the module’s path to PYTHONPATH:
export PYTHONPATH="${PYTHONPATH}:/path/to/your/module/"
A: A hacky way to do it is to append the current directory to the PATH at runtime as follows:
import pathlib
import sys
sys.path.append(pathlib.Path(__file__).parent.resolve())
import file_to_import # the actual intended import
In contrast to another solution for this question this uses pathlib instead of os.path.
A: This method queries and auto populates the path:
import os
import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
os.sys.path.insert(1, parentdir)
# print("currentdir = ", currentdir)
# print("parentdir=", parentdir)
A: What a debate!
Relative newcomer to python (but years of programming experience, and dislike of perl). Relative lay-person when it comes to the dark art of Apache setup, but I know what I (think I) need to get my little experimental projects working at home.
Here is my summary of what the situ seems to be.
If I use the -m 'module' approach, I need to:-
*
*dot it all together;
*run it from a parent folder;
*lose the '.py';
*create an empty (!) __init__.py file in every sub-folder.
How does that work in a cgi environment, where I have aliased my scripts directory, and want to run a script directly as /dirAlias/cgi_script.py??
Why is amending sys.path a hack? The python docs page states: "A program is free to modify this list for its own purposes." If it works, it works, right? The bean counters in Accounts don't care how it works.
I just want to go up one level and down into a 'modules' dir:-
.../py
/cgi
/build
/modules
so my 'modules' can be imported from either the cgi world or the server world.
I've tried the -m/modules approach but I think I prefer the following (and am not confused how to run it in cgi-space):-
*
*Create XX_pathsetup.py in the /path/to/python/Lib dir (or any other dir in the default sys.path list). 'XX' is some identifier that declares an intent to setup my path according to the rules in the file.
*In any script that wants to be able to import from the 'modules' dir in above directory config, simply import XX_pathsetup.py.
And here's my really simple XX_pathsetup.py:
import sys, os
pypath = sys.path[0].rsplit(os.sep,1)[0]
sys.path.insert( 0, pypath+os.sep+'modules' )
Not a 'hack', IMHO. 1 small file to put in the python 'Lib' dir, one import statement which declares intent to modify the path search order.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "602"
}
|
Q: How to backup a VPS server? And restore it in an emergency too? I have a VPS host running 3 sites using Ubuntu Hardy. I've spent much time setting it up. That includes all the installation + configuration and stuff. What ways are there to do backup + restore for VPS?
A: Backups alone aren't enough. You should be keeping a detailed system log of all configuration changes you make to the system so that you can reproduce your configuration elsewhere. Ideally, perform the changes on a local VM, then write a script to perform those changes automatically, then run those scripts on the live server. By avoiding manual configuration, all your configuration is repeatable, so to deploy to a new server, you just have to run all of your scripts in sequence.
A: You can try to implement a simple script to backup your data using rsynch - you'll need a second Linux machine with Internet access and some tinkering to make sure your backups are reliable in case you need to restore the - think /etc/ settings, website files and any databases you might have. Pay special attention to file permissions.
Some hosting companies offer managed backup with their plans - you could look into that as well, but make sure your backups run and are stored remotely - you don't want the same disaster to strike all copies of your precious data.
Last, if you can do with a small amount of disk space for your backups, you can try a free account from VPS Backup - it's free up to 5GB of compressed data, works on most flavors of Linux and is specially suited to backup MySQL databases as well. Since you don't have to pay for it, it might be a good workaround until you figure longtime solution.
A: It'll depend a lot on what your host offers. MediaTemple and Slicehost both offer snapshot backups for a nominal fee. Contact your host and ask if they offer such a solution.
If your host doesn't offer anything, you could always backup the critical stuff regularly to something like Amazon's S3 storage service.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ASP.Net Redirect Response to a IFrame How can I redirect the response to an IFrame?
A: Do you mean from the server-side? - You can't!
You'll have to do it on the client side.
Say, use a javascript that sends an AJAX request and then embed your response information in the AJAX response. And have the javascript read the response and changes the page in the intended frame accordingly
A: You can do this through a post-back.
Add a tag to your iframe like this:
< iframe runat="server" id="myIframe" />
in your server-side code (button click, link click, whatever posts back):
myIframe.attributes.add ("src", "webpage.aspx")
A: . . . not totally sure what your trying to do, but you normally control the source of an iframe through javascript
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Refactoring in Ruby Are there any programs or IDEs that support refactoring for Ruby or RoR?
A: The best refactoring tool is good test coverage. If your tests cover your code and they all past you can just make whatever changes you want and the tests will find any dependencies you have broken. This is the main reason why IDE-based refactoring tools are less prevalent in Ruby than elsewhere.
A: IntelliJ IDEA with Ruby plugin supports some refactorings.
alt text http://www.skavish.com/rubyrefactorings.png
A: I believe net-beans and eclipse both support some refactoring within their 'ruby-mode' - also the emacs code browser (ECB) and the various ruby support tools (e.g. rinari) for emacs have some support.
A: Aptana has some simple refactoring tools. I often extract into partials and they have a simple shortcut for pulling things out, creating a file and inserting the right call to the partial. Not the most amazing ever but it's useful
A: I'd be bold and say that Rubymine has the best rails/ruby refactoring in all RoR IDEs. Give it a try and see for your self.
A: There's also 3rdRail from CodeGear (from Delphi fame). The only catch is that it's not free.
A: I've used the refactoring in netbeans. I didn't find it that much more useful than find and replace.
A: You could always give RubyMine a try.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Is Async Messaging (In particular pub/sub style messaging) viable as a domain service architecture or only in an SOA-focused environment? I have been researching asynchronous messaging, and I like the way it elegantly deals with some problems within certain domains and how it makes domain concepts more explicit. But is it a viable pattern for general domain-driven development (at least in the service/application/controller layer), or is the design overhead such that it should be restricted to SOA-based scenarios, like remote services and distributed processing?
A: Great question :). The main problem with asynchronous messaging is that when folks use procedural or object oriented languages, working in an asynchronous or event based manner is often quite tricky and complex and hard for the programmer to read & understand. Business logic is often way simpler if its built in a kinda synchronous manner - invoking methods and getting results immediately etc :).
My rule of thumb is generally to try use simpler synchronous programming models at the micro level for business logic; then use asynchrony and SEDA at the macro level.
For example submitting a purchase order might just write a message to a message queue; but the processing of the purchase order might require 10 different steps all being asynchronous and parallel in a high performance distributed system with many concurrent processes & threads processing individual steps in parallel. So the macro level wiring is based on a SEDA kind of approach - but at the micro level the code for the individual 10 steps could be written mostly in a synchronous programming style.
A: Like so many architecture and design questions, the answer is "it depends".
In my experience, the strength of asynchronous messaging has been in the loose coupling it brings to a design. The coupling can be in:
*
*Time - Requests can be handled asynchronously, helping overall scalability.
*Space - As you point out, allowing for distributed processing in a more robust way than many synchronous designs.
*Technology - Messages and queues are one way to bridge technology differences.
Remember that messages and queues are an abstraction that can have a variety of implementations. You don't necessarily need to use a JMS-compliant, transactional, high-performance messaging framework. Implemented correctly, a table in a relational database can act as a queue with the rows as messages. I've seen both approaches used to great effect.
A: I agree with @BradS too BTW
BTW here's a way of hiding the middleware from your business logic while still getting the benefits of loose coupling & SEDA - while being able to easily switch between a variety of different middleware technology - from in memory SEDA to JMS to AMQP to JavaSpaces to database, files or FTP etc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I sort a list of dictionaries by a value of the dictionary? How do I sort a list of dictionaries by a specific key's value? Given:
[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
When sorted by name, it should become:
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
A: If you want to sort the list by multiple keys, you can do the following:
my_list = [{'name':'Homer', 'age':39}, {'name':'Milhouse', 'age':10}, {'name':'Bart', 'age':10} ]
sortedlist = sorted(my_list , key=lambda elem: "%02d %s" % (elem['age'], elem['name']))
It is rather hackish, since it relies on converting the values into a single string representation for comparison, but it works as expected for numbers including negative ones (although you will need to format your string appropriately with zero paddings if you are using numbers).
A: a = [{'name':'Homer', 'age':39}, ...]
# This changes the list a
a.sort(key=lambda k : k['name'])
# This returns a new list (a is not modified)
sorted(a, key=lambda k : k['name'])
A: import operator
a_list_of_dicts.sort(key=operator.itemgetter('name'))
'key' is used to sort by an arbitrary value and 'itemgetter' sets that value to each item's 'name' attribute.
A: The sorted() function takes a key= parameter
newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])
Alternatively, you can use operator.itemgetter instead of defining the function yourself
from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
For completeness, add reverse=True to sort in descending order
newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)
A: I guess you've meant:
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
This would be sorted like this:
sorted(l,cmp=lambda x,y: cmp(x['name'],y['name']))
A: You could use a custom comparison function, or you could pass in a function that calculates a custom sort key. That's usually more efficient as the key is only calculated once per item, while the comparison function would be called many more times.
You could do it this way:
def mykey(adict): return adict['name']
x = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}]
sorted(x, key=mykey)
But the standard library contains a generic routine for getting items of arbitrary objects: itemgetter. So try this instead:
from operator import itemgetter
x = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}]
sorted(x, key=itemgetter('name'))
A: Using the Schwartzian transform from Perl,
py = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
do
sort_on = "name"
decorated = [(dict_[sort_on], dict_) for dict_ in py]
decorated.sort()
result = [dict_ for (key, dict_) in decorated]
gives
>>> result
[{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]
More on the Perl Schwartzian transform:
In computer science, the Schwartzian transform is a Perl programming
idiom used to improve the efficiency of sorting a list of items. This
idiom is appropriate for comparison-based sorting when the ordering is
actually based on the ordering of a certain property (the key) of the
elements, where computing that property is an intensive operation that
should be performed a minimal number of times. The Schwartzian
Transform is notable in that it does not use named temporary arrays.
A: Sometime we need to use lower() for case-insensitive sorting. For example,
lists = [{'name':'Homer', 'age':39},
{'name':'Bart', 'age':10},
{'name':'abby', 'age':9}]
lists = sorted(lists, key=lambda k: k['name'])
print(lists)
# Bart, Homer, abby
# [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}, {'name':'abby', 'age':9}]
lists = sorted(lists, key=lambda k: k['name'].lower())
print(lists)
# abby, Bart, Homer
# [ {'name':'abby', 'age':9}, {'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
A: import operator
To sort the list of dictionaries by key='name':
list_of_dicts.sort(key=operator.itemgetter('name'))
To sort the list of dictionaries by key='age':
list_of_dicts.sort(key=operator.itemgetter('age'))
A: You have to implement your own comparison function that will compare the dictionaries by values of name keys. See Sorting Mini-HOW TO from PythonInfo Wiki
A: Using the Pandas package is another method, though its runtime at large scale is much slower than the more traditional methods proposed by others:
import pandas as pd
listOfDicts = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
df = pd.DataFrame(listOfDicts)
df = df.sort_values('name')
sorted_listOfDicts = df.T.to_dict().values()
Here are some benchmark values for a tiny list and a large (100k+) list of dicts:
setup_large = "listOfDicts = [];\
[listOfDicts.extend(({'name':'Homer', 'age':39}, {'name':'Bart', 'age':10})) for _ in range(50000)];\
from operator import itemgetter;import pandas as pd;\
df = pd.DataFrame(listOfDicts);"
setup_small = "listOfDicts = [];\
listOfDicts.extend(({'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}));\
from operator import itemgetter;import pandas as pd;\
df = pd.DataFrame(listOfDicts);"
method1 = "newlist = sorted(listOfDicts, key=lambda k: k['name'])"
method2 = "newlist = sorted(listOfDicts, key=itemgetter('name')) "
method3 = "df = df.sort_values('name');\
sorted_listOfDicts = df.T.to_dict().values()"
import timeit
t = timeit.Timer(method1, setup_small)
print('Small Method LC: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup_small)
print('Small Method LC2: ' + str(t.timeit(100)))
t = timeit.Timer(method3, setup_small)
print('Small Method Pandas: ' + str(t.timeit(100)))
t = timeit.Timer(method1, setup_large)
print('Large Method LC: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup_large)
print('Large Method LC2: ' + str(t.timeit(100)))
t = timeit.Timer(method3, setup_large)
print('Large Method Pandas: ' + str(t.timeit(1)))
#Small Method LC: 0.000163078308105
#Small Method LC2: 0.000134944915771
#Small Method Pandas: 0.0712950229645
#Large Method LC: 0.0321750640869
#Large Method LC2: 0.0206089019775
#Large Method Pandas: 5.81405615807
A: Here is the alternative general solution - it sorts elements of a dict by keys and values.
The advantage of it - no need to specify keys, and it would still work if some keys are missing in some of dictionaries.
def sort_key_func(item):
""" Helper function used to sort list of dicts
:param item: dict
:return: sorted list of tuples (k, v)
"""
pairs = []
for k, v in item.items():
pairs.append((k, v))
return sorted(pairs)
sorted(A, key=sort_key_func)
A: If you do not need the original list of dictionaries, you could modify it in-place with sort() method using a custom key function.
Key function:
def get_name(d):
""" Return the value of a key in a dictionary. """
return d["name"]
The list to be sorted:
data_one = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
Sorting it in-place:
data_one.sort(key=get_name)
If you need the original list, call the sorted() function passing it the list and the key function, then assign the returned sorted list to a new variable:
data_two = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
new_data = sorted(data_two, key=get_name)
Printing data_one and new_data.
>>> print(data_one)
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
>>> print(new_data)
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
A: Let's say I have a dictionary D with the elements below. To sort, just use the key argument in sorted to pass a custom function as below:
D = {'eggs': 3, 'ham': 1, 'spam': 2}
def get_count(tuple):
return tuple[1]
sorted(D.items(), key = get_count, reverse=True)
# Or
sorted(D.items(), key = lambda x: x[1], reverse=True) # Avoiding get_count function call
Check this out.
A: my_list = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
my_list.sort(lambda x,y : cmp(x['name'], y['name']))
my_list will now be what you want.
Or better:
Since Python 2.4, there's a key argument is both more efficient and neater:
my_list = sorted(my_list, key=lambda k: k['name'])
...the lambda is, IMO, easier to understand than operator.itemgetter, but your mileage may vary.
A: I have been a big fan of a filter with lambda. However, it is not best option if you consider time complexity.
First option
sorted_list = sorted(list_to_sort, key= lambda x: x['name'])
# Returns list of values
Second option
list_to_sort.sort(key=operator.itemgetter('name'))
# Edits the list, and does not return a new list
Fast comparison of execution times
# First option
python3.6 -m timeit -s "list_to_sort = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Faaa', 'age':57}, {'name':'Errr', 'age':20}]" -s "sorted_l=[]" "sorted_l = sorted(list_to_sort, key=lambda e: e['name'])"
1000000 loops, best of 3: 0.736 µsec per loop
# Second option
python3.6 -m timeit -s "list_to_sort = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Faaa', 'age':57}, {'name':'Errr', 'age':20}]" -s "sorted_l=[]" -s "import operator" "list_to_sort.sort(key=operator.itemgetter('name'))"
1000000 loops, best of 3: 0.438 µsec per loop
A: If performance is a concern, I would use operator.itemgetter instead of lambda as built-in functions perform faster than hand-crafted functions. The itemgetter function seems to perform approximately 20% faster than lambda based on my testing.
From https://wiki.python.org/moin/PythonSpeed:
Likewise, the builtin functions run faster than hand-built equivalents. For example, map(operator.add, v1, v2) is faster than map(lambda x,y: x+y, v1, v2).
Here is a comparison of sorting speed using lambda vs itemgetter.
import random
import operator
# Create a list of 100 dicts with random 8-letter names and random ages from 0 to 100.
l = [{'name': ''.join(random.choices(string.ascii_lowercase, k=8)), 'age': random.randint(0, 100)} for i in range(100)]
# Test the performance with a lambda function sorting on name
%timeit sorted(l, key=lambda x: x['name'])
13 µs ± 388 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# Test the performance with itemgetter sorting on name
%timeit sorted(l, key=operator.itemgetter('name'))
10.7 µs ± 38.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# Check that each technique produces the same sort order
sorted(l, key=lambda x: x['name']) == sorted(l, key=operator.itemgetter('name'))
True
Both techniques sort the list in the same order (verified by execution of the final statement in the code block), but the first one is a little faster.
A: As indicated by @Claudiu to @monojohnny in comment section of this answer, given:
list_to_be_sorted = [
{'name':'Homer', 'age':39},
{'name':'Milhouse', 'age':10},
{'name':'Bart', 'age':10}
]
to sort the list of dictionaries by key 'age', 'name'
(like in SQL statement ORDER BY age, name), you can use:
newlist = sorted( list_to_be_sorted, key=lambda k: (k['age'], k['name']) )
or, likewise
import operator
newlist = sorted( list_to_be_sorted, key=operator.itemgetter('age','name') )
print(newlist)
[{'name': 'Bart', 'age': 10}, {'name': 'Milhouse', 'age': 10},
{'name': 'Homer', 'age': 39}]
A: You can use the following:
lst = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
sorted_lst = sorted(lst, key=lambda x: x['age']) # change this to sort by a different field
print(sorted_lst)
A: sorting by multiple columns, while in descending order on some of them:
the cmps array is global to the cmp function, containing field names and inv == -1 for desc 1 for asc
def cmpfun(a, b):
for (name, inv) in cmps:
res = cmp(a[name], b[name])
if res != 0:
return res * inv
return 0
data = [
dict(name='alice', age=10),
dict(name='baruch', age=9),
dict(name='alice', age=11),
]
all_cmps = [
[('name', 1), ('age', -1)],
[('name', 1), ('age', 1)],
[('name', -1), ('age', 1)],]
print 'data:', data
for cmps in all_cmps: print 'sort:', cmps; print sorted(data, cmpfun)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2672"
}
|
Q: Is it possible to advance an enumerator and get its value in a lambda? If I have an IEnumerator variable is it possible to have a lambda function that takes it, advances it with MoveNext() and returns the Current value every single time its called?
A: e => e.MoveNext() ? e.Current : null
This will advance the enumerator and return the current value, and return null when the enumeration is complete.
A: A Lambda expression can contain complex statements, so you can do the following:
Func<IEnumerator, object> f = ie => { ie.MoveNext(); return ie.Current; };
A: Is this what you are looking for?
List<string> strings = new List<string>()
{
"Hello", "I", "am", "a", "list", "of", "strings."
};
IEnumerator<string> e = strings.GetEnumerator();
Func<string> f = () => e.MoveNext() ? e.Current : null;
for (; ; )
{
string str = f();
if (str == null)
break;
Console.Write(str + " ");
}
The point of an IEnumerator is that you already get syntactic sugar to deal with it:
foreach (string str in strings)
Console.Write(str + " ");
Even handling the enumerator directly looks cleaner in this case:
while (e.MoveNext())
Console.Write(e.Current + " ");
A: Extending on Abe's solution, you can also use closures to hold a reference to the enumerator:
var iter = ((IEnumerable<char>)"hello").GetEnumerator();
//with closure
{
Func<object> f =
() =>
{
iter.MoveNext();
return iter.Current;
};
Console.WriteLine(f());
Console.WriteLine(f());
}
//without closure
{
Func<IEnumerator, object> f =
ie =>
{
ie.MoveNext();
return ie.Current;
};
Console.WriteLine(f(iter));
Console.WriteLine(f(iter));
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can you find all the IP addresses in a selected block of text with a javascript bookmarklet? I am just starting to learn javascript, so I don't have the skills to figure out what I assume is a trivial problem.
I'm working with a Wordpress blog that serves as a FAQ for our community and I am trying to pull together some tools to make managing the comments easier. Internet Duct Tape's Greasemonkey tools, like Comment Ninja, are helpful for most of it, but I want to be able to get a list of all the IP addresses that we're getting comments from in order to track trends and so forth.
I just want to be able to select a bunch of text on the comments page and click a bookmarklet (http://bookmarklets.com) in Firefox that pops up a window listing all the IP addresses found in the selection.
Update:
I kind of combined a the answers from levik and Jacob to come up with this:
javascript:ipAddresses=document.getSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g).join("<br>");newWindow=window.open('', 'IP Addresses in Selection', 'innerWidth=200,innerHeight=300,scrollbars');newWindow.document.write(ipAddresses)
The difference is that instead of an alert message, as in levik's answer, I open a new window similar to Jacob's answer. The alert doesn't provide scroll bars which can be a problem for pages with many IP addresses. However, I needed the list to be vertical, unlike Jacob's solution, so I used the hint from levik's to make a for the join instead of levik's \n.
Thanks for all the help, guys.
A: In Firefox, you could do something like this:
javascript:alert(
document.getSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g)
.join("\n"))
How this works:
*
*Gets the selection text from the browser ("document.getSelection()" in FF, in IE it would be "document.selection.createRange().text")
*Applies a regular expression to march the IP addresses (as suggested by Muerr) - this results in an array of strings.
*Joins this array into one string separated by return characters
*Alerts that string
The way you get the selection is a little different on IE, but the principle is the same. To get it to be cross-browser, you'd need to check which method is available. You could also do more complicated output (like create a floating DIV and insert all the IPs into it).
A: Use a regular expression to detect the IP address. A couple examples:
/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/
/^([1-9][0-9]{0,2})+\.([1-9][0-9]{0,2})+\.([1-9][0-9]{0,2})+\.([1-9][0-9]{0,2})+$/
A: As a bookmarklet
javascript:document.write(document.getSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g))
Just create a new bookmark and paste that javascript in
How to do it in Ubiquity
CmdUtils.CreateCommand({
name: "findip",
preview: function( pblock ) {
var msg = 'IP Addresses Found<br/><br/> ';
ips = CmdUtils.getHtmlSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g);
if(ips){
msg += ips.join("<br/>\n");
}else{
msg += 'None';
}
pblock.innerHTML = msg;
},
execute: function() {
ips = CmdUtils.getHtmlSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g);
if(ips){
CmdUtils.setSelection(ips.join("<br/>\n"));
}
}
})
A: Here is a good article on obtaining the IP address of your visitors. You could display this in addition to their comment if you wanted or include it as a label or field in your page so you can reference it later.
A: Have a look at the rot13 bookmarklet for an example of selecting text and performing an action (in this case substitution) when the bookmarklet is clicked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What's the best alternative to C++ for real-time graphics programming? C++ just sucks too much of my time by making me micro-manage my own memory, making me type far too much (hello std::vector<Thingy>::const_iterator it = lotsOfThingys.begin()), and boring me with long compile times. What's the single best alternative for serious real-time graphics programming? Garbage collection is a must (as is the ability to avoid its use when necessary), and speed must be competitive with C++. A reasonable story for accessing C libs is also a must.
(Full disclosure: I have my own answer to this, but I'm interested to see what others have found to be good alternatives to C++ for real-time graphics work.)
Edit: Thanks everyone for the thoughtful replies. Given that there's really no "right" answer to this question I won't be selecting any particular answer. Besides I'd just pick the language I happen to like as a C++ alternative, which wouldn't really be fair.
A: As a developer/researcher/professor of 3D VR applications for some 20 years I would suggest there is no alternative (except possibly C). The only way to reduce latency and enable real-time interaction is an optimized compiled language (eg C or C++) with access to a fast relaible 3D graphics library such as OpenGL. While I agree it is flustrating to have to code everything, this is also essential for performanc and optimization.
A: Sometimes, looking outside the beaten path you can find a real gem. You might want to consider PureBasic (Don't let the name mislead you). Here's some details:
PureBasic Features
*
*Machine Code (Assembly) executables (FASM)
*
*In-line Assembly support
*No run-times needed (no DLLs needed,etc.) 1 executable file
*Tiny executables (as small or smaller/as fast or faster than C++ w/out the runtime)
*You can write DLLs
*Multi-thread support
*Full OS API support
*Multi-platform support
*
*Windows 95-2003
*Linux
*Mac-OS X
*Amiga
*2D & 3D game development
*
*DirectX
*OGRE
*Generous Licensing
*
*Inexpensive (79 Euros or about $112)
*Life-time license (all future updates & versions included)
*One price for all platforms
*External Library support
*
*3rd party DLLs
*User Libraries
*On-line Support
*
*Responsive development team led by it's creator
*On-line forum
*
*One place for answers (don’t have to go all over the net)
*Huge amount of sample code (try code out while in IE with IEtool)
*Fast replies to questions
*Bonus learning (alternative to learning C++)
*
*API
*Structures
*Interfaces
*Pointers
Visit the online forum to get a better idea of PureBasic (http://www.purebasic.fr/english/index.php) or the main site: www.purebasic.com
A: I completely agree with the mention of C# for graphics programming. It has the slight disadvantage of being a managed language and allowing the garbage collector free reign over your application is framerate suicide after a while but with some relatively intelligent pool allocations made early in the program's life any real issues can be avoided.
Several people have already mentioned XNA, which is incredibly friendly and well-documented and I would like to echo that recommendation as well. I'm personally using it for my hobby game projects and it has treated me very well.
XNA isn't the only alternative, though. There is also SlimDX which is under constant development as a means of providing a lean wrapper of DirectX in a similar fashion as Managed DirectX (which was, I believe, discontinued by Microsoft in favor of XNA). Both are worthy of research: http://code.google.com/p/slimdx/
A: There are no true alternatives for big AAA titles, especially on the consoles. For smaller titles C# should do.
A: C# is a good answer here - it has a fair garbage collection (although you'd have to profile it quite a bit - to change the way you handle things now that the entire memory handling is out of your hands), it is simple to use, have a lot of examples and is well documented.
In the 3D department it gives full support for shaders and effects and so - that would be my choice.
Still, C# is not as efficient as C++ and is slower due to overhead, so if it is speed and the flexibility to use any trick in the book you like (with pointers and assembly if you like to get your hands dirty) - stick to C++ and the price would be writing way more code as you mentioned, but having full control over everything including memory management.
A: I would say the D programming language is a good option. You can link to C object files and interface with C++ code through C libraries. D has garbage collection, inline assembly, and game developers have created bindings to SDL and OpenGL libraries, and are also actively working on new game development apis. I love D. Too bad my job doesn't demand it's use. :(
A: Like James (hopkin), for me, the hybrid approach is the best solution. Python and C++ is a good choice, but other style like C#/C++ works. All depends of your graphical context. For game, XNA is a good platform (limited to win32), in this case C#/C++ is the best solution. For scientific visualization, Python/C++ is accepted (like vtk's bindings in python). For mobile game JAVA/C++ can works...
A: If you are targeting Windows, C++/CLI (Microsoft's .NET 'managed' dialect of C++) is an interesting possibility, particularly if you want to leverage your C++ experience. You can mix native code (e.g. calls to C-style libraries) with .NET managed code quite seamlessly, and take advantage of .NET GC and libraries.
As far as concerns about GC impacting 'real time' performance, I think those tend to be overblown. The multi-generational .NET GC is very good at never taking much time to do a collection, unless you are in some kind of critical low-memory situation. I write .NET code that interacts with electronic derivatives exchanges, where time delays == lots of $$$, and we have never had a GC-related issue. A few milliseconds is a long, long time for the GC, but not for a human interacting with a piece of software, even a 'real time' game. If you really need true "real time" performance (for medical devices, process control, etc.) then you can't use Windows anyway - it's just not a real-time OS.
A: Lot of game engines can fit your need, I suppose. For example, using SDL or Cairo, if portability is needed. Lot of scripting languages (coming in general with easy syntax and garbage collection) have binding to these canvas.
Flash might be another alternative.
I will just point out Processing, which is an open source programming language and environment for people who want to program images, animation, and interactions.
Actually, it is a thin wrapper around Java, making it look like a scripting language: it has a (primitive) IDE when you can type a few lines of code and hit Run without even having to save the file. Actually it wraps the code around a class and adds a main() call, compiles it and run it in a window.
Lot of people use it for real-time exhibitions (VJ and similar).
It has the power and limitations of Java, but adds out of the box a number of nice wrappers (libraries) to simplify access to Java2D, OpenGL, SVG, etc.
Somehow, it has become a model of simple graphics language: there are several applications trying to mimic Processing in other languages, like Ruby, Scala or Python. One of the most impressive is a JavaScript implementation, using the canvas component implemented in Firefox, Safari, Opera, etc.
A: I vote c++0x. Partial support is already available in gcc-4.3+ using the -std=c++0x flag.
A: Would 'C' be too obvious an answer?
A: What about D Programming Language?
Some links requested in the comment:
Win32 Api
Derelict (Multimedia lib)
A: I wouldn't discard C++. In fact, I would consider adding Boost to your C++ library, which makes the language much more usable. Your example would become:
BOOST_FOREACH( Thingy& t, lostOfThingys ) {
// do something with 't'
}
Boost has tons of tools that help make C++ a better language.
A: C# is a nice language that fits your requirements, and it is definitely suited for graphics, thanks to the efforts of Microsoft to provide it with great tools and libraries like Visual Studio and XNA.
A: Real-time + garbage collection don't match very well I'm afraid.
It's a bit hard to make any real-time response guarantees if a garbage collector can kick in at any time and spend an undefined amount of processing...
A: I disagree with your premise. When used carefully and properly, C++ is a great language, especially for a domain like real-time graphics, where speed is of the essence.
Memory management becomes easy if you design your system well, and use stl containers and smart pointers.
std::vector::const_iterator it = lotsOfThingys.begin()) will become much shorter if you use
using namespace std;
typedef vector::const_iterator ThingyConstIter;
And you can shorten compile times significantly by breaking up your systems into reasonably self-contained modules, by using precompiled headers, or by using the PIMPL idiom.
A: Perhaps a hybrid approach. Python and C++ make a good combination (see, for example, PyGame).
A: Some variation of Lisp that compiles to machine code could be almost as fast as C++ for this kind of programming. The Naughty Dog team created a version of Lisp called Game Oriented Assembly Lisp, which they used to create several AAA titles, including the Jak and Daxter series. The two major impediments to a Lisp approach in the game industry would be the entrenched nature of C/C++ development (both tools and human assets are heavily invested in C/C++), as well as the difficulty of finding talented engineers who are stars in both the game programming domain and the Lisp language.
Many programming teams in the industry are shifting to a hybrid approach wherein the real-time code, especially graphics and physics code, is written in C or C++, but game logic is done in a higher-level scripting language, which is accessible to and editable by programmers and non-programmers alike. Lua and Python are both popular for higher-level scripting.
A: Let's not forget to mention the new 'auto' use:
auto it = lotsOfThingys.begin(); // Let the compiler figure it out.
auto it2 = lotsOfFoos.begin();
if (it==it2) // It's still strongly typed; a Thingy iter is not a Foo iter.
A: I have very successfully used C++ for the engine, with the application written in Lua on top. JavaScript is also very practical, now the latest generation of JIT based JS engines are around (tracemonkey, V8 etc).
I think C++ will be with us for a while yet; even Tim Sweeney hasn't actually switched to Haskell (pdf) yet, AFAIK :-)
A: Java and LWJGL (OpenGL wrapper) has worked well for me. If you're looking for more of a scene graph type library like Orge have a look at jMonkeyEngine which we used to create a google earth type application (see www.skapeworld.com). If you're sensible with object creation the garbage collection is a non issue.
A: If your target is a PC, I think you can try C#, or embed Lua in your C++ app and run scripts for 'high-level' stuff. However if your target is a console, you must manage your own memory!
A: Objective-C looks like a good match for your requirements (the latest version with optional GC), although it is too dynamic and Smalltalk-like for my taste.
A: XNA is your best bet I think. Being supported by the .NET framework you can build for a Windows or Xbox 360 platform by simply changing a setting in Game Studio. Best yet, all the tools are free!
If you decide to go with XNA you can easily get started using their quickstart guide
XNA Quickstart guide
It has been a rewarding and fun experiance for me so far, and a nice break from the memory management of C++.
A:
Garbage collection is a must (as is
the ability to avoid its use when
necessary)
You can't disable a garbage collector temporarily. You would need a deterministic garbage collector then. But such a beast does come with a performance hit also. I think BEA JRockit is such a beast and then you should stick to Java.
Just to comment on your example; typedef is your friend...
typedef std::vector<Thingy> Thingys;
Thingys::const_iterator it = lotsOfThingys.begin()
A: Don't overlook independent languages in your quest. Emergence BASIC from Ionic Wind Software has a built in DirectX 9 engine, supports OOP and can easily interface with C libraries.
http://www.ionicwind.com
James.
A: The best enviroment for your project is the one you get your task done in the fastest way possible. This - especially for 3D-graphics - includes libraries.
Depending on the task, you may get away with some minor directx hacking. Then you could use .NET and slimdx. Managed languages tend to be faster to programm and easier to debug.
Perhaps you need a really good 3D-engine? Try Ogre3D or Irrlicht. You need commercial grade quality (one might argue that Ogre3D offers that) - go for Cryengine or Unreal. With Ogre3D and Irrlicht you might uses .NET as well, though the ports are not always up to date and plugins are not as easyly included as in the C++ versions. For Cryengine/Unrealengine you won't have a real choice I guess.
You need it more portable? OpenGL for the rescue - though you might need some wrapper (e.g. SDL).
You need a GUI as well? wxWidgets, QT might be a possiblity.
You already have a toolchain? Your libraries need to be able to handle the file formats.
You want to write a library? C / C++ might be a solution, since most of the world can use C / C++ libraries. Perhaps with the use of COM?
There are still a lot of projects/libraries I did not mention (XNA, Boost, ...) and if you want to create some program that does not only display 3D-graphics, you might have other needs as well (Input, Sound, Network, AI, Database, GUI, ...)
To sum it up: A programming language is a tool to reach a goal. It has to be seen in the context of the task at hand. The task has its own needs and these needs may chose the language for you (e.g. you need a certain library to get a feature that takes long to programm and you can only access the library with language X).
If you need the one-does-nearly-all: try C++/CLI (perhaps in combination with C# for easier syntax).
A: Good question.
As for the 'making me type far too much', C++0x seems to address most of it
as mentioned:
auto it = lotsOfThingys.begin()) // ... deduce type, just like in *ML
VS2010beta implements this already.
As for the memory management - for efficiency - you will have to keep good track of memory allocations, with or without garbage collection (ie, make memory-pools, re-use allocated object sometimes) anyhow, so that eventually whether your environment is garbage collected or not, matters less. You'll have to explicitly call the gc() as well, to keep the memory from fragmenting.
Having consistent ways to manage memory is important anywhere.
RAII - is a killer feature of C++
Another thing - is that memory is just one resource, you still have to keep track of other resources with a GC, so RIAA.
Anyhow, C# - is a nice alternative in many respects, I find it a very nice language, especially the ability to write functional-style code in it (the cute lambda -> syntax, map/select 'LINQ' syntax etc), thus the possibility to write parallel code; while it's still a 'standard curly-brackets', when you (or your colleagues) need it.
A: Have a look to Delphi/Pascal Object and some exemples :
http://www.delphigamer.com or http://glscene.cjb.net/
A: You can look at Ada. There is no garbage collector but this language is oftenly used for real-time system needing high reliability. That means less debuging times for your 3D applications.
And, you can also look at Haskell, if you don't know the functional paradigm this language will look weird to you, but it's worth a bit of your time. Tim Sweeney (EPIC Inc) is considering this language as a C++ alternative.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
}
|
Q: can't delete directory under linux due to broken files
kt@rails-ubuntu:~/rails/ledger/releases/20080820144914/.git/hooks$ ls -al
ls: cannot access post-commit: No such file or directory
ls: cannot access update: No such file or directory
ls: cannot access post-update: No such file or directory
ls: cannot access commit-msg: No such file or directory
ls: cannot access pre-rebase: No such file or directory
ls: cannot access post-receive: No such file or directory
ls: cannot access pre-applypatch: No such file or directory
ls: cannot access pre-commit: No such file or directory
total 8
drwxrwxr-x 2 kt kt 4096 2008-09-09 18:10 .
drwxrwxr-x 4 kt kt 4096 2008-09-09 18:10 ..
-????????? ? ? ? ? ? commit-msg
-????????? ? ? ? ? ? post-commit
-????????? ? ? ? ? ? post-receive
-????????? ? ? ? ? ? post-update
-????????? ? ? ? ? ? pre-applypatch
-????????? ? ? ? ? ? pre-commit
-????????? ? ? ? ? ? pre-rebase
-????????? ? ? ? ? ? update
A: First off, here's your question, nicely formatted (surround it in < pre > tags to get this):
kt@rails-ubuntu:~/rails/ledger/releases/20080820144914/.git/hooks$ ls -al
ls: cannot access post-commit: No such file or directory
ls: cannot access update: No such file or directory
ls: cannot access post-update: No such file or directory
[snip]
Anyway, you need to boot up in single-user mode and run fsck. If you can't reboot right now, just move the directory to /tmp and forget about it.
A: (a) Looks like you have some kind of filesystem problems; I'd recommend you run fsck and see if it finds anything
(b) Really not a programming-related question, so off-topic here.
A: I had the same problem caused by Aptana Studio working with rails more than once.
The long term solution was to avoid using aptana to create files.
A: I ran into this problem and tried everything. Surprisingly the solution is very simple. Dude, this is what you do:
Using GUI and not the terminal
1. Move all other files in that folder to a different one with a different name
2. Move the containing directory which should have only the problematic file to trash
3 Empty trash
and yes, it is that simple
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Possible to set tab focus in IE7 from JavaScript Is it possible to launch a new window in JavaScript using the window.Open function, then set the focus to that tab?
Here's what I'm doing today:
var winRef = window.open(outUrl,wName,'left='+ wX +',top=' + wY + ',height=' + wH + ',width=' + wW + args);
try {
// Not all window types support the focus() property.
winRef.focus();
}
catch (exception) {
}
The window opens, but the new tab doesn't receive focus.
A: Jay,
You are seeing designed behavior. To limit opportunities for malicious behavior, scripts running in tabbed windows cannot affect other tabs.
For more information, please see Tabbed Browsing for Developers at http://msdn.microsoft.com/en-us/library/ms537636.aspx :
"The ability to open multiple documents within the same browser window has certain practical and security implications [...] Active tabs (tabs with focus) cannot be affected by scripts that run in inactive or background tabs."
BR.
A: As a user, I never want applications (or tabs) to take focus unless I specifically requested it. I have gone to great lengths to prevent tabs in my browser (Firefox) from taking focus for this reason.
A: I'm reasonably certain you can't shift focus to another tab.
My understanding is this is done to somewhat limit pop ups and other malicious content from stealing the users focus.
A: If the other "tab" is part of your application (and not content from another site) perhaps you should include it in a popup div on top of your main content instead of in a separate window; that way you can always control focusing it, deactivating the content under it (for modal dialogs), hiding it, etc.
A: As a user, shouldn't I be able to control how this operates?
What if there is an application that would be enhanced by this feature that I want to run - shouldn't I be able to grant a domain that privilege?
Just a thought.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to create a triple-join table with Django Using Django's built in models, how would one create a triple-join between three models.
For example:
*
*Users, Roles, and Events are the models.
*Users have many Roles, and Roles many Users. (ManyToMany)
*Events have many Users, and Users many Events. (ManyToMany)
*But for any given Event, any User may have only one Role.
How can this be represented in the model?
A: I'd recommend just creating an entirely separate model for this.
class Assignment(Model):
user = ForeignKey(User)
role = ForeignKey(Role)
event = ForeignKey(Event)
This lets you do all the usual model stuff, such as
user.assignment_set.filter(role__name="Chaperon")
role.assignment_set.filter(event__name="Silly Walkathon")
The only thing left is to enforce your one-role-per-user-per-event restriction. You can do this in the Assignment class by either overriding the save method (http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods) or using signals (http://docs.djangoproject.com/en/dev/topics/signals/)
A: zacherates writes:
I'd model Role as an association class between Users and Roles (...)
I'd also reccomed this solution, but you can also make use of some syntactical sugar provided by Django: ManyToMany relation with extra fields.
Example:
class User(models.Model):
name = models.CharField(max_length=128)
class Event(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(User, through='Role')
def __unicode__(self):
return self.name
class Role(models.Model):
person = models.ForeignKey(User)
group = models.ForeignKey(Event)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
A: I'd model Role as an association class between Users and Roles, thus,
class User(models.Model):
...
class Event(models.Model):
...
class Role(models.Model):
user = models.ForeignKey(User)
event = models.ForeignKey(Event)
And enforce the one role per user per event in either a manager or SQL constraints.
A: While trying to find a faster three-table join for my own Django models, I came across this question. By default, Django 1.1 uses INNER JOINs which can be slow on InnoDB. For a query like:
def event_users(event_name):
return User.objects.filter(roles__events__name=event_name)
this might create the following SQL:
SELECT `user`.`id`, `user`.`name` FROM `user` INNER JOIN `roles` ON (`user`.`id` = `roles`.`user_id`) INNER JOIN `event` ON (`roles`.`event_id` = `event`.`id`) WHERE `event`.`name` = "event_name"
The INNER JOINs can be very slow compared with LEFT JOINs. An even faster query can be found under gimg1's answer: Mysql query to join three tables
SELECT `user`.`id`, `user`.`name` FROM `user`, `roles`, `event` WHERE `user`.`id` = `roles`.`user_id` AND `roles`.`event_id` = `event`.`id` AND `event`.`name` = "event_name"
However, you will need to use a custom SQL query: https://docs.djangoproject.com/en/dev/topics/db/sql/
In this case, it would look something like:
from django.db import connection
def event_users(event_name):
cursor = connection.cursor()
cursor.execute('select U.name from user U, roles R, event E' \
' where U.id=R.user_id and R.event_id=E.id and E.name="%s"' % event_name)
return [row[0] for row in cursor.fetchall()]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: How to get reliable HTTP messages via Firefox XPCOM in Javascript I am trying to program a small server+client in Javascript on Firefox, using XPCOM.
To get the HTTP message in Javascript, I am using the nsIScriptableInputStream interface.
This f**ing component through the read() method randomly cut the message and I cannot make it reliable.
Is anybody know a solution to get reliably the information? (I already tried a binary stream, same failure.)
J.
A: I had the same problem with unreliability... I ended up using XMLHTTPRequest, which when used from the XPCOM component can do cross site requests. The second part of the docs detail how to instantiate the XPCOM version.
If you're looking to serve HTTP request I'd take a look at the POW source code and the use of server sockets, which implements a basic HTTP server in JavaScript. Also check out httpd.js
A: If you control the protocol (that is, both the client and server) I would highly recommend using Javascript/JSON for your server-to-client messages. The client can open a stream either via dynamically adding a <script> tag to the DOM. The server can then send a stream of Javascript commands like:
receiveMsg({type:"text", content:"this is my message"});
Then the client just needs to define a receiveMsg function. This allows you to rely on fast browser code to parse the message and determine where the end of each message is, at which point it will call your handler for you.
Even if you're working with an existing HTTP protocol and can't use JSON, is there some reason you can't use XMLHttpRequest? I would expect it to be more stable than some poorly documented Firefox-specific XPCOM interface.
--Chouser
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: The log file for database is full So our SQL Server 2000 is giving me the error, "The log file for database is full. Back up the transaction log for the database to free up some log space."
How do I go about fixing this without deleting the log like some other sites have mentioned?
Additional Info: Enable AutoGrowth is enabled growing by 10% and is restricted to 40MB.
A: Scott, as you guessed: truncating the log is a bad move if you care about your data.
The following, free, videos will help you see exactly what's going on and will show you how to fix the problem without truncating the logs. (These videos also explain why that's such a dangerous hack and why you are right to look for another solution.)
*
*SQL Server Backups Demystified
*SQL Server Logging Essentials
*Understanding Backup Options
Together these videos will help you understand exactly what's going on and will show you whether you want to switch to SIMPLE recovery, or look into actually changing your backup routines. There are also some additional 'how-to' videos that will show you exactly how to set up your backups to ensure availability while managing log file sizing and growth.
A: I don't think renaming or moving the log file will work while the database is online.
Easiest thing to do, IMO, is to open the properties for the database and switch it to Simple Recovery Model. then shrink the database and then go back and set the DB to Full Recoery Model (or whatever model you need).
Changing the logging mode forces SQL Server to set a checkpoint in the database, after which shrinking the database will free up the excess space.
A: ether backup your database logs regularly if you need to recover up to the minute or do other fun stuff like log shipping in the future, or set the database to simple mode and shrink the data file.
DO NOT copy, rename, or delete the .ldf file this will break your database and after you recover from this you may have data in an inconsistent state making it invalid.
A: To just empty it:
backup log <dbname> with truncate_only
To save it somewhere:
backup log <dbname> to disk='c:\somefile.bak'
If you dont really need transactional history, try setting the database recovery mode to simple.
A: My friend who faced this error in the past recommends:
Try
*
*Backing up the DB. The maintenance plan includes truncation of these files.
*Also try changing the 'recovery mode' for the DB to Simple (instead of Full for instance)
Cause:
The transaction log swells up due to events being logged (Maybe you have a number of transactions failing and being rolled back.. or a sudden peaking in transactions on the server )
A: You may want to check related SO question:
*
*How do you clear the transaction log in a SQL Server 2005 database?
A: Well you could take a copy of the transaction log, then truncate the log file, which is what the error message suggests.
If disk space is full and you can't copy the log to another machine over the network, then connect a drive via USB and copy it off that way.
A: You have the answer in your question: Backup the log, then it will be shrunk.
Make a maintenance plan to regularly backup the database and don't forget to select "Backup the transaction log". That way you'll keep it small.
A: If it's a non production environment use
dump tran <db_name> with no_log;
Once this has completed shrink the log file to free up disk space. Finally switch database recovery mode to simple.
A: As soon as you take a full backup of the database, and the database is not using the Simple recovery model, SQL Server keeps a complete record of all transactions ever performed on the database. It does this so that in the event of a catastrophic failure where you lose the data file, you can restore to the point of failure by backing up the log and, once you have restored an old data backup, restore the log to replay the lost transactions.
To prevent this building up, you must back up the transaction log. Or, you can break the chain at the current point using the TRUNCATE_ONLY or NO_LOG options of BACKUP LOG.
If you don't need this feature, set the recovery model to Simple.
A: My dear friend it is vey important for a DBA to check his log file quite frequently. Because if you don't give much attention towards it some day it is going to give this error.
For this purpose you have to periodically take back up so that the logs file would not faced such error.
Other then this the above given suggestion are quite right.
A: Rename it it. eg:
old-log-16-09-08.log
Then the SQL server can use a new empty one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Which logging library is better? I was wondering; which logging libraries for Delphi do you prefer?
*
*CodeSite
*SmartInspect
*Log4Delphi
*TraceFormat
Please try to add a reasoning why you prefer one over the other if you've used more than one.
I'll add suggestions to this question to keep things readable.
A: And don't forget the free open source TraceTool
A: I have just updated Log4Delphi 0.8 on the Sourceforge page and it rolls up patches and bug fixes from the last 4 years.
Sourceforge Log4Delphi Downloads
A: Log4net/ports of Log4xxx to other languages. It's open-source, pretty wide-spread, popular, has a good community behind, and isused widel (for example, in Hibernate/nHibernate).
A: An important value behind CodeSite is Ray Kanopka's support. He personally answers emails and newsgroup posts, and has done so for many years. His answers often contain code that illustrates excellent coding habits.
A: I've used Codesite and it has been fantastic. On one project, a word-processor, I could easily output a million debug lines, all structured, and Codesite helped greatly with its auto-collapsing indented output. For any task where you have to know what really is happening "underneath" a process that can't be interrupted by user interaction, Codesite is really good. I recommend it heartily.
A: SmartInspect is really useful. It is the only one I have used. The logging library is good, but the console and the remote TCP/IP logging takes it over the top. I think CodeSite has some similar features.
A: Take a look at the features of this Open Source unit:
http://blog.synopse.info/post/2011/04/14/Enhanced-logging-in-SynCommons
*
*logging with a set of levels (not only a hierarchy of levels);
*fast, low execution overhead;
*can load .map file symbols to be used in logging;
*compression of .map into binary .mab (900 KB -> 70 KB);
*optional inclusion of the .map/.mab into the .exe;
*handle libraries (.ocx/.dll);
*exception logging (Delphi or low-level exceptions) with unit names and line numbers;
*optional stack trace with units and line numbers;
*methods or procedure recursive tracing, with Enter and auto-Leave;
*high resolution time stamps, for customer-side profiling of the application execution;
*set / enumerates / TList / TPersistent / TObjectList / dynamic array JSON serialization;
*per-thread, rotating or global logging;
*multiple log files on the same process;
*optional colored console display;
*optional redirected logging (e.g. to third party library, or to a remote server);
*log viewer GUI application, with per event or per thread filters, and method execution profiler;
*Open Source, works from Delphi 5 up to XE6 (Win32 and Win64).
Your feedback is welcome!
A: I didn't use CodeSite probably because I'm completely happy with SmartInspect. Highly recommended.
A: I am looking into Codesite as well. I built my own in the past but I really like the featrues in Codesite. The Raize componenets are very well written and always quality stuff.
A: Log4D is another implementation which is based on Log4J and easy to extend and configure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: .NET Windows Forms Transparent Control I want to simulate a 'Web 2.0' Lightbox style UI technique in a Windows Forms application. That is, to draw attention to some foreground control by 'dimming' all other content in the client area of a window.
The obvious solution is to create a control that is simply a partially transparent rectangle that can be docked to the client area of a window and brought to the front of the Z-Order. It needs to act like a dirty pain of glass through which the other controls can still be seen (and therefore continue to paint themselves). Is this possible?
I've had a good hunt round and tried a few techniques myself but thus far have been unsuccessful.
If it is not possible, what would be another way to do it?
See: http://www.useit.com/alertbox/application-design.html (under the Lightbox section for a screenshot to illustrate what I mean.)
A: This is a really cool idea - I will probably use it, so thanks. Anyway, my solution is really simple... open a new 50% opaque form over your current one and then custom draw a background image for that form with a rectangle matching the bounds of the control you want to highlight filled in the color of the transparency key.
In my rough sample, I called this form the 'LBform' and the meat of it is this:
public Rectangle ControlBounds { get; set; }
private void LBform_Load(object sender, EventArgs e)
{
Bitmap background = new Bitmap(this.Width, this.Height);
Graphics g = Graphics.FromImage(background);
g.FillRectangle(Brushes.Fuchsia, this.ControlBounds);
g.Flush();
this.BackgroundImage = background;
this.Invalidate();
}
Color.Fuchia is the TransparencyKey for this semi-opaque form, so you will be able to see through the rectangle drawn and interact with anything within it's bounds on the main form.
In the experimental project I whipped up to try this, I used a UserControl dynamically added to the form, but you could just as easily use a control already on the form. In the main form (the one you are obscuring) I put the relevant code into a button click:
private void button1_Click(object sender, EventArgs e)
{
// setup user control:
UserControl1 uc1 = new UserControl1();
uc1.Left = (this.Width - uc1.Width) / 2;
uc1.Top = (this.Height - uc1.Height) / 2;
this.Controls.Add(uc1);
uc1.BringToFront();
// load the lightbox form:
LBform lbform = new LBform();
lbform.SetBounds(this.Left + 8, this.Top + 30, this.ClientRectangle.Width, this.ClientRectangle.Height);
lbform.ControlBounds = uc1.Bounds;
lbform.Owner = this;
lbform.Show();
}
Really basic stuff that you can do your own way if you like, but it's just adding the usercontrol, then setting the lightbox form over the main form and setting the bounds property to render the full transparency in the right place. Things like form dragging and closing the lightbox form and UserControl aren't handled in my quick sample. Oh and don't forget to dispose the Graphics instance - I left that out too (it's late, I'm really tired).
Here's my very did-it-in-20-minutes demo
A: Can you do this in .NET/C#?
Yes you certainly can but it takes a little bit of effort. I would recommend the following approach. Create a top level Form that has no border or titlebar area and then give make sure it draws no client area background by setting the TransparencyKey and BackColor to the same value. So you now have a window that draws nothing...
public class DarkenArea : Form
{
public DarkenArea()
{
FormBorderStyle = FormBorderStyle.None;
SizeGripStyle = SizeGripStyle.Hide;
StartPosition = FormStartPosition.Manual;
MaximizeBox = false;
MinimizeBox = false;
ShowInTaskbar = false;
BackColor = Color.Magenta;
TransparencyKey = Color.Magenta;
Opacity = 0.5f;
}
}
Create and position this DarkenArea window over the client area of your form. Then you need to be able to show the window without it taking the focus and so you will need to platform invoke in the following way to show without it becoming active...
public void ShowWithoutActivate()
{
// Show the window without activating it (i.e. do not take focus)
PlatformInvoke.ShowWindow(this.Handle, (short)SW_SHOWNOACTIVATE);
}
You need to make it actually draw something but exclude drawing in the area of the control you want to remain highlighted. So override the OnPaint handler and draw in black/blue or whatever you want but excluding the area you want to remain bright...
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// Do your painting here be exclude the area you want to be brighter
}
Last you need to override the WndProc to prevent the mouse interacting with the window if the user tries something crazy like clicking on the darkened area. Something like this...
protected override void WndProc(ref Message m)
{
if (m.Msg == (int)WM_NCHITTEST)
m.Result = (IntPtr)HTTRANSPARENT;
else
base.WndProc(ref m);
}
That should be enough to get the desired effect. When you are ready to reverse the effect you dispose of the DarkenArea instance and carry on.
A: The forms themselves have the property Opacity that would be perfect, but I don't think most of the individual controls do. You'll have to owner-draw it.
A: The big dimming rectangle is good.
Another way to do it would be:
Roll your own base Form class says a MyLightboxAwareForm class that would listen to a LightboxEvent from a LightboxManager. Then have all your forms inherit from MyLightboxAwareForm.
On calling the Show method on any Lightbox, the LightboxManager would broadcast a LightboxShown event to all MyLightboxAwareForm instances and making them dim themselves.
This has the advantage that normal Win32 forms functionality will continue to work such as taskbar-flashing of the form when you click on one of its modal dialogs or the management of mouseover/mousedown events would still work normally etc.
And if you want the rectangle dimming style, you could just put the logic in MyLightboxAwareForm
A: Another solution that doesn't involve using a new Form :
*
*make a picture of your container (form / panel / whatever),
*change its opacity,
*display it in a new panel's background.
*Fill your container with that panel.
And now the code...
Let's say I have a UserControl called Frame to which I'll want to apply my lightbox effect:
public partial class Frame : UserControl
{
private Panel shadow = new Panel();
private static float LIGHTBOX_OPACITY = 0.3f;
public Frame()
{
InitializeComponent();
shadow.Dock = DockStyle.Fill;
}
public void ShowLightbox()
{
Bitmap bmp = new Bitmap(this.Width, this.Height);
this.pnlContainer.DrawToBitmap(bmp, new Rectangle(0, 0, this.Width, this.Height));
shadow.BackgroundImage = SetImgOpacity(bmp, LIGHTBOX_OPACITY );
this.Controls.Add(shadow);
shadow.BringToFront();
}
// http://www.geekpedia.com/code110_Set-Image-Opacity-Using-Csharp.html
private Image SetImgOpacity(Image imgPic, float imgOpac)
{
Bitmap bmpPic = new Bitmap(imgPic.Width, imgPic.Height);
Graphics gfxPic = Graphics.FromImage(bmpPic);
ColorMatrix cmxPic = new ColorMatrix();
cmxPic.Matrix33 = imgOpac;
ImageAttributes iaPic = new ImageAttributes();
iaPic.SetColorMatrix(cmxPic, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
gfxPic.DrawImage(imgPic, new Rectangle(0, 0, bmpPic.Width, bmpPic.Height), 0, 0, imgPic.Width, imgPic.Height, GraphicsUnit.Pixel, iaPic);
gfxPic.Dispose();
return bmpPic;
}
}
The advantages to using this technique are :
*
*You won't have to handle all of the mouse events
*You won't have to manage multiple forms to communicate with the lightbox elements
*No overriding of WndProc
*You'll be cool because you'll be the only one not to use forms to achieve this effect.
Drawbacks are mainly that this technique is much slower because you have to process an entire image to correct each pixel point using the ColorMatrix.
A: Every form has "Opacity" property. Set it to 50% (or 0.5 from code) so will be half transparent. Remove borders and show it maximized before the form you want to have focus. You can change BackColor of the form or even set background image for different effects.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Join multiple XML files with xinclude tags into single file I am creating an installer in IzPack. It is quite large, and I have broken up my XML files appropriately using <xinclude> and <xfragment> tags. Unfortunately, IzPack does not combine them together when you build your installer. This requires you to package the files with the installer, which just won't work.
I was about to start writing a tool in Java to load the XML files and combine them, but I don't want to go reinventing the wheel.
Do the Java XML libraries provide native handling of xinclude? A google didn't seem to turn up much.
Not a big deal if I have to write this myself, just wanted to check with you guys. Thanks.
Format of XML for example purposes:
File1.xml
<?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
<installation version="1.0">
<packs>
<pack name="Transaction Service" id="Transaction Service" required="no" >
<xinclude href="example/File2.xml" />
</pack>
</packs>
File2.xml
<xfragment>
<file src="..." />
</xfragment>
File2 does not need the standard XML header. The xml file is parsed at build time, because the resources it specifies are included in the installer. What isn't included is the actual XML information (order to write the files, where to put them etc.)
What I am looking to have produced:
<?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
<installation version="1.0">
<packs>
<pack name="Transaction Service" id="Transaction Service" required="no" >
<file src="..." />
</pack>
</packs>
Thanks, I am going to start whipping it together in Java now, but hopefully someone has a simple answer.
Tim Reynolds
A: If you can't get xinclude to work and you're using Ant, I'd recommend XMLTask, which is a plugin task for Ant. It'll do lots of clever stuff, including the one thing you're interested in - constructing a XML file out of fragments.
e.g.
<xmltask source="templatefile.xml" dest="finalfile.xml">
<insert path="/packs/pack[1]" position="under" file="pack1.xml"/>
</xmltask>
(warning- the above is done from memory so please consult the documentation!).
Note that in the above, the file pack1.xml doesn't have to have a root node.
A: I'm not sure if java supports automatic xinclude. But you will have to use namespaces to make it work. So don't use <xinclude ....>, but use:
<xi:xinclude xmlns:xi="http://www.w3.org/2001/XInclude" href="example/File2.xml" />
Normally the included file should still contain the xml header as well. There is no requirement for it to e.g. have the same encoding.
A: Apache Xerces, for example, should support Xinclude, but you will need to enable it.
http://xerces.apache.org/xerces2-j/faq-xinclude.html
import javax.xml.parsers.SAXParserFactory;
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setXIncludeAware(true);
Their documentation also says you can enable it as a feature
A: This works now:
<?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
<installation version="1.0">
<packs>
<pack name="Transaction Service" id="Transaction Service" required="no" >
<xi:include href="example/File2.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
</pack>
</packs>
example/File2.xml
<?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
<xfragment>
<file src="..." />
</xfragment>
A: Just for anyone who wants to know. IzPack used nanoXML to parse all config files. It does not have namespaces. And does not handle xml includes.
To resolve an issue I had I added the "xinclude" etc (fragment/fallback) element to the parser stuff so that it that mostly followed the standards for x:include (notice the name difference?) One is correct and has a namespace. The other is a nasty hack that pretends to follow the standard without using namespaces.
Anyway this is long ago and now IzPack uses a sane XML parser and understands if you do it correctly xi:include or whatever prefix you wish to use there are no problems. It is standard in decent xml parsers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Modal dialogs in IE gets hidden behind IE if user clicks on IE pane I have to write an applet that brings up a password dialog. The problem is that dialog is set to be always on top but when user clicks on IE window dialog gets hidden behind IE window nevertheless. And since dialog is modal and holds all IE threads IE pane does not refresh and dialog window is still painted on top of IE (but not refreshed). This behaviour confuses users (they see dialog on top of IE but it looks like it has hanged since it is not refreshe).
So I need a way to keep that dialog on top of everything. But any other solution to this problem would be nice.
Here's the code:
PassDialog dialog = new PassDialog(parent);
/* do some non gui related initialization */
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
Resolution: As @shemnon noted I should make a window instead of (null, Frame, Applet) parent of modal dialog. So good way to initlialize parent was:
parent = javax.swing.SwingUtilities.getWindowAncestor(theApplet);
A: Make a background Thread that calls toFront on the Dialog every 2 seconds.
Code that we use (I hope I got everything):
class TestClass {
protected void toFrontTimer(JFrame frame) {
try {
bringToFrontTimer = new java.util.Timer();
bringToFrontTask = new BringToFrontTask(frame);
bringToFrontTimer.schedule( bringToFrontTask, 300, 300);
} catch (Throwable t) {
t.printStackTrace();
}
}
class BringToFrontTask extends TimerTask {
private Frame frame;
public BringToFrontTask(Frame frame) {
this.frame = frame;
}
public void run()
{
if(count < 2) {
frame.toFront();
} else {
cancel();
}
count ++;
}
private int count = 0;
}
public void cleanup() {
if(bringToFrontTask != null) {
bringToFrontTask.cancel();
bringToFrontTask = null;
}
if(bringToFrontTimer != null) {
bringToFrontTimer = null;
}
}
java.util.Timer bringToFrontTimer = null;
java.util.TimerTask bringToFrontTask = null;
}
A: This is a shot in the dark as I'm not familiar with applets, but you could take a look at IE's built-in window.showModalDialog method. It's fairly easy to use. Maybe a combination of this and Noah's suggestion?
A: What argument are you using for the parent?
You may have better luck if you use the parent of the Applet.
javax.swing.SwingUtilities.getWindowAncestor(theApplet)
Using the getWindowAncestor will skip the applet parents (getRoot(component) will return applets). In at least some versions of Java there was a Frame that was equivalent to the IE window. YMMV.
A: You might try launching a modal from JavaScript using the JavaScript integration (see http://www.raditha.com/java/mayscript.php for an example).
The JavaScript you would need would be something like:
function getPassword() {
return prompt("Enter Password");
}
And the Java would be:
password = jso.call("getPassword", new String[0]);
Unfortunately that means giving up all hope of having a nice looking modal. Good luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How much data can/should you store in a users session object? We have several wizard style form applications on our website where we capture information from the user on each page and then submit to a backend process using a web service.
Unfortunately we can't submit the information in chunks during each form submission so we have to store it the users session until the end of the process and submit it all at the same time.
Is the amount of server memory/sql server disk space the only constraint on how much I can store in users sessions or is there something else I need to consider?
Edit: The site is built on ASP.NET web forms.
A: Assuming the information is not sensitive then you could store the information in a cookie which would reduce the amount of information required to be stored server side. This would also allow you to access the information via JavaScript.
Alternatively you could use the viewstate to store the information although this can lead to large amounts of data being sent between the server and the client and not my preferred solution.
The amount of session information you should store varies wildly depending on the application, number of expected users, server specification etc. To give a more accurate answer would require more information :)
Finally, assuming that the information collected throughout the process is not required from page to page then you could store all the information in a database table and only store the records unique id in the session. As each page is submitted the db record is updated and then on the final page all the information is retrieved and submitted. This is not an idea solution if you need to retrieve previous information on each subsequent page due to the number of db reads required.
A: You could also have 1 asp page with the entire html form, and hide parts of it until the user fill and "submits" the visible part...
then simply hide the part that is filled out and show the next part of the form...
This would be extremely easy in the .NET framework, use panels for each "wizard step" and add loggic when to display and hide each panel.
you will then have all the data on one page.
A: If you use a traditional HTTP model (i.e. don't use runat="server") you can post the data to another asp page and place the posted data into hidden form elements, you can do this for however many pages you need thus avoiding placing anything in a session variable.
A: Since it is problematic from performance point of view to store large amounts of data in user Session object, ASP.Net provides some other workarounds on top of what is mentioned in the posts above. ASP.NET Profile Provider allows you to persist session related information in a database. You can also use Session State Server which uses a separate server to store all Session information. Both of these situations take into account if you need to use clusters or load balancers, the servers can still recognize the session information across different servers. If you store information in the Http Session object, you run into the problem that one user must always go to the same server for that session.
A: Session, viewstate, database. These are all slow but will get the job done.
Hidden form fields is the answer I like best.
There are other ways to persist state. Cookies, popup window, frameset or iframes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: CodeFile vs CodeBehind What is the difference between CodeFile="file.ascx.cs" and CodeBehind="file.ascx.cs" in the declaration of a ASP.NET user control?
Is one newer or recommended? Or do they have specific usage?
A: I'm working with an Application Project in Visual Studio Express 2012 For Web and using .NET 4.0. In the code behind files for my login and change password pages I found a situation where I needed both CodeBehind and CodeFile in the declaration.
If I don't add a code file reference like
CodeFile=login.aspx.cs
The web page doesn't parse and the browser displays a parser error. It doesn't matter whether I compile the project or not.
If I don't add a code behind reference like
CodeBehind=login.aspx.cs
References to Security classes like MembershipUser fail both at compile time and when attempting to use intellisense with an error like "The type or namespace MembershipUser cannot be found". I have added a reference to System.Web.ApplicationServices as required by the .Net 4.0 framework.
I should add that these troublesome files are running in an application within the website created using the IIS Application tool. When I open the website from Visual Studio I have no difficulty with parser errors or reference errors. This confusion only occurs when I open the application as a project in Visual Studio.
A: Codebehind file need to compile before run but in src we dont need to compile and then run.. just save the file.
A: CodeBehind: Needs to be compiled (ASP.NET 1.1 model). The compiled binary is placed in the bin folder of the website. You need to do a compile in Visual Studio before you deploy. It's a good model when you don't want the source code to be viewable as plain text. For example when delivering to a customer to whom you don't have an obligation to provide code.
CodeFile: You provide the source file with the solution for deployment. ASP.NET 2.0 runtime compiles the code when needed. The compiled files are at Microsoft.NET[.NET version]\Temporary ASP.NET Files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "147"
}
|
Q: What is this delegate call doing in this line of code (C#)? This is from an example accompanying the agsXMPP .Net assembly. I've read up on delegates, but am not sure how that fits in with this line of code (which waits for the logon to occur, and then sends a message. I guess what I'm looking for is an understanding of why delegate(0) accomplishes this, in the kind of simple terms I can understand.
xmpp.OnLogin += delegate(object o) {
xmpp.Send(new Message(new Jid(JID_RECEIVER),
MessageType.chat,
"Hello, how are you?"));
};
A: It's exactly the same as
xmpp.OnLogin += EventHandler(MyMethod);
Where MyMethod is
public void MyMethod(object o)
{
xmpp.Send(new Message(new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?"));
}
A: As Abe noted, this code is creating an anonymous function. This:
xmpp.OnLogin += delegate(object o)
{
xmpp.Send(
new Message(new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?"));
};
would have been accomplished as follows in older versions of .Net (I've excluded class declarations and such, and just kept the essential elements):
delegate void OnLoginEventHandler(object o);
public void MyLoginEventHandler(object o)
{
xmpp.Send(
new Message(new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?"));
}
[...]
xmpp.OnLogin += new OnLoginEventHandler(MyLoginEventHandler);
What you're doing in either case is associating a method of yours to run when the xmpp OnLogin event is fired.
A: OnLogin on xmpp is probably an event declared like this :
public event LoginEventHandler OnLogin;
where LoginEventHandler is as delegate type probably declared as :
public delegate void LoginEventHandler(Object o);
That means that in order to subscribe to the event, you need to provide a method (or an anonymous method / lambda expression) which match the LoginEventHandler delegate signature.
In your example, you pass an anonymous method using the delegate keyword:
xmpp.OnLogin += delegate(object o)
{
xmpp.Send(new Message(new Jid(JID_RECEIVER),
MessageType.chat,
"Hello, how are you?"));
};
The anonymous method matches the delegate signature expected by the OnLogin event (void return type + one object argument). You could also remove the object o parameter leveraging the contravariance, since it is not used inside the anonymous method body.
xmpp.OnLogin += delegate
{
xmpp.Send(new Message(new Jid(JID_RECEIVER),
MessageType.chat,
"Hello, how are you?"));
};
A: The delegate(object o){..} tells the compiler to package up whatever is inside the brackets as an object to be executed later, in this case when OnLogin is fired. Without the delegate() statement, the compiler would think you are tying to execute an action in the middle of an assignemnt statement and give you errors.
A: That is creating an anonymous function. This feature was introduced in C# 2.0
A: It serves as an anonymous method, so you don't need to declare it somewhere else. It's very useful.
What it does in that case is to attach that method to the list of actions that are triggered because of the onLogin event.
A: Agreed with Abe, this is an anonymous method. An anonymous method is just that -- a method without a name, which can be supplied as a parameter argument.
Obviously the OnLogin object is an Event; using an += operator ensures that the method specified by the anonymous delegate above is executed whenever the OnLogin event is raised.
A: Basically, the code inside the {} will run when the "OnLogin" event of the xmpp event is fired. Based on the name, I'd guess that event fires at some point during the login process.
The syntax:
delegate(object o) { statements; }
is a called an anonymous method. The code in your question would be equivilent to this:
public class MyClass
{
private XMPPObjectType xmpp;
public void Main()
{
xmpp.OnLogin += MyMethod;
}
private void MyMethod(object o)
{
xmpp.Send(new Message(new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?"));
}
}
A: You are subscribing to the OnLogin event in xmpp.
This means that when xmpp fires this event, the code inside the anonymous delegate will fire. Its an elegant way to have callbacks.
In Xmpp, something like this is going on:
// Check to see if we should fire the login event
// ALso check to see if anything is subscribed to OnLogin
// (It will be null otherwise)
if (loggedIn && OnLogin != null)
{
// Anyone subscribed will now receive the event.
OnLogin(this);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Embedded Jetty serving static content with form authentication I try to use the Forms-Based authentication within an embedded Jetty 6.1.7 project.
That's why I need to serve servlets and html (login.html) under the same context
to make authentication work. I don't want to secure the hole application since
different context should need different roles. The jetty javadoc states that a
ContextHandlerCollection can handle different handlers for one context but I don't
get it to work. My sample ignoring the authentication stuff will not work, why?
ContextHandlerCollection contexts = new ContextHandlerCollection();
// serve html
Context ctxADocs= new Context(contexts,"/ctxA",Context.SESSIONS);
ctxADocs.setResourceBase("d:\\tmp\\ctxA");
ServletHolder ctxADocHolder= new ServletHolder();
ctxADocHolder.setInitParameter("dirAllowed", "false");
ctxADocHolder.setServlet(new DefaultServlet());
ctxADocs.addServlet(ctxADocHolder, "/");
// serve a sample servlet
Context ctxA = new Context(contexts,"/ctxA",Context.SESSIONS);
ctxA.addServlet(new ServletHolder(new SessionDump()), "/sda");
ctxA.addServlet(new ServletHolder(new DefaultServlet()), "/");
contexts.setHandlers(new Handler[]{ctxA, ctxADocs});
// end of snippet
Any helpful thought is welcome!
Thanks.
Okami
A: Finally I got it right, solution is to use latest jetty 6.1.12 rc2.
I didn't check out what they changed - I'm just happy that it works now.
A: Use the web application descriptor:
Paste this in to your web.xml:
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
<security-role>
<role-name>MySiteRole</role-name>
</security-role>
<security-constraint>
<display-name>ProtectEverything</display-name>
<web-resource-collection>
<web-resource-name>ProtectEverything</web-resource-name>
<url-pattern>*.*</url-pattern>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>MySiteRole</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<web-resource-collection>
<web-resource-name>ExcludeLoginPage</web-resource-name>
<url-pattern>/login.html</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
Without authentication this will hide everything but the login.html.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I sort by multiple conditions with different orders? I'd really like to handle this without monkey-patching but I haven't been able to find another option yet.
I have an array (in Ruby) that I need to sort by multiple conditions. I know how to use the sort method and I've used the trick on sorting using an array of options to sort by multiple conditions. However, in this case I need the first condition to sort ascending and the second to sort descending. For example:
ordered_list = [[1, 2], [1, 1], [2, 1]]
Any suggestions?
Edit: Just realized I should mention that I can't easily compare the first and second values (I'm actually working with object attributes here). So for a simple example it's more like:
ordered_list = [[1, "b"], [1, "a"], [2, "a"]]
A: I was having a nightmare of a time trying to figure out how to reverse sort a specific attribute but normally sort the other two. Just a note about the sorting for those that come along after this and are confused by the |a,b| block syntax. You cannot use the {|a,b| a.blah <=> b.blah} block style with sort_by! or sort_by. It must be used with sort! or sort. Also, as indicated previously by the other posters swap a and b across the comparison operator <=> to reverse the sort order. Like this:
To sort by blah and craw normally, but sort by bleu in reverse order do this:
something.sort!{|a,b| [a.blah, b.bleu, a.craw] <=> [b.blah, a.bleu, b.craw]}
It is also possible to use the - sign with sort_by or sort_by! to do a reverse sort on numerals (as far as I am aware it only works on numbers so don't try it with strings as it just errors and kills the page).
Assume a.craw is an integer. For example:
something.sort_by!{|a| [a.blah, -a.craw, a.bleu]}
A: I had this same basic problem, and solved it by adding this:
class Inverter
attr_reader :o
def initialize(o)
@o = o
end
def <=>(other)
if @o.is && other.o.is
-(@o <=> other.o)
else
@o <=> other.o
end
end
end
This is a wrapper that simply inverts the <=> function, which then allows you to do things like this:
your_objects.sort_by {|y| [y.prop1,Inverter.new(y.prop2)]}
A: Enumerable#multisort is a generic solution that can be applied to arrays of any size, not just those with 2 items. Arguments are booleans that indicate whether a specific field should be sorted ascending or descending (usage below):
items = [
[3, "Britney"],
[1, "Corin"],
[2, "Cody"],
[5, "Adam"],
[1, "Sally"],
[2, "Zack"],
[5, "Betty"]
]
module Enumerable
def multisort(*args)
sort do |a, b|
i, res = -1, 0
res = a[i] <=> b[i] until !res.zero? or (i+=1) == a.size
args[i] == false ? -res : res
end
end
end
items.multisort(true, false)
# => [[1, "Sally"], [1, "Corin"], [2, "Zack"], [2, "Cody"], [3, "Britney"], [5, "Betty"], [5, "Adam"]]
items.multisort(false, true)
# => [[5, "Adam"], [5, "Betty"], [3, "Britney"], [2, "Cody"], [2, "Zack"], [1, "Corin"], [1, "Sally"]]
A: How about:
ordered_list = [[1, "b"], [1, "a"], [2, "a"]]
ordered_list.sort! do |a,b|
[a[0],b[1]] <=> [b[0], a[1]]
end
A: I've been using Glenn's recipe for quite a while now. Tired of copying code from project to project over and over again, I've decided to make it a gem:
http://github.com/dadooda/invert
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: What's the best approach to embed RegEx in Oracle or SQL Server 2005 SQL? This is a 3 part question regarding embedded RegEx into SQL statements.
*
*How do you embed a RegEx expression into an Oracle PL/SQL
select statement that will parse out
the “DELINQUENT” string in the text
string shown below?
*What is the performance impact if used within a
mission critical business
transaction?
*Since embedding regex
into SQL was introduced in Oracle
10g and SQL Server 2005, is it
considered a recommended practice?
Dear Larry :
Thank you for using ABC's alert service.
ABC has detected a change in the status of one of your products in the state of KS. Please review the
information below to determine if this status change was intended.
ENTITY NAME: Oracle Systems, LLC
PREVIOUS STATUS: --
CURRENT STATUS: DELINQUENT
As a reminder, you may contact your the ABC Team for assistance in correcting any delinquencies or, if needed, reinstating
the service. Alternatively, if the system does not intend to continue to engage this state, please notify ABC
so that we can discontinue our services.
Kind regards,
Service Team 1
ABC
--PLEASE DO NOT REPLY TO THIS EMAIL. IT IS NOT A MONITORED EMAIL ACCOUNT.--
Notice: ABC Corporation cannot independently verify the timeliness, accuracy, or completeness of the public information
maintained by the responsible government agency or other sources of data upon which these alerts are based.
A: Why would you need regular expressions here?
INSTR and SUBSTR will do the job perfectly.
But if you convinced you need Regex'es you can use:
REGEXP_INSTR
REGEXP_REPLACE
REGEXP_SUBSTR
(only available in Oracle 10g and up)
SELECT emp_id, text
FROM employee_comment
WHERE REGEXP_LIKE(text,'...-....');
A: If I recall correctly, it is possible to write a UDF in c#/vb for SQL Server.
Here's a link, though possibly not the best: http://www.novicksoftware.com/coding-in-sql/Vol3/cis-v3-N13-dot-net-clr-in-sql-server.htm
A: Why not just use INSTR (for Oracle) or CHARINDEX (for SQL Server) combined with SUBSTRING? Seems a bit more straightforward (and portable, since it's supported in older versions).
http://www.techonthenet.com/oracle/functions/instr.php and http://www.adp-gmbh.ch/ora/sql/substr.html
http://www.databasejournal.com/features/mssql/article.php/3071531 and http://msdn.microsoft.com/en-us/library/ms187748.aspx
A: INSTR and CHARINDEX are great alternative approaches but I'd like to explore the benefits of embedding Regex.
A: In MS SQL you can use LIKE which has some "pattern matching" in it. I would guess Oracle has something similar. Its not Regex, but has some of the matching capabilities. (Note: its not particularly fast).. Fulltext searching could also be an option (again MS SQL) (probably a much faster way in the context of a good sized database)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What's the best way to handle long running process in an ASP.Net application? In my web application there is a process that queries data from all over the web, filters it, and saves it to the database. As you can imagine this process takes some time. My current solution is to increase the page timeout and give an AJAX progress bar to the user while it loads. This is a problem for two reasons - 1) it still takes to long and the user must wait 2) it sometimes still times out.
I've dabbled in threading the process and have read I should async post it to a web service ("Fire and forget").
Some references I've read:
- MSDN
- Fire and Forget
So my question is - what is the best method?
UPDATE: After the user inputs their data I would like to redirect them to the results page that incrementally updates as the process is running in the background.
A: To avoid excessive architecture astronomy, I often use a hidden iframe to call the long running process and stream back progress information. Coupled with something like jsProgressBarHandler, you can pretty easily create great out-of-band progress indication for longer tasks where a generic progress animation doesn't cut it.
In your specific situation, you may want to use one LongRunningProcess.aspx call per task, to avoid those page timeouts.
For example, call LongRunningProcess.aspx?taskID=1 to kick it off and then at the end of that task, emit a
document.location = "LongRunningProcess.aspx?taskID=2".
Ad nauseum.
A: We had a similar issue and solved it by starting the work via an asychronous web service call (which meant that the user did not have to wait for the work to finish). The web service then started a SQL Job which performed the work and periodically updated a table with the status of the work. We provided a UI which allowed the user to query the table.
A: I ran into this exact problem at my last job. The best way I found was to fire off an asychronous process, and notify the user when it's done (email or something else). Making them wait that long is going to be problematic because of timeouts and wasted productivity for them. Having them wait for a progress bar can give them false sense of security that they can cancel the process when they close the browser which may not be the case depending on how you set up the system.
A: *
*How are you querying the remote data?
*How often does it change?
*Are the results something that could be cached for a period of time?
*How long a period of time are we actually talking about here?
The 'best method' is likely to depend in some way on the answers to these questions...
A: You can create another thread and store a reference to the thread in the session or application state, depending on wether the thread can run only once per website, or once per user session.
You can then redirect the user to a page where he can monitor the threads progress. You can set the page to refresh automatically, or display a refresh button to the user.
Upon completion of the thread, you can send an email to the user.
A: My solution to this, has been an out of band service that does these and caches them in db.
When the person asks for something the first time, they get a bit of a wait, and then it shows up but if they refresh, its immediate, and then, because its int he db, its now part of the hourly update for the next 24 hours from the last request.
A: Add the job, with its relevant parameters, to a job queue table. Then, write a windows service that will pick up these jobs and process them, save the results to an appropriate location, and email the requester with a link to the results. It is also a nice touch to give some sort of a UI so the user can check the status of their job(s).
This way is much better than launching a seperate thread or increasing the timeout, especially if your application is larger and needs to scale, as you can simply add multiple servers to process jobs if necessary.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What's the best way to organize code? I'm not talking about how to indent here. I'm looking for suggestions about the best way of organizing the chunks of code in a source file.
Do you arrange methods alphabetically? In the order you wrote them? Thematically? In some kind of 'didactic' order?
What organizing principles do you follow? Why?
A: i normally order by the following
*
*constructors
*destructors
*getters
*setters
*any 'magic' methods
*methods for changing the persisted state of reciever (save() etc)
*behaviors
*public helper methods
*private/protected helper methods
*anything else (although if there is anything else its normally a sign that some refactoring is necessary)
A: I tend to use following pattern:
*
*public static final variables
*static functions, static blocks
*variables
*constructors
*functions that do something related to logic
*getters and setters (are uninteresing mostly so there is no need to read them)
I'm have no pattern of including local classes, and mostly I put them on top of first method that uses them.
I don't like separating methods depending on access level. If some public method uses some private method they will be close to one another.
A: I tend to group methods that relate to each other. Use of a good IDE removes much of this concern. Alphabetizing methods seems like a waste of effort to me.
A: I group them based on what there doing, and then in the order I wrote them (alphabetically would probs be better though)
eg in texture.cpp I have:
//====(DE)CONSTRUCTOR====
...
//====LOAD FUNCTIONS====
...
//====SAVE FUNCTIONS====
...
//====RESOURCE MANGEMENT FUNCTIONS====
//(preventing multiple copies being loaded etc)
...
//====UTILL FUNCTIONS====
//getting texture details, etc
...
//====OVERLOADED OPERTORS====
....
A: Pretty much use this approach for anything I am coding in. Good structure and well commented code makes good reading
*
*Global Variables
*Functions
*Main Body/Method
A: public, protected and then private and within each section alphabetically although I often list constructor first and deconstructor last.
/Allan
A: I tend to group things thematically for lack of a better word.
For example, if I had a public method that used two private methods in the course of doing its work then I would group all three together in the implementation file since odds are good that if you're going to be looking at one of them then you'll need to look at one of the others.
I also always group get/set methods for a particular class member.
It's really personal preference, especially with modern IDEs since there are a lot of features that allow you to automatically jump to locations in the code.
A: I like to keep things simple, so I don't stuff a bunch of methods in a class. Within a class, I usually have the most commonly used (or modified-by-me ;-)) methods listed first. As far as specific code organization goes, each set of methods belongs to a class, so it organizes by itself.
I make use of my editor's search feature, and code folding to navigate through large source files. Similarly, I make use of search features to find things in other contexts too. A grand organization scheme never suited me, so I rely on the power of search in all things, not just code.
A: Interesting point. I hadn't really thought about this.
I tend to put frequently-accessed functions at the top (utility functions, and such), as they're most likely need tweaking.
I don't think organization is particularly important, as I can find any function quickly. I don't scroll through my file to find a function; I search for it.
In C++, I do expect that the functions in the .cpp file are in the same order in which they're declared in the .h file. Which is usually constructors, followed by destructors, followed by primary/central functionality functions, followed by utility functions.
A: I mostly write C code and I tend to order by dependency. If possible I try to match my source code file with me header files, but generally it's if void a() uses int b(char *foo), than int b(char *foo) comes first.
Saves me from adding entries to the header file for local functions.
For the rest it's mainly alphabetic actually, makes searching easier.
A: I have all the private fields, then the public, then the constructors, then the main, then the methods that main calls, in the order they are called.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to retrieve error when launching sqlcmd from C#? I need to run a stored procedure from a C# application.
I use the following code to do so:
Process sqlcmdCall = new Process();
sqlcmdCall.StartInfo.FileName = "sqlcmd.exe";
sqlcmdCall.StartInfo.Arguments = "-S localhost\\SQLEXPRESS -d some_db -Q \":EXIT(sp_test)\""
sqlcmdCall.Start();
sqlcmdCall.WaitForExit();
From the sqlcmdCall object after the call completes, I currently get an ExitCode of -100 for success and of 1 for failure (i.e. missing parameter, stored proc does not exist, etc...).
How can I customize these return codes?
H.
A: I have a small VB.Net app that executes system commands like that. To capture error or success conditions I define regular expressions to match the error text output from the command and I capture the output like this:
myprocess.Start()
procReader = myprocess.StandardOutput()
While (Not procReader.EndOfStream)
procLine = procReader.ReadLine()
If (MatchesRegEx(errRegEx, procLine)) Then
writeDebug("Error reg ex: [" + errorRegEx + "] has matched: [" + procLine + "] setting hasError to true.")
Me.hasError = True
End If
writeLog(procLine)
End While
procReader.Close()
myprocess.WaitForExit(CInt(waitTime))
That way I can capture specific errors and also log all the output from the command in case I run across an unexpected error.
A: If you are trying to call a stored procedure from c# you would want to use ADO.Net instead of the calling sqlcmd via the command line. Look at SqlConnection and SqlCommand in the System.Data.SqlClient namespace.
Once you are calling the stored procedure via SqlCommand you will be able to catch an exception raised by the stored procedure as well we reading the return value of the procedure if you need to.
A: Even with windows authentication you can still use SqlCommand and SqlConnection to execute, and you don't have to re-invent the wheel for exception handling.
A simple connection configuration and a single SqlCommand can execute it without issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I add Debug Breakpoints to lines displayed in a "Find Results" window in Visual Studio In Visual Studio 2005-2015 it is possible to find all lines containing certain references and display them in a "Find Results" window.
Now that these result lines are displayed, is there any keyboard shortcut that would allow adding debug breakpoints to all of them?
A: If you can search for the word exactly, you can use a pair of keyboard shortcuts to do it quickly.
Tools -> Options -> Enviroment -> Keyboard
*
*Edit.GoToFindResults1NextLocation
*EditorContextMenus.CodeWindow.Breakpoint.InsertBreakpoint
Assign them to Control+Alt+F11 and F10 and you can go through all the results very quickly. I haven't found a shortcut for going to the next reference however.
A: I needed something similar to disable all breakpoints and place a breakpoint on every "Catch ex as Exception". However, I expanded this a little so it will place a breakpoint at every occurance of the string you have selected. All you need to do with this is highlight the string you want to have a breakpoint on and run the macro.
Sub BreakPointAtString()
Try
DTE.ExecuteCommand("Debug.DisableAllBreakpoints")
Catch ex As Exception
End Try
Dim tsSelection As String = DTE.ActiveDocument.Selection.text
DTE.ActiveDocument.Selection.selectall()
Dim AllText As String = DTE.ActiveDocument.Selection.Text
Dim findResultsReader As New StringReader(AllText)
Dim findResult As String = findResultsReader.ReadLine()
Dim lineNum As Integer = 1
Do Until findResultsReader.Peek = -1
lineNum += 1
findResult = findResultsReader.ReadLine()
If Trim(findResult) = Trim(tsSelection) Then
DTE.ActiveDocument.Selection.GotoLine(lineNum)
DTE.ExecuteCommand("Debug.ToggleBreakpoint")
End If
Loop
End Sub
Hope it works for you :)
A: This answer does not work for Visual Studio 2015 or later. A more recent answer can be found here.
You can do this fairly easily with a Visual Studio macro. Within Visual Studio, hit Alt-F11 to open the Macro IDE and add a new module by right-clicking on MyMacros and selecting Add|Add Module...
Paste the following in the source editor:
Imports System
Imports System.IO
Imports System.Text.RegularExpressions
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Public Module CustomMacros
Sub BreakpointFindResults()
Dim findResultsWindow As Window = DTE.Windows.Item(Constants.vsWindowKindFindResults1)
Dim selection As TextSelection
selection = findResultsWindow.Selection
selection.SelectAll()
Dim findResultsReader As New StringReader(selection.Text)
Dim findResult As String = findResultsReader.ReadLine()
Dim findResultRegex As New Regex("(?<Path>.*?)\((?<LineNumber>\d+)\):")
While Not findResult Is Nothing
Dim findResultMatch As Match = findResultRegex.Match(findResult)
If findResultMatch.Success Then
Dim path As String = findResultMatch.Groups.Item("Path").Value
Dim lineNumber As Integer = Integer.Parse(findResultMatch.Groups.Item("LineNumber").Value)
Try
DTE.Debugger.Breakpoints.Add("", path, lineNumber)
Catch ex As Exception
' breakpoints can't be added everywhere
End Try
End If
findResult = findResultsReader.ReadLine()
End While
End Sub
End Module
This example uses the results in the "Find Results 1" window; you might want to create an individual shortcut for each result window.
You can create a keyboard shortcut by going to Tools|Options... and selecting Keyboard under the Environment section in the navigation on the left. Select your macro and assign any shortcut you like.
You can also add your macro to a menu or toolbar by going to Tools|Customize... and selecting the Macros section in the navigation on the left. Once you locate your macro in the list, you can drag it to any menu or toolbar, where it its text or icon can be customized to whatever you want.
A: Paul, thanks a lot, but I have the following error (message box), may be I need to restart my PC:
Error
---------------------------
Error HRESULT E_FAIL has been returned from a call to a COM component.
---------------------------
OK
---------------------------
I would propose the following solution that's very simple but it works for me
Sub BreakPointsFromSearch()
Dim n As Integer = InputBox("Enter the number of search results")
For i = 1 To n
DTE.ExecuteCommand("Edit.GoToNextLocation")
DTE.ExecuteCommand("Debug.ToggleBreakpoint")
Next
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Report templates for Team Foundation Server 2008 Does anybody have links to site or pre built report running on the SQL Analysis Service provided by TFS2008?
Creating a meaningful Excel report or a new report sometime is a very boring and difficult taks, maybe finding a way to share reports could be a good idea?
A: Try this download: Creating and Customizing TFS Reports, it includes a few samples and some guidance. More here.
Also try the TFS Reporting Samples.zip linked from this site.
This site links to a large number of TFS reporting resources:
http://blogs.msdn.com/teams_wit_tools/archive/2007/03/26/tfs-report-developer-resources.aspx
A: If you are using SCRUM, this has Sprint reports and Product Burndown reports:
http://www.scrumforteamsystem.com/en/default.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How does one unit test sections of code that are procedural or event-based I'm convinced from this presentation and other commentary here on the site that I need to learn to Unit Test. I also realize that there have been many questions about what unit testing is here. Each time I go to consider how it should be done in the application I am currently working on, I walk away confused. It is a xulrunner application application, and a lot of the logic is event-based - when a user clicks here, this action takes place.
Often the examples I see for testing are testing classes - they instantiate an object, give it mock data, then check the properties of the object afterward. That makes sense to me - but what about the non-object-oriented pieces?
This guy mentioned that GUI-based unit testing is difficult in most any testing framework, maybe that's the problem. The presentation linked above mentions that each test should only touch one class, one method at a time. That seems to rule out what I'm trying to do.
So the question - how does one unit testing procedural or event-based code? Provide a link to good documentation, or explain it yourself.
On a side note, I also have a challenge of not having found a testing framework that is set up to test xulrunner apps - it seems that the tools just aren't developed yet. I imagine this is more peripheral than my understanding the concepts, writing testable code, applying unit testing.
A: The idea of unit testing is to test small sections of code with each test. In an event based system, one form of unit testing you could do, would be to test how your event handlers respond to various events. So your unit test might set an aspect of your program into a specific state, then call the event listener method directly, and finally test the subsequent state of of your program.
If you plan on unit testing an event-based system, you will make your life a lot easier for yourself if you use the dependency injection pattern and ideally would go the whole way and use inversion of control (see http://martinfowler.com/articles/injection.html and http://msdn.microsoft.com/en-us/library/aa973811.aspx for details of these patterns)
(thanks to pc1oad1etter for pointing out I'd messed up the links)
A: At first I would test events like this:
private bool fired;
private void HandlesEvent(object sender, EventArgs e)
{
fired = true;
}
public void Test()
{
class.FireEvent += HandlesEvent;
class.PErformEventFiringAction(null, null);
Assert.IsTrue(fired);
}
And Then I discovered RhinoMocks.
RhinoMocks is a framework that creates mock objects and it also handles event testing. It may come in handy for your procedural testing as well.
A: Answering my own question here, but I came across an article that take explains the problem, and does a walk-through of a simple example -- Agile User Interface Development. The code and images are great, and here is a snippet that shows the idea:
Agile gurus such as Kent Beck and
David Astels suggest building the GUI
by keeping the view objects very thin,
and testing the layers "below the
surface." This "smart object/thin
view" model is analogous to the
familiar document-view and
client-server paradigms, but applies
to the development of individual GUI
elements. Separation of the content
and presentation improves the design
of the code, making it more modular
and testable. Each component of the
user interface is implemented as a
smart object, containing the
application behavior that should be
tested, but no GUI presentation code.
Each smart object has a corresponding
thin view class containing only
generic GUI behavior. With this design
model, GUI building becomes amenable
to TDD.
A: The problem is that "event based programming" links far too much logic to the events. The way such a system should be designed is that there should be a subsystem that raises events (and you can write tests to ensure that these events are raised in the proper order). And there should be another subsystem that deals only with managing, say, the state of a form. And you can write a unit test that will verify that given the correct inputs (ie. events being raised), will set the form state to the correct values.
Beyond that, the actual event handler that is raised from component 1, and calls the behavior on component 2 is just integration testing which can be done manually by a QA person.
A: Your question doesn't state your programming language of choice, but mine is C# so I'll exemplify using that. This is however just a refinement over Gilligans answer by using anonymous delegates to inline your test code. I'm all in favor of making tests as readable as possible, and to me that means all test code within the test method;
// Arrange
var car = new Car();
string changedPropertyName = "";
car.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
{
if (sender == car)
changedPropertyName = e.PropertyName;
};
// Act
car.Model = "Volvo";
// Assert
Assert.AreEqual("Model", changedPropertyName,
"The notification of a property change was not fired correctly.");
The class I'm testing here implements the INotifyPropertyChanged interface and therefore a NotifyPropertyChanged event should be raised whenever a property's value has changed.
A: An approach I've found helpful for procedural code is to use TextTest. It's not so much about unit testing, but it helps you do automated regression testing. The idea is that you have your application write a log then use texttest to compare the log before and after your changes.
A: See the oft-linked Working Effectively with Legacy Code. See the sections titled "My Application Is All API Calls" and "My Project is Not Object-Oriented. How Do I Make Safe Changes?".
In C/C++ world (my experience) the best solution in practice is to use the linker "seam" and link against test doubles for all the functions called by the function under test. That way you don't change any of the legacy code, but you can still test it in isolation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Three column web design with variable sides I've been trying to come up with a way to create a 3 column web design where the center column has a constant width and is always centered. The columns to the left and right are variable. This is trivial in tables, but not correct semantically.
I haven't been able to get this working properly in all current browsers. Any tips on this?
A: Use this technique, and simply specify a fixed width for the centre column.
A: Check this out: http://www.glish.com/css/2.asp
And replace the width: xx% for #maincenter by a fixed value. Seems to work when I change it with Firebug, worth a shot?
#maincenter {
width: 200px;
float: left;
background: #fff;
padding-bottom: 10px;
}
A: I think you'd need to start off with initial (fixed) widths for both sidebar columns and then, when the page loads, use javascript to get the window width and calculate the new width of the sidebars.
sidebar width = (window width - center column width) / 2
You could then reapply the javascript if the window is resized.
A: This article at A List Apart has a solution resulting in a 3-column layout that will :
*
*have a fluid center with fixed width sidebars,
*allow the center column to appear first in the source,
*allow any column to be the tallest,
*require only a single extra div of markup, and
*require very simple CSS, with minimal patches.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: X/Gnome: How to measure the geometry of an open window Is there a standard X / Gnome program that will display the X,Y width and depth in pixels of a window that I select? Something similar to the way an xterm shows you the width and depth of the window (in lines) as you resize it.
I'm running on Red Hat Enterprise Linux 4.4.
Thanks!
A: $ xwininfo
xwininfo: Please select the window about which you
would like information by clicking the
mouse in that window.
xwininfo: Window id: 0x1200007 "xeyes"
Absolute upper-left X: 1130
Absolute upper-left Y: 0
Relative upper-left X: 0
Relative upper-left Y: 0
Width: 150
Height: 100
Depth: 24
Visual Class: TrueColor
Border width: 0
Class: InputOutput
Colormap: 0x20 (installed)
Bit Gravity State: NorthWestGravity
Window Gravity State: NorthWestGravity
Backing Store State: NotUseful
Save Under State: no
Map State: IsViewable
Override Redirect State: no
Corners: +1130+0 -0+0 -0-924 +1130-924
-geometry 150x100-0+0
A: Yes, you're looking for the program 'xwininfo'. Run it in another terminal and then click on the window you want info about and it will give it to you.
Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: How to implement a simple auto-complete functionality? I'd like to implement a simple class (in Java) that would allow me to register and deregister strings, and on the basis of the current set of strings auto-complete a given string. So, the interface would be:
*
*void add(String)
*void remove(String)
*String complete(String)
What's the best way to do this in terms of algorithms and data-structures?
A: you should consider to use a PATRICIA trie for the data structure. Search for 'patricia trie' on google and you'll find a lot of information...
A: The datastructure you are after is called a Ternary Search Tree.
There's a great JavaWorld example at www.javaworld.com/javaworld/jw-02-2001/jw-0216-ternary.html
A: It would have to be some kind of a List that you can maintain in sorted order. You would also have to write your own search algorithm that would give you the index of the first element in the list that matches your search pattern. Then iterate from that index until the first element that doesn't match and you have your list of possible completions.
I'd look at TreeList from commons-collections. It has fast insert and remove times from the middle of the List which you'll want in order to maintain sorted order. It would probably be fairly easy to write your search function off of the tree that backs that list.
A: For those who stumble upon this question...
I just posted a server-side autocomplete implementation on Google Code. The project includes a java library that can be integrated into existing applications and a standalone HTTP AJAX autocomplete server.
My hope is that enables people to incorporate efficient autocomplete into their applications. Kick the tires!
A: I have created a JQuery plugin called Simple AutoComplete, that allows you to add many autocomplete as you want on the same page, and to add filters with extra param, and execute a callback function to bring other params, like the id of the item.
See it at http://www.idealmind.com.br/projetos/simple-autocomplete-jquery-plugin/
A: Regular expressions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to fix MySQL Data Truncation Error when inserting a lot of data? I'm working with a fairly simple database, from a Java application. We're trying to insert about 200k of text at a time, using the standard JDBC mysql adapter. We intermittently get a com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column error.
The column type is longtext, and database collation is UTF-8. The error shows up using both MyISAM and InnoDB table engines. Max packet size has been set ot 1 GB on both client and server sides, so that shouldn't be causing a problem, either.
A: Well you can make it ignore the error by doing an INSERT IGNORE which will just truncate the data and insert it anyway. (from http://dev.mysql.com/doc/refman/5.0/en/insert.html )
If you use the IGNORE keyword, errors
that occur while executing the INSERT
statement are treated as warnings
instead. For example, without IGNORE,
a row that duplicates an existing
UNIQUE index or PRIMARY KEY value in
the table causes a duplicate-key error
and the statement is aborted. With
IGNORE, the row still is not inserted,
but no error is issued. Data
conversions that would trigger errors
abort the statement if IGNORE is not
specified. With IGNORE, invalid values
are adjusted to the closest values and
inserted; warnings are produced but
the statement does not abort.
A: In mysql you can use MEDIUMTEXT or LONGTEXT field type for large text data
A: It sounds to me like you are trying to put too many bytes into a column. I ran across a very similar error with MySQL last night due to a bug in my code. I meant to do
foo.status = 'inactive'
but had actually typed
foo.state = 'inactive'
Where foo.state is supposed to be a two character code for a US State ( varchar(2) ). I got the same error as you. You might go look for a similar situation in your code.
A: Check that your UTF-8 data is all 3-byte Unicode. If you have 4-byte characters (legal in Unicode and Java, illegal in MySQL 5), it can throw this error when you try to insert them. This is an issue that should be fixed in MySQL 6.0.
A: I just hit this problem and solved it by removing all the non-standard ascii characters in my text (following the UTF-8 advice above).
I had the problem on a Debian 4, Java 5 system; but the same code worked fine with Ubuntu 9.04, Java 6. Both run MySql 5.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How can I show scrollbars on a System.Windows.Forms.TextBox only when the text doesn't fit? For a System.Windows.Forms.TextBox with Multiline=True, I'd like to only show the scrollbars when the text doesn't fit.
This is a readonly textbox used only for display. It's a TextBox so that users can copy the text out. Is there anything built-in to support auto show of scrollbars? If not, should I be using a different control? Or do I need to hook TextChanged and manually check for overflow (if so, how to tell if the text fits?)
Not having any luck with various combinations of WordWrap and Scrollbars settings. I'd like to have no scrollbars initially and have each appear dynamically only if the text doesn't fit in the given direction.
@nobugz, thanks, that works when WordWrap is disabled. I'd prefer not to disable wordwrap, but it's the lesser of two evils.
@André Neves, good point, and I would go that way if it was user-editable. I agree that consistency is the cardinal rule for UI intuitiveness.
A: I also made some experiments, and found that the vertical bar will always show if you enable it, and the horizontal bar always shows as long as it's enabled and WordWrap == false.
I think you're not going to get exactly what you want here. However, I believe that users would like better Windows' default behavior than the one you're trying to force. If I were using your app, I probably would be bothered if my textbox real-estate suddenly shrinked just because it needs to accomodate an unexpected scrollbar because I gave it too much text!
Perhaps it would be a good idea just to let your application follow Windows' look and feel.
A: There's an extremely subtle bug in nobugz's solution that results in a heap corruption, but only if you're using AppendText() to update the TextBox.
Setting the ScrollBars property from OnTextChanged will cause the Win32 window (handle) to be destroyed and recreated. But OnTextChanged is called from the bowels of the Win32 edit control (EditML_InsertText), which immediately thereafter expects the internal state of that Win32 edit control to be unchanged. Unfortunately, since the window is recreated, that internal state has been freed by the OS, resulting in an access violation.
So the moral of the story is: don't use AppendText() if you're going to use nobugz's solution.
A: I came across this question when I wanted to solve the same problem.
The easiest way to do it is to change to System.Windows.Forms.RichTextBox. The ScrollBars property in this case can be left to the default value of RichTextBoxScrollBars.Both, which indicates "Display both a horizontal and a vertical scroll bar when needed." It would be nice if this functionality were provided on TextBox.
A: I had some success with the code below.
public partial class MyTextBox : TextBox
{
private bool mShowScrollBar = false;
public MyTextBox()
{
InitializeComponent();
checkForScrollbars();
}
private void checkForScrollbars()
{
bool showScrollBar = false;
int padding = (this.BorderStyle == BorderStyle.Fixed3D) ? 14 : 10;
using (Graphics g = this.CreateGraphics())
{
// Calcualte the size of the text area.
SizeF textArea = g.MeasureString(this.Text,
this.Font,
this.Bounds.Width - padding);
if (this.Text.EndsWith(Environment.NewLine))
{
// Include the height of a trailing new line in the height calculation
textArea.Height += g.MeasureString("A", this.Font).Height;
}
// Show the vertical ScrollBar if the text area
// is taller than the control.
showScrollBar = (Math.Ceiling(textArea.Height) >= (this.Bounds.Height - padding));
if (showScrollBar != mShowScrollBar)
{
mShowScrollBar = showScrollBar;
this.ScrollBars = showScrollBar ? ScrollBars.Vertical : ScrollBars.None;
}
}
}
protected override void OnTextChanged(EventArgs e)
{
checkForScrollbars();
base.OnTextChanged(e);
}
protected override void OnResize(EventArgs e)
{
checkForScrollbars();
base.OnResize(e);
}
}
A: Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form. It's not quite perfect but ought to work for you.
using System;
using System.Drawing;
using System.Windows.Forms;
public class MyTextBox : TextBox {
private bool mScrollbars;
public MyTextBox() {
this.Multiline = true;
this.ReadOnly = true;
}
private void checkForScrollbars() {
bool scroll = false;
int cnt = this.Lines.Length;
if (cnt > 1) {
int pos0 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(0)).Y;
if (pos0 >= 32768) pos0 -= 65536;
int pos1 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(1)).Y;
if (pos1 >= 32768) pos1 -= 65536;
int h = pos1 - pos0;
scroll = cnt * h > (this.ClientSize.Height - 6); // 6 = padding
}
if (scroll != mScrollbars) {
mScrollbars = scroll;
this.ScrollBars = scroll ? ScrollBars.Vertical : ScrollBars.None;
}
}
protected override void OnTextChanged(EventArgs e) {
checkForScrollbars();
base.OnTextChanged(e);
}
protected override void OnClientSizeChanged(EventArgs e) {
checkForScrollbars();
base.OnClientSizeChanged(e);
}
}
A: What Aidan describes is almost exactly the UI scenario I am facing. As the text box is read only, I don't need it to respond to TextChanged. And I'd prefer the auto-scroll recalculation to be delayed so it's not firing dozens of times per second while a window is being resized.
For most UIs, text boxes with both vertical and horizontal scroll bars are, well, evil, so I'm only interested in vertical scroll bars here.
I also found that MeasureString produced a height that was actually bigger than what was required. Using the text box's PreferredHeight with no border as the line height gives a better result.
The following seems to work pretty well, with or without a border, and it works with WordWrap on.
Simply call AutoScrollVertically() when you need it, and optionally specify recalculateOnResize.
public class TextBoxAutoScroll : TextBox
{
public void AutoScrollVertically(bool recalculateOnResize = false)
{
SuspendLayout();
if (recalculateOnResize)
{
Resize -= OnResize;
Resize += OnResize;
}
float linesHeight = 0;
var borderStyle = BorderStyle;
BorderStyle = BorderStyle.None;
int textHeight = PreferredHeight;
try
{
using (var graphics = CreateGraphics())
{
foreach (var text in Lines)
{
var textArea = graphics.MeasureString(text, Font);
if (textArea.Width < Width)
linesHeight += textHeight;
else
{
var numLines = (float)Math.Ceiling(textArea.Width / Width);
linesHeight += textHeight * numLines;
}
}
}
if (linesHeight > Height)
ScrollBars = ScrollBars.Vertical;
else
ScrollBars = ScrollBars.None;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
finally
{
BorderStyle = borderStyle;
ResumeLayout();
}
}
private void OnResize(object sender, EventArgs e)
{
m_timerResize.Stop();
m_timerResize.Tick -= OnDelayedResize;
m_timerResize.Tick += OnDelayedResize;
m_timerResize.Interval = 475;
m_timerResize.Start();
}
Timer m_timerResize = new Timer();
private void OnDelayedResize(object sender, EventArgs e)
{
m_timerResize.Stop();
Resize -= OnResize;
AutoScrollVertically();
Resize += OnResize;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
}
|
Q: Making a game in C++ using parallel processing I wanted to "emulate" a popular flash game, Chrontron, in C++ and needed some help getting started. (NOTE: Not for release, just practicing for myself)
Basics:
Player has a time machine. On each iteration of using the time machine, a parallel state
is created, co-existing with a previous state. One of the states must complete all the
objectives of the level before ending the stage. In addition, all the stages must be able
to end the stage normally, without causing a state paradox (wherein they should have
been able to finish the stage normally but, due to the interactions of another state,
were not).
So, that sort of explains how the game works. You should play it a bit to really
understand what my problem is.
I'm thinking a good way to solve this would be to use linked lists to store each state,
which will probably either be a hash map, based on time, or a linked list that iterates
based on time. I'm still unsure.
ACTUAL QUESTION:
Now that I have some rough specs, I need some help deciding on which data structures to use for this, and why. Also, I want to know what Graphics API/Layer I should use to do this: SDL, OpenGL, or DirectX (my current choice is SDL). And how would I go about implementing parallel states? With parallel threads?
EDIT (To clarify more):
OS -- Windows (since this is a hobby project, may do this in Linux later)
Graphics -- 2D
Language -- C++ (must be C++ -- this is practice for a course next semester)
Q-Unanswered: SDL : OpenGL : Direct X
Q-Answered: Avoid Parallel Processing
Q-Answered: Use STL to implement time-step actions.
So far from what people have said, I should:
1. Use STL to store actions.
2. Iterate through actions based on time-step.
3. Forget parallel processing -- period. (But I'd still like some pointers as to how it
could be used and in what cases it should be used, since this is for practice).
Appending to the question, I've mostly used C#, PHP, and Java before so I wouldn't describe myself as a hotshot programmer. What C++ specific knowledge would help make this project easier for me? (ie. Vectors?)
A: What you should do is first to read and understand the "fixed time-step" game loop (Here's a good explanation: http://www.gaffer.org/game-physics/fix-your-timestep).
Then what you do is to keep a list of list of pairs of frame counter and action. STL example:
std::list<std::list<std::pair<unsigned long, Action> > > state;
Or maybe a vector of lists of pairs. To create the state, for every action (player interaction) you store the frame number and what action is performed, most likely you'd get the best results if action simply was "key <X> pressed" or "key <X> released":
state.back().push_back(std::make_pair(currentFrame, VK_LEFT | KEY_PRESSED));
To play back the previous states, you'd have to reset the frame counter every time the player activates the time machine and then iterate through the state list for each previous state and see if any matches the current frame. If there is, perform the action for that state.
To optimize you could keep a list of iterators to where you are in each previous state-list. Here's some pseudo-code for that:
typedef std::list<std::pair<unsigned long, Action> > StateList;
std::list<StateList::iterator> stateIteratorList;
//
foreach(it in stateIteratorList)
{
if(it->first == currentFrame)
{
performAction(it->second);
++it;
}
}
I hope you get the idea...
Separate threads would simply complicate the matter greatly, this way you get the same result every time, which you cannot guarantee by using separate threads (can't really see how that would be implemented) or a non-fixed time-step game loop.
When it comes to graphics API, I'd go with SDL as it's probably the easiest thing to get you started. You can always use OpenGL from SDL later on if you want to go 3D.
A: This sounds very similar to Braid. You really don't want parallel processing for this - parallel programming is hard, and for something like this, performance should not be an issue.
Since the game state vector will grow very quickly (probably on the order of several kilobytes per second, depending on the frame rate and how much data you store), you don't want a linked list, which has a lot of overhead in terms of space (and can introduce big performance penalties due to cache misses if it is laid out poorly). For each parallel timeline, you want a vector data structure. You can store each parallel timeline in a linked list. Each timeline knows at what time it began.
To run the game, you iterate through all active timelines and perform one frame's worth of actions from each of them in lockstep. No need for parallel processing.
A: I have played this game before. I don't necessarily think parallel processing is the way to go. You have shared objects in the game (levers, boxes, elevators, etc) that will need to be shared between processes, possibly with every delta, thereby reducing the effectiveness of the parallelism.
I would personally just keep a list of actions, then for each subsequent iteration start interleaving them together. For example, if the list is in the format of <[iteration.action]> then the 3rd time thru would execute actions 1.1, 2.1, 3.1, 1.2, 2.2, 3.3, etc.
A: After briefly glossing over the description, I think you have the right idea, I would have a state object that holds the state data, and place this into a linked list...I don't think you need parallel threads...
as far as the graphics API, I have only used opengl, and can say that it is pretty powerful and has a good C / C++ API, opengl would also be more cross platform as you can use the messa library on *Nix computers.
A: A very interesting game idea. I think you are right that parrellel computing would be benefical to this design, but no more then any other high resource program.
The question is a bit ambigous. I see that you are going to write this in C++ but what OS are you coding it for? Do you intend on it being cross platform and what kind of graphics would you like, ie 3D, 2D, high end, web based.
So basically we need a lot more information.
A: Parallel processing isn't the answer. You should simply "record" the players actions then play them back for the "previous actions"
So you create a vector (singly linked list) of vectors that holds the actions. Simply store the frame number that the action was taken (or the delta) and complete that action on the "dummy bot" that represents the player during that particular instance. You simply loop through the states and trigger them one after another.
You get a side effect of easily "breaking" the game when a state paradox happens simply because the next action fails.
A: Unless you're desperate to use C++ for your own education, you should definitely look at XNA for your game & graphics framework (it uses C#). It's completely free, it does a lot of things for you, and soon you'll be able to sell your game on Xbox Live.
To answer your main question, nothing that you can already do in Flash would ever need to use more than one thread. Just store a list of positions in an array and loop through with a different offset for each robot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is it possible to use .htaccess to send six digit number URLs to a script but handle all other invalid URLs as 404s? Is it possible to use .htaccess to process all six digit URLs by sending them to a script, but handle every other invalid URL as an error 404?
For example:
http://mywebsite.com/132483
would be sent to:
http://mywebsite.com/scriptname.php?no=132483
but
http://mywebsite.com/132483a or
http://mywebsite.com/asdf
would be handled as a 404 error.
I presently have this working via a custom PHP 404 script but it's kind of kludgy. Seems to me that .htaccess might be a more elegant solution, but I haven't been able to figure out if it's even possible.
A: <IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^([0-9]{6})$ scriptname.php?no=$1 [L]
</IfModule>
To preserve the clean URL
http://mywebsite.com/132483
while serving scriptname.php use only [L].
Using [R=301] will redirect you to your scriptname.php?no=xxx
You may find this useful http://www.addedbytes.com/download/mod_rewrite-cheat-sheet-v2/pdf/
A: In your htaccess file, put the following
RewriteEngine On
RewriteRule ^([0-9]{6})$ /scriptname.php?no=$1 [L]
The first line turns the mod_rewrite engine on. The () brackets put the contents into $1 - successive () would populate $2, $3... and so on. The [0-9]{6} says look for a string precisely 6 characters long containing only characters 0-9.
The [L] at the end makes this the last rule - if it applies, rule processing will stop.
Oh, the ^ and $ mark the start and end of the incoming uri.
Hope that helps!
A: Yes it's possible with mod_rewrite. There are tons of good mod_rewrite tutorials online a quick Google search should turn up your answer in no time.
Basically what you're going to want to do is ensure that the regular expression you use is just looking for digits and no other characters and to ensure the length is 6. Then you'll redirect to scriptname.?no= with the number you captured.
Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: FileSystemWatcher Dispose call hangs We just started running in to an odd problem with a FileSystemWatcher where the call to Dispose() appears to be hanging. This is code that has been working without any problems for a while but we just upgraded to .NET3.5 SP1 so I'm trying to find out if anyone else has seen this behavior. Here is the code that creates the FileSystemWatcher:
if (this.fileWatcher == null)
{
this.fileWatcher = new FileSystemWatcher();
}
this.fileWatcher.BeginInit();
this.fileWatcher.IncludeSubdirectories = true;
this.fileWatcher.Path = project.Directory;
this.fileWatcher.EnableRaisingEvents = true;
this.fileWatcher.NotifyFilter = NotifyFilters.Attributes;
this.fileWatcher.Changed += delegate(object s, FileSystemEventArgs args)
{
FileWatcherFileChanged(args);
};
this.fileWatcher.EndInit();
The way this is being used is to update the state image of a TreeNode object (adjusted slightly to remove business specific information):
private void FileWatcherFileChanged(FileSystemEventArgs args)
{
if (this.TreeView != null)
{
if (this.TreeView.InvokeRequired)
{
FileWatcherFileChangedCallback d = new FileWatcherFileChangedCallback(FileWatcherFileChanged);
this.TreeView.Invoke(d, new object[]
{
args
});
}
else
{
switch (args.ChangeType)
{
case WatcherChangeTypes.Changed:
if (String.CompareOrdinal(this.project.FullName, args.FullPath) == 0)
{
this.StateImageKey = GetStateImageKey();
}
else
{
projectItemTreeNode.StateImageKey = GetStateImageKey();
}
break;
}
}
}
}
Is there something we're missing or is this an anomoly from .NET3.5 SP1?
A: Just a thought... Any chance there's a deadlock issue here?
You're calling TreeView.Invoke, which is a blocking call. If a filesystem change happens just as you're clicking whatever button causes the FileSystemWatcher.Dispose() call, your FileWatcherFileChanged method will get called on a background thread and call TreeView.Invoke, which will block until your form thread can process the Invoke request. However, your form thread would be calling FileSystemWatcher.Dispose(), which probably doesn't return until all pending change requests are processed.
Try changing the .Invoke to .BeginInvoke and see if that helps. That may help point you in the right direction.
Of course, it could also be a .NET 3.5SP1 issue. I'm just speculating here based on the code you provided.
A: Scott, we've occasionally seen issues with control.Invoke in .NET 2. Try switching to control.BeginInvoke and see if that helps.
Doing that will allow the FileSystemWatcher thread to return immediately. I suspect your issue is somehow that the control.Invoke is blocking, thus causing the FileSystemWatcher to freeze upon dispose.
A: We are also having this issue. Our application runs on .Net 2.0 but is compiled by VS 2008 SP1. I have .NET 3.5 SP1 installed as well. I've got no idea why this happens either, it doesn't look like a deadlock issue on our end as no other threads are running at this point (it is during application shutdown).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Will this C++ code cause a memory leak (casting array new) I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array new thus:
STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize];
Later on however the memory is freed using a delete call:
delete pStruct;
Will this mix of array new[] and non-array delete cause a memory leak or would it depend on the compiler? Would I be better off changing this code to use malloc and free instead?
A: I personally think you'd be better off using std::vector to manage your memory, so you don't need the delete.
std::vector<BYTE> backing(sizeof(STRUCT) + nPaddingSize);
STRUCT* pStruct = (STRUCT*)(&backing[0]);
Once backing leaves scope, your pStruct is no longer valid.
Or, you can use:
boost::scoped_array<BYTE> backing(new BYTE[sizeof(STRUCT) + nPaddingSize]);
STRUCT* pStruct = (STRUCT*)backing.get();
Or boost::shared_array if you need to move ownership around.
A: The behaviour of the code is undefined. You may be lucky (or not) and it may work with your compiler, but really that's not correct code. There's two problems with it:
*
*The delete should be an array delete [].
*The delete should be called on a pointer to the same type as the type allocated.
So to be entirely correct, you want to be doing something like this:
delete [] (BYTE*)(pStruct);
A: Yes it will cause a memory leak.
See this except from C++ Gotchas: http://www.informit.com/articles/article.aspx?p=30642 for why.
Raymond Chen has an explanation of how vector new and delete differ from the scalar versions under the covers for the Microsoft compiler... Here:
http://blogs.msdn.com/oldnewthing/archive/2004/02/03/66660.aspx
IMHO you should fix the delete to:
delete [] pStruct;
rather than switching to malloc/free, if only because it's a simpler change to make without making mistakes ;)
And, of course, the simpler to make change that I show above is wrong due to the casting in the original allocation, it should be
delete [] reinterpret_cast<BYTE *>(pStruct);
so, I guess it's probably as easy to switch to malloc/free after all ;)
A: The C++ standard clearly states:
delete-expression:
::opt delete cast-expression
::opt delete [ ] cast-expression
The first alternative is for non-array objects, and the second is for arrays. The operand shall have a pointer type, or a class type having a single conversion function (12.3.2) to a pointer type. The result has type void.
In the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object [...] If not, the behavior is undefined.
The value of the operand in delete pStruct is a pointer to an array of char, independent of its static type (STRUCT*). Therefore, any discussion of memory leaks is quite pointless, because the code is ill-formed, and a C++ compiler is not required to produce a sensible executable in this case.
It could leak memory, it could not, or it could do anything up to crashing your system. Indeed, a C++ implementation with which I tested your code aborts the program execution at the point of the delete expression.
A: As highlighted in other posts:
1) Calls to new/delete allocate memory and may call constructors/destructors (C++ '03 5.3.4/5.3.5)
2) Mixing array/non-array versions of new and delete is undefined behaviour. (C++ '03 5.3.5/4)
Looking at the source it appears that someone did a search and replace for malloc and free and the above is the result. C++ does have a direct replacement for these functions, and that is to call the allocation functions for new and delete directly:
STRUCT* pStruct = (STRUCT*)::operator new (sizeof(STRUCT) + nPaddingSize);
// ...
pStruct->~STRUCT (); // Call STRUCT destructor
::operator delete (pStruct);
If the constructor for STRUCT should be called, then you could consider allocating the memory and then use placement new:
BYTE * pByteData = new BYTE[sizeof(STRUCT) + nPaddingSize];
STRUCT * pStruct = new (pByteData) STRUCT ();
// ...
pStruct->~STRUCT ();
delete[] pByteData;
A: If you really must do this sort of thing, you should probably call operator new directly:
STRUCT* pStruct = operator new(sizeof(STRUCT) + nPaddingSize);
I believe calling it this way avoids calling constructors/destructors.
A: @eric - Thanks for the comments. You keep saying something though, that drives me nuts:
Those run-time libraries handle the
memory management calls to the OS in a
OS independent consistent syntax and
those run-time libraries are
responsible for making malloc and new
work consistently between OSes such as
Linux, Windows, Solaris, AIX, etc....
This is not true. The compiler writer provides the implementation of the std libraries, for instance, and they are absolutely free to implement those in an OS dependent way. They're free, for instance, to make one giant call to malloc, and then manage memory within the block however they wish.
Compatibility is provided because the API of std, etc. is the same - not because the run-time libraries all turn around and call the exact same OS calls.
A: The various possible uses of the keywords new and delete seem to create a fair amount of confusion. There are always two stages to constructing dynamic objects in C++: the allocation of the raw memory and the construction of the new object in the allocated memory area. On the other side of the object lifetime there is the destruction of the object and the deallocation of the memory location where the object resided.
Frequently these two steps are performed by a single C++ statement.
MyObject* ObjPtr = new MyObject;
//...
delete MyObject;
Instead of the above you can use the C++ raw memory allocation functions operator new and operator delete and explicit construction (via placement new) and destruction to perform the equivalent steps.
void* MemoryPtr = ::operator new( sizeof(MyObject) );
MyObject* ObjPtr = new (MemoryPtr) MyObject;
// ...
ObjPtr->~MyObject();
::operator delete( MemoryPtr );
Notice how there is no casting involved, and only one type of object is constructed in the allocated memory area. Using something like new char[N] as a way to allocate raw memory is technically incorrect as, logically, char objects are created in the newly allocated memory. I don't know of any situation where it doesn't 'just work' but it blurs the distinction between raw memory allocation and object creation so I advise against it.
In this particular case, there is no gain to be had by separating out the two steps of delete but you do need to manually control the initial allocation. The above code works in the 'everything working' scenario but it will leak the raw memory in the case where the constructor of MyObject throws an exception. While this could be caught and solved with an exception handler at the point of allocation it is probably neater to provide a custom operator new so that the complete construction can be handled by a placement new expression.
class MyObject
{
void* operator new( std::size_t rqsize, std::size_t padding )
{
return ::operator new( rqsize + padding );
}
// Usual (non-placement) delete
// We need to define this as our placement operator delete
// function happens to have one of the allowed signatures for
// a non-placement operator delete
void operator delete( void* p )
{
::operator delete( p );
}
// Placement operator delete
void operator delete( void* p, std::size_t )
{
::operator delete( p );
}
};
There are a couple of subtle points here. We define a class placement new so that we can allocate enough memory for the class instance plus some user specifiable padding. Because we do this we need to provide a matching placement delete so that if the memory allocation succeeds but the construction fails, the allocated memory is automatically deallocated. Unfortunately, the signature for our placement delete matches one of the two allowed signatures for non-placement delete so we need to provide the other form of non-placement delete so that our real placement delete is treated as a placement delete. (We could have got around this by adding an extra dummy parameter to both our placement new and placement delete, but this would have required extra work at all the calling sites.)
// Called in one step like so:
MyObject* ObjectPtr = new (padding) MyObject;
Using a single new expression we are now guaranteed that memory won't leak if any part of the new expression throws.
At the other end of the object lifetime, because we defined operator delete (even if we hadn't, the memory for the object originally came from global operator new in any case), the following is the correct way to destroy the dynamically created object.
delete ObjectPtr;
Summary!
*
*Look no casts! operator new and operator delete deal with raw memory, placement new can construct objects in raw memory. An explicit cast from a void* to an object pointer is usually a sign of something logically wrong, even if it does 'just work'.
*We've completely ignored new[] and delete[]. These variable size objects will not work in arrays in any case.
*Placement new allows a new expression not to leak, the new expression still evaluates to a pointer to an object that needs destroying and memory that needs deallocating. Use of some type of smart pointer may help prevent other types of leak. On the plus side we've let a plain delete be the correct way to do this so most standard smart pointers will work.
A: Technically I believe it could cause a problem with mismatched allocators, though in practice I don't know of any compiler that would not do the right thing with this example.
More importantly if STRUCT where to have (or ever be given) a destructor then it would invoke the destructor without having invoked the corresponding constructor.
Of course, if you know where pStruct came from why not just cast it on delete to match the allocation:
delete [] (BYTE*) pStruct;
A: I am currently unable to vote, but slicedlime's answer is preferable to Rob Walker's answer, since the problem has nothing to do with allocators or whether or not the STRUCT has a destructor.
Also note that the example code does not necessarily result in a memory leak - it's undefined behavior. Pretty much anything could happen (from nothing bad to a crash far, far away).
The example code results in undefined behavior, plain and simple. slicedlime's answer is direct and to the point (with the caveat that the word 'vector' should be changed to 'array' since vectors are an STL thing).
This kind of stuff is covered pretty well in the C++ FAQ (Sections 16.12, 16.13, and 16.14):
http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.12
A: It's an array delete ([]) you're referring to, not a vector delete.
A vector is std::vector, and it takes care of deletion of its elements.
A: Yes that may, since your allocating with new[] but deallocating with delelte, yes malloc/free is safer here, but in c++ you should not use them since they won't handle (de)constructors.
Also your code will call the deconstructor, but not the constructor. For some structs this may cause a memory leak (if the constructor allocated further memory, eg for a string)
Better would be to do it correctly, as this will also correctly call any constructors and deconstructors
STRUCT* pStruct = new STRUCT;
...
delete pStruct;
A: You'd could cast back to a BYTE * and the delete:
delete[] (BYTE*)pStruct;
A: It's always best to keep acquisition/release of any resource as balanced as possible.
Although leaking or not is hard to say in this case. It depends on the compiler's implementation of the vector (de)allocation.
BYTE * pBytes = new BYTE [sizeof(STRUCT) + nPaddingSize];
STRUCT* pStruct = reinterpret_cast< STRUCT* > ( pBytes ) ;
// do stuff with pStruct
delete [] pBytes ;
A: You're sort of mixing C and C++ ways of doing things. Why allocate more than the size of a STRUCT? Why not just "new STRUCT"? If you must do this then it might be clearer to use malloc and free in this case, since then you or other programmers might be a little less likely to make assumptions about the types and sizes of the allocated objects.
A: Len: the problem with that is that pStruct is a STRUCT*, but the memory allocated is actually a BYTE[] of some unknown size. So delete[] pStruct will not de-allocate all of the allocated memory.
A: Use operator new and delete:
struct STRUCT
{
void *operator new (size_t)
{
return new char [sizeof(STRUCT) + nPaddingSize];
}
void operator delete (void *memory)
{
delete [] reinterpret_cast <char *> (memory);
}
};
void main()
{
STRUCT *s = new STRUCT;
delete s;
}
A: I think the is no memory leak.
STRUCT* pStruct = (STRUCT*)new BYTE [sizeof(STRUCT) + nPaddingSize];
This gets translated into a memory allocation call within the operating system upon which a pointer to that memory is returned. At the time memory is allocated, the size of sizeof(STRUCT) and the size of nPaddingSize would be known in order to fulfill any memory allocation requests against the underlying operating system.
So the memory that is allocated is "recorded" in the operating system's global memory allocation tables. Memory tables are indexed by their pointers. So in the corresponding call to delete, all memory that was originally allocated is free. (memory fragmentation a popular subject in this realm as well).
You see, the C/C++ compiler is not managing memory, the underlying operating system is.
I agree there are cleaner methods but the OP did say this was legacy code.
In short, I don't see a memory leak as the accepted answer believes there to be one.
A: @Matt Cruikshank
You should pay attention and read what I wrote again because I never suggested not calling delete[] and just let the OS clean up. And you're wrong about the C++ run-time libraries managing the heap. If that were the case then C++ would not be portable as is today and a crashing application would never get cleaned up by the OS. (acknowledging there are OS specific run-times that make C/C++ appear non-portable). I challenge you to find stdlib.h in the Linux sources from kernel.org. The new keyword in C++ actually is talking to the same memory management routines as malloc.
The C++ run-time libraries make OS system calls and it's the OS that manages the heaps. You are partly correct in that the run-time libraries indicate when to release the memory however, they don't actually walk any heap tables directly. In other words, the runtime you link against does not add code to your application to walk heaps to allocate or deallocate. This is the case in Windows, Linux, Solaris, AIX, etc... It's also the reason you won't fine malloc in any Linux's kernel source nor will you find stdlib.h in Linux source. Understand these modern operating system have virtual memory managers that complicates things a bit further.
Ever wonder why you can make a call to malloc for 2G of RAM on a 1G box and still get back a valid memory pointer?
Memory management on x86 processors is managed within Kernel space using three tables. PAM (Page Allocation Table), PD (Page Directories) and PT (Page Tables). This is at the hardware level I'm speaking of. One of the things the OS memory manager does, not your C++ application, is to find out how much physical memory is installed on the box during boot with help of BIOS calls. The OS also handles exceptions such as when you try to access memory your application does not have rights too. (GPF General Protection Fault).
It may be that we are saying the same thing Matt, but I think you may be confusing the under hood functionality a bit. I use to maintain a C/C++ compiler for a living...
A: @ericmayo - cripes. Well, experimenting with VS2005, I can't get an honest leak out of scalar delete on memory that was made by vector new. I guess the compiler behavior is "undefined" here, is about the best defense I can muster.
You've got to admit though, it's a really lousy practice to do what the original poster said.
If that were the case then C++ would
not be portable as is today and a
crashing application would never get
cleaned up by the OS.
This logic doesn't really hold, though. My assertion is that a compiler's runtime can manage the memory within the memory blocks that the OS returns to it. This is how most virtual machines work, so your argument against portability in this case don't make much sense.
A: @Matt Cruikshank
"Well, experimenting with VS2005, I can't get an honest leak out of scalar delete on memory that was made by vector new. I guess the compiler behavior is "undefined" here, is about the best defense I can muster."
I disagree that it's a compiler behavior or even a compiler issue. The 'new' keyword gets compiled and linked, as you pointed out, to run-time libraries. Those run-time libraries handle the memory management calls to the OS in a OS independent consistent syntax and those run-time libraries are responsible for making malloc and new work consistently between OSes such as Linux, Windows, Solaris, AIX, etc.... This is the reason I mentioned the portability argument; an attempt to prove to you that the run-time does not actually manage memory either.
The OS manages memory.
The run-time libs interface to the OS.. On Windows, this is the virtual memory manager DLLs. This is why stdlib.h is implemented within the GLIB-C libraries and not the Linux kernel source; if GLIB-C is used on other OSes, it's implementation of malloc changes to make the correct OS calls. In VS, Borland, etc.. you will never find any libraries that ship with their compilers that actually manage memory either. You will, however, find OS specific definitions for malloc.
Since we have the source to Linux, you can go look at how malloc is implemented there. You will see that malloc is actually implemented in the GCC compiler which, in turn, basically makes two Linux system calls into the kernel to allocate memory. Never, malloc itself, actually managing memory!
And don't take it from me. Read the source code to Linux OS or you can see what K&R say about it... Here is a PDF link to the K&R on C.
http://www.oberon2005.ru/paper/kr_c.pdf
See near end of Page 149:
"Calls to malloc and free may occur in any order; malloc calls
upon the operating system to obtain more memory as necessary. These routines illustrate some of the considerations involved in writing machine-dependent code in a relatively machineindependent way, and also show a real-life application of structures, unions and typedef."
"You've got to admit though, it's a really lousy practice to do what the original poster said."
Oh, I don't disagree there. My point was that the original poster's code was not conducive of a memory leak. That's all I was saying. I didn't chime in on the best practice side of things. Since the code is calling delete, the memory is getting free up.
I agree, in your defense, if the original poster's code never exited or never made it to the delete call, that the code could have a memory leak but since he states that later on he sees the delete getting called. "Later on however the memory is freed using a delete call:"
Moreover, my reason for responding as I did was due to the OP's comment "variable length structures (TAPI), where the structure size will depend on variable length strings"
That comment sounded like he was questioning the dynamic nature of the allocations against the cast being made and was consequentially wondering if that would cause a memory leak. I was reading between the lines if you will ;).
A: In addition to the excellent answers above, I would also like to add:
If your code runs on linux or if you can compile it on linux then I would suggest running it through Valgrind. It is an excellent tool, among the myriad of useful warnings it produces it also will tell you when you allocate memory as an array and then free it as a non-array ( and vice-versa ).
A: Rob Walker reply is good.
Just small addition, if you don't have any constructor or/and distructors, so you basically need allocate and free a chunk of raw memory, consider using free/malloc pair.
A: ericmayo.myopenid.com is so wrong, that someone with enough reputation should downvote him.
The C or C++ runtime libraries are managing the heap which is given to it in blocks by the Operating System, somewhat like you indicate, Eric. But it is the responsibility of the developer to indicate to the compiler which runtime calls should be made to free memory, and possibly destruct the objects that are there. Vector delete (aka delete[]) is necessary in this case, in order for the C++ runtime to leave the heap in a valid state. The fact that when the PROCESS terminates, the OS is smart enough to deallocate the underlying memory blocks is not something that developers should rely on. This would be like never calling delete at all.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Best way to switch between multiple versions of the Flash player for easier testing? Are there any utilities or browser plugins that let you easily switch the version of the Flash player that is being used?
A: For Firefox 3.x on Window XP, Ubutntu Linux, and Mac OS X (Tiger and Leopard), Flash Switcher works well.
A: For a cross-browser, cross-platform solution, you can use this python script:
http://www.mattshaw.org/projects/flash-plugin-switcher/
A: Found the following: http://www.google.be/search?q=firefox%20switch%20flash%20version
http://www.sephiroth.it/weblog/archives/2006/10/flash_switcher_for_firefox.php (seems nice)
http://www.communitymx.com/content/article.cfm?page=2&cid=6FBA7 (seems nicely integrated as well)
https://addons.mozilla.org/nl/firefox/addon/5044 (from mozilla.org, must be good :p)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to make the taskbar blink my application like Messenger does when a new message arrive? Is there an API call in .NET or a native DLL that I can use to create similar behaviour as Windows Live Messenger when a response comes from someone I chat with?
A: HWND hHandle = FindWindow(NULL,"YourApplicationName");
FLASHWINFO pf;
pf.cbSize = sizeof(FLASHWINFO);
pf.hwnd = hHandle;
pf.dwFlags = FLASHW_TIMER|FLASHW_TRAY; // (or FLASHW_ALL to flash and if it is not minimized)
pf.uCount = 8;
pf.dwTimeout = 75;
FlashWindowEx(&pf);
Stolen from experts-exchange member gtokas.
FlashWindowEx.
A: From a Raymond Chen blog entry:
How do I flash my window caption and taskbar button manually?
How do I flash my window caption and
taskbar button manually? Commenter
Jonathan Scheepers wonders about those
programs that flash their taskbar
button indefinitely, overriding the
default flash count set by
SysteParametersInfo(SPI_SETFOREGROUNDFLASHCOUNT).
The FlashWindowEx function and its
simpler precursor FlashWindow let a
program flash its window caption and
taskbar button manually. The window
manager flashes the caption
automatically (and Explorer follows
the caption by flashing the taskbar
button) if a program calls
SetForegroundWindow when it doesn't
have permission to take foreground,
and it is that automatic flashing that
the SPI_SETFOREGROUNDFLASHCOUNT
setting controls.
For illustration purposes, I'll
demonstrate flashing the caption
manually. This is generally speaking
not recommended, but since you asked,
I'll show you how. And then promise
you won't do it.
Start with the scratch program and
make this simple change:
void
OnSize(HWND hwnd, UINT state, int cx, int cy)
{
if (state == SIZE_MINIMIZED) {
FLASHWINFO fwi = { sizeof(fwi), hwnd,
FLASHW_TIMERNOFG | FLASHW_ALL };
FlashWindowEx(&fwi);
}
}
Compile and run this program, then
minimize it. When you do, its taskbar
button flashes indefinitely until you
click on it. The program responds to
being minimzed by calling the
FlashWindowEx function asking for
everything possible (currently the
caption and taskbar button) to be
flashed until the window comes to the
foreground.
Other members of the FLASHWINFO
structure let you customize the
flashing behavior further, such as
controlling the flash frequency and
the number of flashes. and if you
really want to take control, you can
use FLASHW_ALL and FLASHW_STOP to turn
your caption and taskbar button on and
off exactly the way you want it. (Who
knows, maybe you want to send a
message in Morse code.)
Published Monday, May 12, 2008 7:00 AM
by oldnewthing Filed under: Code
A: FlashWindowEx is the way to go. See here for MSDN documentation
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool FlashWindowEx(ref FLASHWINFO pwfi);
[StructLayout(LayoutKind.Sequential)]
public struct FLASHWINFO
{
public UInt32 cbSize;
public IntPtr hwnd;
public UInt32 dwFlags;
public UInt32 uCount;
public UInt32 dwTimeout;
}
public const UInt32 FLASHW_ALL = 3;
Calling the Function:
FLASHWINFO fInfo = new FLASHWINFO();
fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));
fInfo.hwnd = hWnd;
fInfo.dwFlags = FLASHW_ALL;
fInfo.uCount = UInt32.MaxValue;
fInfo.dwTimeout = 0;
FlashWindowEx(ref fInfo);
This was shamelessly plugged from Pinvoke.net
A: The FlashWindowEx Win32 API is the call used to do this. The documentation for it is at:
http://msdn.microsoft.com/en-us/library/ms679347(VS.85).aspx
A: I believe you're looking for SetForegroundWindow.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: Saving HTML tables to a Database I am trying to scrape an html table and save its data in a database. What strategies/solutions have you found to be helpful in approaching this program.
I'm most comfortable with Java and PHP but really a solution in any language would be helpful.
EDIT: For more detail, the UTA (Salt Lake's Bus system) provides bus schedules on its website. Each schedule appears in a table that has stations in the header and times of departure in the rows. I would like to go through the schedules and save the information in the table in a form that I can then query.
Here's the starting point for the schedules
A: There is a nice book about this topic: Spidering Hacks by Kevin Hemenway and Tara Calishain.
A: It all depends on how properly your HTML to scrape is? If it's valid XHTML, you can simply use some XPath queries on it to get whatever you want.
Example of xpath in php: http://blogoscoped.com/archive/2004_06_23_index.html#108802750834787821
A helper class to scrape a table into an array: http://www.tgreer.com/class_http_php.html
A: I've found that scripting languages are generally better suited for doing such tasks. I personally prefer Python, but PHP will work as well. Chopping, mincing and parsing strings in Java is just too much work.
A: I have tried screen-scraping before, but I found it to be very brittle, especially with dynamically-generated code.
I found a third-party DOM-parser and used it to navigate the source code with Regex-like matching patterns in order to find the data I needed.
I suggested trying to find out if the owners of the site have a published API (often Web Services) for retrieving data from their system. If not, then good luck to you.
A: This would be by far the easiest with Perl, and the following CPAN modules:
*
*http://metacpan.org/pod/HTML::Parser
*http://metacpan.org/pod/LWP
*http://metacpan.org/pod/DBD/mysql
*http://metacpan.org/pod/DBI.pm
CPAN being the main distribution mechanism for Perl modules, and accessible by running the following shell command, for example:
# cpan HTML::Parser
If you're on Windows, things will be more interesting, but you can still do it: http://www.perlmonks.org/?node_id=583586
A: pianohacker overlooked the HTML::TableExtract module, which was designed for exactly this sort of thing. You'd still need LWP to retrieve the table.
A: If what you want is a form a csv table then you can use this:
using python:
for example imagine you want to scrape forex quotes in csv form from some site like: fxoanda
then...
from BeautifulSoup import BeautifulSoup
import urllib,string,csv,sys,os
from string import replace
date_s = '&date1=01/01/08'
date_f = '&date=11/10/08'
fx_url = 'http://www.oanda.com/convert/fxhistory?date_fmt=us'
fx_url_end = '&lang=en&margin_fixed=0&format=CSV&redirected=1'
cur1,cur2 = 'USD','AUD'
fx_url = fx_url + date_f + date_s + '&exch=' + cur1 +'&exch2=' + cur1
fx_url = fx_url +'&expr=' + cur2 + '&expr2=' + cur2 + fx_url_end
data = urllib.urlopen(fx_url).read()
soup = BeautifulSoup(data)
data = str(soup.findAll('pre', limit=1))
data = replace(data,'[<pre>','')
data = replace(data,'</pre>]','')
file_location = '/Users/location_edit_this'
file_name = file_location + 'usd_aus.csv'
file = open(file_name,"w")
file.write(data)
file.close()
once you have it in this form you can convert the data to any form you like.
A: At the risk of starting a shitstorm here on SO, I'd suggest that if the format of the table never changes, you could just about get away with using Regularexpressions to parse and capture the content you need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I create a custom font for a blackberry application I want to use a specific foreign language font for a Blackberry application. How is such a font created and loaded onto the Blackberry device?
For example: ਪੰਜਾਬੀ
A: for Blackberry OS 5 or above, you can use class FontFamily to load your custom font into application.
A: A quick google search shows that the same thing has been asked at blackberry forums.
The solution they came up with is a class for loading the font from a fnt file.
There are programs available to import and edit fnt files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How Does Listening to a Multicast Hurt Me? I'm receiving a recovery feed from an exchange for recovering data missed from their primary feed.
The exchange strongly recommends listening to the recovery feed only when data is needed, and leaving the multicast once I have recovered the data I need.
My question is, if I am using asio, and not reading from the NIC when I don't need it, what is the harm? The messages have sequence numbers, so I can't accidentally process an old message "left" on the card.
Is this really harming my application?
A: It's likely not harming your application so much as harming your machine - since the nic is still configured into the multicast group, it's still listening to those messages and passing them up, before your software ignores them and they get discarded. That's a lot of extra work that your network stack and kernel are doing, and therefore a lot of extra load on the machine in general, not just your app.
A: Listening to your recovery feed could also have a potential impact on a network level. As pjz mentioned, your NIC and IP stack will have more frames/packets to process. In addition, more of your available bandwidth is being used up by data that is not being used by your application; this could lead to dropped frames if there is congestion on your link. Whether congestion is likely to occur depends on whether your server is 100Mb or 1Gb attached, how much other traffic your host is sending/receiving, etc.
Another potential concern is the impact on other hosts. If the switch your host is attached to does not have IGMP snooping enabled, then all hosts on the same VLAN will receive the additional multicast traffic, which could lead them to experience the same problems as mentioned above.
If you have a networking team administering your network for you, it may be worth seeking out some recommendations from them? If you feel it is necessary to subscribe to a redundant feed, it would seem prudent to work out what level of redundancy already exists in your network and how likely it is that messages on the primary feed will be lost.
A: An addition to muz's comment...
It's unlikely that this will make any difference to your system, but it's worth being aware that there is an overhead associated with maintaining a multicast membership (assuming that you're using IGMP - which is probably reasonable given the restriction about "leaving the multicast")
IGMP requires the sending and processing of multicast group memberships at regular intervals. And (as alluded to in muz's comment) if you have any switches or routers between you and the multicast source that are capable of igmp snooping then they are able to disable the multicast for a given network.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: When using Linq to SQL with stored procedures, must char(1) columns be returned as c# chars? When using Linq to SQL and stored procedures, the class generated to describe the proc's result set uses char properties to represent char(1) columns in the SQL proc. I'd rather these be strings - is there any easy way to make this happen?
A: You could modify the {database}.designer.cs file. I don't have one handy to check, but I believe it's fairly straight forward --- you'll just have to plow through a lot of code, and remember to re-apply the change if you ever regenerate it.
Alternately, you could create your own class and handle it in the select. For example, given the LINQ generated class:
class MyTable
{ int MyNum {get; set;}
int YourNum {get; set;}
char OneChar {get; set;}
}
you could easily create:
class MyFixedTable
{ int MyNum {get; set;}
int YourNum {get; set;}
string OneChar {get; set;}
public MyFixedTable(MyTable t)
{
this,MyNum = t.MyNum;
this.YourNum = t.YourNum;
this.OneChar = new string(t.OneChar, 1);
}
}
Then instead of writing:
var q = from t in db.MyTable
select t;
write
var q = from t in db.MyTable
select new MyFixTable(t);
A: var whatever =
from x in something
select new { yourString = Char.ToString(x.theChar); }
A: Just go to the designer window and change the type to string. I do it all the time, as I find Strings to be easier to use than Char in my code.
A: Not sure why you'd want to do that. The underlying data type can't store more than one char, by representing it as a string variable you introduce the need to check lengths before committing to the db, where as if you leave it as is you can just call ToString() on the char to get a string
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I exclude the bin folder from sourcesafe in a Visual Studio 2008 web application? How can I exclude the bin folder from SourceSafe in a Visual Studio 2008 web application? I want to be able to check in everything recursively from the solution node without picking up anything in the bin folder.
A: *
*Right-click the folder in your
project
*select "Exclude from project"
A: Yes, you could exclude files from source control in your projects.
For example (In Visual Studio), if you added the ConnectionStrings.config file to your project then select the ConnectionStrings.config file in the Solution Explorer and then select "Exclude ConnectionStrings.config from Source Control" from the File->Source Control menu. Now, your file will be ignored by Source Control and won't be checked into Source Control.
Note: If you right click on the ConnectionStrings.config file in Solution Explorer and bring up the context menu for it then there is a "Exclude From Project" menu item, THIS IS NOT the option to exclude from Source Control. So do not get confused between the "Exclude ConnectionStrings.config from Source Control" and "Exclude From Project"; they are not the same thing. "Exclude ConnectionStrings.config from Source Control" can only be accessed in the File->Source Control menu.
A: You can hide the folder through Windows explorer, although it'll disappear from your Visual Studio Solution Exporer, I don't think that'll affect the website.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What is the difference between lambdas and delegates in the .NET Framework? I get asked this question a lot and I thought I'd solicit some input on how to best describe the difference.
A: A delegate is a function signature; something like
delegate string MyDelegate(int param1);
The delegate does not implement a body.
The lambda is a function call that matches the signature of the delegate. For the above delegate, you might use any of;
(int i) => i.ToString();
(int i) => "ignored i";
(int i) => "Step " + i.ToString() + " of 10";
The Delegate type is badly named, though; creating an object of type Delegate actually creates a variable which can hold functions -- be they lambdas, static methods, or class methods.
A: The question is a little ambiguous, which explains the wide disparity in answers you're getting.
You actually asked what the difference is between lambdas and delegates in the .NET framework; that might be one of a number of things. Are you asking:
*
*What is the difference between lambda expressions and anonymous delegates in the C# (or VB.NET) language?
*What is the difference between System.Linq.Expressions.LambdaExpression objects and System.Delegate objects in .NET 3.5?
*Or something somewhere between or around those extremes?
Some people seem to be trying to give you the answer to the question 'what is the difference between C# Lambda expressions and .NET System.Delegate?', which doesn't make a whole lot of sense.
The .NET framework does not in itself understand the concepts of anonymous delegates, lambda expressions, or closures - those are all things defined by language specifications. Think about how the C# compiler translates the definition of an anonymous method into a method on a generated class with member variables to hold closure state; to .NET, there's nothing anonymous about the delegate; it's just anonymous to the C# programmer writing it. That's equally true of a lambda expression assigned to a delegate type.
What .NET DOES understand is the idea of a delegate - a type that describes a method signature, instances of which represent either bound calls to specific methods on specific objects, or unbound calls to a particular method on a particular type that can be invoked against any object of that type, where said method adheres to the said signature. Such types all inherit from System.Delegate.
.NET 3.5 also introduces the System.Linq.Expressions namespace, which contains classes for describing code expressions - and which can also therefore represent bound or unbound calls to methods on particular types or objects. LambdaExpression instances can then be compiled into actual delegates (whereby a dynamic method based on the structure of the expression is codegenned, and a delegate pointer to it is returned).
In C# you can produce instances of System.Expressions.Expression types by assigning a lambda expression to a variable of said type, which will produce the appropriate code to construct the expression at runtime.
Of course, if you were asking what the difference is between lambda expressions and anonymous methods in C#, after all, then all this is pretty much irelevant, and in that case the primary difference is brevity, which leans towards anonymous delegates when you don't care about parameters and don't plan on returning a value, and towards lambdas when you want type inferenced parameters and return types.
And lambda expressions support expression generation.
A: I don't have a ton of experience with this, but the way I would describe it is that a delegate is a wrapper around any function, whereas a lambda expression is itself an anonymous function.
A: A delegate is always just basically a function pointer. A lambda can turn into a delegate, but it can also turn into a LINQ expression tree. For instance,
Func<int, int> f = x => x + 1;
Expression<Func<int, int>> exprTree = x => x + 1;
The first line produces a delegate, while the second produces an expression tree.
A: Short version:
A delegate is a type that represents references to methods. C# lambda expression is a syntax to create delegates or expression trees.
Kinda long version:
Delegate is not "the name for a variable" as it's said in the accepted answer.
A delegate is a type (literally a type, if you inspect IL, it's a class) that represents references to methods (learn.microsoft.com).
This type could be initiated to associate its instance with any method with a compatible signature and return type.
namespace System
{
// define a type
public delegate TResult Func<in T, out TResult>(T arg);
}
// method with the compatible signature
public static bool IsPositive(int int32)
{
return int32 > 0;
}
// initiated and associate
Func<int, bool> isPositive = new Func<int, bool>(IsPositive);
C# 2.0 introduced a syntactic sugar, anonymous method, enabling methods to be defined inline.
Func<int, bool> isPositive = delegate(int int32)
{
return int32 > 0;
};
In C# 3.0+, the above anonymous method’s inline definition can be further simplified with lambda expression
Func<int, bool> isPositive = (int int32) =>
{
return int32 > 0;
};
C# lambda expression is a syntax to create delegates or expression trees. I believe expression trees are not the topic of this question (Jamie King about expression trees).
More could be found here.
A: One difference is that an anonymous delegate can omit parameters while a lambda must match the exact signature. Given:
public delegate string TestDelegate(int i);
public void Test(TestDelegate d)
{}
you can call it in the following four ways (note that the second line has an anonymous delegate that does not have any parameters):
Test(delegate(int i) { return String.Empty; });
Test(delegate { return String.Empty; });
Test(i => String.Empty);
Test(D);
private string D(int i)
{
return String.Empty;
}
You cannot pass in a lambda expression that has no parameters or a method that has no parameters. These are not allowed:
Test(() => String.Empty); //Not allowed, lambda must match signature
Test(D2); //Not allowed, method must match signature
private string D2()
{
return String.Empty;
}
A: lambdas are simply syntactic sugar on a delegate. The compiler ends up converting lambdas into delegates.
These are the same, I believe:
Delegate delegate = x => "hi!";
Delegate delegate = delegate(object x) { return "hi";};
A: A delegate is a reference to a method with a particular parameter list and return type. It may or may not include an object.
A lambda-expression is a form of anonymous function.
A: A delegate is a Queue of function pointers, invoking a delegate may invoke multiple methods. A lambda is essentially an anonymous method declaration which may be interpreted by the compiler differently, depending on what context it is used as.
You can get a delegate that points to the lambda expression as a method by casting it into a delegate, or if passing it in as a parameter to a method that expects a specific delegate type the compiler will cast it for you. Using it inside of a LINQ statement, the lambda will be translated by the compiler into an expression tree instead of simply a delegate.
The difference really is that a lambda is a terse way to define a method inside of another expression, while a delegate is an actual object type.
A: It is pretty clear the question was meant to be "what's the difference between lambdas and anonymous delegates?" Out of all the answers here only one person got it right - the main difference is that lambdas can be used to create expression trees as well as delegates.
You can read more on MSDN: http://msdn.microsoft.com/en-us/library/bb397687.aspx
A: Delegates are equivalent to function pointers/method pointers/callbacks (take your pick), and lambdas are pretty much simplified anonymous functions. At least that's what I tell people.
A: They are actually two very different things. "Delegate" is actually the name for a variable that holds a reference to a method or a lambda, and a lambda is a method without a permanent name.
Lambdas are very much like other methods, except for a couple subtle differences.
*
*A normal method is defined in a "statement" and tied to a permanent name, whereas a lambda is defined "on the fly" in an "expression" and has no permanent name.
*Some lambdas can be used with .NET expression trees, whereas methods cannot.
A delegate is defined like this:
delegate Int32 BinaryIntOp(Int32 x, Int32 y);
A variable of type BinaryIntOp can have either a method or a labmda assigned to it, as long as the signature is the same: two Int32 arguments, and an Int32 return.
A lambda might be defined like this:
BinaryIntOp sumOfSquares = (a, b) => a*a + b*b;
Another thing to note is that although the generic Func and Action types are often considered "lambda types", they are just like any other delegates. The nice thing about them is that they essentially define a name for any type of delegate you might need (up to 4 parameters, though you can certainly add more of your own). So if you are using a wide variety of delegate types, but none more than once, you can avoid cluttering your code with delegate declarations by using Func and Action.
Here is an illustration of how Func and Action are "not just for lambdas":
Int32 DiffOfSquares(Int32 x, Int32 y)
{
return x*x - y*y;
}
Func<Int32, Int32, Int32> funcPtr = DiffOfSquares;
Another useful thing to know is that delegate types (not methods themselves) with the same signature but different names will not be implicitly casted to each other. This includes the Func and Action delegates. However if the signature is identical, you can explicitly cast between them.
Going the extra mile.... In C# functions are flexible, with the use of lambdas and delegates. But C# does not have "first-class functions". You can use a function's name assigned to a delegate variable to essentially create an object representing that function. But it's really a compiler trick. If you start a statement by writing the function name followed by a dot (i.e. try to do member access on the function itself) you'll find there are no members there to reference. Not even the ones from Object. This prevents the programmer from doing useful (and potentially dangerous of course) things such as adding extension methods that can be called on any function. The best you can do is extend the Delegate class itself, which is surely also useful, but not quite as much.
Update: Also see Karg's answer illustrating the difference between anonymous delegates vs. methods & lambdas.
Update 2: James Hart makes an important, though very technical, note that lambdas and delegates are not .NET entities (i.e. the CLR has no concept of a delegate or lambda), but rather they are framework and language constructs.
A: Delegates are really just structural typing for functions. You could do the same thing with nominal typing and implementing an anonymous class that implements an interface or abstract class, but that ends up being a lot of code when only one function is needed.
Lambda comes from the idea of lambda calculus of Alonzo Church in the 1930s. It is an anonymous way of creating functions. They become especially useful for composing functions
So while some might say lambda is syntactic sugar for delegates, I would says delegates are a bridge for easing people into lambdas in c#.
A: Some basic here.
"Delegate" is actually the name for a variable that holds a reference to a method or a lambda
This is a anonymous method -
(string testString) => { Console.WriteLine(testString); };
As anonymous method do not have any name we need a delegate in which we can assign both of these method or expression. For Ex.
delegate void PrintTestString(string testString); // declare a delegate
PrintTestString print = (string testString) => { Console.WriteLine(testString); };
print();
Same with the lambda expression. Usually we need delegate to use them
s => s.Age > someValue && s.Age < someValue // will return true/false
We can use a func delegate to use this expression.
Func< Student,bool> checkStudentAge = s => s.Age > someValue && s.Age < someValue ;
bool result = checkStudentAge ( Student Object);
A: Lambdas are simplified versions of delegates. They have some of the the properties of a closure like anonymous delegates, but also allow you to use implied typing. A lambda like this:
something.Sort((x, y) => return x.CompareTo(y));
is a lot more concise than what you can do with a delegate:
something.Sort(sortMethod);
...
private int sortMethod(SomeType one, SomeType two)
{
one.CompareTo(two)
}
A: Heres an example I put up awhile on my lame blog. Say you wanted to update a label from a worker thread. I've got 4 examples of how to update that label from 1 to 50 using delegates, anon delegates and 2 types of lambdas.
private void button2_Click(object sender, EventArgs e)
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync();
}
private delegate void UpdateProgDelegate(int count);
private void UpdateText(int count)
{
if (this.lblTest.InvokeRequired)
{
UpdateProgDelegate updateCallBack = new UpdateProgDelegate(UpdateText);
this.Invoke(updateCallBack, new object[] { count });
}
else
{
lblTest.Text = count.ToString();
}
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
/* Old Skool delegate usage. See above for delegate and method definitions */
for (int i = 0; i < 50; i++)
{
UpdateText(i);
Thread.Sleep(50);
}
// Anonymous Method
for (int i = 0; i < 50; i++)
{
lblTest.Invoke((MethodInvoker)(delegate()
{
lblTest.Text = i.ToString();
}));
Thread.Sleep(50);
}
/* Lambda using the new Func delegate. This lets us take in an int and
* return a string. The last parameter is the return type. so
* So Func<int, string, double> would take in an int and a string
* and return a double. count is our int parameter.*/
Func<int, string> UpdateProgress = (count) => lblTest.Text = count.ToString();
for (int i = 0; i < 50; i++)
{
lblTest.Invoke(UpdateProgress, i);
Thread.Sleep(50);
}
/* Finally we have a totally inline Lambda using the Action delegate
* Action is more or less the same as Func but it returns void. We could
* use it with parameters if we wanted to like this:
* Action<string> UpdateProgress = (count) => lblT…*/
for (int i = 0; i < 50; i++)
{
lblTest.Invoke((Action)(() => lblTest.Text = i.ToString()));
Thread.Sleep(50);
}
}
A: I assume that your question concerns c# and not .NET, because of the ambiguity of your question, as .NET does not get alone - that is, without c# - comprehension of delegates and lambda expressions.
A (normal, in opposition to so called generic delegates, cf later) delegate should be seen as a kind of c++ typedef of a function pointer type, for instance in c++ :
R (*thefunctionpointer) ( T ) ;
typedef's the type thefunctionpointer which is the type of pointers to a function taking an object of type T and returning an object of type R. You would use it like this :
thefunctionpointer = &thefunction ;
R r = (*thefunctionpointer) ( t ) ; // where t is of type T
where thefunction would be a function taking a T and returning an R.
In c# you would go for
delegate R thedelegate( T t ) ; // and yes, here the identifier t is needed
and you would use it like this :
thedelegate thedel = thefunction ;
R r = thedel ( t ) ; // where t is of type T
where thefunction would be a function taking a T and returning an R. This is for delegates, so called normal delegates.
Now, you also have generic delegates in c#, which are delegates that are generic, i.e. that are "templated" so to speak, using thereby a c++ expression. They are defined like this :
public delegate TResult Func<in T, out TResult>(T arg);
And you can used them like this :
Func<double, double> thefunctor = thefunction2; // call it a functor because it is
// really as a functor that you should
// "see" it
double y = thefunctor(2.0);
where thefunction2 is a function taking as argument and returning a double.
Now imagine that instead of thefunction2 I would like to use a "function" that is nowhere defined for now, by a statement, and that I will never use later. Then c# allows us to use the expression of this function. By expression I mean the "mathematical" (or functional, to stick to programs) expression of it, for instance : to a double x I will associate the double x*x. In maths you write this using the "\mapsto" latex symbol. In c# the functional notation has been borrowed : =>. For instance :
Func<double, double> thefunctor = ( (double x) => x * x ); // outer brackets are not
// mandatory
(double x) => x * x is an expression. It is not a type, whereas delegates (generic or not) are.
Morality ? At end, what is a delegate (resp. generic delegate), if not a function pointer type (resp. wrapped+smart+generic function pointer type), huh ? Something else ! See this and that.
A: Well, the really oversimplified version is that a lambda is just shorthand for an anonymous function. A delegate can do a lot more than just anonymous functions: things like events, asynchronous calls, and multiple method chains.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "107"
}
|
Q: Firefox, saved passwords, and the change password dialogue If a user saves the password on the login form, ff3 is putting the saved password in the change password dialoge on the profile page, even though its not the same input name as the login. how can I prevent this?
A: Try using autocomplete="off" as an attribute of the text box. I've used it in the past to stop credit card details being stored by the browser but i dont know if it works with passwords. e.g. print("<input type="text" name="cc" autocomplete="off" />");
A: I think that FF autofills fields based on the "name" attribute of the field so that if the password box has the name="password" and the change password box has the same it will fill in the same password in both places.
Try changing the name attribute of one of the boxes.
A: Some sites have 3 inputs for changing a password, one for re-entering the current password and two for entering the new password. If the re-entering input was first and got auto-filled, it wouldn't be a problem.
A: Go in tools->page properties->security on the page you wish to modify.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: What is your choice for a Time Managment Solution? I've come across a few different applications that monitor my usage while on the computer, but what have you used, and like? whether it be writing down your activities in a composition notbook or install an app that reports silently to a server? what do you like?
A: For explicit time tracking for projects I use SlimTimer. I also run RescueTime to track my time implicitly, but I end up not looking at that data very often.
A: I use neomem to keep track of things by hand. This allows me to keep track of more than just time. I often keeps notes associated with the story. This has become a collection of knowledge that I often search.
A: I use a paper timesheet to track my time. It looks like this:
(source: redbitbluebit.com)
and as a back up, I use a paid version the excellent TimeSnapper in case I need to go back and retrace anything I missed tracking the time on.
A: I prefer writing the times down using pen and paper. That way you can more fairly weigh things that would have been miscalculated if you were recording them with a stopwatch or timer.
If you start on something and have to get up for a few minutes, a timer may count that toward your working time had you neglected to stop or pause the timer. The good-old pen and paper are going to more accurately show which tasks you focused most of your time and energy on...not just the ones that you started earliest and ended latest. It may not be 100% accurate, but neither is the timer if you don't use it properly.
I have used both in the past, and find that there are problems with both, but I prefer the pen and paper method.
A: We use Standard Time as a Time Tracking tool and it's got a nice quick tasks window that is relatively small and lets you easily click checkboxes to switch between tasks. You can also create projects/customers and pre-set tasks to be loaded for each project (development, unit testing, documentation, etc...) and then just use the quick tasks window to switch which task you are currently working on without wasting too much time going through a full blown GUI.
It's not cheap - about $150/user - so if it's for personal use it might not be the best bet, but if you're looking for a solution for a team of developers then I've found it to be a good fit.
A: I use the time tracker plugin on Firefox. It tracks my surfing time of the whole day
A: I've been using Toggl for about a year now and I've found it to be spot on. It's simple to use and allows you to perform basic reporting against various criteria. You can either input time entries manually or use a stopwatch timer utility.
I tried out several applications before I settled on Toggl. For me, the intuitiveness of the Toggl interface was what decided it. I like my productivity applications to get out of my way and let me do my job and Toggl does just that.
There are various pricing plans, including a free one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Best practice for passing parameters in Microsoft Visual Studio Tools for Office (VSTO) 3 (C#) Many of the parameters for interacting with the Office Object model in VSTO require object parameters that are passed by reference, even when the notional type of the parameter is an int or string.
*
*I suppose that this mechanism is used so that code can modify the parameter, although I can't figure out why these need to be passed as generic object instead of as their more appropriate types. Can anyone enlighten me?
*The mechanism I've been using (cribbed from help and MSDN resources) essentially creates a generic object that contains the appropriate data and then passes that to the method, for example:
object nextBookmarkName = "NextContent";
object nextBookmark = this.Bookmarks.get_Item( ref nextBookmarkName ).Range;
Microsoft.Office.Interop.Word.Range newRng = this.Range( ref nextBookmark, ref nextBookmark );
This seems like a lot of extra code, but I can't see a better way to do it. I'm sure I'm missing something; what is it? Or is this really the best practice?
A: I agree with Joe. I even developed helper structs and classes like this one:
internal struct Argument
{
internal static object False = false;
internal static object Missing = System.Type.Missing;
internal static object True = true;
}
And this one:
/// <summary>
/// Defines the "special characters"
/// in Microsoft Word that VSTO 1.x
/// translates into C# strings.
/// </summary>
internal struct Characters
{
/// <summary>
/// Word Table end-of-cell marker.
/// </summary>
/// <remarks>
/// Word Table end-of-row markers are also
/// equal to this value.
/// </remarks>
internal static string CellBreak = "\r\a";
/// <summary>
/// Word line break (^l).
/// </summary>
internal static string LineBreak = "\v";
/// <summary>
/// Word Paragraph break (^p).
/// </summary>
internal static string ParagraphBreak = "\r";
}
And a few more...
A: I'd be interested in this too. I'm coding several apps that uses automation in Word and I even have things like
object oFalse = false, oTrue = true, oOne = 1;
It's very nasty, but it's the only way I know so far.
The only thing I can think of is writing a wrapper class for the frequently used functions...
A: I think it was just poor design of the original Word object model. I know that passing strings by reference can be slightly faster in the COM world because it avoids the need to make a copy, so perhaps that was part of the justification. But the downside is that the callee can modify the value, and in most cases with Word they are input parameters.
I think your technique is the best practice. For the millions of optional parameters that many of the Word object model methods require, you can create a single static field "missing" something like:
object missing = Type.Missing;
// Example
object fileName = ...
document.SaveAs(ref fileName, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing);
A: I think, all of this is taken care of with VS.NET 2010 and new language constructs introduced in c# 4.0 (c# will have optional arguments).
See the video by Anders Hejlberg at PDC 2008 on channel9 for changes related to office development.
I cant find that link but this could also be helpful.
http://channel9.msdn.com/shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Capturing cout in Visual Studio 2005 output window? I created a C++ console app and just want to capture the cout/cerr statements in the Output Window within the Visual Studio 2005 IDE. I'm sure this is just a setting that I'm missing. Can anyone point me in the right direction?
A: You can capture the output of cout like this, for example:
std::streambuf* old_rdbuf = std::cout.rdbuf();
std::stringbuf new_rdbuf;
// replace default output buffer with string buffer
std::cout.rdbuf(&new_rdbuf);
// write to new buffer, make sure to flush at the end
std::cout << "hello, world" << std::endl;
std::string s(new_rdbuf.str());
// restore the default buffer before destroying the new one
std::cout.rdbuf(old_rdbuf);
// show that the data actually went somewhere
std::cout << s.size() << ": " << s;
Magicking it into the Visual Studio 2005 output window is left as an exercise to a Visual Studio 2005 plugin developer. But you could probably redirect it elsewhere, like a file or a custom window, perhaps by writing a custom streambuf class (see also boost.iostream).
A: You can't do this.
If you want to output to the debugger's output window, call OutputDebugString.
I found this implementation of a 'teestream' which allows one output to go to multiple streams. You could implement a stream that sends data to OutputDebugString.
A: A combination of ben's answer and Mike Dimmick's: you would be implementing a stream_buf_ that ends up calling OutputDebugString. Maybe someone has done this already? Take a look at the two proposed Boost logging libraries.
A: I've finally implemented this, so I want to share it with you:
#include <vector>
#include <iostream>
#include <windows.h>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/tee.hpp>
using namespace std;
namespace io = boost::iostreams;
struct DebugSink
{
typedef char char_type;
typedef io::sink_tag category;
std::vector<char> _vec;
std::streamsize write(const char *s, std::streamsize n)
{
_vec.assign(s, s+n);
_vec.push_back(0); // we must null-terminate for WINAPI
OutputDebugStringA(&_vec[0]);
return n;
}
};
int main()
{
typedef io::tee_device<DebugSink, std::streambuf> TeeDevice;
TeeDevice device(DebugSink(), *cout.rdbuf());
io::stream_buffer<TeeDevice> buf(device);
cout.rdbuf(&buf);
cout << "hello world!\n";
cout.flush(); // you may need to flush in some circumstances
}
BONUS TIP: If you write:
X:\full\file\name.txt(10) : message
to the output window and then double-click on it, then Visual Studio will jump to the given file, line 10, and display the 'message' in status bar. It's very useful.
A: Is this a case of the output screen just flashing and then dissapearing? if so you can keep it open by using cin as your last statement before return.
A: Also, depending on your intentions, and what libraries you are using, you may want to use the TRACE macro (MFC) or ATLTRACE (ATL).
A: Write to a std::ostringsteam and then TRACE that.
std::ostringstream oss;
oss << "w:=" << w << " u=" << u << " vt=" << vt << endl;
TRACE(oss.str().data());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Access USB with Java, in order to find thumbdrive manufacturer's serial#/unique-ID Looking for a way to read the unique ID / serial# of a USB thumb drive;
please note that
- I am looking for the value of the manufacturer, not the one Windows allocates for it.
- I need to support multiple OS (Windows, Unix, Mac), thus needs to be a Java solution
The idea is to be able to distinguish between different USB thumb drives.
A: RXTX is the way to go. In the world of model trains, JMRI (Java Model Railroad Interface) has become very popular. JMRI runs on all platforms (Windows, Linux and Mac) and communicates with a variety of USB based devices (command stations). RXTX is in fact used by JMRI.
A: I've never tried using it (it's been on my todo list for a good few months now), but there is the "marge" project on java.net:
http://marge.java.net/
This should let you connect to bluetooth devices (although I don't think it is 100% feature complete, there is demo code on there), and then the ClientDevice class has a "getBluetoothAddress" method which I believe should be unique to that device
http://marge.java.net/javadoc/v06/marge-core/net/java/dev/marge/entity/ClientDevice.html
As I say though, I've never tried it...
A: You might give a look at the following projects:
javax-usb and jusb. They seem to support Linux and Windows.
Anyway, since USB access in Java requires the use of native libraries, you might not achieve the required portability.
A: I have never investigated this thoroughly, but from memory the RXTX library implementation of the javax.comm packages are supposedly very good and now have USB support.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How do we create an installer than doesn't require administrator permissions? When creating a setup/MSI with Visual Studio is it possible to make a setup for a simple application that doesn't require administrator permissions to install? If its not possible under Windows XP is it possible under Vista?
For example a simple image manipulation application that allows you to paste photos on top of backgrounds. I believe installing to the Program Files folder requires administrator permissions? Can we install in the \AppData folder instead?
The objective is to create an application which will install for users who are not members of the administrators group on the local machine and will not show the UAC prompt on Vista.
I believe a limitation this method would be that if it installs under the app data folder for the current user other users couldn't run it.
Update:
Can you package a click once install in a normal setup.exe type installer? You may ask why we want this - the reason is we have an installer that does a prereq check and installs anything required (such as .NET) and we then downloads and executes the MSI. We would like to display a normal installer start screen too even if that's the only thing displayed. We don't mind if the app can only be seen by one user (the user it's installed for).
A: ClickOnce is a good solution to this problem. If you go to Project Properties > Publish, you can setup settings for this. In particular, "Install Mode and Settings" is good to look at:
*
*The application is available online only -- this is effectively a "run once" application
*The application is avaiable offline as well (launchable from Start Menu) -- this installs the app on the PC
You don't actually have to use the ClickOnce web deployment stuff. If you do a Build > Publish, and then zip up the contents of the publish\ folder, you can effectively distribute that as an installer. To make it even smoother, create a self-extracting archive from the folder that automatically runs the setup.exe file.
Even if you install this way, if you opt to use it, the online update will still work for the application. All you have to do is put the ClickOnce files online, and put the URL in the project's Publish properties page.
A: Vista is more restrictive about this kind of thing, so if you can't do it for XP you can bet Vista won't let you either.
You are right that installing to the program files folder using windows installer requires administrative permissions. In fact, all write access to that folder requires admin permsissions, which is why you should no longer store your data in the same folder as your executable.
Fortunately, if you're using .Net you can use ClickOnce deployment instead of an msi, which should allow you to install to a folder in each user's profile without requiring admin permissions.
A: The only way that I know of to do this is to build a ClickOnce application in .NET 2.0+
If the user of your application has the correct pre-requsits installed then the application can just be "launched".
Check out:
*
*Microsoft Family.Show
A: IF UAC is enabled, you couldn't write to Program Files. Installing to \AppData will indeed only install the program for one user.
However, you must note that any configuration changes that require changes to the registry probably(I'd have to double check on that) administrator privilege. Off the top of my head modifications to the desktop background are ultimately stored in HKEY_CURRENT_USER.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: True timeout on LWP::UserAgent request method I am trying to implement a request to an unreliable server. The request is a nice to have, but not 100% required for my perl script to successfully complete. The problem is that the server will occasionally deadlock (we're trying to figure out why) and the request will never succeed. Since the server thinks it is live, it keeps the socket connection open thus LWP::UserAgent's timeout value does us no good what-so-ever. What is the best way to enforce an absolute timeout on a request?
FYI, this is not an DNS problem. The deadlock has something to do with a massive number of updates hitting our Postgres database at the same time. For testing purposes, we've essentially put a while(1) {} line in the servers response handler.
Currently, the code looks like so:
my $ua = LWP::UserAgent->new;
ua->timeout(5); $ua->cookie_jar({});
my $req = HTTP::Request->new(POST => "http://$host:$port/auth/login");
$req->content_type('application/x-www-form-urlencoded');
$req->content("login[user]=$username&login[password]=$password");
# This line never returns
$res = $ua->request($req);
I've tried using signals to trigger a timeout, but that does not seem to work.
eval {
local $SIG{ALRM} = sub { die "alarm\n" };
alarm(1);
$res = $ua->request($req);
alarm(0);
};
# This never runs
print "here\n";
The final answer I'm going to use was proposed by someone offline, but I'll mention it here. For some reason, SigAction works while $SIG(ALRM) does not. Still not sure why, but this has been tested to work. Here are two working versions:
# Takes a LWP::UserAgent, and a HTTP::Request, returns a HTTP::Request
sub ua_request_with_timeout {
my $ua = $_[0];
my $req = $_[1];
# Get whatever timeout is set for LWP and use that to
# enforce a maximum timeout per request in case of server
# deadlock. (This has happened.)
use Sys::SigAction qw( timeout_call );
our $res = undef;
if( timeout_call( 5, sub {$res = $ua->request($req);}) ) {
return HTTP::Response->new( 408 ); #408 is the HTTP timeout
} else {
return $res;
}
}
sub ua_request_with_timeout2 {
print "ua_request_with_timeout\n";
my $ua = $_[0];
my $req = $_[1];
# Get whatever timeout is set for LWP and use that to
# enforce a maximum timeout per request in case of server
# deadlock. (This has happened.)
my $timeout_for_client = $ua->timeout() - 2;
our $socket_has_timedout = 0;
use POSIX;
sigaction SIGALRM, new POSIX::SigAction(
sub {
$socket_has_timedout = 1;
die "alarm timeout";
}
) or die "Error setting SIGALRM handler: $!\n";
my $res = undef;
eval {
alarm ($timeout_for_client);
$res = $ua->request($req);
alarm(0);
};
if ( $socket_has_timedout ) {
return HTTP::Response->new( 408 ); #408 is the HTTP timeout
} else {
return $res;
}
}
A: You might try LWPx::ParanoidAgent, a subclass of LWP::UserAgent which is more cautious about how it interacts with remote webservers.
Among other things, it allows you to specify a global timeout. It was developed by Brad Fitzpatrick as part of the LiveJournal project.
A: You can make your own timeout like this:
use LWP::UserAgent;
use IO::Pipe;
my $agent = new LWP::UserAgent;
my $finished = 0;
my $timeout = 5;
$SIG{CHLD} = sub { wait, $finished = 1 };
my $pipe = new IO::Pipe;
my $pid = fork;
if($pid == 0) {
$pipe->writer;
my $response = $agent->get("http://stackoverflow.com/");
$pipe->print($response->content);
exit;
}
$pipe->reader;
sleep($timeout);
if($finished) {
print "Finished!\n";
my $content = join('', $pipe->getlines);
}
else {
kill(9, $pid);
print "Timed out.\n";
}
A: From what I understand, the timeout property doesn't take into account DNS timeouts. It's possible that you could make a DNS lookup separately, then make the request to the server if that works, with the correct timeout value set for the useragent.
Is this a DNS problem with the server, or something else?
EDIT: It could also be a problem with IO::Socket. Try updating your IO::Socket module, and see if that helps. I'm pretty sure there was a bug in there that was preventing LWP::UserAgent timeouts from working.
Alex
A: The following generalization of one of the original answers also restores the alarm signal handler to the previous handler and adds a second call to alarm(0) in case the call in the eval clock throws a non alarm exception and we want to cancel the alarm. Further $@ inspection and handling can be added:
sub ua_request_with_timeout {
my $ua = $_[0];
my $request = $_[1];
# Get whatever timeout is set for LWP and use that to
# enforce a maximum timeout per request in case of server
# deadlock. (This has happened.)`enter code here`
my $timeout_for_client_sec = $ua->timeout();
our $res_has_timedout = 0;
use POSIX ':signal_h';
my $newaction = POSIX::SigAction->new(
sub { $res_has_timedout = 1; die "web request timeout"; },# the handler code ref
POSIX::SigSet->new(SIGALRM),
# not using (perl 5.8.2 and later) 'safe' switch or sa_flags
);
my $oldaction = POSIX::SigAction->new();
if(!sigaction(SIGALRM, $newaction, $oldaction)) {
log('warn',"Error setting SIGALRM handler: $!");
return $ua->request($request);
}
my $response = undef;
eval {
alarm ($timeout_for_client_sec);
$response = $ua->request($request);
alarm(0);
};
alarm(0);# cancel alarm (if eval failed because of non alarm cause)
if(!sigaction(SIGALRM, $oldaction )) {
log('warn', "Error resetting SIGALRM handler: $!");
};
if ( $res_has_timedout ) {
log('warn', "Timeout($timeout_for_client_sec sec) while waiting for a response from cred central");
return HTTP::Response->new(408); #408 is the HTTP timeout
} else {
return $response;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How you disable the processor cache on a PowerPC processor? In our embedded system (using a PowerPC processor), we want to disable the processor cache. What steps do we need to take?
To clarify a bit, the application in question must have as constant a speed of execution as we can make it.
Variability in executing the same code path is not acceptable. This is the reason to turn off the cache.
A: I'm kind of late to the question, and also it's been a while since I did all the low-level processor init code on PPCs, but I seem to remember the cache & MMU being pretty tightly coupled (one had to be enabled to enable the other) and I think in the MMU page tables, you could define the cacheable attribute.
So my point is this: if there's a certain subset of code that must run in deterministic time, maybe you locate that code (via a linker command file) in a region of memory that is defined as non-cacheable in the page tables? That way all the code that can/should benefit from the cache does, and the (hopefully) subset of code that shouldn't, doesn't.
I'd handle it this way anyway, so that later, if you want to enable caching for part of the system, you just need to flip a few bits in the MMU page tables, instead of (re-)writing the init code to set up all the page tables & caching.
A: From the E600 reference manual:
The HID0 special-purpose register contains several bits that invalidate, disable, and lock the instruction and data caches.
You should use HID0[DCE] = 0 to disable the data cache.
You should use HID0[ICE] = 0 to disable the instruction cache.
Note that at power up, both caches are disabled.
You will need to write this in assembly code.
A: Perhaps you don't want to globally disable cache, you only want to disable it for a particular address range?
On some processors you can configure TLB (translation lookaside buffer) entries for address ranges such that each range could have caching enabled or disabled. This way you can disable caching for memory mapped I/O, and still leave caching on for the main block of RAM.
The only PowerPC I've done this on was a PowerPC 440EP (from IBM, then AMCC), so I don't know if all PowerPCs work the same way.
A: What kind of PPC core is it? The cache control is very different between different cores from different vendors... also, disabling the cache is in general considered a really bad thing to do to the machine. Performance becomes so crawlingly slow that you would do as well with an old 8-bit processor (exaggerating a bit). Some ARM variants have TCMs, tightly-coupled memories, that work instead of caches, but I am not aware of any PPC variant with that facility.
Maybe a better solution is to keep Level 1 caches active, and use the on-chip L2 caches as statically mapped RAM instead? That is common on modern PowerQUICC devices, at least.
A: Turning off the cache will do you no good at all. Your execution speed will drop by an order of magnitude. You would never ship a system like this, so its performance under these conditions is of no interest.
To achieve a steady execution speed, consider one of these approaches:
1) Lock some or all of the cache. All current PowerPC chips from Freescale, IBM, and AMCC offer this feature.
2) If it's a Freescale chip with L2 cache, consider mapping part of that cache as on-chip memory.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQLGetData issues using C++ and SQL Native Client I have a C++ application that uses SQL Native Client to connect to a MS SQL Server 2000.
I am trying to retrieve a result from a TEXT column containing more data than the buffer initially allocated to it provides. To clarify my issue, I'll outline what I'm doing (code below):
*
*allocate buffer of 1024 bytes use
*bind buffer to column using SQLBindColumn
*execute a SELECT query using SQLExecute
*iterate through results using SQLFetch
*SQLFetch was unable to return the entire result to my buffer: I'd like to use SQLGetData to retrieve the entire column value
The above order of operations presents a problem: SQLGetData does not work on bound columns in my driver.
A working solution is to use the SQL_DATA_AT_EXEC flag as illustrated by the code below.
Begin code:
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <sqlncli.h>
#include <cstdio>
#include <string>
const int MAX_CHAR = 1024;
bool test_retcode( RETCODE my_code, const char* my_message )
{
bool success = ( my_code == SQL_SUCCESS_WITH_INFO || my_code == SQL_SUCCESS );
if ( ! success )
{
printf( "%s", my_message );
}
return success;
}
int main ( )
{
SQLHENV EnvironmentHandle;
RETCODE retcode = SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &EnvironmentHandle );
test_retcode( retcode, "SQLAllocHandle(Env) failed!" );
retcode = SQLSetEnvAttr( EnvironmentHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER );
test_retcode( retcode, "SQLSetEnvAttr(ODBC version) Failed" );
SQLHDBC ConnHandle;
retcode = SQLAllocHandle( SQL_HANDLE_DBC, EnvironmentHandle, &ConnHandle );
test_retcode( retcode, "Could not allocate MS SQL 2000 connection handle." );
SQLSMALLINT driver_out_length;
retcode = SQLDriverConnect( ConnHandle,
NULL, // we're not interested in spawning a window
(SQLCHAR*) "DRIVER={SQL Native Client};SERVER=localhost;UID=username;PWD=password;Database=Test;",
SQL_NTS,
NULL,
0,
&driver_out_length,
SQL_DRIVER_NOPROMPT );
test_retcode( retcode, "SQLConnect() Failed" );
SQLHSTMT StatementHandle;
retcode = SQLAllocHandle(SQL_HANDLE_STMT, ConnHandle, &StatementHandle);
test_retcode( retcode, "Failed to allocate SQL Statement handle." );
char* buffer = new char[ MAX_CHAR ];
SQLINTEGER length = MAX_CHAR - 1;
// -- Bind Block
retcode = SQLBindCol( StatementHandle,
1,
SQL_C_CHAR,
(SQLPOINTER) NULL,
(SQLINTEGER) SQL_DATA_AT_EXEC,
&length );
test_retcode( retcode, "Failed to bind column." );
// -- End Bind Block
retcode = SQLExecDirect( StatementHandle, (SQLCHAR*) "SELECT VeryLong FROM LongData", SQL_NTS );
test_retcode( retcode, "SQLExecDirect failed." );
// -- Fetch Block
retcode = SQLFetch( StatementHandle );
if ( retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO && retcode != SQL_NO_DATA )
{
printf( "Problem fetching row.\n" );
return 9;
}
printf( "Fetched data. length: %d\n", length );
// -- End Fetch Block
bool sql_success;
std::string data;
RETCODE r2;
do
{
r2 = SQLGetData( StatementHandle, 1, SQL_C_CHAR, buffer, MAX_CHAR, &length );
if ( sql_success = test_retcode( r2, "SQLGetData failed." ) )
{
data.append( buffer );
}
else
{
char* err_msg = new char[ MAX_CHAR ];
SQLSMALLINT req = 1;
SQLCHAR state[6];
SQLINTEGER error;
SQLINTEGER output_length;
int sql_state = SQLGetDiagRec( SQL_HANDLE_STMT, StatementHandle, req, state, &error, (SQLCHAR*) err_msg, (SQLINTEGER) MAX_CHAR, (SQLSMALLINT*) &output_length );
// state is: 07009, error_msg: "[Microsoft][SQL Native Client]Invalid Descriptor Index"
printf( "%s\n", err_msg );
delete err_msg;
return 9;
}
}
while ( sql_success && r2 != SQL_SUCCESS );
printf( "Done.\n" );
return 0;
}
A: *
*Try to put SQLBindCol after SQLExecDirect.
*For TEXT column use
retcode = SQLBindCol( StatementHandle, 1, SQL_C_CHAR,
(SQLPOINTER) NULL, (SQLINTEGER) SQL_DATA_AT_EXEC, &length );
in this way you can repeat SQLGetData to read entire TEXT data in multiple pieces
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to duplicate a whole line in Vim? How do I duplicate a whole line in Vim in a similar way to Ctrl+D in IntelliJ IDEA/ Resharper or Ctrl+Alt+↑/↓ in Eclipse?
A: I know I'm late to the party, but whatever; I have this in my .vimrc:
nnoremap <C-d> :copy .<CR>
vnoremap <C-d> :copy '><CR>
the :copy command just copies the selected line or the range (always whole lines) to below the line number given as its argument.
In normal mode what this does is copy . copy this line to just below this line.
And in visual mode it turns into '<,'> copy '> copy from start of selection to end of selection to the line below end of selection.
A: yy
will yank the current line without deleting it
dd
will delete the current line
p
will put a line grabbed by either of the previous methods
A: Do this:
First, yy to copy the current line, and then p to paste.
A: If you want another way:
"ayy:
This will store the line in buffer a.
"ap:
This will put the contents of buffer a at the cursor.
There are many variations on this.
"a5yy:
This will store the 5 lines in buffer a.
See "Vim help files for more fun.
A: Default is yyp, but I've been using this rebinding for a year or so and love it:
" set Y to duplicate lines, works in visual mode as well.
nnoremap Y yyp
vnoremap Y y`>pgv
A: I prefer to define a custom keymap Ctrl+D in .vimrc to duplicate the current line both in normal mode and insert mode:
" duplicate line in normal mode:
nnoremap <C-D> Yp
" duplicate line in insert mode:
inoremap <C-D> <Esc> Ypi
A: yyp - remember it with "yippee!"
Multiple lines with a number in between:
y7yp
A: Normal mode: see other answers.
The Ex way:
*
*:t. will duplicate the line,
*:t 7 will copy it after line 7,
*:,+t0 will copy current and next line at the beginning of the file (,+ is a synonym for the range .,.+1),
*:1,t$ will copy lines from beginning till cursor position to the end (1, is a synonym for the range 1,.).
If you need to move instead of copying, use :m instead of :t.
This can be really powerful if you combine it with :g or :v:
*
*:v/foo/m$ will move all lines not matching the pattern “foo” to the end of the file.
*:+,$g/^\s*class\s\+\i\+/t. will copy all subsequent lines of the form class xxx right after the cursor.
Reference: :help range, :help :t, :help :g, :help :m and :help :v
A: YP or Yp or yyp.
A: yy or Y to copy the line (mnemonic: yank)
or
dd to delete the line (Vim copies what you deleted into a clipboard-like "register", like a cut operation)
then
p to paste the copied or deleted text after the current line
or
Shift + P to paste the copied or deleted text before the current line
A: 1 gotcha: when you use "p" to put the line, it puts it after the line your cursor is on, so if you want to add the line after the line you're yanking, don't move the cursor down a line before putting the new line.
A: For those starting to learn vi, here is a good introduction to vi by listing side by side vi commands to typical Windows GUI Editor cursor movement and shortcut keys. It lists all the basic commands including yy (copy line) and p (paste after) or P(paste before).
vi (Vim) for Windows Users
A: If you would like to duplicate a line and paste it right away below the current like, just like in Sublime Ctrl+Shift+D, then you can add this to your .vimrc file.
nmap <S-C-d> <Esc>Yp
Or, for Insert mode:
imap <S-C-d> <Esc>Ypa
A:
Doesn't get any simpler than this! From normal mode:
yy
then move to the line you want to paste at and
p
A: yyp - paste after
yyP - paste before
A: I like:
Shift+v (to select the whole line immediately and let you select other lines if you want), y, p
A: Another option would be to go with:
nmap <C-d> mzyyp`z
gives you the advantage of preserving the cursor position.
A: You can also try <C-x><C-l> which will repeat the last line from insert mode and brings you a completion window with all of the lines. It works almost like <C-p>
A: For someone who doesn't know vi, some answers from above might mislead him with phrases like "paste ... after/before current line".
It's actually "paste ... after/before cursor".
yy or Y to copy the line
or
dd to delete the line
then
p to paste the copied or deleted text after the cursor
or
P to paste the copied or deleted text before the cursor
For more key bindings, you can visit this site: vi Complete Key Binding List
A: I like to use this mapping:
:nnoremap yp Yp
because it makes it consistent to use alongside the native YP command.
A: I use this mapping, which is similar to vscode. I hope it is useful!!!.
nnoremap <A-d> :t. <CR>==
inoremap <A-d> <Esc>:t. <CR>==gi
vnoremap <A-d> :t$ <CR>gv=gv
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1916"
}
|
Q: How to set the header sort glyph in a .NET ListView? How do I set the column which has the header sort glyph, and its direction, in a .NET 2.0 WinForms ListView?
Bump
The listview is .net is not a managed control, it is a very thin wrapper around the Win32 ListView common control. It's not even a very good wrapper - it doesn't expose all the features of the real listview.
The Win32 listview common control supports drawing itself with themes. One of the themed elements is the header sort arrow. Windows Explorer's listview common control knows how to draw one of its columns with that theme element.
*
*does the Win32 listview support specifying which column has what sort order?
*does the Win32 header control that the listview internally uses support specifying which column has what sort order?
*does the win32 header control support custom drawing, so I can draw the header sort glyph myself?
*does the win32 listview control support custom header drawing, so I can draw the header sort glyph myself?
*does the .NET ListView control support custom header drawing, so I can draw the header sort glyph myself?
A: In case someone needs a quick solution (it draws up/down arrow at the beginning of column header text):
ListViewExtensions.cs:
public static class ListViewExtensions
{
public static void DrawSortArrow(this ListView listView, SortOrder sortOrder, int colIndex)
{
string upArrow = "▲ ";
string downArrow = "▼ ";
foreach (ColumnHeader ch in listView.Columns)
{
if (ch.Text.Contains(upArrow))
ch.Text = ch.Text.Replace(upArrow, string.Empty);
else if (ch.Text.Contains(downArrow))
ch.Text = ch.Text.Replace(downArrow, string.Empty);
}
if (sortOrder == SortOrder.Ascending)
listView.Columns[colIndex].Text = listView.Columns[colIndex].Text.Insert(0, downArrow);
else
listView.Columns[colIndex].Text = listView.Columns[colIndex].Text.Insert(0, upArrow);
}
}
Usage:
private void lstOffers_ColumnClick(object sender, ColumnClickEventArgs e)
{
lstOffers.DrawSortArrow(SortOrder.Descending, e.Column);
}
A: I use unicode arrow characters in the title of the column and make the header a linkbutton.
A: There is a listview that I use that has that in-built into it. It's called XPTable..I am digging around my source code to find that helper class that will draw the glyph based on the sort order...This is the code that I have used here..
Hope this helps,
Best regards,
Tom.
A: This article is helpful, uses SendMessage DllImport.
http://www.codeproject.com/Tips/734463/Sort-listview-Columns-and-Set-Sort-Arrow-Icon-on-C
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How can I save some JavaScript state information back to my server onUnload? I have an ExtJS grid on a web page and I'd like to save some of its state information back to the server when the users leaves the page.
Can I do this with an Ajax request onUnload?
If not, what's a better solution?
A: You can use an Ajax request, but be sure to make it a synchronous request rather than an asychronous one. Alternatively, simply save state whenever the user makes a change, this also protects the data if the user's browser crashes.
A: There's an answer above that says to use a synchronous ajax call, and that is the best case scenario. The problem is that unload doesn't work everywhere. If you look here you'll find some tricks to help you get unload events in safari... You could also use Google Gears to save content user side for situations where the user will be coming back, but the only fully safe way to keep that information is to continuously send it as long as the user is on the page or making changes.
A: You could also set a cookie using javascript on unload. I think the advantage ajax has over cookies is that you have the data available to you for reporting and the user (if logged in) can utilise the data across different machines.
The disadvantage of using ajax is that it might slow down the actual closing of the browser window, which could be annoying if the server is slow to respond.
A: It depends on how the user leaves the page.
If there is a 'logoff' button in your GUI, you can trigger an ajax request when the user clicks on this button.
Otherwise I do not think it is a good idea to make a request in the onUnload. As said earlier you would have to make a synchronous request...
An alternative to the cookie solution would be an hidden text field. This is a technique usually used by tools such as RSH that deal with history issues that come with ajax.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: .NET Introspection VS Reflection What is the difference between Introspection and Reflection in .NET
A: Introspection was introduced with FxCop in 2004 as an alternative to Reflection :
What's new in FxCop 1.30 is that it
now performs analysis through a
technique called Introspection. The
use of the Introspection engine allows
for much faster analysis and supports
multithreaded analysis. Unlike the
Reflection engine from previous
versions, in the Introspection engine
the assemblies you're analyzing are
not locked so you won't need to shut
down FxCop to do a fix and recompile
of those assemblies. Finally, the
Introspection engine offers a much
richer analysis infrastructure
compared to the Reflection engine.
A: They're two parts of the same whole.
Introspection refers to the ability of a class to look 'inside' itself and see, for example, what parameters a method takes, what the names of its members are, etc.
Reflection is the specific name for how .NET implements introspection. Other languages may call it something different (C++ calls its limited introspection RTTI, for run-time type information).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How do you read JavaDoc? What tools/websites do you use to read JavaDocs?
I currently use Firefox with 20+ tabs open when working on a J2EE project to have all the documentation available which is not very usable, is eating too much memory and is not searchable.
What I would expect from such a tool/website:
*
*Aggregate JavaDocs from different locations
*Direct access to types like Ctrl+T in Eclipse or similar
*Fulltext search
*Cross referencing between all the Java libraries I've chosen
*For a tool: offline support
*Speed
not mandatory:
*
*possibility to annotate things
*support for different versions of a library (+ diffing ?)
*IDE integration
Edit:
Thanks for your answers. I knew most of the sites but gave them another try. Here is my judgement:
*
*built-in Eclipse/IDE features
*
*tightly integrated
*offline/online support
*javadoconline.com (no longer maintained)
*
*works
*clean looks
*finds matches in more than one version of the api and allows easy switching
*simple but working
*fast
*jdocs (offline)
*
*seems very sophisticated
*sometimes slow
*some recent versions of libraries seem to be missing (Seam 2.0.0, Hibernate Validators) but it looks like you can add them yourself
*IDE integration (not tested)
*wiki style comments to each item
*docjar.com
*
*works
*fast
*cluttered UI
*javadoc_isearch
*
*greasemonkey script for firefox which makes navigating javadocs easier
*works smooth and perfectly
A: If you use Eclipse, it offers support for Javadocs. For example, hovering your mouse over a method call will display a tooltip showing you the Javadoc for that method. Documentation for the core Java classes are supported out of the box. However, if your project uses any additional libraries (JAR files), some configuration is required in order to plug their Javadocs into Eclipse.
*
*Go to the "Java Build Path" section of your project properties.
*Go to the "Libraries" tab and click the "plus" icon next to the JAR file.
*Click "Javadoc location", then the "Edit..." button.
This will let you specify where the Javadocs for that JAR are located. It will even let you specify a website URL, so you don't have to download the Javadocs yourself!
A: You can find Stanford University's JavaDoc here.
A: I wrote my own tool for this. Acording to my colleagues it is best they seen.
It indexes by lucene once, and run you small server on background, so yo browse javadocs (pydocs, perldocs..) like in browser. It allows also separate libraries per language so searchses like "biginteger" or simialr dont go wrong.
https://github.com/judovana/JavadocOfflineSearch/releases
A: I use http://www.teria.com/~koseki/tools/gm/javadoc_isearch/ for FF. Lets me easily browse other libraries as well.
A: JavaDoc jar can be unzipped directly. In theory any released javadocs can be downloaded and viewed offline.
*
*download directly from maven repository. For example: http://central.maven.org/maven2/com/googlecode/objectify/objectify/5.0.3/objectify-5.0.3-javadoc.jar
*Now you get objectify-5.0.3-javadoc.jar, rename the file to objectify-5.0.3-javadoc.zip
*use your favourite unzip tool to extract it, now you have a folder objectify-5.0.3-javadoc
*double click index.html will open the index page on your default browser.
A: Eclipse integrates well with Javadoc and has an HTML-like viewer for it. You can attach source and javadoc to binaries that will show up when you select a class.
A: Something like this may be useful?
http://www.docjar.com/
A: Personally, I've never had a problem with the built-in javadoc browsing tools offered by my IDE.
Currently, I use IntelliJ Idea -- Ctl-Q brings up the javadoc for the method under the cursor, with the hyperlinks to other parts of the documentation functional.
I would imagine NetBeans and Eclipse offer similar functionality.
A: Hm... How about:
*
*http://edu.netbeans.org/quicktour/javadoc.html - NetBeans supports the Javadoc standard for Java documentation - both viewing it and generating it.
*http://globaldocs.zeevbelkin.com/ - This application allows to conveniently browse, over the Internet and local filesystem, multiple javadoc sets, using a single packages/classes hierarchy tree and a searchable index. The viewer supports local and remote docsets (the local docsets, packed to JAR/ZIP-files also are supported).
I prefer NetBeans as it get JavaDoc from Maven ~/.m2 directory automatically...
A: This plug in for Firefox and Chrome is useful for quickly finding package and class names, though it's not a full text search: https://code.google.com/p/javadoc-search-frame/
A: Doxygen (http://www.doxygen.nl/) might fit the bill.
EDIT: I may have misread your question, doxygen is a tool to generate documentation and models based off your code and javadoc.
A: Eclipse is a best way to see the javadocs. Hovering the mouse on method or any declaration you will get automatically generated javadocs by eclipse.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
}
|
Q: How to gracefully deal with ViewState errors? I'm running some c# .net pages with various gridviews. If I ever leave any of them alone in a web browser for an extended period of time (usually overnight), I get the following error when I click any element on the page.
I'm not really sure where to start dealing with the problem. I don't mind resetting the page if it's viewstate has expired, but throwing an error is unacceptable!
Error: The state information is invalid for this page and might be corrupted.
Target: Void ThrowError(System.Exception, System.String, System.String, Boolean)
Data: System.Collections.ListDictionaryInternal
Inner: System.Web.UI.ViewStateException: Invalid viewstate. Client IP: 66.35.180.246 Port: 1799 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9) Gecko/2008052906 Firefox/3.0 ViewState: (**Very long Gibberish Omitted!**)
Offending URL: (**Omitted**)
Source: System.Web
Message: The state information is invalid for this page and might be corrupted.
Stack trace: at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ClientScriptManager.EnsureEventValidationFieldLoaded() at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) at System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) at System.Web.UI.WebControls.DropDownList.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
A: That is odd as the ViewState is stored as a string in the webpage itself. So I do not see how an extended period of time would cause that error. Perhaps one or more objects on the page have been garbage collected or the application reset, so the viewstate is referencing old controls instead of the controls created when the application restarted.
Whatever the case, I feel your pain, these errors are never pleasant to debug, and I have no easy answer as to how to find the problem other than perhaps studying how ViewState works
A: You can remove this error completely by saving your view state to a database and only cleaning within the duration you need to. This also sygnificantly improves the performance of your pages even shen using relatively small viewstates.
At the very least you can inherit from the Page class and add your own ViewStateLoad routen that check to see if it has expired and reloads the default state.
Check ViewState Provider - an implementation using Provider Model Design Pattern for providing a custom Viewstate provider.
A: Alternatively if you know the time-out length then you could add a bit of javascript to the page which redirects the user to an alternative page if there has been no activity on the page after a preset period of time. You can then extend this to warn the customer that their session / page is about to expire and provide them with a means to extend it (e.g. javascript server call back).
A: The above posts give you some answers on solving the problem. If just handling the ugly error in the interim is what you're looking for, custom errors are the easiest way to gracefully handle all your "ugly yellow errors"
http://msdn.microsoft.com/en-us/library/aa479319.aspx
http://msdn.microsoft.com/en-us/library/h0hfz6fc.aspx
A: Another option is to add in a global error handler, that would capture the exception at the application level and redirect the user to a "Session Elapsed" page.
If you want an idea of a general implementation of a global error handler, I have one available on my website, I can give you the code if needed - http://iowacomputergurus.com/free-products/asp.net-global-error-handler.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: asp.net Convert CSV string to string[] Is there an easy way to convert a string from csv format into a string[] or list?
I can guarantee that there are no commas in the data.
A: If you want robust CSV handling, check out FileHelpers
A: string[] splitString = origString.Split(',');
(Following comment not added by original answerer)
Please keep in mind that this answer addresses the SPECIFIC case where there are guaranteed to be NO commas in the data.
A: Try:
Regex rex = new Regex(",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))");
string[] values = rex.Split( csvLine );
Source: http://weblogs.asp.net/prieck/archive/2004/01/16/59457.aspx
A: You can take a look at using the Microsoft.VisualBasic assembly with the
Microsoft.VisualBasic.FileIO.TextFieldParser
It handles CSV (or any delimiter) with quotes. I've found it quite handy recently.
A: String.Split is just not going to cut it, but a Regex.Split may - Try this one:
using System.Text.RegularExpressions;
string[] line;
line = Regex.Split( input, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
Where 'input' is the csv line. This will handle quoted delimiters, and should give you back an array of strings representing each field in the line.
A: There isn't a simple way to do this well, if you want to account for quoted elements with embedded commas, especially if they are mixed with non-quoted fields.
You will also probably want to convert the lines to a dictionary, keyed by the column name.
My code to do this is several hundred lines long.
I think there are some examples on the web, open source projects, etc.
A: Try this;
static IEnumerable<string> CsvParse(string input)
{
// null strings return a one-element enumeration containing null.
if (input == null)
{
yield return null;
yield break;
}
// we will 'eat' bits of the string until it's gone.
String remaining = input;
while (remaining.Length > 0)
{
if (remaining.StartsWith("\"")) // deal with quotes
{
remaining = remaining.Substring(1); // pass over the initial quote.
// find the end quote.
int endQuotePosition = remaining.IndexOf("\"");
switch (endQuotePosition)
{
case -1:
// unclosed quote.
throw new ArgumentOutOfRangeException("Unclosed quote");
case 0:
// the empty quote
yield return "";
remaining = remaining.Substring(2);
break;
default:
string quote = remaining.Substring(0, endQuotePosition).Trim();
remaining = remaining.Substring(endQuotePosition + 1);
yield return quote;
break;
}
}
else // deal with commas
{
int nextComma = remaining.IndexOf(",");
switch (nextComma)
{
case -1:
// no more commas -- read to end
yield return remaining.Trim();
yield break;
case 0:
// the empty cell
yield return "";
remaining = remaining.Substring(1);
break;
default:
// get everything until next comma
string cell = remaining.Substring(0, nextComma).Trim();
remaining = remaining.Substring(nextComma + 1);
yield return cell;
break;
}
}
}
}
A: CsvString.split(',');
A: Get a string[] of all the lines:
string[] lines = System.IO.File.ReadAllLines("yourfile.csv");
Then loop through and split those lines (this error prone because it doesn't check for commas in quote-delimited fields):
foreach (string line in lines)
{
string[] items = line.Split({','}};
}
A: string test = "one,two,three";
string[] okNow = test.Split(',');
A: string s = "1,2,3,4,5";
string myStrings[] = s.Split({','}};
Note that Split() takes an array of characters to split on.
A: separationChar[] = {';'}; // or '\t' ',' etc.
var strArray = strCSV.Split(separationChar);
A: string[] splitStrings = myCsv.Split(",".ToCharArray());
A: Some CSV files have double quotes around the values along with a comma. Therefore sometimes you can split on this string literal: ","
A: A Csv file with Quoted fields, is not a Csv file. Far more things (Excel) output without quotes rather than with quotes when you select "Csv" in a save as.
If you want one you can use, free, or commit to, here's mine that also does IDataReader/Record. It also uses DataTable to define/convert/enforce columns and DbNull.
http://github.com/claco/csvdatareader/
It doesn't do quotes.. yet. I just tossed it together a few days ago to scratch an itch.
Forgotten Semicolon: Nice link. Thanks.
cfeduke: Thanks for the tip to Microsoft.VisualBasic.FileIO.TextFieldParser. Going into CsvDataReader tonight.
A: http://github.com/claco/csvdatareader/ updated using TextFieldParser suggested by cfeduke.
Just a few props away from exposing separators/trimspaces/type ig you just need code to steal.
A: I was already splitting on tabs so this did the trick for me:
public static string CsvToTabDelimited(string line) {
var ret = new StringBuilder(line.Length);
bool inQuotes = false;
for (int idx = 0; idx < line.Length; idx++) {
if (line[idx] == '"') {
inQuotes = !inQuotes;
} else {
if (line[idx] == ',') {
ret.Append(inQuotes ? ',' : '\t');
} else {
ret.Append(line[idx]);
}
}
}
return ret.ToString();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How can I transfer my domains from my existing registrar/hosting service to something like GoDaddy? Will I have to pay again? I have about 9 months left before renewal but my current provider doesn't offer many options / control panels.
Update: thanks for everyone's help - I've finally completed this now.
I had to:
*
*Ask my old registrar to "Unlock" the domain
*Ask my old registrar to set the admin email address of the domain to my email
*Ask my old registrar for the "authcode"
*For the rest I just followed GoDaddy's instructions
What a pain in the a**
A: This is how it works
Lets say you have 9 more months for your current domain to expire
you transfer the domain to GoDaddy (or to any other decent Registrar)
you will be charged the price (little more or equal) to the price of booking a new domain
BUT, you will have the domain for 9 months + one year (or the no. of years you paid godaddy for)
So, you choose to transfer the domain and pay USD9.99 (for a year), you will have the domains for 1 year + 9 months
A: I did this when I had to switch hosts from awful, unreliable Fuitadnet. They managed the domain for me so I emailed them that I wanted to transfer my domain. (I transferred to GoDaddy.)
I don't remember all of the details, but I seem to recall it was a multiple-handshake process. First, they had to get my current registrar to release the domain; this involved having an email sent to me so I could confirm I actually wanted to release the domain. Then, I got a confirmation code that I sent to the new registrar, who did something or the other and came back with a new confirmation code. Once I entered the final confirmation code, the domain belonged to the new registrar. It took a few days and for some reason my first set of codes didn't work, but I found GoDaddy was pretty good at explaining what was going on.
I did have to pay a transfer fee, but the registration retained its length. I opted to renew it because there was a discount at the time.
If you contact your current host/registrar and they should be able to help you out; this was one of the few times I actually got good service out of fuitadnet.
A: You must have the domain unlocked with your current registrar and make sure that your contact information is up to date.
You can then have the new registrar submit a transfer request. This will result in you being sent a notification (assuming your contact information is accurate).
You will have to follow the directions in that transfer request email.
The domain may take up to a few days to fully transfer to the new registrar.
When you transfer a domain, you are effectively extending the registration for another year so you will be charged the standard transfer/registration fee.
If you have any questions, you can always contact the company you would like to become the new registrar. I am sure they would be able to walk you through their process exactly.
A: Just so you know, GoDaddy as a company has a somewhat dubious reputation. I personally have never had any problems with them but I have only a few low-profile sites and have never done anything even remotely complicated with the DNS.
A: There is a domain transfer procedure. It's kind of complex, since it's intended to keep people from stealing domains by transferring them to another registrar (like happened to sex.com back in the 90's). GoDaddy does a good job of talking you through it (I've transferred a domain to them in the past). Of course, you're going to have to pay them to register the domain for you (though they occasionally offer discounts on domain transfers).
A: You probably will have to pay. If you check with your current registrar and with your target registar and see what needs to be done with them and what the costs are.
It is diferent for every registar, even though the actual process is the same.
A: they charge you to transfer (like 6.99?), but godaddy will then renew it for a year. You usually need to contact your current hosting and have them release it for transfer, then follow godaddy's procedure for transferring a new domain in.
A: You may need to pay, but when I switched from Register.com to goDaddy.com I paid a very small amount to transfer (like $10) and also renewed the domain for another 2 years. (This turned out to be much cheaper than renewing with Register.com)
A: Yeah!! I was charged by my new registrar when I moved. Also remember you should have the secret key (transfer code) before you start your transfer process.
A: Depends on the host also. If you go with a company like BlueHost, for example, they'll give you free domain transfers from the losing registrar. I think, in fact, they may give you free transfers. They will and ask if you want to renew your domain with them which will cost you, though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Does a caching-nameserver usually cache the negative DNS response SERVFAIL Does a caching-nameserver usually cache the negative DNS response SERVFAIL?
EDIT:
To clarify the question, I can see the caching nameserver caching negative responses NXDOMAIN, NODATA. But it does not do this for SERVFAIL responses. Is this intentional?
A: SERVFAIL is covered by §7.1 of RFC2308:
Server failures fall into two major
classes. The first is where a
server can determine that it has been
misconfigured for a zone. This may
be where it has been listed as a server, but not configured to be a
server for the zone, or where it has
been configured to be a server for
the zone, but cannot obtain the zone
data for some reason. This can
occur either because the zone file
does not exist or contains errors,
or because another server from which
the zone should have been available
either did not respond or was unable
or unwilling to supply the zone.
The second class is where the
server needs to obtain an answer from
elsewhere, but is unable to do so, due
to network failures, other servers
that don't reply, or return server
failure errors, or similar.
In either case a resolver MAY cache
a server failure response. If it
does so it MUST NOT cache it for
longer than five (5) minutes, and it
MUST be cached against the specific
query tuple <query name, type,
class, server IP address>.
So basically, it's dependent on the implementation of your name server.
A: RFC 1034 describes how to cache negative responses but did not define a mechanism for returning those cache results to peer resolvers. RFC 2308 defines these attributes.
Negative caching was an optional part of the DNS Specifications...
A: One of the timeout fields in the SOA is a "negative timeout". It is usually set to a short time, such as 30 or 60 seconds. So, yes, but for a shorter time than a "positive" response.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: HashBytes() Function T-SQL What's the most efficient way to convert the output of this function from a varbinary() to a a varchar()?
A: How about this:
master.sys.fn_varbintohexstr(@binvalue)
A: For SQL Server 2008 use
CONVERT(varchar, @binary, 1)
1 - style 0x060D,
2 - 060D
http://msdn.microsoft.com/en-gb/library/ms187928.aspx
A: CONVERT(varchar, @binary)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: asp.net dropDownBox selectedIndex not being maintained I have a weird problem with a dropdownbox selectedIndex always being set to 0 upon postback. I'm not accidentally rebinding it in my code. In fact I've placed a breakpoint at the very first line of the page_load event and the value is already set to zero. The dropdown is in the master page of my project, I don't know if that makes a difference. I'm not referencing the control in my content holder.
If I set my autoPostBack = 'true' the page works fine. I don't have to change any code and the selectedIndex is maintained. I have also tried setting enableViewState on and off and it doesn't make a difference. At this point I'm grasping at straws to figure out what's going on. I've never had this problem before.
Here is the code in my page_load event.
If CartEstablished Then
txtCustNum.Visible = False
btnCustSearch.Visible = False
lblCustNum.Visible = True
ddlSalesType.Visible = False
lblSalesType.Visible = True
ddlTerms.Visible = False
lblTerms.Visible = True
lblTerms.Text = TermsDescription
Else
txtCustNum.Visible = True
btnCustSearch.Visible = True
lblCustNum.Visible = False
lblSalesType.Visible = False
ddlSalesType.Visible = True
lblTerms.Visible = False
ddlTerms.Visible = True
End If
If Page.IsPostBack Then
GetUIValues()
Else
LoadTermCodes()
End If
The LoadTermCodes is where I bind the dropdownlist that is causing me problems.
A: Are you sure you are doing a postback and not a refresh? It is hard to help you without more context into the problem or a chunk of the code.
A: This may be barking up the wrong tree, but a couple of things that have bitten me in the past that left me scratching my head:
*
*Naming the input element a duplicated/reserved word (thinking "name", "method", "reset", etc.)
*having the form element physically outside of the form being submitted
I find that when all the logical debugging turns up nothing, my own dumbness has created time-wasting "mystery" bugs like this on occasion.
A: At what stage in the page lifecycle are you binding the dropdownlist? If you're binding in page_init it should work, if you're binding in page_load make sure you wrap a !IsPostBack around the binding commands.
If you post the code in question it'd be easier to troubleshoot.
A: I'm finding the same problem... in my case, the dropdownlist is filled by a javascript function after another dropdownlist onchange client event. On PageLoad, the 2nd dropdownlist has lost all its items and so its selectedIndex turns to 0. Is there any way of preventing this?
A: This may simply be a syntax error, but shouldn't
If Page.IsPostBack Then
GetUIValues()
Else
Look like this
If NOT Page.IsPostBack Then
GetUIValues()
Else
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What's the best way to tell if a method is a property from within Policy Injection? I've got a custom handler applied to a class (using the Policy Injection Application Block in entlib 4) and I would like to know whether the input method is a property when Invoke is called. Following is what my handler looks like.
[ConfigurationElementType(typeof(MyCustomHandlerData))]
public class MyCustomHandler : ICallHandler
{
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
if (input.MethodBase.IsPublic && (input.MethodBase.Name.Contains("get_") || input.MethodBase.Name.Contains("set_")))
{
Console.WriteLine("MyCustomHandler Invoke called with input of {0}", input.MethodBase.Name);
}
return getNext().Invoke(input, getNext);
}
public int Order { get; set; }
}
As you can see from my code sample, the best way I've thought of so far is by parsing the method name. Isn't there a better way to do this?
A: You can also check IsSpecialName is true. this will be true in a property (amongst other things)
At the il level the methods are exposed as follows (using Environment.ExitCode as example):
.method public hidebysig specialname static int32 get_ExitCode() cil managed
.method public hidebysig specialname static void set_ExitCode(int32 'value') cil managed
If you wanted to get fancy you could verify after extracting the name that said property exists but to be honest
if (m.IsSpecialName && (m.Attributes & MethodAttributes.HideBySig) != 0))
as well as starts with get_ or set_ then you should be good even for people using nasty names (faking the hidebysig is easy enough, faking the IsSpecialName would be very tricky)
Nothing is guaranteed though. Someone could emit a class with a set_Foo method that looked just like a real set method but actually wasn't a set on a read only property.
Unless you check whether the property CanRead/CanWrite as well.
This strikes me as madness for you though you aren't expecting deliberate circumvention.
A simple utility/extension method on MethodInfo which did this logic wouldn't be too hard and including IsSpecialName would almost certainly cover all your needs.
A: A couple of you mentioned using the "IsSpecialName" property of the MethodBase type. While it is true that the will return true for property "gets" or "sets", it will also return true for operator overloads such as add_EventName or remove_EventName. So you will need to examine other attributes of the MethodBase instance to determine if its a property accessor. Unfortunately, if all you have is a reference to a MethodBase instance (which I believe is the case with intercepting behaviors in the Unity framework) there is not real "clean" way to determine if its a property setter or getter. The best way I've found is as follows:
C#:
bool IsPropertySetter(MethodBase methodBase){
return methodBase.IsSpecialName && methodBase.Name.StartsWith("set_");
}
bool IsPropertyGetter(MethodBase methodBase){
return methodBase.IsSpecialName && methodBase.Name.StartsWith("get_");
}
VB:
Private Function IsPropertySetter(methodBase As MethodBase) As Boolean
Return methodBase.IsSpecialName AndAlso methodBase.Name.StartsWith("set_")
End Function
Private Function IsPropertyGetter(methodBase As MethodBase) As Boolean
Return methodBase.IsSpecialName AndAlso methodBase.Name.StartsWith("get_")
End Function
A: You could check the IsSpecialName property; it will be true for property getters and setters. However, it will also be true for other special methods, like operator overloads.
A: I'm not familiar with that application block, but assuming that MethodBase property is of type System.Reflection.MethodBase, you could take a look at the IsSpecialName property.
System.Reflection.MethodBase.IsSpecialName on MSDN
A: It is a bit late but other people will read this too. In addition to IsSpecialName and checking for the set_ prefix (operators have op_, event subscr./remov. has add_,remove_) you can check if method is a match to any of properties methods like this:
bool isProperty = method.ReflectedType.GetProperties().FirstOrDefault(p =>
p.GetGetMethod().GetHashCode() == method.GetHashCode()
|| p.GetSetMethod().GetHashCode() == method.GetHashCode())!=null;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Non-blocking pthread_join I'm coding the shutdown of a multithreaded server.If everything goes as it should all the threads exit by their own, but there's a small chance that a thread gets stuck.In this case it would be convenient to have a non-blocking join so I could do.
Is there a way of doing a non-blocking pthread_join?
Some sort of timed join would be good too.
something like this:
foreach thread do
nb_pthread_join();
if still running
pthread_cancel();
I can think more cases where a a non-bloking join would be useful.
As it seems there is no such a function so I have already coded a workaround, but it's not as simple as I would like.
A: If you're developing for QNX, you can use pthread_timedjoin() function.
Otherwise, you can create a separate thread that will perform pthread_join() and alert the parent thread, by signalling a semaphore for example, that the child thread completes. This separate thread can return what is gets from pthread_join() to let the parent thread determine not only when the child completes but also what value it returns.
A: If you are running your application on Linux, you may be interested to know that:
int pthread_tryjoin_np(pthread_t thread, void **retval);
int pthread_timedjoin_np(pthread_t thread, void **retval,
const struct timespec *abstime);
Be careful, as the suffix suggests it, "np" means "non-portable". They are not POSIX standard, gnu extensions, useful though.
link to man page
A: The 'pthread_join' mechanism is a convenience to be used if it happens to do exactly what you want. It doesn't do anything you couldn't do yourself, and where it's not exactly what you want, code exactly what you want.
There is no real reason you should actually care whether a thread has terminated or not. What you care about is whether the work the thread was doing is completed. To tell that, have the thread do something to indicate that it is working. How you do that depends on what is ideal for your specific problem, which depends heavily on what the threads are doing.
Start by changing your thinking. It's not a thread that gets stuck, it's what the thread was doing that gets stuck.
A: The answer really depends on why you want to do this. If you just want to clean up dead threads, for example, it's probably easiest just to have a "dead thread cleaner" thread that loops and joins.
A: I'm not sure what exactly you mean, but I'm assuming that what you really need is a wait and notify mechanism.
In short, here's how it works: You wait for a condition to satisfy with a timeout. Your wait will be over if:
*
*The timeout occurs, or
*If the condition is satisfied.
You can have this in a loop and add some more intelligence to your logic. The best resource I've found for this related to Pthreads is this tutorial:
POSIX Threads Programming (https://computing.llnl.gov/tutorials/pthreads/).
I'm also very surprised to see that there's no API for timed join in Pthreads.
A: There is no timed pthread_join, but if you are waiting for other thread blocked on conditions, you can use timed pthread_cond_timed_wait instead of pthread_cond_wait
A: As others have pointed out there is not a non-blocking pthread_join available in the standard pthread libraries.
However, given your stated problem (trying to guarantee that all of your threads have exited on program shutdown) such a function is not needed. You can simply do this:
int killed_threads = 0;
for(i = 0; i < num_threads; i++) {
int return = pthread_cancel(threads[i]);
if(return != ESRCH)
killed_threads++;
}
if(killed_threads)
printf("%d threads did not shutdown properly\n", killed_threads)
else
printf("All threads exited successfully");
There is nothing wrong with calling pthread_cancel on all of your threads (terminated or not) so calling that for all of your threads will not block and will guarantee thread exit (clean or not).
That should qualify as a 'simple' workaround.
A: You could push a byte into a pipe opened as non-blocking to signal to the other thread when its done, then use a non-blocking read to check the status of the pipe.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: How can I highlight the current cell in a DataGridView when SelectionMode=FullRowSelect I have an editable DataGridView with SelectionMode set to FullRowSelect (so the whole row is highlighted when the user clicks on any cell). However I would like the cell that currently has focus to be highlighted with a different back color (so the user can clearly see what cell they are about to edit). How can I do this (I do not want to change the SelectionMode)?
A: I figured out a better way of doing this, using the CellFormatting event:
Private Sub uxContacts_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles uxContacts.CellFormatting
If uxContacts.CurrentCell IsNot Nothing Then
If e.RowIndex = uxContacts.CurrentCell.RowIndex And e.ColumnIndex = uxContacts.CurrentCell.ColumnIndex Then
e.CellStyle.SelectionBackColor = Color.SteelBlue
Else
e.CellStyle.SelectionBackColor = uxContacts.DefaultCellStyle.SelectionBackColor
End If
End If
End Sub
A: For me CellFormatting does the Trick. I have a set of columns that one can Edit (that I made to appear in a different color) and this is the code I used:
Private Sub Util_CellFormatting(ByVal Sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles dgvUtil.CellFormatting
If dgvUtil.CurrentCell IsNot Nothing Then
If e.RowIndex = dgvUtil.CurrentCell.RowIndex And e.ColumnIndex = dgvUtil.CurrentCell.ColumnIndex And (dgvUtil.CurrentCell.ColumnIndex = 10 Or dgvUtil.CurrentCell.ColumnIndex = 11 Or dgvUtil.CurrentCell.ColumnIndex = 13) Then
e.CellStyle.SelectionBackColor = Color.SteelBlue
Else
e.CellStyle.SelectionBackColor = dgvUtil.DefaultCellStyle.SelectionBackColor
End If
End If
End Sub
A: You want to use the DataGridView RowPostPaint method. Let the framework draw the row, and afterwards go back and color in the cell you're interested in.
An example is here at MSDN
A: Try this, the OnMouseMove method:
Private Sub DataGridView1_CellMouseMove(sender As Object, e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseMove
If e.RowIndex >= 0 Then
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.SelectionBackColor = Color.Red
End If
End Sub
Private Sub DataGridView1_CellMouseLeave(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellMouseLeave
If e.RowIndex >= 0 Then
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.SelectionBackColor = DataGridView1.DefaultCellStyle.SelectionBackColor
End If
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Not able to delete directory I am having a frequent problems with my web hosting (its shared)
I am not able to delete or change permission for a particular directory. The response is,
Cannot delete. Directory may not be empty
I checked the permissions and it looks OK. There are 100's of files in this folder which I don't want.
I contacted my support and they solved it saying it was permission issue. But it reappeared. Any suggestions?
The server is Linux.
A: You can't rmdir a directory with files in it. You must first rm all files and subdirectories. Many times, the easiest solution is:
$ rm -rf old_directory
It's entirely possible that some of the files or subdirectories have permission limitations that might prevent them from being removed. Occasionally, this can be solved with:
$ chmod -R +w old_directory
But I suspect that's what your support people did earlier.
A: This could also be because your FTP client might not be showing the hidden files (like cache, or any hiddn files that your application might create), while the hidden files are preventing you from deleting the directory. (though, in your case, I am not sure if this is the cause .. .it could be permission issue with your hosting provider.. Webserver running as another user (like apache or www) combined with your directories having global write perms).
A: I assume that's a response from an FTP server?
Usually, a message from an FTP server really means it. If it says the directory is not empty, there might be certain files you cannot see that exists in the directory which maybe one of:
*
*Your PHP/JSP/ASP/whatever scripts may run under a different user account thus creating files which you may not be able to see/delete
*Is your hosting's web interface run under your FTP account? There might be conflicting permissions there if you manage some files from the web interface and then later via FTP.
*Hosting server/operating system files created unintentionally e.g. from the hosting's web interface
If it comes from a script, write a one-time throw-away script that delete the files and that directory and then uploads and executes it.
And just to be sure, some FTP server doesn't support direct directory deletion, you need all the files first, is that the case?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I encode arbitrary data to XML using Java 1.4 and SAX? We use SAX to parse XML because it does not require the entire XML document to be read into memory in order to parse a single value. I read many articles that insisted SAX can only be used to parse/decode XML and not create it. Is this true?
A: No, it isn't true, you can encode XML to any Writer in Java using something similar to:
char[] ch;
AttributesImpl atts = new AttributesImpl();
Writer writer = new StringWriter();
StreamResult streamResult = new StreamResult(writer);
SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
// SAX2.0 ContentHandler
TransformerHandler transformerHandler = tf.newTransformerHandler();
Transformer serializer = transformerHandler.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "nodes.dtd");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
transformerHandler.setResult(streamResult);
transformerHandler.startDocument();
atts.clear();
// atts.addAttribute("", "", "xmlns", "CDATA", "http://www.example.com/nodes");
// atts.addAttribute("", "", "xmlns:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance");
// atts.addAttribute("", "", "xsi:schemaLocation", "CDATA", "/nodes.xsd");
transformerHandler.startElement("", "", "node_list", atts);
// displayName element
if (displayName != null) {
transformerHandler.startElement("", "", "display_name", null);
ch = displayName.toCharArray();
transformerHandler.characters(ch, 0, ch.length);
transformerHandler.endElement("", "", "display_name");
}
// nodes element
transformerHandler.startElement("", "", "nodes", null);
atts.clear();
atts.addAttribute("", "", "node_type", "CDATA", "sometype");
transformerHandler.startElement("", "", "node", atts);
ch = node.getValue().toCharArray();
transformerHandler.startElement("", "", "value", null);
transformerHandler.characters(ch, 0, ch.length);
transformerHandler.endElement("", "", "value");
transformerHandler.endElement("", "", "node");
transformerHandler.endElement("", "", "nodes");
transformerHandler.endElement("", "", "node_list");
transformerHandler.endDocument();
String xml = writer.toString();
A: The SAX handler interfaces were designed to be easy to implement. It's easy to write a class with similar (perhaps wrapping a SAX interface) to make it easy to call - chaining, remembering which element to close, easier attributes, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to 'bind' Text property of a label in markup Basically I would like to find a way to ddo something like:
<asp:Label ID="lID" runat="server" AssociatedControlID="txtId" Text="<%# MyProperty %>"></asp:Label>
I know I could set it from code behind (writing lId.Text = MyProperty), but I'd prefer doing it in the markup and I just can't seem to find the solution.
(MyProperty is a string property)
cheers
A: Leave the markup as is and make a call to Page.DataBind(); in your code behind.
A: <asp:Label id="lID" runat="server"><%= MyProperty %></asp:Label>
since asp.net tags do not allow <% %> constructs, you cannot use Text="<%= MyProperty %>".
A: You can do
<asp:Label runat="server" Text='<%# MyProperty %>' />
And then a Page.DataBind() in the codebehind.
A: Code expressions are an option as well. These can be used inside of quotes in ASP tags, unlike standard <%= %> tags.
The general syntax is:
<%$ resources: ResourceKey %>
There is a built-in expression for appSettings:
<%$ appSettings: AppSettingsKey %>
More info on this here: http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx
A: Call lID.Databind() from code-behind
A: <div> <%=MyProperty"%></div>
A: When you use <%# MyProperty %> declaration you need to databind it, but when using <%= MyProperty %> you don't (which is similar to just writing Response.Write(MyProperty).
A: You can do this:
<asp:Label ID="lblCurrentTime" runat="server">
Last update: <%=DateTime.Now.ToString()%>
</asp:Label>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.