Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Ok, the question might not be crystal clear. Let me give some details:
Let's say I have an Shoe (CShoe) object factory class called CFactory.
CFactory is a singleton class that creates and stores all instanciated shoes using a simple hashmap. It is then accessed through static methods to use the created objects.
Is there a way to force CShoe's constructor so that it can only called by the factory? (in other words, ensure that the creation of shoes can only be done by the shoes factory singleton class and not by other classes) | You could make `Shoe` an `inner class` of `ShoeFactory`:
```
public class ShoeFactory {
public static class Shoe {
private String name;
private Shoe() {
}
private Shoe(String name) {
this.name = name;
}
}
public static Shoe createShoe(String shoeName) {
return new Shoe(shoeName);
}
}
```
I think this pretty much covers all the cases except .... *reflection*:
```
public class SmellyShoe {
public static void main(String[] args) {
try {
java.lang.reflect.Constructor c = Shoe.class.getDeclaredConstructors()[0];
c.setAccessible(true);
Shoe smelly = (Shoe)c.newInstance(null);
// grr
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
``` | You could give the CShoe constructor package access, and put both CShoe and CFactory in the same package. | How do I make a constructor available to only the factory class? | [
"",
"java",
"class",
"oop",
"singleton",
""
] |
I know that this has already been asked [here](https://stackoverflow.com/questions/70956/exclude-certain-pages-from-using-a-httpmodule) but the answer (using a handler instead) doesn't solve the issue, as I'm using a third party component that doesn't implement IHttpHandler.
So, again, is there any way to load/unload a HttpModule on a certain request?
EDIT: I forgot to mention that we're working with .NET 2.0. I'm sorry about forgeting it. | I haven't tested this, but a [comment in this article](http://www.west-wind.com/weblog/posts/44979.aspx) seems to suggest that it is possible to register modules only for certain locations by using a `<location`> element in web.config, e.g:
```
<location path="some/path">
<system.web>
<httpModules>
<remove name="name"/>
<add name="name" type="type"/>
</httpModules>
</system.web>
</location>
``` | I assume that the problem is with the inheritance of the HttpModule, do you need the inheritance of your web.config with the third party control?
Try adding this attribute where the path will be where you component is stored;
```
<location path="/ThirdPartyComponents" inheritInChildApplications="false">
...
</location>
``` | Disabling HttpModule on certain location | [
"",
"c#",
".net",
"asp.net",
"ihttpmodule",
""
] |
In the Java code for our application I'm pretty sure there are lots of classes and methods which have `public` access but probably only need package level access.
What I'd like to do is to tidy up our code on a package by package level, making only things that really need to visible outside each package `public` as this should simplify other refactoring that I want to do.
I was wondering if there was a tool available that could help me with this. Ideally it would analyse all the code and produce a report saying which classes and method had public access but are only called from within the same package.
The *Find Usages* option in Netbeans can help me with this, but running it by hand for every class and method and analysing the output line by line will take forever. | I've used [ProGuard](http://proguard.sourceforge.net/ "ProGuard"), which is byte code manipulation tool, to find dead code in the past. There's an example in the [ProGuard manual](http://proguard.sourceforge.net/manual/examples.html#deadcode "deadcode finding") on how to use it. Note the tool does a lot of other stuff as well and it's not really a typical use of it, but it's the only thing I know of that can scan an entire application for dead code.
Edit: So I misread the question. Perhaps [UCDetector](http://www.ucdetector.org/) is what you want. It claims to be able to detect "code where the visibility could be changed to protected, default or private. It is tied to Eclipse though. I just tried UCDetector on my code base and it seems to do the job. Certainly detected some methods and classes that could have their visibility reduced. | The cheap (and quite probably faster than installing a tool for a single pass) is to search and replace `public class` to `class` and similarly for `abstract`, `final` and `interface`. Recompile. Fix what breaks until it does compile. | Is there a tool for analysing the Access Level of Java classes and methods? | [
"",
"java",
""
] |
I have a stored procedure that I want to call from within another, and then loop through the results. Sort of like using a cursor with a stored procedure rather than a SQL select statement. I can't quite figure out how to do it.
I can get the whole result like this:
```
DECLARE @result int;
EXEC @result = sp_who;
PRINT @result;
```
Interestingly, this seems to change the type of @result to something other than int, but whatever. How do I then loop through the results, row by row? How do access the data from the individual columns? For example, how would I kill processes where the forth column (loginname) is like '%gatesb' or whatever? | You would declare a table variable to hold the results of the stored procedure and then loop through them in a while loop:
```
declare @temp table (
idx int identity(1,1),
field1 int,
field2 varchar(max))
declare @result int
insert into @temp (field1, field2)
exec @result = sp_who
declare @counter int
set @counter = 1
while @counter < (select max(idx) from @temp)
begin
-- do what you want with the rows here
set @counter = @counter + 1
end
``` | Rewrite sp\_who as a table function | How do I use the results of a stored procedure from within another? | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
```
<?
$MySQLPassword = "indian";
$HostName = "localhost";
$UserName = "monty";
mysql_connect($HostName,$UserName,$MySQLPassword)
or die("ERROR: Could not connect to database!");
mysql_select_db("sachin") or die("cannot select db");
$keyword = $_POST['keyword'];
echo $keyword;
/* Execute the query that performs the actual search in the DB: */
$result = mysql_query(" SELECT p.page_url AS url,
COUNT(*) AS occurrences
FROM page p, word w, occurrence o
WHERE p.page_id = o.page_id AND
w.word_id = o.word_id AND
w.word_word = \"$keyword\"
GROUP BY p.page_id
ORDER BY occurrences DESC
" );
$output = new DOMDocument();
$output->formatOutput = true;
$output = "<loginsuccess>";
for( $i = 1; $row = mysql_fetch_array($result); $i++ ) {
$output .="<person><keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur></person>";
}
$output .= "</loginsuccess>";
print ($output);
?>
```
I am getting the output as XML, but i need to store it in a separate xml file, can any one help me out.
One more question,....
I am using fwrite and able to write into a file, but how can i clear the file each time it writes, instead of writing at the end of file? i need the existing content to be destroyed and re written again. | Use [fwrite](https://www.php.net/fwrite).
EDIT: To truncate, use:
```
$handle = fopen($filename , "wb")
```
when doing the open.
The w means open for writing and truncate to 0 length. The b means binary mode so Windows doesn't mess with your line endings. | file\_put\_contents is the easiest way of dumping a string to file. | Using PHP to output XML | [
"",
"php",
"xml",
""
] |
I'm working on a community based website using zend framework - but its so slow it takes a while for pages to load. I would like to know what aspects of the zend framework should I look into to ensure it runs much faster.
Any tips and help would be greatly appreciated :)
---
Nice advice - I took upon the database and indexed it from scratch - there werent any indexes to start with :\ but anyway the speed has improved a bit but its still rather slow. Is there anything else that I must be keeping an eye on right here?
Because I'm just assuming its something to do with the framework as when I first ran basic tutorial projects made using the framework - they were a bit slow as well.
---
Nice tips - had a look at the zend performance guide article. I'm not so sure where to put the code for caching table metadata though :( [sorry for sounding like such a noob here] as mentioned at [this link](http://framework.zend.com/manual/en/zend.db.table.html#zend.db.table.metadata.caching) | If you can be on the same LAN as the server (at least for testing), then you can verify your profile (somewhat) from a client.
If it's a single machine, the most likely cause for slowdowns is memory issues (something using too much, or too little main memory), followed by horrible DB queries.
A PHP opcode cache always seems to help, also remember to disable "atime" (noatime mount option on \*nix, a registry change on Windows) to avoid expensive disk writes.
A decent article on more Zend specific things is:
<http://till.vox.com/library/post/zendframework-performance.html> | The only way to know for sure where your bottlenecks are is doing deep profiling.
I use xdebug, combined with kcachegrind (part of kde for windows). It generates full call traces for every PHP script that is executed, which you can then inspect to find out which functions are taking up most of the time. No code changes necessary, so you can easily profile third-party libraries like Zend Framework.
* <http://www.xdebug.org/>
* <http://windows.kde.org/> | Zend Framework Performing Slow | [
"",
"php",
"zend-framework",
""
] |
How can I restrict users from entering special characters in the text box. I want only numbers and alphabets to be entered ( Typed / Pasted ).
Any samples? | You have two approaches to this:
1. check the "keypress" event. If the user presses a special character key, stop him right there
2. check the "onblur" event: when the input element loses focus, validate its contents. If the value is invalid, display a discreet warning beside that input box.
I would suggest the second method because its less irritating. Remember to also check `onpaste` . If you use only keypress Then We Can Copy and paste special characters so use `onpaste` also to restrict Pasting special characters
Additionally, I will also suggest that you reconsider if you really want to prevent users from entering special characters. Because many people have $, #, @ and \* in their passwords.
I presume that this might be in order to prevent SQL injection; if so: its better that you handle the checks server-side. Or better still, escape the values and store them in the database. | Try this one, this function allows alphanumeric and spaces:
```
function alpha(e) {
var k;
document.all ? k = e.keyCode : k = e.which;
return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}
```
in your html:
```
<input type="text" name="name" onkeypress="return alpha(event)"/>
``` | Javascript validation: Block special characters | [
"",
"javascript",
"validation",
""
] |
How can I in change the table name using a query statement?
I used the following syntax but I couldn't find the rename keyword in SQL server 2005.
```
Alter table Stu_Table rename to Stu_Table_10
``` | Use sp\_rename:
```
EXEC sp_rename 'Stu_Table', 'Stu_Table_10'
```
You can find documentation on this procedure on [MSDN](http://msdn.microsoft.com/en-us/library/ms188351%28SQL.90%29.aspx).
If you need to include a schema name, this can only be included in the first parameter (that is, this cannot be used to move a table from one schema to another). So, for example, this is valid:
```
EXEC sp_rename 'myschema.Stu_Table', 'Stu_Table_10'
``` | In `MySQL` :-
```
RENAME TABLE `Stu Table` TO `Stu Table_10`
``` | How to change a table name using an SQL query? | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
Hey! I try to do the following
```
QList<QButtonGroup*> groups;
for (int i=0; i<nGroup; i++)
{
QButtonGroup *objects = new QButtonGroup(this);
objects->setExclusive(false);
for (int j=0; j<nObject; j++)
{
Led *tempLed = new Led();
tempLed->setAutoExclusive(false);
layout->addWidget(tempLed,j,i,Qt::AlignLeft);
objects->addButton(tempLed);
}
groups.append(objects);
}
```
And then try to do something like this:
```
groups.at(1)->button(2)->setChecked(true);
```
The code compiles, but at runtime throws unhandled exception.
What am I doing wrong?
Any better way to create group of QButtonGroup? | The QButtonGroup::button function returns the button for a specific ID, but you didn't use an id when you added the button to the buttongroup. QButtonGroup::button returns 0 in your example leading to a null pointer access exception.
```
...
objects->addButton(tempLed);
...
```
If you change the code into
```
...
objects->addButton(tempLed, j );
...
```
you original code will work.
I prefer QList::at over QList::operator[] because you don't want to change the value (==pointer) in the list. | I think the problem is related with the function [at](http://doc.trolltech.com/4.5/qlist.html#at). It returns a const item, and you are calling to a non-const function in it.
Use [operator[]](http://doc.trolltech.com/4.5/qlist.html#operator-5b-5d) instead. | Qt: QList of QButtonGroup | [
"",
"c++",
"qt",
"linked-list",
""
] |
I started working on a web application. This application needs lot of image handling. I started off with [PHP](http://en.wikipedia.org/wiki/PHP) as it was the easiest and cheapest to host. I have used the .NET framework for some of my previous applications and I'm very comfortable with Python.
But I'm not at all comfortable using PHP now, so I have decided to use something easier for me.
Can anyone help me understand if the .NET framework or Python (currently web.py looks good to me)
has some edge over others, considering a lot of image manipulation and let's say about 200 requests per second?
Also I would appreciate if someone can suggest a proper host for either of them.
EDIT:
Sorry for the confusion. By image handling I mean the users of the application are allowed to upload pictures that would be stored in the flat file system while their entries are in the database.
By image manipulation, I mean I would need to create thumbnails for these images too which would be used in the application. | As mentioned previously, any number of development platforms will work, it really depends on your approach to caching the content.
If you are comfortable with Python I would recommend [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29). There is a large development community and a number of large applications and sites running on the framework.
Django internally supports caching through use of [memcached](http://en.wikipedia.org/wiki/Memcached). You are able to customize quite greatly how and what you want to cache, while being able to keep many of the settings for the caching in your actual Django application (I find this nice when using third party hosting services where I do not have complete control of the system).
Here are a few links that may help:
* [Django framework](http://www.djangoproject.com) - General information on the Django framework.
* [Memcached with Django](http://docs.djangoproject.com/en/dev/topics/cache/) - Covers how to configure caching specifically for a Django project.
* [Memcached website](http://danga.com/memcached/)
* [The Django Book](http://www.djangobook.com/en/2.0/) - A free online book to learn Django (it also covers caching and scaling quetsions).
+ [Scaling Chapter](http://www.djangobook.com/en/1.0/chapter20/)
+ [Caching Chapter](http://www.djangobook.com/en/2.0/chapter15/)
There are a number of hosting companies that offer both shared and dedicated hosting plans. I would visit <http://djangohosting.org/> to determine which host may work best for your need. I have used [WebFaction](http://www.webfaction.com) quite a bit and have been extremely pleased with their service. | Please buy Schlossnagle's book, [Scalable Internet Architectures](https://rads.stackoverflow.com/amzn/click/com/067232699X).
You should not be serving the images from Python (or PHP or .Net) but from Apache and Squid. Same is true for Javascript and CSS files -- they're static media, and Python should never touch them.
You should only be processing the HTML portion of the transaction.
This, BTW, is the architecture you get with things like [Django](http://www.djangoproject.com). Static media is handled outside Python. Python handles validation and the HTML part of the processing.
Turns out that you'll spend much of your time fussing around with Squid and Apache trying to get things to go quickly. Python (and the Django framework) are fast enough if you limit their responsibilities. | Scalable web application with lot of image servings | [
"",
".net",
"python",
"scalability",
""
] |
Is it possible to use TRY CATCH blocks in SQL Selects?
For stuff similar to this for example:
```
select
order,
CONVERT(DATETIME, orderDate)
from orders
```
What's the best way of handling this scenario? | I don't know about try-catch, but in SQL Server you have the ISDATE function and can there for do something like
```
CASE WHEN ISDATE(orderDate) = 1 THEN CONVERT(DateTime, orderDate) ELSE GETDATE() END
``` | In MS SQL Server 2012 there is a new construct that does exactly what is asked for:
```
SELECT
CASE WHEN TRY_CONVERT(float, 'test') IS NULL
THEN 'Cast failed'
ELSE 'Cast succeeded'
END AS Result;
GO
```
See also <http://msdn.microsoft.com/en-us/library/hh230993.aspx> | TRY CATCH on a CONVERT in a Select Statement | [
"",
"sql",
"t-sql",
"datetime",
"try-catch",
""
] |
Hello I have the following code
```
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string searchText = "find this text, and some other text";
string replaceText = "replace with this text";
String query = "%SystemDrive%";
string str = Environment.ExpandEnvironmentVariables(query);
string filePath = (str + "mytestfile.xml");
StreamReader reader = new StreamReader( filePath );
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace( content, searchText, replaceText );
StreamWriter writer = new StreamWriter( filePath );
writer.Write( content );
writer.Close();
}
}
}
```
the replace doesn't find the search text because it is on separate lines like
> find this text,
> and some other text.
How would I write the regex epression so that it will find the text. | Why are you trying to use regular expressions for a simple search and replace? Just use:
```
content.Replace(searchText,replaceText);
```
You may also need to add '\n' into your string to add a line break in order for the replace to match.
Try changing search text to:
```
string searchText = "find this text,\n" +
"and some other text";
``` | To search for any whitespace (spaces, line breaks, tabs, ...), you should use \s in your regular expression:
```
string searchText = @"find\s+this\s+text,\s+and\s+some\s+other\s+text";
```
Of course, this is a very limited example, but you get the idea... | C# regex with line breaks | [
"",
"c#",
"regex",
""
] |
is there a way to join 2 NodeLists returned by 2 calls of document.getElementsByTagName?
Say, I have the following code
```
var inputs = documentElement.getElementsByTagName('input');
var selects = document.getElementsByTagName('select');
```
I want to loop through the results. Is it possible in one loop?
Thank you in advance! | Seems like you can use the same Array.prototype.slice.call that makes the args array-like object become an array. ([See here](https://stackoverflow.com/questions/499814/recursively-concatenating-a-javascript-functions-arguments))
```
var inputs = document.getElementsByTagName('input');
var selects = document.getElementsByTagName('select');
inputs = Array.prototype.slice.call(inputs);
selects = Array.prototype.slice.call(selects);
var res = inputs.concat(selects);
alert(res.length);
``` | You can't join them, but you can still loop through them sequentially in one loop like this:
```
for ( var i = 0; i < inputs.length + selects.length; i++ ) {
var element = ( i < inputs.length ) ? inputs[i] : selects[i-inputs.length];
}
```
Alternatively, using jQuery, you could select them all in one go:
```
$('input, select')
``` | JavaScript NodeList | [
"",
"javascript",
"dom",
"concatenation",
"nodelist",
""
] |
When i refresh my flex application, the page does not hold its state and gets back to login page. I am not sure why this occurs, Here is my peiece of code handling session.
public function doLogin($username,$password) {
```
include("connection.php");
session_start();
session_register("session");
$query = "SELECT *
FROM users
WHERE username = '".mysql_escape_string($username)."'
AND password = '".mysql_escape_string($password)."'";
$result = mysql_fetch_array(mysql_query($query));
if(!$result) {
session_unset();
return 'no';
}
else
{
$session['id']=session_id();
$session['username']=$username;
return 'yes';
}
}
public function Logout() {
session_start();
session_register("session");
session_unset();
session_destroy();
return 'logout';
}
```
Should i do something on my Flex pane which loads after a successful login. | your problem is here
```
else
{
$session['id']=session_id();
$session['username']=$username;
return 'yes';
}
}
```
$session is not defined... if you want to store something in the session array use $\_SESSION | After successful login redirect back to some other page.
For example
```
if(doLogin($user,$pass) == 'yes')
{
Header("Location: index.php");
exit;
}
``` | Session problem during refresh | [
"",
"php",
"mysql",
"apache-flex",
""
] |
Running into a problem.
I have a table defined to hold the values of the daily treasury [**yield curve**](http://www.treas.gov/offices/domestic-finance/debt-management/interest-rate/yield.shtml).
It's a pretty simple table used for historical lookup of values.
There are notibly some gaps in the table on year `4`, `6`, `8`, `9`, `11-19` and `21-29`.
The formula is pretty simple in that to calculate year `4` it's `0.5*Year3Value + 0.5*Year5Value`.
The problem is how can I write a `VIEW` that can return the missing years?
I could probably do it in a stored procedure but the end result needs to be a view. | Taking the assumption by *Tom H.* that what you really want is a linear interpolation and the fact that not just years, but also months are missing, you need to base every calculation on MONTH, not YEAR.
For the code below I assume that you have 2 tables (one of which can be computed as part of the view):
* Yield: contains real data and stored *PeriodM* in number-of-month rather then name. If you store *PeriodName* there, you would just need to join on the table:
* Period *(can be computed in the view like shown)*: stores period name and number of months it represents
Following code must work (you just need to create a view based on it):
```
WITH "Period" (PeriodM, PeriodName) AS (
-- // I would store it as another table basically, but having it as part of the view would do
SELECT 01, '1 mo'
UNION ALL SELECT 02, '2 mo' -- // data not stored
UNION ALL SELECT 03, '3 mo'
UNION ALL SELECT 06, '6 mo'
UNION ALL SELECT 12, '1 yr'
UNION ALL SELECT 24, '2 yr'
UNION ALL SELECT 36, '3 yr'
UNION ALL SELECT 48, '4 yr' -- // data not stored
UNION ALL SELECT 60, '5 yr'
UNION ALL SELECT 72, '6 yr' -- // data not stored
UNION ALL SELECT 84, '7 yr'
UNION ALL SELECT 96, '8 yr' -- // data not stored
UNION ALL SELECT 108, '9 yr' -- // data not stored
UNION ALL SELECT 120, '10 yr'
-- ... // add more
UNION ALL SELECT 240, '20 yr'
-- ... // add more
UNION ALL SELECT 360, '30 yr'
)
, "Yield" (ID, PeriodM, Date, Value) AS (
-- // ** This is the TABLE your data is stored in **
-- //
-- // value of ID column is not important, but it must be unique (you may have your PK)
-- // ... it is used for a Tie-Breaker type of JOIN in the view
-- //
-- // This is just a test data:
SELECT 101, 01 /* '1 mo'*/, '2009-05-01', 0.06
UNION ALL SELECT 102, 03 /* '3 mo'*/, '2009-05-01', 0.16
UNION ALL SELECT 103, 06 /* '6 mo'*/, '2009-05-01', 0.31
UNION ALL SELECT 104, 12 /* '1 yr'*/, '2009-05-01', 0.49
UNION ALL SELECT 105, 24 /* '2 yr'*/, '2009-05-01', 0.92
UNION ALL SELECT 346, 36 /* '3 yr'*/, '2009-05-01', 1.39
UNION ALL SELECT 237, 60 /* '5 yr'*/, '2009-05-01', 2.03
UNION ALL SELECT 238, 84 /* '7 yr'*/, '2009-05-01', 2.72
UNION ALL SELECT 239,120 /*'10 yr'*/, '2009-05-01', 3.21
UNION ALL SELECT 240,240 /*'20 yr'*/, '2009-05-01', 4.14
UNION ALL SELECT 250,360 /*'30 yr'*/, '2009-05-01', 4.09
)
, "ReportingDate" ("Date") AS (
-- // this should be a part of the view (or a separate table)
SELECT DISTINCT Date FROM "Yield"
)
-- // This is the Final VIEW that you want given the data structure as above
SELECT d.Date, p.PeriodName, --//p.PeriodM,
CAST(
COALESCE(y_curr.Value,
( (p.PeriodM - y_prev.PeriodM) * y_prev.Value
+ (y_next.PeriodM - p.PeriodM) * y_next.Value
) / (y_next.PeriodM - y_prev.PeriodM)
) AS DECIMAL(9,4) -- // TODO: cast to your type if not FLOAT
) AS Value
FROM "Period" p
CROSS JOIN "ReportingDate" d
LEFT JOIN "Yield" y_curr
ON y_curr.Date = d.Date
AND y_curr.PeriodM = p.PeriodM
LEFT JOIN "Yield" y_prev
ON y_prev.ID = (SELECT TOP 1 y.ID FROM Yield y WHERE y.Date = d.Date AND y.PeriodM <= p.PeriodM ORDER BY y.PeriodM DESC)
LEFT JOIN "Yield" y_next
ON y_next.ID = (SELECT TOP 1 y.ID FROM Yield y WHERE y.Date = d.Date AND y.PeriodM >= p.PeriodM ORDER BY y.PeriodM ASC)
--//WHERE d.Date = '2009-05-01'
``` | You could try unpivot to get the years & values in a list.
Then union this to the missing years
select YearNo
, (select YearValue where YearNo = YearNo-1) \* 0.5 + (select YearValue where YearNo = YearNo+1) \* 0.5 AS YearValue
from unpivotedlist
where YearNo in (our missing list of years)
Then pivot it back up again to get the format you require and pop it in a view? | SQL Server view: how to add missing rows using interpolation | [
"",
"sql",
"sql-server",
"sql-view",
"linear-interpolation",
""
] |
I've got a python list of dictionaries:
```
mylist = [
{'id':0, 'weight':10, 'factor':1, 'meta':'ABC'},
{'id':1, 'weight':5, 'factor':1, 'meta':'ABC'},
{'id':2, 'weight':5, 'factor':2, 'meta':'ABC'},
{'id':3, 'weight':1, 'factor':1, 'meta':'ABC'}
]
```
Whats the most efficient/cleanest way to order that list by weight then factor (numerically). The resulting list should look like:
```
mylist = [
{'id':3, 'weight':1, 'factor':1, 'meta':'ABC'},
{'id':1, 'weight':5, 'factor':1, 'meta':'ABC'},
{'id':2, 'weight':5, 'factor':2, 'meta':'ABC'},
{'id':0, 'weight':10, 'factor':1, 'meta':'ABC'},
]
``` | ```
mylist.sort(key=lambda d: (d['weight'], d['factor']))
```
or
```
import operator
mylist.sort(key=operator.itemgetter('weight', 'factor'))
``` | Something along the lines of the following ought to work:
```
def cmp_dict(x, y):
weight_diff = y['weight'] - x['weight']
if weight_diff == 0:
return y['factor'] - x['factor']
else:
return weight_diff
myList.sort(cmp_dict)
``` | Ordering a list of dictionaries in python | [
"",
"python",
"list",
"dictionary",
""
] |
I am programming a game using Visual C++ 2008 Express and the Ogre3D sdk.
My core gameplay logic is designed to run at 100 times/second. For simplicity, I'll say it's a method called 'gamelogic()'. It is not time-based, which means if I want to "advance" game time by 1 second, I have to call 'gamelogic()' 100 times. 'gamelogic()' is lightweight in comparison to the game's screen rendering.
Ogre has a "listener" logic that informs your code when it's about to draw a frame and when it has finished drawing a frame. If I just call 'gamelogic()' just before the frame rendering, then the gameplay will be greatly affected by screen rendering speed, which could vary from 5fps to 120 fps.
The easy solution that comes to mind is : calculate the time elapsed since last rendered frame and call 'gamelogic()' this many times before the next frame: 100 \* timeElapsedInSeconds
However, I pressume that the "right" way to do it is with multithreading; have a separate thread that runs 'gamelogic()' 100 times/sec.
The question is, how do I achieve this and what can be done when there is a conflict between the 2 separate threads : gamelogic changing screen content (3d object coordinates) while Ogre is rendering the screen at the same time .
Many thanks in advance. | If this is your first game application, using multi-threading to achieve your results might be more work than you should really tackle on your first game. Sychronizing a game loop and render loop in different threads is not an easy problem to solve.
As you correctly point out, rendering time can greatly affect the "speed" of your game. I would suggest that you do not make your game logic dependent on a set time slice (i.e. 1/100 of a second). Make it dependent on the current frametime (well, the last frametime since you don't know how long your current frame will take to render).
Typically I would write something like below (what I wrote is **greatly** simplified):
```
float Frametime = 1.0f / 30.0f;
while(1) {
game_loop(Frametime); // maniuplate objects, etc.
render_loop(); // render the frame
calculate_new_frametime();
}
```
Where Frametime is the calculcated frametime that the current frame took. When you process your game loop you are using the frametime from the previous frame (so set the initial value to something reasonable, like 1/30th or 1/15th of a second). Running it on the previous frametime is close enough to get you the results that you need. Run your game loop using that time frame, then render your stuff. You might have to change the logic in your game loop to not assume a fixed time interval, but generally those kinds of fixes are pretty easy.
Asynchoronous game/render loops may be something that you ultimately need, but that is a tough problem to solve. It involves taking snapshops of objects and their relevant data, putting those snapshots into a buffer and then passing the buffer to the rendering engine. That memory buffer will have to be correctly partitioned around critical sections to avoid having the game loop write to it while the render loop is reading from it. You'll have to take care to make sure that you copy all relevant data into the buffer before passing to the render loop. Additionally, you'll have to write logic to stall either the game or render loops while waiting for one or the other to complete.
This complexity is why I suggest writing it in a more serial manner first (unless you have experience, which you might). The reason being is that doing it the "easy" way first will force you to learn about how your code works, how the rendering engine works, what kind of data the rendering engine needs, etc. Multithreading knowledge is defintely required in complex game development these days, but knowing how to do it well requires indepth knowledge of how game systems interact with each other. | There's not a whole lot of benefit to your core game logic running faster than the player can respond. About the only time it's really useful is for physics simulations, where running at a fast, fixed time step can make the sim behave more consistently.
Apart from that, just update your game loop once per frame, and pass in a variable time delta instead of relying on the fixed one. The benefit you'll get from doing multithreading is minimal compared to the cost, especially if this is your first game. | Asynchronous screen update to gameplay logic, C++ | [
"",
"c++",
"multithreading",
"asynchronous",
"ogre3d",
""
] |
Having an assembly which I cannot modify (vendor-supplied) which have a method returning an ***object*** type but is really of an internal type.
How can I access the fields and/or methods of the object from my assembly?
Keep in mind that I cannot modify the vendor-supplied assembly.
In essence, here's what I have:
From vendor:
```
internal class InternalClass
public string test;
end class
public class Vendor
private InternalClass _internal;
public object Tag {get{return _internal;}}
end class
```
From my assembly using the vendor assembly.
```
public class MyClass
{
public void AccessTest()
{
Vendor vendor = new Vendor();
object value = vendor.Tag;
// Here I want to access InternalClass.test
}
}
``` | Without access to the type (and no "InternalsVisibleTo" etc) you would have to use reflection. But a better question would be: *should* you be accessing this data? It isn't part of the public type contract... it sounds to me like it is intended to be treated as an opaque object (for their purposes, not yours).
You've described it as a public instance field; to get this via reflection:
```
object obj = ...
string value = (string)obj.GetType().GetField("test").GetValue(obj);
```
If it is actually a property (not a field):
```
string value = (string)obj.GetType().GetProperty("test").GetValue(obj,null);
```
If it is non-public, you'll need to use the `BindingFlags` overload of `GetField`/`GetProperty`.
**Important aside**: be careful with reflection like this; the implementation could change in the next version (breaking your code), or it could be obfuscated (breaking your code), or you might not have enough "trust" (breaking your code). Are you spotting the pattern? | I see only one case that you would allow exposure to your internal members to another assembly and that is for testing purposes.
Saying that there is a way to allow "Friend" assemblies access to internals:
In the AssemblyInfo.cs file of the project you add a line for each assembly.
```
[assembly: InternalsVisibleTo("name of assembly here")]
```
this info is available [here.](http://msdn.microsoft.com/en-us/library/0tke9fxk.aspx) | How can I access an internal class from an external assembly? | [
"",
"c#",
"class",
""
] |
My problem involves checking if I have a valid database connection before reading from the database. If the database is down I'd like to write to a xml file instead. I have the location of the database (if it's up) at runtime so if the database was working I can create a new sqlConnection to it. | Use a typical try...catch...finally structure, and based on the specific exception type and message, decide whether you want to write to xml or not.
```
try
{
SqlConnection connection = new SqlConnection(DB("Your DB Name"));
connection.Open();
}
catch (Exception ex)
{
// check the exception message here, if it's telling you that the db is not available. then
//write to xml file.
WriteToXml();
}
finally
{
connection.Close();
}
``` | I would just use something like:
using(SqlConnection conn = new SqlConnection(c)) {
conn.Open();
}
It will throw an exception if invalid. You could write to the xml in the exception. | Checking whether a database is available? | [
"",
"c#",
"database",
""
] |
I've been playing around with the email module in python but I want to be able to know how to embed images which are included in the html.
So for example if the body is something like
```
<img src="../path/image.png"></img>
```
I would like to embed *image.png* into the email, and the `src` attribute should be replaced with `content-id`. Does anybody know how to do this? | **For Python versions 3.4 and above.**
The accepted answer is excellent, but only suitable for older Python versions (2.x and 3.3). I think it needs an update.
Here's how you can do it in newer Python versions (3.4 and above):
```
from email.message import EmailMessage
from email.utils import make_msgid
import mimetypes
msg = EmailMessage()
# generic email headers
msg['Subject'] = 'Hello there'
msg['From'] = 'ABCD <abcd@xyz.com>'
msg['To'] = 'PQRS <pqrs@xyz.com>'
# set the plain text body
msg.set_content('This is a plain text body.')
# now create a Content-ID for the image
image_cid = make_msgid(domain='xyz.com')
# if `domain` argument isn't provided, it will
# use your computer's name
# set an alternative html body
msg.add_alternative("""\
<html>
<body>
<p>This is an HTML body.<br>
It also has an image.
</p>
<img src="cid:{image_cid}">
</body>
</html>
""".format(image_cid=image_cid[1:-1]), subtype='html')
# image_cid looks like <long.random.number@xyz.com>
# to use it as the img src, we don't need `<` or `>`
# so we use [1:-1] to strip them off
# now open the image and attach it to the email
with open('path/to/image.jpg', 'rb') as img:
# know the Content-Type of the image
maintype, subtype = mimetypes.guess_type(img.name)[0].split('/')
# attach it
msg.get_payload()[1].add_related(img.read(),
maintype=maintype,
subtype=subtype,
cid=image_cid)
# the message is ready now
# you can write it to a file
# or send it using smtplib
``` | Here is an example I found.
> [**Recipe 473810: Send an HTML email with embedded image and plain text alternate**](http://code.activestate.com/recipes/473810/):
>
> HTML is the method of choice for those
> wishing to send emails with rich text,
> layout and graphics. Often it is
> desirable to embed the graphics within
> the message so recipients can display
> the message directly, without further
> downloads.
>
> Some mail agents don't support HTML or
> their users prefer to receive plain
> text messages. Senders of HTML
> messages should include a plain text
> message as an alternate for these
> users.
>
> This recipe sends a short HTML message
> with a single embedded image and an
> alternate plain text message.
```
# Send an HTML email with an embedded image and a plain text message for
# email clients that don't want to display the HTML.
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
# Define these once; use them twice!
strFrom = 'from@example.com'
strTo = 'to@example.com'
# Create the root message and fill in the from, to, and subject headers
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgRoot.preamble = 'This is a multi-part message in MIME format.'
# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)
# We reference the image in the IMG SRC attribute by the ID we give it below
msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>Nifty!', 'html')
msgAlternative.attach(msgText)
# This example assumes the image is in the current directory
fp = open('test.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
# Send the email (this example assumes SMTP authentication is required)
import smtplib
smtp = smtplib.SMTP()
smtp.connect('smtp.example.com')
smtp.login('exampleuser', 'examplepass')
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.quit()
``` | Sending Multipart html emails which contain embedded images | [
"",
"python",
"email",
"mime",
"attachment",
"multipart",
""
] |
How can I subtract two dates when one of them is nullable?
```
public static int NumberOfWeeksOnPlan(User user)
{
DateTime? planStartDate = user.PlanStartDate; // user.PlanStartDate is: DateTime?
TimeSpan weeksOnPlanSpan;
if (planStartDate.HasValue)
weeksOnPlanSpan = DateTime.Now.Subtract(planStartDate); // This line is the problem.
return weeksOnPlanSpan == null ? 0 : weeksOnPlanSpan.Days / 7;
}
``` | Try this:
```
weeksOnPlanSpan = DateTime.Now.Subtract(planStartDate.Value);
``` | To subtract two dates when zero, one or both of them is nullable *you just subtract them*. The subtraction operator does the right thing; there's no need for you to write all the logic yourself that is already in the subtraction operator.
```
TimeSpan? timeOnPlan = DateTime.Now - user.PlanStartDate;
return timeOnPlan == null ? 0 : timeOnPlan.Days / 7;
``` | TimeSpan using a nullable date | [
"",
"c#",
"datetime",
".net-2.0",
"nullable",
""
] |
Why does the following code get the runtime error:
> Members of the Triggers collection must be of type EventTrigger
But the EventTrigger element doesn't have a Binding property.
So how do I change the color of the TextBlock based on the DataContext Property?
XAML:
```
<Window x:Class="TestTrigger123345.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel HorizontalAlignment="Left">
<TextBlock Text="{Binding Status}">
<TextBlock.Triggers>
<DataTrigger Binding="{Binding Status}" Value="off">
<Setter Property="TextBlock.Background" Value="Red"/>
</DataTrigger>
</TextBlock.Triggers>
</TextBlock>
</StackPanel>
</Window>
```
Code:
```
namespace TestTriggers
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = this;
Status = "off";
}
public string Status { get; set; }
}
}
``` | That is because you can only set event triggers directly on the Trigger property..
Use a style to achieve what you want:
```
<Style x:Key="Triggers" TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding Status}" Value="off">
<Setter Property="TextBlock.Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
```
The following objects have Triggers collections that can contain the trigger types listed:
```
FrameworkElement Style, ControlTemplate, DataTemplate
---------------- ------------------------------------
EventTrigger EventTrigger
Trigger or MultiTrigger
DataTrigger or MultiDataTrigger
``` | You can do it in a style:
```
<TextBlock Text="{Binding Status}">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding Status}" Value="off">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
``` | How can I get a trigger to change the color of a TextBlock based on a DataContext Property? | [
"",
"c#",
"wpf",
"xaml",
"triggers",
"styles",
""
] |
I have a rather small (ca. 4.5k pageviews a day) website running on Django, with PostgreSQL 8.3 as the db.
I am using the database as both the cache and the sesssion backend. I've heard a lot of good things about using Memcached for this purpose, and I would definitely like to give it a try. However, I would like to know exactly what would be the benefits of such a change: I imagine that my site may be just not big enough for the better cache backend to make a difference. The point is: it wouldn't be me who would be installing and configuring memcached, and I don't want to waste somebody's time for nothing or very little.
How can I measure the overhead introduced by using the db as the cache backend? I've looked at django-debug-toolbar, but if I understand correctly it isn't something you'd like to put on a production site (you have to set `DEBUG=True` for it to work). Unfortunately, I cannot quite reproduce the production setting on my laptop (I have a different OS, CPU and a lot more RAM).
Has anyone benchmarked different Django cache/session backends? Does anybody know what would be the performance difference if I was doing, for example, one session-write on every request? | At my previous work we tried to measure caching impact on site we was developing. On the same machine we load-tested the set of 10 pages that are most commonly used as start pages (object listings), plus some object detail pages taken randomly from the pool of ~200000. The difference was like 150 requests/second to 30000 requests/second and the database queries dropped to 1-2 per page.
What was cached:
* sessions
* lists of objects retrieved for each individual page in object listing
* secondary objects and common content (found on each page)
* lists of object categories and other *categorising properties*
* object counters (calculated offline by cron job)
* individual objects
In general, we used only low-level granular caching, not the high-level cache framework. It required very careful design (cache had to be properly invalidated upon each database state change, like adding or modifying any object). | The [DiskCache](http://www.grantjenks.com/docs/diskcache/ "Python DiskCache") project publishes [Django cache benchmarks](http://www.grantjenks.com/docs/diskcache/djangocache-benchmarks.html "DiskCache Django cache benchmarks") comparing local memory, Memcached, Redis, file based, and [diskcache.DjangoCache](http://www.grantjenks.com/docs/diskcache/api.html#djangocache "DiskCache DjangoCache"). An added benefit of DiskCache is that no separate process is necessary (unlike Memcached and Redis). Instead cache keys and small values are memory-mapped into the Django process memory. Retrieving values from the cache is generally faster than Memcached on localhost. A number of [settings](http://www.grantjenks.com/docs/diskcache/api.html#constants "DiskCache settings") control how much data is kept in memory; the rest being paged out to disk. | How to measure Django cache performance? | [
"",
"python",
"django",
"postgresql",
"caching",
"memcached",
""
] |
I read Rick Strahl's [article](http://www.west-wind.com/weblog/posts/246222.aspx) about ways to deal with the data context. My DBML is inside a class library, I keep my data context open by creating a static Current method in a separate custom partial class within library.
```
public partial class DataContext
{
public static DataContext Current
{
get
{
DataContext dc = HttpContext.Current.Items["dc"] as DataContext;
if (dc == null)
{
dc = new ImmediacyPageDataContext();
HttpContext.Current.Items["dc"] = dc;
}
return dc;
}
}
```
then access it like this
```
DataContext dc = DataContext.Current;
```
However, this causes issues whenever I update my DBML file. After editing the DBML file whenever I try and build the project my designer file doesn't regenerate/gets deleted. If I try running the custom tool option it comes back with an error.
The only way I can get round this is by renaming or deleting the custom partial class, re-generating the designer file, then adding my custom partial class back into the solution. This is a does work, but.. its a bit of a pain.
Is there a better approach to take that will make editing my DBML files easier, while prolonging my DC for as long as possible ? | Go into the code file with your partial DataContext class and move your using statements into your namespace. For some reason the tool will not generate the designer unless this is the case.
```
namespace MyNamespace
{
using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Reflection;
using System.Xml.Linq;
partial class DataContext
{
}
}
```
I believe this change was required when moving from VS2008 to VS2008 SP1, though I may be mixing up some versions. | You should create your partial class in a different file, not the .designer.cs file. The easiest way to do this is to right-click on your DBML in the solution explorer (or in a blank area in the DBML designer) and click "View Code". This will create a new .cs file that won't be overwritten when you save your DBML. | Linq to SQL DataContext Lifetime Management Issue | [
"",
"c#",
"linq",
"linq-to-sql",
""
] |
I have **array** of select tag.
```
<select id='uniqueID' name="status">
<option value="1">Present</option>
<option value="2">Absent</option>
</select>
```
and I want to create a json object having two fields 'uniqueIDofSelect and optionValue' in JavaScript.
I use getElementsByName("status") and I iterate on it.
**EDIT**
I need out put like
```
[{"selectID":2,"OptionValue":"2"},
{"selectID":4,"optionvalue":"1"}]
```
and so on... | From what I understand of your request, this should work:
```
<script>
// var status = document.getElementsByID("uniqueID"); // this works too
var status = document.getElementsByName("status")[0];
var jsonArr = [];
for (var i = 0; i < status.options.length; i++) {
jsonArr.push({
id: status.options[i].text,
optionValue: status.options[i].value
});
}
</script>
``` | ```
var sels = //Here is your array of SELECTs
var json = { };
for(var i = 0, l = sels.length; i < l; i++) {
json[sels[i].id] = sels[i].value;
}
``` | How to create json by JavaScript for loop? | [
"",
"javascript",
"json",
""
] |
I am writing a server program with one producer and multiple consumers,
what confuses me is only the first task producer put into the queue gets
consumed, after which tasks enqueued no longer get consumed, they remain
in the queue forever.
```
from multiprocessing import Process, Queue, cpu_count
from http import httpserv
import time
def work(queue):
while True:
task = queue.get()
if task is None:
break
time.sleep(5)
print "task done:", task
queue.put(None)
class Manager:
def __init__(self):
self.queue = Queue()
self.NUMBER_OF_PROCESSES = cpu_count()
def start(self):
self.workers = [Process(target=work, args=(self.queue,))
for i in xrange(self.NUMBER_OF_PROCESSES)]
for w in self.workers:
w.start()
httpserv(self.queue)
def stop(self):
self.queue.put(None)
for i in range(self.NUMBER_OF_PROCESSES):
self.workers[i].join()
queue.close()
Manager().start()
```
The producer is a HTTP server which put a task in the queue once receive
a request from the user. It seems that consumer processes are still
blocked when there are new tasks in the queue, which is weird.
P.S. Another two questions not relating to the above, I am not sure if
it's better to put HTTP server in its own process other than the main
process, if yes how can I make the main process keep running before all
children processes end. Second question, what's the best way to stop the
HTTP server gracefully?
**Edit**: add producer code, it's just a simple python wsgi server:
```
import fapws._evwsgi as evwsgi
from fapws import base
def httpserv(queue):
evwsgi.start("0.0.0.0", 8080)
evwsgi.set_base_module(base)
def request_1(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
queue.put('task_1')
return ["request 1!"]
def request_2(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
queue.put('task_2')
return ["request 2!!"]
evwsgi.wsgi_cb(("/request_1", request_1))
evwsgi.wsgi_cb(("/request_2", request_2))
evwsgi.run()
``` | I think there must be something wrong with the web server part, as this works perfectly:
```
from multiprocessing import Process, Queue, cpu_count
import random
import time
def serve(queue):
works = ["task_1", "task_2"]
while True:
time.sleep(0.01)
queue.put(random.choice(works))
def work(id, queue):
while True:
task = queue.get()
if task is None:
break
time.sleep(0.05)
print "%d task:" % id, task
queue.put(None)
class Manager:
def __init__(self):
self.queue = Queue()
self.NUMBER_OF_PROCESSES = cpu_count()
def start(self):
print "starting %d workers" % self.NUMBER_OF_PROCESSES
self.workers = [Process(target=work, args=(i, self.queue,))
for i in xrange(self.NUMBER_OF_PROCESSES)]
for w in self.workers:
w.start()
serve(self.queue)
def stop(self):
self.queue.put(None)
for i in range(self.NUMBER_OF_PROCESSES):
self.workers[i].join()
self.queue.close()
Manager().start()
```
Sample output:
```
starting 2 workers
0 task: task_1
1 task: task_2
0 task: task_2
1 task: task_1
0 task: task_1
``` | **"Second question, what's the best way to stop the HTTP server gracefully?"**
This is hard.
You have two choices for Interprocess Communication:
* Out-of-band controls. The server has another mechanism for communication. Another socket, a Unix Signal, or something else. The something else could be a "stop-now" file in the server's local directory. Seems odd, but it does work well and is simpler than introducing a select loop to listen on multiple sockets or a signal handler to catch a Unis signal.
The "stop-now" file is easy to implement. The `evwsgi.run()` loop merely checks for this file after each request. To make the server stop, you create the file, execute a `/control` request (which will get a 500 error or something, it doesn't really matter) and the server should grind to a halt. Remember to delete the stop-now file, otherwise your server won't restart.
* In-band controls. The server has another URL (`/stop`) which will stop it. Superficially, this seems like a security nightmare, but it depends entirely on where and how this server will be used. Since it appears to be a simple wrapper around an internal request queue, this extra URL works well.
To make this work, you need to write your own version of `evwsgi.run()` that can be terminated by setting some variable in a way that will break out of the loop.
**Edit**
You probably don't want to terminate your server, since you don't know the state of it's worker threads. You need to signal the server and then you just have to wait until it finishes things normally.
If you want to forcibly kill the server, then `os.kill()` (or `multiprocessing.terminate`) will work. Except, of course, you don't know what the child threads were doing. | producer/consumer problem with python multiprocessing | [
"",
"python",
"multiprocessing",
""
] |
Currently, I have been reading lists of data from a binary data file programmatically as follows:
```
tplR = (double*) malloc(sampleDim[0]*sizeof(double));
printf("tplR = %d\n", fread(tplR, sizeof(double), sampleDim[0], dfile));
```
However, as I want to use `find_if()` function on those lists, I would need to get tplR into a list type in stl. In terms of general C++ programming practice, is it usually good practice to make tplR into a list only when I really have to?
If I do make another member variable, for example, tplRList, what would be the easiest way of pushing all sampleDim[0] number of double precision entries into tplRList from tplR? Pushing them one by one until the incremental counter is equal to sampleDim[0]?
Thanks in advance. | You can use find\_if with the array like this:
```
bool equals(int p)
{
return p == 9;
}
int main(int argc,char *argv[])
{
int a[10];
for(int i = 0; i < 10; ++i)
{
a[i] = i;
}
int* p = std::find_if(a, a+10, equals);
cout<<*p;
return 0;
}
``` | You're mistaken in your assumptions. `std::find_if()` merely requires an iterator, not necessarily an STL iterator. As it happens, `double*` supports both \* and ++, so it too is an iterator. | Reading dynamically allocated arrays into lists | [
"",
"c++",
""
] |
HI All I am at the end of the release of my project.So in order to keep working our manager asked us to generate Class Diagrams for the code we had written.Its medium project with 3500 java files .So I think we need to generate class diagrams.First I need to know how reverse engineering works here. Also I looked for some tools in Google(Green, Violet) but not sure
whether they are of any help.Please suggest me how to proceed.Also a good beginning tutorial is appreciated. | **I strongly recommend** [BOUML](http://bouml.free.fr/). Its Java reverse support is absolutely **ROCK SOLID**.
BOUML has many other advanteges:
* it is extremely fast (**fastest** UML tool ever created, check out [benchmarks](http://bouml.free.fr/benchmark.html)),
* has rock solid C++, Java, PHP and others import support,
* it is multiplatform (Linux, Windows, other OSes),
* has a great SVG export support, which is important, because viewing large graphs in vector format, which scales fast in e.g. Firefox, is very convenient (you can quickly switch between "birds eye" view and class detail view),
* it is full featured, impressively intensively developed (look at [development history](http://bouml.free.fr/historic.html), it's hard to believe that such fast progress is possible).
* supports plugins, has modular architecture (this allows [user contributions](http://bouml.free.fr/contrib.html), looks like BOUML community is forming up) | The tool you want to use is [Doxygen](http://www.doxygen.org). It's similar to Javadoc, but works across multiple languages. If figures out the dependencies, and can call graphviz to render the class diagrams. Here's an example of a few [Java classes run through Doxygen](http://www.cypax.net/doxygen/html/inherits.html). | Generating Class Diagram | [
"",
"java",
"class",
"uml",
"diagrams",
""
] |
Imagine an interface with a method to create objects of type **Address**. The entities involved here are irrelevant.
```
/**
* @throws IllegalArgumentException if addy is null or invalid
* @throws PersistenceException if db layer encounters a problem
*/
Object addAddress( Address addy );
```
*addAddress* inserts the domain object into the database.
I've left the return value to be **Object**. My question is: what should the return type be ? Normally I've chosen a boolean return value (assuming no exceptions were thrown). Sometimes I've chosen to return the autogenerated PK key of the record for the **Address**. And more often than not, I just leave it as *void*. What do you normally do & why ? | `bool` is definitely no good since there will be no architecturally sound way of finding out what actually went wrong while inserting a row in a database (by "architecturally sound" I mean absence of singletons and other shared state in service layer). What there's left is a PK and `void`, of which I prefer the PK since it communicates the intent better. | I have traditionally used the approach to return the generated id or have no return value at all. But I am starting to like the idea of returning the added object itself, populated with generated PK. If the object has methods you can use the return value and invoke methods on it directly, or you can directly pass it along to some other method:
```
// invoke a method on the returned object
addAddress(theAddress).DoSomething();
// pass the object to some other method
SomeOtherMethod(addAddress(theAddress));
```
What I would not do is to use a boolean; a failure in the add method is an exceptional state and should be treated as such, throwing an exception. | In a method that performs C in CRUD, what should it return? | [
"",
"java",
"api",
"oop",
""
] |
I have a winform app that fills a lot of its dropdomn fields fram a maintenance table at runtime. Each Form has a `Private void FillMaintFields()`
I have run into a strange error where setting the column visibility on 1 form works but on another gives me an *index out of range* error!
Here is the abriged method on the *offending* form -->
```
private void FillMaintFields()
{
var myMCPTableMaint = new TableMaint();
// Index 27 is Diabetic Teaching Topics
var myDataSet = myMCPTableMaint.GetMaintItem(27);
var myDataTable = myDataSet.Tables[0];
// Diabetic TeachingTopics dropdown
chkcboDiabeticTeachingTopics.Properties.DataSource = myDataTable;
chkcboDiabeticTeachingTopics.Properties.DisplayMember = "ItemDescription";
chkcboDiabeticTeachingTopics.Properties.ValueMember = "ItemID";
// Index 26 is Diabetic Teaching
myDataSet = myMCPTableMaint.GetMaintItem(26);
myDataTable = myDataSet.Tables[0];
lkuDiabeticTeaching.Properties.DataSource = myDataTable;
lkuDiabeticTeaching.Properties.PopulateColumns();
lkuDiabeticTeaching.Properties.DisplayMember = "ItemDescription";
lkuDiabeticTeaching.Properties.ValueMember = "ItemID";
lkuDiabeticTeaching.Properties.Columns[0].Visible = false;
lkuDiabeticTeaching.Properties.Columns[1].Visible = false;
lkuDiabeticTeaching.Properties.Columns[3].Visible = false;
lkuDiabeticTeaching.Properties.Columns[4].Visible = false;
}
```
Now here is the working function on a sister form -->
```
private void FillMaintFields()
{
var myMCPTableMaint = new TableMaint();
// Index 4 is Minimum Contact Schedule
var myDataSet = myMCPTableMaint.GetMaintItem(4);
var myDataTable = myDataSet.Tables[0];
lkuMinContactSchedule.Properties.DataSource = myDataTable;
lkuMinContactSchedule.Properties.PopulateColumns();
lkuMinContactSchedule.Properties.DisplayMember = "ItemDescription";
lkuMinContactSchedule.Properties.ValueMember = "ItemID";
lkuMinContactSchedule.Properties.Columns[0].Visible = false;
lkuMinContactSchedule.Properties.Columns[1].Visible = false;
lkuMinContactSchedule.Properties.Columns[3].Visible = false;
lkuMinContactSchedule.Properties.Columns[4].Visible = false;
// Index 5 is Release of Information Updated Annually
myDataSet = myMCPTableMaint.GetMaintItem(5);
myDataTable = myDataSet.Tables[0];
lkuReleaseInfoUpdateAnnually.Properties.DataSource = myDataTable;
lkuReleaseInfoUpdateAnnually.Properties.PopulateColumns();
lkuReleaseInfoUpdateAnnually.Properties.DisplayMember = "ItemDescription";
lkuReleaseInfoUpdateAnnually.Properties.ValueMember = "ItemID";
lkuReleaseInfoUpdateAnnually.Properties.Columns[0].Visible = false;
lkuReleaseInfoUpdateAnnually.Properties.Columns[1].Visible = false;
lkuReleaseInfoUpdateAnnually.Properties.Columns[3].Visible = false;
lkuReleaseInfoUpdateAnnually.Properties.Columns[4].Visible = false;}
```
They are all using the same method in the DAL and accessing the EXACT same table which has a structure of -->
---
## |ItemID | CategoryID | ItemDescription | OrderID | Active|
I am at a loss here as to why it would work in 1 spot and not another. If I comment out the Columns[] portion in the offending Form it returns the correct data with NO errors but, of course ALL columns visible.
Ideas? Thanks!
## EDIT 1
Based on some comments and concerns:
The error appears on the first line that tries to access the Columns[]. Wherever and whatever column that may be on the offending Form.
If I debug and look at myDataTable it shows the correct columnms and correct data. | Well, I figured it out. Kinda. For some reason I need to call `lkuDiabeticTeaching.Properties.ForceInitialize();` after setting the data source on the offending form.
I can only *guess* that because I have nested forms that somehow this was trying to fire before the control was initialized.
It now looks like this -->
```
// Index 26 is Diabetic Teaching
harDataSet = myHARTableMaint.GetMaintItem(26);
harDataTable = harDataSet.Tables[0];
lkuDiabeticTeaching.Properties.DataSource = harDataTable;
lkuDiabeticTeaching.Properties.ForceInitialize();
lkuDiabeticTeaching.Properties.PopulateColumns();
lkuDiabeticTeaching.Properties.DisplayMember = "ItemDescription";
lkuDiabeticTeaching.Properties.ValueMember = "ItemID";
if(lkuDiabeticTeaching.Properties.Columns.Count > 0)
{
lkuDiabeticTeaching.Properties.Columns[0].Visible = false;
lkuDiabeticTeaching.Properties.Columns[1].Visible = false;
lkuDiabeticTeaching.Properties.Columns[3].Visible = false;
lkuDiabeticTeaching.Properties.Columns[4].Visible = false;
}
```
Thanks to all who gave of there time. | Is the error happening on the "lkuReleaseInfoUpdateAnnually" or the "lkuMinContactSchedule"? Which control is that exactly? It seems the error is on the control side of things, seems like your control in the second form doesn't have all the columns you're expecting it to have.
EDIT: You seem to be confusing the Columns in the dataTable with the columns on your control(s). I'm not sure which control you're using, but doing:
```
lkuReleaseInfoUpdateAnnually.Properties.Columns[0]
```
does NOT mean you're indexing into the DataTable. You're indexing into the columns of your control, which may or may not be there. | Index out of range error; Here but not There? | [
"",
"c#",
"winforms",
"data-binding",
"controls",
"devexpress",
""
] |
I got this parameter:
```
$objDbCmd.Parameters.Add("@telephone", [System.Data.SqlDbType]::VarChar, 18) | Out-Null;
$objDbCmd.Parameters["@telephone"].Value = $objUser.Telephone;
```
Where the string `$objUser.Telephone` can be empty. If it's empty, how can I convert it to `[DBNull]::Value`?
I tried:
```
if ([string]:IsNullOrEmpty($objUser.Telephone)) { $objUser.Telephone = [DBNull]::Value };
```
But that gives me the error:
> Exception calling "ExecuteNonQuery" with "0" argument(s): "Failed to convert parameter value from a ResultPropertyValueCollection to a String."
And if I convert it to a string, it inserts an empty string `""`, and not `DBNull`.
How can this be accomplished?
Thanks. | In PowerShell, you can treat null/empty strings as a boolean.
```
$x = $null
if ($x) { 'this wont print' }
$x = ""
if ($x) { 'this wont print' }
$x = "blah"
if ($x) { 'this will' }
```
So.... having said that you can do:
```
$Parameter.Value = $(if ($x) { $x } else { [DBNull]::Value })
```
But I'd much rather wrap this up in a function like:
```
function CatchNull([String]$x) {
if ($x) { $x } else { [DBNull]::Value }
}
``` | I don't know about powershell, but in C# I would do something like this:
```
if ([string]::IsNullOrEmpty($objUser.Telephone))
{
$objDbCmd.Parameters["@telephone"].Value = [DBNull]::Value;
}
else
{
$objDbCmd.Parameters["@telephone"].Value = $objUser.Telephone;
}
``` | Powershell and SQL parameters. If empty string, pass DBNull | [
"",
"sql",
"powershell",
"dbnull",
""
] |
While debugging crash in a multithreaded application I finally located the problem in this statement:
```
CSingleLock(&m_criticalSection, TRUE);
```
Notice that it is creating an unnamed object of CSingleLock class and hence the critical section object gets unlocked immediately after this statement. This is obviously not what the coder wanted. This error was caused by a simple typing mistake. My question is, is there someway I can prevent the temporary object of a class being created at the compile time itself i.e. the above type of code should generate a compiler error. In general, I think whenever a class tries to do some sort of resource acquisition then the temporary object of that class should not be allowed. Is there any way to enforce it? | **Edit:** As j\_random\_hacker notes, it is possible to force the user to declare a named object in order to take out a lock.
However, even if creation of temporaries was somehow banned for your class, then the user could make a similar mistake:
```
// take out a lock:
if (m_multiThreaded)
{
CSingleLock c(&m_criticalSection, TRUE);
}
// do other stuff, assuming lock is held
```
Ultimately, the user has to understand the impact of a line of code that they write. In this case, they have to know that they're creating an object and they have to know how long it lasts.
Another likely mistake:
```
CSingleLock *c = new CSingleLock(&m_criticalSection, TRUE);
// do other stuff, don't call delete on c...
```
Which would lead you to ask "Is there any way I can stop the user of my class from allocating it on the heap"? To which the answer would be the same.
In C++0x there will be another way to do all this, by using lambdas. Define a function:
```
template <class TLock, class TLockedOperation>
void WithLock(TLock *lock, const TLockedOperation &op)
{
CSingleLock c(lock, TRUE);
op();
}
```
That function captures the correct usage of CSingleLock. Now let users do this:
```
WithLock(&m_criticalSection,
[&] {
// do stuff, lock is held in this context.
});
```
This is much harder for the user to screw up. The syntax looks weird at first, but [&] followed by a code block means "Define a function that takes no args, and if I refer to anything by name and it is the name of something outside (e.g. a local variable in the containing function) let me access it by non-const reference, so I can modify it.) | First, [Earwicker makes some good points](https://stackoverflow.com/questions/914861/disallowing-creation-of-the-temporary-objects/914950#914950) -- you can't prevent every accidental misuse of this construct.
But for your specific case, this can in fact be avoided. That's because C++ does make one (strange) distinction regarding temporary objects: **Free functions cannot take non-const references to temporary objects.** So, in order to avoid locks that blip into and out of existence, just move the locking code out of the `CSingleLock` constructor and into a free function (which you can make a friend to avoid exposing internals as methods):
```
class CSingleLock {
friend void Lock(CSingleLock& lock) {
// Perform the actual locking here.
}
};
```
Unlocking is still performed in the destructor.
To use:
```
CSingleLock myLock(&m_criticalSection, TRUE);
Lock(myLock);
```
Yes, it's slightly more unwieldy to write. But now, the compiler will complain if you try:
```
Lock(CSingleLock(&m_criticalSection, TRUE)); // Error! Caught at compile time.
```
Because the non-const ref parameter of `Lock()` cannot bind to a temporary.
Perhaps surprisingly, class methods *can* operate on temporaries -- that's why `Lock()` needs to be a free function. If you drop the `friend` specifier and the function parameter in the top snippet to make `Lock()` a method, then the compiler will happily allow you to write:
```
CSingleLock(&m_criticalSection, TRUE).Lock(); // Yikes!
```
**MS COMPILER NOTE:** MSVC++ versions up to Visual Studio .NET 2003 incorrectly allowed functions to bind to non-const references in versions prior to VC++ 2005. [This behaviour has been fixed in VC++ 2005 and above](http://msdn.microsoft.com/en-us/library/cfbk5ddc(VS.80).aspx). | Disallowing creation of the temporary objects | [
"",
"c++",
"mfc",
"temporary",
""
] |
My coworker suggested making several of the Eclipse code-formatting and warning settings to be more rigorous. The majority of these changes make sense, but I get this one weird warning in Java. Here's some test code to reproduce the "problem":
```
package com.example.bugs;
public class WeirdInnerClassJavaWarning {
private static class InnerClass
{
public void doSomething() {}
}
final private InnerClass anInstance;
{
this.anInstance = new InnerClass(); // !!!
this.anInstance.doSomething();
}
}
// using "this.anInstance" instead of "anInstance" prevents another warning,
// Unqualified access to the field WeirdInnerClassJavaWarning.anInstance
```
The line with the !!! gives me this warning in Eclipse with my new warning settings:
> Access to enclosing constructor
> WeirdInnerClassJavaWarning.InnerClass()
> is emulated by a synthetic accessor
> method. Increasing its visibility will
> improve your performance.
What does this mean? The warning goes away when I change "private static class" to "protected static class", which makes no sense to me.
---
**edit:** I finally figured out the "correct" fix. The real problem here seems to be that this nested private static class is missing a public constructor. That one tweak removed the warning:
```
package com.example.bugs;
public class WeirdInnerClassJavaWarning {
private static class InnerClass
{
public void doSomething() {}
public InnerClass() {}
}
final private InnerClass anInstance;
{
this.anInstance = new InnerClass();
this.anInstance.doSomething();
}
}
```
I want the class to be a private nested class (so no other class can have access to it, including subclasses of the enclosing class) and I want it to be a static class.
I still don't understand why making the nested class protected rather than private is another method of fixing the "problem", but maybe that is a quirk/bug of Eclipse.
(apologies, I should have called it NestedClass instead of InnerClass to be more clear.) | You can get rid of the warning as follows:
```
package com.example.bugs;
public class WeirdInnerClassJavaWarning {
private static class InnerClass {
protected InnerClass() {} // This constructor makes the warning go away
public void doSomething() {}
}
final private InnerClass anInstance;
{
this.anInstance = new InnerClass();
this.anInstance.doSomething();
}
}
```
As others have said, Eclipse is complaining because a private class with no explicit constructor cannot be instantiated from outside, except via the synthetic method that the Java compiler creates. If you take your code, compile it, and then decompile it with [jad](http://en.wikipedia.org/wiki/JAD_(JAva_Decompiler)) (\*), you get the following (reformatted):
```
public class Test {
private static class InnerClass {
public void doSomething() {}
// DEFAULT CONSTRUCTOR GENERATED BY COMPILER:
private InnerClass() {}
// SYNTHETIC METHOD GENERATED BY THE JAVA COMPILER:
InnerClass(InnerClass innerclass) {
this();
}
}
public Test() {
anInstance.doSomething();
}
// Your instance initialization as modified by the compiler:
private final InnerClass anInstance = new InnerClass(null);
}
```
If you add a protected constructor, the synthetic code is unnecessary. The synthetic code is theoretically, I suppose, slower by a minescule amount than non-synthetic code using a public or protected constructor.
(\*) For jad, I linked to a Wikipedia page ... the domain that hosted this program has expired, but Wikipedia links to another that I have not tested myself. I know there are other (possibly more recent) decompilers, but this is the one I started using. Note: It *complains* when decompiling recent Java class files, but it still does a good job. | By the way, the setting to turn the warning off is in the Java Errors/Warnings page under "Code style" and is called:
> Access to a non-accessible member of an enclosing type | Eclipse warning about synthetic accessor for private static nested classes in Java? | [
"",
"java",
"eclipse",
"nested-class",
"java-synthetic-methods",
""
] |
I have some code that sets up a dictionary with some defualt values for an enum:
```
foreach (string status in Enum.GetNames(typeof(TargetStatusType)))
{
dict.Add((TargetStatusType)Enum.Parse(typeof(TargetStatusType), status), 0);
}
```
Is there an easier way to do this, as it seems a bit messy.
I was hoping I could just do
```
foreach(TargetStatusType status in ?) ...
```
Thanks! | Use [`Enum.GetValues()`](http://msdn.microsoft.com/en-us/library/system.enum.getvalues.aspx):
```
foreach (TargetStatusType type in Enum.GetValues(typeof(TargetStatusType)))
```
Note that although `GetValues()` is only declared to return `Array`, the `foreach` loop performs the cast for you automatically. Alternatively you could cast the result to `TargetStatusType[]` if you wanted to use it in a different loop where casting each value would be inconvenient. | Firstly, there's no need to use a dictionary here (or to create any sort of new collection for that matter). Also, getting the names of the enum values and then parsing them is a awfully convoluted method when you can just call `GetValues`.
The following should do the job:
```
foreach(var status in Enum.GetValues(typeof(TargetStatusType))
.Cast<TargetStatusType>())
{
// ...
}
```
The call to the `Cast` extension method means that your `status` variable is strongly-typed (of type `TargetStatusType`) rather than simply of type `object`. | Getting values from an enum | [
"",
"c#",
".net",
"enums",
""
] |
i have an array like below
```
int[] array = new array[n];// n may be 2,3,4
```
example for N = 4
```
int[] array = new array[4];
array[0] = 2;
array[1] = 4;
array[2] = 6;
array[3] = 8;
```
how i calculate all unrepeated combination of this array without using linq may be within?
2,4,6,8
2,4,8,6
2,8,6,4
2,6,4,6
8,6,4,2
2,4,6,8
.......
.......
....... | Here's a [pretty flexible C# implementation](http://www.interact-sw.co.uk/iangblog/2004/09/16/permuterate) using iterators. | Well, given that you are looking for all unrepeated combinations, that means there will be N! such combinations... (so, in your case, N! = 4! = 24 such combinations).
As I'm in the middle of posting this, dommer has pointed out a good implementation.
Just be warned that it's is going to get really slow for large values of N (since there are N! permutations). | combination question | [
"",
"c#",
"permutation",
""
] |
I'm using the jQuery Table to CSV Plugin. I've altered the popup so that it tells the browser to download a CSV file.
It was:
```
function popup(data) {
var generator = window.open('', 'csv', 'height=400,width=600');
generator.document.write('<html><head><title>CSV</title>');
generator.document.write('</head><body >');
generator.document.write('<textArea cols=70 rows=15 wrap="off" >');
generator.document.write(data);
generator.document.write('</textArea>');
generator.document.write('</body></html>');
generator.document.close();
return true;
}
```
I've changed it to:
```
function popup(data) {
window.location='data:text/csv;charset=utf8,' + encodeURIComponent(data);
return true;
}
```
It works, for the most part. It still requires that you find your spreadsheet software, and create your own filename...because it creates a strange file name (Example: 14YuskG\_.csv.part).
Any suggestions on how to improve this? | Found a solution that works (with help from <http://www.topsemtips.com/2008/11/save-html-table-to-excel-using-jquery/>):
I changed the function to:
```
function popup(data) {
$("#main div.inner").append('<form id="exportform" action="export.php" method="post" target="_blank"><input type="hidden" id="exportdata" name="exportdata" /></form>');
$("#exportdata").val(data);
$("#exportform").submit().remove();
return true;
}
```
And created the file export.php:
```
<?php
header("Content-type: application/vnd.ms-excel; name='excel'");
header("Content-Disposition: filename=export.csv");
header("Pragma: no-cache");
header("Expires: 0");
print $_REQUEST['exportdata'];
?>
```
**Update:**
A more IE7 friendly version:
```
<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=filename.csv');
print $_POST['exportdata'];
?>
``` | thanks for your question and answer, worked well for me. Here is the (almost identical) ASP.Net version of your solution that I'm using:
Change table2CSV.js popup function to:
```
function popup(data) {
$("body").append('<form id="exportform" action="CsvExport.ashx" method="post" target="_blank"><input type="hidden" id="exportdata" name="exportdata" /></form>');
$("#exportdata").val(data);
$("#exportform").submit().remove();
return true;
}
```
Noting the change from export.php to a .ashx generic handler.
The generic handler code:
```
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/force-download";
context.Response.AddHeader("content-disposition", "filename=filename.csv");
context.Response.Write(context.Request.Form["exportdata"]);
}
``` | jQuery Table to CSV export | [
"",
"javascript",
"jquery",
""
] |
I am getting a practical issue and the issue can be dascribed as follows.
We are developing a component (Say a plugin) to do some task when an event is triggered within an external CMS using the API provided by them. They have provided some jar libraries, So what we are doing is implementing an Interface provided by them. Then an internal method is called when an event is triggered. (The CMS is creating only one instance of class when the first event triggers, then it just executes the method with each event trigger)
The function can be summarized as follows,
```
import com.external.ProvidedInterface;
public class MonitorProgram implements ProvidedInterface{
public void process(){
//This method is called when an event is triggered in CMS
}
}
```
Within our class we are using "javax.net.ssl.HttpsURLConnection" (JAVA 1.5). But HttpsURLConnection migrated to javax.net.ssl from com.sun.net.ssl for 1.4. But it seems the CMS I am referring to (We dont know their implementation actually) uses something like this
```
System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
```
leading to a ClassCastException in our code.
I think my question is clear. In our case we cant set VM parameters,
```
-Djava.protocol.handler.pkgs=
```
Also we cant set it back using,
```
System.setProperty("")
```
because the VM instance is same for CMS and our program.
What can I do for get this problem resolved? And idea or experiences? | This is not clear for me.
Do you want to overwrite a system property?
You can do this.
Overwrite the System.property before calling the external library method and when the method returns you can set the old System.property back
```
final String propertyName = "Property";
String oldProperty = System.getProperty(propertyName);
System.setProperty(propertyName,"NEW_VALUE");
monitorProgram.process();
System.setProperty(propertyName,oldProperty);
```
Or do you want to prevent, that the called process overwrites the system.property?
And why you can not set the system property by hand? | I don't think you are going to have much success getting two pieces of code to use different properties.
In your own code however, you can define your own URLStreamHandlerFactory. Doing this will allow you to create a javax.net.ssl.HttpsURLConnection from a URL. While protocol handlers aren't the easiest thing to figure out, I think you can get them to do the job.
See <http://java.sun.com/developer/onlineTraining/protocolhandlers/> | Do I have any method to override System Properties in Java? | [
"",
"java",
"casting",
"jvm",
"runtime",
""
] |
How do you elegantly format a timespan to say example "1 hour 10 minutes" when you have declared it as :
```
TimeSpan t = new TimeSpan(0, 70, 0);
```
?
I am of course aware that you could do some simple maths for this, but I was kinda hoping that there is something in .NET to handle this for me - for more complicated scenarios
**Duplicate** of [How can I String.Format a TimeSpan object with a custom format in .NET?](https://stackoverflow.com/questions/574881/how-can-i-string-format-a-timespan-object-with-a-custom-format-in-net) | There is no built-in functionality for this, you'll need to use a custom method, something like:
```
TimeSpan ts = new TimeSpan(0, 70, 0);
String.Format("{0} hour{1} {2} minute{3}",
ts.Hours,
ts.Hours == 1 ? "" : "s",
ts.Minutes,
ts.Minutes == 1 ? "" : "s")
``` | ```
public static string Pluralize(int n, string unit)
{
if (string.IsNullOrEmpty(unit)) return string.Empty;
n = Math.Abs(n); // -1 should be singular, too
return unit + (n == 1 ? string.Empty : "s");
}
public static string TimeSpanInWords(TimeSpan aTimeSpan)
{
List<string> timeStrings = new List<string>();
int[] timeParts = new[] { aTimeSpan.Days, aTimeSpan.Hours, aTimeSpan.Minutes, aTimeSpan.Seconds };
string[] timeUnits = new[] { "day", "hour", "minute", "second" };
for (int i = 0; i < timeParts.Length; i++)
{
if (timeParts[i] > 0)
{
timeStrings.Add(string.Format("{0} {1}", timeParts[i], Pluralize(timeParts[i], timeUnits[i])));
}
}
return timeStrings.Count != 0 ? string.Join(", ", timeStrings.ToArray()) : "0 seconds";
}
``` | Timespan formatting | [
"",
"c#",
".net",
"timespan",
""
] |
Hey, I was working with a PHP function that takes multiple arguments and formats them. Currently, I'm working with something like this:
```
function foo($a1 = null, $a2 = null, $a3 = null, $a4 = null){
if ($a1 !== null) doSomethingWith($a1, 1);
if ($a2 !== null) doSomethingWith($a2, 2);
if ($a3 !== null) doSomethingWith($a3, 3);
if ($a4 !== null) doSomethingWith($a4, 4);
}
```
But I was wondering if I can use a solution like this:
```
function foo(params $args){
for ($i = 0; $i < count($args); $i++)
doSomethingWith($args[$i], $i + 1);
}
```
But still invoke the function the same way, similar to the params keyword in C# or the arguments array in JavaScript. | [`func_get_args`](http://php.net/manual/en/function.func-get-args.php) returns an array with all arguments of the current function. | If you use PHP 5.6+, you can now do this:
```
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?>
```
source: <http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list> | PHP get all arguments as array? | [
"",
"php",
"arrays",
"function",
"arguments",
""
] |
I'm working on a PHP app that has several objects that can be commented on. Each comment can be voted on, with users being able to give it +1 or -1 (like Digg or Reddit). Right now I'm planning on having a 'votes' table that has carries user\_id and their vote info, which seems to work fine.
The thing is, each object has hundreds of comments that are stored in a separate comments table. After I load the comments, I'm having to tally the votes and then individually check each vote against the user to make sure they can only vote once. This works but just seems really database intensive - a lot of queries for just the comments.
Is there a simpler method of doing this that is less DB intensive? Is my current database structure the best way to go?
To be clearer about current database structure:
**Comments table:**
* user\_id
* object\_id
* total\_votes
**Votes table:**
* comment\_id
* user\_id
* vote
**End Goal:**
* Allow user to vote only once on each comment with least # of MySQL queries (each object has multiple comments) | To make sure that each voter votes only once, design your Votes table with these fields—CommentID, UserID, VoteValue. Make CommentID and UserID the primary key, which will make sure that one user gets only one vote. Then, to query the votes for a comment, do something like this:
```
SELECT SUM(VoteValue)
FROM Votes
WHERE CommentID = ?
```
Does that help? | Why don't you save the totaled votes for every comment? Increment/decrement this when a new vote has happened.
Then you have to check if the user has voted specifically for this comment to allow only one vote per comment per user. | Best practice for comment voting database structure | [
"",
"php",
"mysql",
"comments",
"voting",
""
] |
I am building a pretty basic form app.
I can get a list of IP addresses available on the local machine. However, I want to also determine how these addresses are obtained (e.g. DHCP or static). How can I tell if a static IP address is configured on the system?
The goal is to inform a novice end-user (who may have no knowledge of the network setup, or how to obtain it) what static IP addresses are available. And, if no static address exist, inform them that one needs to be setup.
TIA | Unfortunately you'll probably have to use WMI. There might be another way, but this is the only way that I know.
This code will output all of the information about every adapter on your system. I think the name is "DHCPEnabled" of the property you want.
```
ManagementObjectSearcher searcherNetwork =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_NetworkAdapterConfiguration");
foreach (ManagementObject queryObj in searcherNetwork.Get())
{
foreach (var prop in queryObj.Properties)
{
Console.WriteLine(string.Format("Name: {0} Value: {1}", prop.Name, prop.Value));
}
}
``` | Better use Net.NetworkInformation due to better performance compared to WMI
```
using System.Net.NetworkInformation;
NetworkInterface[] niAdpaters = NetworkInterface.GetAllNetworkInterfaces();
private Boolean GetDhcp(Int32 iSelectedAdpater)
{
if (niAdpaters[iSelectedAdpater].GetIPProperties().GetIPv4Properties() != null)
{
return niAdpaters[iSelectedAdpater].GetIPProperties().GetIPv4Properties().IsDhcpEnabled;
}
else
{
return false;
}
}
``` | Checking static or dynamic IP address in C# .NET? | [
"",
"c#",
".net",
""
] |
i want to realize a construct in MS SQL that would look like this in Oracles PL/SQL:
```
declare
asdf number;
begin
for r in (select * from xyz) loop
insert into abc (column1, column2, column3)
values (r.asdf, r.vcxvc, r.dffgdfg) returning id into asdf;
update xyz set column10 = asdf where ID = r.ID;
end loop;
end;
```
Any idea how to realize this would be helpful.
Thanks in advance | ```
declare @asdf int/varchar -- unsure of datatype
declare @vcxvcint/varchar -- unsure of datatype
declare @dffgdfg int/varchar -- unsure of datatype
declare @id int
declare db_cursor CURSOR FOR SELECT asdf, vcxvc, dffgdfg FROM xyz
OPEN db_cursor
FETCH NEXT FROM db_cursor
INTO @asdf, @vcxvcint, @dffgdfg
WHILE @@FETCH_STATUS = 0
BEGIN
insert into abc (column1, column2, column3) values (@asdf, @vcxvcint, @vcxvcint)
set @id = scope_identity() -- This will get the auto generated ID of the last inserted row
update xyz set column10 = @asdf where id = @
FETCH NEXT FROM db_cursor INTO @name
END
CLOSE db_cursor
DEALLOCATE db_cursor
```
Of course basically all DBA's will kill you if you try and sneak a cursor into production code. | This seems to be simply a copy of one table, right?
Well:
```
SELECT column1, column2, column3 INTO abc FROM xyz
```
I think you could also to something like
```
INSERT INTO abc SELECT column1, column2, column3 FROM xyz
```
but in the second case you need to create the table before, the first instead does also create the TABLE
Cheers
Johannes | Transact-SQL: insert into xyz ( select * from abc ) | [
"",
"sql",
"sql-server",
"t-sql",
"for-loop",
""
] |
Can you give an MS Access equivalent to MySQL `CREATE TABLE IF NOT EXISTS ...`?
Something like this:
```
IF <no such table>
CREATE TABLE history(<fields>)
```
would be suitable as well | For SQL DDL code the answer is no. ACE/Jet SQL does not have any control-of-flow syntax and a ACE/Jet `PROCEDURE` can only execute one SQL statement. Yes, that's right: an ACE/Jet `PROCEDURE` does not support procedural code :( | Here is how to do it via VBA:
```
Sub ViaVBA()
Const strSQLCreateFoo_c As String = _
"CREATE TABLE Foo" & _
"(" & _
"MyField1 INTEGER," & _
"MyField2 Text(10)" & _
");"
Const strSQLAppendBs_c As String = _
"INSERT INTO Foo (MyField1, MyField2) " & _
"SELECT Bar.MyField1, Bar.MyField2 " & _
"FROM Bar " & _
"WHERE Bar.MyField2 Like 'B*';"
If Not TableExists("foo") Then
CurrentDb.Execute strSQLCreateFoo_c
End If
CurrentDb.Execute strSQLAppendBs_c
End Sub
Private Function TableExists(ByVal name As String) As Boolean
On Error Resume Next
TableExists = LenB(CurrentDb.TableDefs(name).name)
End Function
``` | Access: create table if it does not exist | [
"",
"sql",
"ms-access",
""
] |
I'm looking for a regular expression that will replace strings in an input source code with some constant string value such as "string", and that will also take into account escaping the string-start character that is denoted by a double string-start character (e.g. "he said ""hello""").
To clarify, I will provide some examples of input and expected output:
```
input: print("hello world, how are you?")
output: print("string")
input: print("hello" + "world")
output: print("string" + "string")
# here's the tricky part:
input: print("He told her ""how you doin?"", and she said ""I'm fine, thanks""")
output: print("string")
```
I'm working in Python, but I guess this is language agnostic.
EDIT: According to one of the answers, this requirement may not be fit for a regular expression. I'm not sure that's true but I'm not an expert. If I try to phrase my requirement with words, what I'm looking for is to find sets of characters that are between double quotes, wherein even groups of adjacent double quotes should be disregarded, and that sounds to me like it can be figured by a DFA.
Thanks. | If you're parsing Python code, save yourself the hassle and let the standard library's [parser module](http://docs.python.org/library/parser.html) do the heavy lifting.
If you're writing your own parser for some custom language, it's awfully tempting to start out by just hacking together a bunch of regexes, but don't do it. You'll dig yourself into an unmaintainable mess. Read up on parsing techniques and do it right (wikipedia [can](http://en.wikipedia.org/wiki/LR_parser) [help](http://en.wikipedia.org/wiki/Recursive_descent_parser)).
This regex does the trick for all three of your examples:
```
re.sub(r'"(?:""|[^"])+"', '"string"', original)
``` | Maybe:
```
re.sub(r"[^\"]\"[^\"].*[^\"]\"[^\"]",'"string"',input)
```
EDIT:
No that won't work for the final example.
I don't think your requirements are regular: they can't be matched by a regular expression. This is because at the heart of the matter, you need to match any odd number of `"` grouped together, as that is your delimiter.
I think you'll have to do it manually, counting `"`s. | Regular Expression for Stripping Strings from Source Code | [
"",
"python",
"regex",
"string",
""
] |
I have a .NET application that I want to use as a client to call an SSL SOAP web service. I have been supplied with a valid client certificate called `foo.pfx`. There is a password on the certificate itself.
I've located the certificate at the following location: `C:\certs\foo.pfx`
To call the web service, I need to attach the client certificate. Here's the code:
```
public X509Certificate GetCertificateFromDisk(){
try{
string certPath = ConfigurationManager.AppSettings["MyCertPath"].ToString();
//this evaluates to "c:\\certs\\foo.pfx". So far so good.
X509Certificate myCert = X509Certificate.CreateFromCertFile(certPath);
// exception is raised here! "The specified network password is not correct"
return cert;
}
catch (Exception ex){
throw;
}
}
```
It sounds like the exception is around the .NET application trying to read the disk. The method `CreateFromCertFile` is a static method that should create a new instance of X509Certificate. The method isn't overridden, and has only one argument: the path.
When I inspect the Exception, I find this:
```
_COMPlusExceptionCode = -532459699
Source=mscorlib
```
Question: does anyone know what the cause of the exception "The specified network password is not correct" ? | Turns out that I was trying to create a certificate from the .pfx instead of the .cer file.
Lesson learned...
* .cer files are an X.509 certificate in binary form. They are [DER encoded](http://en.wikipedia.org/wiki/Distinguished_Encoding_Rules).
* .pfx files are **container files**. Also DER encoded. They contain not only certificates, but also private keys in encrypted form. | You might need to user `X509Certificate2()` with a parameter of `X509KeyStorageFlags.MachineKeySet` instead. This fixed a similar issue we had. Credit to the original website that suggested this: <http://vdachev.net/2012/03/07/c-sharp-error-creating-x509certificate2-from-a-pfx-or-p12-file-in-production/>
Quoting:
> **Cause**
>
> The cause of the problem doesn’t seem to have much to do with the
> error messages. For some reason the constructor is trying to get
> access to the private key store although the private key is in stored
> in the file being opened. By default the user key store is used but
> ASP.NET (and probably non-interactive Windows services in general) are
> not allowed to open it. Chances are the user key store for the
> selected account doesn’t even exist.
>
> **Solution**
>
> One thing you could try is creating a user key store by logging into
> the account and importing a certificate in its Personal store (and
> then remove it again).
>
> Another solution is to pass an additional parameter to the constructor
> – a flag indicating the private keys are (supposed to be) stored in
> the local computer – X509KeyStorageFlags.MachineKeySet, like this: `var
> certificate = new X509Certificate2(fileName, password,
> X509KeyStorageFlags.MachineKeySet);`
For a PFX with no password, then password can be specified as `string.Empty`.
See also <https://stackoverflow.com/a/8291956/130352> | X509Certificate.CreateFromCertFile - the specified network password is not correct | [
"",
"c#",
"ssl-certificate",
"x509certificate",
""
] |
```
public static string RatingCalculator(int input)
{
if (input < 10)
{
return string.Empty;
}
if (input > 10 && input < 20)
{
return "<img src=\"/images/star.png\" alt=\"*\" /><img src=\"/images/star_empty.png\" alt=\"-\" /><img src=\"/images/star_empty.png\" alt=\"-\" /><img src=\"/images/star_empty.png\" alt=\"-\" /><img src=\"/images/star_empty.png\" alt=\"-\" />";
}
if (input > 21 && input < 40)
{
return "<img src=\"/images/star.png\" alt=\"*\" /><img src=\"/images/star.png\" alt=\"*\" /><img src=\"/images/star_empty.png\" alt=\"-\" /><img src=\"/images/star_empty.png\" alt=\"-\" /><img src=\"/images/star_empty.png\" alt=\"-\" />";
}
if (input > 41 && input < 70)
{
return "<img src=\"/images/star.png\" alt=\"*\" /><img src=\"/images/star.png\" alt=\"*\" /><img src=\"/images/star.png\" alt=\"*\" /><img src=\"/images/star_empty.png\" alt=\"-\" /><img src=\"/images/star_empty.png\" alt=\"-\" />";
}
if (input > 11 && input < 120)
{
return "<img src=\"/images/star.png\" alt=\"*\" /><img src=\"/images/star.png\" alt=\"*\" /><img src=\"/images/star.png\" alt=\"*\" /><img src=\"/images/star.png\" alt=\"*\" /><img src=\"/images/star_empty.png\" alt=\"-\" />";
}
else
{
return "<img src=\"/images/star.png\" alt=\"*\" /><img src=\"/images/star.png\" alt=\"*\" /><img src=\"/images/star.png\" alt=\"*\" /><img src=\"/images/star.png\" alt=\"*\" />";
}
}
``` | Look at the common parts and try and extract them.
Your image tag of a "Full Star" never changes
Your image tag of an "Empty Star" never changes
so you can extract both of those for readability into variables.
Same goes for the formatter string, there will always be "5 consecutive star types"
How about
```
string fs = @"<img src=\"/images/star.png\" alt=\"*\" />"; //Full Star
string es = @"<img src=\"/images/star_empty.png\" alt=\"-\" />"; //Empty Star
string format = @"{0}{1}{2}{3}{4}";
if(input < 10)
return string.Empty;
else if(input < 20)
return string.Format(format, fs, es, es, es, es);
else if(input < 40)
return string.Format(format, fs, fs, es, es, es);
else if(input < 70)
return string.Format(format, fs, fs, fs, es, es);
else if(input < 120)
return string.Format(format, fs, fs, fs, fs, es);
else
return string.Format(format, fs, fs, fs, fs, fs);
```
Alternatively you could use a string builder
```
string fs = @"<img src=\"/images/star.png\" alt=\"*\" />"; //Full Star
string es = @"<img src=\"/images/star_empty.png\" alt=\"-\" />"; //Empty Star
StringBuilder sb = new StringBuilder(fs);
//No need for `sb.Append (input > 10 ? fs : es);` as we'll test "input < 10" in the return statement.
sb.Append (input > 20 ? fs : es);
sb.Append (input > 40 ? fs : es);
sb.Append (input > 70 ? fs : es);
sb.Append (input > 120 ? fs : es);
return (input < 10) ? string.Empty : sb.ToString();
``` | That many string literals in code is bound to look horribly ugly. Also, I'm not sure why the gaps in the values are non-constant (or don't even increase regularly), but that's not a big issue.
Try this:
```
public static string RatingCalculator(int input)
{
int numStars;
if (input < 10)
return string.Empty;
else if (input < 20)
numStars = 1;
else if (input < 40)
numStars = 2;
else if (input < 70)
numStars = 3;
else if (input < 120)
numStars = 4;
else
numStars = 5;
var sb = new StringBuilder();
for (int i = 0; i < numStars; i++)
sb.Append("<img src=\"/images/star.png\" alt=\"*\" />");
for (int i = numStars; i < 5; i++)
sb.Append("<img src=\"/images/star_empty.png\" alt=\"-\" />");
return sb.ToString();
}
``` | is there a short way to do this? | [
"",
"c#",
""
] |
I have a Control that can overlay multiple C# user controls in my GUI. This control has a semi-transparent background in order to 'grey-out' portions of the GUI and the class looks somethink like this:
```
public greyOutControl: UserControl
{
// Usual stuff here
protected overide OnPaint()
{
paintBackround();
base.OnPaint();
}
}
```
Currently the control sometimes gets caught in a loop and constantly re-draws the background, making the semi-transparent color appear less and less transparent.
My idea to combat this is the following (in broad terms):
1) Determine what controls the greyOutControl is on top of
2) call Refresh() on those controls to update the display
3) continue drawing the greyOutControl.
My question is: How can I determine which controls the greyOutControl overlaps?, or is there a way that I can refresh only the part of the GUI that greyOutControl covers? | The solution to this problem I found was to programmatically take a screen shot of the area being overlayed and then use that image as the background for the control being overlayed. This then allows you to put the alpha overlay into the image within the OnPaint() method and the control to draw itself correctly.
This does have the disadvantage that the background isn't updated in the overlapping control, but unless there was a number of event handlers watching if something changes and then update the overlayed control I cant see any way around the issue. Sometimes I regret not trying to use WPF! | Why don't you keep track of your transparent controls and paint them after all the other controls are drawn?. Painting anything at the top of the Z-order shouldn't cause the other controls to be repainted. | c# Winforms: Refreshing a portion of a GUI (containing 1 or more controls) | [
"",
"c#",
"winforms",
"controls",
"user-controls",
""
] |
I know there is a lot of controversy (maybe not controversy, but arguments at least) about which naming convention is the best for JavaScript.
How do you name your variables, functions, objects and such?
I’ll leave my own thoughts on this out, as I haven’t been doing JavaScript for long (a couple of years, only), and I just got a request to create a document with naming conventions to be used in our projects at work. So I’ve been looking (googling) around, and there are so many different opinions.
The books I’ve read on JavaScript also use different naming conventions themselves, but they all agree on one bit: “Find what suits you, and stick to it.” But now that I’ve read so much around, I found that I like some of the other methods a bit better than what I’m used to now. | I follow [Douglas Crockford's code conventions](https://www.crockford.com/code.html) for JavaScript. I also use his [JSLint](https://www.jslint.com/) tool to validate following those conventions. | As Geoff says, what [Crockford says](http://crockford.com/javascript/code.html) is good.
The only exception I follow (and have seen widely used) is to use $varname to indicate a jQuery (or whatever library) object. E.g.
`var footer = document.getElementById('footer');`
`var $footer = $('#footer');` | JavaScript naming conventions | [
"",
"javascript",
"naming-conventions",
""
] |
I would like to show divs at a specific interval (10 seconds) and show next div and as go on and repeat the same.
\*\*
> ***Sequence :***
\*\*
On 10th second
show div1 , hide other divs ,
After 5seconds interval
Show div 2 and hide other divs,
After 5 seconds interval
Show div 3 and hide other divs,
---
> ***Code Follows:***
---
```
<div id='div1' style="display:none;">
<!-- content -->
</div>
<div id='div2' style="display:none;">
<!-- content -->
</div>
<div id='div3' style="display:none;">
<!-- content -->
</div>
``` | **[Working Example](http://jsbin.com/acumo)** here - add **/edit** to the URL to play with the code
You just need to use JavaScript [`setInterval`](https://developer.mozilla.org/En/Window.setInterval) function
```
$('html').addClass('js');
$(function() {
var timer = setInterval(showDiv, 5000);
var counter = 0;
function showDiv() {
if (counter == 0) {
counter++;
return;
}
$('div', '#container')
.stop()
.hide()
.filter(function() {
return this.id.match('div' + counter);
})
.show('fast');
counter == 3 ? counter = 0 : counter++;
}
});
```
```
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body {
background-color: #fff;
font: 16px Helvetica, Arial;
color: #000;
}
.display {
width: 300px;
height: 200px;
border: 2px solid #000;
}
.js .display {
display: none;
}
</style>
</head>
<body>
<h2>Example of using setInterval to trigger display of Div</h2>
<p>The first div will display after 10 seconds...</p>
<div id='container'>
<div id='div1' class='display' style="background-color: red;">
div1
</div>
<div id='div2' class='display' style="background-color: green;">
div2
</div>
<div id='div3' class='display' style="background-color: blue;">
div3
</div>
<div>
</body>
</html>
```
**EDIT:**
In response to your comment about the container div, just modify this
```
$('div','#container')
```
to this
```
$('#div1, #div2, #div3')
``` | Loop through divs every 10 seconds.
```
$(function () {
var counter = 0,
divs = $('#div1, #div2, #div3');
function showDiv () {
divs.hide() // hide all divs
.filter(function (index) { return index == counter % 3; }) // figure out correct div to show
.show('fast'); // and show it
counter++;
}; // function to loop through divs and show correct div
showDiv(); // show first div
setInterval(function () {
showDiv(); // show next div
}, 10 * 1000); // do this every 10 seconds
});
``` | Show and hide divs at a specific time interval using jQuery | [
"",
"javascript",
"jquery",
"css",
"html",
"timeout",
""
] |
I would like to be able to abort a specific sql statement if it takes longer than a specified number of seconds. How can I do that?
For example, I would like to do something like:
```
SET NextStatementTimeOutSeconds = 60
SELECT * FROM MyTable
IF @@LastStatementTimedOut = 1
PRINT 'Statement timed out after 60 seconds'
ELSE
PRINT 'Statement completed in less than 60 seconds'
```
Please note that I made up `NextStatementTimeOutSeconds` and `@@LastStatementTimedOut` in order to illustrate what I would like to do.
---
Thanks for the suggestions. I'm thinking about using such a timeout inside a single sql script/batch like the one above, if possible.
Background: We have several stored procedures that I'd like to be faster than X seconds. So I'd call them one after each other; and if one takes more than X seconds, I'd just abort and print a statement like 'sproc 13 takes too long'. The data varies and I'm trying different index changes, so I'd like to time-test all sprocs after such changes in order to make sure that all of them are below X seconds. | Typically the timeout is set on the command that issues the SQL statement. If that's in C# for example, then you set the IDbCommand.CommandTimeout property and it'll throw a SQLException after the timeout expires if the statement hasn't completed. This will then rollback any transactions.
In scheduled tasks on SQL Server, I'd expect that when you configure the job, there will be a value in an up/down control somewhere that allows you to change the timeout of the job. I think the terminology in SQL Server is a "Execution Timeout" but I don't know how to set it I'm afraid.
The point is - look at the thing running the statement, rather than the actual statement itself. | You can use the [query governor](http://msdn.microsoft.com/en-us/library/ms190419.aspx) to limit the time a query can run. Downside is, it is a global option affecting all queries launched against a specific database.
> Use the query governor cost limit
> option to specify an upper limit on
> the time period in which a query can
> run. Query cost refers to the
> estimated elapsed time, in seconds,
> required to complete a query on a
> specific hardware configuration.
>
> If you specify a nonzero, nonnegative
> value, the query governor disallows
> execution of any query that has an
> estimated cost exceeding that value.
> Specifying 0 (the default) for this
> option turns off the query governor,
> and all queries are allowed to run
> without any time limitation.
>
> If you use sp\_configure to change the
> value of query governor cost limit,
> the changed value is server wide. To
> change the value on a per-connection
> basis, use the SET
> QUERY\_GOVERNOR\_COST\_LIMIT statement.
>
> The query governor cost limit option
> is an advanced option. If you are
> using the sp\_configure system stored
> procedure to change the setting, you
> can change query governor cost limit
> only when show advanced options is set
> to 1. The setting takes effect
> immediately (without a server
> restart). | Can I abort a specific sql statement after a given timespan? | [
"",
"sql",
"timeout",
""
] |
I am looking for a simple way to import/copy images from remote server to a local folder using PHP. I have no FTP access to the server, but all remote images can be accessed via HTTP (i.e. <http://www.mydomain.com/myimage.jpg>).
Example use: A user wishes to add an image to his profile. The image already exists on the web and the user provides with a direct URL. I do not wish to hotlink the image but to import and serve from my domain. | If you have PHP5 and the HTTP stream wrapper enabled on your server, it's incredibly simple to copy it to a local file:
```
copy('http://somedomain.com/file.jpeg', '/tmp/file.jpeg');
```
This will take care of any pipelining etc. that's needed. If you need to provide some HTTP parameters there is a third 'stream context' parameter you can provide. | if nothing works, use this quick solution
```
$imageString = file_get_contents("http://example.com/image.jpg");
$save = file_put_contents('Image/saveto/image.jpg',$imageString);
``` | Copy Image from Remote Server Over HTTP | [
"",
"php",
"image",
"import",
"curl",
"copy",
""
] |
I am mainly a Python programmer. Now I am trying to learn C# .NET.
I see there is a .NET Framework Reference here: <http://msdn.microsoft.com/en-us/library/d11h6832.aspx>
But it is quite user unfriendly. I can't even find System.Console without digging through System namespace even though they have System.CodeDom or System.Collections.
I personally think the [python library reference](http://docs.python.org/library/) is pretty good. So what I want to know is if there are any alternative references for .NET that are more clear. | With MSDN one of the small things that is good about it is that if you're looking for documentation on a specific type then you can just type in <http://msdn.microsoft.com/en-us/library/>< TYPE NAME WITH NAMESPACE >.aspx and you should get documentation for that class.
Other than that just hang out on SO and read a few books. | I use a bookmarklet to MSDN, just save this as a bookmark:
```
javascript:var a = prompt('MSDN Reference Lookup', 'Enter class name');if(a!=null){window.location='http://msdn.microsoft.com/en-us/library/' + a + '.aspx';}
```
And enter fully qualified class names (like System.IO.StreamReader) and you're set. | Any user friendly .NET reference guides for C#? | [
"",
"c#",
".net",
""
] |
I'm looking to do the equivalent of Python's `inspect.getargspec()` in Javascript.
I do know that you can get the `arguments` list from a Javascript function, but what I'm really looking for is the *names* of the arguments from the originally defined function.
If this is in fact impossible, I'm going to have to 'brute-force' it by getting the string of the function, i.e. `myFunc.toString()` and then parsing out the `...` inside of `function myFunc(...)`. Does anyone know how to do this parsing in a general way?
Thanks for any tips. | While I can't see any good reason for this,
```
var reg = /\(([\s\S]*?)\)/;
var params = reg.exec(func);
if (params)
var param_names = params[1].split(',');
```
assuming `func` is the name of your function | The following function will return an array of parameter names of any function passed in.
```
function getParamNames(func) {
var funStr = func.toString();
return funStr.slice(funStr.indexOf('(')+1, funStr.indexOf(')')).match(/([^\s,]+)/g);
}
```
Example usage:
```
getParamNames(getParamNames) // returns ['func']
getParamNames(function (a,b,c,d){}) // returns ['a','b','c','d']
``` | Inspect the names/values of arguments in the definition/execution of a JavaScript function | [
"",
"javascript",
"arguments",
"inspection",
""
] |
I have 2 tables in DB:
1- Element:
* ElementID
* ElementName
2- Methods:
* MethodID
* ElementID
* MethodData
So there is a one to many relation between Elements and Methods,
I load these tables data using asp.net,
What i want to do is to send these data to my javascript, and javascript will do some functions on these data.
For example will loop through all elements and get each element methods and do some stuff with each method data.
I tried to make this as classes in jaascript but found my self wrote a lot of things,
First 2 classes, for elements and methods, then 2 arrays 1- for elements 2- for methods
And inside the methods array i wrote this:
```
this.findByElementId = function(elementId) {
var result = [];
for (var i = 0; i < this.methods.length; i++) {
if (elementId === this.methods[i].methodElement) {
result.push(this.methods[i]);
}
}
return result;
}
```
which made my code slow.
My Question is how to represent this relational structure in javascript for more professional code and faster in processing ? | ```
function Element() {
this.id;
this.type;
this.methods = new Array();
```
}
```
function Method() {
this.id;
this.methodType;
this.methodData;
this.methodElement;
this.methodRank;
}
``` | I've never tried this stuff myself, but people have written LINQ-esque libraries for JavaScript, like [JSINQ](http://www.codeplex.com/jsinq). (That page links to more JS LINQ libraries at the bottom of the page, too.)
It claims that you can "write arbitrarily complex queries against JavaScript arrays, DOM node lists or your own enumerable types", which sounds like what you want. | How to build a relational structure in javascript? | [
"",
"javascript",
"oop",
"relational",
""
] |
I want to ensure that a division of integers is always rounded up if necessary. Is there a better way than this? There is a lot of casting going on. :-)
```
(int)Math.Ceiling((double)myInt1 / myInt2)
``` | UPDATE: This question was [the subject of my blog in January 2013](http://ericlippert.com/2013/01/28/integer-division-that-rounds-up). Thanks for the great question!
---
Getting integer arithmetic correct is hard. As has been demonstrated amply thus far, the moment you try to do a "clever" trick, odds are good that you've made a mistake. And when a flaw is found, changing the code to fix the flaw *without considering whether the fix breaks something else* is not a good problem-solving technique. So far we've had I think five different incorrect integer arithmetic solutions to this completely not-particularly-difficult problem posted.
The right way to approach integer arithmetic problems -- that is, the way that increases the likelihood of getting the answer right the first time - is to approach the problem carefully, solve it one step at a time, and use good engineering principles in doing so.
**Start by reading the specification for what you're trying to replace.** The specification for integer division clearly states:
1. The division rounds the result towards zero
2. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs
3. If the left operand is the smallest representable int and the right operand is –1, an overflow occurs. [...] it is implementation-defined as to whether [an ArithmeticException] is thrown or the overflow goes unreported with the resulting value being that of the left operand.
4. If the value of the right operand is zero, a System.DivideByZeroException is thrown.
What we want is an integer division function which computes the quotient but rounds the result *always upwards*, not *always towards zero*.
**So write a specification for that function.** Our function `int DivRoundUp(int dividend, int divisor)` must have behaviour defined for every possible input. That undefined behaviour is deeply worrying, so let's eliminate it. We'll say that our operation has this specification:
1. operation throws if divisor is zero
2. operation throws if dividend is int.minval and divisor is -1
3. if there is no remainder -- division is 'even' -- then the return value is the integral quotient
4. Otherwise it returns the *smallest* integer that is *greater* than the quotient, that is, it always rounds up.
Now we have a specification, so we know we can come up with a **testable design**. Suppose we add an additional design criterion that the problem be solved solely with integer arithmetic, rather than computing the quotient as a double, since the "double" solution has been explicitly rejected in the problem statement.
So what must we compute? Clearly, to meet our spec while remaining solely in integer arithmetic, we need to know three facts. First, what was the integer quotient? Second, was the division free of remainder? And third, if not, was the integer quotient computed by rounding up or down?
Now that we have a specification and a design, we can start writing code.
```
public static int DivRoundUp(int dividend, int divisor)
{
if (divisor == 0 ) throw ...
if (divisor == -1 && dividend == Int32.MinValue) throw ...
int roundedTowardsZeroQuotient = dividend / divisor;
bool dividedEvenly = (dividend % divisor) == 0;
if (dividedEvenly)
return roundedTowardsZeroQuotient;
// At this point we know that divisor was not zero
// (because we would have thrown) and we know that
// dividend was not zero (because there would have been no remainder)
// Therefore both are non-zero. Either they are of the same sign,
// or opposite signs. If they're of opposite sign then we rounded
// UP towards zero so we're done. If they're of the same sign then
// we rounded DOWN towards zero, so we need to add one.
bool wasRoundedDown = ((divisor > 0) == (dividend > 0));
if (wasRoundedDown)
return roundedTowardsZeroQuotient + 1;
else
return roundedTowardsZeroQuotient;
}
```
Is this clever? No. Beautiful? No. Short? No. Correct according to the specification? *I believe so, but I have not fully tested it.* It looks pretty good though.
We're professionals here; use good engineering practices. Research your tools, specify the desired behaviour, consider error cases first, and **write the code to emphasize its obvious correctness.** And when you find a bug, consider whether your algorithm is deeply flawed to begin with before you just randomly start swapping the directions of comparisons around and break stuff that already works. | All the answers here so far seem rather over-complicated.
In C# and Java, for positive dividend and divisor, you simply need to do:
```
( dividend + divisor - 1 ) / divisor
```
Source: [Number Conversion, Roland Backhouse, 2001](http://www.cs.nott.ac.uk/~rcb/G51MPC/slides/NumberLogic.pdf) | How can I ensure that a division of integers is always rounded up? | [
"",
"c#",
"math",
""
] |
All I am trying to do is take a standard range on an excel sheet (i.e. a named range, or even A1:F100), and run some sql queries on it, and return a recordset that I can either step through in VBA code, or even just paste into some other sheet in the same workbook.
Using ADODB was one thought, but how could I setup the connectionstring to point to some range within the current workbook?
I know before I have made use of the Microsoft query wizard, which was not ideal, but would work. I can't seem to get this to refer to a range within the sheet, only other excel files.
---
Here is the function I am left with. When I run it a few times my excel crashes with the usual out of resources error message. I have removed this function from my spreadsheet, and everything runs seamlessly multiple times, thus it is definitely caused by the code here.
I have cleaned up all the objects (correctly?). Does anyone have any ideas what could be going wrong? Could there be something in the connection string that could be tweaked, or could it be something to do with the variant that is returned from the GetRows method?
I am using MS ADO 2.8, and have also tried 2.5 with the same behaviour.
```
Function getTimeBuckets() As Collection
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim dateRows As Variant
Dim i As Integer
Dim today As Date
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
Set getTimeBuckets = New Collection
strFile = ThisWorkbook.FullName
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strCon
strSQL = "SELECT DISTINCT(Expiration) FROM [PositionSummaryTable] where [Instrument Type] = 'LSTOPT'"
rs.Open strSQL, cn
dateRows = rs.GetRows
rs.Close
'today = Date
today = "6-may-2009"
For i = 1 To UBound(dateRows, 2)
If (dateRows(0, i) >= today) Then
getTimeBuckets.Add (dateRows(0, i))
End If
Next i
Set dateRows = Nothing
Set cn = Nothing
Set rs = Nothing
End Function
``` | You can just use the name.
```
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
strFile = Workbooks(1).FullName
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
''Pick one:
strSQL = "SELECT * FROM DataTable" ''Named range
strSQL = "SELECT * FROM [Sheet1$A1:E346]" ''Range
rs.Open strSQL, cn
Debug.Print rs.GetString
```
**In response to question part 2**
I notice that you only want today's records, so you should be able to modify the sql to:
```
strSQL = "SELECT DISTINCT(Expiration) FROM [PositionSummaryTable] " _
& "where [Instrument Type] = 'LSTOPT' AND [Expiration]=#" _
& Format(Date(),"yyyy/mm/dd") & "#"
```
You have not closed the connection:
```
cn.Close
```
And then
```
Set rs=Nothing
Set cn=Nothing
``` | How about using of LIKE clause?
I tried to use:
```
select * from [PES$] where PID_TAG like '*5400001'
```
without success....
this works:
```
select * from [PES$] where PID_TAG = 'PIT5400001'
```
but this is not I want.
**EDIT**
hummm.... we need to change wildcards to work...
don't use \*, use % | How can I run SQL statements on a named range within an excel sheet? | [
"",
"sql",
"vba",
"excel",
""
] |
I have a stored procedure that takes no parameters, and it returns two fields. The stored procedure sums up all transactions that are applied to a tenant, and it returns the balance and the id of the tenant.
I want to use the record set it returns with a query, and I need to join it's results on the id of the tenant.
This is my current query:
```
SELECT t.TenantName, t.CarPlateNumber, t.CarColor, t.Sex, t.SSNO, t.Phone, t.Memo,
u.UnitNumber,
p.PropertyName
FROM tblTenant t
LEFT JOIN tblRentalUnit u
ON t.UnitID = u.ID
LEFT JOIN tblProperty p
ON u.PropertyID = p.ID
ORDER BY p.PropertyName, t.CarPlateNumber
```
The stored procedure is this:
```
SELECT tenant.ID AS TenantID, SUM(ISNULL(trans.Amount,0)) AS TenantBalance FROM tblTenant tenant
LEFT JOIN tblTransaction trans
ON tenant.ID = trans.TenantID
GROUP BY tenant.ID
```
I would like to add the balance from the stored procedure to it also.
How can I do this? | I actually like the previous answer (don't use the SP), but if you're tied to the SP itself for some reason, you could use it to populate a temp table, and then join on the temp table. Note that you're going to cost yourself some additional overhead there, but it's the only way I can think of to use the actual stored proc.
Again, you may be better off in-lining the query from the SP into the original query. | insert the result of the SP into a temp table, then join:
```
CREATE TABLE #Temp (
TenantID int,
TenantBalance int
)
INSERT INTO #Temp
EXEC TheStoredProc
SELECT t.TenantName, t.CarPlateNumber, t.CarColor, t.Sex, t.SSNO, t.Phone, t.Memo,
u.UnitNumber, p.PropertyName
FROM tblTenant t
INNER JOIN #Temp ON t.TenantID = #Temp.TenantID
...
``` | How can I join on a stored procedure? | [
"",
"sql",
"sql-server-2005-express",
""
] |
Is there any way to extract the request url from an xhr object?
I can see the url in firebug via the channel property but you cant query this using javascript. | I hope I'm understanding your problem correctly.
It should be fairly simple to wrap your XHR objects with your own object to allow for this kind of functionality.
Below is an overly simplified example:
```
// Assumption: GetXHR() returns a new XHR object, cross browser.
function HTTPGet(url, onStartCb, onCompleteCb)
{
var xhr = GetXHR();
// Construct your own xhr object that contains the url and the xhr object itself.
var myXhr = { xhr: xhr, url: url };
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
onCompleteCb(myXhr);
}
};
xhr.open("GET", url);
onStartCb(myXhr);
xhr.send(null);
}
```
I haven't tested this extensively, but it should work and with some modifications (error handling, passing parameters, etc) you should probably be able to turn this example into a fully functional solution. | With the following hack no wrapper is required:
```
var xhrProto = XMLHttpRequest.prototype,
origOpen = xhrProto.open;
xhrProto.open = function (method, url) {
this._url = url;
return origOpen.apply(this, arguments);
};
```
Usage:
```
var r = new XMLHttpRequest();
r.open('GET', '...', true);
alert(r._url); // opens an alert dialog with '...'
``` | Get request url from xhr object | [
"",
"javascript",
""
] |
I am programming a control to allow the users of our intranet to upload multiple files into our system, but with some added functionality.
Imagine you as a user are uploading N files, when you add N files the intranet presents you a list like this:
File\_name\_1 ..... [View] [Remove] [Upload]
File\_name\_2 ..... [View] [Remove] [Upload]
.
.
.
File\_name\_n ..... [View] [Remove] [Upload]
[Remove all file] [Upload all files]
If you clic on the View button the file named "file\_name\_X" will be opened so you can review it and be sure it really is the file you want to upload.
Is this possible?, I am new on the Web programming world and all I found suggest the browsers do not allow you to access local file system from inside a web, but I am not sure. | One way to do this is that you actually upload initially but you only upload it to a "Staging" area. Thus it wouldn't have actually been committed to your system.
This is what Gravatar does which uploads the file and then lets you crop and adjust the image before saving it.
The only other way I've seen this done is using an ActiveX control for example in IE or some other browser extension mechanism. | Uploading files while presenting a good user interface, including progress reporting about the upload, is hard.
I suggest the Yahoo UI uploader widget: <http://developer.yahoo.com/yui/uploader/>
It's also the basis for the Flickr uploader, see the YUI blog post:
<http://yuiblog.com/blog/2009/02/26/flickr-uploadr/>
Larry | Let user review a file before uploading it | [
"",
"asp.net",
"javascript",
""
] |
either this doesn't exist, or I'm not thinking/searching correctly because it's late...
I want to set a JTable column width in Swing based on a prototype value for the largest string I expect (or know) to exist in a particular column. I don't know the # of pixels since I don't necessarily know the font at compile time.
Is there a way to set a prototype value for column width purposes, the way there is for row height purposes? If so, how? | Have you tried creating a JLabel at run time and using its size to resize your table?
```
// create a label that will be using the run-time font
JLabel prototypeLabel = new JLabel("Not Applicable")
// get the labels preferred sizes
int preferredWidth = prototypeLabel.getPreferredSize().getWidth();
int preferredHeight = prototypeLabel.getPreferredSize().getHeight();
// set the sizes of the table's row and columns
myTable.setRowHeight(preferredHeight);
for(TableColumn column : myTable.getColumnModel.getColumns()){
column.setPreferredWidth(preferredWidth);
}
``` | You can try the following code:
```
/**
* Sets the preferred width of the columns of a table from prototypes
* @param table the target table
* @param prototypes an array of prototypes, {@code null} values will be ignored
* @param setMaxWidth {@code true} if the maximum column width should also be set
*/
public static void setWidthFromPrototype(JTable table, Object[] prototypes, boolean setMaxWidth) {
if (prototypes.length != table.getColumnCount())
throw new IllegalArgumentException("The prototypes array should contain exactly one element per table column");
for (int i = 0; i < prototypes.length; i++) {
if (prototypes[i] != null) {
Component proto = table.getCellRenderer(0,i)
.getTableCellRendererComponent(table, prototypes[i], false, false, 0, i);
int prefWidth = (int) proto.getPreferredSize().getWidth() + 1;
table.getColumnModel().getColumn(i).setPreferredWidth(prefWidth);
if (setMaxWidth)
table.getColumnModel().getColumn(i).setMaxWidth(prefWidth);
}
}
}
``` | setting a prototype value (for auto-width calculation) of a JTable column | [
"",
"java",
"swing",
"jtable",
"column-width",
""
] |
What's the fastest way to enumerate through an integer and return the **exponent** of each bit that is turned on? Have seen an example using << and another using Math.Pow. Wondering if there is anything else that's really fast.
Thanks. | I imagine bit-shifting would be the fastest. Untested, but I think the following ought to be fast (as fast as IEnumerables are at least).
```
IEnumerable<int> GetExponents(Int32 value)
{
for(int i=0; i<32; i++)
{
if(value & 1)
yield return i;
value >>= 1;
}
}
```
If you want it to be faster, you might consider returning a `List<int>` instead. | The *fastest* way? Lookup tables are almost always the fastest way. Build an int[][] array with four billion entries, one for each int, containing an array of the numbers you want. Initializing the table will take some time, of course but the lookups will be incredibly fast.
I note that you have not said what "fastest" means with sufficient precision for anyone to actually answer the question. Does it mean fastest amortized time including startup time, or marginal lookup time assuming that startup costs can be neglected? My solution sketch assumes the latter.
Obviously a 32 bit machine with 2 billion bytes of address space will not have enough address space to store thirty billion bytes of arrays. Get yourself a 64 bit machine. You'll need at least that much physical memory installed as well if you want it to be fast -- the paging is going to kill you otherwise.
I sure hope the couple of nanoseconds you save on every lookup are worth buying all that extra hardware. Or maybe you don't *actually* want the *fastest* way?
:-) | Fastest way to enumerate through turned on bits of an integer | [
"",
"c#",
"performance",
"optimization",
"bit-manipulation",
""
] |
I have an sqlConnection manager class like so:
```
public class SQLConn {
public string connStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
private SqlConnection sqlConn;
public SqlConnection Connection()
{
sqlConn = new SqlConnection(connStr);
return sqlConn;
}
public void Open()
{
sqlConn .Open();
}
}
```
If I use a function with the 'using' statement like:
```
var conn = new SQLConn();
using (conn.Connection())
{
String query = "Select * from table";
objSql = new SqlCommand(query, conn.Connection());
conn.Open();
DoSomething();
}
```
Does the using statement dispose of the connection automatically since `conn.Connection()` returns a SqlConnection object? Or, do I have to implement IDisposable and a custom Dispose method on the SqlConn class?
Is this even a good way at all? I'm working with legacy code and I'm not able to use an ORM yet but is there a way to simplify this existing pattern to manage/create SQL connections? | The `using` statement will look at the final type of the expression - i.e. whatever is returned from `.Connection()`; if this returns something that is `IDisposable`, then you're OK.
The compiler will tell you if you get it wrong ;-p (it won't let you use `using` on something that isn't `IDisposable`).
You should probably watch out for where you are creating *two* connections:
```
using (var c = conn.Connection()) // <==edit
{
String query = "Select * from table";
objSql = new SqlCommand(query, c); // <==edit
c.Open();
DoSomething();
}
```
and possibly:
```
public SqlConnection Connection()
{
if(sqlConn == null) sqlConn = new SqlConnection(connStr); // <== edit
return sqlConn;
}
``` | It will work but after the `using {}` you will be left with an sqlConn that internally holds a Disposed SqlConnection. Not a really useful situation | Using C#'s 'using' statement with a custom object's function, do I Need to implement IDisposable? | [
"",
"c#",
"idisposable",
"sqlconnection",
""
] |
I have a string array in C# and I intend to copy it in a notepad so that each row would be located in a line. What should I do? | You can create one string with each element on separate lines like this:
```
string[] array = { "a", "b", "c" };
string lines = string.Join(Environment.NewLine, array);
```
Then you can use the Clipboard class to copy the string to the clipboard. | You can use the System.Windows.Forms.Clipboard.SetText method to store a text on the clipboard. It will then be available for other applications, like notepad, to be pasted in. | String array to notepad | [
"",
"c#",
""
] |
If I have the following situation:
```
StreamWriter MySW = null;
try
{
Stream MyStream = new FileStream("asdf.txt");
MySW = new StreamWriter(MyStream);
MySW.Write("blah");
}
finally
{
if (MySW != null)
{
MySW.Flush();
MySW.Close();
MySW.Dispose();
}
}
```
Can I just call `MySW.Dispose()` and skip the Close even though it is provided? Are there any Stream implimentations that don't work as expected (Like CryptoStream)?
If not, then is the following just bad code:
```
using (StreamWriter MySW = new StreamWriter(MyStream))
{
MySW.Write("Blah");
}
``` | > Can I just call MySW.Dispose() and
> skip the Close even though it is
> provided?
Yes, that’s what it’s for.
> Are there any Stream implementations
> that don't work as expected (Like
> CryptoStream)?
It is safe to assume that if an object implements `IDisposable`, it will dispose of itself properly.
If it doesn’t, then that would be a bug.
> If not, then is the following just bad
> code:
No, that code is the recommended way of dealing with objects that implement `IDisposable`.
More excellent information is in the accepted answer to [Close and Dispose - which to call?](https://stackoverflow.com/questions/61092/close-and-dispose-which-to-call) | I used Reflector and found that `System.IO.Stream.Dispose` looks like this:
```
public void Dispose()
{
this.Close();
}
``` | Does Stream.Dispose always call Stream.Close (and Stream.Flush) | [
"",
"c#",
".net",
"using",
""
] |
C# 2008 SP1
I am using the code below:
```
dt.ReadXml("%AppData%\\DateLinks.xml");
```
However, I am getting an exception that points to the location of where my application is running from:
> Could not find a part of the path
> 'D:\Projects\SubVersionProjects\CatDialer\bin\Debug\%AppData%\DateLinks.xml'.
I thought the `%AppData%` should find the relative path. When I go `Start|Run|%AppData%` windows explorer takes me to that directory.
I can not put the full path in, as the user is different on each client machine. | To get the *AppData* directory, it's best to use the `GetFolderPath` method:
```
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
```
(must add `using System` if not present).
`%AppData%` is an environment variable, and they are not automatically expanded anywhere in .NET, although you can explicitly use the [`Environment.ExpandEnvironmentVariable`](https://learn.microsoft.com/en-us/dotnet/api/system.environment.expandenvironmentvariables) method to do so. I would still strongly suggest that you use `GetFolderPath` however, because as Johannes Rössel points out in the comment, `%AppData%` may not be set in certain circumstances.
Finally, to create the path as shown in your example:
```
var fileName = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData), "DateLinks.xml");
``` | The **BEST** way to use the AppData directory, **IS** to use [`Environment.ExpandEnvironmentVariables`](http://msdn.microsoft.com/en-us/library/system.environment.expandenvironmentvariables.aspx) method.
**Reasons:**
* it replaces parts of your string with valid directories or whatever
* it is case-insensitive
* it is easy and uncomplicated
* it is a standard
* good for dealing with user input
**Examples:**
```
string path;
path = @"%AppData%\stuff";
path = @"%aPpdAtA%\HelloWorld";
path = @"%progRAMfiLES%\Adobe;%appdata%\FileZilla"; // collection of paths
path = Environment.ExpandEnvironmentVariables(path);
Console.WriteLine(path);
```
**[More info:](https://www.askvg.com/list-of-environment-variables-in-windows-xp-vista-and-7/)**
```
%ALLUSERSPROFILE% C:\ProgramData
%APPDATA% C:\Users\Username\AppData\Roaming
%COMMONPROGRAMFILES% C:\Program Files\Common Files
%COMMONPROGRAMFILES(x86)% C:\Program Files (x86)\Common Files
%COMSPEC% C:\Windows\System32\cmd.exe
%HOMEDRIVE% C:
%HOMEPATH% C:\Users\Username
%LOCALAPPDATA% C:\Users\Username\AppData\Local
%PROGRAMDATA% C:\ProgramData
%PROGRAMFILES% C:\Program Files
%PROGRAMFILES(X86)% C:\Program Files (x86) (only in 64-bit version)
%PUBLIC% C:\Users\Public
%SystemDrive% C:
%SystemRoot% C:\Windows
%TEMP% and %TMP% C:\Users\Username\AppData\Local\Temp
%USERPROFILE% C:\Users\Username
%WINDIR% C:\Windows
``` | C# getting the path of %AppData% | [
"",
"c#",
".net",
"path",
""
] |
Trying to request a timestamp (RFC 3161) by using BouncyCastle and connecting to <http://timestamping.edelweb.fr/service/tsp>. I do get a TimestampResponse back from the server but it seems to be without an actual date.
This is the code:
```
public static void main(String[] args) {
String ocspUrl = "http://timestamping.edelweb.fr/service/tsp";
byte[] digest = "hello".getBytes();
OutputStream out = null;
try {
TimeStampRequestGenerator reqgen = new TimeStampRequestGenerator();
TimeStampRequest req = reqgen.generate(TSPAlgorithms.SHA1, digest);
byte request[] = req.getEncoded();
URL url = new URL(ocspUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-type", "application/timestamp-query");
con.setRequestProperty("Content-length", String.valueOf(request.length));
out = con.getOutputStream();
out.write(request);
out.flush();
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage());
}
InputStream in = con.getInputStream();
TimeStampResp resp = TimeStampResp.getInstance(new ASN1InputStream(in).readObject());
TimeStampResponse response = new TimeStampResponse(resp);
response.validate(req);
System.out.println(response.getTimeStampToken().getTimeStampInfo().getGenTime());
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
```
Here is the question(s):
Has anyone used Bouncycastle's library for timestamps and happens to know about the different status codes and what they mean? Or just in general why this wont seem to work.
This line where I expect to see a date just throws a NullPointer:
```
System.out.println(response.getTimeStampToken().getTimeStampInfo().getGenTime());
```
Does anyone know of any other RFC 3161 compliant timestamp servers that are free?
If you would like to run the code you need the bouncycastle jars which can be downloaded from [here](http://www.bouncycastle.org/latest_releases.html). You will need: provider, mail, tsp.
Thanks | The problem seems to be that the content is of the wrong format/length.
```
TimeStampRequest req = reqgen.generate(TSPAlgorithms.SHA1, digest);
```
But what I sent in was just:
```
"hello".getBytes();
```
Creating a proper SHA1Digest from 'hello' and this work just fine.
```
static public byte[] calculateMessageDigest()
throws NoSuchAlgorithmException, IOException {
SHA1Digest md = new SHA1Digest();
byte[] dataBytes = "helloooooooooooooo".getBytes();
int nread = dataBytes.length;
md.update(dataBytes, 0, nread);
byte[] result = new byte[32];
md.doFinal(result, 0);
return result;
```
I also ended up using [Digistamp](http://digistamp.com) as my TSA since they support http authentication which was a requirement. | Analyzing communication with wireshark, this example gives me a "bad message digest" error.
A digest code that works for me is:
```
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
messageDigest.update("messageImprint".getBytes());
byte[] digest = messageDigest.digest();
``` | Timestamp Response is Incorrect - BouncyCastle | [
"",
"java",
"security",
"bouncycastle",
"trusted-timestamp",
"rfc3161",
""
] |
I have a problem where a method is getting an undefined variable error, even though I check for the variable being undefined before calling.
```
// Sets focus and text-select to the passed in element.
idNav.prototype.setFocusFromVar = function(r) {
document.activeInputArea = r; // my variable for tracking focus
r.focus(); // error happens here (line 274 of idNav.js)
r.select();
}
```
The error happens at the r.focus line.
In both places where I call the method, I use a pattern similar to the following with a local variable r in the caller.
```
if (!r)
return;
this.setFocusFromVar(r);
```
and yet the error persists. When r is not null or undefined, it is an input element in a table on my webpage.
I continue to get r is undefined on line 274 of idNav.js, which is the r.focus line. All of the callers of the method are in the same js file as well.
What am I missing?
This error is occurring intermittently in Firefox, I haven't tested this specific error in IE.
EDTA:
r did show up as an undefined and the stack trace of the error shows:
```
setFocusFromVar()(undefined)IDNav.js (line 275)
dhandler(Object originalEvent=Event keydown type=keydown)IDNav.js (line 100)
newTrigger()(Object originalEvent=Event keydown type=keydown)jquery.hotkeys.js (line 1)
F()()jquery.js (line 19)
F()(Object originalEvent=Event keydown type=keydown)jquery.js (line 19)
F()()jquery.js (line 19)
[Break on this error] r.focus();
```
dhandler is one of the methods I checked out and seemed to be good (no problems).
I will take another look at that to be sure though:
It is used for handling the down-arrow and enter keys for navigation through my table of input elements. | Based on your description of the problem, it seems to me that it is sometimes getting called without the sanity check. I'd put the sanity check inside the function rather than outside of it.
However, you also probably want to know how you're getting around it in the first place. I'd modify the function as follows to inspect what is going wrong in Firebug:
```
idNav.prototype.setFocusFromVar = function(r) {
if (!r) {
return; // Set the breakpoint here
}
document.activeInputArea = r;
r.focus();
r.select();
}
```
Then when you hit the breakpoint, you can look at Firebug's stack trace to determine how you got the function without checking whether r was defined or not. | I'd recommend moving (or duplicating) your sanity check inside the function as follows:
```
idNav.prototype.setFocusFromVar = function(r) {
if (!r)
return;
document.activeInputArea = r; // my variable for tracking focus
r.focus(); // error happens here (line 274 of idNav.js)
r.select();
}
``` | Javascript error with undefined variable | [
"",
"javascript",
"firefox",
""
] |
I have a class that looks like the following:
```
public class MyClass {
private String dPart1;
public String getDPart1() {
return dPart1;
}
public void setDPart1(String dPart1) {
this.dPart1 = dPart1;
}
}
```
My hibernate mapping file maps the property as follows:
```
<property name="dPart1" not-null="true"/>
```
I get the following error:
```
org.hibernate.PropertyNotFoundException: Could not find a getter for dPart1 in class com.mypackage.MyClass
at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:282)
at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:275)
at org.hibernate.mapping.Property.getGetter(Property.java:272)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:247)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:125)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:55)
at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:56)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:302)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:434)
at
```
It appears that hibernate doesn't like my capitalization. How should I fix this? | ```
<property name="DPart1" not-null="true"/>
```
should work... | for a property called "dPart1" a hibernate will try a getter named "getDpart1" not "getDPart1"
IIRC | Hibernate - PropertyNotFoundException: Could not find a getter for | [
"",
"java",
"hibernate",
""
] |
I know PDF generation has been discussed a lot here; however, I've yet to find what I need.
I'm trying to generate PDF reports (mainly tables) from python. Yes I've tried ReportLab and Pisa. Both had column content "break out" in circumstances I didn't think were unreasonable and unrealistic to encounter in production.
When I say reasonable I mean 8 - 12 columns of differing widths. Not 80 - 1200 or some such.
I don't need a native python solution as I will be able to have my script launch off the linux command line.
I have these reports working in XHTML and they look more or less perfect ... I'd prefer to leverage them.
What I'm asking is: does anyone know of a tool I can use that will render tables of arbitrary (again within reason) size in PDF with quality near XHTML browser rendering?
I'd like to use something like PrinceXML; however the size of this project doesn't justify the expense of such a tool.
As an aside I have tried to do what I need in Latex , something I'm not apposed to but if that is a *good idea* I'd appreciate an example.
Regards, and thanks in advance. | The stand alone program : wkhtmltopdf is exactly what I needed. The PDF rendering of XHTML is the best of seen from a free tool. | I completely agree with Brandon Craig Rhodes answer.
TeX, plain or with a macro package like LaTeX or ConTeXt, would be a good solution if
you need high quality output. However TeX is a heavy dependency
If you are looking for a lighter alternative you can try to
* generate xsl-fo and render it with apache-fop, or
* write a Python wrapper around [iText](http://www.lowagie.com/iText).
Both can do arbitrary width tables with borders.
xsl-fo is not too difficult to learn and if you are used to XML easier to
generate than LaTeX code.
iText is a powerful PDF library available under MPL and LGPL
There are versions written in Java and C# but unfortunately
there is none in Python yet. | PDF Tables of Arbitrary (within reason) Width | [
"",
"python",
"pdf",
"xhtml",
"latex",
""
] |
Apparently, there's been a big brouhaha over whether or not Python needs tail-call optimization (TCO). This came to a head when someone [shipped Guido a copy of SICP](http://drj11.wordpress.com/2009/04/30/python-tail-call-optimisation/), because he didn't "get it." I'm in the same boat as [Guido](https://en.wikipedia.org/wiki/Guido_van_Rossum). I understand the concept of tail-call optimization. I just can't think of any reason why Python really *needs* it.
To make this easier for me to understand, what would be a snippet of code that would be greatly simplified using TCO? | Personally, I put great value on tail call optimization; but mainly because it makes recursion as efficient as iteration (or makes iteration a subset of recursion). In minimalistic languages you get huge expressive power without sacrificing performance.
In a 'practical' language (like Python), OTOH, you usually have a lot of other constructions for almost every situation imaginable, so it's less critical. It is always a good thing to have, to allow for unforeseen situations, of course. | If you intensely want to use recursion for things that might alternatively be expressed as loops, then "tail call optimization" is really a must. However, Guido, Python's Benevolent Dictator For Life (BDFL), strongly believes in loops being expressed as loops -- so he's not going to special-case tail calls (sacrificing stack-trace dumps and debugging regularity). | What's the big deal with tail-call optimization and why does Python need it? | [
"",
"python",
"tail-recursion",
"tail-call-optimization",
""
] |
There is an online file (such as `http://www.example.com/information.asp`) I need to grab and save to a directory. I know there are several methods for grabbing and reading online files (URLs) line-by-line, but is there a way to just download and save the file using Java? | Give [Java NIO](http://en.wikipedia.org/wiki/New_I/O) a try:
```
URL website = new URL("http://www.website.com/information.asp");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("information.html");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
```
Using `transferFrom()` is **potentially** much more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.
Check more about it [here](http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html).
**Note**: The third parameter in transferFrom is the maximum number of bytes to transfer. `Integer.MAX_VALUE` will transfer at most 2^31 bytes, `Long.MAX_VALUE` will allow at most 2^63 bytes (larger than any file in existence). | Use Apache [Commons IO](http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#copyURLToFile(java.net.URL,%20java.io.File)). It is just one line of code:
```
FileUtils.copyURLToFile(URL, File)
``` | How can I download and save a file from the Internet using Java? | [
"",
"java",
"download",
""
] |
I'm working with a legacy vb6 product and I've come across a problem whereby I need to get the filename part of a full path from a database table through DAO. I've got no access to VBA functions here so I'm looking specifically for MS Access SQL. I have no way of dropping some extra code after the query. I **CAN'T** change/refactor the solution short of modifying the SQL.
Now, DAO doesn't have any `instrrev` or `replace` functionality so I'm pretty limited.
Any guesses out there?
Thanks in advance. | Assuming you can't change the actual database . . .
The only thing I can think of (and I wracked by brains on this one, sorry mate) is to use repeated calls to instr, nested in iif statements e.g. to replace this call to inStrRev
```
SELECT IIf(InStr([FileName],""\"")>0,Mid$([Filename],InStrRev([Filename],""\"")+1),[Filename]) FROM Table1
```
You'd have a compeltely insane
```
SELECT IIf(InStr([FileName],""\"")>0,Mid$([Filename],iif(InStr(1, [FileName], ""\"") > 0, iif(InStr(2, [FileName], ""\"") > 0, iif(InStr(3, [FileName], ""\"") > 0, iif(InStr(4, [FileName], ""\"") > 0, iif(InStr(5, [FileName], ""\"") > 0, iif(InStr(6, [FileName], ""\"") > 0, iif(InStr(7, [FileName], ""\"") > 0, iif(InStr(8, [FileName], ""\"") > 0, iif(InStr(9, [FileName], ""\"") > 0, 1, InStr(9, [FileName], ""\"")), InStr(8, [FileName], ""\"")), InStr(7, [FileName], ""\"")), InStr(6, [FileName], ""\"")), InStr(5, [FileName], ""\"")), InStr(4, [FileName], ""\"")), InStr(3, [FileName], ""\"")), InStr(2, [FileName], ""\"")), InStr(1, [FileName], ""\""))),[Filename]) from table1
```
This will work for a path thats 10 or so sub folders deep.
If you think 10 sub folders is too little, I've a bit of vba to generate the statement to what ever depth you require.
```
Function BuildNestedIIfs(ByVal depth As Integer, byval maxDepth as integer) As String
Dim locator As String
If depth < maxDepth Then
locator = "InStr(" & depth & ", [FileName], """"\"""")"
Build = "iif(" & locator & " > 0, " & Build(depth + 1, maxDepth) & ", " & locator & ")"
Else
Build = "0"
End If
End Function
```
It is obscene, but should work | You should be able to use the built-in vba functions like `instr`, `replace`, `mid`, etc.
There is a "sandbox" mode that may block them - see this on how to unblock them <http://support.microsoft.com/kb/294698> | Awkward DAO string manipulation issue | [
"",
"sql",
"ms-access",
"dao",
""
] |
I've tried searching through search engines,MSDN,etc. but can't anything. Sorry if this has been asked before. Is there any performance difference between using the T-SQL "Between" keyword or using comparison operators? | You can check this easily enough by checking the query plans in both situations. There is no difference of which I am aware. There is a logical difference though between BETWEEN and "<" and ">"... BETWEEN is inclusive. It's equivalent to "<=" and "=>". | The query engine converts between into `>=` and `<=` (take a look at the query plan) so in practise they're identical and in theory `>= <=` is faster because the engine won't have to translate. Good luck noticing a difference though.
I use between anyway, I find it reads easier
Very complex queries/nested views with numerous between comparisons might benefit from changing into `>= <=` as this might potentially prevent optimisation timeouts by reducing the time spent on refactoring the query (just a theory, untested by me & I've never noticed it) | Compare performance difference of T-SQL Between and '<' '>' operator? | [
"",
"sql",
"sql-server",
"performance",
""
] |
I have a html element (like select box input field) in a table. Now I want to copy the object and generate a new one out of the copy, and that with JavaScript or jQuery. I think this should work somehow but I'm a little bit clueless at the moment.
Something like this (pseudo code):
```
oldDdl = $("#ddl_1").get();
newDdl = oldDdl;
oldDdl.attr('id', newId);
oldDdl.html();
``` | Using your code you can do something like this in plain JavaScript using the [cloneNode()](https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode) method:
```
// Create a clone of element with id ddl_1:
let clone = document.querySelector('#ddl_1').cloneNode( true );
// Change the id attribute of the newly created element:
clone.setAttribute( 'id', newId );
// Append the newly created element on element p
document.querySelector('p').appendChild( clone );
```
Or using jQuery [clone()](http://docs.jquery.com/Manipulation/clone) method (not the most efficient):
```
$('#ddl_1').clone().attr('id', newId).appendTo('p'); // append to where you want
``` | The modern approach is to use the [`cloneNode`](https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode) function:
```
let new_element = element.cloneNode(true);
```
where the Boolean indicates whether to also clone its child nodes or not.
Afterwards, you can add the cloned element to DOM somewhere. For example, you can use [`after()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/after) to insert the new element right after the original element:
```
element.after(new_element);
```
**Compatibility:**
[Browser compatibility for Element.after](https://caniuse.com/?search=after)
[Browser compatibility for Node.cloneNode](https://caniuse.com/?search=cloneNode) | Is it possible to clone html element objects in JavaScript? | [
"",
"javascript",
"jquery",
""
] |
I'm trying to access a member structs variables, but I can't seem to get the syntax right.
The two compile errors pr. access are:
error C2274: 'function-style cast' : illegal as right side of '.' operator
error C2228: left of '.otherdata' must have class/struct/union
I have tried various changes, but none successful.
```
#include <iostream>
using std::cout;
class Foo{
public:
struct Bar{
int otherdata;
};
int somedata;
};
int main(){
Foo foo;
foo.Bar.otherdata = 5;
cout << foo.Bar.otherdata;
return 0;
}
``` | You only define a struct there, not allocate one. Try this:
```
class Foo{
public:
struct Bar{
int otherdata;
} mybar;
int somedata;
};
int main(){
Foo foo;
foo.mybar.otherdata = 5;
cout << foo.mybar.otherdata;
return 0;
}
```
If you want to reuse the struct in other classes, you can also define the struct outside:
```
struct Bar {
int otherdata;
};
class Foo {
public:
Bar mybar;
int somedata;
}
``` | `Bar` is inner structure defined inside `Foo`. Creation of `Foo` object does not implicitly create the `Bar`'s members. You need to explicitly create the object of Bar using `Foo::Bar` syntax.
```
Foo foo;
Foo::Bar fooBar;
fooBar.otherdata = 5;
cout << fooBar.otherdata;
```
Otherwise,
Create the Bar instance as member in `Foo` class.
```
class Foo{
public:
struct Bar{
int otherdata;
};
int somedata;
Bar myBar; //Now, Foo has Bar's instance as member
};
Foo foo;
foo.myBar.otherdata = 5;
``` | C++: syntax for accessing member struct from pointer to class | [
"",
"c++",
"struct",
"member",
""
] |
Here is a piece of code that I've written. The problem that I'm having is:
When i click a button in the gridview "rowcommand" adds the item to an arraylist which works fine.
After the user clicks the button the page loads again and it goes to "rowcommand" AGAIN! As a result the same value is added to the arraylist.
Is this something regarding postback? if it's I dont think I've understood it clearly enough! what seems to be wrong here?
//edit 2: entire code block
```
public partial class Action_k : System.Web.UI.Page
{
ArrayList array;
ArrayList tmpArrayList = new ArrayList();
string itemIDs = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
if (Session["username"] == null)
{
Session["anonuser"] = "anon";
Label1.Text = "";
userLabel.Text = "";
ImageButton1.ImageUrl = "~/images/logink.gif";
ImageButton1.PostBackUrl = "~/Login_k.aspx";
}
else
{
userLabel.Text = Session["username"].ToString();
Label1.Text = "Your logged in as: ";
ImageButton1.ImageUrl = "~/images/logoutk.gif";
}
if (Session["array"] == null)
{
array = new ArrayList();
Session.Add("array", array);
}
}
array = Session["array"] as ArrayList;
}
public void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
int index = Convert.ToInt32(e.CommandArgument);
string items = GridView2.DataKeys[index].Value.ToString();
array.Add(items);
Response.Redirect("ShoppingCart_k.aspx?itemID=" + items);
}
}
}
```
Thanks, | Well I found the answer for it, and it was simple. It seems to be a issue when ButtonType="Button".
The problem can be resolved by changing the ButtonType to "Link".
Just incase if your interested here's the link that helped me out.
```
http://forums.asp.net/p/1002747/1324414.aspx#1324414
``` | It's doing what it's suppose to. First your page load event is handled, then your Row Command event is handled.
What you're seeing is that two events are being handled, one after the other.
Also checkout Callbacks versus Postbacks.
Like Joel said, a Postback is going to invalidate and rebuild your page. A Callback uses Javascript/AJAX \_\_doPostBack() and does not invalidate the entire page, just your callback component or container. A page load event is still called though, but you can test for the IsCallback property.
This link may help...
<http://msdn.microsoft.com/en-us/library/ms178141.aspx> | pageload in c# | [
"",
"c#",
"asp.net",
""
] |
So, there seems to be a few questions asking about removing files/directories matching certain cases, but I'm looking for the exact opposite: Delete EVERYTHING in a folder that DOESN'T match my provided examples.
For example, here is an example directory tree:
```
.
|-- coke
| |-- diet
| |-- regular
| `-- vanilla
|-- icecream
| |-- chocolate
| |-- cookiedough
| |-- cupcake
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- vanilla
|-- lol.txt
|-- mtndew
| |-- classic
| |-- codered
| |-- livewire
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- throwback
`-- pepsi
|-- blue
|-- classic
|-- diet
`-- throwback
```
I want to delete everything but the files in test/icecream/cupcake/ and test/mtndew/livewire/. Everything else can go, including the directory structure. So, how can I achieve this? Languages I wouldn't mind this being in: bash or python. | `find`'s `-prune` comes to mind, but it's a pain to get it to work for specific paths (`icecream/cupcake/`) rather than specific directories (`cupcake/`).
Personally, I'd just use `cpio` and hard-link (to avoid having to copy them) the files in the directories you want to keep to a new tree and then remove the old one:
```
find test -path 'test/icecream/cupcake/*' -o -path 'test/mtndew/livewire/*' | cpio -padluv test-keep
rm -rf test
```
That'll also keep your existing directory structure for the directories you intend to keep. | This command will leave only the desired files in their original directories:
```
find test \( ! -path "test/mtndew/livewire/*" ! -path "test/icecream/cupcake/*" \) -delete
```
No need for cpio. It works on Ubuntu, Debian 5, and Mac OS X.
On Linux, it will report that it cannot delete non-empty directories, which is exactly the desired result. On Mac OS X, it will quietly do the right thing. | Delete all files/directories except two specific directories | [
"",
"python",
"linux",
"bash",
""
] |
I am developing on Eclipse on Windows and Code gets deployed on Unix. I am fetching the system property values using System.getProperty("key") ... How do I pass this in Eclipse so that I do not have to modify the code and it works on Eclipse for debugging?
Any suggestions? | Run -> Run configurations, select project, second tab: “Arguments”. Top box is for your program, bottom box is for VM arguments, e.g. `-Dkey=value`. | You can use java `System.properties`, for using them from eclipse you could:
1. Add `-Dlabel="label_value"` in the VM arguments of the test `Run Configuration` like this:
[](https://i.stack.imgur.com/jI0gN.png)
2. Then run the test:
```
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Main {
@Test
public void test(){
System.out.println(System.getProperty("label"));
assertEquals("label_value", System.getProperty("label"));
}
}
```
3. Finally it should pass the test and output this in the console:
```
label_value
``` | How to pass the -D System properties while testing on Eclipse? | [
"",
"java",
"eclipse",
""
] |
I'd like to ge the whole SQL schema for a DB, then generate a hash of it. This is so that I can check if a rollback script returns the schema to it original state. Is there a SP I can use or some other cunning method? I'd like it to be as fast as possible. | The following should work:
```
Microsoft.SqlServer.Management.Smo.Server srv = new Microsoft.SqlServer.Management.Smo.Server("Server");
Microsoft.SqlServer.Management.Smo.Database db = srv.Databases["DB_Name"];
// Set scripting options as needed using a ScriptingOptions object.
Microsoft.SqlServer.Management.Smo.ScriptingOptions so = new ScriptingOptions();
so.AllowSystemObjects = false;
so.ScriptDrops = false;
so.Indexes = true;
so.ClusteredIndexes = true;
so.PrimaryObject = true;
so.SchemaQualify = true;
so.IncludeIfNotExists = false;
so.Triggers = true;
System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();
StringBuilder sb = new StringBuilder();
foreach (Table item in db.Tables)
if (!item.IsSystemObject)
{
sc = item.Script(so);
foreach (string s in sc)
sb.Append(s);
}
foreach (StoredProcedure item in db.StoredProcedures)
if (!item.IsSystemObject)
if (!item.IsSystemObject)
{
sc = item.Script(so);
foreach (string s in sc)
sb.Append(s);
}
foreach (UserDefinedFunction item in db.UserDefinedFunctions)
if (!item.IsSystemObject)
if (!item.IsSystemObject)
{
sc = item.Script(so);
foreach (string s in sc)
sb.Append(s);
}
foreach (Trigger item in db.Triggers)
if (!item.IsSystemObject)
if (!item.IsSystemObject)
{
sc = item.Script(so);
foreach (string s in sc)
sb.Append(s);
}
//sb.GetHashCode();
// For a better hash do this.
System.Security.Cryptography.MD5CryptoServiceProvider hashProvider = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hashData = hashProvider.ComputeHash(ASCIIEncoding.ASCII.GetBytes(sb.ToString()));
``` | If you separate tables and keys from the code and constraints, then you can hash the latter easily.
```
SELECT
CHECKSUM_AGG(BINARY_CHECKSUM (*))
FROM
(SELECT
definition
FROM
sys.default_constraints
UNION ALL
SELECT
definition
FROM
sys.sql_modules
UNION ALL
SELECT
definition
FROM
sys.check_constraints
) foo
``` | Fastest way to script generation SQL server DB schema for hashing | [
"",
"sql",
"sql-server",
"schema",
""
] |
I have a download page where there are 3 download options: Word, Zip, and PDF. There is a folder containing `.doc` files. When a user clicks the Zip option on the page, I want ASP.NET to zip the folder with the `.doc` files into a temporary `.zip` file. Then the client will download it from the server. When the user's download is finished, the temporary Zip file should delete itself.
How can I do this with ASP.NET 2.0 C#?
Note: I know how I can zip and unzip files and remove files from the system with C# ASP.NET 2.0. | I fixed my problem by adding this to the end of the stream code:
```
Response.Flush();
Response.Close();
if(File.Exist(tempFile))
{File.Delete(tempFile)};
``` | Using [DotNetZip](http://dotnetzip.codeplex.com) you can save the zip file directly to the Response.OutputStream. No need for a temporary Zip file.
```
Response.Clear();
// no buffering - allows large zip files to download as they are zipped
Response.BufferOutput = false;
String ReadmeText= "Dynamic content for a readme file...\n" +
DateTime.Now.ToString("G");
string archiveName= String.Format("archive-{0}.zip",
DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=" + archiveName);
using (ZipFile zip = new ZipFile())
{
// add a file entry into the zip, using content from a string
zip.AddFileFromString("Readme.txt", "", ReadmeText);
// add the set of files to the zip
zip.AddFiles(filesToInclude, "files");
// compress and write the output to OutputStream
zip.Save(Response.OutputStream);
}
Response.Flush();
``` | How can I generate a temporary Zip file, then auto-remove it after it is downloaded? | [
"",
"c#",
"asp.net",
"zip",
""
] |
I wonder why **Java** 5 and above provide a printf-style formatter using a static method in class String like this:
```
public static String format(String format, Object... args)
```
instead of
```
public String format(Object... args)
```
so that we can write `"%02d".format(5)` to get `05` instead of `String.format("%02d", 5)`.
I imagined if I could modify the String class, I could add this:
```
public String format(Object... args) {
return format(this, args)
}
```
to get the same result.
I found that in C#, a static method is also used instead of an instance method.
I wonder why they decided to do this, but I didn't come to an explanation. The instance methods `trim` and `substring` returns a new instance of string, so they should have done the same thing with `format`.
Moreover, the `DateFormat` class also uses this:
```
public final String format(Date date)
```
for formatting dates. So if we consider the instance of DateFormat as the formatter, an instance of String could also be used as a formatter.
Any ideas? | Perhaps `"%02d".format(5)` seems to imply that the object on which the `format` method is being called is a format string.
In this case, the format string happens to also be a `String`, so furthering that point, *one could argue that all `String`s are format strings*.
Probably this can be avoided by saying that a static method in the `String` class can be used to format a string, rather than making some implicit statement about all `String`s in general. | While I am not a designer of Java, I can tell you one clear reason for making it static.
Java 5 came out with many features, but two of note were:
* The ability to perform "import static" commands that allowed static methods to be used from within a class easily and without listing their class name.
* A static utility method that performed printfs easily.
While it'd be nice to be able to say `"bla: %d".format("foo"),` by making the method static you can use format in a way that's very familiar and clean-looking to C programmers used to `printf()`.
```
import static java.lang.String.format;
public class Demo {
public void Test() {
//Do some stuff
format("Hey, this is easy to read!");
}
}
```
And that's why! By using static imports, printfs look almost exactly like they do in C. Awesome! | Why is String's format(Object... args) defined as a static method? | [
"",
"java",
"string",
"format",
"printf",
""
] |
I was recently asking someone why he preferred to return a strongly-typed array over an IList. I had always thought that programming against an interface was the most flexible and best way program when faced with a project having a long life. So it struck me as odd when he replied:
> We typically prefer immutable types
> over mutable ones. Arrays are
> immutable. IList is not.
I'm not entirely sure I understand this statement. Can anyone help clarify this?
Thanks for any help you guys can provide. | I think he maybe thought since an array's length property is immutable, then somehow arrays are *more* immutable than IList or maybe he used the wrong word and interchanged concrete with immutable. Who knows but it's an odd answer.
I think with returning a List there is something slightly implied that it's ok to modify it or that it may change while returning an array doesn't imply that as much.
For example, If you had an object model on top of a repository and had a method like GetCars() that returned a List and a junior programmer saw cars.Add(Car c) ... Would you think he was completely insane for thinking cars.Add(new Car()) might actually add a car into the repository? Arrays are just inherently more explicit.
I think List usage is more appropriate in properties, like Page.Controls.Add
I prefer returning arrays more often than List for several reasons.
* Habit. Collections in 1.0/1.1 SUCKED
* I prefer that my methods return the simplest & most lightweight object they can. If I need to make an Array a List it is trivial.
* They can be used in .net 1.1 and it reduces the surface are of refactoring if I ever needed to support older versions of the runtime I can reuse at least some of my code or apply an identical object model. | Whoever "he" is, is in 100% wrong on the topic. Arrays are a very much mutable. This is in fact one of the reasons not to return an array. There is no way to prevent a caller from changing the elements of an array to whatever they please.
The only way in which an Arrray is immutable is in it's length. Once an array is allocated, it's length cannot be changed. Even APIs such as Array.Resize don't actually resize the array, they just allocate a new one, copy the contents and return the new array (by reference in this case).
I do agree however that there are many cases in which it is better to return immutable data. The primary one is that it allows you to return a reference to an internal collection of a class without doing a complete copy and at the same time preventing the caller from messing with your internal state. Most mutable collections cannot make such guarantees. | returning IList<T> vs Array in C#? | [
"",
"c#",
".net",
"arrays",
"list",
"mutability",
""
] |
Is there a better way than using globals to get interesting values from a context manager?
```
@contextmanager
def transaction():
global successCount
global errorCount
try:
yield
except:
storage.store.rollback()
errorCount += 1
else:
storage.store.commit()
successCount += 1
```
Other possibilities:
* ### singletons
sort of globals...
* ### tuple as an argument to the context manager
makes the function more specific to a problem /less reusable
* ### instance that holds the specific attributes as an argument to the context manager
same problems as the tuple, but more legible
* ### raise an exception at the end of the context manager holding the values.
really bad idea | See <http://docs.python.org/reference/datamodel.html#context-managers>
Create a class which holds the success and error counts, and which implements the `__enter__` and `__exit__` methods. | I still think you should be creating a class to hold you error/success counts, as I said in you [last question](https://stackoverflow.com/questions/877440/try-except-except-how-to-avoid-repeating-code). I'm guessing you have your own class, so just add something like this to it:
```
class transaction:
def __init__(self):
self.errorCount = 0
self.successCount = 0
def __enter__(*args):
pass
def __exit__(self, type, value, traceback):
if type:
storage.store.rollback()
self.errorCount += 1
else:
storage.store.commit()
self.successCount += 1
```
(`type` is None if there are no exceptions once invoking the `contextmanager`)
And then you probably are already using this somewhere, which will invoke the `contextmanager` and run your `__exit__()` code. **Edit:** As Eli commented, only create a new transaction instance when you want to reset the coutners.
```
t = transaction()
for q in queries:
with t:
t.execute(q)
``` | How should I return interesting values from a with-statement? | [
"",
"python",
"with-statement",
"contextmanager",
""
] |
If you submit an update statement to a RDBMS in which the order of the column\_name = value mappings don't match the physical layout of the file, does it affect (theoretically) the efficiency of the update operation?
I ask mainly out of curiosity, knowing full well that there's probably little effect. | I can say, in SQL Server and in Oracle, this is 'planned out' in the 'execution plan' stage and you will not notice a performance change when changing parameter ordering. I can't speak to some of the other 'less-enterprise' databases out there (SqLite, Firebird, Pervasive), but I expect that all databases will perform these steps when they parse the SQL statements into database operations. | If your DB engine is so poor as to be unable to optimize updates in this case, you certainly have worse problems to worry about:-(. IOW, there had *better* be no effect -- this is a matter of quality of implementation for the DB engine, but it's such a trivial one that I'd be appalled and astonished if it were otherwise. | SQL update statement construction - effects on efficiency | [
"",
"sql",
"rdbms",
""
] |
I've seen a few web searches and responses to this but it seems they all involve views.
How can I adjust a column so that it only allows NULL or a unique value?
In my case there's a table with stock items in which only the server items have a serial number. The rest are null. I would like to enforce some kind of control against entering the same serials.
Also, I cannot redesign the architecture as I'm writing a new front end to a still live site. | Can you validate from the frontend? Before you insert or commit your data make sure it is unique or NULL. | In MySQL, a `UNIQUE` column that's also nullable allows any number of nulls (in all engines). So, if you're using MySQL, just add a UNIQUE constraint to the column of interest. This behavior is the SQL standard and is also supported by PostgreSQL and SQLite (and apparently Oracle for single-column `UNIQUE` constraint only, though I can't confirm this).
However, this SQL standard behavior won't necessarily work for all other RDBMS engines, such as SQL Server or DB2; if you specify what engines you need to support, we may be able to offer more specific suggestions. | How can I make a column allow null or unique serial | [
"",
"sql",
"sql-server",
""
] |
What are some apraoches i can take to rewrite fairly large procedural php *roughly 2000 lines of code* app as an oo app. And should i even try to do so, or should i build on top of the existing app? I wrote it when i was learning programming and i now i want to expand it. | There is no silver bullet. However, you could do a lot worse than picking up this book:
<http://www.amazon.co.uk/Working-Effectively-Legacy-Robert-Martin/dp/0131177052> | I would probably do the following, converting the app into MVC:
1. Identify the purpose of each function (is it handling the request parameters, outputting data, querying the database?)
2. Try to refactor functions that do all of the above by splitting them into functions doing nothing more than one of those things.
3. For each function, try to find a suitable top object/class that can contain this function as a method
```
function addUserRecord($dbHandle, $userData) {[...]}
// Becomes
class User {
private $db;
public function addUser($data) {
[...]
}
}
```
4. For each separate \*.php-file that is accessible from the outside, turn it into an action of a corresponding controller:
> *<http://foo.bar.com/user/addUser.php>* // becomes
> *<http://foo.bar.com/user/add-user>*
Corresponding controller, using [Zend\_Framework](http://framework.zend.com)
```
class UserController extends Zend_Controller_Action {
public function addUserAction () {
[...]
}
}
```
5. Move all output specific stuff, such as echoing, into views.
The hardest part will probably be to create proper models, but it is very important and will be the foundation of your application. | Rewriting a midsize application in OO | [
"",
"php",
"oop",
""
] |
What is the best cross-browser way to detect the scrollTop of the browser window? I prefer not to use any pre-built code libraries because this is a very simple script, and I don't need all of that deadweight. | ```
function getScrollTop(){
if(typeof pageYOffset!= 'undefined'){
//most browsers except IE before #9
return pageYOffset;
}
else{
var B= document.body; //IE 'quirks'
var D= document.documentElement; //IE with doctype
D= (D.clientHeight)? D: B;
return D.scrollTop;
}
}
alert(getScrollTop())
``` | Or just simple as:
```
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
``` | Cross-browser method for detecting the scrollTop of the browser window | [
"",
"javascript",
"cross-browser",
""
] |
I have a servlet filter that handles errors for both vanilla servlets and `JSF` pages.
If an error is detected the user is redirected to an error page where he can give feedback. Then I try to read the value in the `ErrorBean` object. However, sometimes the error is not present - there is a 50-50 chance of the error being present.
When I use
```
FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
```
it sometimes returns a map with 1 entry and sometimes an empty map. In every case, the id is passed at http level.
I can't really reproduce what is causing this. Here is the relevant code (helper methods + empty implementations omitted). The ErrorFilter is mapped at `/*` and the ErrorBean is a session scope bean managed by JSF.
**ErrorFilter**
```
public class ErrorFilter implements Filter
{
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException
{
HttpServletRequest hreq = (HttpServletRequest) req;
HttpServletResponse hres = (HttpServletResponse) resp;
try
{
chain.doFilter(req, resp);
}
catch (IOException e)
{
handleError(e, hreq, hres);
}
catch (ServletException e)
{
handleError(e, hreq, hres);
}
catch (RuntimeException e)
{
handleError(e, hreq, hres);
}
}
private static void handleError(Throwable e, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
final RequestInfo requestInfo = new RequestInfo(getUri(req), req.getSession().getId(), null, null, UserFactory.getUser(), InetAddress.getByName(req.getRemoteAddr()));
String token = new DecimalFormat("00000000").format(Math.abs(RANDOM.nextInt() % Integer.MAX_VALUE));
//log msg
//send mail in a different thread
if (!req.getRequestURI().startsWith("/faces/error.jsp"))
{
resp.sendRedirect("/faces/error.jsp?token=" + token);
}
else
{
//log that an infite loop occurred
throw new ServletException(crapMsg, e);
}
}
}
```
**ErrorBean**
```
public class ErrorBean implements Serializable
{
private String feedback;
private String lastToken;
public String getLastErrorCode()
{
return "your token: " + getToken();
}
private String getToken()
{
final String token = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("token");
//here the "token" returns null although it is sent via get.
if (token != null)
{
if (!token.equals(lastToken))
{
// reset data on token change.
feedback = null;
}
lastToken = token;
}
return lastToken;
}
public void setFeedback(String feedback)
{
this.feedback = feedback;
}
public String getFeedback()
{
if (feedback == null)
{
feedback = getDefaultMessage();
}
return feedback;
}
public void send()
{
sendMail(lastToken,feedback);
}
}
``` | From my humble point of view, The faces Context should see the parameter the vary first time when request is already redirected on : `resp.sendRedirect("/faces/error.jsp?token=" + token);`
But when you make some other request, Faces do manipulation with it's Navigation system and Redirect the page, and obviously that the Filter is doing `chain.doFilter(req,resp);` that time, which authorize the JSF Navigation model to execute and thus removing your request parameter.
My suggestion is that you can add it to another session value, It'll be easier to manipulate then. | I don't think the FacesContext is available in a Servlet Filter. Doesn't a filter run before hitting the FacesServlet (which creates the FacesContext)?
Try reading: <http://www.thoughtsabout.net/blog/archives/000033.html> | http GET parameter SOMETIMES missing when using JSF | [
"",
"java",
"http",
"jsf",
"servlets",
""
] |
I am C# developer and now I am involved in some large, already in production, project that is written in Visual Basic.NET.
I am trying hard not to write in C# and use some automatic conversion tool to Visual Basic.NET. I want to be able to read and write fluently in Visual Basic.NET **QUICKLY**. I can write and read VB.NET but it is not so easy like writing and reading C#.
I would be grateful if someone who was in the same situation could share there experience or point to some good resources. | Here's a few quick links. The logic is the same. It's basically just syntax.
[Comparison of C Sharp and Visual Basic .NET](http://en.wikipedia.org/wiki/Comparison_of_C_sharp_and_Visual_Basic_.NET)
[C# and VB.NET Comparison Cheat Sheet](http://aspalliance.com/625)
[VB.NET and C# Comparison](http://www.harding.edu/fmccown/vbnet_csharp_comparison.html) | [This](http://www.harding.edu/fmccown/vbnet_csharp_comparison.html) is a good page that I've used in that situation in the past. It's not up-to-the-minute accurate, but should be a good starting point. | Visual Basic.NET resources for C# developer | [
"",
"c#",
"vb.net",
"programming-languages",
""
] |
I'm trying to implement a custom control in C# and I need to get events when the mouse is hovered. I know there is the MouseHover event but it only fires once. To get it to fire again I need to take the mouse of the control and enter it again.
Is there any way I can accomplish this? | Let's define "stops moving" as "remains within an `x` pixel radius for `n` ms".
Subscribe to the MouseMove event and use a timer (set to `n` ms) to set your timeout. Each time the mouse moves, check against the tolerance. If it's outside your tolerance, reset the timer and record a new origin.
Pseudocode:
```
Point lastPoint;
const float tolerance = 5.0;
//you might want to replace this with event subscribe/unsubscribe instead
bool listening = false;
void OnMouseOver()
{
lastpoint = Mouse.Location;
timer.Start();
listening = true; //listen to MouseMove events
}
void OnMouseLeave()
{
timer.Stop();
listening = false; //stop listening
}
void OnMouseMove()
{
if(listening)
{
if(Math.abs(Mouse.Location - lastPoint) > tolerance)
{
//mouse moved beyond tolerance - reset timer
timer.Reset();
lastPoint = Mouse.Location;
}
}
}
void timer_Tick(object sender, EventArgs e)
{
//mouse "stopped moving"
}
``` | I realize that this is an old topic but I wanted to share a way I found to do it: on the mouse move event call ResetMouseEventArgs() on the control that catches the event. | Multiple MouseHover events in a Control | [
"",
"c#",
"winforms",
""
] |
I am interested to learn about the binary format for a single or a double type used by C++ on Intel based systems.
I have avoided the use of floating point numbers in cases where the data needs to potentially be read or written by another system (i.e. files or networking). I do realise that I could use fixed point numbers instead, and that fixed point is more accurate, but I am interested to learn about the floating point format. | Floating-point format is determined by the processor, not the language or compiler. These days almost all processors (including all Intel desktop machines) either have no floating-point unit or have one that complies with IEEE 754. You get two or three different sizes (Intel with SSE offers 32, 64, and 80 bits) and each one has a sign bit, an exponent, and a significand. The number represented is usually given by this formula:
```
sign * (2**(E-k)) * (1 + S / (2**k'))
```
where k' is the number of bits in the significand and k is a constant around the middle range of exponents. There are special representations for zero (plus and minus zero) as well as infinities and other "not a number" (NaN) values.
There are definite quirks; for example, the fraction 1/10 cannot be represented exactly as a binary IEEE standard floating-point number. For this reason the IEEE standard also provides for a decimal representation, but this is used primarily by handheld calculators and not by general-purpose computers.
Recommended reading: David Golberg's [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.sun.com/source/806-3568/ncg_goldberg.html) | Wikipedia has a reasonable summary - see <http://en.wikipedia.org/wiki/IEEE_754>.
Burt if you want to transfer numbers betwen systems you should avoid doing it in binary format. Either use middleware like CORBA (only joking, folks), Tibco etc. or fall back on that old favourite, textual representation. | What is the binary format of a floating point number used by C++ on Intel based systems? | [
"",
"c++",
"binary",
"floating-point",
"intel",
""
] |
I have a list of lists:
```
lst = [[567, 345, 234], [253, 465, 756, 2345], [333, 777, 111, 555]]
```
I want map `lst` into another list containing only the second smallest number from each sublist. So the result should be `[345, 465, 333]`.
If I were just interested in the smallest number, I could write this as `map(lambda x: min(x), lst)`. To get the second smallest numbers, I thought of sorting and then indexing the results, like `map(lambda x: sort(x)[1], lst)`; however, `sort` [returns None rather than chaining](https://stackoverflow.com/questions/11205254).
If it were possible to use multiple statements in a `lambda`, I could write `map(lambda x: sort(x); x[1], lst)`, but this is not allowed.
Can I use `map` to solve the problem without defining a named function? How? | There are several different answers I can give here, from your specific question to more general concerns. So from most specific to most general:
**Q.** Can you put multiple statements in a lambda?
**A.** No. But you don't actually need to use a lambda. You can put the statements in a `def` instead. i.e.:
```
def second_lowest(l):
l.sort()
return l[1]
map(second_lowest, lst)
```
**Q.** Can you get the second lowest item from a lambda by sorting the list?
**A.** Yes. As [alex's answer](https://stackoverflow.com/questions/862412/is-it-possible-to-have-multiple-statements-in-a-python-lambda-expression/862430#862430) points out, `sorted()` is a version of sort that creates a new list, rather than sorting in-place, and can be chained. Note that this is probably what you should be using - it's bad practice for your map to have side effects on the original list.
**Q.** How should I get the second lowest item from each list in a sequence of lists?
**A.** `sorted(l)[1]` is not actually the best way for this. It has O(N log(N)) complexity, while an O(n) solution exists. This can be found in the heapq module.
```
>>> import heapq
>>> l = [5,2,6,8,3,5]
>>> heapq.nsmallest(l, 2)
[2, 3]
```
So just use:
```
map(lambda x: heapq.nsmallest(x,2)[1], list_of_lists)
```
It's also usually considered clearer to use a list comprehension, which avoids the lambda altogether:
```
[heapq.nsmallest(x,2)[1] for x in list_of_lists]
``` | Putting the expressions in a list may simulate multiple expressions:
E.g.:
```
lambda x: [f1(x), f2(x), f3(x), x+1]
```
This will not work with statements. | Is it possible to have multiple statements in a python lambda expression? | [
"",
"python",
"python-2.x",
""
] |
I come from a php background and in php, there is an `array_size()` function which tells you how many elements in the array are used.
Is there a similar method for a `String[]` array? Thanks. | Yes, `.length` (property-like, not a method):
```
String[] array = new String[10];
int size = array.length;
``` | ```
array.length
```
It is actually a final member of the array, not a method. | Java String array: is there a size of method? | [
"",
"java",
"arrays",
"string",
""
] |
Is it possible to sort an array with Unicode / UTF-8 characters in PHP using a natural order algorithm? For example (the order in this array is correctly ordered):
```
$array = array
(
0 => 'Agile',
1 => 'Ágile',
2 => 'Àgile',
3 => 'Âgile',
4 => 'Ägile',
5 => 'Ãgile',
6 => 'Test',
);
```
If I try with asort($array) I get the following result:
```
Array
(
[0] => Agile
[6] => Test
[2] => Àgile
[1] => Ágile
[3] => Âgile
[5] => Ãgile
[4] => Ägile
)
```
And using natsort($array):
```
Array
(
[2] => Àgile
[1] => Ágile
[3] => Âgile
[5] => Ãgile
[4] => Ägile
[0] => Agile
[6] => Test
)
```
How can I implement a function that returns the correct result order (0, 1, 2, 3, 4, 5, 6) under PHP 5? All the multi byte string functions (mbstring, iconv, ...) are available on my system.
**EDIT: I want to natsort() the values, not the keys - the only reason why I'm explicitly defining the keys (and using asort() instead of sort()) is to ease the job of finding out where the *sorting of unicode values* went wrong.** | **Nailed it!**
```
$array = array('Ägile', 'Ãgile', 'Test', 'カタカナ', 'かたかな', 'Ágile', 'Àgile', 'Âgile', 'Agile');
function Sortify($string)
{
return preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|tilde|uml);~i', '$1' . chr(255) . '$2', htmlentities($string, ENT_QUOTES, 'UTF-8'));
}
array_multisort(array_map('Sortify', $array), $array);
```
**Output:**
```
Array
(
[0] => Agile
[1] => Ágile
[2] => Âgile
[3] => Àgile
[4] => Ãgile
[5] => Ägile
[6] => Test
[7] => かたかな
[8] => カタカナ
)
```
---
**Even better:**
```
if (extension_loaded('intl') === true)
{
collator_asort(collator_create('root'), $array);
}
```
Thanks to @tchrist! | The question is not as easy to answer as it seems on the first look. This is one of the areas where PHP's lack of unicode supports hits you with full strength.
Frist of all [`natsort()`](http://de.php.net/manual/en/function.natsort.php) as suggested by other posters has nothing to do with sorting arrays of the type you want to sort. What you're looking for is a locale aware sorting mechanism as sorting strings with extended characters is always a question of the used language. Let's take German for example: A and Ä can sometimes be sorted as if they were the same letter (DIN 5007/1), and sometimes Ä can be sorted as it was in fact "AE" (DIN 5007/2). In Swedish, in contrast, Ä comes at the end of the alphabet.
If you don't use Windows, you're lucky as PHP provides some functions to exactly this. Using a combination of [`setlocale()`](http://de.php.net/manual/en/function.setlocale.php), [`usort()`](https://www.php.net/manual/en/function.usort.php), [`strcoll()`](https://www.php.net/manual/en/function.strcoll.php) and the correct UTF-8 locale for your language, you get something like this:
```
$array = array('Àgile', 'Ágile', 'Âgile', 'Ãgile', 'Ägile', 'Agile', 'Test');
$oldLocal = setlocale(LC_COLLATE, '<<your_RFC1766_language_code>>.utf8');
usort($array, 'strcoll');
setlocale(LC_COLLATE, $oldLocal);
```
Please note that it's mandatory to use the UTF-8 locale variant in order to sort UTF-8 strings. I reset the locale in the example above to its original value as setting a locale using [`setlocale()`](http://de.php.net/manual/en/function.setlocale.php) can introduce side-effects in other running PHP script - please see PHP manual for more details.
When you do use a Windows machine, there is currently **no** solution to this problem and there won't be any before PHP 6 I assume. Please see my own [question](https://stackoverflow.com/questions/120334/how-to-sort-an-array-of-utf-8-strings) on SO targeting this specific problem. | Natural sorting algorithm in PHP with support for Unicode? | [
"",
"php",
"arrays",
"sorting",
"unicode",
"utf-8",
""
] |
What I need to be able do is format data in a variable, like so:
```
format: xxx-xxx variable: 123456 output: 123-456
```
The problem is I need to be able to change the format, so a static solution wouldn't work. I also like to be able to change the variable size, like:
```
format: xxx-xxx variable: 1234 output: 1-234
```
Note: All of the variables will be numbers
**Edit** I should have been clear on the format its not going to always be grouping of 3, and it may have more then "-" as a symbol, the groups will be inconstant 1-22-333-4444 it will only be in grouping of 1-5 | Your best bet is [preg\_replace](https://www.php.net/preg_replace).
Regular expressions take some getting used to, but this is probably your best bet...
*EDIT:*
```
//initial parsing
$val = preg_replace(
'/(\d*?)(\d{1,2}?)(\d{1,3}?)(\d{1,4})$/',
'${1}-${2}-$[3}-${4}',
$inputString
);
//nuke leading dashes
$val - preg_replace('^\-+', '', $val);
```
The key is to make every set, except the righ-most one non-greedy, allowing for a right-side oriented pattern match. | You could implement the [strategy pattern](http://en.wikipedia.org/wiki/Strategy_pattern) and and have new formatting classes that are swappable at run time. It looks complicated if you haven't seen it before but it really helps with maintainability and allows you to switch the formatter with the setFormatter() at any time.
```
class StyleOne_Formatter implements Formatter
{
public function format($text)
{
return substr($text,0,3).'-'.substr($text,3);
}
}
class StyleTwo_Formatter implements Formatter
{
public function format($text)
{
return substr($text,0,1).'-'.substr($text,1);
}
}
```
Then you would have your formatting class which would be like so:
```
class NumberFormatter implements Formatter
{
protected $_formatter = null;
public function setFormatter(Formatter $formatter)
{
$this->_formatter = $formatter;
}
public function format($text)
{
return $this->_formatter->format($text);
}
}
```
Then you could use it like this:
```
$text = "12345678910";
$formatter = new NumberFormatter();
$formatter->setFormatter(new StyleOne_Formatter());
print $formatter->format($text);
// Outputs 123-45678910
$formatter->setFormatter(new StyleTwo_Formatter());
print $formatter->format($text);
// Outputs 1-2345678910
``` | formatting data in php | [
"",
"php",
"formatting",
"variables",
"string-formatting",
""
] |
The following linq2sql code is causing me much headache and I was hoping someone could help
```
DateTime _maxRecordedDate = (from snapshot in _ctx.Usage_Snapshots
where snapshot.server_id == server_id
orderby snapshot.reported_on descending
select snapshot.reported_on).First().Value;
```
This code works in LinqPad and compiles fine but when the project runs there is a 'Specified Method is Unsupported".
If I don't use Value or cast it I get the following error:
\*\*
> Cannot implicitly convert type
> 'System.DateTime?' to
> 'System.DateTime'. An explicit
> conversion exists (are you missing a
> cast?)
\*\* | ```
DateTime? _maxRecordedDate = _ctx.Usage_Snapshots.Where(s => s.server_id == server_id).Max(d => d.reported_on);
``` | Does it not want First().Value? Maybe just First().
I'm looking at [this](http://msdn.microsoft.com/en-us/vcsharp/aa336750.aspx#FirstSimple). | Trying to get max date from table using Linq2Sql | [
"",
"c#",
"linq-to-sql",
""
] |
i profiled a jdbc/hibernate batch-importer. it takes a csv transforms it slighly and imports it to the database sitting at localhost.
to my surprise the operation was not I/O bound but rather cpu-bound.
according to jmx/jconsole as well as the netbeans profiler it looked like 60% of the cpu time was spent in the "old gen" garbage collector
the rest is used for geometric conversions (this is reasonable) and hibernate session management.
other applications used about 5-10% according to jconsole
so what are "typical" ratios for cpu/young GC/old GC for such batch insert tasks? | Sixty percent is real high. This is often an indication of someone using a lot of temporary Strings, or something similar. The fact that it's happening in the "old generation" suggests it might be happening in the database end, maybe while waiting for database transactions to happen. But that's just a horseback guess.
You probably want to make more detailed profiles of the run. | afer taking a second look at the netbeans profiler/heap walker it became clear that there are tons of String instances containing full sql statements. this was caused by log4jdbc.
so Charlie Martins guess was partially correct.
log4jdbc was not configured to log to any appender, but its log level was still set to INFO. although the log file did not contain any sql information, it was still rendered in background.
the performance boost from not having log4jdbc was MASSIVE.
the database cpu% utilisation went up from 1-2% to 20-50% (one core fully utilized)
previously 5000 entries were inserted in batch mode, which took about 100 SECONDS
without logging once chunk of 5000 entries is now inserted in about 1-2 SECONDS.
GC now takes about 6-7% of the total cpu time, as it should be.
so my conclusio:
## Having a GC time of >20% is a clear indication that something is wrong. | healthy garbage collection metrics? | [
"",
"java",
"garbage-collection",
""
] |
This compiles:
```
int* p1;
const int* p2;
p2 = p1;
```
This does not:
```
vector<int*> v1;
vector<const int*> v2;
v2 = v1; // Error!
v2 = static_cast<vector<const int*> >(v1); // Error!
```
What are the type equivalence rules for nested const pointers? I thought the conversion would be implicit. Besides, I'd rather not implement point-wise assignment of STL containers, unless I really have to. | Direct assignment is not possible. As others explained, the equivalence is not established by the pointer types, but by the container types. In this case, vector doesn't want to accept another vector that has a different, but compatible element type.
No real problem, since you can use the `assign` member function:
```
v2.assign(v1.begin(), v1.end());
``` | Conversion from `int*` to `const int*` is built into the language, but vectors of these have no automatic conversion from one to the other. | STL container assignment and const pointers | [
"",
"c++",
"gcc",
"stl",
"constants",
""
] |
I have a web application that uses TONS of javascript, and as usual, there are a lot of textual constants that will be displayed to the user embedded in the code itself.
What do you think is the best way to make this localizable?
I know I need to take those strings off of the code and replace them with constants, which will be defined into some external place.
For the server side, ASP.Net provides some very neat capabilities for dealing with this.
What's the best to do this in Javascript?
The best idea I have is to have a JS file with ALL the string constants of the JS of the site (i'd have different copies of this, for each language), and then on each page, I include this script first, before all the others.
This seems like the most centralized way, that also wastes the least bandwidth.
Are there any other better approaches?
Thanks! | here's how we did it (in ASP.net), pretty much along the lines of what you've mentioned:
1) Created two javascript files: one which defines all javascript functions/DOM manipulations as required by the site, and, second called Messages.js: this defines all the string literals that need to be localized, something like var ALERT\_MSG = "Alert message in english".
2) Created different version of the Messages.js, one for each locale that we are supporting and localized the strings. The localized js files were named using messages.locale.js naming convention (for eg. messages.fr-FR.js).
3) Included the js files within the "ScriptManager" and provided the ResourceUICultures for the Messages.js file: this ensures that the correct localized file is embedded in the html output (if you are not using ASP.net you can build this basic functionality by doing some culture sniffing and including the appropriate js file).
4) Voila! | Your approach makes sense. Details:
I'd have the strings for each language in an object.
localized={"cat":"chat","dog":"chien"};
Then in code:
localized["cat"]
The quotations around of the keys and the array notation (rather than the more common object dot notation) are to avoid collisions with JavaScript reserved words. | How to do localizable javascript? | [
"",
"javascript",
"localization",
""
] |
in my multithraded application, I'm using a sleep() function (the one from the GLFW library):
```
glfwSleep(..);
```
and it apparently leads my application to segfaulting as my call stack shows:
```
#0 76CFC2BC WaitForSingleObjectEx() (C:\Windows\system32\kernel32.dll:??)
#1 00000016 ??() (??:??)
#2 0000006C ??() (??:??)
#3 00000000 ??() (??:??)
```
The `glfwSleep()` is used inside a thread. Is that dangerous? Why is my program segfaulting as a consequence to that?
### Edit:
When the parameter of the `glfwSleep()` is < 0.02 (secs) it doesn't segfault!
### Edit 2:
From the official documentation of GLFW :
> Writing threaded applications may be
> very awkward before you get used to
> it, but there are a few key rules that
> are fairly simple to follow:
>
> * ALWAYS assure exclusive access to data that is shared between threads!
> * Make sure that threads are synchronized properly!
> * **NEVER busy wait!**
I think i got my answer..have to find an alternative now..
Thanks! | From [the GLFW wiki](http://www.haskell.org/haskellwiki/GLFW):
> GLFW doesn't work well with GHC
> threads, forkIO or threadDelay. So
> avoid them if you can. | To quote [*The Pragmatic Programmer*](http://www.pragprog.com/the-pragmatic-programmer),
> **``select’’ Isn’t Broken**
>
> It is rare to
> find a bug in the OS or the compiler,
> or even a third-party product or
> library. The bug is most likely in the
> application.
Why is your program calling `WaitForSingleObjectEx()` when `glfwSleep()` calls `Sleep()`? Well, even though you don't have the source code to `Sleep()`, it's not completely a black box. Disassemble `Sleep()` and you'll probably see (depending on which version of Windows you have) that `Sleep()` either calls or tail-calls `SleepEx()`. On XP, `SleepEx()` calls `NtDelayExecutionThread()`, and on Vista it calls `WaitForSingleObjectEx()`.
So what happened to the rest of your stack? 00000016, 0000006C, and 00000000 aren't valid return addresses. I would not be surprised if somewhere in your code, you pass a pointer to a stack-allocated buffer to another thread, and while your program is sleeping, that other thread corrupts the first thread's stack. Step into `Sleep()`, put a memory breakpoint on the return address, and you may be able to catch the culprit. | How can a glfwSleep() cause a segfault? | [
"",
"c++",
"c",
"segmentation-fault",
"sleep",
"glfw",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.