Thursday, April 28, 2011

In C++, are changes to pointers passed to a function reflected in the calling function?

If I pass a pointer P from function f1 to function f2, and modify the contents of P in f2, will these modifications be reflected in f1 automatically?

For example, if I need to delete the first node in a linked list:

void f2( Node *p)
{
    Node *tmp = p;
    p = p -> next;
    delete tmp;
}

Will the changes made to P be reflected in the calling function, or will it now point to a memory space that has been deallocated?

( My intuitive answer here is no, changes are not reflected. However, good sources tell me that the above code will work. Can someone take the time to give the answer and explain the reasoning behind it also please? Also, if the above code is faulty, how can we achieve this without using a return type? )

From stackoverflow
  • If I pass a pointer P from function f1 to function f2, and modify the contents of P in f2, will these modifications be reflected in f1 automatically?

    No. Since C and C++ implement pass-by-value, the value of the pointer is copied when it’s passed to the function. Only that local copy is modified, and the value is not copied back when the function is left (this would be copy-by-reference which a few languages support).

    If you want the original value to be modified, you need to pass a reference to the pointer, i.e. change your signature of f2 to read:

    void f2( Node*& p)
    

    However, your f2 not only changes the pointer p, it also changes its underlying value (= the value being pointed to) by using delete. That change is indeed visible to the caller.

    Bart van Ingen Schenau : In addition: If you want to have a value changed in C, your only option is to pass the address. i.e. `void f2( Node** p)`.
    Steve Jessop : "it also changes its underlying value": here "underlying value" == "referand"?
    Konrad Rudolph : @Steve: underlying value == pointee (== referand?).
    Steve Jessop : Yes. If we want to be pedantic, the high-faluting technical term used in 3.7.3.2/4 of the standard is "the storage referenced by the pointer" ;-)
  • This will work, althrough not the way you want to.

    If you call it like:

    Node* mynode = new Node(); /*fill data*/
    f2(mynode);
    

    -> there will be the content of mynode undefined.

    it will pass the value of the pointer to another function, and the value (p) will be local for function f2. If you want to modify it, use this way:

    Node* mynode = new Node(); /*fill data*/
    f2(&mynode);
    
    void f2(Node** p)
    {
     Node* tmp = *p;
     *p = (*p)->next;
     delete tmp;
    }
    
    Konrad Rudolph : No, it’s not undefined – it just remains unchanged (or do you mean “pointee” by “content”?).
    Steve Jessop : The value is unchanged, but using that value as a pointer in any way (for example comparing it to another pointer value including a null pointer) is undefined. By examining it byte-by-byte, you could validly observe that the representation hasn't changed.
    Konrad Rudolph : @Steve: since it’s so much fun …: Using the pointer in a comparison is *only* undefined if it doesn’t point to the element of an array (or one past the last element of the array). ;-) So yes, this example code would indeed be invalid – provided `new` isn’t overloaded to allocate storage from inside an array buffer.
    Steve Jessop : @Konrad: touché. My unstated assumption is that `delete` calls a standard deallocation function on its operand.

iPhone programming: Inserting labels between sentences

I have an interesting UI where a table view contains some lines of text. There are certain words in each line that I need to highlight and those words can be selected to render some tooltip.

I thought of using labels for these words so I can highlight them and also capture any touch events. But I couldn't find a way of achieving a flow layout.

Is there a better approach to do this?

Thanks in advance for the help!

From stackoverflow
  • A UIWebView would certainly handle the layout problem, but may cause other performance issues, especially if you're putting it in a table view.

    You might also look at the NSString (UIStringDrawing) methods, which are helpful for measuring and drawing text. They're quite powerful actually, allowing you to specify size constraints and line break modes.

    Mansi : Thanks. I will try it out. Is there a sample app that I can refer to?
    Brian : @Mansi, sorry, none that I'm aware of
    Mansi : Go for three20 library!

Adding \000 to each char in a password string

Why would one do this.

for ($i = 0; $i < $len; $i++) {
    $unicodepassword .= "{$passwd{$i}}\000";
}

Context: This is a password set when creating or modifying a user in Active directory. We are rewriting some ancient code and nothing works without this. Making changes in our LDAP does not require this kind of "encoding".

Also the result of this exercise is called "unicodepassword", seems strange to me.

From stackoverflow
  • Also the result of this exercise is called "unicodepassword", seems strange to me.

    This is actually a simple conversion from ASCII to UTF-16 (little endian). For characters > #127, it will translate into a unicode code point whose value is the same as ord($passwd{$i}) (so it will depend on the encoding of the original password).

    leChuck : It might explain why this has worked through our transition from ISO to UTF8. Non ASCII characters were never allowed.

What is the most efficient way to generate unique pseudo-random numbers?

Possible Duplicate:
Create Random Number Sequence with No Repeats

I'm trying to generate unique session IDs. Each session ID is a random integer. The main requirement is that each session ID is unique. I'm trying to find the most efficient algorithm to do this.

