qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
160,298
|
<p>This is a part algorithm-logic question (how to do it), part implementation question (how to do it best!). I'm working with Django, so I thought I'd share with that.</p>
<p>In Python, it's worth mentioning that the problem is somewhat related to <a href="https://stackoverflow.com/questions/773/how-do-i-use-pythons-itertoolsgroupby">how-do-i-use-pythons-itertoolsgroupby</a>.</p>
<p>Suppose you're given two Django Model-derived classes:</p>
<pre><code>from django.db import models
class Car(models.Model):
mods = models.ManyToManyField(Representative)
</code></pre>
<p>and</p>
<pre><code>from django.db import models
class Mods(models.Model):
...
</code></pre>
<p>How does one get a list of Cars, grouped by Cars with a common set of Mods?</p>
<p>I.e. I want to get a class likeso:</p>
<pre><code>Cars_by_common_mods = [
{ mods: { 'a' }, cars: { 'W1', 'W2' } },
{ mods: { 'a', 'b' }, cars: { 'X1', 'X2', 'X3' }, },
{ mods: { 'b' }, cars: { 'Y1', 'Y2' } },
{ mods: { 'a', 'b', 'c' }, cars: { 'Z1' } },
]
</code></pre>
<p>I've been thinking of something like:</p>
<pre><code>def cars_by_common_mods():
cars = Cars.objects.all()
mod_list = []
for car in cars:
mod_list.append( { 'car': car, 'mods': list(car.mods.all()) }
ret = []
for key, mods_group in groupby(list(mods), lambda x: set(x.mods)):
ret.append(mods_group)
return ret
</code></pre>
<p>However, that doesn't work because (perhaps among other reasons) the groupby doesn't seem to group by the mods sets. I guess the mod_list has to be sorted to work with groupby. All to say, I'm confident there's something simple and elegant out there that will be both enlightening and illuminating.</p>
<p><em>Cheers & thanks!</em></p>
|
[
{
"answer_id": 161082,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 3,
"selected": true,
"text": "import itertools\n\ncars = [\n {'car': 'X2', 'mods': [1,2]},\n {'car': 'Y2', 'mods': [2]},\n {'car': 'W2', 'mods': [1]},\n {'car': 'X1', 'mods': [1,2]},\n {'car': 'W1', 'mods': [1]},\n {'car': 'Y1', 'mods': [2]},\n {'car': 'Z1', 'mods': [1,2,3]},\n {'car': 'X3', 'mods': [1,2]},\n]\n\ncars.sort(key=lambda car: car['mods'])\n\ncars_by_common_mods = {}\nfor k, g in itertools.groupby(cars, lambda car: car['mods']):\n cars_by_common_mods[frozenset(k)] = [car['car'] for car in g]\n\nprint cars_by_common_mods\n import collections\nimport itertools\nfrom operator import itemgetter\n\nfrom django.db import connection\n\ncursor = connection.cursor()\ncursor.execute('SELECT car_id, mod_id FROM someapp_car_mod ORDER BY 1, 2')\ncars = collections.defaultdict(list)\nfor row in cursor.fetchall():\n cars[row[0]].append(row[1])\n\n# Here's one I prepared earlier, which emulates the sample data we've been working\n# with so far, but using the car id instead of the previous string.\ncars = {\n 1: [1,2],\n 2: [2],\n 3: [1],\n 4: [1,2],\n 5: [1],\n 6: [2],\n 7: [1,2,3],\n 8: [1,2],\n}\n\nsorted_cars = sorted(cars.iteritems(), key=itemgetter(1))\ncars_by_common_mods = []\nfor k, g in itertools.groupby(sorted_cars, key=itemgetter(1)):\n cars_by_common_mods.append({'mods': k, 'cars': map(itemgetter(0), g)})\n\nprint cars_by_common_mods\n\n# Which, for the sample data gives me (reformatted by hand for clarity)\n[{'cars': [3, 5], 'mods': [1]},\n {'cars': [1, 4, 8], 'mods': [1, 2]},\n {'cars': [7], 'mods': [1, 2, 3]},\n {'cars': [2, 6], 'mods': [2]}]\n dict"
},
{
"answer_id": 161227,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 1,
"selected": false,
"text": "groups = []\nuniquekeys = []\nfor k, g in groupby(data, keyfunc):\n groups.append(list(g)) # Store group iterator as a list\n uniquekeys.append(k)\n sortMethod = lambda x: tuple(sorted(set(x.mods)))\nsortedMods = sorted(list(mods), key=sortMethod)\nfor key, mods_group in groupby(sortedMods, sortMethod):\n ret.append(list(mods_group))\n"
},
{
"answer_id": 178657,
"author": "Brian M. Hunt",
"author_id": 19212,
"author_profile": "https://Stackoverflow.com/users/19212",
"pm_score": 0,
"selected": false,
"text": "class ModSet(models.Model):\n mods = models.ManyToManyField(Mod)\n class Car(models.Model):\n modset = models.ForeignKey(ModSet)\n"
}
] |
2008/10/01
|
[
"https://Stackoverflow.com/questions/160298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19212/"
] |
160,304
|
<p>I am using sybase database to query the daily transaction report. I had subquery within my script. </p>
<p>Here as it goes:</p>
<pre><code>SELECT orders.accountid ,items.x,etc
(SELECT charges.mistotal FROM charges where items.id = charges.id)
FROM items,orders
WHERE date = '2008-10-02'
</code></pre>
<p>Here I am getting the error message as:</p>
<blockquote>
<p><em>Subquery cannot return more than one values</em></p>
</blockquote>
<p>My values are 7.50, 25.00</p>
<p>I want to return the 25.00, but when I use </p>
<pre><code>(SELECT TOP 1 charges.mistotal FROM charges where items.id = charges.id)
</code></pre>
<p>My result is 7.50 but I want to return 25.00</p>
<p>Does anyone has any better suggestion?</p>
|
[
{
"answer_id": 160327,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 1,
"selected": false,
"text": "SELECT MAX(charges.mistotal) FROM charges WHERE items.id = charges.id\n"
},
{
"answer_id": 160338,
"author": "senfo",
"author_id": 10792,
"author_profile": "https://Stackoverflow.com/users/10792",
"pm_score": 4,
"selected": false,
"text": "SELECT TOP 1 * \nFROM dbo.YourTable \nORDER BY Col DESC\n SELECT TOP 1 charges.mistotal \nFROM charges where items.id = charges.id \nORDER BY charges.mistotal DESC\n"
},
{
"answer_id": 160343,
"author": "Matt",
"author_id": 4154,
"author_profile": "https://Stackoverflow.com/users/4154",
"pm_score": 0,
"selected": false,
"text": "(SELECT TOP 1 charges.mistotal FROM charges where items.id = charges.id \n ORDER BY charges.mistotal DESC)\n"
},
{
"answer_id": 160355,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "(SELECT TOP 1 charges.mistotal\n FROM charges\n WHERE items.id = charges.id\n ORDER BY charges.mistotal DESC\n)\n (SELECT MAX(charges.mistotal)\n FROM charges\n WHERE charges.id = items.id\n)\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14752/"
] |
160,313
|
<p>I'm working on a project where I'm trying to avoid hard-coding DB IDs in a .NET service-oriented project. There are some instances where I <strong>need</strong> to set ID values through code but I don't want to just hard code the IDs since I've done that before and it lead to DB alignment nightmares when the auto-incrementing IDs were changed when the DB was dumped to a new system.</p>
<p>What I want to do is create an enumerated constants that store the IDs as so that at the worst, only 1 file has to be updated if the DB is ever changed instead of trying to go through thousands upon thousands of lines of code to replace any ID in the system.</p>
<p>This will work on a single system, but in my company's service oriented environment, enumerations don't serialize with their values, just their names.</p>
<p>What is the best way to share IDs across a web service? I'd like to use either enumerations (the ideal situation) or constants in some way, but I can't seem to get this to work. I could make a web method that returns the IDs, but sending a web request for every ID and then serializing the response and deserializing on the client machine just sounds like a bad idea.</p>
<p><strong>EDIT</strong><br>
I wasn't entirely clear about what I was asking, so I'll elaborate.</p>
<p>I want to have a group of constants. The enum would only be used because it groups constants together appropriately. I'm mainly interested in see if there is a way to share constants across a web service. I need the values the enum represent, not the enum itself. The enum is never sent between the service and the client except as an integer. Internally everything is stored as an ID, not an enum.</p>
<p>Having a separate shared library doesn't sound like the ideal solution since I'm almost at the completion point for this project and I'd only be storing 1 enum/class in the library. It seems like a bit of a waste to make for just one class.</p>
|
[
{
"answer_id": 160446,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 0,
"selected": false,
"text": "DayOfWeek ConvertToDayOfWeek(this String str)\n{\n return (DayOfWeek)Enum.Parse(typeof(DayOfWeek), str, true);\n}\n"
},
{
"answer_id": 164325,
"author": "Shaun Bowe",
"author_id": 1514,
"author_profile": "https://Stackoverflow.com/users/1514",
"pm_score": 0,
"selected": false,
"text": "(Int32)objectThatWasPassed.EnumerationValue;\n objectbeingPassed.ConstantProperty = (Int32)Whatever.Constant1;\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] |
160,315
|
<p>I'm trying to write a resolution selection dialog that pops up when a program first starts up. To prevent boring the user, I want to implement the fairly standard feature that you can turn off that dialog with a checkbox, but get it back by holding down the alt key at startup.</p>
<p>Unfortunately, there is no obvious way to ask java whether a given key is <strong>currently being pressed</strong>. You can only register to be informed of new key presses via a KeyListener, but that doesn't help if the keypress starts before the app launches.</p>
|
[
{
"answer_id": 160806,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 2,
"selected": false,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.JFrame;\n\npublic class LockingKeyDemo {\n static Toolkit kit = Toolkit.getDefaultToolkit();\n\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n\n frame.addWindowListener(new WindowAdapter() {\n public void windowActivated(WindowEvent e) {\n System.out.println(\"caps lock1 = \"\n + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));\n\n try {\n Robot robot = new Robot();\n robot.keyPress(KeyEvent.VK_CONTROL);\n robot.keyRelease(KeyEvent.VK_CONTROL);\n } catch (Exception e2) {\n System.out.println(e2);\n }\n\n System.out.println(\"caps lock2 = \"\n + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));\n }\n });\n\n frame.addKeyListener(new KeyAdapter() {\n public void keyReleased(KeyEvent e) {\n System.out.println(\"caps lock3 = \"\n + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));\n }\n });\n\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setSize(200, 200);\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n }\n}\n"
},
{
"answer_id": 160851,
"author": "Karan",
"author_id": 11110,
"author_profile": "https://Stackoverflow.com/users/11110",
"pm_score": 2,
"selected": false,
"text": "KEY_PRESSED sleep.thread(timeInMs)"
},
{
"answer_id": 160861,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 2,
"selected": true,
"text": "public class LockingKeyDemo {\n static Toolkit kit = Toolkit.getDefaultToolkit();\n\n public static void main(String[] args) {\n System.out.println(\"caps lock2 = \"\n + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));\n}\n}\n"
},
{
"answer_id": 11713934,
"author": "AlexV",
"author_id": 206494,
"author_profile": "https://Stackoverflow.com/users/206494",
"pm_score": 2,
"selected": false,
"text": "com.sun.jna.platform.KeyboardUtils.isPressed(java.awt.event.KeyEvent.VK_ALT); User32.INSTANCE.GetAsyncKeyState(...)"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15255/"
] |
160,318
|
<p>The kind of simulation game that I have in mind is the kind where you have things to build in various locations and workers/transporters that connect such locations.</p>
<p>Something more like the Settlers series.</p>
<p>Let's assume I don't want any graphics at the moment, <strong>that</strong> I think I can manage.</p>
<p>So my doubts are the following:</p>
<ol>
<li>Should every entity be a class and each one have a thread?</li>
<li>Should entities be grouped in lists inside classes and each one have a thread?</li>
</ol>
<p>If one takes implementation 1, it's going to be very hard to run on low spec machines and does not scale well for large numbers.</p>
<p>If one takes implementation 2, it's going to be better in terms of resources but then...</p>
<p>How should I group the entities?</p>
<ol>
<li>Have a class for houses in general and have an Interface List to manage that?</li>
<li>Have a class for specific groups of houses and have an Object List to manage that?</li>
</ol>
<p>and what about threads?</p>
<ol>
<li>Should I have the simplistic main game loop?</li>
<li>Should I have a thread for each class group?</li>
<li>How do workers/transporters fit in the picture?</li>
</ol>
|
[
{
"answer_id": 160349,
"author": "Zarkonnen",
"author_id": 15255,
"author_profile": "https://Stackoverflow.com/users/15255",
"pm_score": 2,
"selected": false,
"text": "House"
},
{
"answer_id": 160356,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": " while( 1 )\n{\n foreach( entity in entlist )\n {\n entity->update();\n }\n\n render();\n}\n"
},
{
"answer_id": 12781435,
"author": "Deer Hunter",
"author_id": 1651408,
"author_profile": "https://Stackoverflow.com/users/1651408",
"pm_score": 1,
"selected": false,
"text": "foreach"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8167/"
] |
160,335
|
<p>I've been playing with the .NET built in localization features and they seem to all rely on putting data in resx files. </p>
<p>But most systems can't rely on this because they are database driven. So how do you solve this issue? Is there a built in .NET way, or do you create a translations table in SQL and do it all manually? And if you have to do this on the majority of your sites, is there any reason to even use the resx way of localization?</p>
<p>An example of this is I have an FAQ list on my site, I keep this list in the database so I can easily add/remove more, but by putting it in the database, I have no good way have translating this information into multiple languages.</p>
|
[
{
"answer_id": 164253,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 2,
"selected": false,
"text": "Item (ItemID, ...)\nItemLocal (ItemID,LocaleID,....)\n Item (ItemID, ...)\nItem_ENUS (ItemID,....)\nItem_ENGB (ItemID,....)\nItem_FR (ItemID,....)\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17176/"
] |
160,370
|
<p>In svn, I have a branch which was created, say at revision 22334. Commits were then made on the branch.</p>
<p>How do I get a list of all files that were changed on the branch compared to what's on the trunk? I do not want to see files that were changed on the trunk between when the branch was created and "now".</p>
|
[
{
"answer_id": 160395,
"author": "andy",
"author_id": 21482,
"author_profile": "https://Stackoverflow.com/users/21482",
"pm_score": 7,
"selected": true,
"text": "svn diff -r 22334:HEAD --summarize <url of the branch>\n"
},
{
"answer_id": 5207017,
"author": "Robert Duchnik",
"author_id": 590026,
"author_profile": "https://Stackoverflow.com/users/590026",
"pm_score": 6,
"selected": false,
"text": "svn status -u\n"
},
{
"answer_id": 9901966,
"author": "Binny Jeshan",
"author_id": 1297285,
"author_profile": "https://Stackoverflow.com/users/1297285",
"pm_score": 1,
"selected": false,
"text": "svn status -u | grep -v '\\?' \n"
},
{
"answer_id": 11132492,
"author": "hunter",
"author_id": 1471184,
"author_profile": "https://Stackoverflow.com/users/1471184",
"pm_score": 4,
"selected": false,
"text": "svn status -u | grep M\n"
},
{
"answer_id": 11885510,
"author": "Hasski",
"author_id": 1587846,
"author_profile": "https://Stackoverflow.com/users/1587846",
"pm_score": 2,
"selected": false,
"text": "echo You must invoke st from within branch directory\nSvnUrl=`svn info | grep URL | sed 's/URL: //'`\nSvnVer=`svn info | grep Revision | sed 's/Revision: //'`\nsvn diff -r $SvnVer --summarize $SvnUrl\n"
},
{
"answer_id": 46920533,
"author": "maskarih",
"author_id": 3292365,
"author_profile": "https://Stackoverflow.com/users/3292365",
"pm_score": 5,
"selected": false,
"text": "svn status -q\n With --quiet (-q), it prints only summary information about locally modified items. svn up svn status -q"
},
{
"answer_id": 57669761,
"author": "Sweavo",
"author_id": 11982419,
"author_profile": "https://Stackoverflow.com/users/11982419",
"pm_score": 1,
"selected": false,
"text": "svn log -q -v cut sort svn log --stop-on-copy -q -v | grep '^[[:space:]]'| cut -c6- | sort -u"
},
{
"answer_id": 68303597,
"author": "KawaiiGuyNH",
"author_id": 11836321,
"author_profile": "https://Stackoverflow.com/users/11836321",
"pm_score": 1,
"selected": false,
"text": "svn log --stop-on-copy |tail -4 --stop-on-copy tail svn diff svn diff -r <revision at which you branched>:head --summarize --summarize"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2601671/"
] |
160,373
|
<pre><code>Function FillAdminAccount() As Boolean
FillAdminAccount = True
Try
SQLconn.ConnectionString = "connect timeout=9999999;" & _
"data source=" & DefaultIserver & ";" & _
"initial catalog=" & DefaultIdBase & "; " & _
"user id=userid;" & _
"password=userpass;" & _
"persist security info=True; " & _
"packet size=4096"
SQLconn.Open()
SQLcmd.CommandType = CommandType.Text
SQLcmd.CommandText = "Select distinct username, cast(convert(varchar,userpassword) as varchar) as 'userpassword' from " & tblUsersList & " where usertype='MainAdmin'"
SQLcmd.Connection = SQLconn
SQLreader = SQLcmd.ExecuteReader
While SQLreader.Read = True
CurrentAdminUser = SQLreader("username").ToString
CurrentAdminPass = SQLreader("userpassword").ToString 'PROBLEM'
End While
Catch ex As Exception
ErrorMessage(ex)
Finally
If SQLconn.State = ConnectionState.Open Then SQLconn.Close()
If SQLreader.IsClosed = False Then SQLreader.Close()
End Try
End Function 'FillAdminAccount
</code></pre>
<p>Please see the line with the comment PROBLEM. On this code, the output is equal to <em>"userpassword</em>. As you can see, there is no quotation mark on the right and <strong>I wonder why</strong>. By the way, the data type of the userpassword in the database is BINARY. Wish you could help me on this. Thank you..x_x</p>
|
[
{
"answer_id": 160396,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 1,
"selected": false,
"text": "as varchar) as 'userpassword'\n ...as varchar) as [userpassword] ..\n ...as varchar) as userpassword ..\n"
},
{
"answer_id": 160457,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 1,
"selected": false,
"text": " cast(convert(varchar,userpassword) as varchar\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21963/"
] |
160,376
|
<p>I've noticed that just in the last year or so, many major websites have made the same change to the way their pages are structured. Each has moved their Javascript files from being hosted on the same domain as the page itself (or a subdomain of that), to being hosted on a differently named domain.</p>
<h2>It's not simply parallelization</h2>
<p>Now, there is a well known technique of spreading the components of your page across multiple domains to parallelize downloading. <a href="http://developer.yahoo.com/performance/rules.html#split" rel="nofollow noreferrer">Yahoo recommends it</a> as do many others. For instance, <strong>www.example.com</strong> is where your HTML is hosted, then you put images on <strong>images.example.com</strong> and javascripts on <strong>scripts.example.com</strong>. This gets around the fact that most browsers limit the number of simultaneous connections per server in order to be good net citizens.</p>
<p>The above is <em>not</em> what I am talking about.</p>
<h2>It's not simply redirection to a content delivery network (or maybe it is--see bottom of question)</h2>
<p>What I am talking about is hosting Javascripts specifically on an entirely different domain. Let me be specific. Just in the last year or so I've noticed that:</p>
<p><strong>youtube.com</strong> has moved its .JS files to <strong>ytimg.com</strong></p>
<p><strong>cnn.com</strong> has moved its .JS files to <strong>cdn.turner.com</strong></p>
<p><strong>weather.com</strong> has moved its .JS files to <strong>j.imwx.com</strong></p>
<p>Now, I know about content delivery networks like <a href="http://www.akamai.com" rel="nofollow noreferrer">Akamai</a> who specialize in outsourcing this for large websites. (The name "cdn" in Turner's special domain clues us in to the importance of this concept here).</p>
<p>But note with these examples, each site has its own specifically registered domain for this purpose, and its not the domain of a content delivery network or other infrastructure provider. In fact, if you try to load the home page off most of these script domains, they usually redirect back to the main domain of the company. And if you reverse lookup the IPs involved, they <em>sometimes</em> appear point to a CDN company's servers, sometimes not.</p>
<h2>Why do I care?</h2>
<p>Having formerly worked at two different security companies, I have been made paranoid of malicious Javascripts.</p>
<p>As a result, I follow the practice of whitelisting sites that I will allow Javascript (and other active content such as Java) to run on. As a result, to make a site like <strong>cnn.com</strong> work properly, I have to manually put <strong>cnn.com</strong> into a list. It's a pain in the behind, but I prefer it over the alternative.</p>
<p>When folks used things like <strong>scripts.cnn.com</strong> to parallelize, that worked fine with appropriate wildcarding. And when folks used subdomains off the CDN company domains, I could just permit the CDN company's main domain with a wildcard in front as well and kill many birds with one stone (such as *.edgesuite.net and *.akamai.com).</p>
<p>Now I have discovered that (as of 2008) this is not enough. Now I have to poke around in the source code of a page I want to whitelist, and figure out what "secret" domain (or domains) that site is using to store their Javascripts on. In some cases I've found I have to permit three different domains to make a site work.</p>
<h2>Why did all these major sites start doing this?</h2>
<p>EDIT: OK <a href="https://stackoverflow.com/questions/160376/why-move-your-javascript-files-to-a-different-main-domain-that-you-also-own#160451">as "onebyone" pointed out</a>, it does appear to be related to CDN delivery of content. So let me modify the question slightly based on his research...</p>
<p>Why is <strong>weather.com</strong> using <strong>j.imwx.com</strong> instead of <strong>twc.vo.llnwd.net</strong>?</p>
<p>Why is <strong>youtube.com</strong> using <strong>s.ytimg.com</strong> instead of <strong>static.cache.l.google.com</strong>?</p>
<p>There has to a reasoning behind this.</p>
|
[
{
"answer_id": 160451,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": false,
"text": "$ host j.imwx.com\nj.imwx.com CNAME twc.vo.llnwd.net\ntwc.vo.llnwd.net A 87.248.211.218\ntwc.vo.llnwd.net A 87.248.211.219\n$ whois llnwd.net\n<snip ...>\nRegistrant:\n Limelight Networks Inc.\n 2220 W. 14th Street\n Tempe, Arizona 85281-6945\n United States\n $ host s.ytimg.com\ns.ytimg.com CNAME static.cache.l.google.com\nstatic.cache.l.google.com A 74.125.100.97\n $ host cdn.turner.com\ncdn.turner.com A record currently not present\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4425/"
] |
160,391
|
<p>I've got a ListBox control and I'm presenting a fixed number of ListBoxItem objects in a grid layout. So I've set my ItemsPanelTemplate to be a Grid.</p>
<p>I'm accessing the Grid from code behind to configure the RowDefinitions and ColumnDefinitions.</p>
<p>So far it's all working as I expect. I've got some custom IValueConverter implementations for returning the Grid.Row and Grid.Column that each ListBoxItem should appear in.</p>
<p>However I get weird binding errors sometimes, and I can't figure out exactly why they're happening, or even if they're in my code.</p>
<p>Here's the error I get:</p>
<blockquote>
<p><code>System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'ListBoxItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')</code></p>
</blockquote>
<p>Can anybody explain what's going on?</p>
<p>Oh, and, here's my XAML:</p>
<pre><code><UserControl.Resources>
<!-- Value Converters -->
<v:GridRowConverter x:Key="GridRowConverter" />
<v:GridColumnConverter x:Key="GridColumnConverter" />
<v:DevicePositionConverter x:Key="DevicePositionConverter" />
<v:DeviceBackgroundConverter x:Key="DeviceBackgroundConverter" />
<Style x:Key="DeviceContainerStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="Grid.Row" Value="{Binding Path=DeviceId, Converter={StaticResource GridRowConverter}}" />
<Setter Property="Grid.Column" Value="{Binding Path=DeviceId, Converter={StaticResource GridColumnConverter}}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border CornerRadius="2" BorderThickness="1" BorderBrush="White" Margin="2" Name="Bd"
Background="{Binding Converter={StaticResource DeviceBackgroundConverter}}">
<TextBlock FontSize="12" HorizontalAlignment="Center" VerticalAlignment="Center"
Text="{Binding Path=DeviceId, Converter={StaticResource DevicePositionConverter}}" >
<TextBlock.LayoutTransform>
<RotateTransform Angle="270" />
</TextBlock.LayoutTransform>
</TextBlock>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Bd" Property="BorderThickness" Value="2" />
<Setter TargetName="Bd" Property="Margin" Value="1" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Border CornerRadius="3" BorderThickness="3" Background="#FF333333" BorderBrush="#FF333333" >
<Grid ShowGridLines="False">
<Grid.RowDefinitions>
<RowDefinition Height="15" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal">
<Image Margin="20,3,3,3" Source="Barcode.GIF" Width="60" Stretch="Fill" />
</StackPanel>
<ListBox ItemsSource="{Binding}" x:Name="lstDevices" Grid.Row="1"
ItemContainerStyle="{StaticResource DeviceContainerStyle}"
Background="#FF333333"
SelectedItem="{Binding SelectedDeviceResult, ElementName=root, Mode=TwoWay}" >
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<Grid>
<Grid.LayoutTransform>
<RotateTransform Angle="90" />
</Grid.LayoutTransform>
</Grid>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</Grid>
</Border>
</code></pre>
<p></p>
|
[
{
"answer_id": 163728,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 1,
"selected": false,
"text": "DataTemplates ItemTemplate Style ItemContainerStyle ListBoxItem Panel Panel IValueConverters"
},
{
"answer_id": 176410,
"author": "ligaz",
"author_id": 6409,
"author_profile": "https://Stackoverflow.com/users/6409",
"pm_score": 5,
"selected": false,
"text": "<Style\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:s=\"clr-namespace:System;assembly=mscorlib\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n TargetType=\"{x:Type ListBoxItem}\">\n <Style.Resources>\n <ResourceDictionary/>\n </Style.Resources>\n <Setter Property=\"Panel.Background\">\n <Setter.Value>\n <SolidColorBrush>\n #00FFFFFF\n </SolidColorBrush>\n </Setter.Value>\n </Setter>\n <Setter Property=\"Control.HorizontalContentAlignment\">\n <Setter.Value>\n <Binding Path=\"HorizontalContentAlignment\" RelativeSource=\"{RelativeSource Mode=FindAncestor, AncestorType=ItemsControl, AncestorLevel=1}\"/>\n </Setter.Value>\n </Setter>\n <Setter Property=\"Control.VerticalContentAlignment\">\n <Setter.Value>\n <Binding Path=\"VerticalContentAlignment\" RelativeSource=\"{RelativeSource Mode=FindAncestor, AncestorType=ItemsControl, AncestorLevel=1}\"/>\n </Setter.Value>\n </Setter>\n <Setter Property=\"Control.Padding\">\n <Setter.Value>\n <Thickness>\n 2,0,0,0\n </Thickness>\n </Setter.Value>\n </Setter>\n <Setter Property=\"Control.Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type ListBoxItem}\">\n ...\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n"
},
{
"answer_id": 218400,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 3,
"selected": false,
"text": "ListBoxItem *Item ItemsControl ListBox.ItemContainerGenerator StatusChanged ItemsGenerated"
},
{
"answer_id": 636862,
"author": "JTango18",
"author_id": 76954,
"author_profile": "https://Stackoverflow.com/users/76954",
"pm_score": 5,
"selected": false,
"text": "OverridesDefaultStyle True ItemContainerStyle <Style TargetType=\"ListBoxItem\">\n <Setter Property=\"OverridesDefaultStyle\" Value=\"True\"/>\n <!-- set the rest of your setters, including Template, here -->\n</Style>\n"
},
{
"answer_id": 1578969,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 1,
"selected": false,
"text": "ListBoxItem ItemsControl ListBox <Style TargetType=\"ListBoxItem\">\n <Setter Property=\"Margin\" Value=\"2\" />\n <Setter Property=\"FocusVisualStyle\" Value=\"{x:Null}\" />\n <Setter Property=\"OverridesDefaultStyle\" Value=\"True\" />\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type ListBoxItem}\">\n <ContentPresenter Content=\"{TemplateBinding ContentControl.Content}\" \n HorizontalAlignment=\"Stretch\" \n VerticalAlignment=\"{TemplateBinding Control.VerticalContentAlignment}\" \n SnapsToDevicePixels=\"{TemplateBinding UIElement.SnapsToDevicePixels}\" />\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n Border <Border BorderThickness=\"{TemplateBinding Border.BorderThickness}\" \n Padding=\"{TemplateBinding Control.Padding}\" \n BorderBrush=\"{TemplateBinding Border.BorderBrush}\" \n Background=\"{TemplateBinding Panel.Background}\" \n SnapsToDevicePixels=\"True\">\n <ContentPresenter Content=\"{TemplateBinding ContentControl.Content}\" \n ContentTemplate=\"{TemplateBinding ContentControl.ContentTemplate}\" \n HorizontalAlignment=\"{TemplateBinding Control.HorizontalContentAlignment}\" \n VerticalAlignment=\"{TemplateBinding Control.VerticalContentAlignment}\" \n SnapsToDevicePixels=\"{TemplateBinding UIElement.SnapsToDevicePixels}\" />\n</Border>\n TemplateBinding"
},
{
"answer_id": 7078679,
"author": "SteffenSH",
"author_id": 833384,
"author_profile": "https://Stackoverflow.com/users/833384",
"pm_score": 2,
"selected": false,
"text": "<ListBox ItemsSource=\"{Binding Path=MyListProperty}\" />\n public IList<ListBoxItem> MyListProperty{ get; set;}\n <ListBox ItemsSource=\"{Binding Path=MyListProperty}\" VirtualizingStackPanel.IsVirtualizing=\"False\" />\n"
},
{
"answer_id": 8326034,
"author": "akjoshi",
"author_id": 45382,
"author_profile": "https://Stackoverflow.com/users/45382",
"pm_score": 1,
"selected": false,
"text": "#if DEBUG \n System.Diagnostics.PresentationTraceSources.DataBindingSource.Switch.Level =\n System.Diagnostics.SourceLevels.Critical;\n#endif\n"
},
{
"answer_id": 9286069,
"author": "Carter Medlin",
"author_id": 324479,
"author_profile": "https://Stackoverflow.com/users/324479",
"pm_score": 2,
"selected": false,
"text": "<Application.Resources>\n <Style TargetType=\"ListBoxItem\">\n <Setter Property=\"HorizontalContentAlignment\" Value=\"Left\" />\n <Setter Property=\"VerticalContentAlignment\" Value=\"Center\" />\n </Style>\n</Application.Resources>\n"
},
{
"answer_id": 9381431,
"author": "Alain",
"author_id": 529618,
"author_profile": "https://Stackoverflow.com/users/529618",
"pm_score": 0,
"selected": false,
"text": "<Style TargetType=\"ComboBox\">\n <Setter Property=\"ItemContainerStyle\">\n <Setter.Value> \n <Style TargetType=\"ComboBoxItem\">\n <Setter Property=\"HorizontalContentAlignment\" Value=\"Left\" />\n <Setter Property=\"VerticalContentAlignment\" Value=\"Center\" />\n </Style>\n </Setter.Value>\n </Setter>\n</Style>\n"
},
{
"answer_id": 23455790,
"author": "Chris",
"author_id": 991762,
"author_profile": "https://Stackoverflow.com/users/991762",
"pm_score": 3,
"selected": false,
"text": "Setter VirtualizingWrapPanel Setter <ListView>\n <ListView.Resources>\n <Style TargetType=\"ListViewItem\">\n <Setter Property=\"HorizontalContentAlignment\" Value=\"Left\" />\n <Setter Property=\"VerticalContentAlignment\" Value=\"Top\" />\n </Style>\n </ListView.Resources>\n <ListView.ItemContainerStyle>\n <Style TargetType=\"ListViewItem\">\n <Setter Property=\"HorizontalContentAlignment\" Value=\"Left\" />\n <Setter Property=\"VerticalContentAlignment\" Value=\"Top\" />\n </Style>\n </ListView.ItemContainerStyle>\n <ListView.ItemsPanel>\n <ItemsPanelTemplate>\n <controls:VirtualizingWrapPanel />\n </ItemsPanelTemplate>\n </ListView.ItemsPanel>\n </ListView>\n"
},
{
"answer_id": 24970497,
"author": "RedQueen87",
"author_id": 3625735,
"author_profile": "https://Stackoverflow.com/users/3625735",
"pm_score": 2,
"selected": false,
"text": "<ListBox.Resources>\n <Style x:Key=\"listBoxItemStyle\" TargetType=\"ListBoxItem\">\n <Setter Property=\"HorizontalContentAlignment\" Value=\"Center\" />\n <Setter Property=\"VerticalContentAlignment\" Value=\"Center\" />\n <Setter Property=\"MinWidth\" Value=\"24\"/>\n <Setter Property=\"IsEnabled\" Value=\"{Binding IsEnabled}\"/>\n </Style>\n\n <Style TargetType=\"ListBoxItem\" BasedOn=\"{StaticResource listBoxItemStyle}\"/>\n</ListBox.Resources>\n\n<ListBox.ItemContainerStyle>\n <Binding Source=\"{StaticResource listBoxItemStyle}\"/>\n</ListBox.ItemContainerStyle>\n\n<ListBox.ItemsPanel>\n <ItemsPanelTemplate>\n <WrapPanel Orientation=\"Horizontal\" IsItemsHost=\"True\" MaxWidth=\"170\"/>\n </ItemsPanelTemplate>\n</ListBox.ItemsPanel>\n ItemsPanelTemplate"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14537/"
] |
160,433
|
<p>One of your team members has been appointed "technical lead" or "team lead" yet he is technically incompetent and lacks major leadership skills.</p>
<p>By technically incompetent, I mean that the person doesn't know the difference between an abstract class and an interface, doesn't understand why coupling should be avoided, doesn't understand the concept of cohesion, provides solutions without taking some time to think, doesn't understand why we should favor composition over inheritance and doesn't get design patterns (except the singleton pattern).</p>
<p>Plus that person has over 10 years of "experience" (yes, I did put that word in quotes because he's given a whole different dimension of what experience really is).</p>
<p>I'm dealing with such a person at work. It's taking away the passion I have for this profession.</p>
<p>How do you react? What do you do?</p>
|
[
{
"answer_id": 593500,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 1,
"selected": false,
"text": "public byte[] ReadBytes(string filename)\n{\n FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);\n BinaryReader br = new BinaryReader(fs);\n FileInfo fi = new FileInfo(filename);\n byte[] buffer = new byte[fi.Length];\n\n for (int i = 0; i < buffer.Length; i++)\n {\n // optimize this\n buffer[i] = br.ReadByte();\n }\n\n return buffer;\n}\n File.ReadAllBytes"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24346/"
] |
160,453
|
<p>I have two tables: <code>foos</code> and <code>bars</code>, and there is a many-to-one relationship between them: each <code>foo</code> can have many <code>bars</code>. I also have a view <code>foobars</code>, which joins these two tables (its query is like <code>select foo.*, bar.id from foos, bars where bar.foo_id=foo.id</code>).</p>
<p>EDIT: You would not be wrong if you said that there's a many-to-many relationship between <code>foo</code>s and <code>bar</code>s. A <code>bar</code>, however, is just a tag (in fact, it is a size), and consists just of its name. The table <code>bars</code> has the same role as a link table would have.</p>
<p>I have a rule on inserting to <code>foobars</code> such that the “foo” part is inserted to <code>foos</code> as a new row, and “bar” part, which consists of a couple of bar-id's separated by commas is split, and for each such part a link between it and the appropriate <code>foo</code> is created (I use a procedure to do that).</p>
<p>This works great for inserts. I have a problem, however, when it comes to updating the whole thing. The <code>foo</code> part of the rule is easy. However, I don't know how to deal with the multiple <code>bar</code>s part. When I try to do something like <code>DELETE FROM bars WHERE foo_id=new.foo_id</code> in the rule, I end deleting everything from the table <code>bars</code>.</p>
<p>What am I doing wrong? Is there a way of achieving what I need? Finally, is my approach to the whole thing sensible?</p>
<p>(I do this overcomplicated thing with the view because the data I get is in the form of “<code>foo</code> and all its <code>bar</code>s”, but the user must see just <code>foobars</code>.)</p>
|
[
{
"answer_id": 160616,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 2,
"selected": false,
"text": "foos bars bars foos CREATE TABLE foos (\n id SERIAL PRIMARY KEY,\n ....\n);\nCREATE TABLE bars (\n id SERIAL PRIMARY KEY,\n foo_id INT REFERENCES bars (id) ON DELETE CASCADE,\n ...\n);\n CREATE TABLE foos (\n id SERIAL PRIMARY KEY,\n ....\n);\nCREATE TABLE bars (\n id SERIAL PRIMARY KEY,\n ...\n);\nCREATE TABLE foostobars (\n foo_id INT REFERENCES foos (id) ON DELETE CASCADE,\n bar_id INT REFERENCES bars (id) ON DELETE CASCADE\n);\n CREATE VIEW foobars AS\nSELECT\n foos.id AS foo_id, foos.something,\n bars.id AS bar_id, bars.somethingelse\nFROM foos\nINNER JOIN bars ON bars.foo_id = foo.id;\n CREATE VIEW foobars AS\nSELECT\n foos.id AS foo_id, foos.something,\n bars.id AS bar_id, bars.somethingelse\nFROM foos\nINNER JOIN foostobars AS ftb ON ftb.foo_id = foo.id\nINNER JOIN bars ON bars.id = ftb.bar_id;\n"
},
{
"answer_id": 164275,
"author": "Ryszard Szopa",
"author_id": 19922,
"author_profile": "https://Stackoverflow.com/users/19922",
"pm_score": 0,
"selected": false,
"text": "foo bars"
},
{
"answer_id": 169206,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 0,
"selected": false,
"text": "delete b\n from foo f\n join foobar fb\n on f.FooID = fb.FooID\n join bar b\n on b.BarId = fb.BarID\n where f.FooID = 123\n Create table Foo (\n FooID int\n ,[Other Foo attributes]\n)\n\nCreate table Bar (\n BarID int\n ,[Other Bar attributes]\n)\n\nCreate table FooBar (\n FooID int\n ,BarID int\n)\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19922/"
] |
160,467
|
<p>I need to create an ODBC link from an Access 2003 (Jet) database to a SQL Server hosted view which contains aliased field names containing periods such as:</p>
<pre><code>Seq.Group
</code></pre>
<p>In the SQL source behind the view, the field names are encased in square brackets...</p>
<pre><code>SELECT Table._Group AS [Seq.Group]
</code></pre>
<p>...so SQL Server doesn't complain about creating the view, but when I try to create an ODBC link to it from the Jet DB (either programmatically or via the Access 2003 UI) I receive the error message:</p>
<blockquote>
<p>'Seq.Group' is not a valid name. Make
sure that it does not include invalid
characters or punctuation and that it
is not too long.</p>
</blockquote>
<p>Unfortunately, I cannot modify the structure of the view because it's part of another product, so I am stuck with the field names the way that they are. I <em>could</em> add my own view with punctuation-free field names, but I'd really rather not modify the SQL Server at all because then that becomes another point of maintenance every time there's an upgrade, hotfix, etc. Does anyone know a better workaround?</p>
|
[
{
"answer_id": 161015,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 0,
"selected": false,
"text": "SELECT Table._Group AS [Seq_Group]\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3469/"
] |
160,494
|
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GenericCount
{
class Program
{
static int Count1<T>(T a) where T : IEnumerable<T>
{
return a.Count();
}
static void Main(string[] args)
{
List<string> mystring = new List<string>()
{
"rob","tx"
};
int count = Count1<List<string>>(mystring);******
Console.WriteLine(count.ToString());
}
}
}
</code></pre>
<p>What do I have to change in the above indicated line of code to make it work. I am just trying to pass either List or array in order to get the count. </p>
|
[
{
"answer_id": 160570,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 3,
"selected": true,
"text": "static int Count1<T>(IEnumerable<T> a)\n{\n return a.Count();\n}\n"
},
{
"answer_id": 160584,
"author": "Jon Cahill",
"author_id": 10830,
"author_profile": "https://Stackoverflow.com/users/10830",
"pm_score": 0,
"selected": false,
"text": "namespace GenericCount\n{\n class Program\n {\n static int Count1<T>(IEnumerable<T> a)\n {\n return a.Count();\n }\n\n static void Main(string[] args)\n {\n List<string> mystring = new List<string>()\n {\n \"rob\",\"tx\"\n };\n\n int count = Count1(mystring);\n Console.WriteLine(count.ToString());\n\n }\n }\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
160,497
|
<p>I'm using subversion (TortoiseSVN) and I want to remove the .svn folders from my project for deployment, is there an automated way of doing this using subversion or do I have to create a custom script for this?</p>
|
[
{
"answer_id": 160502,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 5,
"selected": false,
"text": "svn export <url-to-repo> <dest-path>\n"
},
{
"answer_id": 160503,
"author": "nobody",
"author_id": 19405,
"author_profile": "https://Stackoverflow.com/users/19405",
"pm_score": -1,
"selected": false,
"text": "svn export <url>"
},
{
"answer_id": 160505,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 6,
"selected": true,
"text": ".svn .svn"
},
{
"answer_id": 160654,
"author": "Sean Bright",
"author_id": 21926,
"author_profile": "https://Stackoverflow.com/users/21926",
"pm_score": 3,
"selected": false,
"text": "find /path/to/project/root -name '.svn' -type d -exec rm -rf '{}' \\;\n"
},
{
"answer_id": 160762,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "rsync -avz --exclude=\".svn\" /yourprojectwithsvninside/ /yourprojectwithoutsvninside/\n svn export http://yourserver/svn/yourproject/ ./yourproject/\n"
},
{
"answer_id": 4134705,
"author": "Guillermo Ruffino",
"author_id": 229052,
"author_profile": "https://Stackoverflow.com/users/229052",
"pm_score": 0,
"selected": false,
"text": ".svn .svn"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] |
160,514
|
<p>Are there are good uses of Partial Classes outside the webforms/winforms generated code scenarios? Or is this feature basically to support that?</p>
|
[
{
"answer_id": 160825,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "#region"
},
{
"answer_id": 228442,
"author": "David Boike",
"author_id": 10039,
"author_profile": "https://Stackoverflow.com/users/10039",
"pm_score": 2,
"selected": false,
"text": "// Main Part\npublic partial class Class1\n{\n private partial void LogSomethingDebugOnly();\n\n public void SomeMethod()\n {\n LogSomethingDebugOnly();\n // do the real work\n }\n}\n\n// Debug Part - probably in a different file\npublic partial class Class1\n{\n\n #if DEBUG\n\n private partial void LogSomethingDebugOnly()\n {\n // Do the logging or diagnostic work\n }\n\n #endif\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
160,519
|
<p>Can this be done w/ linqtosql?</p>
<pre><code>SELECT City, SUM(DATEDIFF(minute,StartDate,Completed)) AS Downtime
FROM Incidents
GROUP BY City
</code></pre>
|
[
{
"answer_id": 160825,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "#region"
},
{
"answer_id": 228442,
"author": "David Boike",
"author_id": 10039,
"author_profile": "https://Stackoverflow.com/users/10039",
"pm_score": 2,
"selected": false,
"text": "// Main Part\npublic partial class Class1\n{\n private partial void LogSomethingDebugOnly();\n\n public void SomeMethod()\n {\n LogSomethingDebugOnly();\n // do the real work\n }\n}\n\n// Debug Part - probably in a different file\npublic partial class Class1\n{\n\n #if DEBUG\n\n private partial void LogSomethingDebugOnly()\n {\n // Do the logging or diagnostic work\n }\n\n #endif\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3396/"
] |
160,532
|
<p>I want to export the contents of several tables from MSAccess2003.
The tables contain unicode Japanese characters.
I want to store them as tilde delimited text files.</p>
<p>I can do this manually using File/Export and, in the 'Advanced' dialog selecting tilde as Field Delimiter and the Unicode as the Code Page.</p>
<p>I can store this as an Export Specification, but this seems to be table specific.</p>
<p>I want to export many tables using VBA Code.</p>
<p>So far I have tried:</p>
<p>Sub ExportTables()</p>
<pre><code>Dim lTbl As Long
Dim dBase As Database
Dim TableName As String
Set dBase = CurrentDb
For lTbl = 0 To dBase.TableDefs.Count
'If the table name is a temporary or system table then ignore it
If Left(dBase.TableDefs(lTbl).Name, 1) = "~" Or _
Left(dBase.TableDefs(lTbl).Name, 4) = "MSYS" Then
'~ indicates a temporary table
'MSYS indicates a system level table
Else
TableName = dBase.TableDefs(lTbl).Name
DoCmd.TransferText acExportDelim, "UnicodeTilde", TableName, "c:\" + TableName + ".txt", True
End If
Next lTbl
Set dBase = Nothing
</code></pre>
<p>End Sub</p>
<p>When I run this I get an exception:</p>
<p>Run-time error '3011':
The Microsoft Jet database engine could not find the object "Allowance1#txt'. Make sure the object exists and that you spell its name and the path name correctly.</p>
<p>If I debug at this point, TableName is 'Allowance1', as expected.</p>
<p>I guess my UnicodeTilde export specification is table specific, so I can't use it for multiple tables.</p>
<p>What is the solution? Should I use something else, other than TransferText, or perhaps create the export specification programatically?</p>
<p>Any help appreciated.</p>
|
[
{
"answer_id": 161017,
"author": "Richard A",
"author_id": 24355,
"author_profile": "https://Stackoverflow.com/users/24355",
"pm_score": 0,
"selected": false,
"text": "ColNameHeader = True\nCharacterSet = Unicode\nFormat = Delimited(~)\n"
},
{
"answer_id": 172881,
"author": "Richard A",
"author_id": 24355,
"author_profile": "https://Stackoverflow.com/users/24355",
"pm_score": 3,
"selected": true,
"text": "[MyTable.txt]\nCharacterSet = Unicode\nFormat = Delimited(~)\nColNameHeader = True\nNumberDigits = 10\nCol1= \"Col1\" Char Width 10\nCol2= \"Col2\" Integer\nCol3= \"Col3\" Char Width 2\n SELECT * INTO [Text;DATABASE=c:\\export\\;FMT=Delimited(~)].[MyTable.txt] FROM [MyTable]\n [MyTable.txt]\nColNameHeader=True\nCharacterSet=1252\nFormat=CSVDelimited\nCol1=Col1 Char Width 10\nCol2=Col2 Integer\nCol3=Col3 Char Width 2\n Option Compare Database\nOption Explicit\n\n Public Function CreateSchemaFile(bIncFldNames As Boolean, _\n sPath As String, _\n sSectionName As String, _\n sTblQryName As String) As Boolean\n\n\n Dim Msg As String\n On Local Error GoTo CreateSchemaFile_Err\n Dim ws As Workspace, db As Database\n Dim tblDef As TableDef, fldDef As Field\n Dim i As Integer, Handle As Integer\n Dim fldName As String, fldDataInfo As String\n ' -----------------------------------------------\n ' Set DAO objects.\n ' -----------------------------------------------\n Set db = CurrentDb()\n ' -----------------------------------------------\n ' Open schema file for append.\n ' -----------------------------------------------\n Handle = FreeFile\n Open sPath & \"schema.ini\" For Output Access Write As #Handle\n ' -----------------------------------------------\n ' Write schema header.\n ' -----------------------------------------------\n Print #Handle, \"[\" & sSectionName & \"]\"\n Print #Handle, \"CharacterSet = Unicode\"\n Print #Handle, \"Format = Delimited(~)\"\n Print #Handle, \"ColNameHeader = \" & _\n IIf(bIncFldNames, \"True\", \"False\")\n Print #Handle, \"NumberDigits = 10\"\n ' -----------------------------------------------\n ' Get data concerning schema file.\n ' -----------------------------------------------\n Set tblDef = db.TableDefs(sTblQryName)\n With tblDef\n For i = 0 To .Fields.Count - 1\n Set fldDef = .Fields(i)\n With fldDef\n fldName = .Name\n Select Case .Type\n Case dbBoolean\n fldDataInfo = \"Bit\"\n Case dbByte\n fldDataInfo = \"Byte\"\n Case dbInteger\n fldDataInfo = \"Short\"\n Case dbLong\n fldDataInfo = \"Integer\"\n Case dbCurrency\n fldDataInfo = \"Currency\"\n Case dbSingle\n fldDataInfo = \"Single\"\n Case dbDouble\n fldDataInfo = \"Double\"\n Case dbDate\n fldDataInfo = \"Date\"\n Case dbText\n fldDataInfo = \"Char Width \" & Format$(.Size)\n Case dbLongBinary\n fldDataInfo = \"OLE\"\n Case dbMemo\n fldDataInfo = \"LongChar\"\n Case dbGUID\n fldDataInfo = \"Char Width 16\"\n End Select\n Print #Handle, \"Col\" & Format$(i + 1) _\n & \"= \"\"\" & fldName & \"\"\"\" & Space$(1); \"\" _\n & fldDataInfo\n End With\n Next i\n End With\n CreateSchemaFile = True\nCreateSchemaFile_End:\n Close Handle\n Exit Function\nCreateSchemaFile_Err:\n Msg = \"Error #: \" & Format$(Err.Number) & vbCrLf\n Msg = Msg & Err.Description\n MsgBox Msg\n Resume CreateSchemaFile_End\n End Function\n\nPublic Function ExportATable(TableName As String)\nDim ThePath As String\nDim FileName As String\nDim TheQuery As String\nDim Exporter As QueryDef\nThePath = \"c:\\export\\\"\nFileName = TableName + \".txt\"\nCreateSchemaFile True, ThePath, FileName, TableName\nOn Error GoTo IgnoreDeleteFileErrors\nFileSystem.Kill ThePath + FileName\nIgnoreDeleteFileErrors:\nTheQuery = \"SELECT * INTO [Text;DATABASE=\" + ThePath + \"].[\" + FileName + \"] FROM [\" + TableName + \"]\"\nSet Exporter = CurrentDb.CreateQueryDef(\"\", TheQuery)\nExporter.Execute\nEnd Function\n\n\nSub ExportTables()\n\n Dim lTbl As Long\n Dim dBase As Database\n Dim TableName As String\n\n Set dBase = CurrentDb\n\n For lTbl = 0 To dBase.TableDefs.Count - 1\n 'If the table name is a temporary or system table then ignore it\n If Left(dBase.TableDefs(lTbl).Name, 1) = \"~\" Or _\n Left(dBase.TableDefs(lTbl).Name, 4) = \"MSYS\" Then\n '~ indicates a temporary table\n 'MSYS indicates a system level table\n Else\n TableName = dBase.TableDefs(lTbl).Name\n ExportATable (TableName)\n End If\n Next lTbl\n Set dBase = Nothing\nEnd Sub\n"
},
{
"answer_id": 6111949,
"author": "Matt Donnan",
"author_id": 767913,
"author_profile": "https://Stackoverflow.com/users/767913",
"pm_score": 1,
"selected": false,
"text": "| SELECT * FROM MSysIMEXColumns"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24355/"
] |
160,534
|
<p>I need to get the "td" element of a table. I do not have the ability to add a mouseover or onclick event to the "td" element, so I need to add them with JQUERY.</p>
<p>I need JQUERY to add the mouseover and onclick event to the all "td" elements in the table.</p>
<p>Thats what I need, maybe someone can help me out? </p>
|
[
{
"answer_id": 160547,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 6,
"selected": true,
"text": "$(function() {\n $(\"table#mytable td\").mouseover(function() {\n //The onmouseover code\n }).click(function() {\n //The onclick code\n });\n});\n"
},
{
"answer_id": 160556,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 1,
"selected": false,
"text": "$(\"td\").hover(function(){\n $(this).css(\"background\",\"#0000ff\");\n},\nfunction(){\n $(this).css(\"background\",\"#ffffff\");\n});\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7644/"
] |
160,550
|
<p>I thought people would be working on little code projects together, but I don't see them, so here's an easy one:</p>
<p>Code that validates a valid US Zip Code. I know there are ZIP code databases out there, but there are still uses, like web pages, quick validation, and also the fact that zip codes keep getting issued, so you might want to use weak validation.</p>
<p>I wrote a little bit about zip codes in a side project on my wiki/blog:</p>
<p><a href="https://benc.fogbugz.com/default.asp?W24" rel="nofollow noreferrer">https://benc.fogbugz.com/default.asp?W24</a></p>
<p>There is also a new, weird type of zip code. </p>
<p><a href="https://benc.fogbugz.com/default.asp?W42" rel="nofollow noreferrer">https://benc.fogbugz.com/default.asp?W42</a></p>
<p>I can do the javascript code, but it would be interesting to see how many languages we can get here.</p>
|
[
{
"answer_id": 160583,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 7,
"selected": true,
"text": "/(^\\d{5}$)|(^\\d{5}-\\d{4}$)/ var isValidZip = /(^\\d{5}$)|(^\\d{5}-\\d{4}$)/.test(\"90210\");\n"
},
{
"answer_id": 160880,
"author": "Mike Henry",
"author_id": 14934,
"author_profile": "https://Stackoverflow.com/users/14934",
"pm_score": 3,
"selected": false,
"text": "function isValidPostalCode(postalCode, countryCode) {\n switch (countryCode) {\n case \"US\":\n postalCodeRegex = /^([0-9]{5})(?:[-\\s]*([0-9]{4}))?$/;\n break;\n case \"CA\":\n postalCodeRegex = /^([A-Z][0-9][A-Z])\\s*([0-9][A-Z][0-9])$/;\n break;\n default:\n postalCodeRegex = /^(?:[A-Z0-9]+([- ]?[A-Z0-9]+)*)?$/;\n }\n return postalCodeRegex.test(postalCode);\n}\n"
},
{
"answer_id": 546304,
"author": "Andrey Fedorov",
"author_id": 10728,
"author_profile": "https://Stackoverflow.com/users/10728",
"pm_score": 5,
"selected": false,
"text": "function isValidUSZip(sZip) {\n return /^\\d{5}(-\\d{4})?$/.test(sZip);\n}\n"
},
{
"answer_id": 7446316,
"author": "Samer",
"author_id": 439392,
"author_profile": "https://Stackoverflow.com/users/439392",
"pm_score": 3,
"selected": false,
"text": "new RegExp(/^[abceghjklmnprstvxy][0-9][abceghjklmnprstvwxyz]\\s?[0-9][abceghjklmnprstvwxyz][0-9]$/i)"
},
{
"answer_id": 7948939,
"author": "TorchLakeDave",
"author_id": 1021237,
"author_profile": "https://Stackoverflow.com/users/1021237",
"pm_score": 1,
"selected": false,
"text": "/\\b\\d{5}-\\d{4}\\b/\n"
},
{
"answer_id": 14956096,
"author": "Irfan",
"author_id": 902161,
"author_profile": "https://Stackoverflow.com/users/902161",
"pm_score": 0,
"selected": false,
"text": "function isValidCAPostal(pcVal) {\n return ^[A-Za-z][0-9][A-Za-z]\\s{0,1}[0-9][A-Za-z][0-9]$/.test(pcVal);\n}\n"
},
{
"answer_id": 14987926,
"author": "Shogo Yahagi",
"author_id": 2092674,
"author_profile": "https://Stackoverflow.com/users/2092674",
"pm_score": 2,
"selected": false,
"text": "additional-methods.js jQuery.validator.addMethod(\"zipUS\", function(value, element) {\n return /(^\\d{5}$)|(^\\d{5}-\\d{4}$)/.test(value);\n}, \"Please specify a valid US zip code.\");\n .addMethod() function checkZip(value) {\n return (/(^\\d{5}$)|(^\\d{5}-\\d{4}$)/).test(value);\n};\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2910/"
] |
160,555
|
<p>Here's the situation:
I'm developing a simple application with the following structure:</p>
<ul>
<li>FormMain (startup point)</li>
<li>FormNotification</li>
<li>CompleFunctions</li>
</ul>
<p>Right?</p>
<p>Well, in <strong>FormMain</strong> I have the following function:</p>
<pre><code>private void DoItInNewThread(ParameterizedThreadStart pParameterizedThreadStart, object pParameters, ThreadPriority pThreadPriority)
{
Thread oThread = new Thread(pParameterizedThreadStart);
oThread.CurrentUICulture = Settings.Instance.Language;
oThread.IsBackground = true;
oThread.Priority = pThreadPriority;
oThread.Name = "μRemote: Background operation";
oThread.Start(pParameters);
}
</code></pre>
<p>So, everytime that I need to call a time consuming method located on <strong>ComplexFunctions</strong> I do the following:</p>
<pre><code>// This is FormMain.cs
string strSomeParameter = "lala";
DoItInNewThread(new ParameterizedThreadStart(ComplexFunctions.DoSomething), strSomeParameter, ThreadPriority.Normal);
</code></pre>
<p>The other class, FormNotification, its a Form that display some information of the process to the user.
This FormNotification could be called from FormMain or ComplexFunctions.
Example:</p>
<pre><code>// This is ComplexFunctions.cs
public void DoSomething(string pSomeParameter)
{
// Imagine some time consuming task
FormNotification formNotif = new FormNotification();
formNotif.Notify();
}
</code></pre>
<p>FormNotify has a timer, so, after 10 seconds closes the form. I'm not using formNotif.ShowDialog because I don't want to give focus to this Form.
You could check <a href="https://stackoverflow.com/questions/156046/show-a-form-without-stealing-focus-in-c">this link</a> to see what I'm doing in Notify.</p>
<p>Ok, here's the problem:
When I call <strong>FormNotify</strong> from <strong>ComplexFunction</strong> which is called from another Thread in <strong>FormMain</strong> ... this <strong>FormNotify</strong> disappears after a few milliseconds.
It's the same effect that when you do something like this:</p>
<pre><code>using(FormSomething formSomething = new FormSomething)
{
formSomething.Show();
}
</code></pre>
<p><strong>How can avoid this?</strong></p>
<p>These are possible solutions that I don't want to use:</p>
<ul>
<li>Using Thread.Sleep(10000) in FormNotify</li>
<li>Using FormNotif.ShowDialog()</li>
</ul>
<p>This is a simplified scenario (FormNotify does some other fancy stuff that just stay for 10 seconds, but they are irrelevant to see the problem).</p>
<p>Thanks for your time!!!
And please, sorry my english.</p>
|
[
{
"answer_id": 3712806,
"author": "Andranik",
"author_id": 447778,
"author_profile": "https://Stackoverflow.com/users/447778",
"pm_score": 0,
"selected": false,
"text": "Form1 private void button1_Click(object sender, EventArgs e)\n{\n Thread t = new Thread(new ThreadStart(this.ShowForm1));\n t.Start();\n}\n InvokeRequired ShowForm1 InvokeRequired delegate void Func();\nprivate void ShowForm1()\n{ \n if (this.InvokeRequired)\n {\n Func f = new Func(ShowForm1);\n this.Invoke(f);\n }\n else\n {\n Form1 form1 = new Form1();\n form1.Show();\n } \n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386/"
] |
160,557
|
<p>I have a Selenium test case that enters dates into a date selector made up of three pulldowns (year, month, and day). </p>
<pre><code>select validity_Y label=2008
select validity_M label=08
select validity_D label=08
</code></pre>
<p>This part gets repeated a lot throughout the test case. I'd like to reduce it by defining my custom action "selectValidity", so that I can have less redundancy, something like</p>
<pre><code>selectValidity 2008,08,08
</code></pre>
<p>What is the best (easiest, cleanest) way to add macros or subroutines to a test case?</p>
|
[
{
"answer_id": 3712806,
"author": "Andranik",
"author_id": 447778,
"author_profile": "https://Stackoverflow.com/users/447778",
"pm_score": 0,
"selected": false,
"text": "Form1 private void button1_Click(object sender, EventArgs e)\n{\n Thread t = new Thread(new ThreadStart(this.ShowForm1));\n t.Start();\n}\n InvokeRequired ShowForm1 InvokeRequired delegate void Func();\nprivate void ShowForm1()\n{ \n if (this.InvokeRequired)\n {\n Func f = new Func(ShowForm1);\n this.Invoke(f);\n }\n else\n {\n Form1 form1 = new Form1();\n form1.Show();\n } \n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14955/"
] |
160,587
|
<p>I'm using <code>Console.WriteLine()</code> from a very simple WPF test application, but when I execute the application from the command line, I'm seeing nothing being written to the console. Does anyone know what might be going on here?</p>
<p>I can reproduce it by creating a WPF application in VS 2008, and simply adding <code>Console.WriteLine("text")</code> anywhere where it gets executed. Any ideas?</p>
<p>All I need for right now is something as simple as <code>Console.WriteLine()</code>. I realize I could use log4net or somet other logging solution, but I really don't need that much functionality for this application.</p>
<p><strong>Edit:</strong> I should have remembered that <code>Console.WriteLine()</code> is for console applications. Oh well, no stupid questions, right? :-)
I'll just use <code>System.Diagnostics.Trace.WriteLine()</code> and DebugView for now.</p>
|
[
{
"answer_id": 160606,
"author": "Phobis",
"author_id": 19854,
"author_profile": "https://Stackoverflow.com/users/19854",
"pm_score": 8,
"selected": false,
"text": "Trace.WriteLine(\"text\");\n using System.Diagnostics;\n"
},
{
"answer_id": 718505,
"author": "John Leidegren",
"author_id": 58961,
"author_profile": "https://Stackoverflow.com/users/58961",
"pm_score": 8,
"selected": true,
"text": "ConsoleManager.Show() Console.Write [SuppressUnmanagedCodeSecurity]\npublic static class ConsoleManager\n{\n private const string Kernel32_DllName = \"kernel32.dll\";\n\n [DllImport(Kernel32_DllName)]\n private static extern bool AllocConsole();\n\n [DllImport(Kernel32_DllName)]\n private static extern bool FreeConsole();\n\n [DllImport(Kernel32_DllName)]\n private static extern IntPtr GetConsoleWindow();\n\n [DllImport(Kernel32_DllName)]\n private static extern int GetConsoleOutputCP();\n\n public static bool HasConsole\n {\n get { return GetConsoleWindow() != IntPtr.Zero; }\n }\n\n /// <summary>\n /// Creates a new console instance if the process is not attached to a console already.\n /// </summary>\n public static void Show()\n {\n //#if DEBUG\n if (!HasConsole)\n {\n AllocConsole();\n InvalidateOutAndError();\n }\n //#endif\n }\n\n /// <summary>\n /// If the process has a console attached to it, it will be detached and no longer visible. Writing to the System.Console is still possible, but no output will be shown.\n /// </summary>\n public static void Hide()\n {\n //#if DEBUG\n if (HasConsole)\n {\n SetOutAndErrorNull();\n FreeConsole();\n }\n //#endif\n }\n\n public static void Toggle()\n {\n if (HasConsole)\n {\n Hide();\n }\n else\n {\n Show();\n }\n }\n\n static void InvalidateOutAndError()\n {\n Type type = typeof(System.Console);\n\n System.Reflection.FieldInfo _out = type.GetField(\"_out\",\n System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);\n\n System.Reflection.FieldInfo _error = type.GetField(\"_error\",\n System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);\n\n System.Reflection.MethodInfo _InitializeStdOutError = type.GetMethod(\"InitializeStdOutError\",\n System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);\n\n Debug.Assert(_out != null);\n Debug.Assert(_error != null);\n\n Debug.Assert(_InitializeStdOutError != null);\n\n _out.SetValue(null, null);\n _error.SetValue(null, null);\n\n _InitializeStdOutError.Invoke(null, new object[] { true });\n }\n\n static void SetOutAndErrorNull()\n {\n Console.SetOut(TextWriter.Null);\n Console.SetError(TextWriter.Null);\n }\n} \n"
},
{
"answer_id": 23957803,
"author": "Ilya Serbis",
"author_id": 355438,
"author_profile": "https://Stackoverflow.com/users/355438",
"pm_score": 4,
"selected": false,
"text": "C:\\src\\bin\\Debug\\Example.exe > output.txt\n output.txt"
},
{
"answer_id": 41732584,
"author": "Smitty",
"author_id": 5842023,
"author_profile": "https://Stackoverflow.com/users/5842023",
"pm_score": 5,
"selected": false,
"text": "using System.Diagnostics;\n Debug.WriteLine(\"something\");\n"
},
{
"answer_id": 51701886,
"author": "Emelias Alvarez",
"author_id": 8303606,
"author_profile": "https://Stackoverflow.com/users/8303606",
"pm_score": 2,
"selected": false,
"text": "ConsoleView.Show(\"Title of the Console\");\n System.Console.WriteLine(\"The debug message\");\n ConsoleView.Close();\n ConsoleView.Release();\n <Window x:Class=\"CustomControls.FrmConsole\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\"\n xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n xmlns:local=\"clr-namespace:CustomControls\"\n mc:Ignorable=\"d\"\n Height=\"500\" Width=\"600\" WindowStyle=\"None\" ResizeMode=\"NoResize\" WindowStartupLocation=\"CenterScreen\" Topmost=\"True\" Icon=\"Images/icoConsole.png\">\n<Grid>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"40\"/>\n <RowDefinition Height=\"*\"/>\n <RowDefinition Height=\"40\"/>\n </Grid.RowDefinitions>\n <Label Grid.Row=\"0\" Name=\"lblTitulo\" HorizontalAlignment=\"Center\" HorizontalContentAlignment=\"Center\" VerticalAlignment=\"Center\" VerticalContentAlignment=\"Center\" FontFamily=\"Arial\" FontSize=\"14\" FontWeight=\"Bold\" Content=\"Titulo\"/>\n <Grid Grid.Row=\"1\">\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"10\"/>\n <ColumnDefinition Width=\"*\"/>\n <ColumnDefinition Width=\"10\"/>\n </Grid.ColumnDefinitions>\n <TextBox Grid.Column=\"1\" Name=\"txtInner\" FontFamily=\"Arial\" FontSize=\"10\" ScrollViewer.CanContentScroll=\"True\" VerticalScrollBarVisibility=\"Visible\" HorizontalScrollBarVisibility=\"Visible\" TextWrapping=\"Wrap\"/>\n </Grid>\n <Button Name=\"btnCerrar\" Grid.Row=\"2\" Content=\"Cerrar\" Width=\"100\" Height=\"30\" HorizontalAlignment=\"Center\" HorizontalContentAlignment=\"Center\" VerticalAlignment=\"Center\" VerticalContentAlignment=\"Center\"/>\n</Grid>\n partial class FrmConsole : Window\n{\n private class ControlWriter : TextWriter\n {\n private TextBox textbox;\n public ControlWriter(TextBox textbox)\n {\n this.textbox = textbox;\n }\n\n public override void WriteLine(char value)\n {\n textbox.Dispatcher.Invoke(new Action(() =>\n {\n textbox.AppendText(value.ToString());\n textbox.AppendText(Environment.NewLine);\n textbox.ScrollToEnd();\n }));\n }\n\n public override void WriteLine(string value)\n {\n textbox.Dispatcher.Invoke(new Action(() =>\n {\n textbox.AppendText(value);\n textbox.AppendText(Environment.NewLine);\n textbox.ScrollToEnd();\n }));\n }\n\n public override void Write(char value)\n {\n textbox.Dispatcher.Invoke(new Action(() =>\n {\n textbox.AppendText(value.ToString());\n textbox.ScrollToEnd();\n }));\n }\n\n public override void Write(string value)\n {\n textbox.Dispatcher.Invoke(new Action(() =>\n {\n textbox.AppendText(value);\n textbox.ScrollToEnd();\n }));\n }\n\n public override Encoding Encoding\n {\n get { return Encoding.UTF8; }\n\n }\n }\n\n //DEFINICIONES DE LA CLASE\n #region DEFINICIONES DE LA CLASE\n\n #endregion\n\n\n //CONSTRUCTORES DE LA CLASE\n #region CONSTRUCTORES DE LA CLASE\n\n public FrmConsole(string titulo)\n {\n InitializeComponent();\n lblTitulo.Content = titulo;\n Clear();\n btnCerrar.Click += new RoutedEventHandler(BtnCerrar_Click);\n Console.SetOut(new ControlWriter(txtInner));\n DesactivarCerrar();\n }\n\n #endregion\n\n\n //PROPIEDADES\n #region PROPIEDADES\n\n #endregion\n\n\n //DELEGADOS\n #region DELEGADOS\n\n private void BtnCerrar_Click(object sender, RoutedEventArgs e)\n {\n Close();\n }\n\n #endregion\n\n\n //METODOS Y FUNCIONES\n #region METODOS Y FUNCIONES\n\n public void ActivarCerrar()\n {\n btnCerrar.IsEnabled = true;\n }\n\n public void Clear()\n {\n txtInner.Clear();\n }\n\n public void DesactivarCerrar()\n {\n btnCerrar.IsEnabled = false;\n }\n\n #endregion \n}\n static public class ConsoleView\n{\n //DEFINICIONES DE LA CLASE\n #region DEFINICIONES DE LA CLASE\n static FrmConsole console;\n static Thread StatusThread;\n static bool isActive = false;\n #endregion\n\n //CONSTRUCTORES DE LA CLASE\n #region CONSTRUCTORES DE LA CLASE\n\n #endregion\n\n //PROPIEDADES\n #region PROPIEDADES\n\n #endregion\n\n //DELEGADOS\n #region DELEGADOS\n\n #endregion\n\n //METODOS Y FUNCIONES\n #region METODOS Y FUNCIONES\n\n public static void Show(string label)\n {\n if (isActive)\n {\n return;\n }\n\n isActive = true;\n //create the thread with its ThreadStart method\n StatusThread = new Thread(() =>\n {\n try\n {\n console = new FrmConsole(label);\n console.ShowDialog();\n //this call is needed so the thread remains open until the dispatcher is closed\n Dispatcher.Run();\n }\n catch (Exception)\n {\n }\n });\n\n //run the thread in STA mode to make it work correctly\n StatusThread.SetApartmentState(ApartmentState.STA);\n StatusThread.Priority = ThreadPriority.Normal;\n StatusThread.Start();\n\n }\n\n public static void Close()\n {\n isActive = false;\n if (console != null)\n {\n //need to use the dispatcher to call the Close method, because the window is created in another thread, and this method is called by the main thread\n console.Dispatcher.InvokeShutdown();\n console = null;\n StatusThread = null;\n }\n\n console = null;\n }\n\n public static void Release()\n {\n isActive = false;\n if (console != null)\n {\n console.Dispatcher.Invoke(console.ActivarCerrar);\n }\n\n }\n #endregion\n}\n"
},
{
"answer_id": 73971822,
"author": "Bip901",
"author_id": 7812339,
"author_profile": "https://Stackoverflow.com/users/7812339",
"pm_score": 0,
"selected": false,
"text": "AttachConsole [DllImport(\"kernel32.dll\")]\nstatic extern bool AttachConsole(uint dwProcessId);\n\nconst uint ATTACH_PARENT_PROCESS = 0x0ffffffff;\n AttachConsole(ATTACH_PARENT_PROCESS);\nConsole.WriteLine(\"Hello world!\");\nConsole.WriteLine(\"Writing to the hosting console!\");\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18505/"
] |
160,604
|
<p>I'm trying to combine a list of functions like so.</p>
<p>I have this:</p>
<pre><code>Func<int, bool>[] criteria = new Func<int, bool>[3];
criteria[0] = i => i % 2 == 0;
criteria[1] = i => i % 3 == 0;
criteria[2] = i => i % 5 == 0;
</code></pre>
<p>And I want this:</p>
<pre><code>Func<int, bool>[] predicates = new Func<int, bool>[3];
predicates[0] = i => i % 2 == 0;
predicates[1] = i => i % 2 == 0 && i % 3 == 0;
predicates[2] = i => i % 2 == 0 && i % 3 == 0 && i % 5 == 0;
</code></pre>
<p>So far I've got the following code:</p>
<pre><code>Expression<Func<int, bool>>[] results = new Expression<Func<int, bool>>[criteria.Length];
for (int i = 0; i < criteria.Length; i++)
{
results[i] = f => true;
for (int j = 0; j <= i; j++)
{
Expression<Func<int, bool>> expr = b => criteria[j](b);
var invokedExpr = Expression.Invoke(
expr,
results[i].Parameters.Cast<Expression>());
results[i] = Expression.Lambda<Func<int, bool>>(
Expression.And(results[i].Body, invokedExpr),
results[i].Parameters);
}
}
var predicates = results.Select(e => e.Compile()).ToArray();
Console.WriteLine(predicates[0](6)); // Returns true
Console.WriteLine(predicates[1](6)); // Returns false
Console.WriteLine(predicates[2](6)); // Throws an IndexOutOfRangeException
</code></pre>
<p>Does anyone know what I'm doing wrong?</p>
|
[
{
"answer_id": 160661,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 3,
"selected": true,
"text": "Func<int, bool>[] criteria = new Func<int, bool>[3]; \ncriteria[0] = i => i % 2 == 0; \ncriteria[1] = i => i % 3 == 0; \ncriteria[2] = i => i % 5 == 0;\nExpression<Func<int, bool>>[] results = new Expression<Func<int, bool>>[criteria.Length];\nfor (int i = 0; i < criteria.Length; i++)\n{\n results[i] = f => true; \n for (int j = 0; j <= i; j++)\n {\n int ii = i;\n int jj = j;\n Expression<Func<int, bool>> expr = b => criteria[jj](b); \n var invokedExpr = Expression.Invoke(expr, results[ii].Parameters.Cast<Expression>()); \n results[ii] = Expression.Lambda<Func<int, bool>>(Expression.And(results[ii].Body, invokedExpr), results[ii].Parameters);\n }\n} \nvar predicates = results.Select(e => e.Compile()).ToArray(); \n"
},
{
"answer_id": 161932,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": false,
"text": " Func<int, bool>[] criteria = new Func<int, bool>[3];\n criteria[0] = i => i % 2 == 0;\n criteria[1] = i => i % 3 == 0;\n criteria[2] = i => i % 5 == 0;\n\n Func<int, bool>[] predicates = new Func<int, bool>[3];\n\n predicates[0] = criteria[0];\n for (int i = 1; i < criteria.Length; i++)\n {\n //need j to be an unchanging int, one for each loop execution.\n int j = i;\n\n predicates[j] = x => predicates[j - 1](x) && criteria[j](x);\n }\n\n Console.WriteLine(predicates[0](6)); //True\n Console.WriteLine(predicates[1](6)); //True\n Console.WriteLine(predicates[2](6)); //False\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3820/"
] |
160,608
|
<p>I've been wondering whether there is a good "git export" solution that creates a copy of a tree without the <code>.git</code> repository directory. There are at least three methods I know of:</p>
<ol>
<li><code>git clone</code> followed by removing the <code>.git</code> repository directory.</li>
<li><a href="http://www.kernel.org/pub/software/scm/git/docs/git-checkout-index.html" rel="noreferrer"><code>git checkout-index</code></a> alludes to this functionality but starts with "Just read the desired tree into the index..." which I'm not entirely sure how to do.</li>
<li><a href="http://code.google.com/p/git-export/" rel="noreferrer"><code>git-export</code></a> is a third-party script that essentially does a <code>git clone</code> into a temporary location followed by <code>rsync --exclude='.git'</code> into the final destination.</li>
</ol>
<p>None of these solutions really strike me as being satisfactory. The closest one to <code>svn export</code> might be option 1, because both require the target directory to be empty first. But option 2 seems even better, assuming I can figure out what it means to read a tree into the index.</p>
|
[
{
"answer_id": 160620,
"author": "jperras",
"author_id": 5570,
"author_profile": "https://Stackoverflow.com/users/5570",
"pm_score": 5,
"selected": false,
"text": "$ git checkout-index --prefix=git-export-dir/ -a"
},
{
"answer_id": 160719,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 8,
"selected": false,
"text": "git checkout-index -a -f --prefix=/destination/path/\n -a -f"
},
{
"answer_id": 163769,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 12,
"selected": true,
"text": "git archive git archive master | tar -x -C /somewhere/else\n git archive master | bzip2 >source-tree.tar.bz2\n git archive --format zip --output /full/path/to/zipfile.zip master \n git help archive git checkout-index -a -f --prefix=/destination/path/\n"
},
{
"answer_id": 209489,
"author": "Daniel Schierbeck",
"author_id": 20321,
"author_profile": "https://Stackoverflow.com/users/20321",
"pm_score": 5,
"selected": false,
"text": "git-checkout-index git export ~/the/destination/dir\n -f --force PATH git-export"
},
{
"answer_id": 353830,
"author": "Alexander Somov",
"author_id": 44710,
"author_profile": "https://Stackoverflow.com/users/44710",
"pm_score": 8,
"selected": false,
"text": "git archive git archive --format=tar \\\n--remote=ssh://remote_server/remote_repository master | tar -xf -\n git archive --format=tar \\\n--remote=ssh://remote_server/remote_repository master path1/ path2/ | tar -xv\n"
},
{
"answer_id": 1142416,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 2,
"selected": false,
"text": "#!/bin/sh\n[ $# -eq 2 ] || echo \"USAGE $0 REPOSITORY DESTINATION\" && exit 1\nREPOSITORY=$1\nDESTINATION=$2\nTMPNAME=\"/tmp/$(basename $REPOSITORY).$$\"\ngit clone $REPOSITORY $TMPNAME\nrm -rf $TMPNAME/.git\nmkdir -p $DESTINATION\ncp -r $TMPNAME/* $DESTINATION\nrm -rf $TMPNAME\n"
},
{
"answer_id": 2478811,
"author": "RkG",
"author_id": 297518,
"author_profile": "https://Stackoverflow.com/users/297518",
"pm_score": 2,
"selected": false,
"text": "gitss() {\n URL=[url:path]\n\n TMPFILE=\"`/bin/tempfile`\"\n if [ \"$1\" = \"\" ]; then\n echo -e \"Use: gitss repo [tree/commit]\\n\"\n return\n fi\n if [ \"$2\" = \"\" ]; then\n TREEISH=\"HEAD\"\n else\n TREEISH=\"$2\"\n fi\n echo \"Getting $1/$TREEISH...\"\n git archive --format=zip --remote=$URL/$1 $TREEISH > $TMPFILE && unzip $TMPFILE && echo -e \"\\nDone\\n\"\n rm $TMPFILE\n}\n ss = !env GIT_TMPFILE=\"`/bin/tempfile`\" sh -c 'git archive --format=zip --remote=[url:path]/$1 $2 \\ > $GIT_TMPFILE && unzip $GIT_TMPFILE && rm $GIT_TMPFILE' -\n"
},
{
"answer_id": 4052484,
"author": "dkinzer",
"author_id": 256854,
"author_profile": "https://Stackoverflow.com/users/256854",
"pm_score": 3,
"selected": false,
"text": "cp foo [destination] git-archive master foo | -x -C [destination]"
},
{
"answer_id": 7397656,
"author": "slatvick",
"author_id": 72766,
"author_profile": "https://Stackoverflow.com/users/72766",
"pm_score": 5,
"selected": false,
"text": "rsync -a ./FROM/ ./TO --exclude='.*'\n"
},
{
"answer_id": 7971071,
"author": "tocororo",
"author_id": 998663,
"author_profile": "https://Stackoverflow.com/users/998663",
"pm_score": 3,
"selected": false,
"text": "function create_empty () {\n## Processing path (target-dir):\n TRG_PATH=\"${1}\";\n## Component(s):\n EXCLUDE_DIR=\".git\";\necho -en \"\\nAdding '${EMPTY_FILE}' files to empty folder(s): ...\";\n find ${TRG_PATH} -not -path \"*/${EXCLUDE_DIR}/*\" -type d -empty -exec touch {}/${EMPTY_FILE} \\;\n#echo \"done.\";\n## Purging SRC/TRG_DIRs variable(s):\n unset TRG_PATH EMPTY_FILE EXCLUDE_DIR;\n return 0;\n }\n\ndeclare -a GIT_EXCLUDE;\nfunction load_exclude () {\n SRC_PATH=\"${1}\";\n ITEMS=0; while read LINE; do\n# echo -e \"Line [${ITEMS}]: '${LINE%%\\ *}'\";\n GIT_EXCLUDE[((ITEMS++))]=${LINE%%\\ *};\n done < ${SRC_PATH}/.gitattributes;\n GIT_EXCLUDE[${ITEMS}]=\"${EMPTY_FILE}\";\n## Purging variable(s):\n unset SRC_PATH ITEMS;\n return 0;\n }\n\nfunction purge_empty () {\n## Processing path (Source/Target-dir):\n SRC_PATH=\"${1}\";\n TRG_PATH=\"${2}\";\necho -e \"\\nPurging Git-Specific component(s): ... \";\n find ${SRC_PATH} -type f -name ${EMPTY_FILE} -exec /bin/rm '{}' \\;\n for xRULE in ${GIT_EXCLUDE[@]}; do\necho -en \" '${TRG_PATH}/{${xRULE}}' files ... \";\n find ${TRG_PATH} -type f -name \"${xRULE}\" -exec /bin/rm -rf '{}' \\;\necho \"done.'\";\n done;\necho -e \"done.\\n\"\n## Purging SRC/TRG_PATHs variable(s):\n unset SRC_PATH; unset TRG_PATH;\n return 0;\n }\n\nfunction git-export () {\n TRG_DIR=\"${1}\"; SRC_DIR=\"${2}\";\n if [ -z \"${SRC_DIR}\" ]; then SRC_DIR=\"${PWD}\"; fi\n load_exclude \"${SRC_DIR}\";\n## Dynamically added '.empty' files to the Git-Structure:\n create_empty \"${SRC_DIR}\";\n GIT_COMMIT=\"Including '${EMPTY_FILE}' files into Git-Index container.\"; #echo -e \"\\n${GIT_COMMIT}\";\n git add .; git commit --quiet --all --verbose --message \"${GIT_COMMIT}\";\n if [ \"${?}\" -eq 0 ]; then echo \" done.\"; fi\n /bin/rm -rf ${TRG_DIR} && mkdir -p \"${TRG_DIR}\";\necho -en \"\\nChecking-Out Index component(s): ... \";\n git checkout-index --prefix=${TRG_DIR}/ -q -f -a\n## Reset: --mixed = reset HEAD and index:\n if [ \"${?}\" -eq 0 ]; then\necho \"done.\"; echo -en \"Resetting HEAD and Index: ... \";\n git reset --soft HEAD^;\n if [ \"${?}\" -eq 0 ]; then\necho \"done.\";\n## Purging Git-specific components and '.empty' files from Target-Dir:\n purge_empty \"${SRC_DIR}\" \"${TRG_DIR}\"\n else echo \"failed.\";\n fi\n## Archiving exported-content:\necho -en \"Archiving Checked-Out component(s): ... \";\n if [ -f \"${TRG_DIR}.tgz\" ]; then /bin/rm ${TRG_DIR}.tgz; fi\n cd ${TRG_DIR} && tar -czf ${TRG_DIR}.tgz ./; cd ${SRC_DIR}\necho \"done.\";\n## Listing *.tgz file attributes:\n## Warning: Un-TAR this file to a specific directory:\n ls -al ${TRG_DIR}.tgz\n else echo \"failed.\";\n fi\n## Purgin all references to Un-Staged File(s):\n git reset HEAD;\n## Purging SRC/TRG_DIRs variable(s):\n unset SRC_DIR; unset TRG_DIR;\n echo \"\";\n return 0;\n }\n function git-archive () {\n PREFIX=\"${1}\"; ## sudo mkdir -p ${PREFIX}\n REPO_PATH=\"`echo \"${2}\"|awk -F: '{print $1}'`\";\n RELEASE=\"`echo \"${2}\"|awk -F: '{print $2}'`\";\n USER_PATH=\"${PWD}\";\necho \"$PREFIX $REPO_PATH $RELEASE $USER_PATH\";\n## Dynamically added '.empty' files to the Git-Structure:\n cd \"${REPO_PATH}\"; populate_empty .; echo -en \"\\n\";\n# git archive --prefix=git-1.4.0/ -o git-1.4.0.tar.gz v1.4.0\n# e.g.: git-archive /var/www/htdocs /repos/domain.name/website:rel-1.0.0 --explode\n OUTPUT_FILE=\"${USER_PATH}/${RELEASE}.tar.gz\";\n git archive --verbose --prefix=${PREFIX}/ -o ${OUTPUT_FILE} ${RELEASE}\n cd \"${USER_PATH}\";\n if [[ \"${3}\" =~ [--explode] ]]; then\n if [ -d \"./${RELEASE}\" ]; then /bin/rm -rf \"./${RELEASE}\"; fi\n mkdir -p ./${RELEASE}; tar -xzf \"${OUTPUT_FILE}\" -C ./${RELEASE}\n fi\n## Purging SRC/TRG_DIRs variable(s):\n unset PREFIX REPO_PATH RELEASE USER_PATH OUTPUT_FILE;\n return 0;\n }\n"
},
{
"answer_id": 8963061,
"author": "Lars Schillingmann",
"author_id": 1163648,
"author_profile": "https://Stackoverflow.com/users/1163648",
"pm_score": 5,
"selected": false,
"text": " git clone --depth 1 --branch main git://git.somewhere destination_path\n rm -rf destination_path/.git\n --branch stable --branch release/0.9"
},
{
"answer_id": 9416271,
"author": "aredridel",
"author_id": 306320,
"author_profile": "https://Stackoverflow.com/users/306320",
"pm_score": 5,
"selected": false,
"text": "svn export . otherpath\n git archive branchname | (cd otherpath; tar x)\n svn export url otherpath\n git archive --remote=url branchname | (cd otherpath; tar x)\n"
},
{
"answer_id": 12801609,
"author": "orkoden",
"author_id": 1329214,
"author_profile": "https://Stackoverflow.com/users/1329214",
"pm_score": 3,
"selected": false,
"text": "git archive --format=zip --output=archive.zip --remote=USERNAME@HOSTNAME:PROJECTNAME.git HASHOFGITCOMMIT\n"
},
{
"answer_id": 19058735,
"author": "teleme.io",
"author_id": 305945,
"author_profile": "https://Stackoverflow.com/users/305945",
"pm_score": 4,
"selected": false,
"text": "\ngit clone url_of_your_repo path_to_export && rm -rf path_to_export/.git\n"
},
{
"answer_id": 19689284,
"author": "Anthony Hatzopoulos",
"author_id": 881551,
"author_profile": "https://Stackoverflow.com/users/881551",
"pm_score": 6,
"selected": false,
"text": "svn export archive --remote svn svn export trunk master svn export https://github.com/username/repo-name/trunk/\n svn export https://github.com/username/repo-name/trunk/src/lib/folder\n HEAD trunk svn ls https://github.com/jquery/jquery/trunk\n HEAD /branches/ svn ls https://github.com/jquery/jquery/branches/2.1-stable\n /tags/ svn ls https://github.com/jquery/jquery/tags/2.1.3\n"
},
{
"answer_id": 22702614,
"author": "user5286776117878",
"author_id": 2069644,
"author_profile": "https://Stackoverflow.com/users/2069644",
"pm_score": 5,
"selected": false,
"text": ".gitattributes export-ignore git checkout mkdir /path/to/checkout/\ngit --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout -f -q\n mkdir /path/to/checkout/\ngit --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout 2ef2e1f2de5f3d4f5e87df7d8 -f -q -- ./\n /path/to/checkout/ -- ./ -- git checkout HEAD readme.txt git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout fef2e1f2de5f3d4f5e87df7d8 -f -q -- ./libs ./docs/readme.txt\n my_file_2_behind_HEAD.txt HEAD^2 git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout HEAD^2 -f -q -- ./my_file_2_behind_HEAD.txt\n git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout myotherbranch -f -q -- ./\n ./"
},
{
"answer_id": 23299744,
"author": "Fuyu Persimmon",
"author_id": 2382896,
"author_profile": "https://Stackoverflow.com/users/2382896",
"pm_score": 3,
"selected": false,
"text": "git diff-tree -r --no-commit-id --name-only --diff-filter=ACMRT C~..G | xargs tar -rf myTarFile.tar\n"
},
{
"answer_id": 23800579,
"author": "MichaelMoser",
"author_id": 3034482,
"author_profile": "https://Stackoverflow.com/users/3034482",
"pm_score": 1,
"selected": false,
"text": "function garchive()\n{\n if [[ \"x$1\" == \"x-h\" || \"x$1\" == \"x\" ]]; then\n cat <<EOF\nUsage: garchive <archive-name>\ncreate zip archive of the current branch into <archive-name>\nEOF\n else\n local oname=$1\n set -x\n local bname=$(git branch | grep -F \"*\" | sed -e 's#^*##')\n git archive --format zip --output ${oname} ${bname}\n set +x\n fi\n}\n"
},
{
"answer_id": 24760614,
"author": "sdaau",
"author_id": 277826,
"author_profile": "https://Stackoverflow.com/users/277826",
"pm_score": 2,
"selected": false,
"text": "svn /media/disk/repo_svn/subdir$ svn export . /media/disk2/repo_svn_B/subdir\n svn .svn .o svn help export git git /media/disk/git_svn/subdir$ ls -la .\n /media/disk/git_svn/subdir$ git archive --format=tar --prefix=junk/ HEAD | (tar -t -v --full-time -f -)\n git archive git help archive bash /media/disk/git_svn/subdir$ git archive --format=tar master | (tar tf -) | (\\\n DEST=\"/media/diskC/tmp/subdirB\"; \\\n CWD=\"$PWD\"; \\\n while read line; do \\\n DN=$(dirname \"$line\"); BN=$(basename \"$line\"); \\\n SRD=\"$CWD\"; TGD=\"$DEST\"; \\\n if [ \"$DN\" != \".\" ]; then \\\n SRD=\"$SRD/$DN\" ; TGD=\"$TGD/$DN\" ; \\\n if [ ! -d \"$TGD\" ] ; then \\\n CMD=\"mkdir \\\"$TGD\\\"; touch -r \\\"$SRD\\\" \\\"$TGD\\\"\"; \\\n echo \"$CMD\"; \\\n eval \"$CMD\"; \\\n fi; \\\n fi; \\\n CMD=\"cp -a \\\"$SRD/$BN\\\" \\\"$TGD/\\\"\"; \\\n echo \"$CMD\"; \\\n eval \"$CMD\"; \\\n done \\\n)\n /media/disk/git_svn/subdir DEST DEST ls -la /media/disk/git_svn/subdir\nls -la /media/diskC/tmp/subdirB # DEST\n"
},
{
"answer_id": 25060822,
"author": "bishop",
"author_id": 2908724,
"author_profile": "https://Stackoverflow.com/users/2908724",
"pm_score": 4,
"selected": false,
"text": "git archive --remote curl curl -L https://api.github.com/repos/VENDOR/PROJECT/tarball | tar xzf -\n $ curl -L https://api.github.com/repos/jpic/bashworks/tarball | tar xzf -\n$ ls jpic-bashworks-34f4441/\nbreak conf docs hack LICENSE mlog module mpd mtests os README.rst remote todo vcs vps wepcrack\n curl -L https://api.github.com/repos/VENDOR/PROJECT/tarball | \\\ntar xzC /path/you/want --strip 1\n"
},
{
"answer_id": 27788401,
"author": "zeeawan",
"author_id": 4221299,
"author_profile": "https://Stackoverflow.com/users/4221299",
"pm_score": 4,
"selected": false,
"text": "git archive --format zip --output /full/path/to/zipfile.zip master \n"
},
{
"answer_id": 29462605,
"author": "B T",
"author_id": 122422,
"author_profile": "https://Stackoverflow.com/users/122422",
"pm_score": 3,
"selected": false,
"text": "git bundle git bundle create /some/bundle/path.bundle --all"
},
{
"answer_id": 30810513,
"author": "alexis",
"author_id": 1342186,
"author_profile": "https://Stackoverflow.com/users/1342186",
"pm_score": 1,
"selected": false,
"text": ".git git archive .gitattributes git clone tmp=`mktemp`\ngit ls-tree --name-only -r HEAD > $tmp\nrsync -avz --files-from=$tmp --exclude='fonts/*' . raspberry:\n rsync git archive"
},
{
"answer_id": 48945749,
"author": "Tom",
"author_id": 7179161,
"author_profile": "https://Stackoverflow.com/users/7179161",
"pm_score": 2,
"selected": false,
"text": "GIT_WORK_TREE=outputdirectory git checkout -f /var/www/ .git/hooks/post-receive hooks/post-receive"
},
{
"answer_id": 49238201,
"author": "Ondra Žižka",
"author_id": 145989,
"author_profile": "https://Stackoverflow.com/users/145989",
"pm_score": 3,
"selected": false,
"text": "git clone -b someBranch --depth 1 --single-branch git://somewhere.com/repo.git \\\n&& rm -rf repo/.git/\n --single-branch --depth"
},
{
"answer_id": 53150435,
"author": "DomTomCat",
"author_id": 1150303,
"author_profile": "https://Stackoverflow.com/users/1150303",
"pm_score": 3,
"selected": false,
"text": "git archive master --prefix=directoryWithinZip/ --format=zip -o out.zip\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/893/"
] |
160,611
|
<p>I'm trying to unit test (JUnit) a DAO i've created. I'm using Spring as my framework, my DAO (JdbcPackageDAO) extends SimpleJdbcDaoSupport. The testing class (JdbcPackageDAOTest) extends AbstractTransactionalDataSourceSpringContextTests. I've overridden the configLocations as follows:</p>
<pre><code>protected String[] getConfigLocations(){
return new String[] {"classpath:company/dc/test-context.xml"};
}
</code></pre>
<p>My test-context.xml file is defined as follows:</p>
<pre><code><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="dataPackageDao" class="company.data.dao.JdbcPackageDAO">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:hsql://localhost"/>
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>company/data/dao/jdbc.properties</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
</code></pre>
<p>I'm using HSQL as my backend, it's running in standalone mode. My IDE of choice is eclipse. When I run the class as a JUnit test here's my error (below). I have no clue as to why its happening. hsql.jar is on my build path according to Eclipse.</p>
<pre>
org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLException: No suitable driver found for jdbc:hsqldb:hsql://localhost
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:219)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:377)
at org.springframework.test.AbstractTransactionalSpringContextTests.startNewTransaction(AbstractTransactionalSpringContextTests.java:387)
at org.springframework.test.AbstractTransactionalSpringContextTests.onSetUp(AbstractTransactionalSpringContextTests.java:217)
at org.springframework.test.AbstractSingleSpringContextTests.setUp(AbstractSingleSpringContextTests.java:101)
at junit.framework.TestCase.runBare(TestCase.java:128)
at org.springframework.test.ConditionalTestCase.runBare(ConditionalTestCase.java:76)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:120)
at junit.framework.TestSuite.runTest(TestSuite.java:230)
at junit.framework.TestSuite.run(TestSuite.java:225)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:hsqldb:hsql://localhost
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:291)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:277)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:259)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:241)
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:182)
... 18 more
</pre>
|
[
{
"answer_id": 160627,
"author": "Max Stewart",
"author_id": 18338,
"author_profile": "https://Stackoverflow.com/users/18338",
"pm_score": 2,
"selected": false,
"text": "jdbc:hsqldb:hsql://serverName:port/DBname\n"
},
{
"answer_id": 161220,
"author": "NR.",
"author_id": 11701,
"author_profile": "https://Stackoverflow.com/users/11701",
"pm_score": 0,
"selected": false,
"text": "jdbc:hsqldb:hsql://localhost/mydatabase \n"
},
{
"answer_id": 391814,
"author": "duffymo",
"author_id": 37213,
"author_profile": "https://Stackoverflow.com/users/37213",
"pm_score": 2,
"selected": false,
"text": "<property name=\"url\" value=\"jdbc:hsqldb:hsql://localhost\"/>\n"
},
{
"answer_id": 2262136,
"author": "Ivan Koblik",
"author_id": 51260,
"author_profile": "https://Stackoverflow.com/users/51260",
"pm_score": 5,
"selected": false,
"text": "Class.forName(\"org.hsqldb.jdbcDriver\");\n static {\n try {\n DriverManager.registerDriver(new jdbcDriver());\n } catch (Exception e) {}\n}\n"
},
{
"answer_id": 11175182,
"author": "Emac",
"author_id": 1477671,
"author_profile": "https://Stackoverflow.com/users/1477671",
"pm_score": 1,
"selected": false,
"text": "Class.forName(\"org.hsqldb.jdbcDriver\");\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17337/"
] |
160,614
|
<p>I have a Dynamic Data website built in Visual Studio 2008 using .NET 3.5 SP1. The site works OK on my Vista machine, but I get the following error when running it on a Windows XP machine:</p>
<blockquote>
<p>Server Error in '/FlixManagerWeb'
Application.
-------------------------------------------------------------------------------- The resource cannot be found.
Description: HTTP 404. The resource
you are looking for (or one of its
dependencies) could have been removed,
had its name changed, or is
temporarily unavailable. Please
review the following URL and make sure
that it is spelled correctly. </p>
<p>Requested URL: /FlixManagerWeb
-------------------------------------------------------------------------------- Version Information: Microsoft .NET
Framework Version:2.0.50727.3053;
ASP.NET Version:2.0.50727.3053</p>
</blockquote>
<p>I have added the .* -> aspnet_isapi.dll mapping in the site config, made sure that it is an "application," but that did not help. Anyone have any luck running a Dynamic Data website on Windows XP? What (if anything) special is required to get it to work?</p>
|
[
{
"answer_id": 160627,
"author": "Max Stewart",
"author_id": 18338,
"author_profile": "https://Stackoverflow.com/users/18338",
"pm_score": 2,
"selected": false,
"text": "jdbc:hsqldb:hsql://serverName:port/DBname\n"
},
{
"answer_id": 161220,
"author": "NR.",
"author_id": 11701,
"author_profile": "https://Stackoverflow.com/users/11701",
"pm_score": 0,
"selected": false,
"text": "jdbc:hsqldb:hsql://localhost/mydatabase \n"
},
{
"answer_id": 391814,
"author": "duffymo",
"author_id": 37213,
"author_profile": "https://Stackoverflow.com/users/37213",
"pm_score": 2,
"selected": false,
"text": "<property name=\"url\" value=\"jdbc:hsqldb:hsql://localhost\"/>\n"
},
{
"answer_id": 2262136,
"author": "Ivan Koblik",
"author_id": 51260,
"author_profile": "https://Stackoverflow.com/users/51260",
"pm_score": 5,
"selected": false,
"text": "Class.forName(\"org.hsqldb.jdbcDriver\");\n static {\n try {\n DriverManager.registerDriver(new jdbcDriver());\n } catch (Exception e) {}\n}\n"
},
{
"answer_id": 11175182,
"author": "Emac",
"author_id": 1477671,
"author_profile": "https://Stackoverflow.com/users/1477671",
"pm_score": 1,
"selected": false,
"text": "Class.forName(\"org.hsqldb.jdbcDriver\");\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2762/"
] |
160,633
|
<p>Why are flat text files the state of the art for representing source code?</p>
<p>Sure - the preprocessor and compiler need to see a flat file representation of the file, but that's easily created.</p>
<p>It seems to me that some form of XML or binary data could represent lots of ideas that are very difficult to track, otherwise.</p>
<p>For instance, you could embed UML diagrams right into your code. They could be generated semi-automatically, and annotated by the developers to highlight important aspects of the design. Interaction diagrams in particular. Heck, embedding any user drawing might make things more clear.</p>
<p>Another idea is to embed comments from code reviews right into the code.</p>
<p>There could be all sorts of aids to make merging multiple branches easier.</p>
<p>Something I'm passionate about is not just tracking code coverage, but also looking at the parts of code covered by an automated test. The hard part is keeping track of that code, even as the source is modified. For instance, moving a function from one file to another, etc. This can be done with GUIDs, but they're rather intrusive to embed right in the text file. In a rich file format, they could be automatic and unobtrusive.</p>
<p>So why are there no IDEs (to my knowledge, anyway) which allow you to work with code in this way?</p>
<p><strong>EDIT:</strong> On October 7th, 2009.</p>
<p>Most of you got very hung up on the word "binary" in my question. I retract it. Picture XML, very minimally marking up your code. The instant before you hand it to your normal preprocessor or compiler, you strip out all of the XML markup, and pass on just the source code. In this form, you could still do all of the normal things to the file: diff, merge, edit, work with in a simple and minimal editor, feed them into thousands of tools. Yes, the diff, merge, and edit, directly with the minimal XML markup, does get a tad more complicated. But I think the value could be enormous.</p>
<p>If an IDE existed which respected all of the XML, you could add so much more than what we can do today.</p>
<p>For instance, your DOxygen comments could actually <em>look</em> like the final DOxygen output.</p>
<p>When someone wanted to do a code review, like Code Collaborator, they could mark up the source code, in place.</p>
<p>The XML could even be hidden behind comments.</p>
<pre><code>// <comment author="mcruikshank" date="2009-10-07">
// Please refactor to Delegate.
// </comment>
</code></pre>
<p>And then if you want to use vi or emacs, you can just skip over the comments.</p>
<p>If I want to use a state-of-the-art editor, I can see that in about a dozen different helpful ways.</p>
<p>So, that's my rough idea. It's not "building blocks" of pictures that you drag on the screen... I'm not that nuts. :)</p>
|
[
{
"answer_id": 1535445,
"author": "Rebol Tutorial",
"author_id": 2687173,
"author_profile": "https://Stackoverflow.com/users/2687173",
"pm_score": 0,
"selected": false,
"text": "In pursuing (interests of) software\n developers,'' says Alsop, Asymetrix\n "
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8643/"
] |
160,650
|
<p>Is there a way to run some custom Javascript whenever a client-side ASP.NET validator (<code>RequiredFieldValidator</code>, <code>RangeValidator</code>, etc) is triggered? </p>
<p>Basically, I have a complicated layout that requires I run a custom script whenever a DOM element is shown or hidden. I'm looking for a way to automatically run this script when a validator is displayed. (I'm using validators with <code>Display="dynamic"</code>)</p>
|
[
{
"answer_id": 160844,
"author": "Leon Tayson",
"author_id": 18413,
"author_profile": "https://Stackoverflow.com/users/18413",
"pm_score": 0,
"selected": false,
"text": "function customValidation()\n{\n Page_ClientValidate();\n if(!Page_IsValid)\n { //run your resize script }\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23632/"
] |
160,651
|
<p>I would like to provide downloadable files to website users, but want to hide the URL of the files from the user... I'm thinking an HTTPHandler could do the trick, but is it possible to retrieve a file from an external server and stream it to the user?</p>
<p>Perhaps somebody can give me a hint at how to accomplish this, or point me to a resource where it's been done before?</p>
<hr>
<p>Just to elaborate on what I'm trying to achieve... I'm building an ASP.NET website, which contains a music download link. I want to protect the actual URLs of the file, and I also want to store them on an external (PHP) server (MUCH MUCH cheaper)... </p>
<p>So what I need to do is set up a stream that can grab the file from a URL (points to another server), and stream it to the Response object without the user realising it's coming from another server.</p>
<p>Will the TransmitFile method allow streaming of a file from a completely separate server? I don't want the file to be streamed "through" my server, as that defeats the purpose (saving bandwidth)... I want the client (browser) to download the file direct from the other server.</p>
<p>Do I need a handler on the file hosting server perhaps? Maybe a PHP script on the other end is the way to go...?</p>
|
[
{
"answer_id": 160690,
"author": "Carlton Jenke",
"author_id": 1215,
"author_profile": "https://Stackoverflow.com/users/1215",
"pm_score": 0,
"selected": false,
"text": "public class ZipDownloadModule: IHttpHandler, ICompressFilesView, IErrorView \n{\n CompressFilesPresenter _presenter;\n\n public ZipDownloadModule()\n {\n _presenter = new CompressFilesPresenter(this, this);\n }\n #region IHttpHandler Members\n\n public bool IsReusable\n {\n get { return true; }\n }\n\n public void ProcessRequest(HttpContext context)\n {\n OnDownloadFiles();\n }\n\n private void OnDownloadFiles()\n {\n if(Compress != null)\n Compress(this, EventArgs.Empty);\n }\n\n #endregion\n\n #region IFileListDownloadView Members\n\n public IEnumerable<string> FileNames\n {\n get \n {\n string files = HttpContext.Current.Request[\"files\"] ?? string.Empty;\n\n return files.Split(new Char[] { ',' });\n }\n }\n\n public System.IO.Stream Stream\n {\n get\n {\n HttpContext.Current.Response.ContentType = \"application/x-zip-compressed\";\n HttpContext.Current.Response.AppendHeader(\"Content-Disposition\", \"attachment; filename=ads.zip\");\n return HttpContext.Current.Response.OutputStream;\n }\n }\n\n public event EventHandler Compress;\n\n #endregion\n\n #region IErrorView Members\n\n public string errorMessage\n {\n set { }\n }\n\n #endregion\n}\n public class CompressFilesPresenter: PresenterBase<ICompressFilesView>\n{\n IErrorView _errorView;\n\n public CompressFilesPresenter(ICompressFilesView view, IErrorView errorView)\n : base(view)\n {\n _errorView = errorView;\n this.View.Compress += new EventHandler(View_Compress);\n }\n\n void View_Compress(object sender, EventArgs e)\n {\n CreateZipFile();\n }\n\n private void CreateZipFile()\n {\n MemoryStream stream = new MemoryStream();\n\n try\n {\n CreateZip(stream, this.View.FileNames);\n\n WriteZip(stream);\n }\n catch(Exception ex)\n {\n HandleException(ex);\n }\n }\n\n private void WriteZip(MemoryStream stream)\n {\n byte[] data = stream.ToArray();\n\n this.View.Stream.Write(data, 0, data.Length);\n }\n\n private void CreateZip(MemoryStream stream, IEnumerable<string> filePaths)\n {\n using(ZipOutputStream s = new ZipOutputStream(stream)) // this.View.Stream))\n {\n s.SetLevel(9); // 0 = store only to 9 = best compression\n\n foreach(string fullPath in filePaths)\n AddFileToZip(fullPath, s);\n\n s.Finish();\n }\n }\n\n private static void AddFileToZip(string fullPath, ZipOutputStream s)\n {\n byte[] buffer = new byte[4096];\n\n ZipEntry entry;\n\n // Using GetFileName makes the result compatible with XP\n entry = new ZipEntry(Path.GetFileName(fullPath));\n\n entry.DateTime = DateTime.Now;\n s.PutNextEntry(entry);\n\n using(FileStream fs = File.OpenRead(fullPath))\n {\n int sourceBytes;\n do\n {\n sourceBytes = fs.Read(buffer, 0, buffer.Length);\n s.Write(buffer, 0, sourceBytes);\n } while(sourceBytes > 0);\n }\n }\n\n private void HandleException(Exception ex)\n {\n switch(ex.GetType().ToString())\n {\n case \"DirectoryNotFoundException\":\n _errorView.errorMessage = \"The expected directory does not exist.\";\n break;\n case \"FileNotFoundException\":\n _errorView.errorMessage = \"The expected file does not exist.\";\n break;\n default:\n _errorView.errorMessage = \"There has been an error. If this continues please contact AMG IT Support.\";\n break;\n }\n }\n\n private void ClearError()\n {\n _errorView.errorMessage = \"\";\n }\n}\n"
},
{
"answer_id": 345767,
"author": "Joan Pham",
"author_id": 43867,
"author_profile": "https://Stackoverflow.com/users/43867",
"pm_score": 1,
"selected": false,
"text": "HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(serviceUrl);\n webrequest.AllowAutoRedirect = false;\n webrequest.Timeout = 30 * 1000;\n webrequest.ReadWriteTimeout = 30 * 1000;\n webrequest.KeepAlive = false;\n\n Stream remoteStream = null;\n byte[] buffer = new byte[4 * 1024];\n int bytesRead;\n\n try {\n WebResponse responce = webrequest.GetResponse();\n remoteStream = responce.GetResponseStream();\n bytesRead = remoteStream.Read(buffer, 0, buffer.Length);\n\n Server.ScriptTimeout = 30 * 60;\n Response.Buffer = false;\n Response.BufferOutput = false;\n Response.Clear();\n Response.ContentType = \"application/octet-stream\";\n Response.AppendHeader(\"Content-Disposition\", \"attachment; filename=\" + Uid + \".EML\");\n if (responce.ContentLength != -1)\n Response.AppendHeader(\"Content-Length\", responce.ContentLength.ToString());\n\n while (bytesRead > 0 && Response.IsClientConnected) {\n Response.OutputStream.Write(buffer, 0, bytesRead);\n bytesRead = remoteStream.Read(buffer, 0, buffer.Length);\n }\n\n } catch (Exception E) {\n Logger.LogErrorFormat(LogModules.DomainUsers, \"Error transfering message from remote host: {0}\", E.Message);\n Response.End();\n return;\n } finally {\n if (remoteStream != null) remoteStream.Close();\n }\n\n Response.End();\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21969/"
] |
160,666
|
<p>I'd like to have an HTML page which displays a single PNG or JPEG image. I want the image to take up the whole screen but when I do this:</p>
<pre><code><img src="whatever.jpeg" width="100%" height="100%" />
</code></pre>
<p>It just stretches the image and messes up the aspect ratio. How do I solve this so the image has the correct aspect ratio while scaling to the maximum size possible ?</p>
<hr />
<p>The solution posted by Wayne <strong>almost</strong> works except for the case where you have a tall image and a wide window. This code is a slight modification of his code which does what I want:</p>
<pre class="lang-html prettyprint-override"><code><html>
<head>
<script>
function resizeToMax(id){
myImage = new Image()
var img = document.getElementById(id);
myImage.src = img.src;
if(myImage.width / document.body.clientWidth > myImage.height / document.body.clientHeight){
img.style.width = "100%";
} else {
img.style.height = "100%";
}
}
</script>
</head>
<body>
<img id="image" src="test.gif" onload="resizeToMax(this.id)">
</body>
</html>
</code></pre>
|
[
{
"answer_id": 160674,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 2,
"selected": false,
"text": "<img src=\"whatever.jpeg\" width=\"100%\" height=\"auto\" />\n"
},
{
"answer_id": 160717,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 5,
"selected": true,
"text": "<html>\n<head>\n<script>\nfunction resizeToMax(id){\n myImage = new Image() \n var img = document.getElementById(id);\n myImage.src = img.src; \n if(myImage.width > myImage.height){\n img.style.width = \"100%\";\n } else {\n img.style.height = \"100%\";\n }\n}\n</script>\n</head>\n<body>\n<img id=\"image\" src=\"test.gif\" onload=\"resizeToMax(this.id)\">\n</body>\n</html>\n"
},
{
"answer_id": 160729,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "var imgTag = $('myImage'); \nvar imgPath = imgTag.src; \nvar img = new Image(); \nimg.src = imgPath; \nvar mywidth = img.width; \nvar myheight = img.height;\n"
},
{
"answer_id": 160770,
"author": "Samir Talwar",
"author_id": 20856,
"author_profile": "https://Stackoverflow.com/users/20856",
"pm_score": 3,
"selected": false,
"text": "<script type=\"text/javascript\">\n// <![CDATA[\nfunction resizeToMax (id) {\n var img = document.getElementById(id);\n myImage = new Image();\n myImage.src = img.src;\n if (window.innerWidth / myImage.width < window.innerHeight / myImage.height) {\n img.style.width = \"100%\";\n } else {\n img.style.height = \"100%\";\n }\n}\n// ]]>\n</script>\n"
},
{
"answer_id": 12013347,
"author": "tito76",
"author_id": 1607948,
"author_profile": "https://Stackoverflow.com/users/1607948",
"pm_score": 0,
"selected": false,
"text": "<div align=\"center\">\n<embed src=\"image.gif\" height=\"100%\">\n"
},
{
"answer_id": 12979880,
"author": "ondovb",
"author_id": 1260565,
"author_profile": "https://Stackoverflow.com/users/1260565",
"pm_score": 3,
"selected": false,
"text": "background-size:contain <head>\n<style>\n#bigPicture\n{\n width:100%;\n height:100%;\n background:url(http://upload.wikimedia.org/wikipedia/commons/4/44/CatLolCatExample.jpg);\n background-size:contain;\n background-repeat:no-repeat;\n background-position:center;\n}\n</style>\n</head>\n\n<body style=\"margin:0px\">\n <div id=\"bigPicture\">\n </div>\n</body>\n <embed> <img> background-size:contain background-* contain no-repeat center"
},
{
"answer_id": 48269722,
"author": "Jasper de Vries",
"author_id": 880619,
"author_profile": "https://Stackoverflow.com/users/880619",
"pm_score": 2,
"selected": false,
"text": "object-fit contain img { object-fit: contain; }\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324/"
] |
160,691
|
<p>How do you know if the HTTP compression setup is working? Is there any tool I can use to see the compressed page before it is uncompressed by the browser? Are there any tools to measure the amount compressed and response speed?</p>
|
[
{
"answer_id": 18152731,
"author": "bcattle",
"author_id": 1161906,
"author_profile": "https://Stackoverflow.com/users/1161906",
"pm_score": 4,
"selected": false,
"text": "curl -H 'Accept-Encoding: gzip,deflate' -D - http://example.com\n Content-Encoding: gzip"
},
{
"answer_id": 62414849,
"author": "Kodigo",
"author_id": 13757970,
"author_profile": "https://Stackoverflow.com/users/13757970",
"pm_score": 0,
"selected": false,
"text": "content-encoding content-encoding"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17071/"
] |
160,694
|
<p>What Javascript libraries can you recommend for syntax highlighting <code> blocks in HTML?</p>
<p>(One suggestion per answer please).</p>
|
[
{
"answer_id": 160768,
"author": "Edu Felipe",
"author_id": 21648,
"author_profile": "https://Stackoverflow.com/users/21648",
"pm_score": 3,
"selected": false,
"text": "$(\"code\").chili();\n"
},
{
"answer_id": 3359393,
"author": "balupton",
"author_id": 130638,
"author_profile": "https://Stackoverflow.com/users/130638",
"pm_score": 4,
"selected": false,
"text": "code pre language-javascript data-sh"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17453/"
] |
160,697
|
<p>I personally like the <em>exclusive or</em>, <code>^</code>, operator when it makes sense in the context of boolean checks because of its conciseness. I much prefer to write</p>
<pre><code>if (boolean1 ^ boolean2)
{
//do it
}
</code></pre>
<p>than</p>
<pre><code>if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
//do it
}
</code></pre>
<p>but I often get confused looks from other experienced Java developers (not just the newbies), and sometimes comments about how it should only be used for bitwise operations. </p>
<p>I'm curious as to the best practices regarding the usage of the <code>^</code> operator.</p>
|
[
{
"answer_id": 160700,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 9,
"selected": true,
"text": "!="
},
{
"answer_id": 160701,
"author": "Dre",
"author_id": 23033,
"author_profile": "https://Stackoverflow.com/users/23033",
"pm_score": 4,
"selected": false,
"text": "// ^ == XOR"
},
{
"answer_id": 160716,
"author": "Alan",
"author_id": 17205,
"author_profile": "https://Stackoverflow.com/users/17205",
"pm_score": -1,
"selected": false,
"text": "public static boolean xor(boolean a, boolean b) {\n return (a && !b) || (b && !a);\n}\n"
},
{
"answer_id": 2612763,
"author": "Y--",
"author_id": 313385,
"author_profile": "https://Stackoverflow.com/users/313385",
"pm_score": 3,
"selected": false,
"text": "if((boolean1 && !boolean2) || (boolean2 && !boolean1)) \n{ \n //do it \n} \n if(boolean1 != boolean2) \n{ \n //do it \n} \n"
},
{
"answer_id": 4205620,
"author": "Chris Rea",
"author_id": 269367,
"author_profile": "https://Stackoverflow.com/users/269367",
"pm_score": -1,
"selected": false,
"text": "str.contains(\"!=\") ^ str.startsWith(\"not(\")\n str.contains(\"!=\") != str.startsWith(\"not(\")\n"
},
{
"answer_id": 12995170,
"author": "Gunnar Karlsson",
"author_id": 898375,
"author_profile": "https://Stackoverflow.com/users/898375",
"pm_score": 3,
"selected": false,
"text": "flag toggle flags = flags ^ MASK;\n"
},
{
"answer_id": 15030804,
"author": "Cory Gross",
"author_id": 1359785,
"author_profile": "https://Stackoverflow.com/users/1359785",
"pm_score": 3,
"selected": false,
"text": "public static boolean XOR(boolean A, boolean B) {\n return A ^ B;\n}\n // Swap the values in A and B\nA ^= B;\nB ^= A;\nA ^= B;\n"
},
{
"answer_id": 45646557,
"author": "ONE",
"author_id": 6439630,
"author_profile": "https://Stackoverflow.com/users/6439630",
"pm_score": 0,
"selected": false,
"text": "if (isDifferent(boolean1, boolean2))\n{\n //do it\n}\n private boolean isDifferent(boolean1, boolean2)\n{\n return boolean1 ^ boolean2;\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17123/"
] |
160,724
|
<p>I'm working on a Google App Engine project. </p>
<p>My app is working and looking correct locally, but when I try to upload images in an image directory, they're not being displayed at appspot.</p>
<p>As a little troubleshoot, I put a HTML page in "/images/page2.html" and I can load that page at the appspot, but my pages don't display my images. So, it's not a problem with my path.</p>
<p>As another sanity check, I'm also uploading a style sheet directory with .css code in it, and that's being read properly. </p>
<p>I have a suspicion that the problem lies in my app.yaml file. </p>
<p>Any ideas? </p>
<p>I don't want to paste all the code here, but here are some of the key lines. The first two work fine. The third does not work: </p>
<pre><code><link type="text/css" rel="stylesheet" href="/stylesheets/style.css" />
<a href="/images/Page2.html">Page 2</a>
<img src="/images/img.gif">
</code></pre>
<p>This is my app.yaml file</p>
<pre><code>application: myApp
version: 1
runtime: python
api_version: 1
handlers:
- url: /stylesheets
static_dir: stylesheets
- url: /images
static_dir: images
- url: /.*
script: helloworld.py
</code></pre>
|
[
{
"answer_id": 211073,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<img src=\"/images/img.gif\">\n class GetImage(webapp.RequestHandler):\n def get(self):\n self.response.headers['Content-Type'] = 'image/jpg'\n self.response.out.write(image_object)\n <img src=\"/image\"\n application = webapp.WSGIApplication(('/image', GetImage), debug=True)\n"
},
{
"answer_id": 275705,
"author": "Sarp Centel",
"author_id": 16622,
"author_profile": "https://Stackoverflow.com/users/16622",
"pm_score": 2,
"selected": false,
"text": " url: /(.*\\.(gif|png|jpg))\n static_files: static/\\1\n upload: static/(.*\\.(gif|png|jpg))\n"
},
{
"answer_id": 1021301,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<static-files>\n<include path=\"**.*\"/>\n <include path=\"/images/**.*\" />\n</static-files>\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1179/"
] |
160,726
|
<p>I have been thinking a lot about unit testing and how to improve the readability of the unit tests. I thought why not give a character to the classes in the unit test to clarify what they do. </p>
<p>Here is a simple unit test that I wrote: </p>
<pre><code>[TestFixture]
public class when_dave_transfers_money_from_wamu_account_to_the_woodforest_account
{
[Test]
public void should_increase_the_amount_in_woodforest_account_when_transaction_successfull()
{
Dave dave = new Dave();
Wamu wamu = new Wamu();
wamu.Balance = 150;
wamu.AddUser(dave);
Woodforest woodforest = new Woodforest();
woodforest.AddUser(dave);
FundTransferService.Transfer(100, wamu, woodforest);
Assert.AreEqual(wamu.Balance, 50);
Assert.AreEqual(woodforest.Balance, 100);
}
}
</code></pre>
<p>Here is the Dave class: </p>
<pre><code>/// <summary>
/// This is Dave!
/// </summary>
public class Dave : User
{
public Dave()
{
FirstName = "Dave";
LastName = "Allen";
}
}
</code></pre>
<p>The unit test name clearly serves the purpose. But, maybe I want to dig a little deeper and assign the Wamu and Woodforest accounts to Dave whenever Dave is created. The problem is that it will move away from readability as I will have to use index values to refer to the account. </p>
<p>What are your thoughts on making this more readable? </p>
|
[
{
"answer_id": 160738,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "private Dave GetDave_With_Wamu_And_Woodforest_AccountsHookedUp()\n"
},
{
"answer_id": 160743,
"author": "azamsharp",
"author_id": 3797,
"author_profile": "https://Stackoverflow.com/users/3797",
"pm_score": 0,
"selected": false,
"text": " public Dave()\n {\n FirstName = \"Dave\";\n LastName = \"Allen\"; \n\n // add accounts for Dave \n\n Wamu wamu = new Wamu();\n wamu.AddUser(this);\n\n Woodforest woodforest = new Woodforest();\n woodforest.AddUser(this); \n }\n"
},
{
"answer_id": 160786,
"author": "azamsharp",
"author_id": 3797,
"author_profile": "https://Stackoverflow.com/users/3797",
"pm_score": 1,
"selected": false,
"text": " [Test]\n public void should_increase_the_amount_in_woodforest_account_when_transaction_successfull()\n {\n Dave dave = new Dave();\n\n // we know that dave has wamu and wooforest accounts \n\n dave.WamuAccount(\"Wamu\").Balance = 150;\n\n FundTransferService.Transfer(100, dave.WamuAccount(\"Wamu\"), dave.WoodforestAccount(\n \"Woodforest\"));\n\n Assert.AreEqual(50, dave.WamuAccount(\"Wamu\").Balance);\n Assert.AreEqual(100, dave.WoodforestAccount(\"Woodforest\").Balance); \n }\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3797/"
] |
160,737
|
<p>I would like to create a Crystal Reports report using pre-existing LINQ classes that live in a different project than where the report lives. I can't find a way to do this. I'm using VS2008.</p>
<p>Whenever I expand the "Project Data" tree, I see only classes in my current project. The "History" tree shows me the last 5 class in the OTHER project, but I need more than those 5. I found the "Make New Connection" option under "ADO.NET", but it looks like it's looking for XML sources and DLLs.</p>
|
[
{
"answer_id": 160738,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "private Dave GetDave_With_Wamu_And_Woodforest_AccountsHookedUp()\n"
},
{
"answer_id": 160743,
"author": "azamsharp",
"author_id": 3797,
"author_profile": "https://Stackoverflow.com/users/3797",
"pm_score": 0,
"selected": false,
"text": " public Dave()\n {\n FirstName = \"Dave\";\n LastName = \"Allen\"; \n\n // add accounts for Dave \n\n Wamu wamu = new Wamu();\n wamu.AddUser(this);\n\n Woodforest woodforest = new Woodforest();\n woodforest.AddUser(this); \n }\n"
},
{
"answer_id": 160786,
"author": "azamsharp",
"author_id": 3797,
"author_profile": "https://Stackoverflow.com/users/3797",
"pm_score": 1,
"selected": false,
"text": " [Test]\n public void should_increase_the_amount_in_woodforest_account_when_transaction_successfull()\n {\n Dave dave = new Dave();\n\n // we know that dave has wamu and wooforest accounts \n\n dave.WamuAccount(\"Wamu\").Balance = 150;\n\n FundTransferService.Transfer(100, dave.WamuAccount(\"Wamu\"), dave.WoodforestAccount(\n \"Woodforest\"));\n\n Assert.AreEqual(50, dave.WamuAccount(\"Wamu\").Balance);\n Assert.AreEqual(100, dave.WoodforestAccount(\"Woodforest\").Balance); \n }\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
160,742
|
<p>I'm trying to generate some code at runtime where I put in some boiler-plate stuff and the user is allowed to enter the actual working code. My boiler-plate code looks something like this:</p>
<pre><code>using System;
public class ClassName
{
public double TheFunction(double input)
{
// user entered code here
}
}
</code></pre>
<p>Ideally, I think I want to use string.Format to insert the user code and create a unique class name, but I get an exception on the format string unless it looks like this:</p>
<pre><code>string formatString = @"
using System;
public class ClassName
{0}
public double TheFunction(double input)
{0}
{2}
{1}
{1}";
</code></pre>
<p>Then I call string.Format like this:</p>
<pre><code>string entireClass = string.Format(formatString, "{", "}", userInput);
</code></pre>
<p>This is fine and I can deal with the ugliness of using {0} and {1} in the format string in place of my curly braces except that now my user input cannot use curly braces either. Is there a way to either escape the curly braces in my format string, or a good way to turn the curly braces in the user code into {0}'s and {1}'s?</p>
<p>BTW, I know that this kind of thing is a security problem waiting to happen, but this is a Windows Forms app that's for internal use on systems that are not connected to the net so the risk is acceptable in this situation.</p>
|
[
{
"answer_id": 160747,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 6,
"selected": true,
"text": "string s = String.Format(\"{{ hello to all }}\");\nConsole.WriteLine(s); //prints '{ hello to all }'\n"
},
{
"answer_id": 160749,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 1,
"selected": false,
"text": "string.Format(\"{{ {0} }}\", \"Hello, World\"); { Hello, World }"
},
{
"answer_id": 160754,
"author": "Elijah Manor",
"author_id": 4481,
"author_profile": "https://Stackoverflow.com/users/4481",
"pm_score": 3,
"selected": false,
"text": "string formatString = @\"\nusing System;\n\npublic class ClassName\n{{\n public double TheFunction(double input)\n {{\n {0}\n }}\n}}\";\n\nstring entireClass = string.Format(formatString, userInput);\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4797/"
] |
160,776
|
<p>For my server app, I need to check if an ip address is in our blacklist. </p>
<p>What is the most efficient way of comparing ip addresses? Would converting the IP address to integer and comparing them efficient?</p>
|
[
{
"answer_id": 160794,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 2,
"selected": false,
"text": "Sort() Find()"
},
{
"answer_id": 61115899,
"author": "gsaandy",
"author_id": 1419876,
"author_profile": "https://Stackoverflow.com/users/1419876",
"pm_score": 1,
"selected": false,
"text": "function isValidIPv4Range(iPv4Range = '') {\n if (IP_V4_RANGE_REGEX.test(iPv4Range)) {\n const [fromIp, toIp] = iPv4Range.split('-');\n\n if (!isValidOctets(fromIp) || !isValidOctets(toIp)) {\n return false;\n }\n\n const convertToNumericWeight = ip => {\n const [octet1, octet2, octet3, octet4] = ip.split('.').map(parseInt);\n\n return octet4 + (octet3 * 256) + (octet2 * 256 * 256) + (octet1 * 256 * 256 * 256);\n };\n\n return convertToNumericWeight(fromIp) < convertToNumericWeight(toIp);\n }\n return false;\n}"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1599/"
] |
160,791
|
<p>Maybe this is a dumb question, but I have the following behavior in Visual Studio 2005 while designing forms:</p>
<p>1 - Drop a control onto the form (suppose it's a Label, just for discussion)</p>
<p>2 - Drag that label to a specific location (aligning w/other controls, whatever)</p>
<p>3 - Release the mouse button</p>
<p>4 - The control is still stuck to the mouse!!!</p>
<p>To get it un-stuck from the mouse, I have to hit ESC, which restores the Label to it's original location.</p>
<p>This is driving me nuts. I literally have to use the arrow keys to move each control into place, pixel-by-pixel. I don't observe this behavior anywhere else in VS2005, nor do I observe it in the OS in general.</p>
<p>I am running on Windows XP inside a Parallels Virtual Machine, hosted on OS X. I don't think there is a driver problem though, b/c as I already said, no other apps demonstrate anything like this.</p>
<p>Please tell me there is some tiny checkbox buried somewhere that will turn off this behavior.</p>
|
[
{
"answer_id": 160794,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 2,
"selected": false,
"text": "Sort() Find()"
},
{
"answer_id": 61115899,
"author": "gsaandy",
"author_id": 1419876,
"author_profile": "https://Stackoverflow.com/users/1419876",
"pm_score": 1,
"selected": false,
"text": "function isValidIPv4Range(iPv4Range = '') {\n if (IP_V4_RANGE_REGEX.test(iPv4Range)) {\n const [fromIp, toIp] = iPv4Range.split('-');\n\n if (!isValidOctets(fromIp) || !isValidOctets(toIp)) {\n return false;\n }\n\n const convertToNumericWeight = ip => {\n const [octet1, octet2, octet3, octet4] = ip.split('.').map(parseInt);\n\n return octet4 + (octet3 * 256) + (octet2 * 256 * 256) + (octet1 * 256 * 256 * 256);\n };\n\n return convertToNumericWeight(fromIp) < convertToNumericWeight(toIp);\n }\n return false;\n}"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] |
160,813
|
<p>I have a few 'helper' style extension methods I use quite regularly now <em>(they are mostly quite simple, intuitive, and work for good not evil, so please don't have this descend into a discussion around whether or not I should use them).</em> They are largely extending core .NET CLR classes.</p>
<p>Currently, I have to copy the 'ExtensionMethods.cs' file that holds my extension methods to each new project within a solution to be able to use them in multiple projects.</p>
<p>Is it possible to define an extension to work over multiple projects within a solution, or wrap them in an 'extensions' dll, or are they confined to the scope of project?</p>
<p><strong>EDIT</strong> Whilst the 'dedicated project' answers are perfectly valid, I chose marxidad's as I prefer the approach he gives. Thanks for all the answers so far, and I have upmodded them all, as they were all good answers</p>
|
[
{
"answer_id": 15844040,
"author": "Csaba Toth",
"author_id": 292502,
"author_profile": "https://Stackoverflow.com/users/292502",
"pm_score": 0,
"selected": false,
"text": "ObservableCollection ReplaceRange error CS1061: 'System.Collections.ObjectModel.ObservableCollection<WhateverDto>' does not contain a definition for 'ReplaceRange' and no extension method 'ReplaceRange' accepting a first argument of type 'System.Collections.ObjectModel.ObservableCollection<WhateverDto>' could be found (are you missing a using directive or an assembly reference?) ReplaceRange"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] |
160,834
|
<p>I am a member of a team that is about to launch a beta of a python (Django specifically) based web site and accompanying suite of backend tools. The team itself has doubled in size from 2 to 4 over the past few weeks and we expect continued growth for the next couple of months at least. One issue that has started to plague us is getting everyone up to speed in terms of getting their development environment configured and having all the right eggs installed, etc.</p>
<p>I'm looking for ways to simplify this process and make it less error prone. Both zc.buildout and virtualenv look like they would be good tools for addressing this problem but both seem to concentrate primarily on the python-specific issues. We have a couple of small subprojects in other languages (Java and Ruby specifically) as well as numerous python extensions that have to be compiled natively (lxml, MySQL drivers, etc). In fact, one of the biggest thorns in our side has been getting some of these extensions compiled against appropriate versions of the shared libraries so as to avoid segfaults, malloc errors and all sorts of similar issues. It doesn't help that out of 4 people we have 4 different development environments -- 1 leopard on ppc, 1 leopard on intel, 1 ubuntu and 1 windows.</p>
<p>Ultimately what would be ideal would be something that works roughly like this, from the dos/unix prompt:</p>
<p>$ git clone [repository url]
...
$ python setup-env.py
...</p>
<p>that then does what zc.buildout/virtualenv does (copy/symlink the python interpreter, provide a clean space to install eggs) then installs all required eggs, including installing any native shared library dependencies, installs the ruby project, the java project, etc.</p>
<p>Obviously this would be useful for both getting development environments up as well as deploying on staging/production servers.</p>
<p>Ideally I would like for the tool that accomplishes this to be written in/extensible via python, since that is (and always will be) the lingua franca of our team, but I am open to solutions in other languages.</p>
<p>So, my question then is: does anyone have any suggestions for better alternatives or any experiences they can share using one of these solutions to handle larger/broader install bases?</p>
|
[
{
"answer_id": 4060962,
"author": "Brandon Rhodes",
"author_id": 85360,
"author_profile": "https://Stackoverflow.com/users/85360",
"pm_score": 2,
"selected": false,
"text": "develop.py packages .tar.gz virtualenv develop.py"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] |
160,848
|
<p>Does the compiler optimize out any multiplications by 1? That is, consider:</p>
<pre><code>int a = 1;
int b = 5 * a;
</code></pre>
<p>Will the expression 5 * a be optimized into just 5? If not, will it if a is defined as:</p>
<pre><code>const int a = 1;
</code></pre>
|
[
{
"answer_id": 160850,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": true,
"text": "const .maxstack 2\n.locals init ([0] int32, [1] int32)\n\nldc.i4.1 //load 1\nstloc.0 //store in 1st local variable\nldc.i4.5 //load 5\nldloc.0 //load 1st variable\nmul // 1 * 5\nstloc.1 // store in 2nd local variable \n .maxstack 1\n.locals init ( [0] int32 )\n\nldc.i4.5 //load 5 \nstloc.0 //store in local variable\n"
},
{
"answer_id": 160865,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "const"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16942/"
] |
160,859
|
<p>I understand what are lambda functions in Python, but I can't find what is the meaning of "lambda binding" by searching the Python docs.
A link to read about it would be great.
A trivial explained example would be even better.
Thank you.</p>
|
[
{
"answer_id": 160884,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 1,
"selected": false,
"text": "a = dict(foo=\"bar\", zip=\"zap\", zig=\"zag\") # binds a to a newly-created dict object\nb = a # binds b to that same dictionary\n\ndef crunch(param):\n print param\n\ncrunch(a) # binds the parameter \"param\" in the function crunch to that same dict again\n"
},
{
"answer_id": 160898,
"author": "Swati",
"author_id": 12682,
"author_profile": "https://Stackoverflow.com/users/12682",
"pm_score": 5,
"selected": true,
"text": "x x = 7 def foo(x): \n a = lambda: x \n x = 7 \n b = lambda: x \n return a,b\n x = 7"
},
{
"answer_id": 160920,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "def foo(x): \n a = lambda x=x: x \n x = 7 \n b = lambda: x \n return a,b\n\naa, bb = foo(4)\naa() # Prints 4\nbb() # Prints 7\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15073/"
] |
160,874
|
<p>I'm looking for software to create PNG8 format transparent images as per <a href="http://www.sitepoint.com/blogs/2007/09/18/png8-the-clear-winner/" rel="nofollow noreferrer">this article</a>.</p>
<p><strong>NOTE:</strong> I need a Linux solution myself, but please submit answers for other OSes.</p>
|
[
{
"answer_id": 342328,
"author": "mercator",
"author_id": 23263,
"author_profile": "https://Stackoverflow.com/users/23263",
"pm_score": 1,
"selected": false,
"text": "/c3 -c3"
},
{
"answer_id": 1143914,
"author": "Ben Hardy",
"author_id": 59441,
"author_profile": "https://Stackoverflow.com/users/59441",
"pm_score": 2,
"selected": false,
"text": "apt-get install pngnq # If on Ubuntu/Debian\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486/"
] |
160,876
|
<p>I have a (from what I can tell) perfectly working Linux setup (Ubuntu 8.04) where all tools (nslookup, curl, wget, firefox, etc) are able to resolve addresses. Yet, the following code fails:</p>
<pre><code>$s = new IO::Socket::INET(
PeerAddr => 'stackoverflow.com',
PeerPort => 80,
Proto => 'tcp',
);
die "Error: $!\n" unless $s;
</code></pre>
<p>I verified the following things:</p>
<ul>
<li><p>Perl is able to resolve addresses with gethostbyname (ie the code below works):</p>
<p><code>my $ret = gethostbyname('stackoverflow.com');
print inet_ntoa($ret);</code></p></li>
<li><p>The original source code works under Windows</p></li>
<li>This is how it supposed to work (ie. it should resolve hostnames), since LWP tries to use this behavior (in fact I stumbled uppon the problem by trying to debug why LWP wasn't working for me)</li>
<li>Running the script doesn't emit DNS requests (so it doesn't even try to resolve the name). Verified with Wireshark</li>
</ul>
|
[
{
"answer_id": 160907,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": -1,
"selected": false,
"text": "use IO::Socket::INET;\n use Net::DNS;\n\nmy $res = Net::DNS::Resolver->new;\n\n# Perform a lookup, using the searchlist if appropriate.\nmy $answer = $res->search('example.com');\n"
},
{
"answer_id": 160964,
"author": "tye",
"author_id": 21496,
"author_profile": "https://Stackoverflow.com/users/21496",
"pm_score": 4,
"selected": true,
"text": "sub _get_addr {\n my($sock,$addr_str, $multi) = @_;\n my @addr;\n if ($multi && $addr_str !~ /^\\d+(?:\\.\\d+){3}$/) {\n (undef, undef, undef, undef, @addr) = gethostbyname($addr_str);\n } else {\n my $h = inet_aton($addr_str);\n push(@addr, $h) if defined $h;\n }\n @addr;\n}\n MultiHomed => 1, inet_aton(\"hostname.com\") void\ninet_aton(host)\n char * host\n CODE:\n {\n struct in_addr ip_address;\n struct hostent * phe;\n\n if (phe = gethostbyname(host)) {\n Copy( phe->h_addr, &ip_address, phe->h_length, char );\n } else {\n ip_address.s_addr = inet_addr(host);\n }\n\n ST(0) = sv_newmortal();\n if(ip_address.s_addr != INADDR_NONE) {\n sv_setpvn( ST(0), (char *)&ip_address, sizeof ip_address );\n }\n }\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1265/"
] |
160,881
|
<p>So this is a question for anyone who has had to integrate the building/compilation of legacy projects/code in a Team Build/MSBuild environment - specifically, Visual Basic 6 applications/projects.</p>
<p><i>Outside</i> of writing a custom build Task (which I am not against) does anyone have any suggestions on how best to integrate compilation and versioning of legacy VB6 projects into MSBuild builds?</p>
<p>I'm aware of the FreeToDev msbuild tasks at <a href="http://www.codeplex.com/freetodevtasks" rel="noreferrer">CodePlex</a> but they've been withdrawn at the moment.</p>
<p>Ideally I'm looking to version and compile the code as well as capture the compilation output (especially errors) for the msbuild log.</p>
<p>I've seen advice on encapsulating this functionality in a custom task, but really wondered if anyone has tried another solution (aside from executing shell commands) -
In essence, does anyone have a "cleaner" solution?</p>
<p>Ideally, executing commands using would be a last resort..</p>
|
[
{
"answer_id": 160907,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": -1,
"selected": false,
"text": "use IO::Socket::INET;\n use Net::DNS;\n\nmy $res = Net::DNS::Resolver->new;\n\n# Perform a lookup, using the searchlist if appropriate.\nmy $answer = $res->search('example.com');\n"
},
{
"answer_id": 160964,
"author": "tye",
"author_id": 21496,
"author_profile": "https://Stackoverflow.com/users/21496",
"pm_score": 4,
"selected": true,
"text": "sub _get_addr {\n my($sock,$addr_str, $multi) = @_;\n my @addr;\n if ($multi && $addr_str !~ /^\\d+(?:\\.\\d+){3}$/) {\n (undef, undef, undef, undef, @addr) = gethostbyname($addr_str);\n } else {\n my $h = inet_aton($addr_str);\n push(@addr, $h) if defined $h;\n }\n @addr;\n}\n MultiHomed => 1, inet_aton(\"hostname.com\") void\ninet_aton(host)\n char * host\n CODE:\n {\n struct in_addr ip_address;\n struct hostent * phe;\n\n if (phe = gethostbyname(host)) {\n Copy( phe->h_addr, &ip_address, phe->h_length, char );\n } else {\n ip_address.s_addr = inet_addr(host);\n }\n\n ST(0) = sv_newmortal();\n if(ip_address.s_addr != INADDR_NONE) {\n sv_setpvn( ST(0), (char *)&ip_address, sizeof ip_address );\n }\n }\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18471/"
] |
160,889
|
<p>Here's the deal. Is there a way to have strings tokenized in a line based on multiple regexes?</p>
<p>One example:</p>
<p>I have to get all href tags, their corresponding text and some other text based on a different regex.
So I have 3 expressions and would like to tokenize the line and extract tokens of text matching every expression.</p>
<p>I have actually done this using flex (not to be confused with Adobe), which is an implementation of the good old lex. lex provides
an elegant way to do this by executing "actions" based on expressions. One can control the way
lex reading a file too (block / line based read).</p>
<p>The problem is that flex actually produces C/ C++ code which actually does the tokenizing job. I have a
make file which wraps all these things.
I was wondering if perl /python can in some way do the same thing. Its just that I would like to do everything
I like in a single programming language itself.</p>
<p>Tokenizing is just one of the things that I want to do as part of my application.</p>
<p>Apart from perl or python can any language (functional also) do this?</p>
<p>I did read about PLY and ANTLR here (<a href="https://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085">Parsing, where can I learn about it</a>).</p>
<p>But is there a way to do it naturally in python itself? pardon my ignorance, but are these tools used in any popular products / services?</p>
<p>Thank you.</p>
|
[
{
"answer_id": 160895,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 2,
"selected": false,
"text": "from pyparsing import Word, alphas\ngreet = Word( alphas ) + \",\" + Word( alphas ) + \"!\" # <-- grammar defined here\nhello = \"Hello, World!\"\nprint hello, \"->\", greet.parseString( hello )\n Hello, World! -> ['Hello', ',', 'World', '!']\n"
},
{
"answer_id": 160896,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 3,
"selected": false,
"text": "from BeautifulSoup import BeautifulSoup, SoupStrainer\nimport re\n\nlinks = SoupStrainer('a')\n[tag for tag in BeautifulSoup(doc, parseOnlyThese=links)]\n# [<a href=\"http://www.bob.com/\">success</a>, \n# <a href=\"http://www.bob.com/plasma\">experiments</a>, \n# <a href=\"http://www.boogabooga.net/\">BoogaBooga</a>]\n\nlinksToBob = SoupStrainer('a', href=re.compile('bob.com/'))\n[tag for tag in BeautifulSoup(doc, parseOnlyThese=linksToBob)]\n# [<a href=\"http://www.bob.com/\">success</a>, \n# <a href=\"http://www.bob.com/plasma\">experiments</a>]\n"
},
{
"answer_id": 161146,
"author": "pjf",
"author_id": 19422,
"author_profile": "https://Stackoverflow.com/users/19422",
"pm_score": 4,
"selected": true,
"text": "#!/usr/bin/perl\nuse strict;\nuse warnings;\nuse WWW::Mechanize;\n\nmy $mech = WWW::Mechanize->new;\n\n$mech->get(\"http://stackoverflow.com/\");\n\n$mech->success or die \"Oh no! Couldn't fetch stackoverflow.com\";\n\nforeach my $link ($mech->links) {\n print \"* [\",$link->text, \"] points to \", $link->url, \"\\n\";\n}\n $link"
},
{
"answer_id": 161977,
"author": "draegtun",
"author_id": 12195,
"author_profile": "https://Stackoverflow.com/users/12195",
"pm_score": 2,
"selected": false,
"text": "use pQuery;\n\npQuery( 'http://www.perl.com' )->find( 'a' )->each( \n sub {\n my $pQ = pQuery( $_ ); \n say $pQ->text, ' -> ', $pQ->toHtml;\n }\n);\n\n# prints all HTML anchors on www.perl.com\n# => link text -> anchor HTML\n use strict;\nuse warnings;\nuse Parse::RecDescent;\n\nmy $grammar = q{\n alpha : /\\w+/\n sep : /,|\\s/\n end : '!'\n greet : alpha sep alpha end { shift @item; return \\@item }\n};\n\nmy $parse = Parse::RecDescent->new( $grammar );\nmy $hello = \"Hello, World!\";\nprint \"$hello -> @{ $parse->greet( $hello ) }\";\n\n# => Hello, World! -> Hello , World !\n"
},
{
"answer_id": 162301,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 1,
"selected": false,
"text": "/\\G.../gc LOOP:\n {\n print(\" digits\"), redo LOOP if /\\G\\d+\\b[,.;]?\\s*/gc;\n print(\" lowercase\"), redo LOOP if /\\G[a-z]+\\b[,.;]?\\s*/gc;\n print(\" UPPERCASE\"), redo LOOP if /\\G[A-Z]+\\b[,.;]?\\s*/gc;\n print(\" Capitalized\"), redo LOOP if /\\G[A-Z][a-z]+\\b[,.;]?\\s*/gc;\n print(\" MiXeD\"), redo LOOP if /\\G[A-Za-z]+\\b[,.;]?\\s*/gc;\n print(\" alphanumeric\"), redo LOOP if /\\G[A-Za-z0-9]+\\b[,.;]?\\s*/gc;\n print(\" line-noise\"), redo LOOP if /\\G[^A-Za-z0-9]+/gc;\n print \". That's all!\\n\";\n }\n"
},
{
"answer_id": 172371,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 0,
"selected": false,
"text": "my $input = \"...\";\nwhile (1) {\n if ($input =~ /\\G(\\w+)/gc) { print \"word: '$1'\\n\"; next }\n if ($input =~ /\\G(\\s+)/gc) { print \"whitespace: '$1'\\n\"; next }\n\n if ($input !~ /\\G\\z/gc) { print \"tokenizing error at character \" . pos($input) . \"\\n\" }\n print \"done!\\n\"; last;\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24382/"
] |
160,890
|
<p>I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method:</p>
<pre><code>Random.nextInt(74)
</code></pre>
<p>I'm not interested in a discussion about seeds or true randomness, just how you accomplish the same task in Objective-C. I've scoured Google, and there just seems to be lots of different and conflicting bits of information.</p>
|
[
{
"answer_id": 160910,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "#include <time.h>\n#include <stdlib.h>\n...\nsrand(time(NULL));\nint r = rand() % 74;\n random() arc4random() rand()"
},
{
"answer_id": 161141,
"author": "Michael Buckley",
"author_id": 22540,
"author_profile": "https://Stackoverflow.com/users/22540",
"pm_score": 5,
"selected": false,
"text": "#import <stdlib.h>\n#import <time.h>\n\nsrandom(time(NULL));\nrandom() % 74;\n"
},
{
"answer_id": 163178,
"author": "lajos",
"author_id": 3740,
"author_profile": "https://Stackoverflow.com/users/3740",
"pm_score": 11,
"selected": true,
"text": "arc4random_uniform() rand #include <stdlib.h>\n// ...\n// ...\nint r = arc4random_uniform(74);\n arc4random NAME\n arc4random, arc4random_stir, arc4random_addrandom -- arc4 random number generator\n\nLIBRARY\n Standard C Library (libc, -lc)\n\nSYNOPSIS\n #include <stdlib.h>\n\n u_int32_t\n arc4random(void);\n\n void\n arc4random_stir(void);\n\n void\n arc4random_addrandom(unsigned char *dat, int datlen);\n\nDESCRIPTION\n The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8\n bit S-Boxes. The S-Boxes can be in about (2**1700) states. The arc4random() function returns pseudo-\n random numbers in the range of 0 to (2**32)-1, and therefore has twice the range of rand(3) and\n random(3).\n\n The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via\n arc4random_addrandom().\n\n There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically\n initializes itself.\n\nEXAMPLES\n The following produces a drop-in replacement for the traditional rand() and random() functions using\n arc4random():\n\n #define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1))\n"
},
{
"answer_id": 2151334,
"author": "Eli",
"author_id": 117588,
"author_profile": "https://Stackoverflow.com/users/117588",
"pm_score": 4,
"selected": false,
"text": "//Random.h\nvoid initRandomSeed(long firstSeed);\nfloat nextRandomFloat();\n //Random.m\nstatic unsigned long seed;\n\nvoid initRandomSeed(long firstSeed)\n{ \n seed = firstSeed;\n}\n\nfloat nextRandomFloat()\n{\n return (((seed= 1664525*seed + 1013904223)>>16) / (float)0x10000);\n}\n #import \"Random.h\"\n\n- (void)applicationDidFinishLaunching:(UIApplication *)application\n{\n initRandomSeed( (long) [[NSDate date] timeIntervalSince1970] );\n //Do other initialization junk.\n}\n float myRandomNumber = nextRandomFloat() * 74;\n"
},
{
"answer_id": 7082580,
"author": "yood",
"author_id": 31605,
"author_profile": "https://Stackoverflow.com/users/31605",
"pm_score": 9,
"selected": false,
"text": "arc4random_uniform(upper_bound) arc4random_uniform(74)\n arc4random_uniform(upper_bound)"
},
{
"answer_id": 9310745,
"author": "Tibidabo",
"author_id": 649610,
"author_profile": "https://Stackoverflow.com/users/649610",
"pm_score": 5,
"selected": false,
"text": "float low_bound = 0; \nfloat high_bound = 47;\nfloat rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);\n float rndValue = (((float)arc4random()/0x100000000)*47);\n float low_bound = -35.76; \nfloat high_bound = 12.09;\nfloat rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);\n int intRndValue = (int)(rndValue + 0.5);\n"
},
{
"answer_id": 11101096,
"author": "AW101",
"author_id": 1321931,
"author_profile": "https://Stackoverflow.com/users/1321931",
"pm_score": 5,
"selected": false,
"text": "arc4random_uniform arc4random_uniform #include <stdlib.h>\n\nint r = 0;\nif (arc4random_uniform != NULL)\n r = arc4random_uniform (74);\nelse\n r = (arc4random() % 74);\n"
},
{
"answer_id": 17193450,
"author": "Groot",
"author_id": 1075405,
"author_profile": "https://Stackoverflow.com/users/1075405",
"pm_score": 6,
"selected": false,
"text": "- (NSInteger)randomValueBetween:(NSInteger)min and:(NSInteger)max {\n return (NSInteger)(min + arc4random_uniform(max - min + 1));\n}\n #define RAND_FROM_TO(min, max) (min + arc4random_uniform(max - min + 1))\n NSInteger myInteger = RAND_FROM_TO(0, 74) // 0, 1, 2,..., 73, 74\n"
},
{
"answer_id": 28693353,
"author": "adijazz91",
"author_id": 3820802,
"author_profile": "https://Stackoverflow.com/users/3820802",
"pm_score": 2,
"selected": false,
"text": "int x = arc4random()%100;\n int x = (arc4random()%501) + 500;\n"
},
{
"answer_id": 30171545,
"author": "Tom Howard",
"author_id": 1803879,
"author_profile": "https://Stackoverflow.com/users/1803879",
"pm_score": 3,
"selected": false,
"text": "arc4random_uniform(75)"
},
{
"answer_id": 32840929,
"author": "soumya",
"author_id": 4169569,
"author_profile": "https://Stackoverflow.com/users/4169569",
"pm_score": 2,
"selected": false,
"text": "int value;\nvalue = (arc4random() % 74);\nNSLog(@\"random number: %i \", value);\n\n//In order to generate 1 to 73, do the following:\nint value1;\nvalue1 = (arc4random() % 73) + 1;\nNSLog(@\"random number step 2: %i \", value1);\n"
},
{
"answer_id": 34371277,
"author": "TwoStraws",
"author_id": 5041820,
"author_profile": "https://Stackoverflow.com/users/5041820",
"pm_score": 2,
"selected": false,
"text": "NSInteger rand = [[GKRandomSource sharedRandom] nextInt];\n NSInteger rand6 = [[GKRandomSource sharedRandom] nextIntWithUpperBound:6];\n GKRandomDistribution *d6 = [GKRandomDistribution d6];\n[d6 nextInt];\n GKShuffledDistribution"
},
{
"answer_id": 38388107,
"author": "Robert Wasmann",
"author_id": 1927253,
"author_profile": "https://Stackoverflow.com/users/1927253",
"pm_score": 1,
"selected": false,
"text": "static inline int random_range(int low, int high){ return (random()%(high-low+1))+low;}\nstatic inline CGFloat frandom(){ return (CGFloat)random()/UINT32_C(0x7FFFFFFF);}\nstatic inline CGFloat frandom_range(CGFloat low, CGFloat high){ return (high-low)*frandom()+low;}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6044/"
] |
160,904
|
<p>I have to write a component that re-creates SQL Server tables (structure and data) in an Oracle database. This component also has to take new data entered into the Oracle database and copy it back into SQL Server.</p>
<p>Translating the data types from SQL Server to Oracle is not a problem. However, a critical difference between Oracle and SQL Server is causing a major headache. SQL Server considers a blank string ("") to be different from a <code>NULL</code> value, so a <code>char</code> column can be defined as <code>NOT NULL</code> and yet still include blank strings in the data.</p>
<p>Oracle considers a blank string to be the same as a <code>NULL</code> value, so if a <code>char</code> column is defined as <code>NOT NULL</code>, you cannot insert a blank string. This is causing my component to break whenever a <code>NOT NULL</code> char column contains a blank string in the original SQL Server data.</p>
<p>So far my solution has been to not use <code>NOT NULL</code> in any of my mirror Oracle table definitions, but I need a more robust solution. This has to be a code solution, so the answer can't be "use so-and-so's SQL2Oracle product".</p>
<p>How would you solve this problem?</p>
<p>Edit: here is the only solution I've come up with so far, and it may help to illustrate the problem. Because Oracle doesn't allow "" in a NOT NULL column, my component could intercept any such value coming from SQL Server and replace it with "@" (just for example).</p>
<p>When I add a new record to my Oracle table, my code has to write "@" if I really want to insert a "", and when my code copies the new row back to SQL Server, it has to intercept the "@" and instead write "".</p>
<p>I'm hoping there's a more elegant way.</p>
<p>Edit 2: Is it possible that there's a simpler solution, like some setting in Oracle that gets it to treat blank strings the same as all the other major database? And would this setting also be available in Oracle Lite?</p>
|
[
{
"answer_id": 160933,
"author": "Camilo Díaz Repka",
"author_id": 861,
"author_profile": "https://Stackoverflow.com/users/861",
"pm_score": 4,
"selected": true,
"text": "-> ' '"
},
{
"answer_id": 161001,
"author": "Dr8k",
"author_id": 6014,
"author_profile": "https://Stackoverflow.com/users/6014",
"pm_score": 3,
"selected": false,
"text": "CREATE TABLE Example (StringColumn VARCHAR(10) NOT NULL)\n\nALTER TABLE Example\nADD CONSTRAINT CK_Example_StringColumn CHECK (LEN(StringColumn) > 0)\n"
},
{
"answer_id": 161377,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 2,
"selected": false,
"text": "drop table x\n\ndrop table x succeeded.\ncreate table x ( id number, my_varchar varchar2(10))\n\ncreate table succeeded.\ninsert into x values (1, chr(0))\n\n1 rows inserted\ninsert into x values (2, null)\n\n1 rows inserted\nselect id,length(my_varchar) from x\n\nID LENGTH(MY_VARCHAR) \n---------------------- ---------------------- \n1 1 \n2 \n\n2 rows selected\n\nselect * from x where my_varchar is not null\n\nID MY_VARCHAR \n---------------------- ---------- \n1 \n"
},
{
"answer_id": 28301120,
"author": "Ditto",
"author_id": 2157378,
"author_profile": "https://Stackoverflow.com/users/2157378",
"pm_score": 0,
"selected": false,
"text": " SQL> drop table junk;\n\n Table dropped.\n\n SQL>\n SQL> create table junk ( c1 char(5) not null );\n\n Table created.\n\n SQL>\n SQL> insert into junk values ( 'hi' );\n\n 1 row created.\n\n SQL>\n SQL> insert into junk values ( ' ' );\n\n 1 row created.\n\n SQL>\n SQL> insert into junk values ( '' );\n insert into junk values ( '' )\n *\n ERROR at line 1:\n ORA-01400: cannot insert NULL into (\"GREGS\".\"JUNK\".\"C1\")\n\n\n SQL>\n SQL> insert into junk values ( rpad('', 5, ' ') );\n insert into junk values ( rpad('', 5, ' ') )\n *\n ERROR at line 1:\n ORA-01400: cannot insert NULL into (\"GREGS\".\"JUNK\".\"C1\")\n\n\n SQL>\n SQL> declare\n 2 lv_in varchar2(5) := '';\n 3 begin\n 4 insert into junk values ( rpad(lv_in||' ', 5) );\n 5 end;\n 6 /\n\n PL/SQL procedure successfully completed.\n\n SQL>\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14606/"
] |
160,905
|
<p>I'm working on what I think is a pretty standard django site, but am having trouble getting my admin section to display the proper fields.</p>
<p>Here's my models.py:</p>
<pre><code>class Tech(models.Model):
name = models.CharField(max_length = 30)
class Project(models.Model):
title = models.CharField(max_length = 50)
techs = models.ManyToManyField(Tech)
</code></pre>
<p>In other words, a Project can have different Tech objects and different tech objects can belong to different Projects (Project X was created with Python and Django, Project Y was C# and SQL Server)</p>
<p>However, the admin site doesn't display any UI for the Tech objects. Here's my admin.py:</p>
<pre><code>class TechInline(admin.TabularInline):
model = Tech
extra = 5
class ProjectAdmin(admin.ModelAdmin):
fields = ['title']
inlines = []
list_display = ('title')
admin.site.register(Project, ProjectAdmin)
</code></pre>
<p>I've tried adding the <code>TechInline</code> class to the <code>inlines</code> list, but that causes a </p>
<pre><code><class 'home.projects.models.Tech'> has no ForeignKey to <class 'home.projects.models.Project'>
</code></pre>
<p>Error. Also tried adding <code>techs</code> to the <code>fields</code> list, but that gives a </p>
<blockquote>
<p>no such table: projects_project_techs</p>
</blockquote>
<p>Error. I verified, and there is no <code>projects_project_techs</code> table, but there is a <code>projects_tech</code> one. Did something perhaps get screwed up in my syncdb? </p>
<p>I am using Sqlite as my database if that helps.</p>
|
[
{
"answer_id": 160916,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": true,
"text": "TechInline TechInLine python manage.py sqlreset <myapp>\n projects_project_techs"
},
{
"answer_id": 162932,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 0,
"selected": false,
"text": "projects_project_techs techs admin.site.register(Tech)"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
] |
160,923
|
<p>I am pretty sure I have seen this before, but I haven't found out / remembered how to do it. I want to have a line of code that when executed from the Delphi debugger I want the debugger to pop-up like there was a break point on that line. </p>
<p>Something like:</p>
<pre><code>FooBar := Foo(Bar);
SimulateBreakPoint; // Cause break point to occur in Delphi IDE if attached
WriteLn('Value: ' + FooBar);
</code></pre>
<p>Hopefully that makes sense. I know I could use an exception, but that would be a lot more overhead then I want. It is for some demonstration code.</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 160993,
"author": "Joeri Sebrechts",
"author_id": 20980,
"author_profile": "https://Stackoverflow.com/users/20980",
"pm_score": 6,
"selected": true,
"text": "asm int 3 end;\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/255/"
] |
160,924
|
<p>Sometimes when I try to start Firefox it says "a Firefox process is already running". So I have to do this:</p>
<pre><code>jeremy@jeremy-desktop:~$ ps aux | grep firefox
jeremy 7451 25.0 27.4 170536 65680 ? Sl 22:39 1:18 /usr/lib/firefox-3.0.1/firefox
jeremy 7578 0.0 0.3 3004 768 pts/0 S+ 22:44 0:00 grep firefox
jeremy@jeremy-desktop:~$ kill 7451
</code></pre>
<p>What I'd like is a command that would do all that for me. It would take an input string and <code>grep</code> for it (or whatever) in the list of processes, and would kill all the processes in the output:</p>
<pre><code>jeremy@jeremy-desktop:~$ killbyname firefox
</code></pre>
<p>I tried doing it in PHP but <code>exec('ps aux')</code> seems to only show processes that have been executed with <code>exec()</code> in the PHP script itself (so the only process it shows is itself.)</p>
|
[
{
"answer_id": 160926,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 10,
"selected": true,
"text": "pkill firefox\n"
},
{
"answer_id": 160928,
"author": "Bittercoder",
"author_id": 4843,
"author_profile": "https://Stackoverflow.com/users/4843",
"pm_score": 3,
"selected": false,
"text": "killall"
},
{
"answer_id": 160950,
"author": "Andre Bossard",
"author_id": 21027,
"author_profile": "https://Stackoverflow.com/users/21027",
"pm_score": 6,
"selected": false,
"text": "killall <name> ps aux"
},
{
"answer_id": 163335,
"author": "Walter",
"author_id": 23840,
"author_profile": "https://Stackoverflow.com/users/23840",
"pm_score": 6,
"selected": false,
"text": "kill `pidof firefox`\n"
},
{
"answer_id": 15014271,
"author": "Dhiraj",
"author_id": 1701261,
"author_profile": "https://Stackoverflow.com/users/1701261",
"pm_score": 4,
"selected": false,
"text": "export pid=`ps | grep process_name | awk 'NR==1{print $1}' | cut -d' ' -f1`;kill $pid\n"
},
{
"answer_id": 16621797,
"author": "user2396265",
"author_id": 2396265,
"author_profile": "https://Stackoverflow.com/users/2396265",
"pm_score": 4,
"selected": false,
"text": "killall killall processname\n -9 -KILL kill"
},
{
"answer_id": 23823738,
"author": "Chadiso",
"author_id": 1847117,
"author_profile": "https://Stackoverflow.com/users/1847117",
"pm_score": 3,
"selected": false,
"text": "export pid=`ps aux | grep process_name | awk 'NR==1{print $2}' | cut -d' ' -f1`;kill -9 $pid\n"
},
{
"answer_id": 26938108,
"author": "JayS",
"author_id": 1812942,
"author_profile": "https://Stackoverflow.com/users/1812942",
"pm_score": 3,
"selected": false,
"text": "kill -9 `pgrep myprocess`\n"
},
{
"answer_id": 27820938,
"author": "Victor",
"author_id": 3029603,
"author_profile": "https://Stackoverflow.com/users/3029603",
"pm_score": 8,
"selected": false,
"text": "pkill -f \"Process name\"\n -f"
},
{
"answer_id": 34290551,
"author": "The Vee",
"author_id": 1537925,
"author_profile": "https://Stackoverflow.com/users/1537925",
"pm_score": 2,
"selected": false,
"text": "kill bash kill kill %1 bash enable -n kill kill enable"
},
{
"answer_id": 35555148,
"author": "Fab",
"author_id": 5328150,
"author_profile": "https://Stackoverflow.com/users/5328150",
"pm_score": 2,
"selected": false,
"text": "#!/bin/sh\n\nkillables=$(ps aux | grep $1 | grep -v mykill | grep -v grep)\nif [ ! \"${killables}\" = \"\" ]\nthen\n echo \"You are going to kill some process:\"\n echo \"${killables}\"\nelse\n echo \"No process with the pattern $1 found.\"\n return\nfi\necho -n \"Is it ok?(Y/N)\"\nread input\nif [ \"$input\" = \"Y\" ]\nthen\n for pid in $(echo \"${killables}\" | awk '{print $2}')\n do\n echo killing $pid \"...\"\n kill $pid \n echo $pid killed\n done\nfi\n"
},
{
"answer_id": 37167657,
"author": "query_port",
"author_id": 6226193,
"author_profile": "https://Stackoverflow.com/users/6226193",
"pm_score": 0,
"selected": false,
"text": "ps aux | grep processname | cut -d' ' -f7 | xargs kill -9 $\n"
},
{
"answer_id": 38337778,
"author": "Tahsin Turkoz",
"author_id": 3618397,
"author_profile": "https://Stackoverflow.com/users/3618397",
"pm_score": 6,
"selected": false,
"text": "pgrep -f [part_of_a_command]\n pkill -f [part_of_a_command]\n kill -9 $(pgrep -f [part_of_a_command])\n -u pkill -f [part_of_a_command] -u [username]\n"
},
{
"answer_id": 39821265,
"author": "prosti",
"author_id": 5884955,
"author_profile": "https://Stackoverflow.com/users/5884955",
"pm_score": 5,
"selected": false,
"text": "kill -9 `pidof firefox`\n kill -9 `pgrep firefox`\n pidof > pgrep firefox\n6316\n6565\n> pidof firefox\n6565 6316\n"
},
{
"answer_id": 43232096,
"author": "Mike",
"author_id": 448078,
"author_profile": "https://Stackoverflow.com/users/448078",
"pm_score": 5,
"selected": false,
"text": "snippet ps ax | grep <snippet> | grep -v grep | awk '{print $1}' | xargs kill\n"
},
{
"answer_id": 56791395,
"author": "Andrey Bochkov",
"author_id": 3629114,
"author_profile": "https://Stackoverflow.com/users/3629114",
"pm_score": 0,
"selected": false,
"text": "ps ps -fe | awk 'NR==1{for (i=1; i<=NF; i++) {if ($i==\"COMMAND\") Ncmd=i; else if ($i==\"PID\") Npid=i} if (!Ncmd || !Npid) {print \"wrong or no header\" > \"/dev/stderr\"; exit} }$Ncmd~\"/\"name\"$\"{print \"killing \"$Ncmd\" with PID \" $Npid; system(\"kill \"$Npid)}' name=.*firefox.*\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813/"
] |
160,930
|
<p>How can I check if a given number is even or odd in C?</p>
|
[
{
"answer_id": 160935,
"author": "Chris Young",
"author_id": 9417,
"author_profile": "https://Stackoverflow.com/users/9417",
"pm_score": 10,
"selected": true,
"text": "if (x % 2) { /* x is odd */ }\n /* modulo.c */\n#include <stdio.h>\n\nint main(void)\n{\n int x;\n for (x = 0; x < 10; x++)\n if (x % 2)\n printf(\"%d is odd\\n\", x);\n return 0;\n}\n\n/* and.c */\n#include <stdio.h>\n\nint main(void)\n{\n int x;\n for (x = 0; x < 10; x++)\n if (x & 1)\n printf(\"%d is odd\\n\", x);\n return 0;\n}\n"
},
{
"answer_id": 160936,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "i % 2 == 0\n"
},
{
"answer_id": 160942,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 7,
"selected": false,
"text": "if((x & 1) == 0)\n printf(\"EVEN!\\n\");\nelse\n printf(\"ODD!\\n\");\n"
},
{
"answer_id": 160944,
"author": "Michael Petrotta",
"author_id": 23897,
"author_profile": "https://Stackoverflow.com/users/23897",
"pm_score": 3,
"selected": false,
"text": "// C#\nbool isEven = ((i % 2) == 0);\n"
},
{
"answer_id": 160958,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 4,
"selected": false,
"text": "// Java\npublic static boolean isOdd(int num){\n return num % 2 != 0;\n}\n\n/* C */\nint isOdd(int num){\n return num % 2;\n}\n"
},
{
"answer_id": 161049,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 8,
"selected": false,
"text": "public boolean isOdd(int num) {\n int i = 0;\n boolean odd = false;\n\n while (i != num) {\n odd = !odd;\n i = i + 1;\n }\n\n return odd;\n}\n isEven"
},
{
"answer_id": 161066,
"author": "eugensk",
"author_id": 17495,
"author_profile": "https://Stackoverflow.com/users/17495",
"pm_score": 3,
"selected": false,
"text": "bool isEven(unsigned int x)\n{\n unsigned int half1 = 0, half2 = 0;\n while (x)\n {\n if (x) { half1++; x--; }\n if (x) { half2++; x--; }\n\n }\n return half1 == half2;\n}\n"
},
{
"answer_id": 161326,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 4,
"selected": false,
"text": "isEven = (x & 1);\n isEven = (x & 1) ^ ((-1 & 1) | ((x < 0) ? 0 : 1)));\n"
},
{
"answer_id": 161558,
"author": "Pierre",
"author_id": 24449,
"author_profile": "https://Stackoverflow.com/users/24449",
"pm_score": 4,
"selected": false,
"text": "/*forward declaration, C compiles in one pass*/\nbool isOdd(unsigned int n);\n\nbool isEven(unsigned int n)\n{\n if (n == 0) \n return true ; // I know 0 is even\n else\n return isOdd(n-1) ; // n is even if n-1 is odd\n}\n\nbool isOdd(unsigned int n)\n{\n if (n == 0)\n return false ;\n else\n return isEven(n-1) ; // n is odd if n-1 is even\n}\n"
},
{
"answer_id": 161739,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 2,
"selected": false,
"text": "public static class RudiGroblerExtensions\n{\n public static bool IsOdd(this int i)\n {\n return ((i % 2) != 0);\n }\n}\n int i = 5;\nif (i.IsOdd())\n{\n // Do something...\n}\n"
},
{
"answer_id": 161842,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 5,
"selected": false,
"text": "public enum Evenness\n{\n Unknown = 0,\n Even = 1,\n Odd = 2\n}\n\npublic static Evenness AnalyzeEvenness(object o)\n{\n\n if (o == null)\n return Evenness.Unknown;\n\n string foo = o.ToString();\n\n if (String.IsNullOrEmpty(foo))\n return Evenness.Unknown;\n\n char bar = foo[foo.Length - 1];\n\n switch (bar)\n {\n case '0':\n case '2':\n case '4':\n case '6':\n case '8':\n return Evenness.Even;\n case '1':\n case '3':\n case '5':\n case '7':\n case '9':\n return Evenness.Odd;\n default:\n return Evenness.Unknown;\n }\n}\n"
},
{
"answer_id": 162869,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 2,
"selected": false,
"text": "i % 2 ? odd : even;\n i & 1 ? odd : even;\n\ni << (BITS_PER_INT - 1) ? odd : even;\n"
},
{
"answer_id": 163188,
"author": "Tooony",
"author_id": 23864,
"author_profile": "https://Stackoverflow.com/users/23864",
"pm_score": 0,
"selected": false,
"text": "void tellMeIfItIsAnOddNumberPlease(int iToTest){\n int iLastDigit;\n iLastDigit = iToTest - (iToTest / 10 * 10);\n if (iLastDigit % 2 == 0){\n printf(\"The number %d is even!\\n\", iToTest);\n } else {\n printf(\"The number %d is odd!\\n\", iToTest);\n }\n}\n printf(\"%d%s\\n\",iToTest,0==(iToTest-iToTest/10*10)%2?\" is even\":\" is odd\");\n if (iToTest & 1) {\n // Even\n} else {\n // Odd\n}\n"
},
{
"answer_id": 166368,
"author": "Vihung",
"author_id": 15452,
"author_profile": "https://Stackoverflow.com/users/15452",
"pm_score": 0,
"selected": false,
"text": "x & 1 x % 2"
},
{
"answer_id": 168834,
"author": "DocMax",
"author_id": 6234,
"author_profile": "https://Stackoverflow.com/users/6234",
"pm_score": 2,
"selected": false,
"text": "int isOdd(int n) { return n ^ n * n ? isOdd(n * n) : n; }\n __declspec(naked) bool __fastcall isOdd(const int x)\n{\n __asm\n {\n mov eax,ecx\n mul eax\n mul eax\n mul eax\n mul eax\n mul eax\n mul eax\n ret\n }\n}\n"
},
{
"answer_id": 198057,
"author": "None",
"author_id": 25012,
"author_profile": "https://Stackoverflow.com/users/25012",
"pm_score": 1,
"selected": false,
"text": "int isOdd(int i){\n return(i % 2);\n}\n"
},
{
"answer_id": 2345243,
"author": "Thomas Eding",
"author_id": 239916,
"author_profile": "https://Stackoverflow.com/users/239916",
"pm_score": 3,
"selected": false,
"text": "typedef unsigned int uint;\n\nchar parity_uint [UINT_MAX];\nchar parity_sint_shifted [((uint) INT_MAX) + ((uint) abs (INT_MIN))];\nchar* parity_sint = parity_sint_shifted - INT_MIN;\n\nvoid build_parity_tables () {\n char parity = 0;\n unsigned int ui;\n for (ui = 1; ui <= UINT_MAX; ++ui) {\n parity_uint [ui - 1] = parity;\n parity = !parity;\n }\n parity = 0;\n int si;\n for (si = 1; si <= INT_MAX; ++si) {\n parity_sint [si - 1] = parity;\n parity = !parity;\n }\n parity = 1;\n for (si = -1; si >= INT_MIN; --si) {\n parity_sint [si] = parity;\n parity = !parity;\n }\n}\n\nchar uparity (unsigned int n) {\n if (n == 0) {\n return 0;\n }\n return parity_uint [n - 1];\n}\n\nchar sparity (int n) {\n if (n == 0) {\n return 0;\n }\n if (n < 0) {\n ++n;\n }\n return parity_sint [n - 1];\n}\n char even (int n) {\n int k;\n for (k = INT_MIN; k <= INT_MAX; ++k) {\n if (n == 2 * k) {\n return 1;\n }\n }\n return 0;\n}\n\nchar odd (int n) {\n int k;\n for (k = INT_MIN; k <= INT_MAX; ++k) {\n if (n == 2 * k + 1) {\n return 1;\n }\n }\n return 0;\n}\n int even even even odd"
},
{
"answer_id": 10357149,
"author": "Thomas Eding",
"author_id": 239916,
"author_profile": "https://Stackoverflow.com/users/239916",
"pm_score": 2,
"selected": false,
"text": "public static boolean isEven (Integer Number) {\n Pattern number = Pattern.compile(\"^.*?(?:[02]|8|(?:6|4))$\");\n String num = Number.toString(Number);\n Boolean numbr = new Boolean(number.matcher(num).matches());\n return numbr.booleanValue();\n}\n"
},
{
"answer_id": 16369720,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "static dbl IntPow(dbl st0, int x) {\n UINT OrMask = UINT_MAX -1;\n dbl st1=1.0;\n if(0==x) return (dbl)1.0;\n\n while(1 != x) {\n if (UINT_MAX == (x|OrMask)) { // if LSB is 1... \n //if(x & 1) {\n //if(x % 2) {\n st1 *= st0;\n } \n x = x >> 1; // shift x right 1 bit... \n st0 *= st0;\n }\n return st1 * st0;\n}\n"
},
{
"answer_id": 18744262,
"author": "Astridax",
"author_id": 1392407,
"author_profile": "https://Stackoverflow.com/users/1392407",
"pm_score": 1,
"selected": false,
"text": "if(number & 1){\n\n //Number is odd\n\n} else {\n\n //Number is even\n}\n"
},
{
"answer_id": 21777983,
"author": "Kiril Aleksandrov",
"author_id": 2243615,
"author_profile": "https://Stackoverflow.com/users/2243615",
"pm_score": 2,
"selected": false,
"text": "return (((a>>1)<<1) == a) a = 10101011\n-----------------\na>>1 --> 01010101\na<<1 --> 10101010\n\nb = 10011100\n-----------------\nb>>1 --> 01001110\nb<<1 --> 10011100\n"
},
{
"answer_id": 24649002,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "if (x % 2 == 0)\n total += 1; //even number\n else\n total -= 1; //odd number\n if ((x & 1) == 0)\n total += 1; //even number\n else\n total -= 1; //odd number\n\nSystem.Math.DivRem((long)x, (long)2, out outvalue);\n if ( outvalue == 0)\n total += 1; //even number\n else\n total -= 1; //odd number\n\nif (((x / 2) * 2) == x)\n total += 1; //even number\n else\n total -= 1; //odd number\n\nif (((x >> 1) << 1) == x)\n total += 1; //even number\n else\n total -= 1; //odd number\n\n while (index > 1)\n index -= 2;\n if (index == 0)\n total += 1; //even number\n else\n total -= 1; //odd number\n\ntempstr = x.ToString();\n index = tempstr.Length - 1;\n //this assumes base 10\n if (tempstr[index] == '0' || tempstr[index] == '2' || tempstr[index] == '4' || tempstr[index] == '6' || tempstr[index] == '8')\n total += 1; //even number\n else\n total -= 1; //odd number\n"
},
{
"answer_id": 30701091,
"author": "Pankaj Prakash",
"author_id": 2401088,
"author_profile": "https://Stackoverflow.com/users/2401088",
"pm_score": 0,
"selected": false,
"text": "% if(num%2 ==0) \n{\n printf(\"Even\");\n}\nelse\n{\n printf(\"Odd\");\n}\n (num%2 ==0) printf(\"Even\") : printf(\"Odd\");\n if(num & 1) \n{\n printf(\"Odd\");\n}\nelse \n{\n printf(\"Even\");\n}\n"
},
{
"answer_id": 32693856,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "# defining function for number parity check\ndef parity(number):\n \"\"\"Parity check function\"\"\"\n # if number is 0 (zero) return 'Zero neither ODD nor EVEN',\n # otherwise number&1, checking last bit, if 0, then EVEN, \n # if 1, then ODD.\n return (number == 0 and 'Zero neither ODD nor EVEN') \\\n or (number&1 and 'ODD' or 'EVEN')\n\n# cycle trough numbers from 0 to 13 \nfor number in range(0, 14):\n print \"{0:>4} : {0:08b} : {1:}\".format(number, parity(number))\n 0 : 00000000 : Zero neither ODD nor EVEN\n 1 : 00000001 : ODD\n 2 : 00000010 : EVEN\n 3 : 00000011 : ODD\n 4 : 00000100 : EVEN\n 5 : 00000101 : ODD\n 6 : 00000110 : EVEN\n 7 : 00000111 : ODD\n 8 : 00001000 : EVEN\n 9 : 00001001 : ODD\n 10 : 00001010 : EVEN\n 11 : 00001011 : ODD\n 12 : 00001100 : EVEN\n 13 : 00001101 : ODD\n"
},
{
"answer_id": 37248465,
"author": "Moinak Debnath",
"author_id": 4061847,
"author_profile": "https://Stackoverflow.com/users/4061847",
"pm_score": -1,
"selected": false,
"text": "#include <stdio.h>\nint main()\n{\n int n;//using modulus operator\n scanf(\"%d\",&n);//take input n from STDIN \n printf(\"%s\",n%2==0?\"Even\":\"Odd\");//prints Even/Odd depending on n to STDOUT\n return 0;\n}\n 1111\n 0001\n &-----\n 0001\n 1000\n 0001\n &-----\n 0000\n #include <stdio.h>\n\nint main()\n{\n int n;//using AND operator\n scanf(\"%d\",&n);//take input n from STDIN \n printf(\"%s\",n&1?\"Odd\":\"Even\");//prints Even/Odd depending on n to STDOUT\n return 0;\n}\n"
},
{
"answer_id": 40040733,
"author": "Lou",
"author_id": 1488067,
"author_profile": "https://Stackoverflow.com/users/1488067",
"pm_score": 2,
"selected": false,
"text": "(0xFFFFFFFF == (x | 0xFFFFFFFE) x & 1 mod int isOdd_mod(unsigned x) {\n return (x % 2);\n}\n\nint isOdd_and(unsigned x) {\n return (x & 1);\n}\n\nint isOdd_or(unsigned x) {\n return (0xFFFFFFFF == (x | 0xFFFFFFFE));\n} \n isOdd_mod(unsigned int): # @isOdd_mod(unsigned int)\n and edi, 1\n mov eax, edi\n ret\n\nisOdd_and(unsigned int): # @isOdd_and(unsigned int)\n and edi, 1\n mov eax, edi\n ret\n\nisOdd_or(unsigned int): # @isOdd_or(unsigned int)\n and edi, 1\n mov eax, edi\n ret\n isOdd_mod(unsigned int):\n mov eax, edi\n and eax, 1\n ret\n\nisOdd_and(unsigned int):\n mov eax, edi\n and eax, 1\n ret\n\nisOdd_or(unsigned int):\n or edi, -2\n xor eax, eax\n cmp edi, -1\n sete al\n ret\n // x % 2\ntest bl,1 \nje (some address) \n\n// x & 1\ntest bl,1 \nje (some address) \n\n// Roy's bitwise or\nmov eax,ebx \nor eax,0FFFFFFFEh \ncmp eax,0FFFFFFFFh \njne (some address)\n test and mod cmp eax,0FFFFFFFFh #if LINUX get_time #include <stdio.h>\n\n#if LINUX\n#include <sys/time.h>\n#include <sys/resource.h>\ndouble get_time()\n{\n struct timeval t;\n struct timezone tzp;\n gettimeofday(&t, &tzp);\n return t.tv_sec + t.tv_usec*1e-6;\n}\n#else\n#include <windows.h>\ndouble get_time()\n{\n LARGE_INTEGER t, f;\n QueryPerformanceCounter(&t);\n QueryPerformanceFrequency(&f);\n return (double)t.QuadPart / (double)f.QuadPart * 1000.0;\n}\n#endif\n\n#define NUM_ITERATIONS (1000 * 1000 * 1000)\n\n// using a macro to avoid function call overhead\n#define Benchmark(accumulator, name, operation) { \\\n double startTime = get_time(); \\\n double dummySum = 0.0, elapsed; \\\n int x; \\\n for (x = 0; x < NUM_ITERATIONS; x++) { \\\n if (operation) dummySum += x; \\\n } \\\n elapsed = get_time() - startTime; \\\n accumulator += elapsed; \\\n if (dummySum > 2000) \\\n printf(\"[Test: %-12s] %0.2f ms\\r\\n\", name, elapsed); \\\n}\n\nvoid DumpAverage(char *test, double totalTime, double reference)\n{\n printf(\"[Test: %-12s] AVERAGE TIME: %0.2f ms (Relative diff.: %+6.3f%%)\\r\\n\",\n test, totalTime, (totalTime - reference) / reference * 100.0);\n}\n\nint main(void)\n{\n int repeats = 20;\n double runningTimes[3] = { 0 };\n int k;\n\n for (k = 0; k < repeats; k++) {\n printf(\"Run %d of %d...\\r\\n\", k + 1, repeats);\n Benchmark(runningTimes[0], \"Plain mod 2\", (x % 2));\n Benchmark(runningTimes[1], \"Bitwise or\", (0xFFFFFFFF == (x | 0xFFFFFFFE)));\n Benchmark(runningTimes[2], \"Bitwise and\", (x & 1));\n }\n\n {\n double reference = runningTimes[0] / repeats;\n printf(\"\\r\\n\");\n DumpAverage(\"Plain mod 2\", runningTimes[0] / repeats, reference);\n DumpAverage(\"Bitwise or\", runningTimes[1] / repeats, reference);\n DumpAverage(\"Bitwise and\", runningTimes[2] / repeats, reference);\n }\n\n getchar();\n\n return 0;\n}\n"
},
{
"answer_id": 45432795,
"author": "Omar Faruk",
"author_id": 5778851,
"author_profile": "https://Stackoverflow.com/users/5778851",
"pm_score": 1,
"selected": false,
"text": "I execute this code for ODD & EVEN:\n\n#include <stdio.h>\nint main()\n{\n int number;\n printf(\"Enter an integer: \");\n scanf(\"%d\", &number);\n\n if(number % 2 == 0)\n printf(\"%d is even.\", number);\n else\n printf(\"%d is odd.\", number);\n}\n"
},
{
"answer_id": 50072690,
"author": "Beyondo",
"author_id": 8524922,
"author_profile": "https://Stackoverflow.com/users/8524922",
"pm_score": 0,
"selected": false,
"text": "!(i%2) / i%2 == 0 int isOdd(int n)\n{\n return n & 1;\n}\n Binary : Decimal\n-------------------\n0000 = 0\n0001 = 1\n0010 = 2\n0011 = 3\n0100 = 4\n0101 = 5\n0110 = 6\n0111 = 7\n1000 = 8\n1001 = 9\nand so on...\n 0001 7 (1-byte int)| 0 0 0 0 0 1 1 1\n &\n1 (1-byte int)| 0 0 0 0 0 0 0 1\n********************************************\nResult | F F F F F F F T\n 7 & 1 n & 1 n & 2 0010 return n & 1; return n & 0x01;"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24391/"
] |
160,954
|
<p>I have a Rails project which has a Postgres database for the actual application but which needs to pull a heck of a lot of data out of an Oracle database. </p>
<p>database.yml looks like</p>
<pre><code>development:
adapter: postgresql
database: blah blah
...
oracle_db:
adapter: oracle
database: blah blah
</code></pre>
<p>My models which descend from data on the Oracle DB look something like </p>
<pre><code>class LegacyDataClass < ActiveRecord::Base
establish_connection "oracle_db"
set_primary_key :legacy_data_class_id
has_one :other_legacy_class, :foreign key => :other_legacy_class_id_with_funny_column_name
...
end
</code></pre>
<p>Now, by habit I often do a lot of my early development (and this is early development) by coding for a bit and then playing in the Rails console. For example, after defining all the associations for LegacyDataClass I'll start trying things like <code>a = LegacyDataClass.find(:first); puts a.some_association.name</code>. Unexpectedly, this dies with LegacyDataClass not being already loaded. </p>
<p>I can then <code>require 'LegacyDataClass'</code> which fixes the problem until I either need to <code>reload!</code>, which won't actually reload it, or until I open a new instance of the console.</p>
<p>Thus the questions:</p>
<ul>
<li><strong>Why</strong> does this happen? Clearly there is some Rails magic I am not understanding.</li>
<li>What is the convenient Rails <strong>workaround</strong>?</li>
</ul>
|
[
{
"answer_id": 160989,
"author": "James Baker",
"author_id": 9365,
"author_profile": "https://Stackoverflow.com/users/9365",
"pm_score": 3,
"selected": true,
"text": "models/legacy_model.rb \"require 'LegacyDataClass'\""
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15046/"
] |
160,960
|
<p>I have a function that takes a struct, and I'm trying to store its variables in array:</p>
<pre><code>int detect_prm(Param prm) {
int prm_arr[] = {prm.field1, prm.field2, prm.field3};
return 0;
}
</code></pre>
<p>But with <code>gcc -Wall -ansi -pedantic-errors -Werror</code> I get the following error:</p>
<blockquote>
<p>initializer element is not computable at load time</p>
</blockquote>
<p>It looks fine to me, what's wrong?</p>
|
[
{
"answer_id": 160969,
"author": "Mike Thompson",
"author_id": 2754,
"author_profile": "https://Stackoverflow.com/users/2754",
"pm_score": 5,
"selected": true,
"text": "int prm_arr[3];\n\nprm_arr[0] = prm.field1;\nprm_arr[1] = prm.field2;\nprm_arr[2] = prm.field3;\n"
},
{
"answer_id": 161019,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 4,
"selected": false,
"text": "--std=c99"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628/"
] |
160,970
|
<p>If I have two variables:</p>
<pre><code>Object obj;
String methodName = "getName";
</code></pre>
<p>Without knowing the class of <code>obj</code>, how can I call the method identified by <code>methodName</code> on it?</p>
<p>The method being called has no parameters, and a <code>String</code> return value. It's <em>a getter for a Java bean</em>.</p>
|
[
{
"answer_id": 160976,
"author": "Owen",
"author_id": 11442,
"author_profile": "https://Stackoverflow.com/users/11442",
"pm_score": 8,
"selected": false,
"text": "Class<?> c = Class.forName(\"class name\");\nMethod method = c.getDeclaredMethod(\"method name\", parameterTypes);\nmethod.invoke(objectToInvokeOn, params);\n \"class name\" objectToInvokeOn \"method name\" parameterTypes Class[] params Object[]"
},
{
"answer_id": 160979,
"author": "zxcv",
"author_id": 9628,
"author_profile": "https://Stackoverflow.com/users/9628",
"pm_score": 3,
"selected": false,
"text": "public class method2 {\n public int add(int a, int b)\n {\n return a + b;\n }\n\n public static void main(String args[])\n {\n try {\n Class cls = Class.forName(\"method2\");\n Class partypes[] = new Class[2];\n partypes[0] = Integer.TYPE;\n partypes[1] = Integer.TYPE;\n Method meth = cls.getMethod(\n \"add\", partypes);\n method2 methobj = new method2();\n Object arglist[] = new Object[2];\n arglist[0] = new Integer(37);\n arglist[1] = new Integer(47);\n Object retobj \n = meth.invoke(methobj, arglist);\n Integer retval = (Integer)retobj;\n System.out.println(retval.intValue());\n }\n catch (Throwable e) {\n System.err.println(e);\n }\n }\n}\n"
},
{
"answer_id": 160980,
"author": "chickeninabiscuit",
"author_id": 3966,
"author_profile": "https://Stackoverflow.com/users/3966",
"pm_score": 4,
"selected": false,
"text": "Object obj;\n\nMethod method = obj.getClass().getMethod(\"methodName\", null);\n\nmethod.invoke(obj, null);\n"
},
{
"answer_id": 161005,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 11,
"selected": true,
"text": "java.lang.reflect.Method method;\ntry {\n method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);\n} catch (SecurityException e) { ... }\n catch (NoSuchMethodException e) { ... }\n methodName try {\n method.invoke(obj, arg1, arg2,...);\n} catch (IllegalArgumentException e) { ... }\n catch (IllegalAccessException e) { ... }\n catch (InvocationTargetException e) { ... }\n .invoke"
},
{
"answer_id": 161011,
"author": "Petr Macek",
"author_id": 15045,
"author_profile": "https://Stackoverflow.com/users/15045",
"pm_score": 6,
"selected": false,
"text": "import java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\npublic class ReflectionTest {\n\n private String methodName = \"length\";\n private String valueObject = \"Some object\";\n\n @Test\n public void testGetMethod() throws SecurityException, NoSuchMethodException, IllegalArgumentException,\n IllegalAccessException, InvocationTargetException {\n Method m = valueObject.getClass().getMethod(methodName, new Class[] {});\n Object ret = m.invoke(valueObject, new Object[] {});\n Assert.assertEquals(11, ret);\n }\n\n\n\n}\n"
},
{
"answer_id": 161032,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 4,
"selected": false,
"text": "/**\n * Allow for instance call, avoiding certain class circular dependencies. <br />\n * Calls even private method if java Security allows it.\n * @param aninstance instance on which method is invoked (if null, static call)\n * @param classname name of the class containing the method \n * (can be null - ignored, actually - if instance if provided, must be provided if static call)\n * @param amethodname name of the method to invoke\n * @param parameterTypes array of Classes\n * @param parameters array of Object\n * @return resulting Object\n * @throws CCException if any problem\n */\npublic static Object reflectionCall(final Object aninstance, final String classname, final String amethodname, final Class[] parameterTypes, final Object[] parameters) throws CCException\n{\n Object res;// = null;\n try {\n Class aclass;// = null;\n if(aninstance == null)\n {\n aclass = Class.forName(classname);\n }\n else\n {\n aclass = aninstance.getClass();\n }\n //Class[] parameterTypes = new Class[]{String[].class};\n final Method amethod = aclass.getDeclaredMethod(amethodname, parameterTypes);\n AccessController.doPrivileged(new PrivilegedAction() {\n public Object run() {\n amethod.setAccessible(true);\n return null; // nothing to return\n }\n });\n res = amethod.invoke(aninstance, parameters);\n } catch (final ClassNotFoundException e) {\n throw new CCException.Error(PROBLEM_TO_ACCESS+classname+CLASS, e);\n } catch (final SecurityException e) {\n throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_SECURITY_ISSUE, e);\n } catch (final NoSuchMethodException e) {\n throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_NOT_FOUND, e);\n } catch (final IllegalArgumentException e) {\n throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_ILLEGAL_ARGUMENTS+String.valueOf(parameters)+GenericConstants.CLOSING_ROUND_BRACKET, e);\n } catch (final IllegalAccessException e) {\n throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_ACCESS_RESTRICTION, e);\n } catch (final InvocationTargetException e) {\n throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_INVOCATION_ISSUE, e);\n } \n return res;\n}\n"
},
{
"answer_id": 3056891,
"author": "SMayne",
"author_id": 368639,
"author_profile": "https://Stackoverflow.com/users/368639",
"pm_score": -1,
"selected": false,
"text": "public static object methodCaller(String methodName)\n{\n if(methodName.equals(\"getName\"))\n return className.getName();\n}\n //calling a toString method is unnessary here, but i use it to have my programs to both rigid and self-explanitory \nSystem.out.println(methodCaller(methodName).toString()); \n"
},
{
"answer_id": 16292985,
"author": "anujin",
"author_id": 1394305,
"author_profile": "https://Stackoverflow.com/users/1394305",
"pm_score": 4,
"selected": false,
"text": "//Step1 - Using string funClass to convert to class\nString funClass = \"package.myclass\";\nClass c = Class.forName(funClass);\n\n//Step2 - instantiate an object of the class abov\nObject o = c.newInstance();\n//Prepare array of the arguments that your function accepts, lets say only one string here\nClass[] paramTypes = new Class[1];\nparamTypes[0]=String.class;\nString methodName = \"mymethod\";\n//Instantiate an object of type method that returns you method name\n Method m = c.getDeclaredMethod(methodName, paramTypes);\n//invoke method with actual params\nm.invoke(o, \"testparam\");\n"
},
{
"answer_id": 30671481,
"author": "silver",
"author_id": 2806819,
"author_profile": "https://Stackoverflow.com/users/2806819",
"pm_score": 7,
"selected": false,
"text": "Dog package com.mypackage.bean;\n\npublic class Dog {\n private String name;\n private int age;\n\n public Dog() {\n // empty constructor\n }\n\n public Dog(String name, int age) {\n this.name = name;\n this.age = age;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getAge() {\n return age;\n }\n\n public void setAge(int age) {\n this.age = age;\n }\n\n public void printDog(String name, int age) {\n System.out.println(name + \" is \" + age + \" year(s) old.\");\n }\n}\n ReflectionDemo package com.mypackage.demo;\n\nimport java.lang.reflect.*;\n\npublic class ReflectionDemo {\n\n public static void main(String[] args) throws Exception {\n String dogClassName = \"com.mypackage.bean.Dog\";\n Class<?> dogClass = Class.forName(dogClassName); // convert string classname to class\n Object dog = dogClass.newInstance(); // invoke empty constructor\n\n String methodName = \"\";\n\n // with single parameter, return void\n methodName = \"setName\";\n Method setNameMethod = dog.getClass().getMethod(methodName, String.class);\n setNameMethod.invoke(dog, \"Mishka\"); // pass arg\n\n // without parameters, return string\n methodName = \"getName\";\n Method getNameMethod = dog.getClass().getMethod(methodName);\n String name = (String) getNameMethod.invoke(dog); // explicit cast\n\n // with multiple parameters\n methodName = \"printDog\";\n Class<?>[] paramTypes = {String.class, int.class};\n Method printDogMethod = dog.getClass().getMethod(methodName, paramTypes);\n printDogMethod.invoke(dog, name, 3); // pass args\n }\n}\n Mishka is 3 year(s) old. Constructor<?> dogConstructor = dogClass.getConstructor(String.class, int.class);\nObject dog = dogConstructor.newInstance(\"Hachiko\", 10);\n String dogClassName = \"com.mypackage.bean.Dog\";\nClass<?> dogClass = Class.forName(dogClassName);\nObject dog = dogClass.newInstance();\n Dog dog = new Dog();\n\nMethod method = Dog.class.getMethod(methodName, ...);\nmethod.invoke(dog, ...);\n"
},
{
"answer_id": 31321045,
"author": "nurnachman",
"author_id": 403717,
"author_profile": "https://Stackoverflow.com/users/403717",
"pm_score": 2,
"selected": false,
"text": "Class<?> aClass = Class.forName(FULLY_QUALIFIED_CLASS_NAME);\nMethod method = aClass.getMethod(methodName, YOUR_PARAM_1.class, YOUR_PARAM_2.class);\nmethod.invoke(OBJECT_TO_RUN_METHOD_ON, YOUR_PARAM_1, YOUR_PARAM_2);\n"
},
{
"answer_id": 33044958,
"author": "Gautam",
"author_id": 582421,
"author_profile": "https://Stackoverflow.com/users/582421",
"pm_score": 1,
"selected": false,
"text": "public class MethodInvokerClass {\n public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, ClassNotFoundException, InvocationTargetException, InstantiationException {\n Class c = Class.forName(MethodInvokerClass.class.getName());\n Object o = c.newInstance();\n Class[] paramTypes = new Class[1];\n paramTypes[0]=String.class;\n String methodName = \"countWord\";\n Method m = c.getDeclaredMethod(methodName, paramTypes);\n m.invoke(o, \"testparam\");\n}\npublic void countWord(String input){\n System.out.println(\"My input \"+input);\n}\n My input testparam"
},
{
"answer_id": 37339469,
"author": "Rahul Karankal",
"author_id": 5912936,
"author_profile": "https://Stackoverflow.com/users/5912936",
"pm_score": 3,
"selected": false,
"text": "public static Method method[];\npublic static MethodClass obj;\npublic static String testMethod=\"A\";\n\npublic static void main(String args[]) \n{\n obj=new MethodClass();\n method=obj.getClass().getMethods();\n try\n {\n for(int i=0;i<method.length;i++)\n {\n String name=method[i].getName();\n if(name==testMethod)\n { \n method[i].invoke(name,\"Test Parameters of A\");\n }\n }\n }\n catch(Exception ex)\n {\n System.out.println(ex.getMessage());\n }\n}\n"
},
{
"answer_id": 39601917,
"author": "Marcel",
"author_id": 5411494,
"author_profile": "https://Stackoverflow.com/users/5411494",
"pm_score": 3,
"selected": false,
"text": "try {\n YourClass yourClass = new YourClass();\n Method method = YourClass.class.getMethod(\"yourMethodName\", ParameterOfThisMethod.class);\n method.invoke(yourClass, parameter);\n} catch (Exception e) {\n e.printStackTrace();\n}\n"
},
{
"answer_id": 40758462,
"author": "dina",
"author_id": 5980143,
"author_profile": "https://Stackoverflow.com/users/5980143",
"pm_score": 2,
"selected": false,
"text": "import java.lang.reflect.*; public static Object launchProcess(String className, String methodName, Class<?>[] argsTypes, Object[] methodArgs)\n throws Exception {\n\n Class<?> processClass = Class.forName(className); // convert string classname to class\n Object process = processClass.newInstance(); // invoke empty constructor\n\n Method aMethod = process.getClass().getMethod(methodName,argsTypes);\n Object res = aMethod.invoke(process, methodArgs); // pass arg\n return(res);\n}\n String className = \"com.example.helloworld\";\nString methodName = \"print\";\nClass<?>[] argsTypes = {String.class, String.class};\nObject[] methArgs = { \"hello\", \"world\" }; \nlaunchProcess(className, methodName, argsTypes, methArgs);\n"
},
{
"answer_id": 41339316,
"author": "Subrahmanya Prasad",
"author_id": 5564537,
"author_profile": "https://Stackoverflow.com/users/5564537",
"pm_score": 3,
"selected": false,
"text": "Method method = someVariable.class.getMethod(SomeClass);\nString status = (String) method.invoke(method);\n SomeClass someVariable"
},
{
"answer_id": 42519563,
"author": "Christian Ullenboom",
"author_id": 388317,
"author_profile": "https://Stackoverflow.com/users/388317",
"pm_score": 3,
"selected": false,
"text": "Object obj = new Point( 100, 200 );\nString methodName = \"toString\"; \nClass<String> resultType = String.class;\n\nMethodType mt = MethodType.methodType( resultType );\nMethodHandle methodHandle = MethodHandles.lookup().findVirtual( obj.getClass(), methodName, mt );\nString result = resultType.cast( methodHandle.invoke( obj ) );\n\nSystem.out.println( result ); // java.awt.Point[x=100,y=200]\n"
},
{
"answer_id": 45395762,
"author": "user8387971",
"author_id": 8387971,
"author_profile": "https://Stackoverflow.com/users/8387971",
"pm_score": 2,
"selected": false,
"text": "class Student{\n int rollno;\n String name;\n\n void m1(int x,int y){\n System.out.println(\"add is\" +(x+y));\n }\n\n private void m3(String name){\n this.name=name;\n System.out.println(\"danger yappa:\"+name);\n }\n void m4(){\n System.out.println(\"This is m4\");\n }\n}\n import java.lang.reflect.Method;\npublic class StudentTest{\n\n public static void main(String[] args){\n\n try{\n\n Class cls=Student.class;\n\n Student s=(Student)cls.newInstance();\n\n\n String x=\"kichha\";\n Method mm3=cls.getDeclaredMethod(\"m3\",String.class);\n mm3.setAccessible(true);\n mm3.invoke(s,x);\n\n Method mm1=cls.getDeclaredMethod(\"m1\",int.class,int.class);\n mm1.invoke(s,10,20);\n\n }\n catch(Exception e){\n e.printStackTrace();\n }\n }\n}\n"
},
{
"answer_id": 54883454,
"author": "Sandeep Nalla",
"author_id": 8732673,
"author_profile": "https://Stackoverflow.com/users/8732673",
"pm_score": 3,
"selected": false,
"text": "public static void callMethodByName(Object object, String methodName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {\n object.getClass().getDeclaredMethod(methodName).invoke(object);\n}\n public static void callMethodByName(Object object, String methodName, int i, String s) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {\n object.getClass().getDeclaredMethod(methodName, int.class, String.class).invoke(object, i, s);\n }\n package practice;\n\nimport java.io.IOException;\nimport java.lang.reflect.InvocationTargetException;\n\npublic class MethodInvoke {\n\n public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {\n String methodName1 = \"methodA\";\n String methodName2 = \"methodB\";\n MethodInvoke object = new MethodInvoke();\n callMethodByName(object, methodName1);\n callMethodByName(object, methodName2, 1, \"Test\");\n }\n\n public static void callMethodByName(Object object, String methodName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {\n object.getClass().getDeclaredMethod(methodName).invoke(object);\n }\n\n public static void callMethodByName(Object object, String methodName, int i, String s) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {\n object.getClass().getDeclaredMethod(methodName, int.class, String.class).invoke(object, i, s);\n }\n\n void methodA() {\n System.out.println(\"Method A\");\n }\n\n void methodB(int i, String s) {\n System.out.println(\"Method B: \"+\"\\n\\tParam1 - \"+i+\"\\n\\tParam 2 - \"+s);\n }\n}\n"
},
{
"answer_id": 59969586,
"author": "Amir Fo",
"author_id": 7580839,
"author_profile": "https://Stackoverflow.com/users/7580839",
"pm_score": 4,
"selected": false,
"text": "FunctionalInterface @FunctionalInterface\npublic interface Method {\n double execute(int number);\n}\n\npublic class ShapeArea {\n private final static double PI = 3.14;\n\n private Method[] methods = {\n this::square,\n this::circle\n };\n\n private double square(int number) {\n return number * number;\n }\n\n private double circle(int number) {\n return PI * number * number;\n }\n\n public double run(int methodIndex, int number) {\n return methods[methodIndex].execute(number);\n }\n}\n public class ShapeArea {\n private final static double PI = 3.14;\n\n private Method[] methods = {\n number -> {\n return number * number;\n },\n number -> {\n return PI * number * number;\n },\n };\n\n public double run(int methodIndex, int number) {\n return methods[methodIndex].execute(number);\n }\n}\n @FunctionalInterface\npublic interface Method {\n Object execute(Object ...args);\n}\n\npublic class Methods {\n private Method[] methods = {\n this::square,\n this::rectangle\n };\n\n private double square(int number) {\n return number * number;\n }\n\n private double rectangle(int width, int height) {\n return width * height;\n }\n\n public Method run(int methodIndex) {\n return methods[methodIndex];\n }\n}\n methods.run(1).execute(width, height);\n"
},
{
"answer_id": 60026477,
"author": "Andronicus",
"author_id": 7606764,
"author_profile": "https://Stackoverflow.com/users/7606764",
"pm_score": 2,
"selected": false,
"text": "on(obj).call(methodName /*params*/).get()\n public class TestClass {\n\n public int add(int a, int b) { return a + b; }\n private int mul(int a, int b) { return a * b; }\n static int sub(int a, int b) { return a - b; }\n\n}\n\nimport static org.joor.Reflect.*;\n\npublic class JoorTest {\n\n public static void main(String[] args) {\n int add = on(new TestClass()).call(\"add\", 1, 2).get(); // public\n int mul = on(new TestClass()).call(\"mul\", 3, 4).get(); // private\n int sub = on(TestClass.class).call(\"sub\", 6, 5).get(); // static\n System.out.println(add + \", \" + mul + \", \" + sub);\n }\n}\n"
},
{
"answer_id": 65878101,
"author": "chrizonline",
"author_id": 291779,
"author_profile": "https://Stackoverflow.com/users/291779",
"pm_score": 1,
"selected": false,
"text": "class Person {\n public void method1() {\n try {\n Method m2 = this.getClass().getDeclaredMethod(\"method2\");\n m1.invoke(this);\n } catch (NoSuchMethodException e) {\n e.printStackTrace();\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (InvocationTargetException e) {\n e.printStackTrace();\n }\n }\n\n public void method2() {\n // Do something\n }\n\n}\n"
},
{
"answer_id": 68720276,
"author": "FriskySaga",
"author_id": 5849965,
"author_profile": "https://Stackoverflow.com/users/5849965",
"pm_score": 1,
"selected": false,
"text": "class MainClass\n{\n public static int foo()\n {\n return 123;\n }\n\n public static void main(String[] args)\n {\n Method method = MainClass.class.getMethod(\"foo\");\n int result = (int) method.invoke(null); // answer evaluates to 123\n }\n}\n class getMethod() null invoke() invoke()"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] |
160,971
|
<p>I've read some of the recent language vs. language questions with interest... <a href="https://stackoverflow.com/questions/150043/python-v-perl#150103">Perl vs. Python</a>, <a href="https://stackoverflow.com/questions/136977/after-c-python-or-java#137343">Python vs. Java</a>, <a href="https://stackoverflow.com/questions/157207/can-one-language-be-better-than-another">Can one language be better than another?</a></p>
<p>One thing I've noticed is that a lot of us have <em>very superficial</em> reasons for disliking languages. We notice these things at first glance and they turn us off. We shun what are probably perfectly good languages as a result of features that we'd probably learn to love or ignore in 2 seconds if we bothered.</p>
<p>Well, I'm as guilty as the next guy, if not more. Here goes:</p>
<ul>
<li>Ruby: All the Ruby example code I see uses the <code>puts</code> command, and that's a sort of childish Yiddish anatomical term. So as a result, I can't take Ruby code seriously even though I should.</li>
<li>Python: The first time I saw it, I smirked at the whole significant whitespace thing. I avoided it for the next several years. Now I hardly use anything else.</li>
<li>Java: I don't like identifiersThatLookLikeThis. I'm not sure why exactly.</li>
<li>Lisp: I have trouble with all the parentheses. Things of different importance and purpose (function declarations, variable assignments, etc.) are not syntactically differentiated and I'm too lazy to learn what's what.</li>
<li>Fortran: uppercase everything hurts my eyes. I know modern code doesn't have to be written like that, but most example code is...</li>
<li>Visual Basic: it bugs me that <code>Dim</code> is used to declare variables, since I remember the good ol' days of GW-BASIC when it was <em>only</em> used to dimension arrays.</li>
</ul>
<p>What languages <em>did</em> look right to me at first glance? Perl, C, QBasic, JavaScript, assembly language, BASH shell, FORTH.</p>
<p>Okay, now that I've aired my dirty laundry... I want to hear yours. <strong>What are your language hangups? What superficial features bother you? How have you gotten over them?</strong></p>
|
[
{
"answer_id": 160996,
"author": "Michael Petrotta",
"author_id": 23897,
"author_profile": "https://Stackoverflow.com/users/23897",
"pm_score": 3,
"selected": false,
"text": "throws"
},
{
"answer_id": 160997,
"author": "LeopardSkinPillBoxHat",
"author_id": 22489,
"author_profile": "https://Stackoverflow.com/users/22489",
"pm_score": 2,
"selected": false,
"text": "if (condition)\n{\n callSomeConditionalMethod();\n}\ncallSomeOtherMethod();\n if (condition)\n callSomeConditionalMethod();\ncallSomeOtherMethod();\n"
},
{
"answer_id": 161085,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 3,
"selected": false,
"text": "Begin End Begin End Type foo = Record\n // ...\nend;\n"
},
{
"answer_id": 161089,
"author": "deceze",
"author_id": 476,
"author_profile": "https://Stackoverflow.com/users/476",
"pm_score": 3,
"selected": false,
"text": "$x = returnsArray();\n$x[1];\n returnsArray()[1];\n function sort($a, $b) {\n return $a < $b;\n}\nusort($array, 'sort');\n usort($array, function($a, $b) { return $a < $b; });\n"
},
{
"answer_id": 161097,
"author": "Barry Brown",
"author_id": 17312,
"author_profile": "https://Stackoverflow.com/users/17312",
"pm_score": 2,
"selected": false,
"text": "($lastname, $firstname, $rest) = split(' ', $fullname);\n"
},
{
"answer_id": 161158,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 3,
"selected": false,
"text": "int main() // function declaration / definition\nprintf(\"hello\") // function call\n(int)x // type cast\n2*(7+8) // override precedence\nint (*)(int) // function pointer\nint x(3) // initializer\nif (condition) // special part of syntax of if, while, for, switch\n foo<bar>(baz(),baaz)\n foo bar"
},
{
"answer_id": 161189,
"author": "Dean Rather",
"author_id": 14966,
"author_profile": "https://Stackoverflow.com/users/14966",
"pm_score": 5,
"selected": false,
"text": "// common parameters back-to-front\nin_array(needle, haystack);\nstrpos(haystack, needle);\n\n// _ to separate words, or not?\nfilesize();\nfile_exists;\n\n// super globals prefix?\n$GLOBALS;\n$_POST;\n"
},
{
"answer_id": 161213,
"author": "ThatBloke",
"author_id": 7050,
"author_profile": "https://Stackoverflow.com/users/7050",
"pm_score": 2,
"selected": false,
"text": "\n DECLARE mycurse CURSOR LOCAL FAST_FORWARD READ_ONLY\n FOR\n SELECT field1, field2, fieldN FROM atable\n\n OPEN mycurse\n FETCH NEXT FROM mycurse INTO @Var1, @Var2, @VarN\n\n WHILE @@fetch_status = 0\n BEGIN\n -- do something really clever...\n\n FETCH NEXT FROM mycurse INTO @Var1, @Var2, @VarN\n END\n CLOSE mycurse\n DEALLOCATE mycurse\n"
},
{
"answer_id": 161259,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": -1,
"selected": false,
"text": "if (a and b)\n{\n do something\n}\n if (a)\n{\n if (b)\n {\n do something\n }\n else\n {\n what about this case?\n }\n}\nelse\n{\n if (b)\n {\n what about this case?\n }\n else\n {\n do something else\n }\n}\n"
},
{
"answer_id": 163425,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 4,
"selected": false,
"text": "xmlns=\"http://purl.org/rss/1.0/\""
},
{
"answer_id": 172986,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 1,
"selected": false,
"text": "if-then-else x -> y ; z\n ; or x y z"
},
{
"answer_id": 598327,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 2,
"selected": false,
"text": "# Default starting value of the loop\n# counter variable reference.\ndirective.foreach.counter.initial.value = 1\n"
},
{
"answer_id": 1829669,
"author": "Pavel Minaev",
"author_id": 111335,
"author_profile": "https://Stackoverflow.com/users/111335",
"pm_score": 2,
"selected": false,
"text": "self. def foo()\n 123\nend\n\ndef foo=(x)\nend\n\ndef bar()\n x = foo() # okay, same as self.foo()\n x = foo # not okay, reads unassigned local variable foo\n foo = 123 # not okay, assigns local variable foo\nend\n self."
},
{
"answer_id": 1829749,
"author": "Earlz",
"author_id": 69742,
"author_profile": "https://Stackoverflow.com/users/69742",
"pm_score": 0,
"selected": false,
"text": "void event...(object sender,EventArgs e){\n int t=(int)(decimal)(MyControl.Value); //Value is an object which is actually a decimal to be converted into an int\n}\n [MyAttribute(Argument)] void function... const if(a)\n b();\n if(a)\n b();\n c();\n if(a)\n b(); c();\n if(a){ ....\n}else if(b){ ...\n"
},
{
"answer_id": 1829750,
"author": "Carl Smotricz",
"author_id": 172211,
"author_profile": "https://Stackoverflow.com/users/172211",
"pm_score": 3,
"selected": false,
"text": "veryLongVariableNames IDENTIFICATION DIVISION."
},
{
"answer_id": 1829902,
"author": "Juliet",
"author_id": 40516,
"author_profile": "https://Stackoverflow.com/users/40516",
"pm_score": 2,
"selected": false,
"text": "* , (\"Juliet\", 23, true) (string * int * bool) module q = List;; x.Where(item => ...).OrderBy(item => ...) from item in x where ... orderby ... select Module Hangups\n Dim _juliet as String = \"Too Wordy!\"\n\n Public Property Juliet() as String\n Get\n Return _juliet\n End Get\n Set (ByVal value as String)\n _juliet = value\n End Set\n End Property\nEnd Module\n"
},
{
"answer_id": 1835020,
"author": "Sarah Vessels",
"author_id": 38743,
"author_profile": "https://Stackoverflow.com/users/38743",
"pm_score": 0,
"selected": false,
"text": "__methodName__"
},
{
"answer_id": 6446890,
"author": "Keith Adler",
"author_id": 135952,
"author_profile": "https://Stackoverflow.com/users/135952",
"pm_score": 0,
"selected": false,
"text": "with SomeObject\n{\n .Property = \"Some value\";\n .Event();\n}\n SomeObject.Property = \"Some value\";\nSomeObject.Event();\n var result = SomeObject.SomeCollection.First().SomeProperty ??? \"Default value\";\n string result = string.Empty;\n\nif ( SomeObject != null && SomeObject.SomeCollection.Count() > 0 )\n{\n result = SomeObject.SomeCollection.FirsT().SomeProperty;\n}\nelse\n{\n result = \"Default value\";\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20789/"
] |
160,974
|
<p>Basically I have the following class:</p>
<pre><code>class StateMachine {
...
StateMethod stateA();
StateMethod stateB();
...
};
</code></pre>
<p>The methods stateA() and stateB() should be able return pointers to stateA() and stateB().
How to typedef the StateMethod?</p>
|
[
{
"answer_id": 161000,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 2,
"selected": false,
"text": "class X\n{\n public:\n typedef const boost::function0<Method> Method;\n\n // some kind of mutually recursive state machine\n Method stateA()\n { return boost::bind(&X::stateB, this); }\n Method stateB()\n { return boost::bind(&X::stateA, this); }\n};\n"
},
{
"answer_id": 161029,
"author": "Simon Buchan",
"author_id": 20135,
"author_profile": "https://Stackoverflow.com/users/20135",
"pm_score": 2,
"selected": false,
"text": "typedef StateMethod (StateMachine::*StateMethod)();\n typedef void (StateMachine::*StateMethod)(); state = (StateMethod)(this->*state)(); boost::function boost::function0<ReturnType>"
},
{
"answer_id": 161039,
"author": "Jacob Krall",
"author_id": 3140,
"author_profile": "https://Stackoverflow.com/users/3140",
"pm_score": 5,
"selected": true,
"text": "struct StateMethod;\ntypedef StateMethod (StateMachine:: *FuncPtr)(); \nstruct StateMethod\n{\n StateMethod( FuncPtr pp ) : p( pp ) { }\n operator FuncPtr() { return p; }\n FuncPtr p;\n};\n\nclass StateMachine {\n StateMethod stateA();\n StateMethod stateB();\n};\n\nint main()\n{\n StateMachine *fsm = new StateMachine();\n FuncPtr a = fsm->stateA(); // natural usage syntax\n return 0;\n} \n\nStateMethod StateMachine::stateA\n{\n return stateA; // natural return syntax\n}\n\nStateMethod StateMachine::stateB\n{\n return stateB;\n}\n"
},
{
"answer_id": 161040,
"author": "njsf",
"author_id": 4995,
"author_profile": "https://Stackoverflow.com/users/4995",
"pm_score": 3,
"selected": false,
"text": "class StateMachine { \n\n public: \n\n class StateMethod; \n typedef StateMethod (StateMachine::*statemethod)(); \n\n class StateMethod { \n\n statemethod method; \n StateMachine& obj; \n\n public: \n\n StateMethod(statemethod method_, StateMachine *obj_) \n : method(method_), obj(*obj_) {} \n\n StateMethod operator()() { return (obj.*(method))(); } \n }; \n\n StateMethod stateA() { return StateMethod(&StateMachine::stateA, this); } \n\n StateMethod stateB() { return StateMethod(&StateMachine::stateB, this); } \n\n}; \n"
},
{
"answer_id": 163671,
"author": "Assaf Lavie",
"author_id": 11208,
"author_profile": "https://Stackoverflow.com/users/11208",
"pm_score": 0,
"selected": false,
"text": "class StateMachine { \n bool stateA(int someArg); \n};\n char c = StateMachine::stateA\n error: a value of type \"bool (StateMachine::*)(int)\" cannot be used to initialize \n an entity of type \"char\" \n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1692070/"
] |
160,995
|
<p>I tried this XAML:</p>
<pre><code><Slider Width="250" Height="25" Minimum="0" Maximum="1" MouseLeftButtonDown="slider_MouseLeftButtonDown" MouseLeftButtonUp="slider_MouseLeftButtonUp" />
</code></pre>
<p>And this C#:</p>
<pre><code>private void slider_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
sliderMouseDown = true;
}
private void slider_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
sliderMouseDown = false;
}
</code></pre>
<p>The sliderMouseDown variable never changes because the MouseLeftButtonDown and MouseLeftButtonUp events are never raised. How can I get this code to work when a user has the left mouse button down on a slider to have a bool value set to true, and when the mouse is up, the bool is set to false?</p>
|
[
{
"answer_id": 168928,
"author": "cplotts",
"author_id": 22294,
"author_profile": "https://Stackoverflow.com/users/22294",
"pm_score": 4,
"selected": false,
"text": "this.AddHandler\n(\n Slider.MouseLeftButtonDownEvent,\n new MouseButtonEventHandler(slider_MouseLeftButtonDown),\n true\n);\n"
},
{
"answer_id": 10958377,
"author": "benjamin.popp",
"author_id": 385567,
"author_profile": "https://Stackoverflow.com/users/385567",
"pm_score": 1,
"selected": false,
"text": "AddHandler(Slider.MouseLeftButtonDownEvent, ..., true)\n"
},
{
"answer_id": 27954933,
"author": "Derrick",
"author_id": 561759,
"author_profile": "https://Stackoverflow.com/users/561759",
"pm_score": 3,
"selected": false,
"text": " private void sliderr_LostMouseCapture(object sender, MouseEventArgs e)\n\n private void slider_GotMouseCapture(object sender, MouseEventArgs e)\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/160995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23939/"
] |
161,022
|
<p>I have some styles applied to html for example </p>
<pre><code><body style="background: #C3DAF9;">
</code></pre>
<p>and when I use forms authentication it is ignored. If I put the style into an external .css file then it works. </p>
<p>This doesn't seem like normal behaviour to me. </p>
|
[
{
"answer_id": 161501,
"author": "Errico Malatesta",
"author_id": 24439,
"author_profile": "https://Stackoverflow.com/users/24439",
"pm_score": -1,
"selected": false,
"text": "<body bgcolor=\"#C3DAF9\">\n"
},
{
"answer_id": 165385,
"author": "Stephen Price",
"author_id": 24395,
"author_profile": "https://Stackoverflow.com/users/24395",
"pm_score": 2,
"selected": true,
"text": "if (User.Identity.IsAuthenticated) {\n if (User.Identity is BookingIdentity) {\n BookingIdentity id = (BookingIdentity) User.Identity;\n\n Response.Write(\"<p/>UserName: \" + id.Name);\n }\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24395/"
] |
161,027
|
<p>Let's say I am modelling a process that involves a conversation or exchnage between two actors. For this example, I'll use something easily understandable:-</p>
<ol>
<li>Supplier creates a price list,</li>
<li>Buyer chooses some items to buy and sends a Purchase Order,</li>
<li>Supplier receives the purchase order and sends the goods.</li>
<li>Supplier sends an invoice</li>
<li>Buyer receives the invoice and makes a payment</li>
</ol>
<p>Of course each of those steps in itself could be quick complicated. How would you split this up into use cases in your requirements document?</p>
<p>If this process was treated as a single use-case it could fill a book.</p>
<p>Alternatively, making a use case out of each of the above steps would hide some of the essential interaction and flow that should be captured. Would it make sense to have a use case that starts at "Received a purchase order" and finishes at "Send an Invoice" and then another that starts at "Receive an Invoice" and ends at "Makes a Payment"?</p>
<p>Any advice?</p>
|
[
{
"answer_id": 161501,
"author": "Errico Malatesta",
"author_id": 24439,
"author_profile": "https://Stackoverflow.com/users/24439",
"pm_score": -1,
"selected": false,
"text": "<body bgcolor=\"#C3DAF9\">\n"
},
{
"answer_id": 165385,
"author": "Stephen Price",
"author_id": 24395,
"author_profile": "https://Stackoverflow.com/users/24395",
"pm_score": 2,
"selected": true,
"text": "if (User.Identity.IsAuthenticated) {\n if (User.Identity is BookingIdentity) {\n BookingIdentity id = (BookingIdentity) User.Identity;\n\n Response.Write(\"<p/>UserName: \" + id.Name);\n }\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14663/"
] |
161,030
|
<p>In .NET is there a way to enable Assembly.Load tracing? I know while running under the debugger it gives you a nice message like "Loaded 'assembly X'" but I want to get a log of the assembly loads of my running application outside the debugger, preferably intermingled with my Debug/Trace log messages. </p>
<p>I'm tracing out various things in my application and I basically want to know what action triggered a particular assembly to be loaded.</p>
|
[
{
"answer_id": 161035,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 5,
"selected": true,
"text": "AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(OnAssemblyLoad);\n"
},
{
"answer_id": 1578820,
"author": "Thomas Bratt",
"author_id": 15985,
"author_profile": "https://Stackoverflow.com/users/15985",
"pm_score": 2,
"selected": false,
"text": "Loaded 'C:\\Windows\\assembly\\GAC_64\\mscorlib\\2.0.0.0__b77a5c561934e089\\mscorlib.dll'\nLoaded 'C:\\projects\\trunk\\bin\\Tester.exe', Symbols loaded.\nLoaded 'C:\\projects\\trunk\\bin\\log4net.dll'\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12784/"
] |
161,048
|
<p>I am trying to send an email from a site I am building, but it ends up in the yahoo spam folder. It is the email that sends credentials. What can I do to legitimize it?</p>
<pre><code>$header = "From: site <sales@site.com>\r\n";
$header .= "To: $name <$email>\r\n";
$header .= "Subject: $subject\r\n";
$header .= "Reply-To: site <sales@site.com>" . "\r\n";
$header .= "MIME-VERSION: 1.0\r\n";
$header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$phpversion = phpversion();
$header .= "X-Mailer: PHP v$phpversion\r\n";
mail($email,$subject,$body,$header);
</code></pre>
|
[
{
"answer_id": 2194725,
"author": "jschrab",
"author_id": 12694,
"author_profile": "https://Stackoverflow.com/users/12694",
"pm_score": 2,
"selected": false,
"text": "mail('recipient@domain.com', 'Subject', $mail_body, $headers, \" -f sender@domain.com\");\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3800/"
] |
161,053
|
<p>This question may sound fairly elementary, but this is a debate I had with another developer I work with.</p>
<p>I was taking care to stack allocate things where I could, instead of heap allocating them. He was talking to me and watching over my shoulder and commented that it wasn't necessary because they are the same performance wise.</p>
<p>I was always under the impression that growing the stack was constant time, and heap allocation's performance depended on the current complexity of the heap for both allocation (finding a hole of the proper size) and de-allocating (collapsing holes to reduce fragmentation, as many standard library implementations take time to do this during deletes if I am not mistaken).</p>
<p>This strikes me as something that would probably be very compiler dependent. For this project in particular I am using a <a href="http://en.wikipedia.org/wiki/Metrowerks" rel="noreferrer">Metrowerks</a> compiler for the <a href="http://en.wikipedia.org/wiki/PowerPC" rel="noreferrer">PPC</a> architecture. Insight on this combination would be most helpful, but in general, for GCC, and MSVC++, what is the case? Is heap allocation not as high performing as stack allocation? Is there no difference? Or are the differences so minute it becomes pointless micro-optimization.</p>
|
[
{
"answer_id": 161073,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 7,
"selected": false,
"text": "sub esp, 0x10\n"
},
{
"answer_id": 163765,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 7,
"selected": false,
"text": "#include <ctime>\n#include <iostream>\n\nnamespace {\n class empty { }; // even empty classes take up 1 byte of space, minimum\n}\n\nint main()\n{\n std::clock_t start = std::clock();\n for (int i = 0; i < 100000; ++i)\n empty e;\n std::clock_t duration = std::clock() - start;\n std::cout << \"stack allocation took \" << duration << \" clock ticks\\n\";\n start = std::clock();\n for (int i = 0; i < 100000; ++i) {\n empty* e = new empty;\n delete e;\n };\n duration = std::clock() - start;\n std::cout << \"heap allocation took \" << duration << \" clock ticks\\n\";\n}\n std::clock() empty e volatile volatile e extern e delete delete #include <cstdio>\n#include <chrono>\n\nnamespace {\n void on_stack()\n {\n int i;\n }\n\n void on_heap()\n {\n int* i = new int;\n delete i;\n }\n}\n\nint main()\n{\n auto begin = std::chrono::system_clock::now();\n for (int i = 0; i < 1000000000; ++i)\n on_stack();\n auto end = std::chrono::system_clock::now();\n\n std::printf(\"on_stack took %f seconds\\n\", std::chrono::duration<double>(end - begin).count());\n\n begin = std::chrono::system_clock::now();\n for (int i = 0; i < 1000000000; ++i)\n on_heap();\n end = std::chrono::system_clock::now();\n\n std::printf(\"on_heap took %f seconds\\n\", std::chrono::duration<double>(end - begin).count());\n return 0;\n}\n on_stack took 2.070003 seconds\non_heap took 57.980081 seconds\n cl foo.cc /Od /MT /EHsc on_stack took 0.000000 seconds\non_heap took 51.608723 seconds\n on_stack on_heap on_stack took 0.000003 seconds\non_heap took 0.000002 seconds\n"
},
{
"answer_id": 16979453,
"author": "Kent Munthe Caspersen",
"author_id": 2438446,
"author_profile": "https://Stackoverflow.com/users/2438446",
"pm_score": 2,
"selected": false,
"text": "Proc P\n{\n pointer x;\n Proc S\n {\n pointer y;\n y = allocate_some_data();\n x = y;\n }\n}\n"
},
{
"answer_id": 17827306,
"author": "ZijingWu",
"author_id": 2428052,
"author_profile": "https://Stackoverflow.com/users/2428052",
"pm_score": -1,
"selected": false,
"text": " int f(int i)\n {\n if (i > 0)\n { \n int array[1000];\n } \n }\n __Z1fi:\n Leh_func_begin1:\n pushq %rbp\n Ltmp0:\n movq %rsp, %rbp\n Ltmp1:\n subq $**3880**, %rsp <--- here we have the array allocated, even the if doesn't excited.\n Ltmp2:\n movl %edi, -4(%rbp)\n movl -8(%rbp), %eax\n addq $3880, %rsp\n popq %rbp\n ret \n Leh_func_end1:\n"
},
{
"answer_id": 30043382,
"author": "bitnick",
"author_id": 2962931,
"author_profile": "https://Stackoverflow.com/users/2962931",
"pm_score": 2,
"selected": false,
"text": "class Foo {\npublic:\n Foo(int a) {\n\n }\n}\nint func() {\n int a1, a2;\n std::cin >> a1;\n std::cin >> a2;\n\n Foo f1(a1);\n __asm push a1;\n __asm lea ecx, [this];\n __asm call Foo::Foo(int);\n\n Foo* f2 = new Foo(a2);\n __asm push sizeof(Foo);\n __asm call operator new;//there's a lot instruction here(depends on system)\n __asm push a2;\n __asm call Foo::Foo(int);\n\n delete f2;\n}\n func f1 f2 f1(a1) esp func f1 lea ecx [ebp+f1], call Foo::SomeFunc() FIFO FIFO int i = 0"
},
{
"answer_id": 53132683,
"author": "FrankHB",
"author_id": 2307646,
"author_profile": "https://Stackoverflow.com/users/2307646",
"pm_score": 4,
"selected": false,
"text": "::operator new new call/cc PUSH POP <memory_resource> alloca"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366/"
] |
161,056
|
<p>Is there a CSS editor which automatically expands one-line declarations as multi-line declarations on focus ? To clarify my thought, see example below:</p>
<p>Original CSS:</p>
<pre><code>div#main { color: orange; margin: 1em 0; border: 1px solid black; }
</code></pre>
<p>But when focusing on it, editor automatically expands it to:</p>
<pre><code>div#main {
color: orange;
margin: 1em 0;
border: 1px solid black;
}
</code></pre>
<p>And when it looses focus, editor again it automatically compresses it to one-line declaration.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 162432,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "function ExpandContractCSS()\n local ext = string.lower(props[\"FileExt\"])\n if ext ~= \"css\" then return end\n local line = GetCurrentLine()\n local newForm\n if string.find(line, \"}\") then\n -- On one line\n newForm = string.gsub(line, \"; *\", \";\\r\\n \")\n newForm = string.gsub(newForm, \"{ *\", \"{\\r\\n \")\n newForm = string.gsub(newForm, \" *}\", \"}\")\n else\n -- To contract\n -- Well, just use Ctrl+Z!\n -- Maybe not, code to come if interest\n end\n if newForm ~= nil then\n ReplaceCurrentLine(newForm)\n end\nend\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
161,064
|
<p>I'm running autoconf and configure sets SHELL to '/bin/sh'.
This creates huge problems. How to force SHELL to be '/bin/bash' for autoconf?</p>
<p>I'm trying to get this running on osx, it's working on linux. Linux is using SHELL=/bin/bash. osx defaults to /bin/sh.</p>
|
[
{
"answer_id": 161070,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": -1,
"selected": false,
"text": "ln -f /bin/bash /bin/sh"
},
{
"answer_id": 161071,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 0,
"selected": false,
"text": "if test \"$SHELL\" = \"/bin/sh\" && test -x /bin/bash; then\n exec /bin/bash -c \"$0\" \"$@\"\nfi\n"
},
{
"answer_id": 161128,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 4,
"selected": true,
"text": "CONFIG_SHELL=/bin/bash ./configure ...\n"
},
{
"answer_id": 9611812,
"author": "Kaz",
"author_id": 1250772,
"author_profile": "https://Stackoverflow.com/users/1250772",
"pm_score": 2,
"selected": false,
"text": "if test X$foo = X ; then ... # check if foo is empty\n if [ \"$x\" = \"\" ] ; then ...\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15054/"
] |
161,074
|
<p>Currently running Server 2003 but am looking at reinstalling in the near future due to a change of direction with the domains. Should I take this opportunity to install Windows Server 2008 instead?
I would love to play with new technology and the server is only for a small home business so downtime/performance issues aren't really a concern.</p>
|
[
{
"answer_id": 161780,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 0,
"selected": false,
"text": "/3GB"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23988/"
] |
161,084
|
<p>I was just wondering if anyone knew of a good way that I could parse the file at the bottom of the post.</p>
<p>I have a database setup with the correct tables for each section eg Refferal Table,Caller Table,Location Table. Each table has the same columns that are show in the file below</p>
<p>I would really like something that is fairly genetic so if the file layout changes it won't mess me around to much. At the moment I am just reading the file in a line at a time and just using a case statement to check which section i'm in. </p>
<p>Is anyone able to help me with this?</p>
<p>PS. I am using VB but C# or anything else will be fine, also the x's in the document are just personal info I have blanked</p>
<p>Thanks,
Nathan</p>
<p>File:---></p>
<pre><code>DIAL BEFORE YOU DIG
Call 1100, Fax 1300 652 077
PO Box 7710 MELBOURNE, VIC 8004
Utilities are requested to respond within 2 working days and reference the Sequence number.
[REFFERAL DETAILS]
FROM= Dial Before You Dig - Web
TO= Technical Services
UTILITY ID= xxxxxx
COMPANY= {Company Name}
ENQUIRY DATE= 02/10/2008 13:53
COMMENCEMENT DATE= 06/10/2008
SEQUENCE NO= xxxxxxxxx
PLANNING= No
[CALLER DETAILS]
CUSTOMER ID= 403552
CONTACT NAME= {Name of Contact}
CONTACT HOURS= 0
COMPANY= Underground Utility Locating
ADDRESS= {Address}
SUBURB= {Suburb}
STATE= {State}
POSTCODE= 4350
TELEPHONE= xxxxxxxxxx
MOBILE= xxxxxxxxxx
FAX TYPE= Private
FAX NUMBER= xxxxxxxxxx
PUBLIC ADDRESS= xxxxxxxxxx
PUBLIC TELEPHONE=
EMAIL ADDRESS= {Email Address}
[LOCATION DETAILS]
ADDRESS= {Location Address}
SUBURB= {Location Suburb}
STATE= xxx
POSTCODE= xxx
DEPOSITED PLAN NO= 0
SECTION & HUNDRED NO= 0
PROPERTY PHONE NO=
SIDE OF STREET= B
INTERSECTION= xxxxxx
DISTANCE= 0-200m B
ACTIVITY CODE= 15
ACTIVITY DESCRIPTION= xxxxxxxxxxxxxxxxxx
MAP TYPE= StateGrid
MAP REF= Q851_63
MAP PAGE=
MAP GRID 1=
MAP GRID 2=
MAP GRID 3=
MAP GRID 4=
MAP GRID 5=
GPS X COORD=
GPS Y COORD=
PRIVATE/ROAD/BOTH= B
TRAFFIC AFFECTED= No
NOTIFICATION NO= 3082321
MESSAGE= entire intersection of Allora-Clifton rd , Hillside
rd and merivale st
MOCSMESSAGE= Digsafe generated referral
Notice: Please DO NOT REPLY TO THIS EMAIL as it has been automatically generated and replies are not monitored. Should you wish to advise Dial Before You Dig of any issues with this enquiry, please Call 1100
(See attached file: 3082321_LLGDA94.GML)
</code></pre>
|
[
{
"answer_id": 161152,
"author": "pbh101",
"author_id": 1266,
"author_profile": "https://Stackoverflow.com/users/1266",
"pm_score": 2,
"selected": false,
"text": "split() = test1.txt"
},
{
"answer_id": 224550,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 1,
"selected": false,
"text": "Using f As StreamReader = File.OpenText(\"sample.txt\")\n Dim g As String = \"undefined\"\n Do\n Dim s As String = f.ReadLine\n If s Is Nothing Then Exit Do\n s = s.Replace(Chr(9), \" \")\n If s.StartsWith(\"[\") And s.EndsWith(\"]\") Then\n g = s.Substring(\"[\".Length, s.Length - \"[]\".Length)\n Else\n Dim ss() As String = s.Split(New Char() {\"=\"c}, 2)\n If ss.Length = 2 Then\n Console.WriteLine(\"{0}.{1}={2}\", g, Trim(ss(0)), Trim(ss(1)))\n End If\n End If\n Loop\nEnd Using\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
] |
161,093
|
<p>I have a table that looks like that:</p>
<p><img src="https://i.stack.imgur.com/R0TIr.jpg" alt="alt text"></p>
<p>The rows are sorted by CLNDR_DATE DESC.</p>
<p>I need to find a CLNDR_DATE that corresponds to the highlighted row, in other words:<br>
Find the topmost group of rows WHERE EFFECTIVE_DATE IS NOT NULL,
and return the CLNR_DATE of a last row of that group.</p>
<p>Normally I would open a cursor and cycle from top to bottom until I find a NULL in EFFECTIVE_DATE. Then I would know that the date I am looking for is CLNDR_DATE, obtained at the previous step.</p>
<p>However, I wonder if the same can be achieved with a single SQL?</p>
|
[
{
"answer_id": 161105,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 4,
"selected": true,
"text": "SELECT min(CLNDR_DATE) FROM [TABLE]\nWHERE (EFFECTIVE_DATE IS NOT NULL)\n AND (CLNDR_DATE > (\n SELECT max(CLNDR_DATE) FROM [TABLE] WHERE EFFECTIVE_DATE IS NULL\n ))\n"
},
{
"answer_id": 161109,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 0,
"selected": false,
"text": "SELECT CLNDR_DATE \nFROM TABLE\nWHERE CLNDR_DATE > (SELECT MAX(CLNDR_DATE)\n FROM TABLE \n WHERE EFFECTIVE_DATE IS NOT NULL)\nORDER BY CLNDR_DATE\n"
},
{
"answer_id": 161150,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 1,
"selected": false,
"text": "select *\nfrom\n(\n select \n clndr_date, \n effective_date, \n lag(clndr_date, 1, null) over (order by clndr_date desc) prev_clndr_date\n from table\n)\nwhere effective_date is null\n lag(clndr_date, 1, null) over (order by clndr_date desc)"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10557/"
] |
161,108
|
<p>I've been developing web applications for a while and i am quite comfortable with mySql, in fact as many do i use some form of SQL almost every day. I like the syntax and a have zero problems writing queries or optimizing my tables. I have enjoyed this mysql <a href="http://www.tmtm.org/en/mysql/ruby/" rel="nofollow noreferrer">api</a>.</p>
<p>The thing that has been bugging me is Ruby on Rails uses ActiveRecord and migrates everything so you use functions to query the database. I suppose the idea being you "never have to look at SQL again". Maybe this isn't KISS (keep it simple stupid) but is the ActiveRecord interface really best? If so why? </p>
<p>Is development without having to ever write a SQL statement healthy? What if you ever have to look something up that isn't already defined as a rails function? I know they have a function that allows me to do a custom query. I guess really i want to know what people think the advantages are of using ActiveRecord over mySQL and if anyone feels like me that maybe this would be for the rails community what the calculator was to the math community and some people might forget how to do long division.</p>
|
[
{
"answer_id": 162267,
"author": "François Beausoleil",
"author_id": 7355,
"author_profile": "https://Stackoverflow.com/users/7355",
"pm_score": 3,
"selected": true,
"text": "Post.find(1)\n SELECT * FROM posts WHERE posts.id = 1\n class Post < ActiveRecord::Base\n validates_presence_of :title\n validates_length_of :title, :maximum => 80\nend\n if params[:post][:title].blank? then\n # complain\nelsif params[:post][:title].length > 80 then\n # complain again\nend\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18159/"
] |
161,123
|
<p>I want Netbeans 6.1 to store the .netbeans directory in another place than the default. How do I do this?</p>
|
[
{
"answer_id": 161142,
"author": "cretzel",
"author_id": 18722,
"author_profile": "https://Stackoverflow.com/users/18722",
"pm_score": 0,
"selected": false,
"text": " <Netbeans>/etc/netbeans.conf\n\n netbeans_default_userdir=<dir>\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18722/"
] |
161,127
|
<p>We have a scenario where we want to display a list of items and indicate which is the "current" item (with a little arrow marker or a changed background colour).</p>
<p>ItemsControl is no good to us, because we need the context of "SelectedItem". However, we want to move the selection programattically and not allow the user to change it.</p>
<p>Is there a simple way to make a ListBox non-interactive? We can fudge it by deliberately swallowing mouse and keyboard events, but am I missing some fundamental property (like setting "IsEnabled" to false without affecting its visual style) that gives us what we want?</p>
<p>Or ... is there another WPF control that's the best of both worlds - an ItemsControl with a SelectedItem property?</p>
|
[
{
"answer_id": 161232,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 1,
"selected": false,
"text": " <ItemsControl DataContext=\"{Binding Source={StaticResource Things}}\" ItemsSource=\"{Binding}\" Margin=\"0\">\n <ItemsControl.Resources>\n <local:SelectedConverter x:Key=\"conv\"/>\n </ItemsControl.Resources>\n <ItemsControl.ItemsPanel>\n <ItemsPanelTemplate>\n <local:Control Background=\"{Binding Path=IsSelected, Converter={StaticResource conv}}\"/>\n </ItemsPanelTemplate>\n </ItemsControl.ItemsPanel>\n"
},
{
"answer_id": 161366,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 5,
"selected": true,
"text": "ListBoxItem.IsEnabled false <ListBox x:Name=\"_listBox\">\n <ListBox.ItemContainerStyle>\n <Style TargetType=\"ListBoxItem\">\n <Setter Property=\"IsEnabled\" Value=\"False\"/>\n </Style>\n </ListBox.ItemContainerStyle>\n</ListBox>\n <ListBox x:Name=\"_listBox\">\n <ListBox.ItemContainerStyle>\n <Style TargetType=\"ListBoxItem\">\n <Setter Property=\"IsEnabled\" Value=\"False\"/>\n <Style.Triggers>\n <Trigger Property=\"IsEnabled\" Value=\"False\">\n <Setter Property=\"Foreground\" Value=\"Red\" />\n </Trigger>\n </Style.Triggers>\n </Style>\n </ListBox.ItemContainerStyle>\n</ListBox>\n"
},
{
"answer_id": 4939276,
"author": "Jim",
"author_id": 608909,
"author_profile": "https://Stackoverflow.com/users/608909",
"pm_score": 2,
"selected": false,
"text": " private void lstSMTs_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)\n {\n e.Handled = !editRights;\n }\n"
},
{
"answer_id": 69809258,
"author": "Mike Nakis",
"author_id": 773113,
"author_profile": "https://Stackoverflow.com/users/773113",
"pm_score": 2,
"selected": false,
"text": "<ListBox IsHitTestVisible=\"False\">\n <ScrollViewer>\n <ListBox IsHitTestVisible=\"False\">\n </ListBox>\n</ScrollViewer>\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615/"
] |
161,166
|
<p>Currently I'm trying to erase a sequence of iterators from a set, however GCC's standard library seems to be broken because std::set::erase(iterator) should return the an iterator (next iterator), however in GCC it returns void (which is standard?)</p>
<p>Anyways I want to write:</p>
<pre><code>myIter = mySet.erase(myIter);
</code></pre>
<p>But GCC doesn't like it...
So Is it safe to write this instead?</p>
<pre><code>mySet.erase(myIter++);
</code></pre>
<p>Edit: And yes I'm checking against mySet.end();</p>
|
[
{
"answer_id": 161239,
"author": "Camille",
"author_id": 16990,
"author_profile": "https://Stackoverflow.com/users/16990",
"pm_score": 4,
"selected": true,
"text": "mySet.erase(myIter++);\n"
},
{
"answer_id": 161254,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 2,
"selected": false,
"text": "void erase(iterator position);\n iterator to_erase = myIter++;\nmySet.erase(to_erase);\n// Now myIter is still on the next element\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] |
161,176
|
<p>I am working on an ASP site hosted using SUN One (used to be called Chillisoft) server. I am having trouble loading in an XML file, the code I am using is below</p>
<pre><code>dim directory
set directory = Server.CreateObject("MSXML2.DOMDocument")
if(directory.load(Server.MapPath("directory.xml"))) then
Response.Write("Loaded")
else
Response.Write("NotLoaded")
If directory.parseError.errorCode Then
Response.Write( "Parse error" )
end if
end if
</code></pre>
<p>My asp page and directory.xml are both in the same folder "/public_html/".</p>
<p>I think the problem might have something to do with the mappath not finding the file, but no errors are returned so not sure what to do.</p>
<p>Thanks</p>
|
[
{
"answer_id": 161245,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 1,
"selected": false,
"text": "Set directory = Server.CreateObject(\"MSXML2.DOMDocument\")\ndirectory.async = false\ndirectory.load(Server.MapPath(\"directory.xml\")\n Response.Write(Server.MapPath(\"directory.xml\"))\n Dim direcotory\nSet directory = Server.CreateObject(\"MSXML.DOMDocument\")\nResponse.Write(Not (directory Is Nothing))\n"
},
{
"answer_id": 168450,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 0,
"selected": false,
"text": "1 Response.Write(directory.async)"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
161,177
|
<p>Does C++ support '<a href="http://java.sun.com/docs/books/tutorial/essential/exceptions/finally.html" rel="noreferrer"><strong>finally</strong></a>' blocks?</p>
<p>What is the <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="noreferrer"><strong>RAII idiom</strong></a>?</p>
<p>What is the difference between C++'s RAII idiom and <a href="http://www.c-sharpcorner.com/uploadfile/dipalchoksi/usingstatement11092005065819am/usingstatement.aspx" rel="noreferrer"><strong>C#'s 'using' statement</strong></a>?</p>
|
[
{
"answer_id": 161179,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": 8,
"selected": false,
"text": "// A class with implements RAII\nclass lock\n{\n mutex &m_;\n\npublic:\n lock(mutex &m)\n : m_(m)\n {\n m.acquire();\n }\n ~lock()\n {\n m_.release();\n }\n};\n\n// A class which uses 'mutex' and 'lock' objects\nclass foo\n{\n mutex mutex_; // mutex for locking 'foo' object\npublic:\n void bar()\n {\n lock scopeLock(mutex_); // lock object.\n\n foobar(); // an operation which may throw an exception\n\n // scopeLock will be destructed even if an exception\n // occurs, which will release the mutex and allow\n // other functions to lock the object and run.\n }\n};\n"
},
{
"answer_id": 161203,
"author": "SmacL",
"author_id": 22564,
"author_profile": "https://Stackoverflow.com/users/22564",
"pm_score": 3,
"selected": false,
"text": "int CMyApp::Run() \n{\n __try\n {\n int i = CWinApp::Run();\n m_Exitok = MAGIC_EXIT_NO;\n return i;\n }\n __finally\n {\n if (m_Exitok != MAGIC_EXIT_NO)\n FaultHandler();\n }\n}\n"
},
{
"answer_id": 161247,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 6,
"selected": false,
"text": "void someFunc()\n{\n DB db(\"DBDesciptionString\");\n // Use the db object.\n\n} // db goes out of scope and destructor closes the connection.\n // This happens even in the presence of exceptions.\n void someFunc()\n{\n DB db = new DB(\"DBDesciptionString\");\n try\n {\n // Use the db object.\n }\n finally\n {\n // Can not rely on finaliser.\n // So we must explicitly close the connection.\n try\n {\n db.close();\n }\n catch(Throwable e)\n {\n /* Ignore */\n // Make sure not to throw exception if one is already propagating.\n }\n }\n}\n"
},
{
"answer_id": 2701414,
"author": "Unhandled exception",
"author_id": 324539,
"author_profile": "https://Stackoverflow.com/users/324539",
"pm_score": -1,
"selected": false,
"text": "try\n{\n ...\n goto finally;\n}\ncatch(...)\n{\n ...\n goto finally;\n}\nfinally:\n{\n ...\n}\n"
},
{
"answer_id": 2958622,
"author": "Mephane",
"author_id": 356532,
"author_profile": "https://Stackoverflow.com/users/356532",
"pm_score": 3,
"selected": false,
"text": "void DoStuff(vector<string> input)\n{\n list<Foo*> myList;\n\n try\n { \n for (int i = 0; i < input.size(); ++i)\n {\n Foo* tmp = new Foo(input[i]);\n if (!tmp)\n throw;\n\n myList.push_back(tmp);\n }\n\n DoSomeStuff(myList);\n }\n finally\n {\n while (!myList.empty())\n {\n delete myList.back();\n myList.pop_back();\n }\n }\n}\n void DoStuff(vector<string> input)\n{\n list<Foo*> myList;\n\n try\n { \n for (int i = 0; i < input.size(); ++i)\n {\n Foo* tmp = new Foo(input[i]);\n if (!tmp)\n throw;\n\n myList.push_back(tmp);\n }\n\n DoSomeStuff(myList);\n }\n catch(...)\n {\n }\n\n while (!myList.empty())\n {\n delete myList.back();\n myList.pop_back();\n }\n}\n"
},
{
"answer_id": 23962251,
"author": "bcmpinc",
"author_id": 558366,
"author_profile": "https://Stackoverflow.com/users/558366",
"pm_score": 2,
"selected": false,
"text": "int * array = new int[10000000];\ntry {\n // Some code that can throw exceptions\n // ...\n throw std::exception();\n // ...\n} catch (...) {\n // The finally-block (if an exception is thrown)\n delete[] array;\n // re-throw the exception.\n throw; \n}\n// The finally-block (if no exception was thrown)\ndelete[] array;\n return"
},
{
"answer_id": 24663837,
"author": "Mark Lakata",
"author_id": 364818,
"author_profile": "https://Stackoverflow.com/users/364818",
"pm_score": 1,
"selected": false,
"text": "unique_ptr #include <vector>\n#include <memory>\n#include <list>\nusing namespace std;\n\nclass Foo\n{\n ...\n};\n\nvoid DoStuff(vector<string> input)\n{\n list<unique_ptr<Foo> > myList;\n\n for (int i = 0; i < input.size(); ++i)\n {\n myList.push_back(unique_ptr<Foo>(new Foo(input[i])));\n }\n\n DoSomeStuff(myList);\n}\n"
},
{
"answer_id": 25510879,
"author": "Paolo.Bolzoni",
"author_id": 1876111,
"author_profile": "https://Stackoverflow.com/users/1876111",
"pm_score": 6,
"selected": false,
"text": "namespace detail { //adapt to your \"private\" namespace\ntemplate <typename F>\nstruct FinalAction {\n FinalAction(F f) : clean_{f} {}\n ~FinalAction() { if(enabled_) clean_(); }\n void disable() { enabled_ = false; };\n private:\n F clean_;\n bool enabled_{true}; }; }\n\ntemplate <typename F>\ndetail::FinalAction<F> finally(F f) {\n return detail::FinalAction<F>(f); }\n #include <iostream>\nint main() {\n int* a = new int;\n auto delete_a = finally([a] { delete a; std::cout << \"leaving the block, deleting a!\\n\"; });\n std::cout << \"doing something ...\\n\"; }\n doing something...\nleaving the block, deleting a!\n [...]\n auto precision = std::cout.precision();\n auto set_precision_back = finally( [precision, &std::cout]() { std::cout << std::setprecision(precision); } );\n std::cout << std::setprecision(3);\n //strong guarantee\nvoid copy_to_all(BIGobj const& a) {\n first_.push_back(a);\n auto undo_first_push = finally([first_&] { first_.pop_back(); });\n\n second_.push_back(a);\n auto undo_second_push = finally([second_&] { second_.pop_back(); });\n\n third_.push_back(a);\n //no necessary, put just to make easier to add containers in the future\n auto undo_third_push = finally([third_&] { third_.pop_back(); });\n\n undo_first_push.disable();\n undo_second_push.disable();\n undo_third_push.disable(); }\n #include <iostream>\nint main() {\n int* a = new int;\n\n struct Delete_a_t {\n Delete_a_t(int* p) : p_(p) {}\n ~Delete_a_t() { delete p_; std::cout << \"leaving the block, deleting a!\\n\"; }\n int* p_;\n } delete_a(a);\n\n std::cout << \"doing something ...\\n\"; }\n"
},
{
"answer_id": 32349333,
"author": "jave.web",
"author_id": 1835470,
"author_profile": "https://Stackoverflow.com/users/1835470",
"pm_score": 0,
"selected": false,
"text": "try{\n // something that might throw exception\n} catch( ... ){\n // what to do with uknown exception\n}\n\n//final code to be called always,\n//don't forget that it might throw some exception too\ndoSomeCleanUp(); \n exit() something wrong! #include <stdio.h>\n#include <iostream>\n#include <string>\n\nstd::string test() {\n try{\n // something that might throw exception\n throw \"exceptiooon!\";\n\n return \"fine\";\n } catch( ... ){\n return \"something wrong!\";\n }\n \n return \"finally\";\n}\n\nint main(void) {\n \n std::cout << test();\n \n \n return 0;\n}\n"
},
{
"answer_id": 34010851,
"author": "Mark Lakata",
"author_id": 364818,
"author_profile": "https://Stackoverflow.com/users/364818",
"pm_score": 3,
"selected": false,
"text": "finally nullptr extern Queue downstream, upstream;\n\n int Example()\n {\n try\n {\n while(!ExitRequested())\n {\n X* x = upstream.pop();\n if (!x) break;\n x->doSomething();\n downstream.push(x);\n } \n }\n finally { \n downstream.push(nullptr);\n }\n }\n downstream push(nullptr) downstream nullptr class Finally\n {\n public:\n\n Finally(std::function<void(void)> callback) : callback_(callback)\n {\n }\n ~Finally()\n {\n callback_();\n }\n std::function<void(void)> callback_;\n };\n extern Queue downstream, upstream;\n\n int Example()\n {\n Finally atEnd([](){ \n downstream.push(nullptr);\n });\n while(!ExitRequested())\n {\n X* x = upstream.pop();\n if (!x) break;\n x->doSomething();\n downstream.push(x);\n }\n }\n"
},
{
"answer_id": 38701485,
"author": "Fabio A.",
"author_id": 566849,
"author_profile": "https://Stackoverflow.com/users/566849",
"pm_score": 2,
"selected": false,
"text": "finally finally std::exception_ptr std::promise C++11 #include <future>\n\ntemplate <typename Fun>\nclass FinallyHelper {\n template <typename T> struct TypeWrapper {};\n using Return = typename std::result_of<Fun()>::type;\n\npublic: \n FinallyHelper(Fun body) {\n try {\n execute(TypeWrapper<Return>(), body);\n }\n catch(...) {\n m_promise.set_exception(std::current_exception());\n }\n }\n\n Return get() {\n return m_promise.get_future().get();\n }\n\nprivate:\n template <typename T>\n void execute(T, Fun body) {\n m_promise.set_value(body());\n }\n\n void execute(TypeWrapper<void>, Fun body) {\n body();\n }\n\n std::promise<Return> m_promise;\n};\n\ntemplate <typename Fun>\nFinallyHelper<Fun> make_finally_helper(Fun body) {\n return FinallyHelper<Fun>(body);\n}\n #define try_with_finally for(auto __finally_helper = make_finally_helper([&] { try \n#define finally }); \\\n true; \\\n ({return __finally_helper.get();})) \\\n/***/\n void test() {\n try_with_finally {\n raise_exception();\n } \n\n catch(const my_exception1&) {\n /*...*/\n }\n\n catch(const my_exception2&) {\n /*...*/\n }\n\n finally {\n clean_it_all_up();\n } \n}\n std::promise std::promise finally break try catch() catch() try try catch()'s finally void finally_noreturn"
},
{
"answer_id": 47574378,
"author": "anton_rh",
"author_id": 5447906,
"author_profile": "https://Stackoverflow.com/users/5447906",
"pm_score": 4,
"selected": false,
"text": "template <typename TCode, typename TFinallyCode>\ninline void with_finally(const TCode &code, const TFinallyCode &finally_code)\n{\n try\n {\n code();\n }\n catch (...)\n {\n try\n {\n finally_code();\n }\n catch (...) // Maybe stupid check that finally_code mustn't throw.\n {\n std::terminate();\n }\n throw;\n }\n finally_code();\n}\n with_finally(\n [&]()\n {\n try\n {\n // Doing some stuff that may throw an exception\n }\n catch (const exception1 &)\n {\n // Handling first class of exceptions\n }\n catch (const exception2 &)\n {\n // Handling another class of exceptions\n }\n // Some classes of exceptions can be still unhandled\n },\n [&]() // finally\n {\n // This code will be executed in all three cases:\n // 1) exception was not thrown at all\n // 2) exception was handled by one of the \"catch\" blocks above\n // 3) exception was not handled by any of the \"catch\" block above\n }\n);\n // Please never throw exception below. It is needed to avoid a compilation error\n// in the case when we use \"begin_try ... finally\" without any \"catch\" block.\nclass never_thrown_exception {};\n\n#define begin_try with_finally([&](){ try\n#define finally catch(never_thrown_exception){throw;} },[&]()\n#define end_try ) // sorry for \"pascalish\" style :(\n begin_try\n{\n // A code that may throw\n}\ncatch (const some_exception &)\n{\n // Handling some exceptions\n}\nfinally\n{\n // A code that is always executed\n}\nend_try; // Sorry again for this ugly thing\n void function(std::vector<const char*> &vector)\n{\n int *arr1 = (int*)malloc(800*sizeof(int));\n if (!arr1) { throw \"cannot malloc arr1\"; }\n ON_FINALLY({ free(arr1); });\n\n int *arr2 = (int*)malloc(900*sizeof(int));\n if (!arr2) { throw \"cannot malloc arr2\"; }\n ON_FINALLY({ free(arr2); });\n\n vector.push_back(\"good\");\n ON_EXCEPTION({ vector.pop_back(); });\n\n ...\n"
},
{
"answer_id": 51738786,
"author": "tobi_s",
"author_id": 8680401,
"author_profile": "https://Stackoverflow.com/users/8680401",
"pm_score": 3,
"selected": false,
"text": "finally finally finally finally #include <gsl/gsl_util.h>\n\nvoid example()\n{\n int handle = get_some_resource();\n auto handle_clean = gsl::finally([&handle] { clean_that_resource(handle); });\n\n // Do a lot of stuff, return early and throw exceptions.\n // clean_that_resource will always get called.\n}\n gsl::finally() disable()"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6386/"
] |
161,200
|
<p>Is there a way to upload a file to a FTP server when behind an HTTP proxy ?</p>
<p>It seems that uploading a file is not supported behind an HTTP Proxy using .Net Webclient. (<a href="http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.proxy.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.proxy.aspx</a>).</p>
<p>If there is no workaround ? If not, do you know a good and free FTP library I can use ?</p>
<p><strong>Edit</strong>: Unfortunately, I don't have any FTP proxy to connect to.</p>
|
[
{
"answer_id": 161807,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 3,
"selected": false,
"text": "FtpWebRequest FtpWebRequest"
},
{
"answer_id": 162321,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 2,
"selected": false,
"text": "CONNECT myserver:21 HTTP/1.0 HTTP/1.0 200 HTTP/1.1 200 "
},
{
"answer_id": 919660,
"author": "Martin Vobr",
"author_id": 16132,
"author_profile": "https://Stackoverflow.com/users/16132",
"pm_score": 3,
"selected": false,
"text": "// initialize FTP client \nFtp client = new Ftp();\n\n// setup proxy details \nclient.Proxy.ProxyType = FtpProxyType.HttpConnect;\nclient.Proxy.Host = proxyHostname;\nclient.Proxy.Port = proxyPort;\n\n// add proxy username and password when needed \nclient.Proxy.UserName = proxyUsername;\nclient.Proxy.Password = proxyPassword;\n\n// connect, login \nclient.Connect(hostname, port);\nclient.Login(username, password);\n\n// do some work \n// ... \n\n// disconnect \nclient.Disconnect();\n"
},
{
"answer_id": 14647742,
"author": "miconico",
"author_id": 683729,
"author_profile": "https://Stackoverflow.com/users/683729",
"pm_score": 2,
"selected": false,
"text": "FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));\n\nSystem.Net.WebProxy proxy = System.Net.WebProxy.GetDefaultProxy();\nproxy.Credentials = System.Net.CredentialCache.DefaultCredentials;\n\n// set the ftpWebRequest proxy\nreqFTP.Proxy = proxy;\n"
},
{
"answer_id": 19977124,
"author": "Elephantik",
"author_id": 123708,
"author_profile": "https://Stackoverflow.com/users/123708",
"pm_score": -1,
"selected": false,
"text": "var ctor = typeof(HttpWebRequest).GetConstructor(\n BindingFlags.NonPublic | BindingFlags.Instance, \n null, \n new Type[] { typeof(Uri), typeof(ServicePoint) }, \n null);\nvar req = (WebRequest)ctor.Invoke(new object[] { new Uri(\"ftp://user:pass@host/test.txt\"), null });\nreq.Proxy = new WebProxy(\"myproxy\", 8080);\nreq.Method = WebRequestMethods.Http.Put;\n\nusing (var inStream = req.GetRequestStream())\n{\n var buffer = Encoding.ASCII.GetBytes(\"test upload\");\n inStream.Write(buffer, 0, buffer.Length);\n}\n\nusing (req.GetResponse())\n{\n}\n"
},
{
"answer_id": 20353753,
"author": "A. 'Eradicator' Polyakov",
"author_id": 3061817,
"author_profile": "https://Stackoverflow.com/users/3061817",
"pm_score": 0,
"selected": false,
"text": " public bool UploadFile(string localFilePath, string remoteDirectory)\n {\n var fileName = Path.GetFileName(localFilePath);\n string content;\n using (var reader = new StreamReader(localFilePath))\n content = reader.ReadToEnd();\n\n var proxyAuthB64Str = Convert.ToBase64String(Encoding.ASCII.GetBytes(_proxyUserName + \":\" + _proxyPassword));\n var sendStr = \"PUT ftp://\" + _ftpLogin + \":\" + _ftpPassword\n + \"@\" + _ftpHost + remoteDirectory + fileName + \" HTTP/1.1\\n\"\n + \"Host: \" + _ftpHost + \"\\n\"\n + \"User-Agent: Mozilla/4.0 (compatible; Eradicator; dotNetClient)\\n\" + \"Proxy-Authorization: Basic \" + proxyAuthB64Str + \"\\n\"\n + \"Content-Type: application/octet-stream\\n\"\n + \"Content-Length: \" + content.Length + \"\\n\"\n + \"Connection: close\\n\\n\" + content;\n\n var sendBytes = Encoding.ASCII.GetBytes(sendStr);\n\n using (var proxySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))\n {\n proxySocket.Connect(_proxyHost, _proxyPort);\n if (!proxySocket.Connected)\n throw new SocketException();\n proxySocket.Send(sendBytes);\n\n const int recvSize = 65536;\n var recvBytes = new byte[recvSize];\n proxySocket.Receive(recvBytes, recvSize, SocketFlags.Partial);\n\n var responseFirstLine = new string(Encoding.ASCII.GetChars(recvBytes)).Split(\"\\n\".ToCharArray()).Take(1).ElementAt(0);\n var httpResponseCode = Regex.Replace(responseFirstLine, @\"HTTP/1\\.\\d (\\d+) (\\w+)\", \"$1\");\n var httpResponseDescription = Regex.Replace(responseFirstLine, @\"HTTP/1\\.\\d (\\d+) (\\w+)\", \"$2\");\n return httpResponseCode.StartsWith(\"2\");\n }\n return false;\n }\n"
},
{
"answer_id": 33503062,
"author": "Martin Prikryl",
"author_id": 850848,
"author_profile": "https://Stackoverflow.com/users/850848",
"pm_score": 2,
"selected": false,
"text": "FtpWebRequest FtpWebRequest // Setup session options\nSessionOptions sessionOptions = new SessionOptions\n{\n Protocol = Protocol.Ftp,\n HostName = \"example.com\",\n UserName = \"user\",\n Password = \"mypassword\",\n};\n\n// Configure proxy\nsessionOptions.AddRawSettings(\"ProxyMethod\", \"3\");\nsessionOptions.AddRawSettings(\"ProxyHost\", \"proxy\");\n\nusing (Session session = new Session())\n{\n // Connect\n session.Open(sessionOptions);\n\n // Upload file\n string localFilePath = @\"C:\\path\\file.txt\";\n string pathUpload = \"/file.txt\";\n session.PutFiles(localFilePath, pathUpload).Check();\n}\n SessionOptions.AddRawSettings"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22970/"
] |
161,212
|
<p>I need to be able to periodically send email alerts to subscribed users. PHP seems to struggle with sending <em>one</em> message, so I'm looking for good alternatives.</p>
<p>Any language will do, if the implementation is fast enough. The amount of mails sent will eventually be in the thousands.</p>
<p>If purchasing licensed software can be avoided, so much the better.</p>
|
[
{
"answer_id": 162087,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 1,
"selected": false,
"text": "MAIL FROM:<me@example.com>\nRCPT TO:<you@example.com>\nDATA\nFrom: Me <me@example.com>\nTo: You <you@example.com>\nSubject: test email\n\nThis is the body of the test email I'm sending\n.\n cat *.bsmtp | exim -bS\n MAIL FROM:<me@example.com>\nRCPT TO:<you@example.com>\nRCPT TO:<him@example.com>\nRCPT TO:<her@example.com>\nRCPT TO:<them@example.com>\nDATA\nFrom: Me <me@example.com>\nTo: Me <me@example.com>\nSubject: test email\n\nThis is the body of the test email I'm sending\n.\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21716/"
] |
161,221
|
<p>I am using the System.Web.Routing assembly in a WebForms application. When running the application deployed on win2008/IIS7 I got the following message.</p>
<blockquote>
<p>Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the \\ section in the application configuration. </p>
</blockquote>
<p>This is only a problem when using a route I have configured. It is not a problem when directly navigating to an aspx page.</p>
<p>EnableSessionState has been turned on in both the web.config and the Page directive. I have added the Session entry to httpmodule of the web.config.</p>
<p>This is not an issue when developing using Visual Studio on my workstation. It is only a problem when trying to run the application under IIS7 on Win 2008.</p>
|
[
{
"answer_id": 950695,
"author": "SirDemon",
"author_id": 80813,
"author_profile": "https://Stackoverflow.com/users/80813",
"pm_score": 1,
"selected": false,
"text": "IRouteHandler"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5360/"
] |
161,222
|
<p>I've been using maven2 and hudson for a while to do my continuous integration, but I find that Eclipse and Maven do not play well together. Sure there's a plugin, but it's cranky to mash the maven project into something that eclipse likes and the build times and unit test are too long.
I'm considering switching back to a pure eclipse project with no ant and no maven involved. With the infinitest plugin and possible the JavaRebel agent, it would give me a very fast build-deploy-test cycle. However I'd still like to have automatic and testing as well, so:</p>
<p>How do I use continuous integration with an Eclipse project?</p>
<p>Is there a command line way to do it? </p>
<p>Is there a build server that already supports it natively?</p>
|
[
{
"answer_id": 161476,
"author": "Valters Vingolds",
"author_id": 885,
"author_profile": "https://Stackoverflow.com/users/885",
"pm_score": 2,
"selected": false,
"text": "mvn -o verify -Ditest <profiles>\n <profile>\n <id>integration-test</id>\n <activation>\n <property>\n <name>itest</name>\n </property>\n </activation>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-surefire-plugin</artifactId>\n <executions>\n <execution>\n <id>itest</id>\n </execution>\n </executions>\n <configuration>\n <testSourceDirectory>src/main</testSourceDirectory>\n <testClassesDirectory>target/classes</testClassesDirectory>\n <forkMode>once</forkMode>\n </configuration>\n </plugin>\n </plugins>\n </build>\n </profile>\n</profiles>\n"
},
{
"answer_id": 229724,
"author": "s3v1",
"author_id": 17554,
"author_profile": "https://Stackoverflow.com/users/17554",
"pm_score": 3,
"selected": true,
"text": "<dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>4.5</version>\n <!-- <scope>provided</scope> -->\n </dependency>\n\n <dependency>\n <groupId>org.infinitest</groupId>\n <artifactId>infinitest</artifactId>\n <scope>test</scope>\n <version>4.0</version>\n </dependency>\n\n</dependencies>\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17554/"
] |
161,224
|
<p>Hibernate has a handful of methods that, one way or another, takes your object and puts it into the database. What are the differences between them, when to use which, and why isn't there just one intelligent method that knows when to use what?</p>
<p>The methods that I have identified thus far are:</p>
<ul>
<li><code>save()</code></li>
<li><code>update()</code></li>
<li><code>saveOrUpdate()</code></li>
<li><code>saveOrUpdateCopy()</code></li>
<li><code>merge()</code></li>
<li><code>persist()</code></li>
</ul>
|
[
{
"answer_id": 10100479,
"author": "Hari Krishna",
"author_id": 1325738,
"author_profile": "https://Stackoverflow.com/users/1325738",
"pm_score": 3,
"selected": false,
"text": "save() persist() save() persist( save() persist() save() long s = session.save(k);\n persist()"
},
{
"answer_id": 17040611,
"author": "HakunaMatata",
"author_id": 1418801,
"author_profile": "https://Stackoverflow.com/users/1418801",
"pm_score": 4,
"selected": false,
"text": " Session session = sessionFactory1.openSession();\n Transaction tx = session.beginTransaction();\n Item item = (Item) session.get(Item.class, new Long(1234));\n tx.commit();\n session.close(); // end of first session, item is detached\n\n item.getId(); // The database identity is \"1234\"\n item.setDescription(\"my new description\");\n Session session2 = sessionFactory.openSession();\n Transaction tx2 = session2.beginTransaction();\n Item item2 = (Item) session2.get(Item.class, new Long(1234));\n session2.update(item); // Throws NonUniqueObjectException\n tx2.commit();\n session2.close();\n Session session = sessionFactory1.openSession();\n Transaction tx = session.beginTransaction();\n Item item = (Item) session.get(Item.class, new Long(1234));\n tx.commit();\n session.close(); // end of first session, item is detached\n\n item.getId(); // The database identity is \"1234\"\n item.setDescription(\"my new description\");\n Session session2 = sessionFactory.openSession();\n Transaction tx2 = session2.beginTransaction();\n Item item2 = (Item) session2.get(Item.class, new Long(1234));\n Item item3 = session2.merge(item); // Success!\n tx2.commit();\n session2.close();\n"
},
{
"answer_id": 18600952,
"author": "Sergii Shevchyk",
"author_id": 946224,
"author_profile": "https://Stackoverflow.com/users/946224",
"pm_score": 7,
"selected": false,
"text": "╔══════════════╦═══════════════════════════════╦════════════════════════════════╗\n║ METHOD ║ TRANSIENT ║ DETACHED ║\n╠══════════════╬═══════════════════════════════╬════════════════════════════════╣\n║ ║ sets id if doesn't ║ sets new id even if object ║\n║ save() ║ exist, persists to db, ║ already has it, persists ║\n║ ║ returns attached object ║ to DB, returns attached object ║\n╠══════════════╬═══════════════════════════════╬════════════════════════════════╣\n║ ║ sets id on object ║ throws ║\n║ persist() ║ persists object to DB ║ PersistenceException ║\n║ ║ ║ ║\n╠══════════════╬═══════════════════════════════╬════════════════════════════════╣\n║ ║ ║ ║\n║ update() ║ Exception ║ persists and reattaches ║\n║ ║ ║ ║\n╠══════════════╬═══════════════════════════════╬════════════════════════════════╣\n║ ║ copy the state of object in ║ copy the state of obj in ║\n║ merge() ║ DB, doesn't attach it, ║ DB, doesn't attach it, ║\n║ ║ returns attached object ║ returns attached object ║\n╠══════════════╬═══════════════════════════════╬════════════════════════════════╣\n║ ║ ║ ║\n║saveOrUpdate()║ as save() ║ as update() ║\n║ ║ ║ ║\n╚══════════════╩═══════════════════════════════╩════════════════════════════════╝\n"
},
{
"answer_id": 53428776,
"author": "GingerBeer",
"author_id": 7409356,
"author_profile": "https://Stackoverflow.com/users/7409356",
"pm_score": 0,
"selected": false,
"text": "Session ses1 = sessionFactory.openSession();\n\n Transaction tx1 = ses1.beginTransaction();\n\n HibEntity entity = getHibEntity();\n\n ses1.persist(entity);\n ses1.evict(entity);\n\n ses1.merge(entity);\n\n ses1.delete(entity);\n\n tx1.commit();\n Session ses1 = sessionFactory.openSession();\n\n Transaction tx1 = ses1.beginTransaction();\n HibEntity entity = getHibEntity();\n\n ses1.persist(entity);\n ses1.evict(entity);\n\n HibEntity copied = (HibEntity)ses1.merge(entity);\n ses1.delete(copied);\n\n tx1.commit();\n Session ses1 = sessionFactory.openSession();\n\n Transaction tx1 = ses1.beginTransaction();\n\n HibEntity entity = getHibEntity();\n\n ses1.persist(entity);\n ses1.evict(entity);\n\n ses1.update(entity);\n\n ses1.delete(entity);\n\n tx1.commit();\n"
},
{
"answer_id": 54907032,
"author": "Vlad Mihalcea",
"author_id": 1025118,
"author_profile": "https://Stackoverflow.com/users/1025118",
"pm_score": 5,
"selected": false,
"text": "update EntityManager Session EntityManager save saveOrUpdate update persist EntityManager Session persist PersistEvent DefaultPersistEventListener doInJPA(entityManager -> {\n Book book = new Book()\n .setIsbn(\"978-9730228236\")\n .setTitle(\"High-Performance Java Persistence\")\n .setAuthor(\"Vlad Mihalcea\");\n\n entityManager.persist(book);\n \n LOGGER.info(\n \"Persisting the Book entity with the id: {}\", \n book.getId()\n );\n});\n CALL NEXT VALUE FOR hibernate_sequence\n\n-- Persisting the Book entity with the id: 1\n\nINSERT INTO book (\n author, \n isbn, \n title, \n id\n) \nVALUES (\n 'Vlad Mihalcea', \n '978-9730228236', \n 'High-Performance Java Persistence', \n 1\n)\n id Book Map EntityManager Session persist flush IDENTITY IDENTITY save save SaveOrUpdateEvent DefaultSaveOrUpdateEventListener save update saveOrUpdate save doInJPA(entityManager -> {\n Book book = new Book()\n .setIsbn(\"978-9730228236\")\n .setTitle(\"High-Performance Java Persistence\")\n .setAuthor(\"Vlad Mihalcea\");\n\n Session session = entityManager.unwrap(Session.class);\n\n Long id = (Long) session.save(book);\n\n LOGGER.info(\n \"Saving the Book entity with the id: {}\", \n id\n );\n});\n CALL NEXT VALUE FOR hibernate_sequence\n\n-- Saving the Book entity with the id: 1\n\nINSERT INTO book (\n author, \n isbn, \n title, \n id\n) \nVALUES (\n 'Vlad Mihalcea', \n '978-9730228236', \n 'High-Performance Java Persistence', \n 1\n)\n persist persist save update update SaveOrUpdateEvent DefaultSaveOrUpdateEventListener update save saveOrUpdate update Book update Book _book = doInJPA(entityManager -> {\n Book book = new Book()\n .setIsbn(\"978-9730228236\")\n .setTitle(\"High-Performance Java Persistence\")\n .setAuthor(\"Vlad Mihalcea\");\n\n entityManager.persist(book);\n\n return book;\n});\n\nLOGGER.info(\"Modifying the Book entity\");\n\n_book.setTitle(\n \"High-Performance Java Persistence, 2nd edition\"\n);\n\ndoInJPA(entityManager -> {\n Session session = entityManager.unwrap(Session.class);\n\n session.update(_book);\n\n LOGGER.info(\"Updating the Book entity\");\n});\n CALL NEXT VALUE FOR hibernate_sequence\n\nINSERT INTO book (\n author, \n isbn, \n title, \n id\n) \nVALUES (\n 'Vlad Mihalcea', \n '978-9730228236', \n 'High-Performance Java Persistence', \n 1\n)\n\n-- Modifying the Book entity\n-- Updating the Book entity\n\nUPDATE \n book \nSET \n author = 'Vlad Mihalcea', \n isbn = '978-9730228236', \n title = 'High-Performance Java Persistence, 2nd edition'\nWHERE \n id = 1\n UPDATE Updating the Book entity @SelectBeforeUpdate @SelectBeforeUpdate SELECT loaded state Book @SelectBeforeUpdate @Entity(name = \"Book\")\n@Table(name = \"book\")\n@SelectBeforeUpdate\npublic class Book {\n\n //Code omitted for brevity\n}\n Book _book = doInJPA(entityManager -> {\n Book book = new Book()\n .setIsbn(\"978-9730228236\")\n .setTitle(\"High-Performance Java Persistence\")\n .setAuthor(\"Vlad Mihalcea\");\n\n entityManager.persist(book);\n\n return book;\n});\n\ndoInJPA(entityManager -> {\n Session session = entityManager.unwrap(Session.class);\n\n session.update(_book);\n});\n INSERT INTO book (\n author, \n isbn, \n title, \n id\n) \nVALUES (\n 'Vlad Mihalcea', \n '978-9730228236', \n 'High-Performance Java Persistence', \n 1\n)\n\nSELECT \n b.id,\n b.author AS author2_0_,\n b.isbn AS isbn3_0_,\n b.title AS title4_0_\nFROM \n book b\nWHERE \n b.id = 1\n UPDATE saveOrUpdate save update saveOrUpdate SaveOrUpdateEvent DefaultSaveOrUpdateEventListener update save saveOrUpdate saveOrUpdate UPDATE Book _book = doInJPA(entityManager -> {\n Book book = new Book()\n .setIsbn(\"978-9730228236\")\n .setTitle(\"High-Performance Java Persistence\")\n .setAuthor(\"Vlad Mihalcea\");\n\n Session session = entityManager.unwrap(Session.class);\n session.saveOrUpdate(book);\n\n return book;\n});\n\n_book.setTitle(\"High-Performance Java Persistence, 2nd edition\");\n\ndoInJPA(entityManager -> {\n Session session = entityManager.unwrap(Session.class);\n session.saveOrUpdate(_book);\n});\n NonUniqueObjectException save update saveOrUpdate Book _book = doInJPA(entityManager -> {\n Book book = new Book()\n .setIsbn(\"978-9730228236\")\n .setTitle(\"High-Performance Java Persistence\")\n .setAuthor(\"Vlad Mihalcea\");\n\n Session session = entityManager.unwrap(Session.class);\n session.saveOrUpdate(book);\n\n return book;\n});\n\n_book.setTitle(\n \"High-Performance Java Persistence, 2nd edition\"\n);\n\ntry {\n doInJPA(entityManager -> {\n Book book = entityManager.find(\n Book.class, \n _book.getId()\n );\n\n Session session = entityManager.unwrap(Session.class);\n session.saveOrUpdate(_book);\n });\n} catch (NonUniqueObjectException e) {\n LOGGER.error(\n \"The Persistence Context cannot hold \" +\n \"two representations of the same entity\", \n e\n );\n}\n NonUniqueObjectException EntityManager Book update org.hibernate.NonUniqueObjectException: \n A different object with the same identifier value was already associated with the session : [com.vladmihalcea.book.hpjp.hibernate.pc.Book#1]\n at org.hibernate.engine.internal.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:651)\n at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:284)\n at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:227)\n at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:92)\n at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)\n at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:682)\n at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:674)\n NonUniqueObjectException merge EntityManager Session merge merge merge MergeEvent DefaultMergeEventListener merge Book merge Book _book = doInJPA(entityManager -> {\n Book book = new Book()\n .setIsbn(\"978-9730228236\")\n .setTitle(\"High-Performance Java Persistence\")\n .setAuthor(\"Vlad Mihalcea\");\n\n entityManager.persist(book);\n\n return book;\n});\n\nLOGGER.info(\"Modifying the Book entity\");\n\n_book.setTitle(\n \"High-Performance Java Persistence, 2nd edition\"\n);\n\ndoInJPA(entityManager -> {\n Book book = entityManager.merge(_book);\n\n LOGGER.info(\"Merging the Book entity\");\n\n assertFalse(book == _book);\n});\n INSERT INTO book (\n author, \n isbn, \n title, \n id\n) \nVALUES (\n 'Vlad Mihalcea', \n '978-9730228236', \n 'High-Performance Java Persistence', \n 1\n)\n\n-- Modifying the Book entity\n\nSELECT \n b.id,\n b.author AS author2_0_,\n b.isbn AS isbn3_0_,\n b.title AS title4_0_\nFROM \n book b\nWHERE \n b.id = 1\n\n-- Merging the Book entity\n\nUPDATE \n book \nSET \n author = 'Vlad Mihalcea', \n isbn = '978-9730228236', \n title = 'High-Performance Java Persistence, 2nd edition'\nWHERE \n id = 1\n merge merge merge SELECT update persist merge update save saveOrUpdate update save"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2238/"
] |
161,231
|
<p><strong>Is there a way of forcing a (child) class to have constructors with particular signatures or particular static methods in C# or Java?</strong></p>
<p>You can't obviously use interfaces for this, and I know that it will have a limited usage. One instance in which I do find it useful is when you want to enforce some design guideline, for example:</p>
<p><strong>Exceptions</strong><br>
They should all have the four canonical constructors, but there is no way to enforce it. You have to rely on a tool like FxCop (C# case) to catch these.</p>
<p><strong>Operators</strong><br>
There is no contract that specifies that two classes can be summed (with operator+ in C#)</p>
<p>Is there any design pattern to work around this limitation?
What construct could be added to the <em>language</em> to overcome this limitation in future versions of C# or Java?</p>
|
[
{
"answer_id": 161271,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 2,
"selected": false,
"text": "class Base\n{\n private Base() { }\n public Base(int x) {}\n}\n\nclass Derived : Base\n{\n //public Derived() { } won't compile because Base() is private\n public Derived(int x) :base(x) {}\n public Derived() : base (0) {} // still works because you are giving a value to base\n}\n"
},
{
"answer_id": 161371,
"author": "jrudolph",
"author_id": 7647,
"author_profile": "https://Stackoverflow.com/users/7647",
"pm_score": 3,
"selected": false,
"text": "interface Fruit{}\n\ninterface FruitFactory<F extends Fruit>{\n F newFruit(String color,double weight);\n\n Cocktail mixFruits(F f1,F f2);\n}\n class Apple implements Fruit{}\nclass AppleFactory implements FruitFactory<Apple>{\n public Apple newFruit(String color, double weight){\n // create an instance\n }\n public Cocktail mixFruits(Apple f1,Apple f2){\n // implementation\n }\n}\n"
},
{
"answer_id": 161635,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 1,
"selected": false,
"text": "interface IFoo \n{ \n IFoo(int gottaHaveThis); \n static Bar(); \n}\n\ninterface ISummable\n{\n operator+(ISummable a, ISummable b);\n}\n new IFoo(someInt) IFoo.Bar() class Foo: IFoo\n{\n Foo(int gottaHaveThis) {};\n static Bar() {};\n}\n\nclass SonOfFoo: Foo \n{\n // SonOfFoo(int gottaHaveThis): base(gottaHaveThis); is implicitly defined\n}\n\nclass DaughterOfFoo: Foo\n{\n DaughhterOfFoo (int gottaHaveThis) {};\n}\n ISummable PassedFirstGrade = (ISummable) 10; \n"
},
{
"answer_id": 161966,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 1,
"selected": false,
"text": "class Program\n{\n static void Main(string[] args)\n {\n Console.WriteLine(Foo.Instance.GetHelloWorld());\n Console.ReadLine();\n }\n}\n\npublic class Foo : FooStaticContract<FooFactory>\n{\n public Foo() // Non-static ctor.\n {\n }\n\n internal Foo(bool st) // Overloaded, parameter not used.\n {\n }\n\n public override string GetHelloWorld()\n {\n return \"Hello World\";\n }\n}\n\npublic class FooFactory : IStaticContractFactory<Foo>\n{\n #region StaticContractFactory<Foo> Members\n\n public Foo CreateInstance()\n {\n return new Foo(true); // Call static ctor.\n }\n\n #endregion\n}\n\npublic interface IStaticContractFactory<T>\n{\n T CreateInstance();\n}\n\npublic abstract class StaticContract<T, Factory>\n where Factory : IStaticContractFactory<T>, new() \n where T : class\n{\n private static Factory _factory = new Factory();\n\n private static T _instance;\n /// <summary>\n /// Gets an instance of this class. \n /// </summary>\n public static T Instance\n {\n get\n {\n // Scary.\n if (Interlocked.CompareExchange(ref _instance, null, null) == null)\n {\n T instance = _factory.CreateInstance();\n Interlocked.CompareExchange(ref _instance, instance, null);\n }\n return _instance;\n }\n }\n}\n\npublic abstract class FooStaticContract<Factory>\n : StaticContract<Foo, Factory>\n where Factory : IStaticContractFactory<Foo>, new() \n{\n public abstract string GetHelloWorld();\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7028/"
] |
161,238
|
<p>As I understand it, the command to ignore the <em>content</em> of a directory using SVN is this:</p>
<pre><code>svn propset svn:ignore "*" tmp/
</code></pre>
<p>This should set the ignore property on the content of the <code>tmp</code> directory, right? In other words, the wildcard is set to be the ignore value on the tmp directory. Trouble is, here's what is happening on my Windows box:</p>
<pre><code>> svn propset svn:ignore "*" ./tmp
property 'svn:ignore' set on 'app'
property 'svn:ignore' set on 'config'
property 'svn:ignore' set on 'db'
property 'svn:ignore' set on 'doc'
property 'svn:ignore' set on 'lib'
property 'svn:ignore' set on 'log'
property 'svn:ignore' set on 'nbproject'
property 'svn:ignore' set on 'public'
[etc...]
</code></pre>
<p>That's not right. Am I doing something wrong (or perhaps going insane), or is my svn on Windows broken?</p>
<p><strong>Some notes:</strong></p>
<ul>
<li>The machine is running Windows Vista SP1</li>
<li>Setting this property via Tortoise works perfectly.</li>
<li>I'm using the <a href="http://www.collab.net/downloads/subversion/" rel="nofollow noreferrer">Collabnet binaries for Windows</a>:</li>
</ul>
<blockquote>
<p><code>> svn --version<br />
svn, version 1.5.2 (r32768)<br />
compiled Aug 28 2008, 19:05:34</code></p>
</blockquote>
<hr>
<p><strong><em>Update:</em></strong> I've have just tried this on a Windows XP machine and it works as expected. So either this is a Vista specific issue, or there is a problem with my Vista configuration. Is anyone else able to reproduce this problem on Vista? I have just spotted that Vista isn't listed as one of the supported platforms on the <a href="http://www.collab.net/downloads/subversion/" rel="nofollow noreferrer">CollabNet downloads page</a>.</p>
|
[
{
"answer_id": 161338,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 4,
"selected": true,
"text": "* svn propset svn:ignore [value] app config db doc lib log nbproject public ... tmp svn propset svn:ignore tmp -F .svnignore svn propset svn:ignore tmp propedit propdel svn st svn revert -R svn propset"
},
{
"answer_id": 161380,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "* -F svn propset svn:ignore tmp .\n svn:ignore . tmp/ tmp"
},
{
"answer_id": 161387,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "[C:\\Temp\\temp] :svn propset svn:ignore \"*\" tmp/\nproperty 'svn:ignore' set on 'tmp'\n [C:\\Temp\\temp] :svn proplist *\nsvn: Skipping argument: '.svn' ends in a reserved name\nProperties on 'tmp':\n svn:ignore\n"
},
{
"answer_id": 2638621,
"author": "Alexander Klimetschek",
"author_id": 2709,
"author_profile": "https://Stackoverflow.com/users/2709",
"pm_score": 1,
"selected": false,
"text": "echo \"*\" > .svnignore && svn propset svn:ignore <path> -F .svnignore && rm .svnignore\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1944/"
] |
161,251
|
<p>Is there a programming language suitable for building web applications, that is compiled, strongly-typed, and isn't ASP.NET?</p>
<p>I thought of using Mono (<a href="http://www.mono-project.com/" rel="nofollow noreferrer">http://www.mono-project.com/</a>), but I wonder if there are any other alternatives.</p>
<p>(If the language and framework are open-source, that's a big plus!)</p>
|
[
{
"answer_id": 2465962,
"author": "none",
"author_id": 78244,
"author_profile": "https://Stackoverflow.com/users/78244",
"pm_score": 2,
"selected": false,
"text": "* A Web parameters module. This module takes care of retrieving the forms or URL parameters and to build an associative table for easy access.\n* A session server, this is a very important module to be able to keep client’s data from page to page.\n* Support SOAP to develop Web Services.\n* A tool (based on ASIS) to generate a WSDL document from an Ada spec.\n* A tool to generate Web Services stubs/skeletons from a WSDL document.\n* A template parser, this module makes it possible to completely separate the Web design from the code. No more scripting into your Web page. This template engine is amazingly fast due to its concurrent cached compiled templates support.\n* An Ajax runtime based on templates hiding javascript.\n* Support for Secure Sockets (HTTPS/SSL), this is based on OpenSSL library.\n* Support for large servers using dispatchers based on URI, request methods, timers.\n* Support for virtual hosting (dispatchers based on the host name).\n* Support for server push.\n* A directory browser ready to be used in any application.\n* A status page to get many information about the current AWS server.\n* A log module. Log files keep information about all resources requested to the server.\n* Hotplug modules which can be loaded/unloaded dynamically to add specific features to a server.\n* A light communication API to exchange data between applications using the HTTP protocol.\n* A configuration API to tune/change the server parameters without recompilation.\n* A client API to retrieve any Web page from a Web site.\n* A Web Page service to build a simple static page server.\n* Support for SMTP, LDAP and Jabber protocols.\n* And more…\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23341/"
] |
161,252
|
<p>I'm trying to run some commands in paralel, in background, using bash. Here's what I'm trying to do:</p>
<pre><code>forloop {
//this part is actually written in perl
//call command sequence
print `touch .file1.lock; cp bigfile1 /destination; rm .file1.lock;`;
}
</code></pre>
<p>The part between backticks (``) spawns a new shell and executes the commands in succession. The thing is, control to the original program returns only after the last command has been executed. I would like to execute the whole statement in background (I'm not expecting any output/return values) and I would like the loop to continue running.</p>
<p>The calling program (the one that has the loop) would not end until all the spawned shells finish.</p>
<p>I could use threads in perl to spawn different threads which call different shells, but it seems an overkill...</p>
<p>Can I start a shell, give it a set of commands and tell it to go to the background?</p>
|
[
{
"answer_id": 161284,
"author": "GavinCattell",
"author_id": 21644,
"author_profile": "https://Stackoverflow.com/users/21644",
"pm_score": 4,
"selected": false,
"text": "for command in $commands\ndo\n \"$command\" &\ndone\nwait\n wait"
},
{
"answer_id": 161291,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 1,
"selected": false,
"text": "{command1 & ; command2 & ; command3 & ; }\n"
},
{
"answer_id": 161333,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 6,
"selected": true,
"text": "print `(touch .file1.lock; cp bigfile1 /destination; rm .file1.lock;) &`;\n"
},
{
"answer_id": 161383,
"author": "Mad_Ady",
"author_id": 23780,
"author_profile": "https://Stackoverflow.com/users/23780",
"pm_score": 4,
"selected": false,
"text": "adrianp@frost:~$ (echo \"started\"; sleep 15; echo \"stopped\")\nstarted\nstopped\nadrianp@frost:~$ (echo \"started\"; sleep 15; echo \"stopped\") &\nstarted\n[1] 7101\nadrianp@frost:~$ stopped\n\n[1]+ Done ( echo \"started\"; sleep 15; echo \"stopped\" )\nadrianp@frost:~$ \n"
},
{
"answer_id": 169022,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 1,
"selected": false,
"text": "my @children;\nfor (...) {\n ...\n my $child = fork;\n exec \"touch .file1.lock; cp bigfile1 /destination; rm .file1.lock;\" if $child == 0;\n push @children, $child;\n}\n# and if you want to wait for them to finish,\nwaitpid($_) for @children;\n print `some command`\n system \"some command\"\n some command"
},
{
"answer_id": 1683256,
"author": "NVRAM",
"author_id": 57582,
"author_profile": "https://Stackoverflow.com/users/57582",
"pm_score": 3,
"selected": false,
"text": "pids=\nfor file in bigfile*\ndo\n # Skip if file is not newer...\n targ=/destination/$(basename \"${file}\")\n [ \"$targ\" -nt \"$file\" ] && continue\n\n # Use a lock file: \".fileN.lock\" for each \"bigfileN\"\n lock=\".${file##*/big}.lock\"\n ( touch $lock; cp \"$file\" \"$targ\"; rm $lock ) &\n pids=\"$pids $!\"\ndone\nwait $pids\n"
},
{
"answer_id": 12404603,
"author": "Eliseo Carrasco",
"author_id": 1668355,
"author_profile": "https://Stackoverflow.com/users/1668355",
"pm_score": 2,
"selected": false,
"text": "# date\n# jue sep 13 12:43:21 CEST 2012\n# at 12:45\nwarning: commands will be executed using /bin/sh\nat> command1\nat> command2\nat> ...\nat> CTRL-d\nat> <EOT>\njob 20 at Thu Sep 13 12:45:00 2012\n"
},
{
"answer_id": 14536754,
"author": "slm",
"author_id": 33204,
"author_profile": "https://Stackoverflow.com/users/33204",
"pm_score": 2,
"selected": false,
"text": "Compound Commands (list) list is executed in a subshell environment (see COMMAND EXECUTION ENVIRONMENT below). Variable assignments and\n builtin commands that affect the shell's environment do not remain in effect after the command completes. The\n return status is the exit status of list.\n\n { list; }\n list is simply executed in the current shell environment. list must be terminated with a newline or semicolon.\n This is known as a group command. The return status is the exit status of list. Note that unlike the metacharac‐\n ters ( and ), { and } are reserved words and must occur where a reserved word is permitted to be recognized.\n Since they do not cause a word break, they must be separated from list by whitespace or another shell metacharac‐\n ter.\n % ( date; sleep 5; date; )\nSat Jan 26 06:52:46 EST 2013\nSat Jan 26 06:52:51 EST 2013\n % { date; sleep 5; date; }\nSat Jan 26 06:52:13 EST 2013\nSat Jan 26 06:52:18 EST 2013\n"
},
{
"answer_id": 19029366,
"author": "lechup",
"author_id": 479931,
"author_profile": "https://Stackoverflow.com/users/479931",
"pm_score": 5,
"selected": false,
"text": "{ command1; command2; command3; } &\nwait\n & wait stderr stdout { command1; command2; command3; } 2>&2 1>&1 &\n forloop() {\n { touch .file1.lock; cp bigfile1 /destination; rm .file1.lock; } &\n}\n# ... do some other concurrent stuff\nwait # wait for childs to end\n"
},
{
"answer_id": 22948867,
"author": "RAKK",
"author_id": 2796088,
"author_profile": "https://Stackoverflow.com/users/2796088",
"pm_score": 2,
"selected": false,
"text": "processes=0;\nfor X in `seq 0 10`; do\n let processes+=1;\n { { echo Job $processes; sleep 3; echo End of job $processes; } & };\n if [[ $processes -eq 5 ]]; then\n wait;\n processes=0;\n fi;\ndone;\n xz xz * for gzip -cd \"$X\" | xz -9c > \"${X%.gz}.xz\""
},
{
"answer_id": 26588961,
"author": "Anastasios Andronidis",
"author_id": 1067688,
"author_profile": "https://Stackoverflow.com/users/1067688",
"pm_score": 0,
"selected": false,
"text": "print `touch .file1.lock && cp bigfile1 /destination && rm .file1.lock &`;\n"
},
{
"answer_id": 26685801,
"author": "Nikolas Britton",
"author_id": 4204519,
"author_profile": "https://Stackoverflow.com/users/4204519",
"pm_score": 1,
"selected": false,
"text": "for i in x; do ((a; b; c;)&); done for i in 500 300 100; do ((printf \"Start $i: \"; date; dd if=/dev/zero of=testfile_$i bs=1m count=$i 2>/dev/null; printf \"End $i: \"; date;)&) && sleep 1; done"
},
{
"answer_id": 26687080,
"author": "Kannan Mohan",
"author_id": 1198887,
"author_profile": "https://Stackoverflow.com/users/1198887",
"pm_score": 0,
"selected": false,
"text": "parallel $ ls *|parallel -kj0 --eta 'cp {} /tmp/destination'\n -j0 -j<n> <n> -k --eta"
},
{
"answer_id": 40691679,
"author": "Radu Simionescu",
"author_id": 517450,
"author_profile": "https://Stackoverflow.com/users/517450",
"pm_score": 2,
"selected": false,
"text": "(command1 ; command2 ; command3) &\n"
},
{
"answer_id": 56963954,
"author": "Rounak Datta",
"author_id": 8303407,
"author_profile": "https://Stackoverflow.com/users/8303407",
"pm_score": 0,
"selected": false,
"text": "for hrNum in {00..11};\ndo\n oneHour=$((10#$hrNum + 0))\n secondHour=$((10#$hrNum + 12))\n { echo \"$oneHour\"; echo \"$secondHour\"; } &\n wait\ndone\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23780/"
] |
161,315
|
<p>I wrote a small web app using ruby on rails, its main purpose is to upload, store, and display results from xml(files can be up to several MB) files. After running for about 2 months I noticed that the mongrel process was using about 4GB of memory. I did some research on debugging ruby memory leaks and could not find much. So I have two questions.</p>
<ul>
<li>Are there any good tools that can be used to find memory leaks in Ruby/rails?</li>
<li>What type of coding patterns cause memory leaks in ruby?</li>
</ul>
|
[
{
"answer_id": 164206,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 4,
"selected": false,
"text": "#Put this in applictation_controller.rb\nbefore_filter :log_ram # or use after_filter\ndef log_ram\n logger.warn 'RAM USAGE: ' + `pmap #{Process.pid} | tail -1`[10,40].strip\nend\n puts 'RAM USAGE: ' + `pmap #{Process.pid} | tail -1`[10,40].strip\n"
},
{
"answer_id": 2377810,
"author": "Sardathrion - against SE abuse",
"author_id": 232794,
"author_profile": "https://Stackoverflow.com/users/232794",
"pm_score": 2,
"selected": false,
"text": "1234567890 RAM USAGE: 27456K\n $ grep 'RAM USAGE' fubar.log | awk '{print s \" \" $1 \" \" $4; s++}' | sed 's/K//g' > mem.log\n #!/bin/sh\nrm -f mem.png\nR --vanilla --no-save --slave <<RSCRIPT\n lst <- read.table(\"mem.log\")\n attach(lst)\n m = memory / 1024.0\n summary(m)\n png(filename=\"mem.png\", width=1024)\n plot(date, m, type='l', main=\"Memory usage\", xlab=\"time\", ylab=\"memory\")\nRSCRIPT\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
161,342
|
<p>I need to validate the email address of my users. Unfortunately, making a validator that <a href="https://www.rfc-editor.org/rfc/rfc2822#section-3.4.1" rel="nofollow noreferrer">conforms to standards</a> is hard.</p>
<p><a href="http://www.ex-parrot.com/%7Epdw/Mail-RFC822-Address.html" rel="nofollow noreferrer">Here</a> is an example of a regex expression that tries to conform to the standard.</p>
<p>Is there a PHP library (preferably, open-source) that validates an email address?</p>
|
[
{
"answer_id": 161362,
"author": "Chris",
"author_id": 4742,
"author_profile": "https://Stackoverflow.com/users/4742",
"pm_score": 4,
"selected": false,
"text": "filter_var($someEmail, FILTER_VALIDATE_EMAIL);"
},
{
"answer_id": 161909,
"author": "Pierre Spring",
"author_id": 1532,
"author_profile": "https://Stackoverflow.com/users/1532",
"pm_score": 0,
"selected": false,
"text": "$mail_validator = new Zend_Validate_EmailAddress();\n$mail_validator->isValid($address); // returns true or false\n svn external"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1599/"
] |
161,348
|
<p>Given the following:</p>
<pre><code>#light
//any function returning bool * 'a
let foo =
let x = ref 10
fun () ->
x := !x - 1
if !x <> 0 then
(true, x)
else
(false, x)
while let (c,x) = foo() in c do print_any x;//can't access x, but would be convinent.
//this is how I want it to work, without all the typing
let rec loop f =
match f() with
| (true, x) ->
print_any x
loop f
| (false, _) -> ()
loop foo
</code></pre>
<p>How should I go about solving this?
Or should I just go through the hassle to convert "foo" to a sequence expression?</p>
|
[
{
"answer_id": 161362,
"author": "Chris",
"author_id": 4742,
"author_profile": "https://Stackoverflow.com/users/4742",
"pm_score": 4,
"selected": false,
"text": "filter_var($someEmail, FILTER_VALIDATE_EMAIL);"
},
{
"answer_id": 161909,
"author": "Pierre Spring",
"author_id": 1532,
"author_profile": "https://Stackoverflow.com/users/1532",
"pm_score": 0,
"selected": false,
"text": "$mail_validator = new Zend_Validate_EmailAddress();\n$mail_validator->isValid($address); // returns true or false\n svn external"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21182/"
] |
161,356
|
<p>How can I create a new Word document pro grammatically using Visual Studio Tools for Office? </p>
|
[
{
"answer_id": 298600,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "Globals.ThisAddIn.Application.Documents.Add(ref objTemplate, ref missingType, ref missingType, ref missingType); \n objTemplate"
},
{
"answer_id": 2739835,
"author": "Tim Ridgely",
"author_id": 207945,
"author_profile": "https://Stackoverflow.com/users/207945",
"pm_score": 0,
"selected": false,
"text": "using Word = Microsoft.Office.Interop.Word;\n\nobject missing = System.Reflection.Missing.Value;\nWord.Application app = new Word.ApplicationClass();\nWord.Document doc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing);\ndoc.Activate();\napp.Selection.TypeText(\"This is some text in my new Word document.\");\napp.Selection.TypeParagraph();\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] |
161,368
|
<p>We're moving a solution with 20+ projects from .net 2.0 to 3.5 and at the same time moving from Visual Studio 2005 to 2008. We're also at the same time switching from MS Entlib 2.0 to 4.0. </p>
<ul>
<li>Is there any reasons not to let the
Visual Studio wizard convert the
solution for us?</li>
<li>Is 3.5 fully backwards compatible
with 2.0?</li>
<li>Is Entlib 4.0 fully backwards compatible
with 2.0?</li>
</ul>
<p><strong>Edit:</strong> I might been a bit confused when I wrote this, the backwards compatability is supposed to mean; is there anything that exists in a 2.0 project that will not work/compile in 3.5</p>
<p>:)</p>
<p>//W</p>
|
[
{
"answer_id": 1048688,
"author": "Christian Hayter",
"author_id": 115413,
"author_profile": "https://Stackoverflow.com/users/115413",
"pm_score": 1,
"selected": false,
"text": "CacheManager cache = CacheFactory.GetCacheManager() CacheManager ICacheManager (TextWriter, Exception) (TextWriter, Exception, Guid)"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2538222/"
] |
161,378
|
<p>I have a WinForms TreeView with one main node and several sub-nodes.</p>
<p>How can I hide the + (plus sign) in the main node?</p>
|
[
{
"answer_id": 161401,
"author": "Doug L.",
"author_id": 19179,
"author_profile": "https://Stackoverflow.com/users/19179",
"pm_score": 5,
"selected": true,
"text": ".ShowRootLines = false ShowRootLines Expand() ShowPlusMinus"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
161,388
|
<p>I'm using @media print in my external css file to hide menus etc. However while printing the little triangle of a dropdownlist still shows. Is there a css setting available to hide it as well and only print the selected item?</p>
|
[
{
"answer_id": 161468,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<select name=\"Snakes\" style=\"width: 200px;\">\n <option value=\"A\">Anaconda</option>\n <option value=\"B\">Boa</option>\n <option value=\"C\">Cobra</option>\n <option selected=\"\" value=\"P\">Python</option>\n <option value=\"V\">Viper</option>\n</select>\n<!-- Put this style in a class, of course -->\n<div style=\"background-color: white; \n min-width: 20px; max-width: 20px; position: relative; \n right: -180px; top: -19px;\">&Nbsp;</div>\n"
},
{
"answer_id": 166810,
"author": "David Heggie",
"author_id": 4309,
"author_profile": "https://Stackoverflow.com/users/4309",
"pm_score": 1,
"selected": false,
"text": " <p><a class=\"print\" href=\"#\">print this</a></p>\n <form action=\"/my/action/\" method=\"POST\">\n <select id=\"mySelect\">\n <option value=\"1\">An Option</option>\n <option value=\"2\" selected=\"selected\">Another Option</option>\n </select>\n </form>\n $(document).ready(function() {\n $('a.print').click(function() {\n var selected = $('#mySelect option:selected').text();\n $('#mySelect').after('<p class=\"replacement\">' + selected + '</p>');\n $('#mySelect').hide();\n window.print();\n });\n });\n"
},
{
"answer_id": 10607347,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 3,
"selected": false,
"text": "-moz-appearance: none;\n-webkit-appearance: none;\nappearance: none;\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
161,398
|
<p>I'm possibly just stupid, but I'm trying to find a user in Active Directory from C#, using the Login name ("domain\user").</p>
<p>My "Skeleton" AD Search Functionality looks like this usually:</p>
<pre><code>de = new DirectoryEntry(string.Format("LDAP://{0}", ADSearchBase), null, null, AuthenticationTypes.Secure);
ds = new DirectorySearcher(de);
ds.SearchScope = SearchScope.Subtree;
ds.PropertiesToLoad.Add("directReports");
ds.PageSize = 10;
ds.ServerPageTimeLimit = TimeSpan.FromSeconds(2);
SearchResult sr = ds.FindOne();
</code></pre>
<p>Now, that works if I have the full DN of the user (ADSearchBase usually points to the "Our Users" OU in Active Directory), but I simply have no idea how to look for a user based on the "domain\user" syntax.</p>
<p>Any Pointers?</p>
|
[
{
"answer_id": 161719,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 4,
"selected": true,
"text": "String.Format(\"(&(objectCategory=person)(objectClass=user)(sn={0}))\", \n EscapeFilterLiteral(lastName, false)); \n public static string EscapeFilterLiteral(string literal, bool escapeWildcards)\n{\n if (literal == null) throw new ArgumentNullException(\"literal\");\n\n literal = literal.Replace(\"\\\\\", \"\\\\5c\");\n literal = literal.Replace(\"(\", \"\\\\28\");\n literal = literal.Replace(\")\", \"\\\\29\");\n literal = literal.Replace(\"\\0\", \"\\\\00\");\n literal = literal.Replace(\"/\", \"\\\\2f\");\n if (escapeWildcards) literal = literal.Replace(\"*\", \"\\\\2a\");\n return literal;\n}\n"
},
{
"answer_id": 18216100,
"author": "Kevin M",
"author_id": 1838481,
"author_profile": "https://Stackoverflow.com/users/1838481",
"pm_score": -1,
"selected": false,
"text": "\"(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(sAMAccountName=John))\"\n \"(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(userPrincipalName=John))\"\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
161,399
|
<p>I have a control where I have to check in which page I am, so I can set a certain variable accordingly.</p>
<pre><code>string pageName = this.Page.ToString();
switch (pageName)
{
case "ASP.foo_bar_aspx": doSomething(); break;
default: doSomethingElse(); break;
}
</code></pre>
<p>this works fine locally and on some developmentservers, however when I put it live, It stopped working because I don't get <code>ASP.foo_bar_aspx</code> but <code>_ASP.foo_bar_aspx</code>
(notice the underscore in the live version)
Why does it act that way, Can I set it somehow?</p>
|
[
{
"answer_id": 161409,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 1,
"selected": false,
"text": "HttpContext.Current.Request.FilePath HttpContext.Current.Request..."
},
{
"answer_id": 161411,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 3,
"selected": true,
"text": "if (Page is FooBar) { ... }\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15981/"
] |
161,404
|
<p>I have three tables, A, B, C, where A is many to one B, and B is many to one C. I'd like a list of all C's in A. </p>
<p>My tables are something like this: A[id, valueA, lookupB], B[id, valueB, lookupC], C[id, valueC]. I've written a query with two nested SELECTs, but I'm wondering if it's possible to do INNER JOIN with DISTINCT somehow.</p>
<pre><code>SELECT valueC
FROM C
INNER JOIN
(
SELECT DISTINCT lookupC
FROM B INNER JOIN
(
SELECT DISTINCT lookupB
FROM A
)
A2 ON B.id = A2.lookupB
)
B2 ON C.id = B2.lookupC
</code></pre>
<p>EDIT:
The tables are fairly large, A is 500k rows, B is 10k rows and C is 100 rows, so there are a lot of uneccesary info if I do a basic inner join and use DISTINCT in the end, like this:</p>
<pre><code>SELECT DISTINCT valueC
FROM
C INNER JOIN B on C.id = B.lookupB
INNER JOIN A on B.id = A.lookupB
</code></pre>
<p>This is very, very slow (magnitudes times slower than the nested SELECT I do above.</p>
|
[
{
"answer_id": 161423,
"author": "kristian",
"author_id": 20377,
"author_profile": "https://Stackoverflow.com/users/20377",
"pm_score": 1,
"selected": false,
"text": "SELECT DISTINCT C.valueC\nFROM \nC\nINNER JOIN B ON C.id = B.lookupC\nINNER JOIN A ON B.id = A.lookupB\n"
},
{
"answer_id": 161428,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 4,
"selected": false,
"text": "SELECT DISTINCT a.valueA, c.valueC\nFROM C\n INNER JOIN B ON B.lookupC = C.id\n INNER JOIN A ON A.lookupB = B.id\nORDER BY a.valueA, c.valueC\n"
},
{
"answer_id": 161429,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 2,
"selected": false,
"text": "SELECT DISTINCT C.valueC \nFROM C \n LEFT JOIN B ON C.id = B.lookupC\n LEFT JOIN A ON B.id = A.lookupB\nWHERE C.id IS NOT NULL\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2973/"
] |
161,432
|
<p>Imagine the following type:</p>
<pre><code>public struct Account
{
public int Id;
public double Amount;
}
</code></pre>
<p>What is the best algorithm to synchronize two <code>IList<Account></code> in C# 2.0 ? (No linq) ?</p>
<p>The first list (L1) is the reference list, the second (L2) is the one to synchronize according to the first:</p>
<ul>
<li>All accounts in L2 that are no longer present in L1 must be deleted from L2</li>
<li>All accounts in L2 that still exist in L1 must be updated (amount attribute)</li>
<li>All accounts that are in L1 but not yet in L2 must be added to L2</li>
</ul>
<p>The Id identifies accounts. It's no too hard to find a naive and working algorithm, but I would like to know if there is a smart solution to handle this scenario without ruining readability and perfs.</p>
<p><strong>EDIT</strong> :</p>
<ul>
<li>Account type doesn't matter, is could be a class, has properties, equality members, etc.</li>
<li>L1 and L2 are not sorted</li>
<li>L2 items could not be replaced by L1 items, they must be updated (field by field, property by property)</li>
</ul>
|
[
{
"answer_id": 161535,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 2,
"selected": false,
"text": "class Program\n{\n static void Main()\n {\n List<string> left = new List<string> { \"Alice\", \"Charles\", \"Derek\" };\n List<string> right = new List<string> { \"Bob\", \"Charles\", \"Ernie\" };\n\n EnumerableExtensions.CompareSortedCollections(left, right, StringComparer.CurrentCultureIgnoreCase,\n s => Console.WriteLine(\"Left: \" + s), s => Console.WriteLine(\"Right: \" + s), (x,y) => Console.WriteLine(\"Both: \" + x + y));\n }\n}\n\nstatic class EnumerableExtensions\n{\n public static void CompareSortedCollections<T>(IEnumerable<T> source, IEnumerable<T> destination, IComparer<T> comparer, Action<T> onLeftOnly, Action<T> onRightOnly, Action<T, T> onBoth)\n {\n EnumerableIterator<T> sourceIterator = new EnumerableIterator<T>(source);\n EnumerableIterator<T> destinationIterator = new EnumerableIterator<T>(destination);\n\n while (sourceIterator.HasCurrent && destinationIterator.HasCurrent)\n {\n // While LHS < RHS, the items in LHS aren't in RHS\n while (sourceIterator.HasCurrent && (comparer.Compare(sourceIterator.Current, destinationIterator.Current) < 0))\n {\n onLeftOnly(sourceIterator.Current);\n sourceIterator.MoveNext();\n }\n\n // While RHS < LHS, the items in RHS aren't in LHS\n while (sourceIterator.HasCurrent && destinationIterator.HasCurrent && (comparer.Compare(sourceIterator.Current, destinationIterator.Current) > 0))\n {\n onRightOnly(destinationIterator.Current);\n destinationIterator.MoveNext();\n }\n\n // While LHS==RHS, the items are in both\n while (sourceIterator.HasCurrent && destinationIterator.HasCurrent && (comparer.Compare(sourceIterator.Current, destinationIterator.Current) == 0))\n {\n onBoth(sourceIterator.Current, destinationIterator.Current);\n sourceIterator.MoveNext();\n destinationIterator.MoveNext();\n }\n }\n\n // Mop up.\n while (sourceIterator.HasCurrent)\n {\n onLeftOnly(sourceIterator.Current);\n sourceIterator.MoveNext();\n }\n\n while (destinationIterator.HasCurrent)\n {\n onRightOnly(destinationIterator.Current);\n destinationIterator.MoveNext();\n }\n }\n}\n\ninternal class EnumerableIterator<T>\n{\n private readonly IEnumerator<T> _enumerator;\n\n public EnumerableIterator(IEnumerable<T> enumerable)\n {\n _enumerator = enumerable.GetEnumerator();\n MoveNext();\n }\n\n public bool HasCurrent { get; private set; }\n\n public T Current\n {\n get { return _enumerator.Current; }\n }\n\n public void MoveNext()\n {\n HasCurrent = _enumerator.MoveNext();\n }\n}\n"
},
{
"answer_id": 54690709,
"author": "Mateus Wolkmer",
"author_id": 9629238,
"author_profile": "https://Stackoverflow.com/users/9629238",
"pm_score": 1,
"selected": false,
"text": "IEquatable<> Equals() public struct Account : IEquatable<Account>\n{\n public int Id;\n public double Amount;\n\n public bool Equals(Account other)\n {\n if (other == null) return false;\n return (this.Id.Equals(other.Id));\n }\n}\n L1.ForEach (L1Account =>\n{\n var L2Account = L2.Find(a => a.Id == L1Account.id);\n // If found, update values\n if (L2Account != null)\n {\n L1Account.Amount = L2Account.Amount;\n L2.Remove(L2Account);\n }\n // If not found, remove it\n else\n {\n L1.Remove(L1Account);\n }\n}\n// Add any remaining L2 Account to L1\nL1.AddRange(L2);\n"
},
{
"answer_id": 65855217,
"author": "Teneko",
"author_id": 2788957,
"author_profile": "https://Stackoverflow.com/users/2788957",
"pm_score": 0,
"selected": false,
"text": "CollectionModification<LeftItemType,RightItemType> CollectionChangedEventArgs<T> CollectionModification List<T>.GetEnumerator YieldIteratorInfluencedReadOnlyList<ItemType> IComparer<T> /// <summary>\n/// The algorithm creates modifications that can transform one collection into another collection.\n/// The collection modifications may be used to transform <paramref name=\"leftItems\"/>.\n/// Assumes <paramref name=\"leftItems\"/> and <paramref name=\"rightItems\"/> to be sorted by that order you specify by <paramref name=\"collectionOrder\"/>.\n/// Duplications are allowed but take into account that duplications are yielded as they are appearing.\n/// </summary>\n/// <typeparam name=\"LeftItemType\">The type of left items.</typeparam>\n/// <typeparam name=\"RightItemType\">The type of right items.</typeparam>\n/// <typeparam name=\"ComparablePartType\">The type of the comparable part of left item and right item.</typeparam>\n/// <param name=\"leftItems\">The collection you want to have transformed.</param>\n/// <param name=\"getComparablePartOfLeftItem\">The part of left item that is comparable with part of right item.</param>\n/// <param name=\"rightItems\">The collection in which <paramref name=\"leftItems\"/> could be transformed.</param>\n/// <param name=\"getComparablePartOfRightItem\">The part of right item that is comparable with part of left item.</param>\n/// <param name=\"collectionOrder\">the presumed order of items to be used to determine <see cref=\"IComparer{T}.Compare(T, T)\"/> argument assignment.</param>\n/// <param name=\"comparer\">The comparer to be used to compare comparable parts of left and right item.</param>\n/// <param name=\"yieldCapabilities\">The yieldCapabilities that regulates how <paramref name=\"leftItems\"/> and <paramref name=\"rightItems\"/> are synchronized.</param>\n/// <returns>The collection modifications.</returns>\n/// <exception cref=\"ArgumentNullException\">Thrown when non-nullable arguments are null.</exception>\npublic static IEnumerable<CollectionModification<LeftItemType, RightItemType>> YieldCollectionModifications<LeftItemType, RightItemType, ComparablePartType>(\n IEnumerable<LeftItemType> leftItems,\n Func<LeftItemType, ComparablePartType> getComparablePartOfLeftItem,\n IEnumerable<RightItemType> rightItems,\n Func<RightItemType, ComparablePartType> getComparablePartOfRightItem,\n SortedCollectionOrder collectionOrder,\n IComparer<ComparablePartType> comparer,\n CollectionModificationsYieldCapabilities yieldCapabilities)\n IEqualityComparer<T> /// <summary>\n/// The algorithm creates modifications that can transform one collection into another collection.\n/// The collection modifications may be used to transform <paramref name=\"leftItems\"/>.\n/// The more the collection is synchronized in an orderly way, the more efficient the algorithm is.\n/// Duplications are allowed but take into account that duplications are yielded as they are appearing.\n/// </summary>\n/// <typeparam name=\"LeftItemType\">The type of left items.</typeparam>\n/// <typeparam name=\"RightItemType\">The type of right items.</typeparam>\n/// <typeparam name=\"ComparablePartType\">The type of the comparable part of left item and right item.</typeparam>\n/// <param name=\"leftItems\">The collection you want to have transformed.</param>\n/// <param name=\"getComparablePartOfLeftItem\">The part of left item that is comparable with part of right item.</param>\n/// <param name=\"rightItems\">The collection in which <paramref name=\"leftItems\"/> could be transformed.</param>\n/// <param name=\"getComparablePartOfRightItem\">The part of right item that is comparable with part of left item.</param>\n/// <param name=\"equalityComparer\">The equality comparer to be used to compare comparable parts.</param>\n/// <param name=\"yieldCapabilities\">The yield capabilities, e.g. only insert or only remove.</param>\n/// <returns>The collection modifications.</returns>\n/// <exception cref=\"ArgumentNullException\">Thrown when non-nullable arguments are null.</exception>\npublic static IEnumerable<CollectionModification<LeftItemType, RightItemType>> YieldCollectionModifications<LeftItemType, RightItemType, ComparablePartType>(\n IEnumerable<LeftItemType> leftItems,\n Func<LeftItemType, ComparablePartType> getComparablePartOfLeftItem,\n IEnumerable<RightItemType> rightItems,\n Func<RightItemType, ComparablePartType> getComparablePartOfRightItem,\n IEqualityComparer<ComparablePartType>? equalityComparer,\n CollectionModificationsYieldCapabilities yieldCapabilities)\n where ComparablePartType : notnull\n IndexDirectory NullableKeyDictionary LinkedBucketList public class Account\n{\n public Account(int id) =>\n Id = id;\n\n public int Id { get; }\n public double Amount { get; }\n}\n\n public class AccountEqualityComparer : EqualityComparer<Account>\n{\n public new static AccountEqualityComparer Default = new AccountEqualityComparer();\n\n public override bool Equals([AllowNull] Account x, [AllowNull] Account y) =>\n ReferenceEquals(x, y) || (!(x is null && y is null) && x.Id.Equals(y.Id));\n\n public override int GetHashCode([DisallowNull] Account obj) =>\n obj.Id;\n}\n using Teronis.Collections.Algorithms.Modifications;\nusing Teronis.Collections.Synchronization;\nusing Teronis.Collections.Synchronization.Extensions;\nusing Teronis.Reflection;\n\npublic class AccountCollectionViewModel : SyncingCollectionViewModel<Account, Account>\n{\n public AccountCollectionViewModel()\n : base(CollectionSynchronizationMethod.Sequential(AccountEqualityComparer.Default))\n {\n // In case of SyncingCollectionViewModel, we have to pass a synchronization method.\n //\n // Sequential means any order\n //\n }\n\n protected override Account CreateSubItem(Account superItem) =>\n superItem;\n\n protected override void ApplyCollectionItemReplace(in ApplyingCollectionModificationBundle modificationBundle)\n {\n foreach (var (oldItem, newItem) in modificationBundle.OldSuperItemsNewSuperItemsModification.YieldTuplesForOldItemNewItemReplace())\n {\n // Implementation detail: update left public property values by right public property values.\n TeronisReflectionUtils.UpdateEntityVariables(oldItem, newItem);\n }\n }\n}\n\n using System.Diagnostics;\nusing System.Linq;\n\nclass Program\n{\n static void Main()\n {\n // Arrange\n var collection = new AccountCollectionViewModel();\n\n var initialData = new Account[] {\n new Account(5) { Amount = 0 },\n new Account(7) { Amount = 0 },\n new Account(3) { Amount = 0 }\n };\n\n var newData = new Account[] {\n new Account(5) { Amount = 10 }, \n /* Account by ID 7 got removed .. */ \n /* but account by ID 8 is new. */ \n new Account(8) { Amount = 10 },\n new Account(3) { Amount = 10 }\n };\n\n // Act\n collection.SynchronizeCollection(initialData);\n\n // Assert\n Debug.Assert(collection.SubItems.ElementAt(1).Id == 7, \"The account at index 1 has not the ID 7.\");\n Debug.Assert(collection.SubItems.All(x => x.Amount == 0), \"Not all accounts have an amount of 0.\");\n\n // Act\n collection.SynchronizeCollection(newData);\n\n // Assert\n Debug.Assert(collection.SubItems.ElementAt(1).Id == 8, \"The account at index 1 has not the ID 8.\");\n Debug.Assert(collection.SubItems.All(x => x.Amount == 10), \"Not all accounts have an amount of 10.\");\n\n ;\n }\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4687/"
] |
161,443
|
<p>In Kohana/CodeIgniter, I can have a URL in this form:</p>
<pre><code>http://www.name.tld/controller_name/method_name/parameter_1/parameter_2/parameter_3 ...
</code></pre>
<p>And then read the parameters in my controller as follows:</p>
<pre><code>class MyController
{
public function method_name($param_A, $param_B, $param_C ...)
{
// ... code
}
}
</code></pre>
<p>How do you achieve this in the Zend Framework?</p>
|
[
{
"answer_id": 161636,
"author": "Andrew Taylor",
"author_id": 1776,
"author_profile": "https://Stackoverflow.com/users/1776",
"pm_score": 4,
"selected": false,
"text": "$router = new Zend_Controller_Router_Rewrite();\n\n$router->addRoute(\n 'index',\n new Zend_Controller_Router_Route('index/index/:param1/:param2/:param3/:param4', array('controller' => 'index', 'action' => 'index'))\n);\n\n$frontController->setRouter($router);\n $this->_request->getParam('param1');\n"
},
{
"answer_id": 1041892,
"author": "Jeffrey04",
"author_id": 5742,
"author_profile": "https://Stackoverflow.com/users/5742",
"pm_score": 1,
"selected": false,
"text": "abstract class Coolsilon_Controller_Base \n extends Zend_Controller_Action { \n\n public function dispatch($actionName) { \n $parameters = array(); \n\n foreach($this->_parametersMeta($actionName) as $paramMeta) { \n $parameters = array_merge( \n $parameters, \n $this->_parameter($paramMeta, $this->_getAllParams()) \n ); \n } \n\n call_user_func_array(array(&$this, $actionName), $parameters); \n } \n\n private function _actionReference($className, $actionName) { \n return new ReflectionMethod( \n $className, $actionName \n ); \n } \n\n private function _classReference() { \n return new ReflectionObject($this); \n } \n\n private function _constructParameter($paramMeta, $parameters) { \n return array_key_exists($paramMeta->getName(), $parameters) ? \n array($paramMeta->getName() => $parameters[$paramMeta->getName()]) : \n array($paramMeta->getName() => $paramMeta->getDefaultValue()); \n } \n\n private function _parameter($paramMeta, $parameters) { \n return $this->_parameterIsValid($paramMeta, $parameters) ? \n $this->_constructParameter($paramMeta, $parameters) : \n $this->_throwParameterNotFoundException($paramMeta, $parameters); \n } \n\n private function _parameterIsValid($paramMeta, $parameters) { \n return $paramMeta->isOptional() === FALSE \n && empty($parameters[$paramMeta->getName()]) === FALSE; \n } \n\n private function _parametersMeta($actionName) { \n return $this->_actionReference( \n $this->_classReference()->getName(), \n $actionName \n ) \n ->getParameters(); \n } \n\n private function _throwParameterNotFoundException($paramMeta, $parameters) { \n throw new Exception(”Parameter: {$paramMeta->getName()} Cannot be empty”); \n } \n} \n"
},
{
"answer_id": 1981544,
"author": "Andy",
"author_id": 114770,
"author_profile": "https://Stackoverflow.com/users/114770",
"pm_score": 2,
"selected": false,
"text": "application/configs/routes.ini routes.popular.route = popular/:type/:page/:sortOrder\nroutes.popular.defaults.controller = popular\nroutes.popular.defaults.action = index\nroutes.popular.defaults.type = images\nroutes.popular.defaults.sortOrder = alltime\nroutes.popular.defaults.page = 1\nroutes.popular.reqs.type = \\w+\nroutes.popular.reqs.page = \\d+\nroutes.popular.reqs.sortOrder = \\w+\n bootstrap.php // create $frontController if not already initialised\n$frontController = Zend_Controller_Front::getInstance(); \n\n$config = new Zend_Config_Ini(APPLICATION_PATH . ‘/config/routes.ini’);\n$router = $frontController->getRouter();\n$router->addConfig($config,‘routes’);\n"
},
{
"answer_id": 6776614,
"author": "Victor",
"author_id": 509235,
"author_profile": "https://Stackoverflow.com/users/509235",
"pm_score": 2,
"selected": false,
"text": "Zend_Controller_Action dispatch($action) $this->$action(); call_user_func_array(array($this,$action), $this->getUrlParametersByPosition()); /**\n * Returns array of url parts after controller and action\n */\nprotected function getUrlParametersByPosition()\n{\n $request = $this->getRequest();\n $path = $request->getPathInfo();\n $path = explode('/', trim($path, '/'));\n if(@$path[0]== $request->getControllerName())\n {\n unset($path[0]);\n }\n if(@$path[1] == $request->getActionName())\n {\n unset($path[1]);\n }\n return $path;\n}\n /mycontroller/myaction/123/321 public function editAction($param1 = null, $param2 = null)\n{\n // $param1 = 123\n // $param2 = 321\n}\n func_get_args() getParam() /**\n * Dispatch the requested action\n *\n * @param string $action Method name of action\n * @return void\n */\npublic function dispatch($action)\n{\n // Notify helpers of action preDispatch state\n $this->_helper->notifyPreDispatch();\n\n $this->preDispatch();\n if ($this->getRequest()->isDispatched()) {\n if (null === $this->_classMethods) {\n $this->_classMethods = get_class_methods($this);\n }\n\n // preDispatch() didn't change the action, so we can continue\n if ($this->getInvokeArg('useCaseSensitiveActions') || in_array($action, $this->_classMethods)) {\n if ($this->getInvokeArg('useCaseSensitiveActions')) {\n trigger_error('Using case sensitive actions without word separators is deprecated; please do not rely on this \"feature\"');\n }\n //$this->$action();\n call_user_func_array(array($this,$action), $this->getUrlParametersByPosition()); \n } else {\n $this->__call($action, array());\n }\n $this->postDispatch();\n }\n\n // whats actually important here is that this action controller is\n // shutting down, regardless of dispatching; notify the helpers of this\n // state\n $this->_helper->notifyPostDispatch();\n} \n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5742/"
] |
161,462
|
<p>I'm using <code>org.w3c</code> <code>XML API</code> to open an existing <code>XML</code> file. I'm removing some nodes , and I'm adding others instead.</p>
<p>The problem is that the new nodes that are added are written one after the other, with no newline and no indentation what so ever. While it's true that the <code>XML</code> file is valid , it is very hard for a human to examine it.</p>
<p>Is there anyway to add indentation , or at least a newline after each node?</p>
|
[
{
"answer_id": 161478,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 7,
"selected": true,
"text": "Transformer StreamResult transform transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\ntransformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n"
},
{
"answer_id": 10412619,
"author": "Thilina",
"author_id": 1369861,
"author_profile": "https://Stackoverflow.com/users/1369861",
"pm_score": 4,
"selected": false,
"text": "transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\ntransformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11234/"
] |
161,474
|
<p>My basic question is, in .NET, how do I clone WebControls?</p>
<p>I would like to build a custom tag, which can produce multiple copies of its children.
Ultimately I intend to build a tag similar to in JSP/Struts.</p>
<p>But the first hurdle I have is the ability to duplicate/clone the contents of a control.</p>
<p>Consider this rather contrived example;</p>
<pre><code><custom:duplicate count="2">
<div>
<p>Some html</p>
<asp:TextBox id="tb1" runat="server" />
</div>
</custom:duplicate>
</code></pre>
<p>The HTML markup which is output would be something like,</p>
<pre><code><div>
<p>Some html</p>
<input type="text" id="tb1" />
</div>
<div>
<p>Some html</p>
<input type="text" id="tb1" />
</div>
</code></pre>
<p><em>Note: I know i have the id duplicated, I can come up with a solution to that later!</em></p>
<p>So what we would have is my custom control with 3 children (I think) - a literal control, a TextBox control, and another literal control.</p>
<p>In this example I have said 'count=2' so what the control should do is output/render its children twice.</p>
<p>What I would hope to do is write some "OnInit" code which does something like:</p>
<pre><code>List<WebControl> clones;
for(int i=1; i<count; i++)
{
foreach(WebControl c in Controls)
{
WebControl clone = c.Clone();
clones.Add(clone);
}
}
Controls.AddRange(clones);
</code></pre>
<p>However, as far as I can tell, WebControls do not implement ICloneable, so its not possible to clone them in this way.</p>
<p>Any ideas how I can clone WebControls?</p>
|
[
{
"answer_id": 1372034,
"author": "Juri",
"author_id": 50109,
"author_profile": "https://Stackoverflow.com/users/50109",
"pm_score": 1,
"selected": false,
"text": "public class MyCustomServerCtrl\n{\n\n ...\n\n public MyCustomServerCtrl Clone()\n {\n return MemberwiseClone() as MyCustomServerCtrl;\n }\n\n}\n"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24232/"
] |
161,477
|
<p>Is there a typedef equivalent in C#, or someway to get some sort of similar behaviour? I've done some googling, but everywhere I look seems to be negative. Currently I have a situation similar to the following:</p>
<pre><code>class GenericClass<T>
{
public event EventHandler<EventData> MyEvent;
public class EventData : EventArgs { /* snip */ }
// ... snip
}
</code></pre>
<p>Now, it doesn't take a rocket scientist to figure out that this can very quickly lead to a lot of typing (apologies for the horrible pun) when trying to implement a handler for that event. It'd end up being something like this:</p>
<pre><code>GenericClass<int> gcInt = new GenericClass<int>;
gcInt.MyEvent += new EventHandler<GenericClass<int>.EventData>(gcInt_MyEvent);
// ...
private void gcInt_MyEvent(object sender, GenericClass<int>.EventData e)
{
throw new NotImplementedException();
}
</code></pre>
<p>Except, in my case, I was already using a complex type, not just an int. It'd be nice if it were possible to simplify this a little...</p>
<p>Edit: ie. perhaps typedefing the EventHandler instead of needing to redefine it to get similar behaviour.</p>
|
[
{
"answer_id": 161484,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 10,
"selected": true,
"text": "using CustomerList = System.Collections.Generic.List<Customer>;\n typedef typedef #include using gcInt.MyEvent += gcInt_MyEvent;\n"
},
{
"answer_id": 161488,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 3,
"selected": false,
"text": "public delegate GenericHandler EventHandler<EventData>\n gcInt.MyEvent += \n"
},
{
"answer_id": 161870,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 5,
"selected": false,
"text": "public class FooList : List<Foo> { ... }\n"
},
{
"answer_id": 161929,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "void LowestCommonHander( object sender, EventArgs e ) { ... } \n gcInt.MyEvent += LowestCommonHander;\n gcInt.MyEvent += (sender, e) =>\n{\n e. //you'll get correct intellisense here\n};\n"
},
{
"answer_id": 9401099,
"author": "palswim",
"author_id": 393280,
"author_profile": "https://Stackoverflow.com/users/393280",
"pm_score": 5,
"selected": false,
"text": "class TypedefString // Example with a string \"typedef\"\n{\n private string Value = \"\";\n public static implicit operator string(TypedefString ts)\n {\n return ((ts == null) ? null : ts.Value);\n }\n public static implicit operator TypedefString(string val)\n {\n return new TypedefString { Value = val };\n }\n}\n"
},
{
"answer_id": 35973121,
"author": "Matt Klein",
"author_id": 1672027,
"author_profile": "https://Stackoverflow.com/users/1672027",
"pm_score": 3,
"selected": false,
"text": "GenericClass<int> public class SomeInt : LikeType<int>\n{\n public SomeInt(int value) : base(value) { }\n}\n\n[TestClass]\npublic class HashSetExample\n{\n [TestMethod]\n public void Contains_WhenInstanceAdded_ReturnsTrueWhenTestedWithDifferentInstanceHavingSameValue()\n {\n var myInt = new SomeInt(42);\n var myIntCopy = new SomeInt(42);\n var otherInt = new SomeInt(4111);\n\n Assert.IsTrue(myInt == myIntCopy);\n Assert.IsFalse(myInt.Equals(otherInt));\n\n var mySet = new HashSet<SomeInt>();\n mySet.Add(myInt);\n\n Assert.IsTrue(mySet.Contains(myIntCopy));\n }\n}\n"
},
{
"answer_id": 37242758,
"author": "shakram02",
"author_id": 4422856,
"author_profile": "https://Stackoverflow.com/users/4422856",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nnamespace UsingStatement\n{\n using Typedeffed = System.Int32;\n using TypeDeffed2 = List<string>;\n class Program\n {\n static void Main(string[] args)\n {\n Typedeffed numericVal = 5;\n Console.WriteLine(numericVal++);\n\n TypeDeffed2 things = new TypeDeffed2 { \"whatever\"};\n }\n }\n}\n"
},
{
"answer_id": 49569473,
"author": "Aaron Franke",
"author_id": 4441547,
"author_profile": "https://Stackoverflow.com/users/4441547",
"pm_score": 1,
"selected": false,
"text": "typedef using #if REAL_T_IS_DOUBLE\nusing real_t = System.Double;\n#else\nusing real_t = System.Single;\n#endif\n real_t"
},
{
"answer_id": 51295920,
"author": "kofifus",
"author_id": 460084,
"author_profile": "https://Stackoverflow.com/users/460084",
"pm_score": 4,
"selected": false,
"text": "void f(string connectionID, string username) void f(ConID connectionID, UserName username) class SomeType { \n public void Method() { .. }\n}\n\nsealed class SomeTypeTypeDef {\n public SomeTypeTypeDef(SomeType composed) { this.Composed = composed; }\n\n private SomeType Composed { get; }\n\n public override string ToString() => Composed.ToString();\n public override int GetHashCode() => HashCode.Combine(Composed);\n public override bool Equals(object obj) => obj is TDerived o && Composed.Equals(o.Composed); \n public bool Equals(SomeTypeTypeDefo) => object.Equals(this, o);\n\n // proxy the methods we want\n public void Method() => Composed.Method();\n}\n namespace Typedef {\n\n [JsonConverter(typeof(JsonCompositionConverter))]\n public abstract class Composer<TDerived, T> : IEquatable<TDerived> where TDerived : Composer<TDerived, T> {\n protected Composer(T composed) { this.Composed = composed; }\n protected Composer(TDerived d) { this.Composed = d.Composed; }\n\n protected T Composed { get; }\n\n public override string ToString() => Composed.ToString();\n public override int GetHashCode() => HashCode.Combine(Composed);\n public override bool Equals(object obj) => obj is Composer<TDerived, T> o && Composed.Equals(o.Composed); \n public bool Equals(TDerived o) => object.Equals(this, o);\n }\n\n class JsonCompositionConverter : JsonConverter {\n static FieldInfo GetCompositorField(Type t) {\n var fields = t.BaseType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);\n if (fields.Length!=1) throw new JsonSerializationException();\n return fields[0];\n }\n\n public override bool CanConvert(Type t) {\n var fields = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);\n return fields.Length == 1;\n }\n\n // assumes Compositor<T> has either a constructor accepting T or an empty constructor\n public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {\n while (reader.TokenType == JsonToken.Comment && reader.Read()) { };\n if (reader.TokenType == JsonToken.Null) return null; \n var compositorField = GetCompositorField(objectType);\n var compositorType = compositorField.FieldType;\n var compositorValue = serializer.Deserialize(reader, compositorType);\n var ctorT = objectType.GetConstructor(new Type[] { compositorType });\n if (!(ctorT is null)) return Activator.CreateInstance(objectType, compositorValue);\n var ctorEmpty = objectType.GetConstructor(new Type[] { });\n if (ctorEmpty is null) throw new JsonSerializationException();\n var res = Activator.CreateInstance(objectType);\n compositorField.SetValue(res, compositorValue);\n return res;\n }\n\n public override void WriteJson(JsonWriter writer, object o, JsonSerializer serializer) {\n var compositorField = GetCompositorField(o.GetType());\n var value = compositorField.GetValue(o);\n serializer.Serialize(writer, value);\n }\n }\n\n}\n sealed Class SomeTypeTypeDef : Composer<SomeTypeTypeDef, SomeType> {\n public SomeTypeTypeDef(SomeType composed) : base(composed) {}\n\n // proxy the methods we want\n public void Method() => Composed.Method();\n}\n SomeTypeTypeDef SomeType"
},
{
"answer_id": 58756912,
"author": "Vlad Rudenko",
"author_id": 901333,
"author_profile": "https://Stackoverflow.com/users/901333",
"pm_score": 2,
"selected": false,
"text": "public class Vector : List<int> { }\n public abstract class Typedef<T, TDerived> where TDerived : Typedef<T, TDerived>, new()\n{\n private T _value;\n\n public static implicit operator T(Typedef<T, TDerived> t)\n {\n return t == null ? default : t._value;\n }\n\n public static implicit operator Typedef<T, TDerived>(T t)\n {\n return t == null ? default : new TDerived { _value = t };\n }\n}\n\n// Usage examples\n\nclass CountryCode : Typedef<string, CountryCode> { }\nclass CurrencyCode : Typedef<string, CurrencyCode> { }\nclass Quantity : Typedef<int, Quantity> { }\n\nvoid Main()\n{\n var canadaCode = (CountryCode)\"CA\";\n var canadaCurrency = (CurrencyCode)\"CAD\";\n CountryCode cc = canadaCurrency; // Compilation error\n Concole.WriteLine(canadaCode == \"CA\"); // true\n Concole.WriteLine(canadaCurrency); // CAD\n\n var qty = (Quantity)123;\n Concole.WriteLine(qty); // 123\n}\n"
},
{
"answer_id": 70776413,
"author": "JJJ",
"author_id": 5547,
"author_profile": "https://Stackoverflow.com/users/5547",
"pm_score": 3,
"selected": false,
"text": "global using Bar = Foo\n global using DateTime = DontUseDateTime\n"
},
{
"answer_id": 71799159,
"author": "OS Freak",
"author_id": 13709083,
"author_profile": "https://Stackoverflow.com/users/13709083",
"pm_score": 2,
"selected": false,
"text": "using System.Collections.Generic;\nglobal using CustomerList = List<Customer>;\n"
},
{
"answer_id": 74462218,
"author": "Rob Vermeulen",
"author_id": 150187,
"author_profile": "https://Stackoverflow.com/users/150187",
"pm_score": 0,
"selected": false,
"text": "global using global using CustomerList = System.Collections.Generic.List<Customer>;\n CustomerList List<Customer>"
}
] |
2008/10/02
|
[
"https://Stackoverflow.com/questions/161477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.