Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
PROBLEM SOLVED.
Special thanks to Andrew Noyes for explaining its not a class but a Object Literal Notation. What a noob am I..
EDIT:
SORRY, i made a mistake in my js file, the structure of my js is like this:
(I am totally new to javascript, i need your guys help here...)
```
var className = {
settings : {
setA : true,
setB: true,
setC: true,
},
Default : {
move: true,
remove: true,
edit: true,\
},
...
}
```
And in my html, index.html, i include the class.js file, but i want to change the setting to like:
```
Default : {
move : false,
remove: false,
edit: false,
}
```
because only the edit.html, users are allowed to move, remove and edit.
How do I do that? Should I have 2 js, class\_disable.js (include in index.html) and class\_enable.js(for edit.html)?
Need your advise..
I tried:
```
className.settings.Default = {move = false, remove = false, edit = false};
```
But it does not work. | This isn't valid syntax:
```
className.settings.Default = {move = false, remove = false, edit = false};
```
Object values are assigned using a colon, as follows:
```
className.settings.Default = {
move: false,
remove: false,
edit: false
};
```
Alternatively, you could use this syntax:
```
className.settings.Default.move = false;
className.settings.Default.remove = false;
className.settings.Default.edit: false;
```
What you're using here is not a class, it's called Object Literal Notation, and is very common in JavaScript. There is no class or constructor, you're simply assigning properties to an object using literals, thus the name object literal notation. | ```
className.settings = {move: false, remove: false, edit: false};
``` | How to change class variable in Javascript? | [
"",
"javascript",
"class",
"variables",
""
] |
Here is the major jist of what i want this to do.
I have created two button in my Form Initializer As shown Below
```
public Form1()
{
InitializeComponent();
Button b1 = new Button();
b1.Parent = this;
b1.Name = "btnA";
b1.Text = "Button A";
b1.Click += new EventHandler(button_Click);
b1.Show();
Button b2 = new Button();
b2.Parent = this;
b2.Name = "btnB";
b2.Text = "Button B";
b2.Click += new EventHandler(button_Click);
b2.Show();
}
private void button_Click(object sender, EventArgs e)
{
MessageBox.Show("Button A or Button B was Clicked?");
}
```
I need to know which button has been clicked, and obviously manipulate that button that was clicked.
Even something like change the text of the Button that was clicked.
Im preaty sure that we can use the object sender to access the button from which the event was fired but just dont know how to use the sender to manipulate the correct button.
Any Direction or help will be apreciated thanks | Just cast `sender` to `Button`:
```
private void button_Click(object sender, EventArgs e)
{
Button clicked = (Button) sender;
MessageBox.Show("Button " + clicked.Name + " was Clicked.");
}
``` | The `sender` parameter is the object that raised the event:
```
Button button = sender as Button;
if( button != null )
{
MessageBox.Show("Button " + button.Name + " was clicked");
}
else
{
MessageBox.Show("Not a button?");
}
``` | Which object was clicked when an event is fired? | [
"",
"c#",
"winforms",
""
] |
I have a PHP application in which there is a div container which includes the app which has been `$_GET` from the URL string.
Currently, there are two applications which require TinyMCE, and one application which requires jQuery and jQuery UI.
**Question is, where should I include the files on the page?**
In the header, the page loads really slowly, >30 seconds (now <10 seconds, using different router), at at the bottom, the pages which require the scripts fail to load correctly.
The JS files have already been minified and compressed.
TinyMCE won't gZIP becuase Zlib is installed (as a result of GD), so how should I optimise the situation? | The [Yahoo! Exceptional Performance team](http://developer.yahoo.com/performance/) recommends to [put the `script` elements at the end of the `body` element](http://developer.yahoo.com/performance/rules.html#js_bottom). | At the bottom and run your scripts when the document is fully loaded (using "onload" event). | Where should I include JS files | [
"",
"javascript",
"html",
"include",
""
] |
I have the following (javascript/jquery) code to show a busy indicator (after a delay) while an image is loading:
```
function imgUpdate(arg) {
var loaded = false;
$("#image").one("load", function(){
loaded = true;
$("#busyIndicator").hide();
});
setTimeout(function(){
if (!loaded) {
$("#busyIndicator").show();
}
}, 250);
$("#image")[0].src = arg;
}
```
Sometimes, the indicator comes up and stays up. How is this possible if the browser's javascript engine is single-threaded? (This is on Firefox 3, by the way.)
One note: this seems to happen when the image being loaded is already cached.
Another note: if I log to my firebug console, all of the lines in imgUpdate are executed, but a log message inside the onload handler never prints on subsequent calls to imgUpdate. | Clearing the image's src tag seems to fix the problem:
```
function imgUpdate(arg) {
var loaded = false;
$("#image").one("load", function(){
loaded = true;
$("#busyIndicator").hide();
});
setTimeout(function(){
if (!loaded) {
$("#busyIndicator").show();
}
}, 250);
$("#image")[0].src = "";
$("#image")[0].src = arg;
}
``` | I'm hard pressed to replicate this.
Here is the implementation of what you're doing:
A version using caching:
<http://jsbin.com/uwuho>
A version with caching being prevented: (uses parameter to avoid caching)
<http://jsbin.com/oguvi>
Hit F5/Ctrl-F5 to see it go. (in particular with the version which prevents caching)
With or without caching neither version is doing what you'd described.
Your problem *probably* lies elsewhere. | Busy indicator race condition in Javascript | [
"",
"javascript",
"jquery",
"race-condition",
""
] |
How do I get the last element of a list? Which way is preferred?
```
alist[-1]
alist[len(alist) - 1]
``` | `some_list[-1]` is the shortest and most Pythonic.
In fact, you can do much more with this syntax. The `some_list[-n]` syntax gets the nth-to-last element. So `some_list[-1]` gets the last element, `some_list[-2]` gets the second to last, etc, all the way down to `some_list[-len(some_list)]`, which gives you the first element.
You can also set list elements in this way. For instance:
```
>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]
```
Note that getting a list item by index will raise an [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError) if the expected item doesn't exist. This means that `some_list[-1]` will raise an exception if `some_list` is empty, because an empty list can't have a last element. | If your `str()` or `list()` objects might end up being empty as so: `astr = ''` or `alist = []`, then you might want to use `alist[-1:]` instead of `alist[-1]` for object "sameness".
The significance of this is:
```
alist = []
alist[-1] # will generate an IndexError exception whereas
alist[-1:] # will return an empty list
astr = ''
astr[-1] # will generate an IndexError exception whereas
astr[-1:] # will return an empty str
```
Where the distinction being made is that returning an empty list object or empty str object is more "last element"-like then an exception object. | How do I get the last element of a list? | [
"",
"python",
"list",
"indexing",
""
] |
After user subscribe email to my website. My website will generate an email confirmation and send to them. In the email content, i need to include activation key, something like:
www.domain.com/activate.php?key=$generatedKey
How do you generate the key? using sha1($email)??
After generate the key, i store it in database, so that when user click the link I can verified it with the database?? I am new to it, please advise.. I need an Email Confirmation script.. | Personally, just I use a combination of things like:
```
$generatedKey = sha1(mt_rand(10000,99999).time().$email);
```
The chance of collision is small, but I recommend checking your database first before sending it out (using UNIQUE constraints is an easy way). | You basically have a few options:
1) Create a single unique identifier that is seemingly random and store it in your database with which username it corresponds to
2) Generate a random password and include the user id and password in the link and store the password in the database
3) Use a one way hashing function (md5, sah1, etc) and a secret identifier to encrypt the user identifier. You don't have to store the encrypted user identifier in your database.
Option 1 is difficult because you have to worry about checking the database to see if the key already exists. However, it is nice that the URL does not contain the username being activated.
If you are already going to use some sort of database to store the user information (probably a password at minimum) in the future, you could go with option 2. It doesn't take a lot to add another column to your database. When sending the email, save the username and something like $key = sha1(rand(1, 99999) . $username) in another column for the row that contains the username. Then have your link look like this: <http://you.com/activation.php?user=>$username&key=$key. In activation.php you check to see if the key is equal to the value stored in the database.
If you want to use less storage space in your database, option 3 will work. You can use something like $key = sha1($mysecret . $username) as the secret identifier. Use something odd that only you know as $mysecret such as 'aaafj\_my\_secret\_adfaf'. Use the same type of URL as in option 2. However, because you can generate $key based only on $username, you don't need to store it. So when you are processing in activation.php, just check to see if sha1($mysecret . $\_GET[username]) == $\_GET[key]. If it does, you know you have the correct user. Theoretically, with enough registrations, someone could figure out your value for $mysecret and generate the activation keys too. However, you would surely notice the billions or more of registrations that it would take before they could begin to calculate what it is. The number of activations required is based on the key size of the hashing function. Use sha1 (160 bit) vs md5 (128 bit) to make it harder to guess your $mysecret value. | How to generate a secure activation string in php? | [
"",
"php",
"email",
"auto-generate",
"confirmation",
""
] |
I have an URL pointing to content and I need to get the highest value contained in one of the columns. Is there any aggregate function that will accomplish that or do I have to do this manually? | If you're querying an Android content provider, you should be able to achieve this by passing `MAX(COLUMN_NAME)` in to the selection parameter of `ContentResolver.query`:
```
getContentResolver().query(uri, projection, "MAX(COLUMN_NAME)", null, sortOrder);
```
Where Uri is the address of the content provider. This should return the single row with the highest value in COLUMN\_NAME. | Android's database uses SQLite, so `SELECT MAX(thecolumn) FROM TheTable` should work, just like in any other SQLite implementation (or for that matter any other SQL, "ite" or not;-). (If you're not using `android.database` you'd better specify *what* you're using instead;-). | Android: Get highest value in column | [
"",
"sql",
"database",
"android",
"aggregate",
""
] |
I have multiple cameras sending images at random intervals via FTP to a predetermined folders.
For example:
recordings/camera1/images/ - for first camera
recordings/camera2/images/ - for second camera
etc
Each of them save images in .jpg format and then close FTP connection.
I need to call a PHP script after each time a new file is added. Let's say whenever a new image is added into the /recordings folder I need to call the php script with
```
newimage.php?location=recordings/camera1/images/picture002.jpg
```
and so on.
The server is a Linux box running ProFTPD
How I can get this done?
Please note: Cron job is not an option as there will thousands of files and we are not using a DB. So we cannot find out if there are any new files. | I would advise you to take a look at the [mod\_exec](http://www.castaglia.org/proftpd/modules/mod_exec.html) of ProFTPD.
Here is a quote explaining its goal:
> The mod\_exec module can be used to
> execute external programs or scripts
> at various points in the process of
> handling FTP commands. By conscious
> design, ProFTPD does not and will not
> execute external programs. This is a
> security decision, as it was decided
> not to allow ProFTPD to serve as a
> means of compromising a system or
> disclosing information via bugs in
> external programs or scripts. Use of
> this module allows for such external
> programs to be executed, and also
> opens up the server to the mentioned
> possibilities of compromise or
> disclosure via those programs.
You can also take a look at [inotify](http://www.ibm.com/developerworks/linux/library/l-inotify.html) which offers you to monitor system file activity. | You should use [`fam_monitor_directory`](http://php.net/manual/en/function.fam-monitor-directory.php) function in PHP (if it was compiled using `--with-fam`). It does exactly what you need, i.e. execute a PHP program whenever the directory's content changes.
Use something like this in your cronjob (it doesn't matter how many files there are in the directory, the loop goes one time for each *change* in the directory:
```
/* opens a connection to the FAM service daemon */
$fam_res = fam_open ();
/* The second argument is the full pathname of the directory to monitor. */
$nres = fam_monitor_directory ( $fam_res, '/home/www/example.com/cameras/');
while( fam_pending ( $fam_res ) ) {
$arr = (fam_next_event($fam_res)) ;
if ($arr['code']) == FAMCreated ) {
/* deal here with the new file, which name now is stored in $arr['filename'] */
}
}
fam_close($fam_res);
``` | Run PHP script when a new file is added via FTP | [
"",
"php",
"linux",
"ftp",
""
] |
So some guy at some other company thought it would be awesome if instead of using soap or xml-rpc or rest or any other reasonable communication protocol he just embedded all of his response as cookies in the header.
I need to pull these cookies out as hopefully an array from this curl response. If I have to waste a bunch of my life writing a parser for this I will be very unhappy.
Does anyone know how this can simply be done, preferably without writing anything to a file?
I will be very grateful if anyone can help me out with this. | ```
$ch = curl_init('http://www.google.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get headers too with this line
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
// get cookie
// multi-cookie variant contributed by @Combuster in comments
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
var_dump($cookies);
``` | Although this question is quite old, and the accepted response is valid, I find it a bit unconfortable because the content of the HTTP response (HTML, XML, JSON, binary or whatever) becomes mixed with the headers.
I've found a different alternative. CURL provides an option (`CURLOPT_HEADERFUNCTION`) to set a callback that will be called for each response header line. The function will receive the curl object and a string with the header line.
You can use a code like this (adapted from TML response):
```
$cookies = Array();
$ch = curl_init('http://www.google.com/');
// Ask for the callback.
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "curlResponseHeaderCallback");
$result = curl_exec($ch);
var_dump($cookies);
function curlResponseHeaderCallback($ch, $headerLine) {
global $cookies;
if (preg_match('/^Set-Cookie:\s*([^;]*)/mi', $headerLine, $cookie) == 1)
$cookies[] = $cookie;
return strlen($headerLine); // Needed by curl
}
```
This solution has the drawback of using a global variable, but I guess this is not an issue for short scripts. And you can always use static methods and attributes if curl is being wrapped into a class. | how to get the cookies from a php curl into a variable | [
"",
"php",
"cookies",
"curl",
""
] |
```
if hasattr(obj, 'attribute'):
# do somthing
```
vs
```
try:
# access obj.attribute
except AttributeError, e:
# deal with AttributeError
```
Which should be preferred and why? | `hasattr` internally and rapidly performs the same task as the `try/except` block: it's a very specific, optimized, one-task tool and thus should be preferred, when applicable, to the very general-purpose alternative. | *Any benches that illustrate difference in performance?*
timeit it's your friend
```
$ python -mtimeit -s 'class C(object): a = 4
c = C()' 'hasattr(c, "nonexistent")'
1000000 loops, best of 3: 1.87 usec per loop
$ python -mtimeit -s 'class C(object): a = 4
c = C()' 'hasattr(c, "a")'
1000000 loops, best of 3: 0.446 usec per loop
$ python -mtimeit -s 'class C(object): a = 4
c = C()' 'try:
c.a
except:
pass'
1000000 loops, best of 3: 0.247 usec per loop
$ python -mtimeit -s 'class C(object): a = 4
c = C()' 'try:
c.nonexistent
except:
pass'
100000 loops, best of 3: 3.13 usec per loop
$
|positive|negative
hasattr| 0.446 | 1.87
try | 0.247 | 3.13
``` | hasattr() vs try-except block to deal with non-existent attributes | [
"",
"python",
"exception",
"attributes",
"hasattr",
""
] |
Given 2 objects A and B of type T, I want to assign the properties' values in A to the same properties in B without doing an explicit assignment for each property.
I want to save code like this:
```
b.Nombre = a.Nombre;
b.Descripcion = a.Descripcion;
b.Imagen = a.Imagen;
b.Activo = a.Activo;
```
doing something like
```
a.ApplyProperties(b);
```
Is it possible? | I have a type in [`MiscUtil`](http://pobox.com/~skeet/csharp/miscutil) called `PropertyCopy` which does something similar - although it creates a new instance of the target type and copies the properties into that.
It doesn't require the types to be the same - it just copies all the readable properties from the "source" type to the "target" type. Of course if the types are the same, that's more likely to work :) It's a shallow copy, btw.
In the code block at the bottom of this answer, I've extended the capabilities of the class. To copy from one instance to another, it uses simple `PropertyInfo` values at execution time - this is slower than using an expression tree, but the alternative would be to write a dynamic method, which I'm not too hot on. If performance is absolutely critical for you, let me know and I'll see what I can do. To use the method, write something like:
```
MyType instance1 = new MyType();
// Do stuff
MyType instance2 = new MyType();
// Do stuff
PropertyCopy.Copy(instance1, instance2);
```
(where `Copy` is a generic method called using type inference).
I'm not really ready to do a full MiscUtil release, but here's the updated code, including comments. I'm not going to rewrap them for the SO editor - just copy the whole chunk.
(I'd also probably redesign the API a bit in terms of naming if I were starting from scratch, but I don't want to break existing users...)
```
#if DOTNET35
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
namespace MiscUtil.Reflection
{
/// <summary>
/// Non-generic class allowing properties to be copied from one instance
/// to another existing instance of a potentially different type.
/// </summary>
public static class PropertyCopy
{
/// <summary>
/// Copies all public, readable properties from the source object to the
/// target. The target type does not have to have a parameterless constructor,
/// as no new instance needs to be created.
/// </summary>
/// <remarks>Only the properties of the source and target types themselves
/// are taken into account, regardless of the actual types of the arguments.</remarks>
/// <typeparam name="TSource">Type of the source</typeparam>
/// <typeparam name="TTarget">Type of the target</typeparam>
/// <param name="source">Source to copy properties from</param>
/// <param name="target">Target to copy properties to</param>
public static void Copy<TSource, TTarget>(TSource source, TTarget target)
where TSource : class
where TTarget : class
{
PropertyCopier<TSource, TTarget>.Copy(source, target);
}
}
/// <summary>
/// Generic class which copies to its target type from a source
/// type specified in the Copy method. The types are specified
/// separately to take advantage of type inference on generic
/// method arguments.
/// </summary>
public static class PropertyCopy<TTarget> where TTarget : class, new()
{
/// <summary>
/// Copies all readable properties from the source to a new instance
/// of TTarget.
/// </summary>
public static TTarget CopyFrom<TSource>(TSource source) where TSource : class
{
return PropertyCopier<TSource, TTarget>.Copy(source);
}
}
/// <summary>
/// Static class to efficiently store the compiled delegate which can
/// do the copying. We need a bit of work to ensure that exceptions are
/// appropriately propagated, as the exception is generated at type initialization
/// time, but we wish it to be thrown as an ArgumentException.
/// Note that this type we do not have a constructor constraint on TTarget, because
/// we only use the constructor when we use the form which creates a new instance.
/// </summary>
internal static class PropertyCopier<TSource, TTarget>
{
/// <summary>
/// Delegate to create a new instance of the target type given an instance of the
/// source type. This is a single delegate from an expression tree.
/// </summary>
private static readonly Func<TSource, TTarget> creator;
/// <summary>
/// List of properties to grab values from. The corresponding targetProperties
/// list contains the same properties in the target type. Unfortunately we can't
/// use expression trees to do this, because we basically need a sequence of statements.
/// We could build a DynamicMethod, but that's significantly more work :) Please mail
/// me if you really need this...
/// </summary>
private static readonly List<PropertyInfo> sourceProperties = new List<PropertyInfo>();
private static readonly List<PropertyInfo> targetProperties = new List<PropertyInfo>();
private static readonly Exception initializationException;
internal static TTarget Copy(TSource source)
{
if (initializationException != null)
{
throw initializationException;
}
if (source == null)
{
throw new ArgumentNullException("source");
}
return creator(source);
}
internal static void Copy(TSource source, TTarget target)
{
if (initializationException != null)
{
throw initializationException;
}
if (source == null)
{
throw new ArgumentNullException("source");
}
for (int i = 0; i < sourceProperties.Count; i++)
{
targetProperties[i].SetValue(target, sourceProperties[i].GetValue(source, null), null);
}
}
static PropertyCopier()
{
try
{
creator = BuildCreator();
initializationException = null;
}
catch (Exception e)
{
creator = null;
initializationException = e;
}
}
private static Func<TSource, TTarget> BuildCreator()
{
ParameterExpression sourceParameter = Expression.Parameter(typeof(TSource), "source");
var bindings = new List<MemberBinding>();
foreach (PropertyInfo sourceProperty in typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (!sourceProperty.CanRead)
{
continue;
}
PropertyInfo targetProperty = typeof(TTarget).GetProperty(sourceProperty.Name);
if (targetProperty == null)
{
throw new ArgumentException("Property " + sourceProperty.Name + " is not present and accessible in " + typeof(TTarget).FullName);
}
if (!targetProperty.CanWrite)
{
throw new ArgumentException("Property " + sourceProperty.Name + " is not writable in " + typeof(TTarget).FullName);
}
if ((targetProperty.GetSetMethod().Attributes & MethodAttributes.Static) != 0)
{
throw new ArgumentException("Property " + sourceProperty.Name + " is static in " + typeof(TTarget).FullName);
}
if (!targetProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
{
throw new ArgumentException("Property " + sourceProperty.Name + " has an incompatible type in " + typeof(TTarget).FullName);
}
bindings.Add(Expression.Bind(targetProperty, Expression.Property(sourceParameter, sourceProperty)));
sourceProperties.Add(sourceProperty);
targetProperties.Add(targetProperty);
}
Expression initializer = Expression.MemberInit(Expression.New(typeof(TTarget)), bindings);
return Expression.Lambda<Func<TSource, TTarget>>(initializer, sourceParameter).Compile();
}
}
}
#endif
``` | Because I believe Jon's version is a tad too complicated and and Steve's version is too simple, and I like Daniel's idea of an extension class.
Plus a Generic version is pretty but unnecessary as all items are objects.
I would like to volunteer my lean and mean version. Credits to all the above. :D
**Code:**
```
using System;
using System.Reflection;
/// <summary>
/// A static class for reflection type functions
/// </summary>
public static class Reflection
{
/// <summary>
/// Extension for 'Object' that copies the properties to a destination object.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="destination">The destination.</param>
public static void CopyProperties(this object source, object destination)
{
// If any this null throw an exception
if (source == null || destination == null)
throw new Exception("Source or/and Destination Objects are null");
// Getting the Types of the objects
Type typeDest = destination.GetType();
Type typeSrc = source.GetType();
// Iterate the Properties of the source instance and
// populate them from their desination counterparts
PropertyInfo[] srcProps = typeSrc.GetProperties();
foreach (PropertyInfo srcProp in srcProps)
{
if (!srcProp.CanRead)
{
continue;
}
PropertyInfo targetProperty = typeDest.GetProperty(srcProp.Name);
if (targetProperty == null)
{
continue;
}
if (!targetProperty.CanWrite)
{
continue;
}
if (targetProperty.GetSetMethod(true) != null && targetProperty.GetSetMethod(true).IsPrivate)
{
continue;
}
if ((targetProperty.GetSetMethod().Attributes & MethodAttributes.Static) != 0)
{
continue;
}
if (!targetProperty.PropertyType.IsAssignableFrom(srcProp.PropertyType))
{
continue;
}
// Passed all tests, lets set the value
targetProperty.SetValue(destination, srcProp.GetValue(source, null), null);
}
}
}
```
**Usage:**
```
/// <summary>
/// ExampleCopyObject
/// </summary>
/// <returns></returns>
public object ExampleCopyObject()
{
object destObject = new object();
this.CopyProperties(destObject); // inside a class you want to copy from
Reflection.CopyProperties(this, destObject); // Same as above but directly calling the function
TestClass srcClass = new TestClass();
TestStruct destStruct = new TestStruct();
srcClass.CopyProperties(destStruct); // using the extension directly on a object
Reflection.CopyProperties(srcClass, destObject); // Same as above but directly calling the function
//so on and so forth.... your imagination is the limits :D
return srcClass;
}
public class TestClass
{
public string Blah { get; set; }
}
public struct TestStruct
{
public string Blah { get; set; }
}
```
As I was bored and a linq version was suggested by a comment
```
using System;
using System.Linq;
using System.Reflection;
/// <summary>
/// A static class for reflection type functions
/// </summary>
public static class Reflection
{
/// <summary>
/// Extension for 'Object' that copies the properties to a destination object.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="destination">The destination.</param>
public static void CopyProperties(this object source, object destination)
{
// If any this null throw an exception
if (source == null || destination == null)
throw new Exception("Source or/and Destination Objects are null");
// Getting the Types of the objects
Type typeDest = destination.GetType();
Type typeSrc = source.GetType();
// Collect all the valid properties to map
var results = from srcProp in typeSrc.GetProperties()
let targetProperty = typeDest.GetProperty(srcProp.Name)
where srcProp.CanRead
&& targetProperty != null
&& (targetProperty.GetSetMethod(true) != null && !targetProperty.GetSetMethod(true).IsPrivate)
&& (targetProperty.GetSetMethod().Attributes & MethodAttributes.Static) == 0
&& targetProperty.PropertyType.IsAssignableFrom(srcProp.PropertyType)
select new { sourceProperty = srcProp, targetProperty = targetProperty };
//map the properties
foreach (var props in results)
{
props.targetProperty.SetValue(destination, props.sourceProperty.GetValue(source, null), null);
}
}
}
``` | Apply properties values from one object to another of the same type automatically? | [
"",
"c#",
"linq-to-sql",
""
] |
I am working on a program written in Java which, *for some actions*, launches external programs using user-configured command lines. Currently it uses `Runtime.exec()` and does not retain the `Process` reference (the launched programs are either a text editor or archive utility, so no need for the system in/out/err streams).
There is a minor problem with this though, in that when the Java program exits, it doesn't really quit until all the launched programs are exited.
I would greatly prefer it if the launched programs were completely independent of the JVM which launched them.
The target operating system is multiple, with Windows, Linux and Mac being the minimum, but any GUI system with a JVM is really what is desired (hence the user configurability of the actual command lines).
Does anyone know how to make the launched program execute completely independently of the JVM?
---
**Edit in response to a comment**
The launch code is as follows. The code may launch an editor positioned at a specific line and column, or it may launch an archive viewer. Quoted values in the configured command line are treated as ECMA-262 encoded, and are decoded and the quotes stripped to form the desired exec parameter.
The launch occurs on the EDT.
```
static Throwable launch(String cmd, File fil, int lin, int col) throws Throwable {
String frs[][]={
{ "$FILE$" ,fil.getAbsolutePath().replace('\\','/') },
{ "$LINE$" ,(lin>0 ? Integer.toString(lin) : "") },
{ "$COLUMN$",(col>0 ? Integer.toString(col) : "") },
};
String[] arr; // array of parsed tokens (exec(cmd) does not handle quoted values)
cmd=TextUtil.replace(cmd,frs,true,"$$","$");
arr=(String[])ArrayUtil.removeNulls(TextUtil.stringComponents(cmd,' ',-1,true,true,true));
for(int xa=0; xa<arr.length; xa++) {
if(TextUtil.isQuoted(arr[xa],true)) {
arr[xa]=TextDecode.ecma262(TextUtil.stripQuotes(arr[xa]));
}
}
log.println("Launching: "+cmd);
Runtime.getRuntime().exec(arr);
return null;
}
```
---
This appears to be happening only when the program is launched from my IDE. I am closing this question since the problem exists only in my development environment; **it is not a problem in production**. From the test program in one of the answers, and further testing I have conducted I am satisfied that it is not a problem that will be seen by any user of the program on any platform. | It may help if you post a test section of minimal code needed to reproduce the problem. I tested the following code on Windows and a Linux system.
```
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
Runtime.getRuntime().exec(args[0]);
}
}
```
And tested with the following on Linux:
```
java -jar JustForTesting.jar /home/monceaux/Desktop/__TMP/test.sh
```
where test.sh looks like:
```
#!/bin/bash
ping -i 20 localhost
```
as well as this on Linux:
```
java -jar JustForTesting.jar gedit
```
And tested this on Windows:
```
java -jar JustForTesting.jar notepad.exe
```
All of these launched their intended programs, but the Java application had no problems exiting. I have the following versions of Sun's JVM as reported by `java -version` :
* Windows: 1.6.0\_13-b03
* Linux: 1.6.0\_10-b33
I have not had a chance to test on my Mac yet. Perhaps there is some interaction occuring with other code in your project that may not be clear. You may want to try this test app and see what the results are. | There is a parent child relation between your processes and you have to break that.
For Windows you can try:
```
Runtime.getRuntime().exec("cmd /c start editor.exe");
```
For Linux the process seem to run detached anyway, no nohup necessary.
I tried it with `gvim`, `midori` and `acroread`.
```
import java.io.IOException;
public class Exec {
public static void main(String[] args) {
try {
Runtime.getRuntime().exec("/usr/bin/acroread");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished");
}
}
```
I think it is not possible to to it with [Runtime.exec](http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html) in a platform independent way.
for POSIX-Compatible system:
```
Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "your command"}).waitFor();
``` | How do I launch a completely independent process from a Java program? | [
"",
"java",
"exec",
"external-process",
""
] |
I am writing a program which will tokenize the input text depending upon some specific rules. I am using C++ for this.
**Rules**
```
Letter 'a' should be converted to token 'V-A'
Letter 'p' should be converted to token 'C-PA'
Letter 'pp' should be converted to token 'C-PPA'
Letter 'u' should be converted to token 'V-U'
```
This is just a sample and in real time I have around 500+ rules like this. If I am providing input as '*appu*', it should tokenize like '*V-A + C-PPA + V-U*'. I have implemented an algorithm for doing this and wanted to make sure that I am doing the right thing.
**Algorithm**
All rules will be kept in a XML file with the corresponding mapping to the token. Something like
```
<rules>
<rule pattern="a" token="V-A" />
<rule pattern="p" token="C-PA" />
<rule pattern="pp" token="C-PPA" />
<rule pattern="u" token="V-U" />
</rules>
```
1 - When the application starts, read this xml file and keep the values in a '*std::map*'. This will be available until the end of the application(singleton pattern implementation).
2 - Iterate the input text characters. For each character, look for a match. If found, become more greedy and look for more matches by taking the next characters from the input text. Do this until we are getting a no match. So for the input text '*appu*', first look for a match for '*a*'. If found, try to get more match by taking the next character from the input text. So it will try to match '*ap*' and found no matches. So it just returns.
3 - Replace the letter 'a' from input text as we got a token for it.
4 - Repeat step 2 and 3 with the remaining characters in the input text.
Here is a more simple explanation of the steps
```
input-text = 'appu'
tokens-generated=''
// First iteration
character-to-match = 'a'
pattern-found = true
// since pattern found, going recursive and check for more matches
character-to-match = 'ap'
pattern-found = false
tokens-generated = 'V-A'
// since no match found for 'ap', taking the first success and replacing it from input text
input-text = 'ppu'
// second iteration
character-to-match = 'p'
pattern-found = true
// since pattern found, going recursive and check for more matches
character-to-match = 'pp'
pattern-found = true
// since pattern found, going recursive and check for more matches
character-to-match = 'ppu'
pattern-found = false
tokens-generated = 'V-A + C-PPA'
// since no match found for 'ppu', taking the first success and replacing it from input text
input-text = 'u'
// third iteration
character-to-match = 'u'
pattern-found = true
tokens-generated = 'V-A + C-PPA + V-U' // we'r done!
```
**Questions**
1 - Is this algorithm looks fine for this problem or is there a better way to address this problem?
2 - If this is the right method, std::map is a good choice here? Or do I need to create my own key/value container?
3 - Is there a library available which can tokenize string like the above?
Any help would be appreciated
:) | So you're going through all of the tokens in your map looking for matches? You might as well use a list or array, there; it's going to be an inefficient search regardless.
A much more efficient way of finding just the tokens suitable for starting or continuing a match would be to store them as a [trie](http://en.wikipedia.org/wiki/Trie). A lookup of a letter there would give you a sub-trie which contains only the tokens which have that letter as the first letter, and then you just continue searching downward as far as you can go.
---
Edit: let me explain this a little further.
First, I should explain that I'm not familiar with these the C++ `std::map`, beyond the name, which makes this a perfect example of why one learns the theory of this stuff as well as than details of particular libraries in particular programming languages: unless that library is badly misusing the name "map" (which is rather unlikely), the name itself tells me a lot about the characteristics of the data structure. I know, for example, that there's going to be a function that, given a single key and the map, will very efficiently search for and return the value associated with that key, and that there's also likely a function that will give you a list/array/whatever of all of the keys, which you could search yourself using your own code.
My interpretation of your data structure is that you have a map where the keys are what you call a pattern, those being a list (or array, or something of that nature) of characters, and the values are tokens. Thus, you can, given a full pattern, quickly find the token associated with it.
Unfortunately, while such a map is a good match to converting your XML input format to a internal data structure, it's not a good match to the searches you need to do. Note that you're not looking up entire patterns, but the first character of a pattern, producing a set of possible tokens, followed by a lookup of the second character of a pattern *from within the set of patterns produced by that first lookup*, and so on.
So what you really need is not a single map, but maps of maps of maps, each keyed by a single character. A lookup of "p" on the top level should give you a new map, with two keys: `p`, producing the `C-PPA` token, and "anything else", producing the `C-PA` token. This is effectively a trie data structure.
Does this make sense?
It may help if you start out by writing the parsing code first, in this manner: imagine someone else will write the functions to do the lookups you need, and he's a really good programmer and can do pretty much any magic that you want. Writing the parsing code, concentrate on making that as simple and clean as possible, creating whatever interface using these arbitrary functions you need (while not getting trivial and replacing the whole thing with one function!). Now you can look at the lookup functions you ended up with, and that tells you how you need to access your data structure, which will lead you to the type of data structure you need. Once you've figured that out, you can then work out how to load it up. | It may seem a bit complicated, but the most efficient way to do that is to use a graph to represent a state-chart. At first, i thought [boost.statechart](http://www.boost.org/doc/libs/1_39_0/libs/statechart/doc/index.html) would help, but i figured it wasn't really appropriate. This method can be more efficient that using a simple std::map IF there are many rules, the number of possible characters is limited and the length of the text to read is quite high.
So anyway, using a simple graph :
0) create graph with "start" vertex
1) read xml configuration file and create vertices when needed (transition from one "set of characters" (eg "pp") to an additional one (eg "ppa")). Inside each vertex, store a transition table to the next vertices. If "key text" is complete, mark vertex as final and store the resulting text
2) now read text and interpret it using the graph. Start at the "start" vertex. ( \* ) Use table to interpret one character and to jump to new vertex. If no new vertex has been selected, an error can be issued. Otherwise, if new vertex is final, print the resulting text and jump back to start vertex. Go back to (\*) until there is no more text to interpret.
You could use [boost.graph](http://www.boost.org/doc/libs/1_39_0/libs/graph/doc/index.html) to represent the graph, but i think it is overly complex for what you need. Make your own custom representation. | Tokenize the text depending on some specific rules. Algorithm in C++ | [
"",
"c++",
"algorithm",
"tokenize",
""
] |
OK, I know how to make a simple custom JComponent. I know how to override a TableCellRenderer. I can't seem to combine the two.
Here's a sample `JComponent` I created:
```
public static class BarRenderer extends JComponent
{
final private double xmin;
final private double xmax;
private double xval;
public BarRenderer(double xmin, double xmax)
{
this.xmin=xmin;
this.xmax=xmax;
}
@Override protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Rectangle r = g.getClipBounds();
g.drawRect(r.x, r.y,
(int)(r.width * ((xval-xmin)/(xmax-xmin))), r.height);
}
public void setXval(double x) {
this.xval = x;
repaint();
}
public double getXval() { return xval; }
}
```
It works fine as a standalone JComponent. I call `setXval(something)` and it updates just fine. (edit: I have a Swing Timer that updates the data periodically)
But if this component is something I return in TableCellRenderer.getTableCellRendererComponent(), then it only repaints when I click on the cell in question. What gives? I must be leaving out something really simple. | For performance reasons a JTable reuses renderer components to paint multiple cells - so when you see the component in the JTable it isn't actually there in the traditional sense of a Component in a Container which is present at a location. This means that calling repaint() on the renderer component does nothing.
The most effective option would be to store the Integer value of the bar in your TableModel. Your TableCellRenderer would then look something like this:
```
public class BarTableCellRenderer implements TableCellRenderer {
private final BarRenderer rendererComponent = new BarRenderer(0, 10);
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
rendererComponent.setXval((Integer)value);
return rendererComponent;
}
}
```
Then you could change the Integer in your TableModel and it would trigger a repaint of the bar (you may need a TableModel.fireTableCellUpdated dependent on the TableModel implementation you are using). | Both of you (Russ Hayward and Andrew) helped, the key was essentially to do the following:
* store the state to be made visible in the TableModel itself, not in the renderer
* make sure that when the TableModel's state changes, `fireTableCellUpdated()` is called
* have only *one* TableCellRenderer object and *one* JComponent for my custom column (not one per cell)
+ within `TableCellRenderer.getTableCellRendererComponent()` store the cell's state for purposes of being rendering soon after (long-term storage is in the TableModel)
+ provide that state to the JComponent
+ return the JComponent
+ override `JComponent.PaintComponent()`
* one convenient possibility is for a custom renderer to extend JComponent and implement TableCellRenderer, then in `TableCellRenderer.getTableCellRendererComponent()` you store the cell's state and `return this;`
Here's the relevant excerpt of my code that now works:
```
class TraceControlTableModel extends AbstractTableModel {
/* handle table state here */
// convenience method for setting bar value (table model's column 2)
public void setBarValue(int row, double x)
{
setValueAt(x, row, 2);
}
}
// one instance of BarRenderer will be set as the
// TableCellRenderer for table column 2
public static class BarRenderer extends JComponent
implements TableCellRenderer
{
final private double xmin;
final private double xmax;
private double xval;
public BarRenderer(double xmin, double xmax)
{
super();
this.xmin=xmin;
this.xmax=xmax;
}
@Override protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Rectangle r = g.getClipBounds();
g.drawRect(r.x, r.y,
(int)(r.width * ((xval-xmin)/(xmax-xmin))), r.height);
}
@Override
public Component getTableCellRendererComponent(JTable arg0,
Object value,
boolean isSelected, boolean hasFocus,
int row, int col)
{
// save state here prior to returning this object as a component
// to be painted
this.xval = (Double)value;
return this;
}
}
``` | using a custom Swing JComponent in a TableCellRenderer | [
"",
"java",
"swing",
"jcomponent",
"tablecellrenderer",
""
] |
i'm writing a dll which is a wrapper to a access database. and i'm pretty new to c# in general as my background is in web development LAMP with perl, i'm not sure what's a good way to return error to a calling app in case they pass the wrong parameters to my functions or what not.
I have no idea as of now except to probably do some msgbox or throw some exceptions but i don't know where to start looking. Any help or resources would be more than useful :)
thanks~ | You probably don't want to display message dialogs from within your dll, that's the job of the client application, as part of the presentation layer.
.Net library assemblies typically bubble up exceptions to the host application, so that's the approach I'd look at.
```
public static class LibraryClass
{
public static void DoSomething(int positiveInteger)
{
if (positiveInteger < 0)
{
throw new ArgumentException("Expected a positive number", "positiveInteger");
}
}
}
```
Then it's up to your host application to handle those exceptions, logging and displaying them as appropriate.
```
try
{
LibraryClass.DoSomething(-3);
}
catch(ArgumentException argExc)
{
MessageBox.Show("An Error occurred: " + argExc.ToString());
}
``` | Wrong parameters are usually handled by throwing a ArgumentException or one of its subclasses. | What's a good way for a c# dll to return error to the calling application? | [
"",
"c#",
"exception",
"error-handling",
""
] |
Oracle:
```
select systimestamp from dual
```
MySQL:
```
select current_timestamp
```
SQL Server:
```
select current_timestamp
```
PostgreSQL:
```
select current_timestamp
```
The question is, how can I get the current timestamp in [HSQLDB](http://hsqldb.org/)? I use version 1.8.0.10 | You can write
```
select current_timestamp from tablename
```
where `tablename` is a real table in your database.
The result of the query is only the current timestamp. | In a select I use
```
SELECT CURRENT_DATE AS today, CURRENT_TIME AS now FROM (VALUES(0))
``` | How to do "select current_timestamp" in hsqldb? | [
"",
"sql",
"database",
"hsqldb",
"embedded-database",
""
] |
I'm writing a web app using Python and the web.py framework, and I need to use memcached throughout.
I've been searching the internet trying to find some good documentation on the [python-memcached](http://www.tummy.com/Community/software/python-memcached/) module, but all I could find was [this example on the MySQL website](http://dev.mysql.com/doc/refman/5.1/en/ha-memcached-interfaces-python.html), and the documentation on its methods isn't great. | It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system.
Most clients follow the same rules. You can read the generic instructions and best practices on [the memcached homepage](http://www.danga.com/memcached/).
If you really want to dig into it, I'd look at the source. Here's the header comment:
```
"""
client module for memcached (memory cache daemon)
Overview
========
See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.
Usage summary
=============
This should give you a feel for how this module operates::
import memcache
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
mc.set("some_key", "Some value")
value = mc.get("some_key")
mc.set("another_key", 3)
mc.delete("another_key")
mc.set("key", "1") # note that the key used for incr/decr must be a string.
mc.incr("key")
mc.decr("key")
The standard way to use memcache with a database is like this::
key = derive_key(obj)
obj = mc.get(key)
if not obj:
obj = backend_api.get(...)
mc.set(key, obj)
# we now have obj, and future passes through this code
# will use the object from the cache.
Detailed Documentation
======================
More detailed documentation is available in the L{Client} class.
"""
``` | I would advise you to use `pylibmc` instead.
It can act as a drop-in replacement of python-memcache, but a lot faster(as it's written in C). And you can find handy documentation for it [here](http://sendapatch.se/projects/pylibmc/).
And to the question, as pylibmc just acts as a drop-in replacement, you can still refer to documentations of pylibmc for your python-memcache programming. | Good examples of python-memcache (memcached) being used in Python? | [
"",
"python",
"memcached",
""
] |
I am new to makefiles and facing some issue with it. I have created the following makefile. It works correctly. But when I modify the *main.cpp* and run *make*, it says *"everything is up to date"*. I need to do a *make clean* and run make again, everything will work.
Looks like there is some issue with this makefile and I can't figure it out where it is going wrong. Can anyone help me to find out where is the error in this makefile and why it is not building changed files?
```
#Main makefile which does the build
CFLAGS =
CC = g++
PROG = fooexe
#each module will append the source files to here
SRC :=
#including the description
include foo/module.mk
OBJ := $(patsubst %.cpp, %.o, $(filter %.cpp,$(SRC))) main.o
#linking the program
fooexe: $(OBJ)
$(CC) -o $(PROG) $(OBJ)
%.o:
$(CC) -c $(SRC) -o $(patsubst %.cpp, %.o, $(filter %.cpp,$(SRC)))
main.o:
$(CC) -c main.cpp
depend:
makedepend -- $(CFLAGS) -- $(SRC)
.PHONY:clean
clean:
find . -name "*.o" | xargs rm -vf
rm -vf fooexe
``` | Normally the .o file needs to have a dependency on the corresponding .cpp file. I think this is the syntax, but not 100% sure:
```
%.o : %.cpp
$(CC) ...
main.o : main.cpp
$(CC) ...
``` | ```
%.o:
$(CC) -c $(SRC) -o $(patsubst %.cpp, %.o, $(filter %.cpp,$(SRC)))
```
This is a pattern rule that tells make, "whenever a `.o` file is required and does not exist, run `$(CC)` on all of the `.cpp` files in `$(SRC)`." It doesn't recompile `.cpp` files when they change because it doesn't list any prerequisites. If the required `.o` files already exist, then there's no reason for make to execute the `$(CC)` command.
If you change the first line to `%.o: %.cpp` as Andy White suggested, then the updated rule now tells make, "whenever a .o file is required and does not exist or is older than the corresponding `.cpp` file, run `$(CC)` on all of the `.cpp` files in `$(SRC)`."
This is better, but there's still a problem: the updated rule always compiles all of your `.cpp` files, even the ones that are are up to date. To fix this, the command part of the rule needs to recompile the correct `.cpp` file into the correct `.o` file. You can do this using automatic variables such as `$<` (1st prerequisite) and `$@` (target):
```
%.o: %.cpp
$(CC) -c $< -o $@
```
The [GNU Make Manual](http://www.gnu.org/software/make/manual/make.html#Pattern-Examples) has more explanation and details. | makefile not building updated part of the program - C++ | [
"",
"c++",
"makefile",
""
] |
Does anyone have any books/tutorials which may be useful in getting started in Windows device driver development?
For plain Win32/GUI development, Petzold's book seems to be the essential reference. Does such exist for drivers?
I would like to note that I'm not actually talking to hardware -- I actually want to emulate a piece of hardware in software, but I'd like to see how things work in general first.
Billy3 | One thing to beware of is the device driver development (architecture and tools) changes more than Win32 development ... so while Petzold's book from the 1990s is fine for Win32 and may be considered a timeless classic, the architecture for many kinds of drivers (printer drivers, network drivers, etc.) has varied in various O/S releases.
Here's a blog entry which reviews various books: [Windows Device Drivers Book Reviews](http://blogs.msdn.com/iliast/archive/2006/10/25/Windows-Device-Drivers-Book-Reviews.aspx).
Don't forget the microsoft documentation included with the DDK: and, most importantly, the sample drivers (source code) included with the DDK. When I wanted to write a mock serial port driver, for example, I found the sample serial driver documentation combined with the DDK documentation was invaluable (and sufficient). | To learn kernel development well:
a. lots of samples kernel programs:
Windows DDK sample:
<http://social.msdn.microsoft.com/Forums/en-US/softwaretesting/thread/08690203-1757-4129-b59a-6bae10bcdce8/>
WDK samples:
<http://msdn.microsoft.com/en-us/windows/hardware/gg487428>
Or just search:
<http://www.google.com/search?q=windows+ddk+samples>
(because above URL may change, but Google will likely to return u the most appropriate/reachable one)
b. lots of debugging techniques, and among which I found the best is VMware (or VirtualBox) + windbg + serial port debugging:
<http://www.google.com/search?q=windbg+vmware+kernel+debug>
and this paper is classic for using VMWare + windbg (Lord of the Ring0):
<http://silverstr.ufies.org/lotr0/windbg-vmware.html>
c. as well as system admin tools which others have built:
<http://technet.microsoft.com/en-us/sysinternals/bb545021>
(In the past called SysInternals built by Mark Russinovich, co-author of "Windows Internal" - MUST READ!!)
<http://technet.microsoft.com/en-us/sysinternals/bb963901>
from these tools u have will immense debugging options.
d. Join the OSR mailing list (ntdev especially is very active, but there are others like windbg):
<http://www.osronline.com/page.cfm?name=ListServer>
e. Watch lots of video related to windows + kernel at channel9 (google returned over 1000 links):
<http://www.google.com/search?q=site:channel9.msdn.com+kernel+video&num=100>
f. Discussion forum like:
<http://social.microsoft.com/Forums/en-us/kernel/threads>
<http://social.msdn.microsoft.com/Forums/en-US/wdk/threads>
Subscribed to the free OSR magazine too (hardcopy). I have received mine since 1998 till now - and it is delivered half-way round the earth! | Getting Started on Driver Development | [
"",
"c++",
"windows",
"driver",
""
] |
Considering that the following statements return `4`, what is the difference between the `int` and `long` types in C++?
```
sizeof(int)
sizeof(long)
``` | From [this](http://tsemba.org/c/inttypes.html) reference:
> An int was originally intended to be
> the "natural" word size of the
> processor. Many modern processors can
> handle different word sizes with equal
> ease.
Also, this bit:
> On many (but not all) C and C++
> implementations, a long is larger than
> an int. Today's most popular desktop
> platforms, such as Windows and Linux,
> run primarily on 32 bit processors and
> most compilers for these platforms use
> a 32 bit int which has the same size
> and representation as a long. | The guarantees the standard gives you go like this:
```
1 == sizeof(char) <= sizeof(short) <= sizeof (int) <= sizeof(long) <= sizeof(long long)
```
So it's perfectly valid for `sizeof (int)` and `sizeof (long)` to be equal, and many platforms choose to go with this approach. You will find some platforms where `int` is 32 bits, `long` is 64 bits, and `long long` is 128 bits, but it seems very common for `sizeof (long)` to be 4.
(Note that `long long` is recognized in C from C99 onwards, but was normally implemented as an extension in C++ prior to C++11.) | Difference between long and int data types | [
"",
"c++",
"types",
"integer",
"size",
""
] |
I am trying to have my main thread spawn off a new thread and, after some time, raise the interrupt flag. When it does so, the spawned thread should see that flag and terminate itself.
The main thread looks something like this:
```
final Thread t = new Thread()
{
@Override
public void run()
{
f();
}
};
t.start();
try
{
t.join(time);
t.interrupt();
if(t.isAlive())
{
t.join(allowance);
if(t.isAlive())
throw new Exception();
}
}
catch(Exception e)
{
System.err.println("f did not terminate in the alloted time");
}
```
And the spawned thread has a bunch of the following scattered throughout its code:
```
if(Thread.interrupted()) return;
```
When I am in debug mode, everything works perfectly. The interrupt flag is raised by the main thread and is caught by the spawned thread. However, in regular run mode the spawned thread doesn't seem to receive the interrupt flag, no matter how long I set the allowance.
Does anyone know what I am doing wrong?
Note: I am using Ubuntu and I am all-together new to anything Linux. Can the problem be with the OS? I have not tested the code on any other OS. | I suggest you consider using an ExecutorService which is designed to do this sort of thing and could help you in other ways.
```
ExecutorService service = Executors.newCachedThreadPool();
Future<ResultType> future = service.submit(new Callable<ResultType() {
public ResultType call() throws Exception {
// do soemthing
return (ResultType) ...;
}
);
// do anything you like until you need to result.
try {
ResultType result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException timedOut) {
// handle exception
// cancel the task, interrupting if still running.
result.cancel(true);
} catch (ExecutionException taskThrewAnException) {
// handle exception
}
// when you have finished with the service, which is reusable.
service.shutdown();
``` | Here are my guesses:
* When main thread calls `t.interrupt();` the t thread has already finished execution.
* When main thread calls `t.interrupt();` in the t thread there are no more calls to check `interrupted()` flag.
* You get the exception as a result of running the code? Do you get the exception you throw in your code after "allowance" time or you got some other like `ThreadInterruptedException` or similar? Try writing the message of the caught exception... | Threading in Java | [
"",
"java",
"multithreading",
"interrupt",
""
] |
I am sure that the above question has a straightforward answer but I couldn't easily find it (neither in the documentation nor on stackoverflow.com)
I got the notion that a BeanFactory/ApplicatioContext can be initialized with several bean configuration files. Is that so? And, if it is how can it be done? | See [section 3.2.2.1](http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-instantiation) in the Spring Reference documentation. This describes how a configuration file can be split into separate configuration files that can then be imported into your main configuration file. | Mark's answer is fine. You may also want to try this:
```
ApplicationContext context = new ClassPathXmlApplicationContext( new String[]{
"services.xml",
"daos.xml",
"webservices.xml",
"validators.xml"
});
``` | How can I configure a Spring BeanFactory with several bean configuration files? | [
"",
"java",
"spring",
""
] |
Can I make XmlSerializer ignore the namespace (xmlns attribute) on deserialization so that it doesn't matter if the attribute is added or not or even if the attribute is bogus? I know that the source will always be trusted so I don't care about the xmlns attribute. | Yes, you can tell the XmlSerializer to ignore namespaces during de-serialization.
Define an XmlTextReader that ignores namespaces. Like so:
```
// helper class to ignore namespaces when de-serializing
public class NamespaceIgnorantXmlTextReader : XmlTextReader
{
public NamespaceIgnorantXmlTextReader(System.IO.TextReader reader): base(reader) { }
public override string NamespaceURI
{
get { return ""; }
}
}
// helper class to omit XML decl at start of document when serializing
public class XTWFND : XmlTextWriter {
public XTWFND (System.IO.TextWriter w) : base(w) { Formatting= System.Xml.Formatting.Indented;}
public override void WriteStartDocument () { }
}
```
Here's an example of how you would de-serialize using that TextReader:
```
public class MyType1
{
public string Label
{
set { _Label= value; }
get { return _Label; }
}
private int _Epoch;
public int Epoch
{
set { _Epoch= value; }
get { return _Epoch; }
}
}
String RawXml_WithNamespaces = @"
<MyType1 xmlns='urn:booboo-dee-doo'>
<Label>This document has namespaces on its elements</Label>
<Epoch xmlns='urn:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'>0</Epoch>
</MyType1>";
System.IO.StringReader sr;
sr= new System.IO.StringReader(RawXml_WithNamespaces);
var s1 = new XmlSerializer(typeof(MyType1));
var o1= (MyType1) s1.Deserialize(new NamespaceIgnorantXmlTextReader(sr));
System.Console.WriteLine("\n\nDe-serialized, then serialized again:\n");
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("urn", "booboo-dee-doo");
s1.Serialize(new XTWFND(System.Console.Out), o1, ns);
Console.WriteLine("\n\n");
```
The result is like so:
```
<MyType1>
<Label>This document has namespaces on its elements</Label>
<Epoch>0</Epoch>
</MyType1>
``` | If you expect no namespace, but the input has namespaces, then you can set
> Namespaces = false
on your XmlTextReader. | Can I make XmlSerializer ignore the namespace on deserialization? | [
"",
"c#",
".net",
"serialization",
"xml-serialization",
""
] |
I'm wondering the performance differences between instantiating a class once in a form or whenever it is needed. For example, say I have a customer form to edit a customer. On the form load, I instantiate a customer class and call a function to return the customer data to populate the form controls.
```
CustomerInfo customer = new CustomerInfo();
CustomerDetail cust = customer.GetCustomer(customerId);
txtName. cust.Name;
...
```
Also on the form there is a save button. When that button is clicked, I create another instance of the Customer class to update the data.
```
CustomerDetail cust = new CustomerData();
cust.Id = customerId;
cust.Name = txtName.Text;
CustomerInfo customer = new CustomerInfo();
customer.Update(cust);
```
I know this works fine. However, is it better, performance wise, just to create a single instance of the Customer class for the whole form to call both GetCustomer and Update? I know the GC will take care of those instances, but I'm not sure it would destroy the first instance before going on to the next.
Also, this example I use just two function calls to customer class, but, really, there could be more.
Thanks for the help. | The idea should be that you create an instance of Customer for every distinct customer that you are manipulating. So if your form only deals with a single customer then you should have only one instance, but if your form deals with multiple customers then you will have multiple instances.
In terms of performance, that only becomes an issue if you are dealing with many instances, I would say thousands. | Premature optimization is the root of all evil.
NEVER consider optimization until you have a solution coded for optimum readability and find it insufficient to pass a test that tests a customer specification.
If your optimization does not then pass the same test that failed with the unoptimized version, revert it. | Performance concerns of instantiating a class multiple times | [
"",
"c#",
".net",
"performance",
""
] |
Is there any way to run one last command before a running Python script is stopped by being killed by some other script, keyboard interrupt etc. | ```
import time
try:
time.sleep(10)
finally:
print "clean up"
clean up
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
```
If you need to catch other OS level interrupts, look at the signal module:
<http://docs.python.org/library/signal.html>
### Signal Example
```
from signal import *
import sys, time
def clean(*args):
print "clean me"
sys.exit(0)
for sig in (SIGABRT, SIGBREAK, SIGILL, SIGINT, SIGSEGV, SIGTERM):
signal(sig, clean)
time.sleep(10)
``` | You could use the `atexit` module. With it, you can register a function which will be called at program termination. An example from here: <http://docs.python.org/library/atexit.html>
```
try:
_count = int(open("/tmp/counter").read())
except IOError:
_count = 0
def incrcounter(n):
global _count
_count = _count + n
def savecounter():
open("/tmp/counter", "w").write("%d" % _count)
import atexit
atexit.register(savecounter)
```
You can also pass positional and keyword parameters to the function you want to call at program termination.
Note that there are a few circumstances listed in the docs in which your handler won't be called:
> **Note**: The functions registered via this module are not called when the program is killed by a signal not handled by Python, when a Python fatal internal error is detected, or when [`os._exit()`](https://docs.python.org/3/library/os.html#os._exit) is called.
As such, you may want to also register a signal handler. | How to run one last function before getting killed in Python? | [
"",
"python",
"function",
"interrupt",
"exit",
""
] |
One of the popular way to organize project directory is more or less like this:
```
MyLib
+--mylib_class_a.h
mylib_class_a.cpp
mylib_library_private_helpers.h
mylib_library_private_helpers.cpp
MyApp
+--other_class.h
other_class.cpp
app.cpp
```
`app.cpp`:
```
#include "other_class.h"
#include <mylib_class_a.h> // using library MyLib
```
All `.h` and `.cpp` files for the same library are in the same directory. To avoid name collision, file names are often prefix with company name and/or library name. MyLib will be in MyApp's header search path, etc. I'm not a fan of prefixing filenames, but I like the idea of looking at the `#include` and know exactly where that header file belongs. I don't hate this approach of organizing files, but I think there should be a better way.
Since I'm starting a new project, I want to solicit some directory organization ideas. Currently I like this directory structure:
```
ProjA
+--include
+--ProjA
+--mylib
+--class_a.h
+--app
+--other_class.h
+--src
+--mylib
+--class_a.cpp
library_private_helpers.h
library_private_helpers.cpp
+--app
+--other_class.cpp
app.cpp
util.h
```
`app.cpp`:
```
#include "util.h" // private util.h file
#include <ProjA/app/other_class.h> // public header file
#include <ProjA/mylib/class_a.h> // using class_a.h of mylib
#include <other3rdptylib/class_a.h> // class_a.h of other3rdptylib, no name collision
#include <class_a.h> // not ProjA/mylib/class_a.h
#include <ProjA/mylib/library_private_helpers.h> // error can't find .h
```
`.cpp` files and private (only visible to immediate library) `.h` files are stored under the src directory (src is sometimes called lib). Public header files are organized into a project/lib directory structure and included via `<ProjectName/LibraryName/headerName.h>`. File names are not prefixed with anything. If I ever needed to package up MyLib to be used by other teams, I could simply change my makefile to copy the appropriate binary files and the whole include/ProjA directory.
Once files are checked into source control and people start working on them it will be hard to change directory structure. It is better to get it right at the get-go.
Anyone with experience organizing source code like this? Anything you don't like about it? If you have a better way to do it, I would very much like to hear about it. | Well, it all depends on how big these projects are. If you've only got a few files, then whack them all in one folder.
Too many folders when you haven't got many files to manage is in my opinion overkill. It gets annoying digging in and out of folders when you've only got a few files in them.
Also, it depends on who's using this stuff. If you're writing a library and its going to be used by other programmers, then it's good to organize the headers they want to use into an include folder. If you're creating a number of libraries and publishing them all, then your structure might work. But, if they're independent libraries, and the development isn't all done together and they get versioned and released at different times, you'd be better off sticking with having all files for one project locatable within one folder.
In fact, I would say keep everything in one folder, until you get to a point where you find its unmanagable, then reorganize into a clever scheme of dividing the source up into folders like you've done. You'll probably know how it needs to be organized from the problems you run into.
KISS is usually always the solution in programming -> keep everything as simple as possible. | Why not do something like the first, only use the directory that `MyLib` resides in as a part of the include directive, which reduces the silly prefixing:
```
#include <MyLib/ClassA.h>
```
That tells you where they are from. As for the second choice, I personally get really annoyed when I have a header or source file open, and have to navigate around through the directory structure to find the other and open it. With your second example, if you had `src/mylib/class_a.cpp` open, and wanted to edit the header, in many editors you'd have to go back two levels, then into `include/ProjA` before finding the header. And how are we to know that the header is in the `ProjA` subdirectory without some other external clue? Plus, it's too easy for one file or the other to get moved into a different place that "better" represents how it is used, without the alternate file being moved. It just gives me headaches when I encounter it at my job (and we do have some parts of our codebase where people did every potential problem I've just mentioned). | C++ project source code layout | [
"",
"c++",
"version-control",
"directory-structure",
"code-organization",
"project-organization",
""
] |
Given the following flow:
1) User clicks on a link, opens a popup window.
2) User does some things, clicks on a button to save changes.
3) Using AJAX, some data is POSTed.
4) In the AJAX response handler, the popup is closed and the main window refreshed.
There is a problem in FireFox 2, where closing the popup within a response handler fails (until some user activity, such as mouse movement, is performed on the window).
```
Sample code (popup window only):
function ajax_cb()
{
window.close();
}
// Send a POST request, ajax_cb will be called when readystate == 4.
function test_ajax_close()
{
Request.sendPOST("file:///test.html", "", ajax_cb);
}
```
In the above sample, the window will eventually close, but first requires user interaction. According to this [link](http://www.htmlbugs.com/archives/6-Firefox-+-AJAX-requests-+-window.close.html):
> Firefox gets unhappy if it still has a socket open doing an async AJAX request and you attempt to do a window.close(). | just wrap your close in a short timeout..
```
setTimeout(window.close, 100);
```
It shoould be enough time for the socket to finish closing, and the poopup to self-close. | One solution I came up with is to poll some variable externally and close the window when it changes. I'm looking for a better solution, but the sample code is:
```
var response_received = 0;
function ajax_cb()
{
response_received = 1;
}
function monitor_response()
{
if (response_received)
{
self.close();
return;
}
setTimeout("monitor_response()", 100);
}
function test_ajax_close()
{
Request.sendPOST("file:///test.html", "", ajax_cb);
monitor_response();
}
``` | Closing a popup window in Firefox 2 within an AJAX response handler | [
"",
"javascript",
"ajax",
"firefox",
""
] |
I know this is a common requirement and there are lots of answers out in the wild. I would really appreciate if someone can provide a correct script which opens only external links from an HTML file in a new window. | You can use jQuery for this:
```
$(document).ready(function(){
$("a[href^='http']:not([href*='"+location.hostname+"'])").attr("target","_blank");
});
```
It should match both http and https links. | I use a little JavaScript on my own site. I then have a style setup to modify the link (it adds a little image/globe, vaguely MSDN like. Making the link open in a new page would also be trivial by modifying the target attribute.
```
if (document.links) {
for (var i = 0; i < document.links.length; i++) {
l = document.links[i].href;
if (l.indexOf('http://www.mysite.com')!=0 &&
l.indexOf('http://udv.mysite.com')!=0 &&
l.indexOf('http://')==0 ) {
c = document.links[i];
if (c.className == "dontModify") continue;
c.className = c.className + " external";
if (c.title != "") {
c.title = "External link: " + c.title;
}
}
}
}
``` | How to open only external links in a new browser window via JavaScript? | [
"",
"javascript",
""
] |
I would like to make a very simple ant script that does 1 thing, which is to bulid a jar file. But when I try to use a very simple example, it fails due to dependancies on jars that my source depends on. So, How you you specify jars that there are jars that need to be in the class path when building an Ant target.
```
<project name="project" default="default">
<property name="src.dir" value="src"/>
<property name="build.dir" value="build"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.dir" value="${build.dir}/jar"/>
<property name="lib.dir" value="//tomcat/common/lib"/>
<description> description </description>
<!-- =================================
target: default
================================= -->
<target name="default" depends="compile" description="description">
<jar destfile="/path/to/dir/Library.jar">
</jar>
</target>
<target name="compile">
<mkdir dir="${classes.dir}"/>
<javac srcdir="${src.dir}" destdir="${classes.dir}"/>
</target>
</project>
``` | Based on your example you can just put libs inside javac:
```
<javac srcdir="${src.dir}" destdir="${classes.dir}">
<classpath>
<pathelement location="${lib.dir}/lib1.jar"/>
<pathelement location="${lib.dir}/lib2.jar"/>
</classpath>
</javac>
``` | Your question isn't entirely clear - I suspect you mean you want to compile your source (with the `javac` task) and *then* build a jar file from the results. If that's not the case, I don't see where your source dependencies come into it. If that *is* the case, then the `jar` task is irrelevant.
In the [`javac`](http://ant.apache.org/manual/Tasks/javac.html) task, use the classpath attribute to specify other jar dependencies. | Ant Script Example | [
"",
"java",
"eclipse",
"ant",
"jar",
""
] |
In Java, you can load all kinds of resources using the same API but with different URL protocols:
```
file:///tmp.txt
http://127.0.0.1:8080/a.properties
jar:http://www.foo.com/bar/baz.jar!/COM/foo/Quux.class
```
This nicely decouples the actual loading of the resource from the application that needs the resource, and since a URL is just a String, resource loading is also very easily configurable.
Is there a protocol to load resources using the current classloader?
This is similar to the Jar protocol, except that I do not need to know which jar file or class folder the resource is coming from.
I can do that using [`Class.getResourceAsStream("a.xml")`](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)), of course, but that would require me to use a different API, and hence changes to existing code. I want to be able to use this in all places where I can specify a URL for the resource already, by just updating a property file. | ## Intro and basic Implementation
First up, you're going to need at least a URLStreamHandler. This will actually open the connection to a given URL. Notice that this is simply called `Handler`; this allows you to specify `java -Djava.protocol.handler.pkgs=org.my.protocols` and it will automatically be picked up, using the "simple" package name as the supported protocol (in this case "classpath").
### Usage
```
new URL("classpath:org/my/package/resource.extension").openConnection();
```
### Code
```
package org.my.protocols.classpath;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
/** A {@link URLStreamHandler} that handles resources on the classpath. */
public class Handler extends URLStreamHandler {
/** The classloader to find resources from. */
private final ClassLoader classLoader;
public Handler() {
this.classLoader = getClass().getClassLoader();
}
public Handler(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
protected URLConnection openConnection(URL u) throws IOException {
final URL resourceUrl = classLoader.getResource(u.getPath());
return resourceUrl.openConnection();
}
}
```
### Launch issues
If you're anything like me, you don't want to rely on a property being set in the launch to get you somewhere (in my case, I like to keep my options open like Java WebStart - which is why *I* need all this).
## Workarounds/Enhancements
### Manual code Handler specification
If you control the code, you can do
```
new URL(null, "classpath:some/package/resource.extension", new org.my.protocols.classpath.Handler(ClassLoader.getSystemClassLoader()))
```
and this will use your handler to open the connection.
But again, this is less than satisfactory, as you don't need a URL to do this - you want to do this because some lib you can't (or don't want to) control wants urls...
### JVM Handler registration
The ultimate option is to register a `URLStreamHandlerFactory` that will handle all urls across the jvm:
```
package my.org.url;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.util.HashMap;
import java.util.Map;
class ConfigurableStreamHandlerFactory implements URLStreamHandlerFactory {
private final Map<String, URLStreamHandler> protocolHandlers;
public ConfigurableStreamHandlerFactory(String protocol, URLStreamHandler urlHandler) {
protocolHandlers = new HashMap<String, URLStreamHandler>();
addHandler(protocol, urlHandler);
}
public void addHandler(String protocol, URLStreamHandler urlHandler) {
protocolHandlers.put(protocol, urlHandler);
}
public URLStreamHandler createURLStreamHandler(String protocol) {
return protocolHandlers.get(protocol);
}
}
```
To register the handler, call `URL.setURLStreamHandlerFactory()` with your configured factory. Then do `new URL("classpath:org/my/package/resource.extension")` like the first example and away you go.
### JVM Handler Registration Issue
Note that this method may only be called once per JVM, and note well that Tomcat will use this method to register a JNDI handler (AFAIK). Try Jetty (I will be); at worst, you can use the method first and then it has to work around you!
## License
*I release this to the public domain, and ask that if you wish to modify that you start a OSS project somewhere and comment here with the details. A better implementation would be to have a `URLStreamHandlerFactory` that uses `ThreadLocal`s to store `URLStreamHandler`s for each `Thread.currentThread().getContextClassLoader()`. I'll even give you my modifications and test classes.* | ```
URL url = getClass().getClassLoader().getResource("someresource.xxx");
```
That should do it. | URL to load resources from the classpath in Java | [
"",
"java",
"url",
"classloader",
""
] |
If you take an existing C code base and compile it with a C++ compiler, what sort of issues can you expect to crop up? For example, I think that assigning an integer to an value with an enumerated type will fail in C++, whereas it's legal (if a bit nasty) in C.
If I don't wrap all my C files in `extern C { ... }`, am I going to get name-mangling where I least expect it? Is there some reason why I really shouldn't do this?
For background, we have a very large code-base written in C. For a few years we've been jumping through hoops to do things that would come naturally via C++ ( homebrewe inheritance, for example). We'd like to start moving towards C++, but in a gradual fashion; getting our CORBA-like framework to support it, and refactoring modules as we go along to take advantage of the more natural approach C++ would provide. | I've done something like this once. The main source of problems was that C++ is more strict about types, as you suspected. You'll have to add casts where void\* are mixed with pointers of other types. Like allocating memory:
```
Foo *foo;
foo = malloc(sizeof(*foo));
```
The above is typical C code, but it'll need a cast in C++:
```
Foo *foo;
foo = (Foo*)malloc(sizeof(*foo));
```
There are new reserved words in C++, such as "class", "and", "bool", "catch", "delete", "explicit", "mutable", "namespace", "new", "operator", "or", "private", "protected", "friend", etc. These cannot be used as variable names, for example.
The above are probably the most common problems when you compile old C code with a C++ compiler. For a complete list of incompatibilities, see [Incompatibilities Between ISO C and ISO C++](http://david.tribble.com/text/cdiffs.htm).
You also ask about name mangling. In absence of extern "C" wrappers, the C++ compiler *will* mangle the symbols. It's not a problem as long as you use *only* a C++ compiler, and don't rely on dlsym() or something like that to pull symbols from libraries. | See [Incompatibilities between ISO C and ISO C++](http://david.tribble.com/text/cdiffs.htm) for a *very* detailed list of all of the incompatibilities. There are a lot of subtle issues, including some which don't immediately manifest in a compiler error. For example, one issue that can be a problem is the size of character constants:
```
// In C, prints 4. In C++, prints 1
printf("%d\n", sizeof('A'));
``` | What issues can I expect compiling C code with a C++ compiler? | [
"",
"c++",
"c",
"compiler-construction",
"migration",
"language-interoperability",
""
] |
I am trying to get values from html list `<li>`.
```
<ul>
<li><a>Main Menu</a>
<ul class="leftbutton" >
<li value="List1"><a>Sampe 1</a></li>
<li value="List2"><a>Sample 2</a></li>
<li value="List3"><a>Sample 3</a></li>
<li value="List4"><a>Sample 4</a></li>
<li value="List5"><a>Sample 5</a></li>
</ul>
</li>
</ul>
<iframe id="iframeid" width="100%" height="100%" align="middle"></iframe>
function changeList()
{
var iframe = document.getElementById("iframeid");
var url = document.getElementById("selectedlist").value + ".html";
iframe.src = url;
}
```
Where would I put `onClick="changeList()"` to get the values from the list? | You get several things wrong here.
1. a HTML list item (`<li>`) does not have a value
2. a HTML list has no "selected item"
3. you cannot get any "selected" item by calling `getElementById()`
Here is my alternative suggestion:
```
<ul>
<li><a>Main Menu</a>
<ul class="leftbutton" >
<li><a href="List1.html" onclick="return changeList(this);">Sample 1</a></li>
<li><a href="List2.html" onclick="return changeList(this);">Sample 2</a></li>
<li><a href="List3.html" onclick="return changeList(this);">Sample 3</a></li>
<li><a href="List4.html" onclick="return changeList(this);">Sample 4</a></li>
<li><a href="List5.html" onclick="return changeList(this);">Sample 5</a></li>
</ul>
</li>
</ul>
<iframe id="iframeid" width="100%" height="100%" align="middle"></iframe>
<script type="text/javascript">
function changeList(a)
{
var iframe = document.getElementById("iframeid");
iframe.src = a.href;
return false;
}
</script>
```
Thoughts: If JavaScript is deactivated, it still works (rudimentarily). The function returns `false`, so when JavaScript is enabled clicking on the link cancels the href navigation.
Be aware that up to HTML 4.01 Transitional it is also possible to do this entirely without JavaScript. A `target` attribute with the frame name is sufficient:
```
<ul>
<li><a>Main Menu</a>
<ul class="leftbutton" >
<li><a href="List1.html" target="iframename">Sample 1</a></li>
<li><a href="List2.html" target="iframename">Sample 2</a></li>
<li><a href="List3.html" target="iframename">Sample 3</a></li>
<li><a href="List4.html" target="iframename">Sample 4</a></li>
<li><a href="List5.html" target="iframename">Sample 5</a></li>
</ul>
</li>
</ul>
<iframe id="iframeid" name="iframename" width="100%" height="100%" align="middle"></iframe>
``` | I'm not 100% sure about inline iframes but you could simply use
```
<li><a href="/path/to/html" target="myIframeId">Value</a></li>
```
This isn't valid html 4 strict but is valid with transitional and works in all browsers regardless. | How to get the html List value through JavaScript? | [
"",
"javascript",
"html",
"dom-events",
""
] |
On my Google App Engine application, i'm storing an auto-updated date/time in my model like that :
```
class MyModel(db.Model):
date = db.DateTimeProperty(auto_now_add=True)
```
But, that date/time is the local time on server, according to it's time zone.
So, when I would like to display it on my web page, how may I format it according the **client** time zone ?
Also, how may I know on which time zone that google server is ? | With respect to the second part of your question:
Python time() returns UTC regardless of what time zone the server is in. timezone() and tzname() will give you, respectively, the offset to local time on the server and the name of the timezone and the DST timezone as a tuple. GAE uses Python 2.5.x as of the time of this posting; see the documentation for Python time functions [here](http://www.python.org/doc/2.3.5/lib/module-time.html).
For the first part of the question:
You can either format the date with code on the server, or with code on the client.
* If you format on the server, you can
+ Use the timezone of the requester's IP address
+ Require a user to register and give you a timezone, store it, and use the stored value
+ Use a (hidden?) field on the GET or POST so the client's desired timezone is part of the request
* If you format on the client, you'll need to write a few lines of JavaScript. The procedure is something like "make a date from UTC using Date(utctime), then stuff it into the document." By default, JavaScript dates display as local time regardless of how they were initialized - awesome!
I recommend formatting on the client, because what's a webpage like without a bit of JavaScript? It's 2009! [Marcelo](http://blogs.msdn.com/marcelolr/archive/2008/06/04/javascript-date-utc-and-local-times.aspx) has some examples. | Ok, so thanks to Thomas L Holaday, I have to sent that UTC date to the client, for example using JSON :
```
json = '{"serverUTCDate":new Date("%s")}' % date.ctime()
```
And then, on the client side, add/remove the number of seconds according to the user time zone like that :
```
var localDate = serverUTCDate.getTime() - (new Date()).getTimezoneOffset()*60000;
``` | On GAE, how may I show a date according to right client TimeZone? | [
"",
"python",
"django",
"google-app-engine",
"timezone",
""
] |
I was thinking of doing this with C++, basically from an external editor or something the programmer can say: MyClass::dude = "hello" where 'dude' is a static integer in 'MyClass'.
What the program does at runtime is it partitions the input to MyClass :: dude = "hello" and finds the class called 'MyClass' and assigns the dude variable in it as "hello".
The idea behind it is for it to act as a sort of a runtime debugger.
Is this safe/sane? | Yes, this is a typical tool used during development to help fine-tune games. It's not so often something you type in as much as a screen where you can adjust variables on the fly with a controller (that changes some class variable under the hood), but for pc games, there isn't a reason why you couldn't type in something, especially if it's text. You would, of course, need to program your own system where a class notifies some part of your engine of it's name and how to get at some of its variables. | Your typical debugger can already do this for all basic types.
Assigning a char string value is a bit more involved since it requires allocating memory for the actual string and assigning a pointer to it to the variable. | Making all variables in a program modifiable at runtime by the programmer, smart idea? | [
"",
"c++",
"debugging",
"console",
""
] |
This post started out as "What are some common patterns in unit testing multi-threaded code ?", but I found some [other](https://stackoverflow.com/questions/12159/how-should-i-unit-test-threaded-code) [discussions](https://stackoverflow.com/questions/352695/best-way-to-run-multi-threaded-nunit-tests) on SO that generally agreed that "It is Hard (TM)" and "It Depends (TM)". So I thought that reducing the scope of the question would be more useful.
***Background*** : We are implementing a simple scheduler that gives you a way to register callbacks when starting and stopping jobs and of course configure the frequency of scheduling. Currently, we're making a lightweight wrapper around java.util.Timer.
***Aspects***:
* I haven't found a way to test this scheduler by relying on only public interfaces (something like `addJob(jobSchedule, jobArgs,jobListener)` , `removeJob(jobId)`).
* How do I time the fact that the the job was called according to the schedule specified ? | you could use a **recorder object** that record the order, timings and other useful stuff in each unit test of your scheduler. The test is simple:
1. create a **recorder object**
2. configure the schedule
3. execute a unit test
4. check that recorder object is "compatible" with the schedule | One thing also to remember is that you don't need to test that Timer works. You can write a mock version of Timer (by extending the class or using [EasyMock](http://easymock.org/Links.html)) that simply checks that you are calling it correctly, possibly even replacing enough that you don't need threads at all. In this case that might be more work than needed if your job listener has enough callbacks to track the scheduler.
The other important thing to remember is that when testing the scheduler, use custom jobs that track how the scheduler is working; when testing scheduled jobs, call the callbacks directly and not through the scheduler. You may have a higher level integration test that checks both together, depending on the system. | What are some strategies to unit test a scheduler? | [
"",
"java",
"multithreading",
"unit-testing",
""
] |
Given a string, figure out how many characters minimum are needed to make the word a palindrome. Examples:
```
ABBA : 0 (already a palindrome)
ABB: 1
FAE: 2
FOO: 1
``` | Algorithms only, since this is probably homework [Apologies to Raymond, it's an interview question rather than homework, as his edits/comments make clear. However, the algorithms and added pseudo-code are still valid for that purpose, and I've added some C code at the end].
You need to find the longest palindrome at the end of the string. An algorithm to see if a string is a palindrome can be created by simply running one pointer from the start of the string and one from the end, checking that the characters they refer to are identical, until they meet in the middle. Something like:
```
function isPalindrome(s):
i1 = 0
i2 = s.length() - 1
while i2 > i1:
if s.char_at(i1) not equal to s.char_at(i2):
return false
increment i1
decrement i2
return true
```
Try that with the full string. If that doesn't work, save the first character on a stack then see if the remaining characters form a palindrome. If that doesn't work, save the second character as well and check again from the third character onwards.
Eventually you'll end up with a series of saved characters and the remaining string which is a palindrome.
Best case is if the original string *was* a palindrome in which case the stack will be empty. Worst case is one character left (a one-character string is automatically a palindrome) and all the others on the stack.
The number of characters you need to add to the end of the original string is the number of characters on the stack.
To actually make the palindrome, pop the characters off the stack one-by-one and put them at the start and the end of the palindromic string.
Examples:
```
String Palindrome Stack Notes
------ ---------- ----- -----
ABBA Y - no characters needed.
String Palindrome Stack Notes
------ ---------- ----- -----
ABB N -
BB Y A one character needed.
ABBA Y - start popping, finished.
String Palindrome Stack Notes
------ ---------- ----- -----
FAE N -
AE N F
E Y AF two characters needed.
AEA Y F start popping.
FAEAF Y - finished.
String Palindrome Stack Notes
------ ---------- ----- -----
FOO N -
OO Y F one character needed.
FOOF Y - start popping, finished.
String Palindrome Stack Notes
------ ---------- ----- -----
HAVANNA N -
AVANNA N H
VANNA N AH
ANNA Y VAH three characters needed.
VANNAV Y AH start popping.
AVANNAVA Y H
HAVANNAVAH Y - finished.
```
```
String Palindrome Stack Notes
------ ---------- -------- -----
deoxyribo N -
eoxyribo N d
oxyribo N ed
: : :
bo N iryxoed
o Y biryxoed eight chars needed.
bob Y iryxoed start popping.
ibobi Y ryxoed
: : :
oxyribobiryxo Y ed
eoxyribobiryxoe Y d
deoxyribobiryxoed Y - finished.
```
Converting this method to "code":
```
function evalString(s):
stack = ""
while not isPalindrome(s):
stack = s.char_at(0) + stack
s = s.substring(1)
print "Need " + s.length() + " character(s) to make palindrome."
while stack not equal to "":
s = stack.char_at(0) + s + stack.char_at(0)
stack = stack.substring(1)
print "Palindrome is " + s + "."
```
For those less interested in pseudo-code, here's a test program in C which does the trick.
```
#include <stdio.h>
#include <string.h>
static char *chkMem (char *chkStr) {
if (chkStr == NULL) {
fprintf (stderr, "Out of memory.\n");
exit (1);
}
return chkStr;
}
static char *makeStr (char *oldStr) {
char *newStr = chkMem (malloc (strlen (oldStr) + 1));
return strcpy (newStr, oldStr);
}
static char *stripFirst (char *oldStr) {
char *newStr = chkMem (malloc (strlen (oldStr)));
strcpy (newStr, &(oldStr[1]));
free (oldStr);
return newStr;
}
static char *addFront (char *oldStr, char addChr) {
char *newStr = chkMem (malloc (strlen (oldStr) + 2));
sprintf (newStr, "%c%s", addChr, oldStr);
free (oldStr);
return newStr;
}
```
```
static char *addBoth (char *oldStr, char addChr) {
char *newStr = chkMem (malloc (strlen (oldStr) + 3));
sprintf (newStr, "%c%s%c", addChr, oldStr, addChr);
free (oldStr);
return newStr;
}
static int isPalindrome (char *chkStr) {
int i1 = 0;
int i2 = strlen (chkStr) - 1;
while (i2 > i1)
if (chkStr[i1++] != chkStr[i2--])
return 0;
return 1;
}
```
```
static void evalString (char *chkStr) {
char * stack = makeStr ("");
char * word = makeStr (chkStr);
while (!isPalindrome (word)) {
printf ("%s: no, ", word);
stack = addFront (stack, *word);
word = stripFirst (word);
printf ("stack <- %s, word <- %s\n", stack, word);
}
printf ("%s: yes, need %d character(s)\n", word, strlen (stack));
printf ("----------------------------------------\n");
printf ("Adjusting to make palindrome:\n");
while (strlen (stack) > 0) {
printf (" %s, stack <- %s\n", word, stack);
word = addBoth (word, *stack);
stack = stripFirst (stack);
}
printf (" %s\n", word);
printf ("========================================\n");
free (word);
free (stack);
}
int main (int argc, char *argv[]) {
int i;
for (i = 1; i < argc; i++) evalString (argv[i]);
return 0;
}
```
Running this with:
```
mkpalin abb abba fae foo deoxyribo
```
gives the output:
```
abb: no, stack <- a, word <- bb
bb: yes, need 1 character(s)
----------------------------------------
Adjusting to make palindrome:
bb, stack <- a
abba
========================================
```
```
abba: yes, need 0 character(s)
----------------------------------------
Adjusting to make palindrome:
abba
========================================
```
```
fae: no, stack <- f, word <- ae
ae: no, stack <- af, word <- e
e: yes, need 2 character(s)
----------------------------------------
Adjusting to make palindrome:
e, stack <- af
aea, stack <- f
faeaf
========================================
```
```
foo: no, stack <- f, word <- oo
oo: yes, need 1 character(s)
----------------------------------------
Adjusting to make palindrome:
oo, stack <- f
foof
========================================
```
```
deoxyribo: no, stack <- d, word <- eoxyribo
eoxyribo: no, stack <- ed, word <- oxyribo
oxyribo: no, stack <- oed, word <- xyribo
xyribo: no, stack <- xoed, word <- yribo
yribo: no, stack <- yxoed, word <- ribo
ribo: no, stack <- ryxoed, word <- ibo
ibo: no, stack <- iryxoed, word <- bo
bo: no, stack <- biryxoed, word <- o
o: yes, need 8 character(s)
----------------------------------------
Adjusting to make palindrome:
o, stack <- biryxoed
bob, stack <- iryxoed
ibobi, stack <- ryxoed
ribobir, stack <- yxoed
yribobiry, stack <- xoed
xyribobiryx, stack <- oed
oxyribobiryxo, stack <- ed
eoxyribobiryxoe, stack <- d
deoxyribobiryxoed
========================================
``` | I saw this question in a competition once. I was stumped then.
But i think i've gotten this after discussing it with my friends. The thing is to find the minimum characters to insert into a string, you need to find the longest palindrome its centered around.
Take the string "accaz"
Imagine the string accaz is the palindrome acca with z inserted at the end. So we need to add another z at the start.
Another string :"mykma"
Imagine this to be mym with two characters k and a inserted into it. So we need to two more characters to make it a palindrome. (the palindrome would be amkykma).
I've written a program in Java implementing this.
```
import java.util.*;
import java.io.*;
public class MinPalin{
//Function to check if a string is palindrome
public boolean isPaindrome(String s){
int beg=0;
int end=s.length()-1;
while(beg<end){
if(s.charAt(beg)!=s.charAt(end)){
return false;
}
beg++;
end--;
}
return true;
}
public int MinInsert(String s){
int min=0;
if(isPaindrome(s)){
return min;
}
min++;
while(true){
ArrayList<String> temp=comboes(s,min);
if(hasPalindrome(temp)){
return min;
}
else
min++;
}
}
/*
* Returns an arraylist of strings, in which n characters are removed
*
*/
public ArrayList<String> comboes(String s,int n){
ArrayList<String> results=new ArrayList<String>();
if(n==1){
for(int i=0;i<s.length();i++){
String text="";
for(int j=0;j<s.length();j++){
if(i!=j){
text=text+""+s.charAt(j);
}
}
results.add(text);
}
}
else{
ArrayList<String> temp=new ArrayList<String>();
for(int i=0;i<s.length();i++){
String tempString="";
for(int j=0;j<s.length();j++){
if(i!=j){
tempString=tempString+s.charAt(j);
}
}
temp=comboes(tempString, n-1);
for(int j=0;j<temp.size();j++){
results.add(""+temp.get(j));
}
}
}
return results;
}
public boolean hasPalindrome(ArrayList<String> text){
for(String temp:text){
if(isPaindrome(temp)){
return true;
}
}
return false;
}
public static void main(String[] args)throws IOException
{
System.out.println("Enter the word :");
MinPalin obj=new MinPalin();
BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
int n=obj.MinInsert(r.readLine());
System.out.println("Characters needed : "+n);
}
}
```
Hope this helps. | How do I figure out the least number of characters to create a palindrome? | [
"",
"c#",
"string",
"algorithm",
""
] |
I know there is a lot of similar questions are tons of great answers to this. I tried to look at the classical inheritance methods, or those closure methods etc. Somehow I consider they are more or less "hack" methods to me, as it doesn't really what the javascript is designed to do. (Welcome anybody correct me if I am wrong).
OK, as long as it works, I satisfy with the classical inheritance pattern like:
```
PARENTClass = function (basevar) { do something here; };
PARENTClass.prototype = { a: b, c: d}; // prototype is auto gen
// Inheritance goes here
CHILDClass = function (childvar) { do something; };
CHILDClass.prototype = new PARENTClass(*1); // Actual inheritance to the prototype statement
// Instance
CHILDInstance = new CHILDClass(whatever);
```
Above is somehow, to my understanding the inheritance of JS. But one scenario I have no idea how to implement, is that what if I want to do some initializing DURING object creation (ie, within constructor), and the new object can be used right away.... My illustration on problem might not be too clear, so let me use the following C# Psuedo to explain what I want to do:
```
class PARENT {
public PARENT (basevar) { ... }
}
class CHILD : PARENT {
public CHILD (basevar) : PARENT (basevar) // constructor of child, and call parent constructor during construct.
{ ... }
}
```
For some reason (like init. UI elements), putting them in constructor seems the best way to do. Anyone have idea on how can I do it.
PS: in the \*1, I have no idea what I should put there.
PS2: The above situation I DID found the jquery.inherit library can do, I just wonder if not using library can achieve it.
PS3: Or my understanding is wrong. Since javascript is not intended to mimick OOP (that's why i call it hack), what is the "CORRECT" logic to implement this. | It is not a *hack* as such; JavaScript is a prototyped language, as defined by [Wikipedia](http://en.wikipedia.org/wiki/Prototype-based_programming) as where:
> ..classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes.
As it says, classes are not used in JavaScript; each object that you create is descended from the JavaScript `Object`; all objects in JavaScript have the `prototype` object, and all instances of objects you create 'inherit' methods and properties from their object's prototype object. Take a look at the MDC [prototype](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/prototype) object reference for more information.
As of this, when you call the line:
```
CHILDClass.prototype = new PARENTClass();
```
This allows the `CHILDClass` object to add methods and properties to its prototype object from the `PARENTClass` object, which creates an effect similar to the idea of inheritance present in class-based languages. Since the `prototype` object affects every instance created of that object, this allows the parent object's methods and properties to be present in every instance of your child object.
If you want to call your parent class's constructor in your child class's constructor, you use the JavaScript `call` function; this allows you to call the parent class's constructor in the context of the child class's constructor, therefore setting the newly prototyped properties in your child class to what they are set as in the parent class.
You also do not need to put anything where you have specified the `*1`, since that line is merely used to add the methods and properties to the child class's prototype object; however, bear in mind that it calls the parent class's constructor, so if there are any arguments that are fundamental in the operation of the parent class constructor, you should check that these are present so as to avoid JavaScript errors. | You can manually invoke the parent constructor in the subclass constructor like this:
```
CHILDClass = function (basevar) {
PARENTClass.call(this, basevar);
// do something;
};
```
The trick here is using the `call` method, which allows you to invoke a method in the context of a different object. See [the documentation of `call`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/call) for more details. | javascript inheritance | [
"",
"javascript",
"inheritance",
""
] |
I'm running a number of threads which each attempt to perform INSERTS to one SQLite database. Each thread creates it's own connection to the DB. They each create a command, open a Transaction perform some INSERTS and then close the transaction. It seems that the second thread to attempt anything gets the following SQLiteException: The database file is locked. I have tried unwrapping the INSERTS from the transaction as well as narrowing the scope of INSERTS contained within each commit with no real effect; subsequent access to the db file raises the same exception.
Any thoughts? I'm stumped and I'm not sure where to look next... | Update your insertion code so that if it encounters an exception indicating database lock, it waits a bit and tries again. Increase the wait time by random increments each time (the "random backoff" algorithm). This should allow the threads to each grab the global write lock. Performance will be poor, but the code should work without significant modification.
However, SQLite is not appropriate for highly-concurrent modification. You have two permanent solutions:
* Move to a "real" database, such as PostgreSQL or MySQL
* Serialize all your database modifications through one thread, to avoid SQLite's modifications. | Two things to check:
1) Confirmed that your version of SQLite was compiled with THREAD support
2) Confirm that you are not opening the database EXCLUSIVE | Difficulty running concurrent INSERTS on SQLite database in C# | [
"",
"c#",
"sqlite",
"system.data.sqlite",
""
] |
I am using a listbox in my C#2.0 windows forms application. The method to populate the list box is
```
private void PopulateListBox(ListBox lb, ReportColumnList reportColumnList)
{
lb.DataSource = reportColumnList.ReportColumns;
lb.DisplayMember = "ColumnName";
lb.ValueMember = "ColumnName";
}
```
However, when it executes the method it also calls the SelectedIndexChanged event handler of the listbox, even though I am not setting the selected index in the method above. How can I prevent the SelectedIndexChanged event handler from being called for the above code?
I want the event to be called only when the user makes the selections in the ListBox. Or is there any other event which is only for user selecting listbox items using mouse click?
On another note, even if the user clicks on an empty area in the list box the SelectedIndexChanged event gets fired. So I am wondering how different is it from the MouseClick event? | You can populate the listbox using lb.Items.AddRange() instead of setting the datasource. In addition to not triggering the SelectedIndexChanged, this also won't pre-select the first item.
```
lb.Items.Clear();
lb.Items.AddRange(reportColumnList.ReportColumns.ToArray());
``` | There are three ways you can go about this.
A) Don't hook into the SelectedIndexChanged event until AFTER you've called this method.
B) Have a private boolean in your class that's initially set to true. At the start of your PopulateListBoxmethod, set it to false, and at the end set it back to true. In your event handler for SelectedIndexChanged , if the flag is false, just return and do nothing.
C) In the start of your PopulateListBoxmethod, unhook from the event (this.listbox1.SelectedIndexChanged -= myMethod;) and then right before the method is done, rehook into that event. | How to prevent ListBox.SelectedIndexChanged event? | [
"",
"c#",
".net",
"winforms",
""
] |
There's a related question [What is the preferred Java XML binding framework?](https://stackoverflow.com/questions/205749/java-xml-binding)
In the answer currently ranked 2nd there, the poster drew a distinction between XML Serialization, and Java/XML data binding. As best I can tell, XML data binding means "creating an in-memory object graph from an XML document". And XML Serialization means "creating an XML document from an in-memory object graph."
I don't see that they are different at all, just different perspectives on the same problem.
The argument was that the emphasis in data binding is on the object model, while the emphasis in serialization is on the document format. I don't see that at all. If one is serializing an object graph to XML, presumably one cares about the format - it needs to be readable, toolable, validatable. (If the format is irrelevant, then why not just use binary serialization and be done with it?) On the other hand, when performing "data binding" (what I would call *de-serializing*), there must be a balanced emphasis on both the document format and the object model.
So the question to you:
Is there a difference between *Java/XML data binding* and *XML Serialization* that is worth worrying about? | Thanks for all the input. Considering it all, I still feel that the distinction is an artificial one. Primary? Secondary? It feels subjective, fuzzy, arbitrary and artificial. This tells me there is no meaningful distinction. | No, there is a very important **conceptual** difference here, like you mention.
It may be that implementations have strong similarities, and maybe that causes confusion, but conceptually it is not that unclear.
Data binding means binding Java objects to non-object content (relational data for ORMs, xml or json documents etc); and different representations (POJOs, relational/hierarchic data) are equally important. Data binding has to concern itself with specifics of data format(s) it supports; some features have no equivalent constructs in Java POJOs (for example: XML mixed content, comments, processing instructions, difference between attributes and elements). Data binding focuses on trying to bridge the impedance: allow as seamless conversion between representations as possible, and in both directions.
With object serialization, you start and end with (Java) objects -- other formats are of secondary concern, and only serve the purpose of passing objects. They may hard-code exact structure in data format used; but even if not, limit kinds of constructs that can be used.
Object serialization has to deal with things that are specific to objects: identity, references, handling of cycles; things that data binders can ignore.
But here's what may confuse matters: in general, object serialization libs (like XStream) offer lots of flexibility to customize external format (even though it's of less importance than objects). And you can certainly use data binding tools as alternatives to pure object serialization tools -- for many/most cases they work pretty well.
So you can indeed use tools for "secondary purposes". But there are limitations, depending on exact feature set you need: many data binding tools can not deal with cyclic references; object serializers can not support but subset xml and so forth. And even where you can use secondary tools, you might be better off choosing differently, with regards to ease of use, or performance. | Is XML Serialization really different from XML databinding, and if so, how? | [
"",
"java",
"xml",
"xml-serialization",
""
] |
So I have seen some comments on various web sites, pages, and questions I have asked about separating php and html.
I assume this means doing this:
```
<?php
myPhpStuff();
?>
<html>
<?php
morePhpStuff();
?>
```
Rather than:
```
<?php
doPhpStuff();
echo '<html>';
?>
```
But why does this matter? Is it really important to do or is it a preference?
---
Also it seems like when I started using PHP doing something like breaking out of PHP in a while loop would cause errors. Perhaps this is not true anymore or never was.
---
I made a small example with this concept but to me it seems so messy:
```
<?php
$cookies = 100;
while($cookies > 0)
{
$cookies = $cookies -1;
?>
<b>Fatty has </b><?php echo $cookies; ?> <b>cookies left.</b><br>
<?php
}
?>
```
Are there instances when it is just better to have the HTML inside the PHP?
```
<?php
$cookies = 100;
while($cookies > 0)
{
$cookies = $cookies -1;
echo'<b>Fatty has </b> '.$cookies.' <b>cookies left.</b><br>';
}
?>
``` | Let's make it clear what is not separation
* you switch from php mode to html mode
* you use print or echo statements to write out html code
* you use small php snipplets inside html files
If you do this, there is no separation at all, no matter if you escape from php to html blocks or do it the other way and put php code into html.
Have a look at a good templating engine, there are a plenty of reasons in the "why use ...." parts of the manuals. I'd suggert www.smarty.net especially <http://www.smarty.net/whyuse.php>
**It will answer all your questions now you have.** | When people talk about separating PHP and HTML they are probably referring to the practice of separating a website's presentation from the code that is used to generate it.
For example, say you had a DVD rental website and on the homepage you showed a list of available DVDs. You need to do several things: get DVD data from a database, extract and/or format that data and maybe mix some data from several tables. format it for output, combine the DVD data with HTML to create the webpage the user is going to see in their browser.
It is good practice to separate the HTML generation from the rest of the code, this means you can easily change your HTML output (presentation) without having to change the business logic (the reading and manipulation of data). And the opposite is true, you can change your logic, or even your database, without having to change your HTML.
A common pattern for this is called [MVC (model view controller)](http://en.wikipedia.org/wiki/Model-view-controller).
You might also want to look at the Smarty library - it's a widely used PHP library for separating presentation and logic. | separating php and html... why? | [
"",
"php",
"html",
"formatting",
""
] |
Does anybody know of a way I can calculate very large integers in c#
I am trying to calculate the factorial of numbers e.g.
5! = 5\*4\*3\*2\*1 = 120
with small numbers this is not a problem but trying to calculate the factorial of the bigest value of a unsigned int which is 4,294,967,295 it doesn't seem possible.
I have looked into the BigInteger class but it doesn't seem to do what I need
any help would be greatly appreciated | 4294967295! = 10^(10^10.597) ~ 10^(40000000000)
This value requires about 40 Gb of RAM to store, even if you will find any BigInteger implementation for C#!
P.S. Well, with optimized storing, let's say 9 digits in 4 bytes, it will take ~18 Gb of RAM. | To calculate the factorial of `uint.MaxValue` you'd need a *lot* of storage.
For example, the [Wikipedia article](http://en.wikipedia.org/wiki/Factorial) as 8.2639316883... × 10^5,565,708. You're going to gain information like crazy.
I *strongly* suspect you're not going find any way of calculating it on a sane computer in a sane amount of time. Why do you need this value? Would Stirling's approximation be close enough? | working with very large integers in c# | [
"",
"c#",
"factorial",
""
] |
Imagine an application based on options.
I want to add an exclamation mark to the end of every string (itself, an extremely easy task). However, I have an option in web.config or an XML file, so if the option is true, the exclamation is appended, otherwise it isn't.
I know how to check web.config or an xml file for the setting's value, however, what is the best way to do this? In the case of a string, it will be heavily used in any program.
I could write:
```
if (ExclamationIsSet)
{
// Append here
}
// Otherwise it isn't set, so don't.
```
However, this isn't practical for a large (or even small) codebase. Is there a way to get rid of this manual checking? I've heard AOP or attributes may be able to solve this, but I haven't seen an example.
What methods could solve this problem? | The operation can be described as:
```
public interface ITextDecorator
{
string GetString(string input);
}
```
This encapsulates the *how* (Web.config, XML, etc.) and emphasizes the *what* (decorating a string).
Then, any class which might need to decorate text can take an instance of that interface:
```
public class Foo
{
private ITextDecorator _textDecorator;
public Foo(ITextDecorator textDecorator)
{
_textDecorator = textDecorator;
}
public void Bar(string text)
{
text = _textDecorator.GetString(text);
// ...
}
}
```
Example implementations of `ITextDecorator` might be:
```
public sealed class ExclamationPointTextDecorator : ITextDecorator
{
public string GetString(string input)
{
return input + "!";
}
}
public sealed class ConditionalTextDecorator : ITextDecorator
{
private Func<bool> _condition;
private ITextDecorator _innerTextDecorator;
public ConditionalTextDecorator(Func<bool> condition, ITextDecorator innerTextDecorator)
{
_condition = condition;
_innerTextDecorator = innerTextDecorator;
}
public string GetString(string input)
{
return _condition() ? _innerTextDecorator.GetString(input) : input;
}
}
```
An example usage of these classes might be:
```
var textDecorator = new ConditionalTextDecorator(
() => true, // Check Web.config, an XML file, or any other condition
new ExclamationPointTextDecorator());
var foo = new Foo(textDecorator);
foo.Bar("Test");
```
Notice the decoupling of the exclamation point appending from its conditional invocation. Both classes can now be reused independent of the other. This design style of fine-grained objects works best with an Inversion of Control (IoC) container. However, it is not required. | I probably wouldn't use AOP here... my question is: **when** are you doing this appending? I would simply hook into a utility method at that point - i.e.
```
WriteOutput(someValue); // presumably with some other args
```
where `WriteOutput` has the burden of checking this flag - i.e. it isn't in a *lot* of places. You might also find that C# 3.0 extension methods have a role to play; for example, if you are writing to a `TextWriter`:
```
public static void WriteWithMarker(this TextWriter writer, SomeType value) {
writer.Write(value);
if(ExclamationIsSet) writer.Write(SomeExtraStuff);
}
```
then your code just (always) calls `output.WriteWithMarker(value);` - job done.
I would probably also ensure I minimise impact by storing this value once at init - static constructors are quite handy for that:
```
public static class MyUtiltiyClass {
private static readonly bool exclamationIsSet;
public static bool ExclamationIsSet {get{return exclamationIsSet;}}
static MyUtiltiyClass() {
exclamationIsSet = FindWhetherTheFlagIsSet();
}
public static void WriteWithMarker(this TextWriter writer, SomeType value) {
writer.Write(value);
if(ExclamationIsSet) writer.Write(SomeExtraStuff);
}
//etc
}
```
Perhaps with more context on what and where you are currently doing this it might become clearer.... | Getting rid of the burden of checking for a setting's value every time an object is used | [
"",
"c#",
"aop",
""
] |
This seems like it should be simple:
I want a `list` like any other `list`, except it has a different `.__str__` method.
1. Trying to set `object.__str__ = foo` results in a read-only error
2. Trying to subclass `list` means you need some way to convert an existing `list` to an instance of the subclass. This requires either copying all attributes manually (a huge pain), or somehow copying them all automatically, which I don't know how to do.
3. Trying to write a wrapper around the `list` object means I have to figure out some way to send all messages to the wrapped object except `.__str__` which I handle with my own method. Don't know how to do this.
Any alternatives, or solutions #2 or #3 greatly appreciated. Thanks! | This solution works without a wrapper. And works if you join two lists by add. Any operation that modify the list itself will work as expected. Only functions that return a copy of the list like: sorted, reveresed will return the native python list which is fine. sort and reverse on the other hand operate on the list itself and will keep the type.
```
class myList(list):
def __new__(cls, data=None):
obj = super(myList, cls).__new__(cls, data)
return obj
def __str__(self):
return 'myList(%s)' % list(self)
def __add__(self, other):
return myList(list(self) + list(other))
>>> l = myList(range(5))
>>> print l
myList([0, 1, 2, 3, 4])
>>> print l + [1, 2]
myList([0, 1, 2, 3, 4, 1, 2])
>>> l.sort()
>>> print l
myList([0, 1, 2, 3, 4])
``` | If you would like to override `__str__` for other containers (e.g., `tuple`), you can take advantage of multiple inheritance:
```
class PrettyStr(object):
def __str__(self):
ret = ''
if isinstance(self, (list, tuple)):
ret = ''.join(str(elem) for elem in self)
else:
pass # handle other types here
return ret
class MyList(PrettyStr, list):
pass
class MyTuple(PrettyStr, tuple):
pass
if __name__ == "__main__":
print MyList([1, 2, 3, 4])
print MyTuple((1, 2, 3, 4))
``` | Replace __str__ method on list object in Python | [
"",
"python",
""
] |
I'm trying to create a set of classes where a common ancestor is responsible for all the logic involved in setting various properties, and the descendants just change the access of properties depending on whether they are required in the particular descendant.
When I try to do it as shown below I get a compiler error: *"cannot change access modifiers when overriding 'protected' inherited member"*
Is there a way to achieve what I'm trying to do? Thanks
```
public class Parent
{
private int _propertyOne;
private int _propertyTwo;
protected virtual int PropertyOne
{
get { return _propertyOne; }
set { _propertyOne = value; }
}
protected virtual int PropertyTwo
{
get { return _propertyTwo; }
set { _propertyTwo = value; }
}
}
public class ChildOne : Parent
{
public override int PropertyOne // Compiler Error CS0507
{
get { return base.PropertyOne; }
set { base.PropertyOne = value; }
}
// PropertyTwo is not available to users of ChildOne
}
public class ChildTwo : Parent
{
// PropertyOne is not available to users of ChildTwo
public override int PropertyTwo // Compiler Error CS0507
{
get { return base.PropertyTwo; }
set { base.PropertyTwo = value; }
}
}
``` | You can do this by using "new" instead of "override" to hide the parent's protected property as follows:
```
public class ChildOne : Parent
{
public new int PropertyOne // No Compiler Error
{
get { return base.PropertyOne; }
set { base.PropertyOne = value; }
}
// PropertyTwo is not available to users of ChildOne
}
public class ChildTwo : Parent
{
// PropertyOne is not available to users of ChildTwo
public new int PropertyTwo
{
get { return base.PropertyTwo; }
set { base.PropertyTwo = value; }
}
}
``` | You can't change the access, but you can re-declare the member with greater access:
```
public new int PropertyOne
{
get { return base.PropertyOne; }
set { base.PropertyOne = value; }
}
```
The problem is that this is a *different* `PropertyOne`, and inheritance / virtual might not work as expected. In the above case (where we just call `base.*`, and the new method isn't virtual) that is probably fine. If you need real polymorphism *above* this, then you can't do it (AFAIK) without introducing an intermediate class (since you can't `new` and `override` the same member in the same type):
```
public abstract class ChildOneAnnoying : Parent {
protected virtual int PropertyOneImpl {
get { return base.PropertyOne; }
set { base.PropertyOne = value; }
}
protected override int PropertyOne {
get { return PropertyOneImpl; }
set { PropertyOneImpl = value; }
}
}
public class ChildOne : ChildOneAnnoying {
public new int PropertyOne {
get { return PropertyOneImpl; }
set { PropertyOneImpl = value; }
}
}
```
The important point in the above is that there is still a single virtual member to override: `PropertyOneImpl`. | How to increase the access modifier of a property | [
"",
"c#",
"oop",
"polymorphism",
""
] |
I'm looking to write a portable filesystem scanner, capable of listing all files on a given directory path recursively.
To do this, I'm attempting to use cygwin for my compiler, making use of dirent.h and using the template:
```
#include <dirent.h>
#include <stdio.h>
int main(void)
{
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
// Stuff
}
closedir(d);
}
return(0);
}
```
But need to add recursive directory searching as well. To do this, my solution was to attempt to opendir() on the next file, and judge the error code to determine if it was successfully opened as a directory (which I would then recurse on) or if it was returned to be 'not a directory', which would then be listed as just a file.
I admit it feels very klugey, but I have been unable to find a better method that can retain some portability (not win32), even after hours of searching.
So my simplified solution (some psuedo for simplicity) is looking something like this:
```
int scan(string startdir)
{
DIR *d;
struct dirent *dir;
d = opendir(startdir.cstr());
if (d)
{
while ((dir = readdir(d)) != NULL)
{
if( NOT '.' AND NOT '..')
{
if(temp = opendir(startdir + d) == NULL)
{
//FILE OR ERROR
}else{
//Opened successfully as a directory, so recurse
scan(startdir + d->d_name + "\\");
}
}
}
closedir(d);
}
return(0);
}
```
This is just half rewritten psuedo code to keep it simple, but it seems to work (although I'm very open to suggestions on better ways to do this).
The major issue I'm having, however, is a particular link file 'c:\cygwin\dev\fd' which seems to be opening as a directory and recursively opening itself over and over infinitely.
The 'fd' file is 4KB, 106 bytes with no extension and is a shortcut that does not point anywhere in Windows.
This error seems to indicate that either this kludgey method is bugged, or there's a problem in the cygwin implementation that I'm compiling in.
As a short example:
```
Error Reading: c:\cygwin\dev\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\5\fd\0 No such file or directory
```
Excluding that directory, the search seems to work well. But I'm not alright with hard coding an exclusion in to the scanner.
If anyone has any ideas, suggestions, solutions, or alternative methods to this problem, your input would be appreciated.
Thanks. | The culprit seems to be that the fd file links into /proc/
I do not guarantee it to be true, but I am under the impression that this enables the scanner to recursively loop through its own directory structure.
My efforts with readlink() to address this issue were promising at first, but I'm finding that with deeper levels of scanning, it becomes unreliable and the errors can still occur.
I am now looking into other ways to achieve this functionality (ie boost::filesystem). | If you can use boost, consider using [boost::filesystem](http://www.boost.org/doc/libs/1_39_0/libs/filesystem/doc/index.htm). The tutorials include a simple ls program that you can easily extend to work recursively. The library also includes methods to query the types of files, which probably can solve your specific problem. | C++ Recursive File/Directory scanning using Cygwin | [
"",
"c++",
"recursion",
"filesystems",
"cygwin",
""
] |
I have the following question:
I need to pass a parameter (for example ID ) when I finish a form and the action save the form's values, this will forward to the result = "success" and I need that the action that will be call in the success come with the ID and other parameters to later use in the next form for save this information (info-form2 and info.form1)...
for example:
**FORM1 ( USER ) ==== "success" ====> FORM2 ( ADDRESS )**
*userForm.html ===================> addressForm.html?user\_id=X ...(where X : Id passed throw of UserAction (method:save) to AddressAction (method:newAddress))*
Please I will appreciate your help
Thanks in advance | You used the word "forward" but it sounds like you want to go to a new page (address.html) to collect more information about the address. If this is the case, you need to redirect to the address page after the user action completes.
```
<action name="user" class="UserAction">
<!-- Redirect to another namespace -->
<!-- for Struts 2.2 --> <result type="redirectAction">
<!-- for Struts 2.0 <result type="redirect-action"> -->
<param name="actionName">collect-address</param>
<param name="userId">${userId}</param>
</result>
</action>
```
The ${userId} syntax will call getUserId on your UserAction and pass that parameter as you showed in your question: addressForm.html?user\_id=X. collect-address can have a success result that goes to addressForm.html. [Docs here.](http://struts.apache.org/2.0.6/docs/redirect-action-result.html) If you want to avoid using another action, you can try [using the result type="redirect"](http://struts.apache.org/2.0.6/docs/redirect-result.html) and pass things through that way.
If you really want to forward, you can use [action chaining](http://struts.apache.org/2.0.6/docs/action-chaining.html). This is [discouraged by Ted Husted on the Struts2 team](http://www.mail-archive.com/user@struts.apache.org/msg53168.html) but it may work for you.
Instead of action chaining, try to bring all the code to complete this request into a single action and use helper or service classes for User and Address to separate and reuse the code instead of "action chaining". | Not very clear what you want to do.
Looks like after successfull execution of an action, the request gets forwarded to another action. In the first action you want to pass parameter ID and use that in the 2nd action. Since both the actions are getting used in the same request call you can save the ID parameter in request like this
request.setAttribute("ID", iDValueObject);
In the second action you can extract the value of ID like this
request.getAttribute("ID"); | Struts 2: parameters between Actions | [
"",
"java",
"jakarta-ee",
"parameters",
"struts2",
"struts-action",
""
] |
What's the difference - performance-wise - between reading from a socket 1 byte a time vs reading in large chunk?
I have a C++ application that needs to pull pages from a web server and parse the received page line by line. Currently, I'm reading 1 byte at a time until I encounter a CRLF or the max of 1024 bytes is reached.
If reading in large chunk(e.g. 1024 bytes at a time) is a lot better performance-wise, any idea on how to achieve the same behavior I currently have (i.e. being able to store and process 1 html line at a time - until the CRLF without consuming the succeeding bytes yet)?
EDIT:
I can't afford too big buffers. I'm in a very tight code budget as the application is used in an embedded device. I prefer keeping only one fixed-size buffer, preferrably to hold one html line at a time. This makes my parsing and other processing easy as I am by anytime I try to access the buffer for parsing, I can assume that I'm processing one complete html line.
Thanks. | If you are reading directly from the socket, and not from an intermediate higher-level representation that can be buffered, then without any possible doubt, it is just better to read completely the 1024 bytes, put them in RAM in a buffer, and then parse the data from the RAM.
Why? Reading on a socket is a system call, and it causes a context switch on each read, which is expensive. Read more about it: [IBM Tech Lib: Boost socket performances](http://www.ibm.com/developerworks/linux/library/l-hisock.html#N100AF) | I can't comment on C++, but from other platforms - yes, this can make a *big* difference; particularly in the amount of switches the code needs to do, and the number of times it needs to worry about the async nature of streams etc.
But the real test is, of course, to profile it. Why not write a basic app that churns through an arbitrary file using both approaches, and test it for some typical files... the effect is usually startling, **if** the code is IO bound. If the files are small and most of your app runtime is spent *processing* the data once it is in memory, you aren't likely to notice any difference. | Reading from a socket 1 byte a time vs reading in large chunk | [
"",
"c++",
"c",
"sockets",
"cgi",
""
] |
Ideally, I only need a simple `SSLSocketChannel`.
I already have a component that reads and writes message over ordinary `SocketChannel`, but for some of these connections, I have to use SSL over the wire; the operations over these connections, however, are the same.
Does anyone knows a free `SSLSocketChannel` implementation (with the appropriate selector) or something similar? I've found [this](http://docs.norther.org/api/tammi/org/norther/tammi/acorn/nio/SSLSocketChannel.html), but the selector doesn't accept it since its vendor isn't SUN.
I'm decoupling the reading\_from/writing\_to net logic from the insertion and retrieval of network data via a simple object, in order to use a `SSLEngine` without getting mad, but it's really tricky to implement that correctly, given the fact that I don't know the internals of SSL protocol... | Check out Restlet's implementation it may do what you need, and it's all about NIO.
[Restlet Engine Javadoc](http://www.restlet.org/documentation/1.2/engine/)
Specifically the HttpClientCall. SetProtocol(HTTPS) - getResponseEntityChannel returns a ReadableByteChannel (getEntityChannel returns a WriteableByteChannel) | Jetty has an NIO SSL implementation for their server: [SslSelectorChannelConnector](http://www.mortbay.org/jetty/jetty-6/xref/org/mortbay/jetty/security/SslSelectChannelConnector.html). You might want to peek at it for details on what its doing.
There is also an old (but decent) article from [O'Reilly](http://www.onjava.com/pub/a/onjava/2004/11/03/ssl-nio.html?page=last&x-order=date) that explains the details about NIO + SSL along with example code. | SSL and SocketChannel | [
"",
"java",
"ssl",
"nio",
"socketchannel",
"sslengine",
""
] |
I want to retrieve an image from SQL Server to show it in an ASP.NET app. I think that I can write down the image retrieved from SQL Server to a server's folder and show it throw its path. Is there any other better way?
I have the same problem with audio and video files (can I use silverlight to play these audio and video files?)
My worry is that I don't want to store these files (images, audios and videos) on server to show it. | You can write a custom HTTP handler that will take ID of the item you are trying to display on the query string parameter.
This handler will then retrieve the data from SQL Server, and return it just like downloading a file. This [post](http://www.clariusconsulting.net/blogs/kzu/archive/2003/08/27/74.aspx) has the steps.
I am not sure about the capability of Silverlight streaming from a "file", you may need to use [Silverlight Streaming Service](http://silverlight.live.com/). | Is there a better way? IMHO, yes there is. Store your image file as a file. That's what the filesystem is for, and you don't get involved in fudging around with the database.
I have, in the past, used MySQL to store images and retrieved them with PHP, but that solution got really old really quickly from a maintenance point of view. It comes down to the fact that you are always going to have to store the data in some way, and the most efficient way is also the simplest.
If you *must* store it in the database, I'd use a generic accessor page (e.g. myImage.aspx) which queries the database and streams the returned blob directly to the browser. Your img tag would probably then need to look like
```
<img src="/img/myImage.aspx?imgId=123456" <other tag data> />
``` | Retrieve an image from SQL Server to show it in an ASP.NET app | [
"",
"c#",
"asp.net",
"silverlight-2.0",
""
] |
Hi guys I ran the analyser on <http://www.websiteoptimization.com/services/analyze/> and I got a number of issues the most prominent are the ones below:
---
*TOTAL\_OBJECTS - Warning! The total number of objects on this page is 93 which by their number will dominate web page delay. Consider reducing this to a more reasonable number. Above 20 objects per page the overhead from dealing with the actual objects (description time and wait time) accounts for more than 80% of whole page latency. See Figure II-3: Relative distribution of latency components showing that object overhead dominates web page latency in Website Optimization Secrets for more details on how object overhead dominates web page latency. Combine, refine, and optimize your external objects. Replace graphic rollovers with CSS rollovers to speed display and minimize HTTP requests. Consider using CSS sprites to help consolidate decorative images. Using CSS techniques such as colored backgrounds, borders, or spacing instead of graphic techniques can reduce HTTP requests. Replace graphic text headers with CSS text headers to further reduce HTTP requests. Finally, consider optimizing parallel downloads by using different hostnames or a CDN to reduce object overhead.*
*TOTAL\_IMAGES - Warning! The total number of images on this page is 85 , consider reducing this to a more reasonable number. Recommend combining, replacing, and optimizing your graphics. Replace graphic rollover menus with CSS rollover menus to speed display and minimize HTTP requests. Consider using CSS sprites to help consolidate decorative images. Use CSS techniques such as colored backgrounds, borders, or spacing instead of graphic techniques to reduce HTTP requests. Replace graphic text headers with CSS text headers to further reduce HTTP requests. Finally, consider optimizing parallel downloads by using different hostnames to reduce object overhead.*
---
The issue is that 85 images mentioned are all referenced in my css file - I'm not sure how but I would like to bring this number down - however I do require all these files at some point in my website.
Any ideas to optimize this even further.
Plus my javascript file is a whopping 150K even after maximum compression - I've run out of ideas to reduce overheads and could sue some tips. | You can use [CSS Sprites](http://www.smashingmagazine.com/2009/04/27/the-mystery-of-css-sprites-techniques-tools-and-tutorials/) for images (eg menu rollovers or icons). This is beneficial for two reasons:
* Spriting images common to multiple pages allows the browser to cache the sprite image, and therefore reduces subsequent downloads on other pages of your site.
* Spriting images reduces server load by reducing the number of requests sent to and received by the server, since many images can be combined into one larger image.
You said that your JavaScript is compressed to the maximum - however, is all of it needed by your page? Or can it be split between several pages? Also, are there bits in your script that are unnecessary or that can be cut down, for example by using wrapper functions for tasks that you commonly perform in your scripts. A simple example of this would be using the Prototype-esque `$` function in place of `document.getElementById`, which if called many times can reduce the size of your JavaScript quite significantly.
Also, as the report suggests, use styled text instead of images representing styled text if and where you can (of course this is not applicable in all instances). | Also look at what your images are. A common thing I see is different background-images for navigation - one image says 'Home', another says 'About us', ect.
You can combine those into one blank background-image and write the text on top. | Check this web optimization report - how can I fix it? | [
"",
"javascript",
"css",
"optimization",
"image",
""
] |
I am using my own extension methods of IQueryable<> to create chainable queries such as FindAll().FindInZip(12345).NameStartsWith("XYZ").OrderByHowIWantIt() etc. which then on deferred execution creates a single query based on my extension methods chain.
The problem with this though, is that all Where's in the extension chain (FindXYZ, FindInZip etc.) will always combine as AND which means I can't do something like this:
FindAll().FirstNameStartsWith("X").OrLastNameStartsWith("Z") because I don't know how I can inject the OR in a separate Where method.
Any idea how I can solve this?
---
additional;
So far I understand how to chain expressions as Or if I wrap them (e.g. CompileAsOr(FirstNameStartsWith("A").LastNameStartsWith("Z").OrderBy(..))
What I'm trying to do though is slightly more complicated (and PredicateBuilder doesn't help here..) in that I want a later IQueryable to basically access the Where conditions that were established prior without having to wrap them to create the Or between them.
As each extension method returns IQueryable<> I understand that it should have the knowledge about the current status of query conditions somewhere, which leads me to believe that there should be some automated way or creating an Or across all prior Where conditions without having to wrap what you want Or'd. | I'm assuming the different parts of the query are only known at runtime, i.e. you can't just use `||` in a `where`...
One lazy option is `Concat` - but this tends to lead to poor TSQL etc; however, I tend to be inclined to write custom `Expression`s instead. The approach to take depends on what the provider is, as LINQ-to-SQL supports different options to EF (for example) - which has a genuine impact here (since you can't use sub-expressions with EF). Can you tell us which?
---
Here's some code that should work with LINQ-to-SQL; if you build an array (or list, and call `.ToArray()`) of expressions, it should work fine; example is LINQ-to-Objects, but should still work:
```
static void Main()
{
var data = (new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).AsQueryable();
var predicates = new List<Expression<Func<int, bool>>>();
predicates.Add(i => i % 3 == 0);
predicates.Add(i => i >= 8);
foreach (var item in data.WhereAny(predicates.ToArray()))
{
Console.WriteLine(item);
}
}
public static IQueryable<T> WhereAny<T>(
this IQueryable<T> source,
params Expression<Func<T,bool>>[] predicates)
{
if (source == null) throw new ArgumentNullException("source");
if (predicates == null) throw new ArgumentNullException("predicates");
if (predicates.Length == 0) return source.Where(x => false); // no matches!
if (predicates.Length == 1) return source.Where(predicates[0]); // simple
var param = Expression.Parameter(typeof(T), "x");
Expression body = Expression.Invoke(predicates[0], param);
for (int i = 1; i < predicates.Length; i++)
{
body = Expression.OrElse(body, Expression.Invoke(predicates[i], param));
}
var lambda = Expression.Lambda<Func<T, bool>>(body, param);
return source.Where(lambda);
}
``` | Use [`PredicateBuilder<T>`](http://www.albahari.com/nutshell/predicatebuilder.aspx). It's probably what you want. | Extend IQueryable<T> Where() as OR instead of AND relationship | [
"",
"c#",
"iqueryable",
""
] |
Does anybody have a good function for validating email addresses by SMTP in PHP?
Also, is it worth it? Will it slow down my server?
--> EDIT: I am referring to something like this:
<http://onwebdevelopment.blogspot.com/2008/08/php-email-address-validation-through.html>
which is meant to complement validation of the syntax of the email address.
It looks complicated though, and I was hoping there was a simpler way of doing this. | If you want to check if there is a mail exchanger at the domain, you can use something like this:
```
/*checks if email is well formed and optionally the existence of a MX at that domain*/
function checkEmail($email, $domainCheck = false)
{
if (preg_match('/^[a-zA-Z0-9\._-]+\@(\[?)[a-zA-Z0-9\-\.]+'.
'\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/', $email)) {
if ($domainCheck && function_exists('checkdnsrr')) {
list (, $domain) = explode('@', $email);
if (checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A')) {
return true;
}
return false;
}
return true;
}
return false;
}
```
Usage:
```
$validated = checkEmail('foo@gmail.com', true);
``` | Here is what I believe you are looking for. It does a validation with the SMTP server. It shows PHP code. <http://www.webdigi.co.uk/blog/2009/how-to-check-if-an-email-address-exists-without-sending-an-email/>. | Simple SMTP email validation function for php? Also, is it worth it? | [
"",
"php",
"email",
""
] |
I'm creating a function which can accept a string which is either retrieved through `file_get_contents()` on a local text file, or something fetched from a url such as `http://site.com/338383.txt`.
The file will be a tab seperated file, with each item in the file being on its own line. Is it better to use `\n` or `\r` to `explode()` the string and get an array of each line?
I've noticed that in some cases `\n` doesn't work. I'd like a consistent way which works all the time. Any thoughts? | You can use [file()](http://uk.php.net/manual/en/function.file.php) to get the contents of the file as array with individual lines. | As [duckyflip](https://stackoverflow.com/users/7370/duckyflip) points out, you can use the [file()](http://uk.php.net/manual/en/function.file.php) function to get an array of file lines. However, if you still need to explode (for an unknown reason), you should use the PHP constant `PHP_EOL` instead of '\n' as this is cross-platform compliant. | Should I use \r or \n for explode()ing the contents of a file in PHP? | [
"",
"php",
"string",
"explode",
""
] |
I happen to use this kind of structure quite a lot:
```
Dictionary<string, List<string>> Foo = new Dictionary<string, List<string>>();
```
Which leads to this kind of code :
```
foreach (DataRow dr in ds.Tables[0].Rows)
{
List<string> bar;
if (!Foo.TryGetValue(dr["Key"].ToString(), out desks))
{
bar= new List<string>();
Foo.Add(dr["Key"].ToString(), bar);
}
bar.Add(dr["Value"].ToString());
}
```
Do you think it's worth writing a custom DictionaryOfList class which would handle this kind of things automatically?
Is there another way to lazily initialize those Lists? | You can write an extension method - GetValueOrCreateDefault() or something like that:
```
foreach (DataRow dr in ds.Tables[0].Rows)
{
Foo.GetValueOrCreateDefault( dr["Key"] ).Add( dr["Value"].ToString() )
}
```
Maybe you can even write an extension method for the whole initialisation? | A dictionary of a list... in .NET 3.5 that would be an `ILookup<TKey,TValue>`. The default implementation (`Lookup<TKey,TValue>`) is immutable, but I wrote an `EditableLookup<TKey,TValue>` for [MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/). This will be a lot simpler to use - i.e.
```
var data = new EditableLookup<string, int>();
data.Add("abc",123);
data.Add("def",456);
data.Add("abc",789);
foreach(int i in data["abc"]) {
Console.WriteLine(i); // 123 & 789
}
```
Other than that, an extension method:
```
public static void Add<TKey, TList, TValue>(
this IDictionary<TKey, TList> lookup,
TKey key, TValue value)
where TList : class, ICollection<TValue>, new()
{
TList list;
if (!lookup.TryGetValue(key, out list))
{
lookup.Add(key, list = new TList());
}
list.Add(value);
}
static void Main() {
var data = new Dictionary<string, List<string>>();
data.Add("abc", "def");
}
``` | How can I ease the pain of initializing dictionaries of Lists in C#? | [
"",
"c#",
".net",
".net-3.5",
"collections",
""
] |
I have a method that creates a new node in a tree - either left or right. If the value is lower than my current value it is inserted on the left, otherwise on the right side.
I want to refactor this code, so that I first see on which side I have to insert my element, and then insert it. Before I implemented this twice: Once for the left side and once for the right side.
It currently looks like this:
```
def neu(self, sortByValue, secondValue):
child = self.left if(sortByValue.lower() < self.value[0].lower()) else self.right
if(child == None):
child = MyTree(sortByValue,secondValue)
else: child.neu(sortByValue,secondValue)
```
My problem is, though, that self.left is None, and self.right is None. So when I create child as a variable and set it to MyTree(...), self.left and self.right are not receiving the value.
Is there anything I can do to improve this? Thanks! | In Python variables are names not locations. For example:
```
>>> a = 1
>>> b = a
>>> a = 2
>>> print b
1
```
In your code you're simply rebinding the name `child` to a different value (your new node) and that has no affect on the previously bound value (None).
Here's a reworking of your code that should do what you want (untested):
```
def neu(self, sortByValue, secondValue):
def child(node):
if(node is None):
return MyTree(sortByValue, secondValue)
else:
child.neu(sortByValue, secondValue)
return node
if(sortByValue.lower() < self.value[0].lower()):
self.left = child(self.left)
else:
self.right = child(self.right)
``` | Hallo ;-)
`self.left` or `self.right` don't receive the value because you assign to `child` which just holds a copy of the destination value and no reference to it.
You want to have a pointer- This doesn't exist directly in Python.
You could express this using a class wrapper, but I think it's more comprehensible when you just write both possibilities in the if clause. | Pointers in Python on variables with None value | [
"",
"python",
"reference",
""
] |
I have a small Win32 console application which is essentially a test harness. I read data in, do some processing on it and currently just output some of the numbers to the console. This isn't a huge problem - I can get an idea of what the data looks like, but it would be much easier to analyse if there was a way of getting that information into a graph for each run of the software.
I've been getting to grips with GNUPlot recently, but can't work out a simple way to get the data sent to it. Has anyone tried this? ..or is there another graphing application I should try?
Excel and OO Calc are great tools and I've loaded .csv data into them for graphing data plenty of times myself. I was, however, hoping for a way to dynamically pipe data into a graphing application to avoid having to close/reopen excel and plot a graph each time I want to look at some data.
I think you can pipe data into GNUPlot (which is why I mentioned it) but the details of how to do so are rather scant. | You don't really need to touch VBA to do this
In Excel you can set up a Data Connection to a file, it supports many files type but CSV does work fine.
* Go to List item
* Data Tab
* Click Connections
* Click Add
* select the file
* go to the connection properties - un-tick prompt for file name
* set the required period.
* close the connections dialog
* select the start cell for importing the data - cell 1a on worksheet 2
* click existing connections
* select you data connection
* flip to worksheet1 add your chart and hookup the data.
the chart will now update automatically
this is Excel 2007 - but think older version had this and I think OO can do it to. | A simple approach is to wtite the data out as CSV and then import it into a spreadsheet like Excel or OpenOffice to do the graph drawing.
**Edit:** Following your question, I got interested in GNUPlot myself - this is the simplest description of using it from the command line that I found: <http://www.goldb.org/goldblog/CommentView,guid,f378e279-eaa5-4d85-b7d2-0339a7c72864.aspx> | How do I plot the output from a C++ Win32 console app? | [
"",
"c++",
"winapi",
"plot",
"charts",
""
] |
For recreational reasons I wrote a PHP class that classifies files with tags instead of in a hierarchical way, the tags are stored in the filename itself in the form of +tag1+tag2+tagN+MD5.EXTENSION and thus I'm stucked with the chars limit (255) imposed by the FS/OS. Here is the class:
```
<?php
class TagFS
{
public $FS = null;
function __construct($FS)
{
if (is_dir($FS) === true)
{
$this->FS = $this->Path($FS);
}
}
function Add($path, $tag)
{
if (is_dir($path) === true)
{
$files = array_slice(scandir($path), 2);
foreach ($files as $file)
{
$this->Add($this->Path($path) . $file, $tag);
}
return true;
}
else if (is_file($path) === true)
{
$file = md5_file($path);
if (is_file($this->FS . $file) === false)
{
if (copy($path, $this->FS . $file) === false)
{
return false;
}
}
return $this->Link($this->FS . $file, $this->FS . '+' . $this->Tag($tag) . '+' . $file . '.' . strtolower(pathinfo($path, PATHINFO_EXTENSION)));
}
return false;
}
function Get($tag)
{
return glob($this->FS . '*+' . str_replace('+', '{+,+*+}', $this->Tag($tag)) . '+*', GLOB_BRACE);
}
function Link($source, $destination)
{
if (is_file($source) === true)
{
if (function_exists('link') === true)
{
return link($source, $destination);
}
if (is_file($destination) === false)
{
exec('fsutil hardlink create "' . $destination . '" "' . $source . '"');
if (is_file($destination) === true)
{
return true;
}
}
}
return false;
}
function Path($path)
{
if (file_exists($path) === true)
{
$path = str_replace('\\', '/', realpath($path));
if ((is_dir($path) === true) && ($path[strlen($path) - 1] != '/'))
{
$path .= '/';
}
return $path;
}
return false;
}
function Tag($string)
{
/*
TODO:
Remove (on Windows): . \ / : * ? " < > |
Remove (on *nix): . /
Remove (on TagFS): + * { }
Remove (on TagFS - Possibly!) -
Max Chars (in Windows) 255
Max Char (in *nix) 255
*/
$result = array_filter(array_unique(explode(' ', $string)));
if (empty($result) === false)
{
if (natcasesort($result) === true)
{
return strtolower(implode('+', $result));
}
}
return false;
}
}
?>
```
I believe this system works well for a couple of small tags, but my problem is when the size of the whole filename exceeds 255 chars. What approach should I take in order to bypass the filename limit? I'm thinking in splitting tags on several hard links of the same file, but the permutations may kill the system.
Are there any other ways to solve this problem?
**EDIT - Some usage examples:**
```
<?php
$images = new TagFS('S:');
$images->Add('P:/xampplite/htdocs/tag/geoaki.png', 'geoaki logo');
$images->Add('P:/xampplite/htdocs/tag/cloud.jpg', 'geoaki cloud tag');
$images->Add('P:/xampplite/htdocs/tag/cloud.jpg', 'nuvem azul branco');
$images->Add('P:/xampplite/htdocs/tag/xml-full.gif', 'geoaki auto vin api service xml');
$images->Add('P:/xampplite/htdocs/tag/dunp3d-1.jpg', 'dunp logo');
$images->Add('P:/xampplite/htdocs/tag/d-proposta-04c.jpg', 'dunp logo');
/*
[0] => S:/+api+auto+geoaki+service+vin+xml+29be189cbc98fcb36a44d77acad13e18.gif
[1] => S:/+azul+branco+nuvem+4151ae7900f33788d0bba5fc6c29bee3.jpg
[2] => S:/+cloud+geoaki+tag+4151ae7900f33788d0bba5fc6c29bee3.jpg
[3] => S:/+dunp+logo+0cedeb6f66cbfc3974c6b7ad86f4fbd3.jpg
[4] => S:/+dunp+logo+8b9fcb119246bb6dcac1906ef964d565.jpg
[5] => S:/+geoaki+logo+5f5174c498ffbfd9ae49975ddfa2f6eb.png
*/
echo '<pre>';
print_r($images->Get('*'));
echo '</pre>';
/*
[0] => S:/+azul+branco+nuvem+4151ae7900f33788d0bba5fc6c29bee3.jpg
*/
echo '<pre>';
print_r($images->Get('azul nuvem'));
echo '</pre>';
/*
[0] => S:/+dunp+logo+0cedeb6f66cbfc3974c6b7ad86f4fbd3.jpg
[1] => S:/+dunp+logo+8b9fcb119246bb6dcac1906ef964d565.jpg
[2] => S:/+geoaki+logo+5f5174c498ffbfd9ae49975ddfa2f6eb.png
*/
echo '<pre>';
print_r($images->Get('logo'));
echo '</pre>';
/*
[0] => S:/+dunp+logo+0cedeb6f66cbfc3974c6b7ad86f4fbd3.jpg
[1] => S:/+dunp+logo+8b9fcb119246bb6dcac1906ef964d565.jpg
*/
echo '<pre>';
print_r($images->Get('logo dunp'));
echo '</pre>';
/*
[0] => S:/+geoaki+logo+5f5174c498ffbfd9ae49975ddfa2f6eb.png
*/
echo '<pre>';
print_r($images->Get('geo* logo'));
echo '</pre>';
?>
```
**EDIT: Due to the several suggestions to use a serverless database or any other type of lookup table (XML, flat, key/value pairs, etc) I want to clarify the following: although this code is written in PHP, the idea is to port it to Python and make a desktop application out of it - this has noting to do (besides the example of course) with PHP. Furthermore, *if I have to* use some kind of lookup table I'll definitely go with SQLite 3, but what I'm looking for is a solution that doesn't involves any other additional "technology" besides the filesystem (folders, files and hardlinks).**
**You may call me nuts but I'm trying to accomplish two simple goals here: 1) keep the system "garbage" free (who likes Thumbs.db or DS\_STORE for example?) and 2) keep the files easily identifiable if for some reason the lookup table (in this case SQLite) gets busy, corrupt, lost or forgot (in backups for instance).**
**PS: This is supposed to run on both Linux, Mac, and Windows (under NTFS).** | If you have use of hard/soft links than you might look into giving each tag it's own directory having a link for each file with that "tag." Then when you are given multiple tags you can compare those found in both. Then the files could be stored in a single folder and having them unique in name of course.
I don't know how this would be different from having a meta file named by the tag, then listing all files that exist in that tag. | I would insert that information into a database, even if it's a lightweight one, like an sqlite file in the same directory.
If you don't want to do that, you could create hard links to the file without any permutations. One file per tag. Tagging P:/xampplite/htdocs/tag/geoaki.png with geoaki and logo would result in two files both being hard links pointing to the same data as the original file:
* P:/xampplite/htdocs/tag/geoaki.png.geoaki)
* P:/xampplite/htdocs/tag/geoaki.png.logo)
This has the advantage that you can select all tags belonging to that file with [`glob()`](http://de.php.net/manual/en/function.glob.php) for example.
```
# All tags
$tags = array();
files = glob('P:/xampplite/htdocs/tag/geoaki.png.*')
foreach ($files as $file) {
if (fileinode($file) === fileinode('P:/xampplite/htdocs/tag/geoaki.png')) {
$tags[] = substr($file, strlen('P:/xampplite/htdocs/tag/geoaki.png.'));
}
}
# Check if file has tag foo:
file_exists('P:/xampplite/htdocs/tag/geoaki.png.foo')
&& fileinode(P:/xampplite/htdocs/tag/geoaki.png.foo) === fileinode('P:/xampplite/htdocs/tag/geoaki.png');
```
One more thing: Relying on md5 hashes alone for identifying files is not safe, you're better off using the file name as the identifier, which is guaranteed to be unique within the folder. Negative effects of md5 as identifier are:
* The system breaks, as soon as a file is changed
* There are collisions in md5, two distinct files could have the same md5 hash (the probability is small, but existent) | Problem on Tag "Filesystem" | [
"",
"php",
"language-agnostic",
"file",
"operating-system",
"filesystems",
""
] |
What's the best way to parse messages received from an IRC server with Python according to the RFC? I simply want some kind of list/whatever, for example:
```
:test!~test@test.com PRIVMSG #channel :Hi!
```
becomes this:
```
{ "sender" : "test!~test@test.com", "target" : "#channel", "message" : "Hi!" }
```
And so on?
(Edit: I want to parse IRC messages in **general**, not just PRIVMSG's) | Look at Twisted's implementation <http://twistedmatrix.com/>
Unfortunately I'm out of time, maybe someone else can paste it here for you.
### Edit
Well I'm back, and strangely no one has pasted it yet so here it is:
<http://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/irc.py#54>
```
def parsemsg(s):
"""Breaks a message from an IRC server into its prefix, command, and arguments.
"""
prefix = ''
trailing = []
if not s:
raise IRCBadMessage("Empty line.")
if s[0] == ':':
prefix, s = s[1:].split(' ', 1)
if s.find(' :') != -1:
s, trailing = s.split(' :', 1)
args = s.split()
args.append(trailing)
else:
args = s.split()
command = args.pop(0)
return prefix, command, args
parsemsg(":test!~test@test.com PRIVMSG #channel :Hi!")
# ('test!~test@test.com', 'PRIVMSG', ['#channel', 'Hi!'])
```
This function closely follows the EBNF described in the IRC RFC. | You can do it with a simple list comprehension if the format is always like this.
```
keys = ['sender', 'type', 'target', 'message']
s = ":test!~test@test.com PRIVMSG #channel :Hi!"
dict((key, value.lstrip(':')) for key, value in zip(keys, s.split()))
```
Result:
```
{'message': 'Hi!', 'type': 'PRIVMSG', 'sender': 'test!~test@test.com', 'target': '#channel'}
``` | Python & parsing IRC messages | [
"",
"python",
"parsing",
"irc",
""
] |
```
class ApplicationContext{
private final NetworkObject networkObject = new networkObject();
public ApplicationContext(){
networkObject.setHost("host");
networkObject.setParams("param");
}
public searchObjects(ObjectType objType){
networkObject.doSearch(buildQuery(objType));
}
}
class NetworkObject{
private final SearchObject searchObject = new SearchObject();
public doSearch(SearchQuery searchQuery){
searchObject.search(searchQuery); //threadsafe, takes 15(s) to return
}
}
```
Consider a webserver running a web application which creates only one ApplicationContext instance (singleton) and uses the same applicationInstance to call searchObjects e.g.
```
ApplicationContext appInstance =
ApplicationContextFactory.Instance(); //singleton
```
Every new request to a webpage say 'search.jsp' makes a call
```
appInstance.searchObjects(objectType);
```
I am making 1000 requests to 'search.jsp' page. All the threads are using the same ApplicationContext instance, and searchObject.search() method takes 15 seconds to return. My Question is Do all other threads wait for their turn (15 sec) to execute when one is already executing the searchObject.search() function or All threads will execute searchObject.search() concurrently, Why??
I hope I have made my question very clear??
**Update:**
Thanks all for clarifying my doubt. Here is my second Question, what difference in performance should be observe when I do:
```
public synchronized doSearch(SearchQuery searchQuery){
searchObject.search(searchQuery); //threadsafe, takes 15(s) to return
}
```
**OR**
```
public doSearch(SearchQuery searchQuery){
searchObject.search(searchQuery); //threadsafe, takes 15(s) to return
}
```
I believe using the function 'doSearch' without synchronized keyword should be giving more performance. But, when I tested it today, the results came out the other way. The performance was similar or sometimes better when I use synchronized keyword.
Can anyone explain the behavior. How should I debug such cases.
Regards,
Perry | Well you haven't *specified* any synchronization in the code, so without any other evidence I'd suspect that all the threads will run concurrently. If `SearchObject.search` contains some synchronization though, that would obvious limit the concurrency.
Mind you, your JSP container is probably using a thread pool to service the 1000 requests, rather than creating 1000 threads.
EDIT: As for why it may be faster with `synchronized`: sometimes concurrency isn't actually helpful to throughput. Things like context switching, disk bottlenecks, cache misses etc have that effect. It's *usually* not a good idea to have more running threads than cores.
For a real-life example, suppose you have a thousand shoppers who all want to buy things from a fairly small shop. How would you go about it? Put all 1000 in the shop at the same time, or keep it down to a fairly small number in the shop at any one time, and a queue outside? | It is wise to realise that performance is with respect to a given environment. In this case, it probably is the performance of the software on your laptop or test server. It is wise to check performance on something similar to a production environment before even considering to optimize the code because the bottleneck there could be quite different than on the development machine.
As an example; when I test my software with a large database on my laptop I always end up being harddisk-IO bound. In production however the database server has plenty memory and speedy disks so it would not be wise to optimise my software for IO.
Similar with threading; the processor in my laptop can run one or two processes simultaneously. Having 8 threads does not speed things up. The production machine however might very well be able to handle 8 threads simultaneously.
What I think is more important than performance is semantics. Using a keyword like synchronous is not only instructive to the compiler, but also to the (next) developer.
By using synchronous you share a lock with all other synchronous methods on ApplicationContext, also the methods which might have nothing to do with searchObject.
Personally I doubt very much you wish to synchronize on an object called ApplicationContext.
If searchObject were not thread safe I would probably recommend a locking object. This comes in to flavors:
```
public void doSearch(SearchQuery searchQuery){
synchronized(searchObject) {// Only if searchObject is guaranteed to be null
searchObject.search(searchQuery); //threadsafe, takes 15(s) to return
}
}
```
or
```
public class ApplicationContext {
private SearchObject searchObject = null;
private final Object searchObjectLock = new Object();
public void doSearch(SearchQuery searchQuery){
synchronized(searchObjectLock) {
searchObject.search(searchQuery); //threadsafe, takes 15(s) to return
}
}
}
```
Don't forget to lock every use of searchObject to prevent threading trouble. Using this fine-grained locking mechanism you can at least keep the ApplicationContext available to classes which do not need searchObject related functionality.
In your case I would not use any synchronisation as it is not required, and check on production-like hardware before determining bottlenecks.
And if searchObject uses a database make sure the database is property indexed and uses that index. If it needs to do 1000 full table scans it won't be fast anyhow... | Why don't multiple threads seem to speed up my web application? | [
"",
"java",
"performance",
"multithreading",
""
] |
At the moment, the only fully supported language, and the de-facto standard for DOM tree manipulation in the browser is JavaScript. It looks like it has deep design issues that make it a minefield of bugs and security holes for the novice.
Do you know of any existent or planned initiative to introduce a better (redesigned) language of any kind (not only javascript) for DOM tree manipulation and HTTP requests in next generation browsers? If yes, what is the roadmap for its integration into, say, Firefox, and if no, for what reasons (apart of interoperability) should be JavaScript the only supported language on the browser platform?
I already used jQuery and I also read "javascript: the good parts". Indeed the suggestions are good, but what I am not able to understand is: why only javascript? On the server-side (your-favourite-os platform), we can manipulate a DOM tree with every language, even fortran. Why does the client side (the browser platform) support only javascript? | The problem with javascript is not the language itself - it's a perfectly good prototyped and dynamic language. If you come from an OO background there's a bit of a learning curve, but it's not the language's fault.
Most people assume that Javascript is like Java because it has similar syntax and a similar name, but actually it's a lot more like lisp. It's actually pretty well suited to DOM manipulation.
The real problem is that it's compiled by the browser, and that means it works in a very different way depending on the client.
Not only is the actual DOM different depending on the browser, but there's a massive difference in performance and layout.
---
*Edit following clarification in question*
Suppose multiple interpreted languages were supported - you still have the same problems. The various browsers would still be buggy and have different DOMs.
In addition you would have to have an interpreter built into the browser or somehow installed as a plug in (that you could check for before you served up the page) for each language. It took ages to get Javascript consistent.
You can't use compiled languages in the same way - then you're introducing an executable that can't easily be scrutinised for what it does. Lots of users would choose not to let it run.
OK, so what about some sort of sandbox for the compiled code? Sounds like Java Applets to me. Or ActionScript in Flash. Or C# in Silverlight.
What about some kind of IL standard? That has more potential. Develop in whatever language you want and then compile it to IL, which the browser then JITs.
Except, Javascript is kind of already that IL - just look at [GWT](http://code.google.com/webtoolkit/). It lets you write programs in Java, but distribute them as HTML and JS.
---
*Edit following further clarification in question*
Javascript isn't, or rather wasn't, the only language supported by browsers: back in the Internet Explorer dark ages you could choose between Javascript or VBScript to run in IE. Technically IE didn't even run Javascript - it ran [JScript](https://en.wikipedia.org/wiki/JScript) (mainly to avoid having to pay Sun for the word *java*, Oracle still own the name *Javascript*).
The problem was that VBScript was proprietary to Microsoft, but also that it just wasn't very good. While Javascript was adding functionality and getting top rate debugging tools in other browsers (like FireBug) VBScript remained IE-only and pretty much un-debuggable (dev tools in IE4/5/6 were none existent). Meanwhile VBScript also expanded to become a pretty powerful scripting tool in the OS, but none of those features were available in the browser (and when they were they became massive security holes).
There are still some corporate internal applications out there that use VBScript (and some rely on those security holes), and they're still running IE7 (they only stopped IE6 because MS finally killed it off).
Getting Javascript to it's current state has been a nightmare and has taken 20 years. It still doesn't have consistent support, with language features (specified in 1999) still missing from some browsers and lots of shims being required.
Adding an alternate language for interpreting in browsers faces two major problems:
* Getting all the browser vendors to implement the new language standard - something they still haven't managed for Javascript in 20 years.
* A second language potentially dilutes the support you already have, allowing (for instance) IE to have second rate Javascript support but great VBScript (again). I really don't want to be writing code in different languages for different browsers.
It should be noted that Javascript isn't 'finished' - it's still evolving to become better in new browsers. The [latest version](http://www.ecma-international.org/news/Publication%20of%20ECMA-262%206th%20edition.htm) is years ahead of of the browsers' implementations and they're working on the next one. | # Compile to Javascript
For now, using a language which compiles to Javascript seems to be the only realistic way to reach all the platforms while writing smarter code, and this will likely remain the case for a long time. With any new offering, there will always be some reason why one or more vendors will not rush to ship it.
(But I don't really think this is a problem. Javascript has been nicely optimized by now. Machine code is also unsafe if written by hand, but works fine as a compile target and execution language.)
# So many options
There is an ever growing pool of languages that compile to Javascript. A fairly comprehensive list can be found here:
* [List of languages that compile to JS](https://github.com/jashkenas/coffeescript/wiki/List-of-languages-that-compile-to-JS) on the Coffeescript Wiki
# Noteworthy
I will mention a few I think are noteworthy (while no doubt neglecting some gems which I am unaware of):
* [Spider](http://spiderlang.org/) appeared in 2016. It claims to take the best ideas of Go, Swift, Python, C# and CoffeeScript. It isn't typesafe, but it does have some minor [safety features](http://spiderlang.org/#code-safety).
* [Elm](http://elm-lang.org/): Haskell may be the **smartest language** of them all, and Elm is a variant of Haskell for Javascript. It is highly type-aware and concise, and offers **Functional Reactive Programming** as a neat alternative to reactive templates or MVC spaghetti. But it may be quite **a shock for procedural programmers**.
* Google's [Go](http://golang.org/) is aimed at conciseness, simplicity, and safety. Go code can be compiled into Javascript by [GopherJS](https://github.com/gopherjs/gopherjs).
* [Dart](http://www.dartlang.org/) was Google's later attempt to replace Javascript. It offers interfaces and abstract classes through a C/Java-like syntax with optional typing.
* [Haxe](http://haxe.org/) is like Flash's ActionScript, but it can **target multiple languages** so your code can be re-used in Java, C, Flash, PHP and Javascript programs. It offers type-safe and dynamic objects.
* [Opalang](http://opalang.org/) adds syntactic sugar to Javascript to provide **direct database access**, smart continuations, type-checking and assist with client/server separation. (Tied to NodeJS and MongoDB.)
* [GorillaScript](http://ckknight.github.io/gorillascript/ "GorillaScript"), *"a compile-to-JavaScript language designed to empower the user while attempting to prevent some common errors."* is akin to Coffeescript but more comprehensive, providing a bunch of extra features to increase safety and reduce repetitive boilerplate patterns.
* [LiteScript](https://github.com/luciotato/LiteScript) falls somewhere inbetween Coffeescript and GorillaScript. It offers async/yield syntax for "inline" callbacks, and checking for variable typos.
* Microsoft's [TypeScript](http://www.typescriptlang.org/) is a small superset of Javascript that lets you place type-restrictions on function arguments, which might catch a few bugs. Similarly [BetterJS](http://betterjs.org/) allows you to apply restrictions, but in pure Javascript, either by adding extra calls or by specifying types in JSDoc comments. And now Facebook has offered [Flow](https://flowtype.org/) which additionally performs type inference.
* [LiveScript](http://gkz.github.io/LiveScript/) is a spin-off from Coffeescript that was popular for its brevity but does not look very readable to me. Probably not the best for teams.
# How to choose?
When **choosing** an alternative language, there are some **factors to consider**:
* If other developers join your project in future, how long will it take them to get up to speed and learn this language, or what are the chances they know it already?
* Does the language have too few features (code will still be full of boilerplate) or too many features (it will take a long time to master, and until then some valid code may be undecipherable)?
* Does it have the features you need for your project? (Does your project need type-checking and interfaces? Does it need smart continuations to avoid nested callback hell? Is there a lot of reactivity? Might it need to target other environments in future?)
# The future...
Jeff Walker has written [a thought-provoking series](http://www.walkercoderanger.com/blog/2014/02/javascript-minefield) of blog posts about "the Javascript problem", including why he thinks neither [TypeScript](http://www.walkercoderanger.com/blog/2014/02/typescript-isnt-the-answer), nor [Dart](http://www.walkercoderanger.com/blog/2014/03/dart-isnt-the-answer) nor [Coffeescript](http://www.walkercoderanger.com/blog/2014/03/coffeescript-isnt-the-answer) offer adequate solutions. He suggests some desirable features for an improved language in [the conclusion](http://www.walkercoderanger.com/blog/2014/04/what-coffeescript-should-have-been/). | Alternatives to JavaScript | [
"",
"javascript",
"browser",
""
] |
How can I read the line break from a value with JavaScript and replace all the line breaks with `<br />` elements?
Example:
A variable passed from PHP as below:
```
"This is man.
Man like dog.
Man like to drink.
Man is the king."
```
I would like my result to look something like this after the JavaScript converts it:
```
"This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."
``` | This will turn all returns into HTML
```
str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');
```
In case you wonder what ?: means.
It is called a non-capturing group. It means that group of regex within the parentheses won't be saved in memory to be referenced later.
You can check out these threads for more information:
<https://stackoverflow.com/a/11530881/5042169>
<https://stackoverflow.com/a/36524555/5042169> | If your concern is just displaying linebreaks, you could do this with CSS.
```
<div style="white-space: pre-line">Some test
with linebreaks</div>
```
Jsfiddle: <https://jsfiddle.net/5bvtL6do/2/>
**Note**: Pay attention to code formatting and indenting, since `white-space: pre-line` will display **all** newlines (except for the last newline after the text, see fiddle). | How do I replace all line breaks in a string with <br /> elements? | [
"",
"javascript",
""
] |
The following code when run obviously prints out "B1/A2/B2". Now, is it possible for it to print "A1/A2/B2" instead (i.e. A#method2() should invoke method1() on A, not on B)?
Note: I have no such need to get pass polymorphism, this question is out of curiosity only.
```
class A {
public void method1() {
System.out.println("A1");
}
public void method2() {
method1();
System.out.println("A2");
}
}
class B extends A {
@Override public void method2() {
super.method2();
System.out.println("B2");
}
@Override public void method1() {
System.out.println("B1");
}
}
public class Tmp {
public static void main(String args[]) {
B b = new B();
b.method2();
}
}
``` | Yes, you can do it.
Define A in package **a**:
```
package a;
public class A {
void method1() {
System.out.println("A1");
}
public void method2() {
method1();
System.out.println("A2");
}
}
```
Define B in package **b**:
```
package b;
import a.A;
public class B extends A {
@Override public void method2() {
super.method2();
System.out.println("B2");
}
void method1() {
System.out.println("B1");
}
}
```
Put your test in package **a** and run it. The result is A1/A2/B2. Of course this is unhealthy: note the necessary omission of @Override on method1 - if you put it back in, you will get a compiler error:
```
method does not override or implement a method from a supertype
``` | I don't believe so; not if you're overriding `method1()` in a subclass. If you really required that behavior, you'd have to declare `A.method1()` as `final`, and you couldn't define it in `B`.
It doesn't make sense to me to do this - you should reconsider your design if you think you need to! | Force invocation of base class method | [
"",
"java",
"inheritance",
"polymorphism",
""
] |
I've just refactored out a new domain class from a presenter class but I can't figure out where to instantiate it.
This is part of a larger ongoing refactoring effort with a poorly maintained legacy project.
The Presenter is currently being created by the view's OnLoad event and the view is passed as a parameter in the constructor. All public methods in the presenter are parameterless and return void. They communicate with the view using public properties of the view.
The view, being essentially a humble form depends entirely on the presenter for everything.
This is the typical Passive View pattern and I'd like to continue to adhere to it. Which brings me to my dilemma. I need to create an instance of my new domain object for the presenter to use.
* If I pass it through the constructor then the view has to create it and gains an unnecessary dependency.
* If I create it anywhere within the presenter, I can't replace it with a mock object in my unit tests.
* If I make it a public property of the presenter then I introduce a creation order dependency on the presenter methods where it is used and I still haven't solved what external class gets responsibility for creating it.
I am not currently using any dependency injection frameworks. While I'm interested it using one in the future the source code is still much to fragile to introduce a third party framework into the mix.
I'm open to any suggestions. | I found a much simpler solution. Here's an example of my original class:
```
public Presenter(IView view)
{
this.View = view;
}
```
I wanted to pass my new dependency as a constructor argument but didn't want to add this dependency to my view as well. Constructor chaining to the rescue!
```
public Presenter(IView view):this(view, new Dependency()){}
public Presenter(IView view, IDependency dependency)
{
this.View = view;
this.Dependency = dependency;
}
```
Now the production code continues to use the original interface while the unit tests use the new one passing in mocks for both the view and dependency. If the number of dependencies continues to grow some refactoring will be needed but for the immediate future this is an ideal solution. | I have it already done !!!
Have a look here in [my repository](http://code.google.com/p/mytodotodaylist/source/browse/#svn/trunk/prototype). My choice here is to use constructor ... satisfying the greediest I'm sure that presenter is Up. In your case you can provide from view specific impl for dependencies.
have fun :) | Where do I put dependency creation for a Presenter class in a Passive View architecture? | [
"",
"c#",
"refactoring",
"dependency-injection",
"mvp",
""
] |
I am trying to use Regex in C# to look for a list of keywords in a bunch of text. However I want to be very specific about what the "surrounding" text can be for something to count as a keyword.
So for example, the keyword "hello" should be found in (hello), hello., hello< but not in hellothere.
My main problem is that I don't REQUIRE the separators, if the keyword is the first word or the last word it's okay. I guess another way to look at it is that the beginning-of-the-file and the end-of-the-file should be acceptable separators.
I'm new to Regex so I was hoping someone could help me get the pattern right. So far I have:
```
[ <(.]+?keyword[<(.]+?
```
where <, (, . are some example separators and keyword is of course the keyword I am looking for. | I think you want something like:
```
(^$|[ <(.])+?keyword($|[<(.]+?)
```
The `^` and `$` chars symbolise the start and end of the input text, respectively. (If you specify the `Multiline` option, it matches to the start/end of the line rather than text, but you would seem to want the `Singleline` option.) | You could use the [word boundary](http://www.regular-expressions.info/wordboundaries.html) anchor:
```
\bkeyword\b
```
which would find your keyword only when not part of a larger word. | Regex match words that are not part of a larger word | [
"",
"c#",
"regex",
""
] |
Disclaimer: I know this is a bad way to do things. It is the only option we have with our client.
Problem:
We need to read data from an Excel file every x amount of time. The data is constantly changing via a 3rd party Excel plug in. The environment for the application is Windows XP, SP1 and .Net 2.0. No upgrading the OS to SP2/3 or upgrading the .Net Framework. Again, this is all per customer parameters.
Here is current code we have:
```
String sConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Settings.ReutersFilePath + ";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\"";
using (OleDbConnection objConn = new OleDbConnection(sConnectionString))
{
try
{
objConn.Open();
_dataSet = new DataSet();
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + ConfigurationManager.AppSettings["Excel.WorksheetName"] + "$]", objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(_dataSet);
_dataTable = _dataSet.Tables[0];
objConn.Close();
// Persists new data to a database.
UpdateSQL();
}
catch (Exception ex) { }
finally
{
_isCurrentlyProcessing = false;
if (objConn != null && (objConn.State != ConnectionState.Broken || objConn.State != ConnectionState.Closed))
{
objConn.Close();
}
}
}
```
This code works when running from console or a Windows form, but when we run it from a Windows service, it cannot access the Excel file. Is there a limitation in XP w/SP1 that doesn't allow interaction with desktop applications like there is in Vista? Can this be done from a service? The reliability of running this from a service is much needed from the client.
Edit:
The service is running as LocalSystem.
Edit #2:
The error I get when running from a service is: The Microsoft Jet database engine cannot open the file ''. It is already opened exclusively by another user, or you need permission to view its data.
The Excel file IS open on the desktop, but it has to be open for it to get updates from the 3rd party application. | In addition to @sontek's answer.
[only applicable If you are the owners/developers of the Spreadsheet in question...]
You may find it easier to work with a "data push" model rather than a "data pull" model. It's usually an easier programming model to push the data via an excel macro directly into your data store, based upon some event from your plug-in. this is often a much better scenario than a service polling on a timer. | Excel doesn't allow you to open a file simultaneously. You need to either create it as a shared workbook or make a copy of the file and work off of the copy.
There is also full excel API (Microsoft.Office.Interop.Excel) that you could try using, which would allow you to hook into the currently opened excel/workbook. | Read from Excel using OleDb in a Windows Service? | [
"",
"c#",
"excel",
""
] |
I am using a SaveFileDialog and would like to evaluate whether a file meets certain conditions before allowing it to be saved. If it doesn't meet the criteria, I don't want the SaveFileDialog to close when "Save" is clicked. I thought the FileOK might work, but the dialog looks like it is already closed by the time that event is fired, and I don't see a way to prevent it from closing in any case. | `FileOK` is a [`CancelEventHandler`](http://msdn.microsoft.com/en-us/library/system.componentmodel.canceleventhandler(VS.71).aspx) - you just have to set the [`Cancel`](http://msdn.microsoft.com/en-us/library/system.componentmodel.canceleventargs.cancel(VS.71).aspx) property of the [`CancelEventArgs`](http://msdn.microsoft.com/en-us/library/system.componentmodel.canceleventargs(VS.71).aspx) to `true`. | Try this approach from FileOK handler
```
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
//your conditions...
if (!openFileDialog1.FileName.Equals( "C:\\hello.txt" ) )
{
//if fail, set e.cancel
MessageBox.Show(@"File name must equal c:\hello.txt.");
e.Cancel = true;
}
}
``` | How can I validate a filename prior to the SaveFileDialog closing? | [
"",
"c#",
"savefiledialog",
""
] |
I want to convert a number of unicode codepoints read from a file to their UTF8 encoding.
e.g I want to convert the string `'FD9B'` to the string `'EFB69B'`.
I can do this manually using string literals like this:
```
u'\uFD9B'.encode('utf-8')
```
but I cannot work out how to do it programatically. | Use the built-in function [`chr()`](https://docs.python.org/3/library/functions.html#chr) to convert the number to character, then encode that:
```
>>> chr(int('fd9b', 16)).encode('utf-8')
'\xef\xb6\x9b'
```
This is the string itself. If you want the string as ASCII hex, you'd need to walk through and convert each character `c` to hex, using `hex(ord(c))` or similar.
***Note***: If you are still stuck with Python 2, you can use [`unichr()`](https://docs.python.org/2/library/functions.html#unichr) instead. | here's a complete solution:
```
>>> ''.join(['{0:x}'.format(ord(x)) for x in unichr(int('FD9B', 16)).encode('utf-8')]).upper()
'EFB69B'
``` | Convert unicode codepoint to UTF8 hex in python | [
"",
"python",
"unicode",
""
] |
I am using a class in a C# ASP.NET project to allow a script written in some random scripting language to expose webservice methods dynamically - in other words, the script should be able to expose a method of any name with any signature (as long as it's valid, anyway) to the outside world through this SOAP interface (able to add and remove them at will, without needing a hard code change), and as such I need to be able to create a webservice class in C# while being able to dynamically add and remove methods at runtime.
Now, the best plan I've been able to come up with so far is (runtime) generating C# code to represent the webservice, using System.Reflection.Emit to compile it and then loading the assembly at runtime - all whenever the script adds or removes a method to/from the service (should not happen very often, mind).
Does anyone have a better idea than this? | You can modify WSDL by using [SoapExtensionReflector](http://msdn.microsoft.com/en-us/library/system.web.services.description.soapextensionreflector.aspx) class. From [Kirk Evans Blog](http://blogs.msdn.com/kaevans/archive/2005/11/16/493496.aspx):
> The SoapExtensionReflector is called when your type is being reflected over to provide the WSDL definition for your service. You can leverage this type to intercept the reflection call and modify the WSDL output.
The following example removes the first method out of 2 web service methods:
```
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public int Multiply(int a, int b)
{
return a * b;
}
}
```
Create a class inherited from SoapExtensionReflector:
```
namespace TestWebservice
{
public class MyReflector : SoapExtensionReflector
{
public override void ReflectMethod()
{
//no-op
}
public override void ReflectDescription()
{
ServiceDescription description = ReflectionContext.ServiceDescription;
if (description.PortTypes[0].Operations.Count == 2)
description.PortTypes[0].Operations.RemoveAt(0);
if (description.Messages.Count == 4)
{
description.Messages.RemoveAt(0);
description.Messages.RemoveAt(0);
}
foreach (Binding binding in description.Bindings)
{
if (binding.Operations.Count == 2)
binding.Operations.RemoveAt(0);
}
if (description.Types.Schemas[0].Items.Count == 4)
{
description.Types.Schemas[0].Items.RemoveAt(0);
description.Types.Schemas[0].Items.RemoveAt(0);
}
}
}
}
```
Add this to configuration/system.web section in web.config:
```
<webServices>
<soapExtensionReflectorTypes>
<add type="TestWebservice.MyReflector, TestWebservice" />
</soapExtensionReflectorTypes>
</webServices>
```
This should give you a starting point to dynamically removing methods from WSDL document. You would also need to throw NotImplementedException from web method if it is disabled.
Finally, you need to disable web service documentation produced by invoking .asmx endpoint without ?WSDL parameter. Set href attribute of wsdlHelpGenerator element to some URL. You can use DefaultWsdlHelpGenerator.aspx as a starting point for your own documentation handler. See question on web service documentation in [XML Files, August 2002](http://msdn.microsoft.com/en-us/magazine/cc302115.aspx). | XMLRPC is fairly dead, isn't it?
SOAP implies a WSDL. How do you generate the WSDL dynamically?
You should look into using WCF. I expect you'll be able to take control of the process of generating the WSDL (and other metadata), yet you should also be able to take control of the processing of incoming messages. In particular, you will be able to examine the incoming messages to determine which script to run, what parameters to pass, etc. | Dynamic C#.NET Webservice | [
"",
"c#",
"asp.net",
"web-services",
"dynamic",
"reflection.emit",
""
] |
When you use `MessageBox.Show()` you have a selection of [MessageBoxButtons](http://msdn.microsoft.com/en-us/library/system.windows.forms.messageboxbuttons%28v=vs.110%29.aspx) to choose from. The buttons available are an enum, and give you options like "Yes No", "OK Cancel", etc.
When I am using, for instance, Norwegian message text the user still gets the English "Yes No".
Is there a way to change the text of the buttons (in C#) so that the language is correct? Can I override the text, or set the current locale in some way so that I can have "Ja Nei" instead of "Yes No"?
I do not want to rely on installing a .NET language pack at my client. | There is no native support for this in .NET (as far as I know, anyway; please correct me if I'm wrong, anyone). I did come across this CodeProject article, that seem to do the trick with some message hooking and P/Invoke:
<http://www.codeproject.com/KB/miscctrl/Localizing_MessageBox.aspx> | Usually messagebox buttons (as all of Windows) honor the currently set UI language for Windows. So if you've got an English installation and can't change languages (MUI versions or Ultimate for Vista/7) you're out of luck.
You could implement a messagebox yourself but I'd beg you not to. Simple things like common hotkeys for the buttons, having the ability to use Ctrl+Ins to copy the contents, etc. are the ones I miss the most when people start reinventing square wheels. | MessageBox buttons - set language? | [
"",
"c#",
".net",
"localization",
"messagebox",
""
] |
I'm developing an application with ASP.NET 3.5 and I have read that the language that the application is shown in is the navigator's language.
Is there any way to choose the language of the application programmatically? For example, I want to see the application in English but my Internet Explorer is in Spanish.
The language is a user's preference stored in the database, so I need to change the language when the user logs in. | You can use the [CultureInfo](http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx "CultureInfo") class to set the culture for your executing environment.
```
CultureInfo ci = new CultureInfo("en-US", false);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
``` | Are you asking how to change your browser's accept language? See <http://windowshelp.microsoft.com/Windows/en-US/help/7b4a0825-28e2-4929-82f6-1feac4adb6f31033.mspx> for instructions for IE 7 and IE 8. The section you want is "To add a language to Internet Explorer" | How do I change the application language in ASP.NET? | [
"",
"c#",
"asp.net-3.5",
""
] |
I am trying to code a function which creates a dropdown of school names selected from a database. It is doing fine creating a dropdown but it is not putting anything in the dropdown. Here is the code:
```
function schoolDD($name, $selected){
$select = '';
if( $selected != null )
{
$select = $selected;
}
$qry = "select *
from school
order by name, id
where display = 'Y'";
$schools = _execQry($qry);
$html = '<select name="'.$name.'" >';
foreach( $schools as $s ){
$html .= '<option value="'. $s['id'] .'"';
if( $select == $s['name'] ){
$html .= 'selected="selected"';
}
$html .= '>'. $s['name'] . '</option>';
}
$html .= '</select>';
return $html;
}
``` | Problem solved. It was because in the query I had order before where. It should have been:
```
$qry = "select *
from school
where display = 'Y'
order by name, id";
```
Not:
```
$qry = "select *
from school
order by name, id
where display = 'Y'";
``` | Looks OK but hard to say without knowing what \_execQry does.
If you add the line
```
print_r($schools);
```
after you call \_execQry, are you definitely retrieving results from the database? | How do you create a form dropdown from a database table in php? | [
"",
"php",
"mysql",
"html",
"forms",
"drop-down-menu",
""
] |
Do you know of any good guides on how to access an Access database using Java?
I know the basics and basic SQL, but I'm thinking more about access control. | ```
private static final String accessDBURLPrefix = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
private static final String accessDBURLSuffix = ";DriverID=22;READONLY=false}";
// Initialize the JdbcOdbc Bridge Driver
static {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(ClassNotFoundException e) {
System.err.println("JdbcOdbc Bridge Driver not found!");
}
}
/** Creates a Connection to a Access Database */
public static Connection getAccessDBConnection(String filename) throws SQLException {
filename = filename.replace('', '/').trim();
String databaseURL = accessDBURLPrefix + filename + accessDBURLSuffix;
return DriverManager.getConnection(databaseURL, "", "");
}
```
Some useful links:
* <http://blog.taragana.com/index.php/archive/how-to-access-ms-access-database-from-jdbc/>
* <http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=2691&lngWId=2> | If you mean using relational databases in Java, you'll need to know [JDBC](http://java.sun.com/docs/books/tutorial/jdbc/index.html).
You won't be able to do much with security using JDBC. You'll have to build it into the application using something like [JAAS](http://java.sun.com/javase/6/docs/technotes/guides/security/) or [Spring Security](http://static.springframework.org/spring-security/site/reference/html/springsecurity.html). | How do I connect to an Access database over a LAN using Java? | [
"",
"java",
"database",
"ms-access",
"jdbc",
"lan",
""
] |
Can assign a pointer to a value on declaration? Something like this:
```
int * p = &(1000)
``` | Yes, you can initialize pointers to a value on declaration, however you can't do:
```
int *p = &(1000);
```
& is the **address of** operator and you can't apply that to a constant (although if you could, that would be interesting). Try using another variable:
```
int foo = 1000;
int *p = &foo;
```
or type-casting:
```
int *p = (int *)(1000); // or reinterpret_cast<>/static_cast<>/etc
``` | What about:
```
// Creates a pointer p to an integer initialized with value 1000.
int * p = new int(1000);
```
Tested and works. ;-) | Initializing pointers in C++ | [
"",
"c++",
"pointers",
"initialization",
""
] |
When I have a given django model class like this:
```
class BaseClass(models.Model):
some_field = models.CharField(max_length = 80)
...
```
and some subclasses of it, for example
```
class SomeClass(BaseClass):
other_field = models.CharField(max_length = 80)
```
Then I know I can get the derived object by calling
```
base = BaseClass.objects.get(pk=3)
my_obj= base.someclass
```
Now the problem arises that I have multiple subclasses, and all I have is an instance of the base class. How can I get to the subclassed object without knowing it's class in advance?
---
The idea is to load a corresponding view and let that do the stuff. My project features only have a limited set of default actions for these models, like view, edit, delete etc. What I don't want is to expose the type of the given object via URL, so the "normal way" is not available | There isn't a built-in way.
Perhaps the best thing to do is to define a `derived_type` field on your base class, which is set automatically on save of the derived class. You could then have a `get_derived` method on the base which checks the value of `derived_type` and returns the actual derived object. | > How can I get to the subclassed object without knowing it's class in advance?
Why would this be useful? If you don't know what class you want, you also won't know which methods to call or which attributes can be inspected.
---
> The idea is to load a corresponding view and let that do the stuff. My project features only have a limited set of default actions for these models, like view, edit, delete etc. What I don't want is to expose the type of the given object via URL, so the "normal way" is not available
If you know the set of model subclasses ahead of time, or are willing to register them with a central view list, you can do something like this:
```
VIEWS = [('subclass_a', a_views), ('subclass_b', b_views)]
def edit(request):
base = (get base somehow)
for attrname, views in VIEWS:
if getattr(base, attrname) is not None:
return views['edit']
```
Depending on how many different kinds of views you have, you might abstract the search out into a separate function, so the end view is something like:
```
def edit(request):
return generic_base_view(request, 'edit')
``` | How to get a subclassed object of a django model | [
"",
"python",
"django",
"inheritance",
"model",
""
] |
**Background**:
I was recently playing around with GDI+ to draw a "Disc" displaying a sweeping color change through 360 degrees. (I dug up some HSL to RGB code to loop through HSL(1,1,1) -> HSL(360,1,1))
Regarding the disc, I first drew a full solid circle using the above, and then a second circle in Grey over the center to give the following

So this is all fine... but I realised that GDI+ is insulating us from a lot of the tricky match that's going on here by way of the `FillPie` method. Also, `FillPie` requires you to supply a bounding rectangle for the pie as opposed to a Radius Length. It also does a full segment fill and doesnt allow you to specify a part of that segment only.
**Question:**
Can anyone point me in the direction of some Math functions or give any explanation on what forumla I would need to calculate the area & plot points of the following "Green Filled Area" given:
```
Point `c` - an x,y co-ordinate
Angle `A` - an angle from horizontal
Angle `B - an angle from horizontal where `B` - `A` == the sweep angle
Length `r` - a distance from `c`
Length `r2` - a distance from `c` where `r2` - `r` == the `height` of the segment to be filled.
```

Links to Math sources are fine but I've had a quick google & look at Wolfram Math and could find what I was looking for. Also, if there was some way to generate a sequence of bounding (x,y) co-or's that could be passed as a `Point[]` to Graphics.FillPolygon, that'd be cool too. | The area is the difference of the outer and inner disc parts. The area of a disc part is proportional to the angle sweep:
```
area = (b-a)*((r+r2)^2-r^2)/2
```
`a` and `b` must be expressed in radians.
For `b-a = 2*Pi`, `area = Pi*(r+r2)^2 - Pi*r^2` is the difference of the areas of the outer and inner discs.
You can generate points on the inner / outer circle using
```
x = cx + r * cos(t) / x = cx + (r+r2) * cos(t)
y = cy + r * sin(t) / y = cy + (r+r2) * sin(t)
```
Where `t` varies from `a` to `b`. | Hope this helps. The second part provides a method for calculating the area of a sector of a circle
<http://www.wikihow.com/Calculate-the-Area-of-a-Circle> | Calculating the bounding points for the area of a "Pie Segment" and "sub areas" | [
"",
"c#",
"math",
"gdi+",
"pie-chart",
""
] |
I have and an AJAX script in a page that works just fine with no bugs in firefoex, but IE6 loads the page with an ugly error icon on the status bar. What is the best way i can go about fixing/debugging this?
Here is the error report:

I have checked line 323 many times Here is the function:
```
function checkAvailability(){
var card_select = document.getElementById('card_select').value;
var price_select = document.getElementById('price_select').value;
var num_of_cards = document.getElementById('num_of_cards').value;
var url = 'checkAvailability.php?cardName=' + card_select + '&value=' + price_select + '&amount=' + num_of_cards;
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.responseText) /**** line 323 ****/
{
document.getElementById('submit_button').className = 'hidden';
document.getElementById('div_error_massage').className = 'anounce_div';
document.getElementById('error_massage').innerHTML = xmlhttp.responseText;
document.getElementById('num_of_cards').className = 'red_inputs';
}
else if(isNaN(num_of_cards))
{
document.getElementById('submit_button').className = 'hidden';
document.getElementById('num_of_cards').className = 'red_inputs';
document.getElementById('div_error_massage').className = 'hidden';
}
else if(num_of_cards != "" && !xmlhttp.responseText)
{
document.getElementById('submit_button').className = '';
document.getElementById('error_massage').innerHTML = 'Total: $' + document.getElementById('price_select').value * document.getElementById('num_of_cards').value + '.00';
document.getElementById('div_error_massage').className = 'anounce_div';
}
else
{
document.getElementById('submit_button').className = 'hidden';
document.getElementById('num_of_cards').className = 'red_inputs';
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
``` | In IE, you can try the old [script debugger](http://www.microsoft.com/downloads/details.aspx?FamilyID=2f465be0-94fd-4569-b3c4-dffdf19ccd99&displaylang=en) or [Visual Web Developer Express](http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/). When the error throws, enter the debugger and examine `xmlhttp`. | In addition to outis' answer, if you want to control where you jump in with the debugger, use Javascript's `debugger` keyword, which acts like a breakpoint. When the line with `debugger;` is hit, in IE you will get a prompt (if debugging is enabled in IE, check your Internet Options) to launch the debugger, starting at that line. In Firefox, the `debugger;` statement is picked up by Firebug as a breakpoint. | How can i debug this ajax script for IE? | [
"",
"javascript",
"ajax",
"internet-explorer",
""
] |
I'm clearly in need of improving my knowledge in this Java field, or I'm doomed to produce "look the same but not exactly" code.
I'm already have the bases... but I'm looking for a training / tuturial oriented only to this.
Thanks | The [book](http://books.google.fi/books?id=3keGb40PWJsC&dq=java+generics+wadler&printsec=frontcover&source=bn&hl=fi&ei=PlwMSpj4IITL-Abh8uyiBg&sa=X&oi=book_result&ct=result&resnum=4#PPP1,M1) written by one of the designers of Java Generics, Philip Wadler | * [Angelika Langer's Java Generics FAQs](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html).
* [Oracle's Java Generics Tutorial](http://docs.oracle.com/javase/tutorial/extra/generics/index.html)
* Joshua Bloch's [Effective Java](http://www.infoq.com/articles/bloch-effective-java-2e), [Chapter 5 - Generics](http://www.infoq.com/resource/articles/bloch-effective-java-2e/en/resources/Bloch_Ch05.pdf) [pdf] | Resource for learning Java generics? | [
"",
"java",
"generics",
""
] |
If I wanted to access a database in Delphi, I could add a datamodule to a project, configure it from my mainform and then access it anywhere in the application; a reference would be stored in a global variable.
I know that in C# and other more modern OO languages global variables are frowned upon. So how can I access my database from where I need it? The biggest problem I have is the configuration: location, user, password, etc. are unknown at design time.
I now have a db-class and make a new instance when I need it, but then I would have to store those settings in some globally accessible thing, and I have simply moved the problem.
What's the standard solution?
Thanks, regards, Miel. | It seems to me that you need to create an appropriate object (containing the connection or similar), and pass that instance to *each object requiring access* (see [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection))
This is different from using singletons. By using this mechanism, it'll free you from the dependency on one object and (perhaps a more compelling reason in this instance) allow you to perform testing by injecting mock objects or similar in place of the originally-injected database accessor object. I would definitely shy away from the singleton mechanism in this scenario. | I always use the [singleton pattern](http://www.yoda.arachsys.com/csharp/singleton.html). As for configuration, look at the **System.Configuration.ConfigurationManager** class which allows you to read settings from your project's app.config/web.config file. | Database access from everywhere in application | [
"",
"c#",
"database",
"oop",
""
] |
I need to check whether an std:string begins with "xyz". How do I do it without searching through the whole string or creating temporary strings with substr(). | I would use compare method:
```
std::string s("xyzblahblah");
std::string t("xyz")
if (s.compare(0, t.length(), t) == 0)
{
// ok
}
``` | An approach that might be more in keeping with the spirit of the Standard Library would be to define your own begins\_with algorithm.
```
#include <algorithm>
using namespace std;
template<class TContainer>
bool begins_with(const TContainer& input, const TContainer& match)
{
return input.size() >= match.size()
&& equal(match.begin(), match.end(), input.begin());
}
```
This provides a simpler interface to client code and is compatible with most Standard Library containers. | std::string comparison (check whether string begins with another string) | [
"",
"c++",
"string",
"stl",
"compare",
""
] |
I use a very simple query with "Like" to find product by its name
```
SELECT p_pid, p_name, p_cat
FROM products
WHERE p_sid=346 AND p_name LIKE 'product name here in utf-8 encoding, can be various languages'
LIMIT 1
```
When I run this query from code with valid product name, I get no results. If I copy the query (echoed by php to the browser) and run it manually in mysql query browser I do get a result. Any idea where I'm wrong?
Notes:
1.There is no error coming from the query. Just no results.
2. I'm using ezsql library
3. The code runs well and perform other SELECTs with the database successfully in the same scope in the code. | Seems to be the issue with encoding.
Try running this query:
```
SELECT HEX(CAST('product name here in utf-8 encoding, can be various languages' AS BINARY))
```
both in `ezSQL` and in the query browser and compare the results.
This will give you binary stream that `MySQL` really gets from your client and uses in comparison.
If you set wrong connection encoding in `ezSQL` properties, the string may get mangled (like, question marks instead of `UTF` symbols).
In this case comparison will of course fail.
**Update:**
Try to force case insensitive collation:
```
SELECT *
FROM table
WHERE field LIKE 'product name here in utf-8 encoding, can be various languages' COLLATE UTF8_GENERAL_CI
```
Also, could you please post binary dump both of your string and the data contained in the field?
```
SELECT p_pid, p_name, p_cat,
HEX(CAST(p_name AS BINARY)),
HEX(CAST('product name here in utf-8 encoding, can be various languages' AS BINARY))
FROM products
WHERE p_pid = @pid_of_product_that_should_match_but_it_doesnt
``` | Are the machine, database and user the same between the manually and automatically run scripts? Could one be accessing the test server while the other accesses the production server (for example.) | mysql query works manually but returns no results when running from code | [
"",
"php",
"mysql",
"select",
"sql-like",
""
] |
I don't know if that's the right word for it, but I am trying to come up with some regex's that can extract coefficients and exponents from a mathematical expression. The expression will come in the form 'axB+cxD+exF' where the lower case letters are the coefficients and the uppercase letters are the exponents. I have a regex that can match to both of them, but I'm wondering if I can use 2 regexs, one to match the coefficients and one for the exponents. Is there a way to match a number with a letter on one side of it without matching the letter? EG, in '3x3+6x2+2x1+8x0' I need to get
['3', '6', '2', '8']
and
['3', '2', '1', '0'] | You can use [positive look-ahead](http://www.regular-expressions.info/lookaround.html#lookahead) to match something that is followed by something else. To match the coefficients, you can use:
```
>>> s = '3x3+6x2+2x1+8x0'
>>> re.findall(r'\d+(?=x)', s)
['3', '6', '2', '8']
```
From the documentation of the [`re`](http://docs.python.org/library/re.html) module:
> (?=...)
> Matches if ... matches next, but doesn’t consume any of the string.
> This is called a lookahead assertion.
> For example, Isaac (?=Asimov) will
> match 'Isaac ' only if it’s followed
> by 'Asimov'.
For the exponents, you can use [positive look-behind](http://www.regular-expressions.info/lookaround.html#lookbehind) instead:
```
>>> s = '3x3+6x2+2x1+8x0'
>>> re.findall(r'(?<=x)\d+', s)
['3', '2', '1', '0']
```
Again, from the docs:
> (?<=...) Matches if the current position in the string is preceded by a match for
> ... that ends at the current position.
> This is called a positive lookbehind
> assertion. (?<=abc)def will find a
> match in abcdef, since the lookbehind
> will back up 3 characters and check if
> the contained pattern matches. | ```
>>> import re
>>> equation = '3x3+6x2+2x1+8x0'
>>> re.findall(r'x([0-9]+)', equation)
['3', '2', '1', '0']
>>> re.findall(r'([0-9]+)x', equation)
['3', '6', '2', '8']
``` | Python regex - conditional matching? | [
"",
"python",
"regex",
""
] |
Say I have:
```
class A {
public:
static void DoStuff();
// ... more methods here ...
};
```
And later on I have a function that wants to call DoStuff:
```
B::SomeFunction(A* a_ptr) {
```
Is it better to say:
```
a_ptr->DoStuff();
}
```
Or is the following better even though I have an instance pointer:
```
A::DoStuff()
}
```
This is purely a matter of style, but I'd like to get some informed opinions before I make a decision. | I think I'd prefer "A::DoStuff()", as it's more clear that a static method is being called. | It's better to call the static method by its name, not through an object, since it doesn't actually use that object at all. In Java, the same problem exists. A not-too-uncommon problem in Java is the following:
```
Thread t = getSomeOtherThread();
t.sleep(1000);
```
This compiles fine but is almost always an error -- `Thread.sleep()` is a static method that causes the *current* thread to sleep, not the thread being acted on as the code seems to imply. | Given a pointer to a C++ object, what is the preferred way to call a static member function? | [
"",
"c++",
"static",
"coding-style",
""
] |
I have some jaxb objects (instantiated from code generated from xsd by jaxb) that I need to clone. The Jaxb class does not appear to provide an interface for doing this easily. I can not hand edit the class and can not extend it - so I need to create a helper/utility method to do this. What is the best approach? | Given the purpose of JAXB, I think the easiest way would be to marshall your object to XML and unmarshall it back.
Lots more discussions on [Google](http://www.google.com/search?q=jaxb+clone).
JAXB FAQ [suggests](https://jaxb.dev.java.net/guide/Working_with_generated_code_in_memory.html) [beanlib](http://beanlib.sourceforge.net/).
There's also some [discussion](http://www.nabble.com/cloning-JAXBElements-td4708089.html) (as well as a link to download) of a Cloneable plugin under jaxb2-commons, although I can't find any reference on the project page. | I've run benchmarks on various solutions for cloning a JAXB object. Here are some results:
1. Using [mofokom's xjc-clone plugin](http://www.mofokom.biz/artifactory/snapshots-public/mofokom/xjc-clone/) seems to be the fastest solution. It just lets all your generated artefacts implement [`Cloneable`](http://docs.oracle.com/javase/7/docs/api/java/lang/Cloneable.html) and publicly overrides [`Object.clone()`](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#clone%28%29). Unfortunately, this hasn't made it into Maven central (yet).
2. Generating [`Serializable`](http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html) artefacts and serialising / deserialising them to a dummy stream is 10x slower than using Java's cloning mechanisms:
```
public <T extends Serializable> T clone(T jaxbObject) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(out);
o.writeObject(jaxbObject);
o.flush();
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
ObjectInputStream i = new ObjectInputStream(in);
return (T) i.readObject();
}
```
3. Marshalling / Unmarshalling the JAXB objects is again 5x slower than serialising / deserialising them. This is what [ykaganovich's](https://stackoverflow.com/a/930867/521799) solution suggests:
```
public <T extends Serializable> T clone(T jaxbObject) {
StringWriter xml = new StringWriter();
JAXB.marshal(jaxbObject, xml);
StringReader reader = new StringReader(xml.toString());
return JAXB.unmarshal(reader, jaxbObject.getClass());
}
``` | How Do I Clone A JAXB Object | [
"",
"java",
"jaxb",
""
] |
In a simple program I made, I wanted to get a list from another project and access the elements from it. Since I'm new to python, I don't really have any idea what to do. In my project, I checked the box for the project name I wanted to reference and... I don't know what to do. A few google searched did me no good, so I'm hoping someone here can tell/link me how to set this up. | Use import. Then you can access the "module" (project) and everything in it like an object./
```
# a.py
some_list = [1,2,3,4]
# b.py
import a
print a.some_list
```
If you run b.py, it will print [1,2,3,4] | Generally if you have some code in `project1.py` and then want to use it from a different file in the same directory, you can import `project1` as a module:
```
import project1
data = project1.my_data_function()
```
This works just the same way as you would import any module form the standard library. | Referencing another project | [
"",
"python",
""
] |
I need to achieve this
```
update [table]
set [column c] = ( select [column a] + ' ' + [column b] from [table] )
```
but I get this error message
*Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.*
How can I achieve the desired effect without the undesired results :)
Jim | That's easy:
```
update table
set c = a + ' ' + b
```
This will update all rows in the table. | try adding a WHERE clause to the sub-query so it picks out only one row. | Updating Column C with the values of Column A and Column B | [
"",
"sql",
"sql-update",
""
] |
I ran into a bug in some code that extracts metadata from some text and puts it into a dictionary.
My test was failing when I compared two dictionary objects because the keys were in different order. I don't really care what order the keys are in.
I'd like to have an assert method available like :
```
Assert.AreEquivalent(propsExpected,propsActual)
```
That would evaluate like:
```
Assert.AreEqual(propsExpected.Count, propsActual.Count);
foreach (var key in propsExpected.Keys)
{
Assert.IsNotNull(props[key]);
Assert.AreEqual(propsExpected[key], props[key]);
}
```
What's the best way to do this? | The trick here is to use a new feature of .Net 3.5 called [extension methods](http://msdn.microsoft.com/en-us/library/bb383977.aspx)
For example to get the Assert class to support the AreEquivalent method using the code you supplied above, you would do something like this:
```
public static class MyAssertExtensions
{
public static void AreEquivalent(this Assert ast,
Dictionary<string, int> propsExpected,
Dictionary<string, int> propsActual)
{
Assert.AreEqual(propsExpected.Count, propsActual.Count);
foreach (var key in propsExpected.Keys)
{
Assert.IsNotNull(props[key]);
Assert.AreEqual(propsExpected[key], props[key]);
}
}
}
```
This way you can actually call the assertion like this:
```
Assert.AreEquivalent(propsExpected,propsActual);
``` | For the sake of completeness, take a look at
[Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.collectionassert_members%28v=vs.80%29.aspx) | How to build custom assertions in C#/VS? | [
"",
"c#",
"visual-studio",
"unit-testing",
""
] |
Hey I want to sort objects based on a computed value in django... how do I do it?
Here is an example User profile model based on stack overflow that explains my predicament:
```
class Profile(models.Model):
user = models.ForeignKey(User)
def get_reputation():
...
return reputation
reputation = property(get_reputation)
```
So, say I want to sort users by reputation. How do I do that? I know you can't just do this:
```
Profile.objects.order_by("-reputation")
```
Thanks for your help everyone :) | If you need to do the sorting in the database (because you have lots of records, and need to e.g. paginate them), the only real option is to turn reputation into a denormalized field (e.g. updated in an overridden `save()` method on the model). | Since your calculation code exists only within Python, you have to perform the sorting in Python as well:
```
sorted (Profile.objects.all (), key = lambda p: p.reputation)
``` | how to sort by a computed value in django | [
"",
"python",
"django",
"web-applications",
"sorting",
"django-models",
""
] |
We're being really stuck here so I decided to ask your help.
Yesterday I've been asked to help to consume a web service, got the URL to the WSDL, and the user credentials to use.
I've never really had anything to do with web services, but having a general idea about them and seeing a few examples I thought it can't be that bad. Obviously I was wrong as I'm stuck now.
Everything seems to be fine, the proxy class (or client) has been generated, building up requests and sending them are fine too, apart from the authentication part. Which we can't seem to figure out how to do.
Using the:
```
client.ChannelFactory.Credentials.UserName.UserName = "myusername";
client.ChannelFactory.Credentials.UserName.Password = "mypassword";
```
doesn't seem to work. (When I check the BindingElementCollection returbed by the client.Endpoint.Binding.CreateBindingElements() there's no SecurityBindingElement)
I've tried so many other ways of doing it, but I think I'm missing something basic and the lack of documentaion is not really helping either.
So the question is: How do I send the username and password when making a call to a web service, using WCF?
**Edit:**
Just to clarify, the request should contain something similar to this:
```
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="1">
<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="UsernameToken-25763165">
<wsse:Username>username</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">1DiaGTkOLk/CZhDaEpbkAaKRfGw=</wsse:Password>
<wsse:Nonce>6ApOnLn5Aq9KSH46pzzcZA==</wsse:Nonce>
<wsu:Created>2009-05-13T18:59:23.309Z</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>
``` | I had the same problem. Instead of the custom token serializer I used a `MessageInspector` to add the correct `UsernameToken` in the `BeforeSendRequest` method. I then used a custom behavior to apply the fix.
The entire process is documented (with a [demo project](http://www.box.net/shared/lu3q83l6kr)) in my blog post [Supporting the WS-I Basic Profile Password Digest in a WCF client proxy](http://blog.benpowell.co.uk/2010/11/supporting-ws-i-basic-profile-password.html). Alternatively, you can just read the [PDF](http://www.box.net/shared/ooom8db1i0).
If you want to follow my progress through to the solution, you'll find it on StackOverflow titled, "[Error in WCF client consuming Axis 2 web service with WS-Security UsernameToken PasswordDigest authentication scheme](https://stackoverflow.com/questions/3102693/error-in-wcf-client-consuming-axis-2-web-service-with-ws-security-usernametoken-p)": | I've achieved similar, using a regular HttpCookie.
To create the cookie:
```
[OperationContract]
public void LoginToApi(string username, string password, string clientName)
{
// authenticate with DB, if successful ...
// construct a cookie
HttpCookie httpCookie = new HttpCookie("SessionID","whateverneeded");
HttpContext.Current.Response.SetCookie(httpCookie);
}
```
This appears in your regular HttpRequests, too. So you just reverse the process, checking the hash/session ID/username/password whatever you put in the cookie on receipt before doing anything. | Web service request authentication | [
"",
"c#",
"wcf",
"web-services",
"authentication",
""
] |
I assume this is a common way to use sprintf:
```
char pText[x];
sprintf(pText, "helloworld %d", Count );
```
but what exactly happens, if the char pointer has less memory allocated, than it will be print to?
i.e. what if x is smaller than the length of the second parameter of sprintf?
i am asking, since i get some strange behaviour in the code that follows the sprintf statement. | It's not possible to answer in general "exactly" what will happen. Doing this invokes what is called [Undefined behavior](http://en.wikipedia.org/wiki/Undefined_behavior), which basically means that anything might happen.
It's a good idea to simply avoid such cases, and use safe functions where available:
```
char pText[12];
snprintf(pText, sizeof pText, "helloworld %d", count);
```
Note how `snprintf()` takes an additional argument that is the buffer size, and won't write more than there is room for. | This is a common error and leads to memory after the char array being overwritten. So, for example, there could be some ints or another array in the memory after the char array and those would get overwritten with the text.
See a nice detailed description about the whole problem (buffer overflows) [here](http://www.ibm.com/developerworks/library/s-buffer-defend.html). There's also a comment that some architectures provide a snprintf routine that has a fourth parameter that defines the maximum length (in your case x). If your compiler doesn't know it, you can also write it yourself to make sure you can't get such errors (or just check that you always have enough space allocated).
Note that the behaviour after such an error is undefined and can lead to very strange errors. Variables are usually aligned at memory locations divisible by 4, so you sometimes won't notice the error in most cases where you have written one or two bytes too much (i.e. forget to make place for a NUL), but get strange errors in other cases. These errors are hard to debug because other variables get changed and errors will often occur in a completely different part of the code. | c++ what happens if you print more characters with sprintf, than the char pointer has allocated? | [
"",
"c++",
"printf",
""
] |
I'm trying to display a datetime from my MySQL database as an iso 8601 formated string with PHP but it's coming out wrong.
17 Oct 2008 is coming out as: 1969-12-31T18:33:28-06:00 which is clearly not correct (the year should be 2008 not 1969)
This is the code I'm using:
```
<?= date("c", $post[3]) ?>
```
`$post[3] is the datetime (CURRENT_TIMESTAMP)` from my MySQL database.
Any ideas what's going wrong? | The second argument of [`date`](http://www.php.net/date) is a UNIX timestamp, not a database timestamp string.
You need to convert your database timestamp with [strtotime](http://www.php.net/strtotime).
```
<?= date("c", strtotime($post[3])) ?>
``` | Using the [DateTime class](http://www.php.net/manual/en/book.datetime.php) available in PHP version 5.2 it would be done like this:
```
$datetime = new DateTime('17 Oct 2008');
echo $datetime->format('c');
```
As of PHP 5.4 you can do this as a one-liner:
```
echo (new DateTime('17 Oct 2008'))->format('c');
``` | How to display a date as iso 8601 format with PHP | [
"",
"php",
"mysql",
"date",
"date-format",
"time-format",
""
] |
I asked another question about HTML and PHP separation as I have seen references to it on tutorial and examples pages but I found that separation of HTML and PHP it something different than what people are actually commenting on and I think that is PHP modes.
That is breaking out of PHP or not. Should It be done? Is it important?
Is it just a matter of preference to echo my HTML output or should I break out to display it?
Example:
```
<?php
echo '<html'>;
?>
```
vs.
```
<?php
dostuff();
?>
<html>
<?
morestuff();
?>
``` | I assume by "breaking out" you mean:
```
<?php foo(); ?>
test
<?php bar(); ?>
```
as opposed to
```
<?php
foo();
echo("test");
bar();
?>
```
Well, one advantage of the first solution is that your layout is still more or less readable in HTML editors. Also, it separates layout and logic, at least more than the other variant. It is probably also slightly faster than the second option because no strings need to be parsed and echo'ed. On the flipside, having tons and tons of individual PHP-blocks can really be hard to read because things that are semantically related are suddenly split. You can, of course, also combine both approaches.
I think the bottom line here is that as soon as you need to do so much formatting and echo'ing that the logic of your program becomes really obscured, you should consider using a 'real' template engine. | I think it depends on the situation.
how many lines do you want to echo to the browser?
do the lines contain $variable values? $array values?
do you loop trough a dataset? etc etc.
To me, it is more reable to just echo the lines most of the time.
```
<?php
if ( check($something) ) {
echo "Some variable is: $something<br/>\n";
} else {
echo "Some variable is something else!<br/>\n";
}
?>
```
can be more readable than:
```
<?php
if ( check($something) ) {
?>
Some variable is: <?php echo $something; ?><br/>
<?php
} else {
?>
Some variable is something else!<br/>
<?php
}
?>
```
and with some IDEs (or [stackoverflow.com](http://stackoverflow.com) syntaxhighlighting for example), it can even be more readable to use:
```
<?php
if ( check($something) ) {
echo 'Some variable is: '.$something."<br/>\n";
} else {
echo "Some variable is something else!<br/>\n";
}
?>
```
**In summary:**
PHP offers you a lot of options to send content to your client.
The 'best method' differs from case tot case.
Choose the method that is *most readable/maintainable* and *use it consistently.* | php modes breaking out of php or not | [
"",
"php",
"html",
""
] |
Im doing research on which one of these to use and I can't really find one that stands out. [Eaccelerator](http://eaccelerator.net/) is faster than [APC](http://pecl.php.net/apc), but APC is better maintained. [Xcache](http://xcache.lighttpd.net/) is faster but the others have easier syntax.
Anyone have recommendations on which to use and why? | APC is going to be included in PHP 6, and I'd guess it has been chosen for good reason :)
It's fairly easy to install and certainly speeds things up. | Check out benchmarks and comparisons:
[here](http://www.ducea.com/2006/10/30/php-accelerators/)
and [here](http://2bits.com/articles/benchmarking-drupal-with-php-op-code-caches-apc-eaccelerator-and-xcache-compared.html)
and [there](http://2bits.com/articles/benchmarking-apc-vs-eaccelerator-using-drupal.html) | apc vs eaccelerator vs xcache | [
"",
"php",
"apc",
"opcode-cache",
"xcache",
"eaccelerator",
""
] |
Running this code:
```
_foo = MockRepository.GenerateStub<IBar>();
_foo.Stub(x => x.Foo()).Return("sdf");
```
When
```
public interface IBar
{
string Foo();
}
public class Bar : IBar
{
public string Foo()
{
throw new NotImplementedException();
}
}
```
throws NotSupportedException - "Can't create mocks of sealed classes". I understand why you can't mock a sealed class (although there are solutions in TypeMock), but what's the problem with mocking a class that returns a sealed class (string) ? | Rhino Mocks appears to be catching and handling this exception. You only see it in the VS.NET Debugger if you've enabled exceptions as breakpoints. It appears that you can safely continue running past this exception breakpoint and it all works as expected. | This happens when you have NOT got "Just my code" enabled under Tools->Options->Debugging->General, and you have CLR exceptions, "Thrown" selected under Debug->Exceptions. Easiest way to fix it is enable "just my code" under Tools->Options->Debugging->General.
 | Mocking a method that returns a sealed class in RhinoMocks | [
"",
"c#",
"mocking",
"rhino-mocks",
"stub",
"sealed",
""
] |
I just wrote some code to scale a font to fit within (the length of) a rectangle. It starts at 18 width and iterates down until it fits.
This seems horribly inefficient, but I can't find a non-looping way to do it.
This line is for labels in a game grid that scales, so I can't see a work-around solution (wrapping, cutting off and extending past the rectangle are all unacceptable).
It's actually pretty quick, I'm doing this for hundreds of rectangles and it's fast enough to just slow it down a touch.
If nobody comes up with anything better, I'll just load the starting guess from a table (so that it's much closer than 18) and use this--except for the lag it works great.
```
public Font scaleFont(String text, Rectangle rect, Graphics g, Font pFont) {
float nextTry=18.0f;
Font font=pFont;
while(x > 4) {
font=g.getFont().deriveFont(nextTry);
FontMetrics fm=g.getFontMetrics(font);
int width=fm.stringWidth(text);
if(width <= rect.width)
return font;
nextTry*=.9;
}
return font;
}
``` | Semi-pseudo code:
```
public Font scaleFont(
String text, Rectangle rect, Graphics g, Font font) {
float fontSize = 20.0f;
font = g.getFont().deriveFont(fontSize);
int width = g.getFontMetrics(font).stringWidth(text);
fontSize = (rect.width / width ) * fontSize;
return g.getFont().deriveFont(fontSize);
}
```
---
A derivation that iterates:
```
/**
* Adjusts the given {@link Font}/{@link String} size such that it fits
* within the bounds of the given {@link Rectangle}.
*
* @param label Contains the text and font to scale.
* @param dst The bounds for fitting the string.
* @param graphics The context for rendering the string.
* @return A new {@link Font} instance that is guaranteed to write the given
* string within the bounds of the given {@link Rectangle}.
*/
public Font scaleFont(
final JLabel label, final Rectangle dst, final Graphics graphics ) {
assert label != null;
assert dst != null;
assert graphics != null;
final var font = label.getFont();
final var text = label.getText();
final var frc = ((Graphics2D) graphics).getFontRenderContext();
final var dstWidthPx = dst.getWidth();
final var dstHeightPx = dst.getHeight();
var minSizePt = 1f;
var maxSizePt = 1000f;
var scaledFont = font;
float scaledPt = scaledFont.getSize();
while( maxSizePt - minSizePt > 1f ) {
scaledFont = scaledFont.deriveFont( scaledPt );
final var layout = new TextLayout( text, scaledFont, frc );
final var fontWidthPx = layout.getVisibleAdvance();
final var metrics = scaledFont.getLineMetrics( text, frc );
final var fontHeightPx = metrics.getHeight();
if( (fontWidthPx > dstWidthPx) || (fontHeightPx > dstHeightPx) ) {
maxSizePt = scaledPt;
}
else {
minSizePt = scaledPt;
}
scaledPt = (minSizePt + maxSizePt) / 2;
}
return scaledFont.deriveFont( (float) Math.floor( scaledPt ) );
}
```
Imagine you want to add a label to a component that has rectangular bounds `r` such that the label completely fills the component's area. One could write:
```
final Font DEFAULT_FONT = new Font( "DejaVu Sans", BOLD, 12 );
final Color COLOUR_LABEL = new Color( 33, 33, 33 );
// TODO: Return a valid container component instance.
final var r = getComponent().getBounds();
final var graphics = getComponent().getGraphics();
final int width = (int) r.getWidth();
final int height = (int) r.getHeight();
final var label = new JLabel( text );
label.setFont( DEFAULT_FONT );
label.setSize( width, height );
label.setForeground( COLOUR_LABEL );
final var scaledFont = scaleFont( label, r, graphics );
label.setFont( scaledFont );
``` | Change all width variables to float instead of int for better result.
```
public static Font scaleFontToFit(String text, int width, Graphics g, Font pFont)
{
float fontSize = pFont.getSize();
float fWidth = g.getFontMetrics(pFont).stringWidth(text);
if(fWidth <= width)
return pFont;
fontSize = ((float)width / fWidth) * fontSize;
return pFont.deriveFont(fontSize);
}
``` | Need a way to scale a font to fit a rectangle | [
"",
"java",
"graphics",
"fonts",
"awt",
""
] |
From a given Date I need to calculate midnight of its day. Here's what I came up with. It's so ugly that I figure there must be a better way.
```
private Date day(Date creation) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(creation);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
```
Suggestions?
Kent | You should consider the built-in date API obselete. Instead use the Joda date and time API.
Here's a drop-in replacement for your method.
```
private Date day(Date creation) {
return new DateMidnight(creation).toDate();
}
```
Here's a simple test:
```
public static void main(String[] args) {
final Date creation = new Date();
final Date midnight = new Foobar().day(creation);
System.out.println("creation = " + creation);
System.out.println("midnight = " + midnight);
}
```
The output is:
```
creation = Sun May 31 10:09:38 CEST 2009
midnight = Sun May 31 00:00:00 CEST 2009
``` | [JODA](http://joda-time.sourceforge.net/) might have a better solution, at the cost of another dependency on a library. I'm looking at its [DateMidnight property](http://joda-time.sourceforge.net/api-release/index.html). I'm sorry that I can't answer more authoritatively, but I'm not a JODA user myself. | Calculating a day given a Date | [
"",
"java",
"date",
""
] |
Let's say your Java program is taking 100% CPU. It has 50 threads. You need to find which thread is guilty. I have not found a tool that can help. Currently I use the following very time consuming routine:
1. Run `jstack <pid>`, where pid is the process id of a Java process. The easy way to find it is to run another utility included in the JDK - `jps`. It is better to redirect jstack's output to a file.
2. Search for "runnable" threads. Skip those that wait on a socket (for some reason they are still marked runnable).
3. Repeat steps 1 and 2 a couple of times and see if you can locate a pattern.
Alternatively, you could attach to a Java process in Eclipse and try to suspend threads one by one, until you hit the one that hogs CPU. On a one-CPU machine, you might need to first reduce the Java process's priority to be able to move around. Even then, Eclipse often isn't able to attach to a running process due to a timeout.
I would have expected Sun's `visualvm` tool to do this.
Does anybody know of a better way? | Try looking at the [Hot Thread Detector plugin for visual VM](http://java.dzone.com/news/porting-hot-thread-detector-vi) -- it uses the ThreadMXBean API to take multiple CPU consumption samples to find the most active threads. It's based on [a command-line equivalent from Bruce Chapman](https://web.archive.org/web/20111225025057/http://weblogs.java.net/blog/brucechapman/archive/2008/03/hot_threads.html) which might also be useful. | Identifying which Java Thread is consuming most CPU in production server.
Most (if not all) productive systems doing anything important will use more than 1 java thread. And when something goes crazy and your cpu usage is on 100%, it is hard to identify which thread(s) is/are causing this. Or so I thought. Until someone smarter than me showed me how it can be done. And here I will show you how to do it and you too can amaze your family and friends with your geek skills.
**A Test Application**
In order to test this, we need a test application. So I will give you one. It consists of 3 classes:
* A `HeavyThread` class that does something CPU intensive (computing MD5 hashes)
* A `LightThread` class that does something not-so-cpu-intensive (counting and sleeping).
* A `StartThreads` class to start 1 cpu intensive and several light threads.
Here is code for these classes:
```
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
/**
* thread that does some heavy lifting
*
* @author srasul
*
*/
public class HeavyThread implements Runnable {
private long length;
public HeavyThread(long length) {
this.length = length;
new Thread(this).start();
}
@Override
public void run() {
while (true) {
String data = "";
// make some stuff up
for (int i = 0; i < length; i++) {
data += UUID.randomUUID().toString();
}
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
// hash the data
digest.update(data.getBytes());
}
}
}
import java.util.Random;
/**
* thread that does little work. just count & sleep
*
* @author srasul
*
*/
public class LightThread implements Runnable {
public LightThread() {
new Thread(this).start();
}
@Override
public void run() {
Long l = 0l;
while(true) {
l++;
try {
Thread.sleep(new Random().nextInt(10));
} catch (InterruptedException e) {
e.printStackTrace();
}
if(l == Long.MAX_VALUE) {
l = 0l;
}
}
}
}
/**
* start it all
*
* @author srasul
*
*/
public class StartThreads {
public static void main(String[] args) {
// lets start 1 heavy ...
new HeavyThread(1000);
// ... and 3 light threads
new LightThread();
new LightThread();
new LightThread();
}
}
```
Assuming that you have never seen this code, and all you have a PID of a runaway Java process that is running these classes and is consuming 100% CPU.
First let's start the `StartThreads` class.
```
$ ls
HeavyThread.java LightThread.java StartThreads.java
$ javac *
$ java StartThreads &
```
At this stage a Java process is running should be taking up 100 cpu. In my top I see:

In top press Shift-H which turns on Threads. The man page for top says:
```
-H : Threads toggle
Starts top with the last remembered 'H' state reversed. When
this toggle is On, all individual threads will be displayed.
Otherwise, top displays a summation of all threads in a
process.
```
And now in my top with Threads display turned ON i see:

And I have a `java` process with PID `28294`. Lets get the stack dump of this process using `jstack`:
```
$ jstack 28924
2010-11-18 13:05:41
Full thread dump Java HotSpot(TM) 64-Bit Server VM (17.0-b16 mixed mode):
"Attach Listener" daemon prio=10 tid=0x0000000040ecb000 nid=0x7150 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"DestroyJavaVM" prio=10 tid=0x00007f9a98027800 nid=0x70fd waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Thread-3" prio=10 tid=0x00007f9a98025800 nid=0x710d waiting on condition [0x00007f9a9d543000]
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at LightThread.run(LightThread.java:21)
at java.lang.Thread.run(Thread.java:619)
"Thread-2" prio=10 tid=0x00007f9a98023800 nid=0x710c waiting on condition [0x00007f9a9d644000]
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at LightThread.run(LightThread.java:21)
at java.lang.Thread.run(Thread.java:619)
"Thread-1" prio=10 tid=0x00007f9a98021800 nid=0x710b waiting on condition [0x00007f9a9d745000]
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at LightThread.run(LightThread.java:21)
at java.lang.Thread.run(Thread.java:619)
"Thread-0" prio=10 tid=0x00007f9a98020000 nid=0x710a runnable [0x00007f9a9d846000]
java.lang.Thread.State: RUNNABLE
at sun.security.provider.DigestBase.engineReset(DigestBase.java:139)
at sun.security.provider.DigestBase.engineUpdate(DigestBase.java:104)
at java.security.MessageDigest$Delegate.engineUpdate(MessageDigest.java:538)
at java.security.MessageDigest.update(MessageDigest.java:293)
at sun.security.provider.SecureRandom.engineNextBytes(SecureRandom.java:197)
- locked <0x00007f9aa457e400> (a sun.security.provider.SecureRandom)
at sun.security.provider.NativePRNG$RandomIO.implNextBytes(NativePRNG.java:257)
- locked <0x00007f9aa457e708> (a java.lang.Object)
at sun.security.provider.NativePRNG$RandomIO.access$200(NativePRNG.java:108)
at sun.security.provider.NativePRNG.engineNextBytes(NativePRNG.java:97)
at java.security.SecureRandom.nextBytes(SecureRandom.java:433)
- locked <0x00007f9aa4582fc8> (a java.security.SecureRandom)
at java.util.UUID.randomUUID(UUID.java:162)
at HeavyThread.run(HeavyThread.java:27)
at java.lang.Thread.run(Thread.java:619)
"Low Memory Detector" daemon prio=10 tid=0x00007f9a98006800 nid=0x7108 runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"CompilerThread1" daemon prio=10 tid=0x00007f9a98004000 nid=0x7107 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"CompilerThread0" daemon prio=10 tid=0x00007f9a98001000 nid=0x7106 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Signal Dispatcher" daemon prio=10 tid=0x0000000040de4000 nid=0x7105 runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Finalizer" daemon prio=10 tid=0x0000000040dc4800 nid=0x7104 in Object.wait() [0x00007f9a97ffe000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00007f9aa45506b0> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118)
- locked <0x00007f9aa45506b0> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159)
"Reference Handler" daemon prio=10 tid=0x0000000040dbd000 nid=0x7103 in Object.wait() [0x00007f9a9de92000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00007f9aa4550318> (a java.lang.ref.Reference$Lock)
at java.lang.Object.wait(Object.java:485)
at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:116)
- locked <0x00007f9aa4550318> (a java.lang.ref.Reference$Lock)
"VM Thread" prio=10 tid=0x0000000040db8800 nid=0x7102 runnable
"GC task thread#0 (ParallelGC)" prio=10 tid=0x0000000040d6e800 nid=0x70fe runnable
"GC task thread#1 (ParallelGC)" prio=10 tid=0x0000000040d70800 nid=0x70ff runnable
"GC task thread#2 (ParallelGC)" prio=10 tid=0x0000000040d72000 nid=0x7100 runnable
"GC task thread#3 (ParallelGC)" prio=10 tid=0x0000000040d74000 nid=0x7101 runnable
"VM Periodic Task Thread" prio=10 tid=0x00007f9a98011800 nid=0x7109 waiting on condition
JNI global references: 910
```
From my top I see that the PID of the top thread is `28938`. And `28938` in hex is `0x710A`. Notice that in the stack dump, each thread has an `nid` which is dispalyed in hex. And it just so happens that `0x710A` is the id of the thread:
```
"Thread-0" prio=10 tid=0x00007f9a98020000 nid=0x710a runnable [0x00007f9a9d846000]
java.lang.Thread.State: RUNNABLE
at sun.security.provider.DigestBase.engineReset(DigestBase.java:139)
at sun.security.provider.DigestBase.engineUpdate(DigestBase.java:104)
at java.security.MessageDigest$Delegate.engineUpdate(MessageDigest.java:538)
at java.security.MessageDigest.update(MessageDigest.java:293)
at sun.security.provider.SecureRandom.engineNextBytes(SecureRandom.java:197)
- locked <0x00007f9aa457e400> (a sun.security.provider.SecureRandom)
at sun.security.provider.NativePRNG$RandomIO.implNextBytes(NativePRNG.java:257)
- locked <0x00007f9aa457e708> (a java.lang.Object)
at sun.security.provider.NativePRNG$RandomIO.access$200(NativePRNG.java:108)
at sun.security.provider.NativePRNG.engineNextBytes(NativePRNG.java:97)
at java.security.SecureRandom.nextBytes(SecureRandom.java:433)
- locked <0x00007f9aa4582fc8> (a java.security.SecureRandom)
at java.util.UUID.randomUUID(UUID.java:162)
at HeavyThread.run(HeavyThread.java:27)
at java.lang.Thread.run(Thread.java:619)
```
And so you can confirm that the thread which is running the `HeavyThread` class is consuming most CPU.
In read world situations, it will probably be a bunch of threads that consume some portion of CPU and these threads put together will lead to the Java process using 100% CPU.
Summary
* Run top
* Press Shift-H to enable Threads View
* Get PID of the thread with highest CPU
* Convert PID to HEX
* Get stack dump of java process
* Look for thread with the matching HEX PID. | Which Java thread is hogging the CPU? | [
"",
"java",
"multithreading",
"cpu",
""
] |
I need to remove a subtree in the Windows registry under Windows Mobile 6. The RegDeleteTree function is not available, and SHDeleteKey is (apparently) not available in any static library under the WM6 SDK, though the declaration is available in shlwapi.h.
I tried to get it from shlwapi.dll, like
```
typedef DWORD (__stdcall *SHDeleteKey_Proc) (HKEY, LPCWSTR);
SHDeleteKey_Proc procSHDeleteKey;
HINSTANCE shlwapidll = ::LoadLibrary(_T("shlwapi.dll"));
if(shlwapidll) {
procSHDeleteKey =
(SHDeleteKey_Proc)GetProcAddress(shlwapidll,_T("SHDeleteKeyW"));
ASSERT(procSHDeleteKey);
}
```
But I hit the assert.
Is there a nice way to delete, recursively, a Registry key (empty or not) under Windows Mobile? | I guess I found the answer myself in [MSDN](http://msdn.microsoft.com/en-us/library/ms724235(VS.85).aspx). It puzzles me that the functionality is not available through the SDK, though...
I put the code from MSDN here as well, just for the record:
```
//*************************************************************
//
// RegDelnodeRecurse()
//
// Purpose: Deletes a registry key and all it's subkeys / values.
//
// Parameters: hKeyRoot - Root key
// lpSubKey - SubKey to delete
//
// Return: TRUE if successful.
// FALSE if an error occurs.
//
//*************************************************************
BOOL RegDelnodeRecurse (HKEY hKeyRoot, LPTSTR lpSubKey)
{
LPTSTR lpEnd;
LONG lResult;
DWORD dwSize;
TCHAR szName[MAX_PATH];
HKEY hKey;
FILETIME ftWrite;
// First, see if we can delete the key without having
// to recurse.
lResult = RegDeleteKey(hKeyRoot, lpSubKey);
if (lResult == ERROR_SUCCESS)
return TRUE;
lResult = RegOpenKeyEx (hKeyRoot, lpSubKey, 0, KEY_READ, &hKey);
if (lResult != ERROR_SUCCESS)
{
if (lResult == ERROR_FILE_NOT_FOUND) {
printf("Key not found.\n");
return TRUE;
}
else {
printf("Error opening key.\n");
return FALSE;
}
}
// Check for an ending slash and add one if it is missing.
lpEnd = lpSubKey + lstrlen(lpSubKey);
if (*(lpEnd - 1) != TEXT('\\'))
{
*lpEnd = TEXT('\\');
lpEnd++;
*lpEnd = TEXT('\0');
}
// Enumerate the keys
dwSize = MAX_PATH;
lResult = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL,
NULL, NULL, &ftWrite);
if (lResult == ERROR_SUCCESS)
{
do {
StringCchCopy (lpEnd, MAX_PATH*2, szName);
if (!RegDelnodeRecurse(hKeyRoot, lpSubKey)) {
break;
}
dwSize = MAX_PATH;
lResult = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL,
NULL, NULL, &ftWrite);
} while (lResult == ERROR_SUCCESS);
}
lpEnd--;
*lpEnd = TEXT('\0');
RegCloseKey (hKey);
// Try again to delete the key.
lResult = RegDeleteKey(hKeyRoot, lpSubKey);
if (lResult == ERROR_SUCCESS)
return TRUE;
return FALSE;
}
//*************************************************************
//
// RegDelnode()
//
// Purpose: Deletes a registry key and all it's subkeys / values.
//
// Parameters: hKeyRoot - Root key
// lpSubKey - SubKey to delete
//
// Return: TRUE if successful.
// FALSE if an error occurs.
//
//*************************************************************
BOOL RegDelnode (HKEY hKeyRoot, LPTSTR lpSubKey)
{
TCHAR szDelKey[MAX_PATH*2];
StringCchCopy (szDelKey, MAX_PATH*2, lpSubKey);
return RegDelnodeRecurse(hKeyRoot, szDelKey);
}
``` | The second argument of `GetProcAddress` is a `LPCSTR` (that is, it is *not* a `LPCTSTR`). So remove the `_T()` and try this:
```
GetProcAddress(shlwapidll, "SHDeleteKeyW");
```
Does that help solve the problem? | Delete a registry key recursively | [
"",
"c++",
"windows-mobile",
"registry",
""
] |
What's the real difference between declaring an array like this:
```
var myArray = new Array();
```
and
```
var myArray = [];
``` | There is a difference, but there is no difference in that example.
Using the more verbose method: `new Array()` does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:
```
x = new Array(5);
alert(x.length); // 5
```
To illustrate the different ways to create an array:
```
var a = [], // these are the same
b = new Array(), // a and b are arrays with length 0
c = ['foo', 'bar'], // these are the same
d = new Array('foo', 'bar'), // c and d are arrays with 2 strings
// these are different:
e = [3] // e.length == 1, e[0] == 3
f = new Array(3), // f.length == 3, f[0] == undefined
;
```
Another difference is that when using `new Array()` you're able to set the size of the array, which affects the stack size. This can be useful if you're getting stack overflows ([Performance of Array.push vs Array.unshift](https://stackoverflow.com/q/44031591/930998)) which is what happens when the size of the array exceeds the size of the stack, and it has to be re-created. So there can actually, depending on the use case, be a performance increase when using `new Array()` because you can prevent the overflow from happening.
As pointed out in [this answer](https://stackoverflow.com/a/44471705/930998), `new Array(5)` will not actually add five `undefined` items to the array. It simply adds space for five items. Be aware that using `Array` this way makes it difficult to rely on `array.length` for calculations. | The difference between creating an array with the implicit array and the array constructor is subtle but important.
When you create an array using
```
var a = [];
```
You're telling the interpreter to create a new runtime array. No extra processing necessary at all. Done.
If you use:
```
var a = new Array();
```
You're telling the interpreter, I want to call the constructor "`Array`" and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.
You may think "Well, this doesn't matter at all. They're the same!". Unfortunately you can't guarantee that.
Take the following example:
```
function Array() {
this.is = 'SPARTA';
}
var a = new Array();
var b = [];
alert(a.is); // => 'SPARTA'
alert(b.is); // => undefined
a.push('Woa'); // => TypeError: a.push is not a function
b.push('Woa'); // => 1 (OK)
```
In the above example, the first call will alert 'SPARTA' as you'd expect. The second will not. You will end up seeing undefined. You'll also note that b contains all of the native Array object functions such as `push`, where the other does not.
While you may expect this to happen, it just illustrates the fact that `[]` is not the same as `new Array()`.
It's probably best to just use `[]` if you know you just want an array. I also do not suggest going around and redefining Array... | What’s the difference between "Array()" and "[]" while declaring a JavaScript array? | [
"",
"javascript",
"arrays",
"declaration",
""
] |
What should I learn to develop software for iPhone?
Thanks | [Beginning Objective C for the C# guy](http://scottcreynolds.com/archive/2009/02/05/beginning-objective-c-for-the-c-guy.aspx) | Learn Objective C. | How can a C# programmer build software for iPhone? | [
"",
"c#",
"iphone",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.