Scenario: Generate 10 random numbers from 1 to 10 inclusive.

My algorithm:

// Generate unique pseudo-random numbers between 1 and 10 inclusive

vector<int> vList;

for (int i = 1; i <= 10; i++)
{
    vList.push_back(i); 
}

// vList should have {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

for (int j = 1; j <= 10; j++)
{
    int k = (rand() % vList.size());
    cout << vList[k] << " ";
    vList.erase(vList.begin() + k);
}

// Sample output: 5 1 10 7 8 2 4 9 3 6

This algorithm has a time complexity of O(n) and a space complexity of O(n). Is there a more efficient algorithm?

From stackoverflow
  • Choose two large primes(a,b : a < b).

    For the n:th ID (n < b) the ID is a^n mod b.

    This will always give n unique pseudorandom numbers.

Creating Android apps without Java

I'd like to start creating Android apps but I don't like Java. I read that scala can be used to do it. Are there another option?(Clojure?)

I'm a Python/Django developer so it would be great to learn a pretty different language.

From stackoverflow
  • At this point Scala is the one that is most mature..I wanted to try groovy myself but its not even out of alpha..

    Plus Scala on android has docs..:)

    Radtoo : http://github.com/jberkel/android-plugin <- I recommend this if you wonder how you might start developing scala for android. It requires simple-build-tool, it provides you with a solution to compile, test, proguard-optimize and install (in the emulator or device) android applications with scala or java. Even automatically on code change (~install-emulator).
  • Appcelerator Titanium is an awesome environment for using web-ish skills (like HTML, CSS, and JavaScript) to build native apps for Android (and iPhone, and desktops, etc.). For example, the gang at Intridea have made several popular Android & iPhone apps with Titanium Mobile, including the OilReporter app that has been used for gathering data on the extent of the Gulf oil spill.

  • If you use Python, maybe SL4A (Scripting Layer for Android) is a good choice.

    You could write python script that runs on Android and use Android API, but it also has a drawback that you need install Python/SL4A runtime library on your Android device.

  • Another immature implementation is JRuby/Ruboto: http://blog.danieljackoway.com/first-ruboto-release.html

  • In addition to the other solutions listed here previously, you have:

    • PhoneGap
    • Rhodes
    • AIR (pre-release)
    • AppInventor
    • Clojure
  • for clojure development a useful tutorial: http://riddell.us/ClojureAndAndroidWithEmacsOnUbuntu.html

    Clojure gets a LOT of benefit from android-2.2's JIT compiler and has not really been widely adopted on previous versions.

  • It's not hard to do with Mirah. Mirah is a very young language that compiles to bytecode that's basically indistinguishable from Java, but adds some great new features like closures, type inference, and ruby-like syntax. It's particularly well-suited for Android because it has no runtime outside the JDK, whereas basically all other JVM languages bring along a lot of baggage, especially languages that weren't designed to target the JVM (like Ruby and Python).

    http://github.com/technomancy/Garrett

    Much nicer than writing Java! (Mirah used to be called Duby.)

When to Use Virtual Objects in QTP?

When to Use Virtual Objects?

From stackoverflow
  • I would use them only if all other approaches failed. Virtual Objects are based on relative coordinates, the properties that are quite unstable. That is maintanance cost is high. I even prefer using keyboard navigation to Virtual objects.

    Prime : @katmoon could you give an example for virtual object usage, my purpose for learning how to use virtual objects, i read in help but i didn't understood that one. please provide one suitable example for virtual object
    katmoon : I don't have QTP right now. It's somewhere under Tools -> Virtual Object manager. There you can create virtual objects following the wizard. Then try to use the recorder to record a script that e.g. clicks the controls that you marked as virtual objects. You should get the virtual objects in the recorded script.
    Tom E : The example used in the QTP training class is the color palette in Paint.exe. The color palette is a single object, but in a test you would want to click individual colors as if they are discrete buttons. However, I agree with katmoon@ that you should only use virtual objects as a last resort. In fact, I have never used them on a real project.

add url to html extention Chrome

Hello,

I am starting to write a extention for chrome. For this extention I like to add automatically the url on the bar to an text field of my extention. When I click on my extention u popup shows a form with a field. The value must be set to the URL of the page i Visit.

I work normaly with Jquery, and maybe the answer can fit in the jquery.

I hope I enplane everything well and thank you for any answer

Update:

This must be the answer

     populateForm();
function populateForm() {
  chrome.tabs.getSelected(null,function(tab) {
    console.debug(tab);
    naam.value = tab.title;
    url.value = tab.url;
    }
    )};
From stackoverflow
  • Your brackets and parentheses are misplaced. Try using this:

    function populateForm() {
        chrome.tabs.getSelected(null, function (tab) {
            console.debug(tab);
            naam.value = tab.title;
            url.value = tab.url;
        });
    }
    populateForm();
    

How to extract specific values from auto-correlated data in MATLAB?

I have been working on extracting the peak values from a graph (see previous question) which looks like this:

alt text

but I have noticed that for some of the xcorr graphs I have been working on the values do not turn out as expected and they normally turn out looking more like this:

alt text

and this:

alt text

Instead of trying to pick the peak values like the code was doing in the first figure, how would I go about trying to pick the values where the downward slope momentarily evens itself out (as shown in Figure 3)?

When I try and run the code in its current state on data like the ones shown in Figure 2 & 3, I do not get any useful data back in return.

I think I need an if statement or similar in the 'find extrema points' section but I'm not sure whether that is correct or not. My .M code for the function looks like this so far:

[inputname, pathname] = uigetfile('*.wav', 'Select WAV-file');

thumb1 = inputname;               %# Get filename information
fprintf('\n%s is being turned into a 30s thumbnail...\n', thumb1);
fprintf('Please wait..!\n\n');
%# load the signal
[y, fs, nb] = wavread(thumb1);
y = mean(y,2);                               %# stereo, take avrg of 2 channels

%# Calculate frame energy
fWidth = round(fs*1);                    %# 10ms
numFrames = floor(length(y)/fWidth);
energy = zeros(1,numFrames);
for f=1:numFrames
  energy(f) = sum( y((f-1)*fWidth+1:f*fWidth).^2 );
end

%# smooth the signal (moving average with window size = 1% * length of data)
WINDOW_SIZE = round(length(energy) * 0.01);  %# 200
XX = filtfilt(ones(1,WINDOW_SIZE)/WINDOW_SIZE, 1, energy);

%# auto-correlation
[r,lags] = xcorr(XX, 'biased');

%# find extrema points
dr = diff(r);
eIdx = find(dr(1:end-1) .* dr(2:end) <= 0) + 1;

[~,loc] = sort(r(eIdx), 'descend');
loc = loc(1:min(3,end));                     %# take the highest 3 values

inf=lags( eIdx(loc) );

thumb=max(inf);

startrecord=round((thumb/1)*fs);
endrecord=round(((thumb+30)/1)*fs);

wavwrite(y(startrecord:endrecord), fs, nb, 'Temp1');
fprintf('The thumbnail of %s has been created.\n\n', thumb1);

Sorry that it all looks so messy, but I wanted to get some visual examples in!

From stackoverflow
  • Those are inflexion points, and if you take the first derivative of your data you will see those as big deviations from a pretty constant slope.

    Play with a boxcar average to do minimal smoothing and with the first derivative to find those inflexion points.

    Mark Spivey : Seeing as how there is already smoothing applied to the signal, I assume I should only be working on finding the first derivative? I've done a bit of looking around, but to be honest I'm not great at maths so a lot of what is being said is going straight over my head. I think I should be trying to use the gradient function to find the values though? Is that along the right lines?
    Marco : I am not familiar with mathlab. Try the gradient function on the data to see what it looks like. The inflection points will look like maxima/minima. The function should be flattish and positive before the peak, then cross the x-axis and be flattish and negative afterward.
  • I believe that it will be easier to find peaks in the negative value of the second derivative. Constant or nearly constant slope will result in 2nd-der =0; anything else, including your actual peaks and inflection points, will have a non-zero 2nd-der. By finding peaks in the negative values, you'll only get the positive peaks, not the negative peaks.

SQL Server - How to lock a table until a stored procedure finishes

I want to do this:

create procedure A as
  lock table a
  -- do some stuff unrelated to a to prepare to update a
  -- update a
  unlock table a
  return table b

Is something like that possible?

Ultimately I want my SQL server reporting services report to call procedure A, and then only show table a after the procedure has finished. (I'm not able to change procedure A to return table a).

From stackoverflow
  • Use the TABLOCKX lock hint for your transaction. See this article for more information on locking.

    David Moye : You could, alternatively, use UPDLOCK if it's okay for others to read the table while you're using it.
    Greg : Where does the transaction come in? Should I wrap my whole SP in a transaction?
    David Moye : For many SPs, it makes sense to begin a transaction at the beginning and commit it at the end. There are, of course, exceptions to this rule, but in general I find it a good practice.

only show X records in dropdown

hi is there a way with the code i have posted to only show a cretain amount of records in a dropdown list. i am not talking about the LIMIT 0,5 in mysql. i have 1000,s of records and it is causing IE to hang. firefox is quick. if someone could give me some guidance i would be grateful. thanks.

<p><fieldset><legend class="style8">Select a Box</legend>

      <select name="suggestTextField1" id="suggestTextField1">
      <option value="">Select a Box</option>
        <?php
do {  
?>
        <option value="<?php echo $row_rsSuggest1['boxref']?>"><?php echo $row_rsSuggest1['boxref']?></option>
        <?php
} while ($row_rsSuggest1 = mysql_fetch_assoc($rsSuggest1));
  $rows = mysql_num_rows($rsSuggest1);
  if($rows > 0) {
      mysql_data_seek($rsSuggest1, 0);
   $row_rsSuggest1 = mysql_fetch_assoc($rsSuggest1);
  }
?>
      </select>
      </fieldset>
      </p>


$colname_rsSuggest1 = "-1";
if (isset($_SESSION['kt_idcode_usr'])) {
  $colname_rsSuggest1 = (get_magic_quotes_gpc()) ? $_SESSION['kt_idcode_usr'] : addslashes($_SESSION['kt_idcode_usr']);
}
mysql_select_db($database_conn, $conn);
$query_rsSuggest1 = sprintf("SELECT DISTINCT `boxref` FROM `files` WHERE customer = '%s' AND boxstatus = 1 ORDER BY boxref ASC", $colname_rsSuggest1);
$rsSuggest1 = mysql_query($query_rsSuggest1, $conn) or die(mysql_error());
$row_rsSuggest1 = mysql_fetch_assoc($rsSuggest1);
$totalRows_rsSuggest1 = mysql_num_rows($rsSuggest1);
From stackoverflow
  • Unless you are using all the records later in the code, it is better to use a LIMIT clause. This will speed up your query and your script by extension. Look at some of the pagination scripts out there to get started.

  • You could change your do{}while() loop that is inserting the <option> to stop after 5 loops, but if you're only going to use 5 the better answer is to only fetch 5 from the database.

    Mr.Putersmit : sorry guys. i am not using 5. i only put that as example so you didn,t think i was looking for mysql limit option. thanks
    Robert : Well, no matter what your limit is, you should only query for what you'll use.
    Mr.Putersmit : i was perhaps thinking would it work to have say the first 100 records loaded and then bring in the next 100 or whatever when the user scrolls the list? if i use LIMIT how do i get the remaining records? thanks
    Robert : If you use limit you'd have to query again to get the next set of records. As others have mentioned a good option is to have paging, IE, you have some sort of interface that allows you to page between the results and replaces the current set of `
  •     $i = 0;
    while ( $i < x ) {
    $i++;
    echo the records
    }
    

    That'll work I think

  • You can accomplish by incorporating paging into your dropdown list. The idea is to only show a handful of items at a time and provide Back/Next buttons that allow the user to view more. This is most easily done with a third-party library, but you can also do it yourself with CSS and Ajax.

    Search for drop down lists with paging support. I haven't used PHP, so I can't point you to any good PHP libraries. There appears to be something at http://www.nitobi.com/products/combobox/paging/ that claims to be PHP compatible, but doesn't seem to work in Firefox. You might also have luck using the YUI Paginator (http://developer.yahoo.com/yui/paginator/) to build your own paging dropdown list.

    Another option is to add Ajax search support to your dropdown list. This will allow the user to type what they are searching for, reducing the list from thousands to, hopefully, something much smaller. This is fairly common, so you shouldn't have trouble finding libraries to do this.

  • thank you robert. any idea where i would start with that? i have searched google but couldn't find anything to modify. thanks

Default access rights of files and directories

I have an application that is installed on Vista PC's by a user with elevated user rights (and administrator via UAC elevation prompt).

The installer writes some files to a folder in the %APPDATA% folder.

When the user (without elevated user rights) run the application, the files (and created folders) in the shared %APPDATA% (c:\ProgramData in Vista) not Accessible.

The files are written by a 3rd party component. If the component is used without elevated user rights, the files er accessible (and writable).

I have tried to change the access rights the files are written without luck.

Is there a way to make the files default access right full control for everyone?

From stackoverflow
  • First, are you sure your installer is setting up the AppData for all users, and not just one? If the installer generates folders under one user's AppData folder, it doesn't matter how many rights you have on the system in general, you're not getting to that folder unless you're that user.

    Second, it sounds like your installer is writing the folder and/or files on behalf of the user performing the install, which would be an admin and thus requiring elevated privileges. There is a way to get and change the ACL permissions for a folder and/or a file. Perhaps a code snippet of what you're trying that doesn't work may help us help you.

    slugster : +1 i said the same in my comment but you were first :)
    Fedearne : The folder is the shared appdata (c:\ProgramData in Vista). The user running the installer is an administrator on behalf of the user via UAC elevation. I would like the files written c:\ProgramData to be accessible (writable) to the user afterwards. The user has write permission to c:\ProgramDat, but not the files written in it by the installer.
  • I solved the problem by creating a subfolder i c:\ProgramData, using the approach described here

    bool modified;
    DirectoryInfo directoryInfo = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MyFolder");
    DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
    FileSystemAccessRule rule = new FileSystemAccessRule(
        securityIdentifier,
        FileSystemRights.Write |
        FileSystemRights.ReadAndExecute |
        FileSystemRights.Modify,
        InheritanceFlags.ContainerInherit |
        InheritanceFlags.ObjectInherit,
        PropagationFlags.InheritOnly,
        AccessControlType.Allow);
    directorySecurity.ModifyAccessRule(AccessControlModification.Add, rule, out modified);
    directoryInfo.SetAccessControl(directorySecurity);
    

    Rules are inherited by subfolders and files. All files and folders created in "MyFolder" is writable to Users group.

PHP Lazy Load Iterator

I have an iterator class that loops over an array of objects and lazily loads from the database when it needs to (when it's not loaded into memory). Problem is this is iterating around 200,000 times and I found out from here: http://www.garfieldtech.com/blog/magic-benchmarks that the iterator interface is incredibly slow.

Would anyone know of a good way to lazy load without using an iterator interface?

From stackoverflow
  • You could use a plain old for loop.

    The iterator interface might be slow, but when doing 200.000 DB queries, chances are pretty good your bottleneck is not the iterator. I'd suggest to profile your code to see if it is really in need of optimization at this position.

    Premature Optimizatizion is the root of all evil :)

    Louis : Actually it will be doing about 10 queries. Each row holds serialized data of about 100 objects. I've done much profiling and this looks like the problem unless there are issues with array access times.
    Gordon : Well, switch to regular arrays then and use a for loop. Without seeing any code, this is the best idea I can offer.
  • Best solution was to use a for loop and a Singleton class with the indexes and iteration methods.

    Gordon : so you did what I suggested but then decided to provide your own answer for acceptance? Too kind.

Notify server to client via Web service

I made a WebService chat. At the client side I am running a thread to check periodically if there any new messages available.

I want to know is there are any way to notify clients via Web Service.

I found something call 'Solicit Response' related to web service. But I am not aware how it works.

Any help is appreciated. Thank you

From stackoverflow
  • In web services, the clients strictly request, they don't listen. What you need is some way for the server to "push" to the client. You're looking for something like Comet which isn't part of a web service per se.

    Edit

    Here's a relevant stackoverflow discussion.

    : thank you very much for your reply. As I know XMLHttpRequest(AJAX) can only used in web. My client is a forms application like gtalk/yahoo/msn. Actually is periodically checking for new message, that real way of working chat applications. I mean is it the way that famous gtalk also working ?
    Dave Aaron Smith : Oh, I see what you're saying. I don't know for sure, but I doubt other forms applications using "polling" (periodically checking for new messages). Usually chats are inactive so polling is inefficient. I imagine they open up a port and use "events" (waiting passively for messages). I'm not sure though.

PHP/PDO: use simple prepared statement with query return/affected rows?

I am new to PDO objects and cannot find a single piece of documentation that will help me. Say I got a simple code to delete a row:

$count = $dbh->exec("DELETE FROM fruit WHERE colour = 'red'");

That will return affected rows, but how would I use prepared statements with that? Can use use $dbh->prepare AND $dbh->exec or query !?

From stackoverflow
  • $dbh->prepare returns a PDOStatement object. You then call $stmt->execute to get the result.

    More info in the PDO manual

    Here's an example from the manual:

    <?php
    /* Execute a prepared statement by passing an array of insert values */
    $calories = 150;
    $colour = 'red';
    $stmt = $dbh->prepare('SELECT name, colour, calories
                           FROM fruit
                           WHERE calories < ? AND colour = ?');
    $stmt->execute(array($calories, $colour));
    ?>
    
    John : But how would I return number of rows affected? Can I use it like in my example, `$count = $stmt->execute`? EDIT: someone else answered it.
  • It should be the same as any other statement:

    $stmt = $dbh->prepare("DELETE FROM fruit WHERE colour = ?");
    $stmt->execute(array('red'));
    $count = $stmt->rowCount();
    

    The PDO Statement rowCount() should be what you are looking to do.

    EDIT

    Fixed by adding the ->rowCount() which will return the row count. ->execute in a statement will return a bool, true or false whether the query errored out or not. Of course all of this information is readily available at the PDO Statement Manual

    John : So `->execute` can return affected rows too, this is exactly what I needed. Thank you!
    Brad F Jacobs : No, I had an error before. The manual states that `->execute` returns a bool, but looking at the other functions in the manual, `->rowCount()` will provide the count.
    John : This would fit my code perfectly, and makes a lot more sense with the `->rowCount()` function in the end. Thanks again.

How can I get multi select dropdown box?

I have two dropdown box. 1st box having list of values. When I click add button the selected value from dropdown1 shift to dropdown2. Then when I click "add all" button all the values from list will shift from dropdown1 to dropdown2 through jQuery. Here I am having problem.

After add the values from box1 to box2 when I click submit button the scrolldown of dropdown is automaticaly scrolling one time then ly values ll be submit. How can I avoid this. Here they are adding the list of values one by one to another box... how can I avoid this.

For example:

var arr =[];
$('#'+selectedValues+' option').each(function (i,option){ arr[i]=$(option).val();
$('input[type=submit]').click(function(){ $('#'+selectedID).val(arr);
From stackoverflow

vb.net Getting a reference to a class by its name

Hello,

I'm trying to use reflection to get the instance of a class in vb.net. I have a class 'A' in my web project and to test it, i create a new aspx page and try to write the following:

Dim t as Type = Type.GetType("A")

This returns "Nothing". But if i do this:

Dim inst as A = new A()
Dim t as Type = inst.GetType()

t's type is "A"

So how come i can't get the type with GetType even if the name is exactly the same? It does works for things like System.Math though so i'm probably missing something as a newbie.

From stackoverflow
  • Two things:

    • You need to include the namespace of the type
    • If the type isn't in mscorlib or the currently executing assembly, you need to specify the assembly name as well (including version numbers and public key information if it's a strongly-named assembly).

    So for instance, to get hold of System.Linq.Enumerable you'd need something like:

    Type.GetType("System.Linq.Enumerable, System.Core, Version=4.0.0.0, " & _
                 "Culture=neutral, PublicKeyToken=b77a5c561934e089")
    
    Marius S. : I guess that's where i get confused. It's a web project and i've added it as a class to that project. There is no namespace defined for that class, although i've tried to defined it and ended up with the same result. So i guess it should be in the currently executing assembly, unless i'm missing something.
    Richard : @Maruis: If you follow your second code to get a `Type` instance from a real object you can use `Type.FullName` to see the complete name including namespace. In ASP.NET depending on WAP or WSP the assembly may be created dynamically (compile on demand), so use `Assembly.GetExecutingAssembly()`.
    Marius S. : That's exactly what i've done with the Type.FullName. I tried doing Type.GetType(realobjecttype.FullName) and it still returned Nothing.
    Jon Skeet : @Marius: Don't use FullName... use AssemblyQualifiedName.
    Marius S. : I tried, but when i typed "thetype.", i didn't get AssemblyQualifiedName in the popup list so i thought it wasn't available.

MAC OSX vim colors mangled

Here's my setup

  • Mac OSX 10.6
  • VIM (default version that comes with OSX 10.6)
  • rails.vim (installed in .vim/autoload)
  • ir_black.vim (installed in .vim/colors)
  • i have "colorscheme ir_black" and "syn on" in ~/.vimrc

Now when I go into terminal and edit a ruby file with vim my colors are messed up. There are only a few colors showing up and some text is even blinking. I'm wondering if there's a conflict between rails.vim syntax highlighting and the ir_black color scheme? Can anyone help me fix this? I would like to use the ir_black color scheme.

From stackoverflow
  • The Mac OSX Terminal.app in Snow Leopard does not support 256 colors, which is required for the ir_black theme (this is the theme I use).

    Download and try something like iTerm.app (http://iterm.sourceforge.net/), and you shouldn't have a problem with colors.

    Or you could use MacVim (http://code.google.com/p/macvim/)

    iljkj : Thank you for the answer. Is there a terminal command to see how many colors the current terminal supports? I googled but can't find anything.
    Bryan Ross : I can't find one either. I did find `infocmp`, however, that reports 256 colors in Terminal.app, which is incorrect.

Do methods ending with _! have a special meaning in Scala?

Do methods ending with _! such as delete_! or i_is_! have a special meaning? Are they "just names"? Do they follow some convention? There's even bulkDelete_!!. (The specific context is Lift if it makes a difference.)

From stackoverflow
  • There are no special meanings to the ! in Scala names. In the family of Lisp-based languages, ! is often used to indicate that a function is has side-effects, and that looks to be the convention here.

    retronym : Another similar convention is to use to use zero parameter lists for side-effect free functions, and one empty parameter list for others. e.g. `gun.model` vs `gun.fire()`
    OscarRyz : Ruby uses `!` for *side effects* also
  • I'm not sure what the convention is for using _! and _!! in Lift, but here's a bit of background.

    Any alphanumeric identifier can have _ and a list of symbols added and still be parsed as a single identifier. For example:

    scala> class Example_!@%*!
    defined class Example_$bang$at$percent$times$bang
    

    (In fact, you can parse almost anything as an identifier if you surround it with backticks--and this is what you do if a Java class uses a Scala reserved word, for example. Or if you want spaces in your identifiers.)

    The compiler only recognizes one symbolic ending specially, however. If there is a method that looks like a getter, then getter_= will be interpreted as a setter. (Whether you actually use it as a setter is up to you; it will have the semantics of a setter, anyway.) So

    scala> class Q { def q = "Hi"; def q_=(s: String) { println(s.reverse) } }
    defined class Q
    
    scala> val q = new Q
    q: Q = Q@b5c12e
    
    scala> q.q
    res0: java.lang.String = Hi
    
    scala> q.q = "Could use this to set something"
    gnihtemos tes ot siht esu dluoC
    

    In addition, the compiler reverses the order of caller and callee in any method that ends in :. This is most often seen in lists: newElement :: existingList is actually a call to existingList.::(newElement). So, for example:

    scala> object Caps { def to_:(s: String) = s.toUpperCase }
    defined module Caps
    
    scala> "Example" to_: Caps
    res40: java.lang.String = EXAMPLE
    

    Any other usage of _ + symbols is convention.

    aioobe : Wow. Great lecture. I knew almost none of this. Thanks!
    retronym : `_` is used to separate groups of word characters from symbol characters. So `foo_!!_bar` is a legal identifier. If you don't want to follow this rule, or need to use a reserved word, you can also enclose it in backticks. This is useful for calling java methods named `type`, for example.
    Rex Kerr : @retronym - Good point about backticks; I'll add that. Try typing `val foo_!!_bar = 0` into the REPL, though....
    retronym : Oh wow, my mental parser is out of sync with the spec. Please ignore. Identifers are basically `\w[\w\d]*(_([:opchar:]*))`
    OscarRyz : Mhh, So, I understand that it is not possible to type for instance `def sort!( ... ` but you would have to use: `def sort_!(...` is that correct?
    Rex Kerr : @S-mSO - That's right. `def sort!()` is invalid. `def sort_!()` is fine.
    aioobe : Ah, that's good to know.
    PhiLho : @retronym: more like `\w[\w\d]*(_([:opchar:]*))?|[:opchar:]+` I think (including $ but this one is reserved). Also I just found out that // and /* cannot be operators...
  • Strangely unmentioned thus far (though not particularly relevant to your question) is unary_! which is treated specially.

    scala> class A { def unary_! = 5 }
    defined class A
    
    scala> !(new A)
    res0: Int = 5
    

get current date and date after two months in php.

this is a very lame question but i m not able to find this one. How to get today's date and date after two months..

format is month-date-year (numerical.)

From stackoverflow
  • You can use the strtotime() function :

    $today = time();
    $twoMonthsLater = strtotime("+2 months", $today);
    
    // If what you really want is exactly 60 days later, then
    $sixtyDaysLater = strtotime("+60 days", $today);
    // ...or 8 weeks later :
    $eightWeeksLater = strtotime("+8 weeks", $today);
    

    In any case, the resulting new timestamps can then be converted to month-date-year :

    echo 'Today is : ' . date('m-d-Y', $today);
    echo 'Two months later will be : ' . date('m-d-Y', $twoMonthsLater);
    

    ** UPDATE **

    From the PHP manual

    Note: Please keep in mind that these functions are dependent on the locale settings of your server. Make sure to take daylight saving time (use e.g. $date = strtotime('+7 days', $date) and not $date += 7*24*60*60) and leap years into consideration when working with these functions.

    Just thought I should mention it...

  • Today:

    date('m-d-Y', time());

    Two months from now:

    date('m-d-Y', time() + (86400 * 60));

    Yanick Rochon : this is not true. '2010-02-01' (Feb. 1, 2010) + 60 days is not exactly two months later. And this does not take into account leap years, etc.

django: trying to access my robots.txt: "TypeError at /robots.txt 'str' object is not callable"

Exception Type: TypeError at /robots.txt

Exception Value: 'str' object is not callable

What gives?

Views:

ROBOTS_PATH = os.path.join(CURRENT_PATH, 'robots.txt')


def robots(request):
""" view for robots.txt file """
return HttpResponse(open(ROBOTS_PATH).read(), 'text/plain')

Settings:

CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))

URLs:

(r'^robots\.txt$', 'robots'),
From stackoverflow
  • Try:

    from appname.views import robots
    (r'^robots\.txt$', robots), 
    

    Or:

    (r'^robots\.txt$', 'projectname.appname.views.robots'),
    

    Django can't figure out where your 'robots' function is.

    pythondjango : Had to remove the quotations. Dumb error. You're the man.

How to setup APE server on windows.

Hi

Can any one help me set-up APE Server on windows machine... I have installed it in Ubuntu in Virtual Box. But can't access on host windows...

From stackoverflow

How can I compile C++ code using another C++ program?

I want to create a program that modifies another c++ source,compiles it and runs the exe. I mean with something like gcc may be I can but on a windows os gcc may not be present. Is it possible?

From stackoverflow
  • I think your options are fairly limited for windows:

    1. Check for an install of a compiler (possibly limit this to a short list) and use that compiler
    2. Bring along a compiler in your application's install package
  • Cowboy answer:

    Only if:

    • the source code doesn't need a lot of files/headers/libraries
    • they can be easily collected by your application
    • the application have connection with some server of yours

    The application could:

    • collect the files in a zip
    • send them over the wire to an compiler service (accesible vía HTTP)
    • the server compile it with its own installation
    • and return the binary executable inside the response.

    Of course: it depends on so many variables that seems not very feasible. And the zip+http thing could be difficult from a C/C++ app.

    Alexander Ivanov : hmm it can be slow...and it depends on internet connection. But it's interesting idea ;)
    Steve Jessop : +1 for audacity.
    helios : Thanks... anyway I was thinking on it and realized about managing zip and http in C... and it was not that nice... :S
    Steve Jessop : You can (should) grab a library for that sort of thing. Even so it's going to be more work than some languages. As it happens I have implemented both HTTP client and zip file writer libraries in the past: not in C but in a language at about the same level, so I was sitting on top of zlib and a Berkely-style sockets interface. I don't really recommend it, for a very simple http client it's not all that difficult, just very tedious. Use libcurl and libtar instead (tar since compression isn't actually essential here anyway, so keep it simple)...

Could you tell me where I can find specification of simple_item_list_1 or simple_item_list_2?

Could you tell me where I can find specification of simple_item_list_1 or simple_item_list_2? Or tell me how to use them both?

From stackoverflow
  • You can find these resources, and others, in your SDK. They are in $ANDROID_SDK/platforms/$VERSION/data/res, where $ANDROID_SDK is where you unpacked the SDK on your machine, and $VERSION is some Android version (e.g., android-8 for Android 2.2).

    kspacja : Okay. I can read source of this XML files, but I still don't know, what object I have to give to contructor of ArrayAdapter, when I use simple_list_item_2. For example, for simple_list_item_1, constructor of ArrayAdapter looks like this: new ArrayAdapter(this, android.R.layout.simple_list_item_1, new String[] {"Car", "Cat"});
    CommonsWare : @kspacja: `ArrayAdapter` doesn't support `simple_list_item_2`. Here is a sample project showing the user of `simple_list_item_1`: http://github.com/commonsguy/cw-android/tree/master/Selection/List/
    kspacja : How to do this with simple_list_item_1 I know. How do I know, that ArrayAdapter doesn't support simple_list_item_2? How do I know what support what?

AIR installer to install 3rd party app

Say I've got a working AIR app that needs to also bundle a driver (licensing okay) for some hardware that the app uses. Anyone know if its possible to launch the driver installer at the end of the app install?

I'm not finding good documentation on this and im wondering if there is a standard pre-install / post-install script I can create to handle stuff like this.

Thanks Stabby

From stackoverflow
  • You should be able to use the NativeProcess API to accomplish this.

    : Okay so I can launch processes, but my question is where to put this code to run when the installer runs - not every time the app runs. Is there a post-install hook somewhere, or a special place I can put NativeProcess code that only runs on the first install?
    Inigoesdr : Well, you have a few options. The easiest would be find a way to check to see if the program is already installed on launch, so it only gets installed when it's not already. For example, write a dummy text file after you finish the installer that you can check for in the AIR app. There is also the encrypted local storage you can use to store a flag that says the installer has already run. (https://www.adobe.com/devnet/air/ajax/articles/encrypted_local_store.html)
    : I see. This is not good - adding a bunch of logic to handle something that should be native to the AIR installer. You said "..after you finish the installer.." - how where you suggesting I run something after the installer?
    Inigoesdr : I originally interpreted your question as "I have a proprietary installer I made", but now that I read it again you didn't really say it like that. That said, you could use something like NSIS(http://nsis.sourceforge.net/Main_Page) to make your own, or wrap one that you are getting from a third party. It might just be easier to make an installer(via NSIS or similar) that runs your driver installer and then runs the .air file.

What AMF Servers Support Remote Shared Objects?

Greetings. I'm planning on building a Flex based multiplayer game, and I'm researching what will be required for the server end. I have PHP experience, so I started looking at ZendAMF.

Now in this game, I'll need the concept of rooms, and real time updates to clients in those rooms, so it looks like I'll be using remote shared objects (correct, yes?). I'm not seeing where ZendAMF can support this.

So I found this page: http://arunbluebrain.wordpress.com/2009/03/04/flex-frameworks-httpcorlanorg/

It seems to indicate that ZendAMF isn't going to do what I want. WebORB for PHP seems to be the only PHP based solution that does messaging, but on that page it doesn't mention "real-time" next to it like the Java based ones below it do.

What should I be looking at for the server piece with my requirements? Do I need to make the jump to something like BlazeDS and try to pick up a bit of Java knowledge?

Thanks.

From stackoverflow
  • Both ZendAmf and weborb use http long pulling. Think of it as pinging to check for updates. If you really need TRUE realtime push notification then PHP will not be your answer due to it not having threads or long running processes. WebOrb has several servers in other languages along with BlazeDS, RubyAMF, PyAmf, and of course LCDS from adobe that allows for true messaging.

    GrayB : Are BlazeDS and LCDS the only servers that support Shared Objects? I'm not seeing that RubyAMF supports this. Seems like it's in the same position as PHP
  • I think you already know the answer, but for other people looking into this as well:

    All *AMF solutions use HTTP as transfer protocol and can't have permanent connection. AMF is sent encoded through HTTP and then it's closed.

    When you want to use "real" real-time (RTMP,RTMPT), you have choices like: opensource: Red5 (Java), BlazeDS (Java), FluorineFX (.NET) commercial: Wowza Media Server (Java), WebORB (.NET and Java)

    David : For commercial servers, I think you forgot Flash Media Server
  • I'd highly reccommed flash media server if you have the cash. I've had good expereince with it in the past