text stringlengths 8 267k | meta dict |
|---|---|
Q: Run a script once an element changes How would I monitor an element, for example a picklist or updated form object, for any changes and then code once any change occurs?
A: $("#element").change(function(){
//do your stuff
});
will probably do it
A: By using jQuery's change method.
$('#element').change(function(){
// ...
});
A: $('#element-id').live('eventType', function(e) {
//do stuff here
});
The 'eventType' will be different based on the type of object '#element-id' is.
http://api.jquery.com/live/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Issue using Show Desktop with SetParent in WPF I am working on a simple active desktop replacement for a school that is migrating to Windows 7. The idea is to create a window with a few large buttons with pictures on so that young children who have trouble reading can use them.
I am using SetParent() to set my window's parent to 'Progman' so that it is always at the back and is not minimised when a user chooses to 'Show Desktop'. Everything works fine on Windows XP but on Windows 7 when users click 'Show Desktop' the window remains but the contents are replaced with the users Windows background. The buttons still work (you just can't see them) and if you resize or otherwise update the window they appear again. A picture of the problem:
Any ideas why this is happening? Does anyone know a way I could force a refresh of the window when 'Show Desktop' is pressed?
A: I suspect in your case your app is throwing an exception but not crashing. WPF apps have a tendency to do this if the exception is thrown during the ctor of some UI element. It can disrupt the rendering stack.
I tried to reproduce the problem but was unsuccessful. From my tests I was able to get the handle to 'Progman' and set the main window as the parent when using the Windows 7 basic theme (no Arrow glass).
When I used the Arrow theme, calling SetParent would cause the window to vanish. A little research turned up a possible fix. Instead of setting the parent as the 'Progman' window, you can try using the 'SysListView32' child (the child window used to hold the desktop icons).
The problem is obtaining 'SysListView32' isn't easy. It used to be a matter of traversing through 'Progman' to 'SHELLDLL_DefView' and then 'SysListView32', however, Windows 7 has changed that. 'SHELLDLL_DefView' is now a child of WorkerW.... some of the time.
Here is the best article I could find explaining this:
http://fernandomachadopirizen.wordpress.com/2010/08/09/give-me-a-handle-and-i-will-move-the-earth/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to retrieve the specific value from Dictionary(key,value) in c# This is my method:
/// <summary>
/// Uses Dictionary(Key,Value) where key is the property and value is the field name.
/// Matches the dictionary of mandatory fields with object properties
/// and checks whether the current object has values in it or
/// not.
/// </summary>
/// <param name="mandatoryFields">List of string - properties</param>
/// <param name="o">object of the current class</
/// <param name="message">holds the message for end user to display</param>
/// <returns>The name of the property</returns>
public static bool CheckMandatoryFields(Dictionary<string,string > mandatoryFields, object o,out StringBuilder message)
{
message = new StringBuilder();
if(mandatoryFields !=null && mandatoryFields.Count>0)
{
var sourceType = o.GetType();
var properties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Static);
for (var i = 0; i < properties.Length; i++)
{
if (mandatoryFields.Keys.Contains(properties[i].Name))
{
if (string.IsNullOrEmpty( properties[i].GetValue(o, null).ToString()))
{
message.AppendLine(string.Format("{0} name is blank.", mandatoryFields.Values));
}
}
}
if(message.ToString().Trim().Length>0)
{
return false;
}
}
return true;
}
In this I have params Dictionary which will hold the property name of the class and its corresponding fieldname from the UI(manually fed by developer in the business layer or UI).
So what I want is that when the property is on the way to validate, if the property is found null or blank, then its corresponding fieldname, which is actually the value of the dictionary will get added to the stringbuilder message in the method above.
I hope i am clear.
A: Do the loop the other way:
public static bool CheckMandatoryFields(Dictionary<string,string > mandatoryFields, object o,out StringBuilder message)
{
message = new StringBuilder();
if(mandatoryFields == null || mandatoryFields.Count == 0)
{
return true;
}
var sourceType = o.GetType();
foreach (var mandatoryField in mandatoryFields) {
var property = sourceType.GetProperty(mandatoryField.Key, BindingFlags.Public | BindingFlags.Static);
if (property == null) {
continue;
}
if (string.IsNullOrEmpty(property.GetValue(o, null).ToString()))
{
message.AppendLine(string.Format("{0} name is blank.", mandatoryField.Value));
}
}
return message.ToString().Trim().Length == 0;
}
This way you iterate over the properties you want to check, so you always have a handle on the "current" property and know the corresponding key and value from the dictionary.
The snippet
if (property == null) {
continue;
}
causes the function to treat properties that exist as names in the dictionary but not as actual properties on the type to be treated as valid, to mirror what your original code does.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using Java to retrieve data from a Microsoft Access database I'm looking to create a Java program that retrieves data from Microsoft Access database (and possible store onto it).
Is this possible? If yes, is it complicated to do? Also are there any examples of Java programs (or code) that does this?
Thanks.
A: Yes, it's perfectly possible. Java's JDBC-ODBC bridge is your best friend for this.
First, you need to configure an ODBC access to your MSAccess database.
Then, you need this simple piece of code:
import java.sql.*;
public class AccessManager {
private Connection con;
private Statement st;
private static final String url="jdbc:odbc:my_access_odbc_dsn";
private static final String className="sun.jdbc.odbc.JdbcOdbcDriver";
private static final String user="";
private static final String pass="";
AccessManager()throws Exception {
Class.forName(className);
con = DriverManager.getConnection(url, user, pass);
st = con.createStatement();
// you can do select, insert, update, delete from
}
}
A: yes, this should be possible via JDBC : so it is as easy as using any other DBMS in java.
take a look at this document
A: While this is perfectly possible using the JDBC-ODBC bridge. The configuration isn't easy to set up, especially if you have an architecture mismatch. Ensure you are using the same architecture for both the JDK, Driver, IDE, OS to prevent ridiculous bugs. If you're using a 64 bit OS ensure tool is also 64 bit. Same applies for 32 bits.
Tut Tut2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Placing Footer at Bottom of Screen
Possible Duplicate:
CSS sticky footer
I had this problem for quite a while now and the problem is with all my footers. Everytime I place in this code syntax:
<Footer>
<p class="About">DESIGN BY MICHAEL & CODE BY ROKO</p>
</Footer>
Footer {
display:block;
position: absolute;
bottom: 0;
width: 100%;
height: 141px;
background: url(../assets/content/footer.png) repeat-x left bottom;
}
The footer is either placed at the bottom but when you scroll, it stay where it is and there footer is pretty much half way up the page, or the text that's supposed to be within' the footer is at the top of the page.
Could anyone please help me? I tried to look up Sticky Footer and the result was still the same...
A: I do something like this and it works pretty well:
<div class="footer" id="footer">My Footer</div>
#footer
{
clear: both;
border: 1px groove #aaaaaa;
background: blue;
color: White;
padding: 0;
text-align: center;
vertical-align: middle;
line-height: normal;
margin: 0;
position: fixed;
bottom: 0px;
width: 100%;
}
You can see an example here: http://jsfiddle.net/RDuWn/
A: I found this: http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page a while ago and use a similar method
A: Check out the below link -
How do you get the footer to stay at the bottom of a Web page?
* {
margin: 0;
}
html, body {
height: 100%;
}
.wrapper {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
height: 142px; /* .push must be the same height as .footer */
}
/*
Sticky Footer by Ryan Fait
http://ryanfait.com/
*/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Replace part of innerHTML without reloading embedded videos I have a div with id #test that contains lots of html, including some youtube-embeds etc.
Somewhere in this div there is this text: "[test]"
I need to replace that text with "(works!)".
The normal way of doing this would of course be:
document.getElementById("test").innerHTML = document.getElementById("test").replace("[test]","(works!)");
But the problem is that if i do that the youtube-embeds will reload, which is not acceptable.
Is there a way to do this?
A: You will have to target the specific elements rather than the parent block. Since the DOM is changing the videos are repainted to the DOM.
A: Maybe TextNode (textContent) will help you, MSDN documentation IE9, other browsers also should support it
A: Change your page so that
[test]
becomes
<span id="replace-me">[test]</span>
now use the following js to find and change it
document.getElementById('replace-me').text = '(works!)';
If you need to change more than one place, then use a class instead of an id and use document.getElementsByClassName and iterate over the returned elements and change them one by one.
Alternatively, you can use jQuery and do it even simpler like this:
$('#replace-me').text('(works!)');
Now for this single replacement using jQuery is probably overkill, but if you need to change multiple places (by class name), jQuery would definitely come in handy :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: difference of reading files string value1 = File.ReadAllText("C:\\file.txt");
string value2 = File.ReadAllText(@"C:\file.txt");
In the above statements when is the difference of using @"C:\file.txt" and C:\file.txt
A: Compiler would read @"C:\file.txt" as is. Removing verbatim (@) will make it treat '\f' as a single escape character (Form feed). In other words:
@"C:\file.txt" == "C:\\file.txt"
@"C:\file.txt" != "C:\file.txt" // treated as C: + FormFeed + ile.txt
Verbatim string literals start with @ and are also enclosed in double
quotation marks. For example:
@"good morning" // a string literal
The advantage of verbatim strings is that escape sequences are not
processed, which makes it easy to write, for example, a fully
qualified file name:
@"c:\Docs\Source\a.txt" // rather than "c:\\Docs\\Source\\a.txt"
String literals:
A regular string literal consists of zero or more characters enclosed
in double quotes, as in "hello", and may include both simple escape
sequences (such as \t for the tab character) and hexadecimal and
Unicode escape sequences.
A verbatim string literal consists of an @ character followed by a
double-quote character, zero or more characters, and a closing
double-quote character. A simple example is @"hello". In a verbatim
string literal, the characters between the delimiters are interpreted
verbatim, the only exception being a quote-escape-sequence. In
particular, simple escape sequences and hexadecimal and Unicode escape
sequences are not processed in verbatim string literals. A verbatim
string literal may span multiple lines.
A: When using a \ in a string, you normally have to use \\ because the \ is an escape character. In reality, the first string you show (File.ReadAllText("C:\file.txt");) should throw a compile error.
The @ will allow you to build your string without using \\ every time you need a \.
A: string value1 = "C:\file.txt";
string value2 = @"C:\file.txt";
the string for value1 will contain a formfeed character where the \f is, while the second one will keep the backslash and the f. (This becomes very clear if you try to output them in a console application with Console.Write...)
The correct way for the value1 version would be "C:\\file.txt"
(The value2 version uses whats called, as Dmitry said, a verbatim string)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: in_array multiple values How do I check for multiple values, such as:
$arg = array('foo','bar');
if(in_array('foo','bar',$arg))
That's an example so you understand a bit better, I know it won't work.
A: IMHO Mark Elliot's solution's best one for this problem. If you need to make more complex comparison operations between array elements AND you're on PHP 5.3, you might also think about something like the following:
<?php
// First Array To Compare
$a1 = array('foo','bar','c');
// Target Array
$b1 = array('foo','bar');
// Evaluation Function - we pass guard and target array
$b=true;
$test = function($x) use (&$b, $b1) {
if (!in_array($x,$b1)) {
$b=false;
}
};
// Actual Test on array (can be repeated with others, but guard
// needs to be initialized again, due to by reference assignment above)
array_walk($a1, $test);
var_dump($b);
This relies on a closure; comparison function can become much more powerful.
Good luck!
A: Intersect the targets with the haystack and make sure the intersection count is equal to the target's count:
$haystack = array(...);
$target = array('foo', 'bar');
if(count(array_intersect($haystack, $target)) == count($target)){
// all of $target is in $haystack
}
Note that you only need to verify the size of the resulting intersection is the same size as the array of target values to say that $haystack is a superset of $target.
To verify that at least one value in $target is also in $haystack, you can do this check:
if(count(array_intersect($haystack, $target)) > 0){
// at least one of $target is in $haystack
}
A: Searching the array for multiple values corresponds to the set operations (set difference and intersection), as you will see below.
In your question, you do not specify which type of array search you want, so I am giving you both options.
ALL needles exist
function in_array_all($needles, $haystack) {
return empty(array_diff($needles, $haystack));
}
$animals = ["bear", "tiger", "zebra"];
echo in_array_all(["bear", "zebra"], $animals); // true, both are animals
echo in_array_all(["bear", "toaster"], $animals); // false, toaster is not an animal
ANY of the needles exist
function in_array_any($needles, $haystack) {
return !empty(array_intersect($needles, $haystack));
}
$animals = ["bear", "tiger", "zebra"];
echo in_array_any(["toaster", "tiger"], $animals); // true, tiger is an amimal
echo in_array_any(["toaster", "brush"], $animals); // false, no animals here
Important consideration
If the set of needles you are searching for is small and known upfront, your code might be clearer if you just use the logical chaining of in_array calls, for example:
$animals = ZooAPI.getAllAnimals();
$all = in_array("tiger", $animals) && in_array("toaster", $animals) && ...
$any = in_array("bear", $animals) || in_array("zebra", $animals) || ...
A: if(empty(array_intersect([21,22,23,24], $check_with_this)) {
print "Not found even a single element";
} else {
print "Found an element";
}
array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
Returns an array containing all of the values in array1 whose values exist in all of the parameters.
empty() — Determine whether a variable is empty
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
A: If you're looking to optimize this search with just a comparison check only I would do:
public function items_in_array($needles, $haystack)
{
foreach ($needles as $needle) {
if (!in_array($needle, $haystack)) {
return false;
}
}
return true;
}
if you're willing to do it ugly doing multiple if(in_array(...&&in_array(... is even faster.
I did a test with 100 and another with 100,000 array elements and between 2 and 15 needles using array_intersect, array_diff, and in_array.
in_array was always significantly faster even when I had to do it 15x for different needles. array_diff was also quite a bit faster than array_intersect.
So if you're just trying to search for a couple of things to see if they exist in an array in_array() is best performance-wise. If you need to know the actual differences/matches then it's probably just easier to use array_diff/array_intersect.
Feel free to let me know if I did my calculations wrong in the ugly example below.
<?php
$n1 = rand(0,100000);
$n2 = rand(0,100000);
$n2 = rand(0,100000);
$n3 = rand(0,100000);
$n4 = rand(0,100000);
$n5 = rand(0,100000);
$n6 = rand(0,100000);
$n7 = rand(0,100000);
$n8 = rand(0,100000);
$n9 = rand(0,100000);
$n10 = rand(0,100000);
$n11 = rand(0,100000);
$n12 = rand(0,100000);
$n13 = rand(0,100000);
$n14 = rand(0,100000);
$n15 = rand(0,100000);
$narr = [$n1, $n2, $n3, $n4, $n5, $n6, $n7, $n8, $n9, $n10, $n11, $n12, $n13, $n14, $n15];
$arr = [];
for($i = 0; $i<100000 ; $i++)
{
$arr[] = rand(0,100000);
}
function array_in_array($needles, $haystack)
{
foreach($needles as $needle)
{
if (!in_array($needle, $haystack))
{
return false;
}
}
return true;
}
$start_time = microtime(true);
$failed = true;
if(array_in_array($narr, $arr))
{
echo "<br>true0<br>";
}
$total_time = microtime(true) - $start_time;
echo "<hr>";
echo($total_time);
$start_time = microtime(true);
if (
in_array($n1, $arr) !== false &&
in_array($n2, $arr) !== false &&
in_array($n3, $arr) !== false &&
in_array($n4, $arr) !== false &&
in_array($n5, $arr) !== false &&
in_array($n6, $arr) !== false &&
in_array($n7, $arr) !== false &&
in_array($n8, $arr) !== false &&
in_array($n9, $arr) !== false &&
in_array($n10, $arr) !== false &&
in_array($n11, $arr) !== false &&
in_array($n12, $arr) !== false &&
in_array($n13, $arr) !== false &&
in_array($n14, $arr) !== false &&
in_array($n15, $arr)!== false) {
echo "<br>true1<br>";
}
$total_time = microtime(true) - $start_time;
echo "<hr>";
echo($total_time);
$first_time = $total_time;
echo "<hr>";
$start_time = microtime(true);
if (empty($diff = array_diff($narr,$arr)))
{
echo "<br>true2<br>";
}
$total_time = microtime(true) - $start_time;
echo($total_time);
print_r($diff);
echo "<hr>";
echo "<hr>";
if ($first_time > $total_time)
{
echo "First time was slower";
}
if ($first_time < $total_time)
{
echo "First time was faster";
}
echo "<hr>";
$start_time = microtime(true);
if (count(($itrs = array_intersect($narr,$arr))) == count($narr))
{
echo "<br>true3<br>";
print_r($result);
}
$total_time = microtime(true) - $start_time;
echo "<hr>";
echo($total_time);
print_r($itrs);
echo "<hr>";
if ($first_time < $total_time)
{
echo "First time was faster";
}
echo "<hr>";
print_r($narr);
echo "<hr>";
print_r($arr);
A: if(in_array('foo',$arg) && in_array('bar',$arg)){
//both of them are in $arg
}
if(in_array('foo',$arg) || in_array('bar',$arg)){
//at least one of them are in $arg
}
A: Going off of @Rok Kralj answer (best IMO) to check if any of needles exist in the haystack, you can use (bool) instead of !! which sometimes can be confusing during code review.
function in_array_any($needles, $haystack) {
return (bool)array_intersect($needles, $haystack);
}
echo in_array_any( array(3,9), array(5,8,3,1,2) ); // true, since 3 is present
echo in_array_any( array(4,9), array(5,8,3,1,2) ); // false, neither 4 nor 9 is present
https://glot.io/snippets/f7dhw4kmju
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "143"
} |
Q: Can't compile/assemble MRC and MCR coprocessor instructions on iPhone? I don't seem to be able to assemble the MCR and MRC ARMv7 instructions (these are coprocessor access instructions) with iPhone? I have some of these instructions in some inline assembly blocks that work quite nicely with the Code Sourcery gcc toolchain building for a different CortexA8 chip (an OMAP chip), but Apple's assemblers - the Clang assembler and their build of the gnu assembler - throw up errors:
{standard input}:41:bad instruction `MRC p15,0,r2,C9,C12,0'
{standard input}:56:bad instruction `MCR p15,0,r0,C9,C12,0'
{standard input}:78:bad instruction `MCR p15,0,r0,C9,C12,1'
{standard input}:96:bad instruction `MCR p15,0,r0,C9,C12,2'
{standard input}:119:bad instruction `MCR p15,0,r2,C9,C12,4'
{standard input}:143:bad instruction `MCR p15,0,r0,C9,C12,5'
{standard input}:165:bad instruction `MCR p15,0,r0,C9,C13,1'
{standard input}:187:bad instruction `MCR p15,0,r0,C9,C13,2'
{standard input}:209:bad instruction `MCR p15,0,r0,C9,C13,0'
{standard input}:228:bad instruction `MRC p15,0,r0,C9,C13,0'
{standard input}:253:bad instruction `MRC p15,0,r0,C9,C13,2'
Any ideas?
A: (Originally as a comment on the question)
Random guess: have you tried changing "MRC" to "mrc"? Apple has a relatively ancient ARM assembler that has trouble with anything written in upper-case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: In an Eclipse plugin, what's the right way to get the .class file that corresponds to the selected java file? I'm writing an Eclipse plugin. I'm looking for the right way to get a selected java file and find it's corresponding .class file.
The way I'm doing it now works for a standard Eclipse java project, but seems less than elegant: I call IJavaProject#getOutputLocation and combine that with the path to the selected file. Then I just change .java to .class.
Here's the code for the method that translates from the incoming selection to a path:
def selection_to_path selection
path = selection.get_paths.first
output_location = path.get_first_segment.get_output_location
root = org.eclipse.core.resources::ResourcesPlugin.getWorkspace().get_root
folder = root.get_folder output_location
folder.get_location.to_s
path_to_file_as_string = path.get_last_segment.get_path.to_s
path_to_file_as_string[/\.java$/] = ".class"
path_elements_of_java_file = path_to_file_as_string.split("/")[3..-1]
all_elements = folder.get_location.to_s.split("/") + path_elements_of_java_file
File.join(all_elements)
end
This works, but I suspect it fails often enough that it's not the right thing to do. In particular, the documentation for getOutputLocation says that my assumptions about class file locations are too simplistic.
So what's the right way to do this?
I don't need this to work all of the time. Certainly there will be many cases where a .java file doesn't have a corresponding .class file (compilation errors, no automatic builds, whatever). I don't care about those; I just want to know if there is a class file, what is its full path?
A: There is no method, which directly finds the corresponding class file resource. The proper way to get the corresponding output folder is to:
*
*Convert the selection to IJavaElement, most probably ICompilationUnit (.java files)
*Find the corresponding IPackageFragmentRoot (the source folder)
*Find the resolved IClasspathEntry
*Find the output location using IClasspathEntry.getOutputLocation() or the IJavaProject.getOutputLocation() method, depending on whether the classpath entry has separate output location.
*Construct the path to the classpath based on the ICompilationUnit's package
The class file may or may not exist depending on whether the project has been build, whether there are build path errors, etc. So, there are additional heuristics, which you need to use to determine whether the result of the above algorithm will be usable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I rank records on the index page by multiple values? I have a table of venues in my app which are displayed on the venues index page in partials with the highest average rated venues at the top and descending:
venues controller
def index
if
@venues = Venue.order("average_rating DESC").all
else
@venues = Venue.all
end
@venues = @venues.paginate :per_page => 15, :page => params[:page]
end
I have just enabled some venues to be free and some to be premium with:
venue.rb
PLANS = %w[free premium]
venue edit.html.erb
<%= f.collection_select :plan, Venue::PLANS, :to_s, :humanize %></p>
How can I make it so all the premium venues are displayed above the free venues even if they have a lower average rating?
Thanks very much for any help its much appreciated!
A: Something like this should work:
@venues = Venue.order("case plan when 'premium' then 1 else 0 end desc, average_rating DESC").all
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get iTunes volume control widget? Anyone know of a way to get a volume control widget similar to iTunes?
A: Not sure how close you'll get but the tutorial below shows how to apply custom themes via images to a UISlider. I haven't tried it yet but I was looking at it the other day.
http://www.applausible.com/blog/?p=250
I found it when browsing the site below which is also a good resource when trying to find controls
http://cocoacontrols.com/platforms/ios/controls
Hope that helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: A seemingly strange OAuthException I am learning to build fb apps, and on the very first attempt, I get this strange OAuthException. The tutorial clearly mentions that I need to pass redirect_uri, client_secret, client_id and code(from the app auth phase). But when the flow completes, instead of getting an access token here is the JSON error object I get:
{"error":{"message":"client_secret should not be passed to \/oauth\/access_token\/","type":"OAuthException"}}
EDIT: this is the snippet I'm using to build the url(pardon the excessive 2nd line, please)
url = "https://graph.facebook.com/oauth/access_token/"
url += "?"
url += urllib.urlencode([('client_id',client_id),
('redirect_uri', redirect_uri),
('client_secret', client_secret),
('code', code)])
where the variables hold correct values.(checked > 5 times)
A: You should remove the / immediately after access_token in the url so that it reads graph.facebook.com/oauth/access_token? followed by your parameters. If that doesn't do it, please show an entire sample url you have generated (with the real client_secret x'ed out of course) since I am not familiar enough with urllib.urlencode to be sure of the formatting, although that part looks right at a glance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Sencha Touch: Dynamic chart labels in a MVC app So I have an app I am using to learn more about touch. I got the basic framework setup based on tutorials I have found around the net where I can bounce around the app clicking on things. I integrated a sencha touch line chart which works fine.
The problem is I want to populate the series labels for the chart based on data that comes back from the server, not hard code the labels. My plan was to once execute:
Ext.redirect('Chart/Index');
I would hit that controller and load the store. In the onLoad listener for the store, once the data is returned, populate the title array in the series and render the chart. I tried to attach a customer listener to the chart view, and then execute it from the store listener.
listeners: {
load:function(el,records, success){
App.fireEvent('myListener', records);
}
},
That isn't working for me, listener is undefined (I do have it defined in the chart view). So that isn't my solution.
Then I tried to give the chart an id, and do a Ext.query(#myChartName); That returned a html element, not something wrapped in Ext that can be executed.
Now it extsj4, I can put a listener for a store in the controller, and define a method in the controller to execute. It can easily access any component within the controller and would be how I would solve this issue. But that doesn't seem to be how MVC works in the touch apps. The examples I have seen are laid out drastically different in fact. (Why is that btw?)
What's my best solution in taking the data in my store after load and populating the labels/legend in my chart?
UPDATE
Added links to the code in question. I am trying to add strings (the label names) to the title array in the series. Notice the Chart View & the Store.
Chart view
http://jsfiddle.net/5JhCu/2/
Controller
http://jsfiddle.net/3C4Tq/1/
Store
http://jsfiddle.net/LT6eh/
FYI, I tried adding the listener to multiple things/objects like the app, the view, within the controller, still no luck.
A: Did you try Ext.getCmp('myChartId') to get access to the chart component?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Detect if a touch is on a moving UIImageView from a View Controller I have a UIViewController that is detecting touch events with touchesBegan. There are moving UIImageView objects that float around the screen, and I need to see if the touch event landed on one of them. What I am trying:
UITouch* touch = [touches anyObject];
if ([arrayOfUIImageViewsOnScreen containsObject: [touch view]]) {
NSLog(@"UIImageView Touched!");
}
But this never happens. Also if I were to do something like this:
int h = [touch view].bounds.size.height;
NSLog([NSString stringWithFormat: @"%d", h]);
it outputs the height of the entire UIViewController (screen) everytime, even if I touch one of the UIImageViews, so clearly [touch view] is not giving me the UIImageView. How do I detect when only a UIImageView is pressed? Please do not suggest using UIButtons.
Thank you!
A: If you only want to detect when a UIImageView is pressed, check the class:
if (touch.view.class == [UIImageView class]) {
//do whatever
}
else {
//isnt a UIImageView so do whatever else
}
Edit----
You haven't set the userInteraction to enabled for the UIImageView have you?!
A: I know you said please do not suggest using UIButtons, but buttons sound like the best/easiest way to me.
A: You could try sending the hitTest message to the main view's CALayer with one of the touches - it'll return the CALayer furthest down the subview hierarchy that you touched.
You could then test to see if the layer you touched is a layer of one of the UIImageView's, and proceed from there.
This code uses a point generated from a UIGestureRecognizer.
CGPoint thePoint = [r locationInView:self.view];
thePoint = [self.view.layer convertPoint:thePoint toLayer:self.view.layer.superlayer];
selectedLayer = [self.view.layer hitTest:thePoint];
A: If you want to check the touch means use CGRectContainsPoint.
1.Capture the touch event and get the point where you touched,
2.Make a CGRect which bounds the object you want to check the touch event,
3.Use CGRectContainsPoint(CGRect , CGPoint) and catch the boolean return value.
http://developer.apple.com/library/ios/#DOCUMENTATION/GraphicsImaging/Reference/CGGeometry/Reference/reference.html
Here is the class reference for CGRect.
A: Forgot about this question- the problem was that I did not wait until viewDidLoad to set userInteractionEnabled on my UIImageView.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jquery ajax returns error but is success I have the following JS
function change_ajaxarea1(){
navigator.notification.activityStart();
$('#ajaxarea1').load('http://server.net/droiddev/backbone1/index.php/welcome/', function(){
navigator.notification.activityStop();
$('#ajaxarea1').css("height","auto");
//$('#ajaxarea1').css("overflow","hidden");
});
//navigator.notification.activityStart();
}
function postarticle(){
$.post("http://server.net/droiddev/backbone1/", { headline: "John", article: "2pm" } );
}
function addarticle(){
var headlinetemp=$('#headline').val();
var articletemp=$('#article').val();
$.ajax({
type:'POST',
dataType:'json',
url: "http://server.net/droiddev/backbone1/index.php/welcome/addarticle/",
data: { 'headline': headlinetemp, 'article': articletemp},
success:function(){
alert('success');
},
error:function(xhr){
alert(xhr.status);
}
});
}
and the following controller code :
<?php
class Welcome extends CI_Controller {
public function index()
{
$data['query']=$this->site_model->get_last_ten_articles();
$this->load->view('partial1',$data);
}
public function addarticle(){
$headline=$this->input->post('headline');
$article=$this->input->post('article');
$this->site_model->insert_entry($headline,$article);
}
}
The addarticle() javascript ajax works and posts the vars to the server and into the db, however, javascript will then run the error function instead of the success function. The http response code is 200 which I thought would make it run the Success function. any suggestions?
A: You need to return json from controller, as this is what jQuery expects. You can return i.e.
{ success : true }
Or you could set html as data type (maybe it will work without content but you may need to return something)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Adding Logout Button to Share Screen in Facebook Connect for iPhone I have been playing with Facebook Connect for iPhone, as well as ShareKit. Seems like Facebook Connect will work best for me for now (in case you were going to suggest Sharekit - just beating you to the chase!). But, I am having one difficulty..
I would like to add a 'logout' button to the "Publish this Story" screen (view). I don't want a button on my own view.. this is being called from an action sheet that also has several other sharing options, and I don't want to also have to list a logout option for each service. I have thought about this long and hard, and the best way for me to do it would be to add a button on "Publish this Story", perhaps up in the facebook header. Does anyone know 1) if this CAN be done and 2) if so, how to approach it?
A: As far as I know, that dialog is served up by Facebook and can't bequeath altered. We had similar needs. We actually decided to offer logout options in Settings instead of from the screen where the sharing options were offered.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to put a semi-opaque layer on a frame? Usually when clearing the frame for a new draw, one uses the glClear() or glClearColor(). But each of those completely removes the previous frame.
I'd like to make the frames disappear gradually, i.e. with each new frame put a semi-transparent overlay on what's already on the canvas. I tried to use the glClearColor()'s alpha parameter, but it doesn't seem to have any effect.
What should I do to achieve this gradual disappearing effect?
A: If you just want to draw the clear color over the last frame without getting rid of it entirely, draw a screen-size quad over the viewport with the same color as what you'd pass to glClearColor, and skip calling glClear(GL_COLOR_BUFFER_BIT) (you should probably still clear the depth/stencil buffers if you're using either of them). So, if you're using a depth buffer, first clear the depth buffer if need be, disable depth testing (this is important mainly to make sure that your quad does not update the depth buffer), draw your screen-size quad, and then re-enable depth testing. Draw anything else afterward if you need to.
What follows assumes you're using OpenGL ES 2.0
If you need to blend two different frames together and you realistically never actually see the clear color, you should probably render the last frame to a texture and draw that over the new frame. For that, you can either read the current framebuffer and copy it to a texture, or create a new framebuffer and attach a texture to it (see glFramebufferTexture2D). Once the framebuffer is set up, you can happily draw into that. After you've drawn the frame into the texture, you can go ahead and bind the texture and draw a quad over the screen (remembering of course to switch the framebuffer back to your regular framebuffer).
If you're using OpenGL ES 1.1, you will instead want to use glCopyTexImage2D (or glCopyTexSubImage2D) to copy the color buffer to a texture.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to handle activity coming to foreground again The books I have are abysmal at explaining how to work with the lifecycle, there's a lot I'm missing that I'm hoping somebody can fill in.
My app structure is that when it's first started, it starts an activity full of legalbabble that the user has to accept. When he says 'ok', I start my main activity and then I call finish like this:
public void onClick(View view) { //as a result of "I accept"
Intent mainIntent = new Intent(mParent, EtMain.class);
startActivity(mainIntent); // Start the main program
finish();
}
Then in EtMain in the onCreate method, I've got some tabs and I instantiate some classes:
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
SetupTabs.setMyTabs(mTabHost, this);
mComData = new ComFields(this); // Create the objects
mDepWx = new WxFields(this, DepArr.Departure);
mArrWx = new WxFields(this, DepArr.Arrival);
mDepVs = new DepFields(this);
mArrVs = new ArrFields(this);
mTabHost.setOnTabChangedListener(new OnTabChangeListener(){
}
Questions:
The 'finish' in the first fragment should terminate the legalbabble activity so it'll never be restarted, right? And the EtMain one will remain forever (until killed externally), even if my app gets pushed to the background, right?
The way it is now, when EtMain gets pushed and later brought to the foreground (by tapping on the icon), it goes through the legalbabble screen as though it's a complete start - that's what I'd like to prevent - going thru the legalbabble screen again.
It would seem that I'd want to override onRestart in the second code fragment and put something in there to restart the app, right? That's the part I'm unclear about.
My question then is what needs to be done in onRestart. Do I have to recreate all the tabs and data in the tabs and all my object instantiations? Or is the memory state of the app saved someplace and then is restored back to the state that it was in before something else was brought to the foreground in which case not much needs to be done because all the objects and listeners will still be there?
A: *
*Yes after the first activity has ended you shouldn't have to view that activity again. You could also write to the shared preferences that the user has previously seen legal info.
*If you're UI object creation is in the onCreate method, this should only be called once. Pausing or resuming will not call the onCreate method again.
*Unless you explicitly remove your objects and tabChangedListeners in the onPause method, you should not have to touch them in the onRestart method.
*Correct, the state of the app is saved automatically. You shouldn't have to touch the onRestart method.
Hope this helps!
A: I think the problem is that the launch activity in your manifest is the legalbabble activity, so when you click on the icon, the system launches another one. A better architecture would be to launch the legalbabble activity it from your EtMain activity in the onCreate method of the latter, using startActivityForResult. From the docs:
As a special case, if you call startActivityForResult() with a requestCode >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your activity, then your window will not be displayed until a result is returned back from the started activity.
When you get the result in onActivityResult, you can call finish() if the legal stuff was declined; otherwise everything will proceed normally.
This avoids the problem that the launch activity defined in your manifest finishes when the legal stuff is accepted.
A: EtMain will not remain forever, if the user backs out (by pressing the BACK key) the Activity will be finished (onPause, then onStop, then onDestroy will be called).
In general you can ignore onRestore until you are doing something complicated.
Once the user has exited your application and re-enters (or presses the icon on the Homescreen), onCreate (followed by onStart and onResume) will be called for your first activity, so you do not need any logic in onRestart, your code in onCreate will do the setting up for you as it did the first time. Because of this your legal babble will appear again when the user starts the app after exiting unless you store a preference (in SharedPreferences or a database or file) to indicate you have already displayed it - in which case finish it straight away and start the main activity.
onRestart is only called when the application goes from the stopped state (onStop has been called but not onDestroy) to the started state (onStart is called but onResume has not yet).
For saving data - some components save their state automatically (e.g. EditTexts remember the text in them, TabHosts remember the currently selected tab etc). Some components will not. If you wish to save extra data then make use of onSaveInstanceState and onRestoreInstanceState. You should only use these methods to restore the state of your application or temporary data, not important things, e.g. the id of the resource what the user was looking at, what zoom level they were at etc. For things like contacts or actual data you should commit these changes to a database, SharedPreferences or other permanent storage (e.g. file) when onPause is called.
I recommend taking a look at the Android Activity lifecycle if you are confused. Or ask more questions!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NSCollectionView's setContent: memory management I have a NSCollectionView that I populate using [collectionView setContent:data]; where data is a NSArray filled with objects all of the same custom NSObject subclass. The item prototype of the collection view is a standard NSCollectionViewItem, not subclassed. The collection item's view is populated using bindings from my NSObject subclass.
Now to the problem, when analyzing my app using heapshots I see that there is a huge increase in memory when opening the window with the collection view. Instruments pinpoints this memory increase to the [collectionView setContent:data]; line. This memory is never reclaimed. Any ideas?
EDIT: I access the data object like this:
NSArray *data = [[[[MWWeatherController sharedInstance] cachedData] objectForKey:[NSString stringWithFormat:@"%u",index]] objectForKey:@"daily"];
A: Have you made the ViewController for the CollectionView KVO compliant?
Has the XIB for the CollectionView an ArrayController?
Bind the CollectionView of the XIB to the arrangedObjects of the ArrayController and set the Items through your ViewController method e.g. setMyCustomObjectsArray, that again sets the array that is observed by the ArrayController.
Make sure you release everything correctly in your custom object's dealloc method too.
A: I think you are not releasing data in your scope ... if you own the 'data' object make sure you release it.
Some query to answer it better --
*
*How you allocate 'data'?
*Who is releasing it?
*[collectionView setContent:data]; more code snippet around this line
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Detect Cellular Data Usage How could I detect when a Wifi connection becomes unavailable and a cellular data (EDGE/3G) connection is being used?
A: There exist an example-app from apple. Just take a look at that.
http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Timeout or try-catch for connecting to a server? (C# WinForms) Which code is preferable to handling failed connections to a server?
Something like this:
Or this kind of code at the beginning of the async callback for TcpClient.BeginConnect:
try
{
tcpClient.EndConnect(async);
}
catch
{
System.Windows.Forms.MessageBox.Show("uh oh");
return;
}
Thanks for reading
A: When your context is handling connection timeouts, I assume that you mean you have not yet received a response from a request made, within a certain period of time.
Wrapping your EndConnect in a try block and catching any exceptions thrown does not necessarily constitute a timeout occurance. There is currently no in-built support for handling timeouts with TcpClient.
Your first link is a good example of how to detect and work with connection timeouts.
This article may be of some help to you also: Using an asynchronous client socket
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: jQuery slider Orbit with Wordpress ZURB's Orbit content slider is awesome. Just trying to get it working with Wordpress.
I was able to implement a similar but trimmed down plugin, Cycle. Was even able to use cycle in widget areas, which is nice.
Trying to accomplish the same with Orbit. Used chrome's console to make sure that javascripts and css were loading. Orbit div shows up, but just pinwheels... Could this have something to do with jQuery "$" shortcut not working in wordpress?
Thanks in advance for any help.
p.s. not sure what code is relevant to paste here... let me know and I will provide it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: backbone.js events and el Okay, so I've read several other questions regarding Backbone views and events not being fired, however I'm still not getting it sadly. I been messing with Backbone for about a day, so I'm sure I'm missing something basic. Here's a jsfiddle with what I'm working with:
http://jsfiddle.net/siyegen/e7sNN/3/
(function($) {
var GridView = Backbone.View.extend({
tagName: 'div',
className: 'grid-view',
initialize: function() {
_.bindAll(this, 'render', 'okay');
},
events: {
'click .grid-view': 'okay'
},
okay: function() {
alert('moo');
},
render: function() {
$(this.el).text('Some Cow');
return this;
}
});
var AppView = Backbone.View.extend({
el: $('body'),
initialize: function() {
_.bindAll(this, 'render', 'buildGrid');
this.render();
},
events: {
'click button#buildGrid': 'buildGrid'
},
render: function() {
$(this.el).append($('<div>').addClass('gridApp'));
$(this.el).append('<button id="buildGrid">Build</button>');
},
buildGrid: function() {
var gridView = new GridView();
this.$('.gridApp').html(gridView.render().el);
}
});
var appView = new AppView();
})(jQuery);
The okay event on the GridView does not fire, I'm assuming because div.grid-view does not exist when the event is first bound. How should I handle the binding and firing of an event that's built on a view dynamically? (Also, it's a short example, but feel free to yell at me if I'm doing anything else that I shouldn't)
A: Your problem is that the events on GridView:
events: {
'click .grid-view': 'okay'
}
say:
when you click on a descendent that matches '.grid-view', call okay
The events are bound with this snippet from backbone.js:
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
So the .grid-view element has to be contained within your GridView's this.el and your this.el is <div class="grid-view">. If you change your events to this:
events: {
'click': 'okay'
}
you'll hear your cows (or "hear them in your mind" after reading the alert depending on how crazy this problem has made you).
Fixed fiddle: http://jsfiddle.net/ambiguous/5dhDW/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: What is a good approach to Flip through many (over 40) images? Ive looked into the ViewFlipper, but defining 40 different views in one XML doc just doesn't seem like a bright idea. I know there has to be a better way, I just don't know how. I have spent some time trying to find a answer with no good answer so far.
A: A simple approach would be to simply contain two ImageViews within the ViewFlipper. Then when you request the next or previous view, set the new image resource for the next view and flip.
If you implement a lazy loader using AsyncTask or a Handler this will stop your UI thread from blocking.
Hope this helps!
A: I have used the Gallery widget (admittedly quite heavily modified) to display 200 fullscreen images in an image viewer for a client.
Alternatively you could use a ViewAimator with either 2 (in this case ViewFlipper) or 3 views (3 if you want to preload both the next and previous images). If you go for this approach then Laurence beat me to suggesting this idea ;) However I'd add that you would want to extend the ViewAnimator/ViewFlipper class to allow it to accept some type of Adapter.
A: You could use a ViewPager (included in the Android compatibility library if you need to support pre-Honeycomb devices).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: appending list error typeerror sequence item o: expecting string, list found this is my code. basicily i think it should work like this self.list makes a ordered list self.contents turns a list into a string so i can display self.list in a scrollable window with self.plbuffer.set_text(self.contents). then os.walk traverses the directory defined in top than findall takes what i write in self.search finds the pattern in filenames and then it should be appended to self.list.
class mplay:
def search_entry(self, widget):
self.list = []
self.contents = "/n".join(self.list)
self.plbuffer.set_text(self.contents)
search = self.search.get_text()
top = '/home/bludiescript/tv-shows'
for dirpath, dirnames, filenames in os.walk(top):
for filename in filenames:
if re.findall(filename, search):
self.list.append(os.path.join([dirpath, filename]))
what does this error mean can i not append to self.list using os.path.join
error = file "./mplay1.py" , line 77 in search_entry
self.contents = "/n".join(self.list) line
typeerror sequence item o: expecting string, list found
A: The list must be a list of strings for it to work:
"/n".join(["123","123","234"]) # works
"/n".join([123, 123, 234]) #error, this is int
You also get an error if it is a list of lists, which is probably the case in yours:
"/n".join([[123, 123, 234],[123, 123, 234]]) # error
Throw in a print self.list to see what it looks like.
When you say it runs fine elsewhere, probably that is because the content of the list is different.
Also, note that joining an empty list [] will return an empty string, so that line is effectively doing nothing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to scan a file of data and print a value to the screen when a number first exceeds a set number I'm working in C and I'm very new at it (2 weeks ago). Basically I have a file that has two columns of data separated by a space. I need to read from the file, line by line, and determine when the first time the second column exceeds some number. When it finds the row I'm looking for, I want it to print to the screen the corresponding number from the first column. Both columns are in numerical order.
To be more specific, column1 is a year and column2 is a population. The first time the population exceeds some number, X, I want to print the corresponding date.
So far I have code that scans and finds when the population > X and then prints the date, but it prints every date that has a population > X. I can't get it to only print the first time it exceeds X and nothing else.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *in;
int ni,i;
double d,p;
if((in=fopen("pop.dat","r"))==NULL) {
printf("\nCannot open pop.dat for reading\n");
exit(1);
}
while(fscanf(in,"%lf %lf",&d,&p)!=EOF) {
if (p>350) printf("\nDate is %f and Population is %f",d,p);
}
fclose(in);
return(0);
}
A: To get it to print just the first you could add the code to a function like this.
double getFirstDate(const char* filename)
{
FILE *in;
int ni,i;
double d,p;
if((in=fopen(filename,"r"))==NULL) {
printf("\nCannot open pop.dat for reading\n");
exit(1);
}
while(fscanf(in,"%lf %lf",&d,&p)!=EOF) {
if (p>350)
{
printf("\nDate is %f and Population is %f",d,p);
fclose(in);
return p;
}
fclose(in);
return -1;
}
Then call this function from main
A: You can also break the loop once you have got the year printed.
while(fscanf(in,"%lf %lf",&d,&p)!=EOF) {
if (p>350) {
printf("\nDate is %f and Population is %f",d,p);
break;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Rails, many instances for one model How can I create many instances of one model in one form?
In my case user must be able to upload many files with descriptions in one time.
A: If there is an association between users and files in your models, you can use nested attributes to build your form with attributes from each model. Check out http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes to get started
Your form would look something like this:
<%= form_for @user do |user_form| %>
First name: <%= user_form.text_field :first_name %>
Last name : <%= user_form.text_field :last_name %>
<%= fields_for @user.files do |file_fields| %>
<%= file_fields.text_field :name %>
<% end %>
<%= f.submit %>
<% end %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL or PHP mistake? Distance calculation I have a problem with my file. I'm making Travian Clone script and we went really far. Now we decided to add artefacts into game.
Goal is to show closest artefacts to the current village we are in. The code is:
function getDistance($coorx1, $coory1, $coorx2, $coory2) {
$max = 2 * WORLD_MAX + 1;
$x1 = intval($coorx1);
$y1 = intval($coory1);
$x2 = intval($coorx2);
$y2 = intval($coory2);
$distanceX = min(abs($x2 - $x1), $max - abs($x2 - $x1));
$distanceY = min(abs($y2 - $y1), $max - abs($y2 - $y1));
$dist = sqrt(pow($distanceX, 2) + pow($distanceY, 2));
return round($dist, 1);
}
unset($reqlvl);
unset($effect);
$arts = mysql_query("SELECT * FROM ".TB_PREFIX."artefacts WHERE id > 0");
$rows = array();
while($row = mysql_fetch_array($arts)) {
$query = mysql_query('SELECT * FROM `' . TB_PREFIX . 'wdata` WHERE `id` = ' . $row['vref']);
$coor2 = mysql_fetch_assoc($query);
$wref = $village->wid;
$coor = $database->getCoor($wref);
$dist = getDistance($coor['x'], $coor['y'], $coor2['x'], $coor2['y']);
$rows[$dist] = $row;
}
ksort($rows, SORT_ASC);
foreach($rows as $row) {
echo '<tr>';
echo '<td class="icon"><img class="artefact_icon_'.$row['type'].'" src="img/x.gif" alt="" title=""></td>';
echo '<td class="nam">';
echo '<a href="build.php?id='.$id.'">'.$row['name'].'</a> <span class="bon">'.$row['effect'].'</span>';
echo '<div class="info">';
if($row['size'] == 1){
$reqlvl = 10;
$effect = "village";
}elseif($row['size'] == 2 OR $row['size'] == 3){
$reqlvl = 20;
$effect = "account";
}
echo '<div class="info">Treasury <b>'.$reqlvl.'</b>, Effect <b>'.$effect.'</b>';
echo '</div></td><td class="pla"><a href="karte.php?d='.$row['vref'].'&c='.$generator->getMapCheck($row['vref']).'">'.$database->getUserField($row['owner'],"username",0).'</a></td>';
echo '<td class="dist">'.getDistance($coor['x'], $coor['y'], $coor2['x'], $coor2['y']).'</td>';
echo '</tr>';
}
?>
but the code seems to be wrong because its showing all same distances. 14.8 to me. I know i maybe have bad explanation but u will probably understand what I need.
A: I can't help with your current code I'm afraid but you could try using the Haversine Formula instead:
// Where:
// $l1 ==> latitude1
// $o1 ==> longitude1
// $l2 ==> latitude2
// $o2 ==> longitude2
function haversine ($l1, $o1, $l2, $o2) {
$l1 = deg2rad ($l1);
$sinl1 = sin ($l1);
$l2 = deg2rad ($l2);
$o1 = deg2rad ($o1);
$o2 = deg2rad ($o2);
$distance = (7926 - 26 * $sinl1) * asin (min (1, 0.707106781186548 * sqrt ((1 - (sin ($l2) * $sinl1) - cos ($l1) * cos ($l2) * cos ($o2 - $o1)))));
return round($distance, 2);
}
Credit goes to this post on go4expert.com, I've used this function in the past and found it works very well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Entity Framework cannot access entity classes I have used Entity Framework for DAL in a few projects but in the one I'm working on right now, I have the edmx file in a class library project and that's all there is in the project. I have this project referenced in another class library project and for some reason I'm not able to access any of the entity classes that are defined in the .designer.cs file. I can't access the context class either. If i look at the referenced project in Object viewer in visual studio, it does not list any entities for this project.
Does anyone know why I'm not able to access the entity classes or the datacontext in another project?
EDIT: If it makes any difference, it's associated with a database on sql azure.
A: This is can happen into two different ways. One is to make sure the Entity Model class are public. The other is to check the Entity Model Namespace is matches to the Context class.
A: I was able to resolve it by deleting the existing edmx file and regenerating a new one.
Apparently the old one got into a weird state, I was not able to figure out how to get it to work again.
A: I have used Entity Framework for DAL in a few projects but in the one I'm working on right now, I have the edmx file in a class library project and that's all there is in the project. I have this project referenced in another class library project where i was not able to initialize the object for the entity class saying connection string was not set ,where i have checke with the connection string which was there.\
A: check your inherited class of DbContext, it must be public
A: Check the Namespaces of the Context class and Designer.cs class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Undefined method `stringify_keys' when calling update_attributes? I am getting this error: undefined method `stringify_keys' for :environ_gross_score:Symbol
when I attempt to create a new rating.
class Rating < ActiveRecord::Base
belongs_to :city
after_save :calculate_rating
def calculate_rating
@env = self.environ
self.city.environ_vote_count += 1
@c = self.city.environ_gross_score
@gross = @c += @env
self.city.update_attributes(:environ_gross_score, @gross )
@hold = self.city.environ_gross_score / self.city.environ_vote_count
self.city.update_attributes(:environ_rating, @hold)
end
end
A: update_attributes takes a single hash, not 2 parameters. Change the line to:
self.city.update_attributes(:environ_gross_score => @gross)
The error was happening because the method assumed that the first argument passed was a hash, which does (in Rails) respond to stringify_keys.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jQuery: get JSON via ajax, but with POST instead of GET I'm using jQuery's $.ajax to make a request to a third-party server, using JSONP. I specify the method as POST, but it uses GET anyway:
$.ajax({
type: "POST",
dataType: "json",
url: other_server + "/run?callback=?",
data: {
code: $(code).val()
},
success: function(obj) {
var res = obj.results;
$(results).val(res);
}
});
Looking in the jQuery source, I see these two lines that seem to force all cross-domain requests to GET, but I don't understand why it needs to be so:
if ( s.crossDomain ) {
s.type = "GET";
Is it possible to do this with a POST instead of a GET? Why does jQuery force the use of GET?
A: JSON-P works by inserting a <script> element into the document, hence it can only make GET requests.
If you want to make a POST request to a remote server then you need to look at XHR instead and set up CORS permissions. Note that this has limited browser support.
Alternatively, keep your requests to the same origin (and have your server make the request to the remote server).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Rails 3.1 - embedding flash.swf files - best practices? Having problems embedding my .swf file in rails 3.1. In past versions of rails I'd use swfobject and simply do:
<div id="swfbox">you don't have flash</div>
<script type ="text/javascript">
swfobject.embedSWF("swf/AudioRecorder.swf", "swfbox", "400", "400", "10.0.0", "");
</script>
This isn't working in rails 3.1. I'm starting to understand the asset pipeline but I'm still confused where to put the .swf file. So far I've tried of putting everything in /public then /app/assets with a combination using:
<%= asset_path("swf/AudioRecorder.swf") %>
A: You should be able to put it in any directory you like under app/assets, then reference it with
<%= asset_path("AudioRecorder.swf") %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Sorted view of a List is it somehow possible to get a sorted List view of a List with the elements from the original List, modify the elements, for example set a property, but the original List should reflect the changes?
Background is I'm sorting two Lists, then for each equal element I'm setting a property (basically it's the intersection) but finally I need the unsorted List with the modified elements.
kind regards,
Johannes
A: If the List holds references to objects (not primitive data types), then just copy the list, sort it and modify the elements.
A: Does it have to be a list? If you keep your elements in a TreeSet, they will always be sorted as you iterate through them, even after you add/remove the elements. Remember though that modifying an element already in the TreeSet may break the sort order. You can remove and add the element to the TreeSet to get around that.
If you have to use a list, you can use Collections.sort(List list) after adding or modifying an element. Of course, if you have to call it often, there will be a performance hit. If performance is a concern, you can just insert the new element (or move the modified one) to maintain the sorted order, which will be cheaper than sorting it: O(n) vs O(n*log(n))
A: Probably the simplest thing to do is add the elements to a new list, sort that list, and when you modify the elements, the original elements will still be modified...
List<?> origA;
List<?> origB;
List<?> newA = new ArrayList<?>(origA);
List<?> newB = new ArrayList<?>(origB);
Collections.sort(newA);
Collections.sort(newB);
// do mods
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use switch-case on a Type?
Possible Duplicate:
Is there a better alternative than this to 'switch on type'?
I need to iterate through all properties of my class and to check if its type of int the i need to do something, if its string .. then do something. I need it using switch-case. Here i am using switch in the following manner, but it asks for some constant. see the code below:
public static bool ValidateProperties(object o)
{
if(o !=null)
{
var sourceType = o.GetType();
var properties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Static);
foreach (var property in properties)
{
var type = property.GetType();
switch (type)
{
*case typeof(int):* getting error here
// d
}
}
}
}
Also i want to know , what check should I use, typeof(int) or typeof(Int32)?
A: You cannot use a switch block to test values of type Type. Compiling your code should give you an error saying something like:
A switch expression or case label must be a bool, char, string,
integral, enum, or corresponding nullable type
You'll need to use if-else statements instead.
Also: typeof(int) and typeof(Int32) are equivalent. int is a keyword and Int32 is the type name.
UPDATE
If you expect that most types will be intrinsic you may improve performance by using a switch block with Type.GetTypeCode(...).
For example:
switch (Type.GetTypeCode(type))
{
case TypeCode.Int32:
// It's an int
break;
case TypeCode.String:
// It's a string
break;
// Other type code cases here...
default:
// Fallback to using if-else statements...
if (type == typeof(MyCoolType))
{
// ...
}
else if (type == typeof(MyOtherType))
{
// ...
} // etc...
}
A: Usually, the easiest solution is to switch on the type name:
switch (type.Name)
{
case "Int32":
...
}
A: This "answer" is an elaboration for Jon's answer. (Marking CW)
For the record, DynamicInvoke is a bit slow. To illustrate this, consider the following program:
void Main()
{
Func<int, string> myFunc = i => i.ToString();
myFunc.DynamicInvoke(1); // Invoke once so initial run costs are not considered
myFunc(1);
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 1000000; i++)
myFunc.DynamicInvoke(1);
stopwatch.Stop();
var elapsed = stopwatch.Elapsed;
stopwatch.Restart();
for (int i = 0; i < 1000000; i++)
myFunc(1);
stopwatch.Stop();
var elapsed2 = stopwatch.Elapsed;
Console.WriteLine("DynamicInvoke: " + elapsed);
Console.WriteLine("Direct Invocation: " + elapsed2);
}
Prints out:
DynamicInvoke: 00:00:03.1959900
Direct Invocation: 00:00:00.0735220
Which means that DynamicInvoke (in this simple case) is 42 times slower than direct invocation.
A: A good and extensible way to do this is to make a dictionary of types and delegates of appropriate type, based on what you want to do with values of that type.
For example:
var typeProcessorMap = new Dictionary<Type, Delegate>
{
{ typeof(int), new Action<int>(i => { /* do something with i */ }) },
{ typeof(string), new Action<string>(s => { /* do something with s */ }) },
};
And then:
void ValidateProperties(object o)
{
var t = o.GetType();
typeProcessorMap[t].DynamicInvoke(o); // invoke appropriate delegate
}
This solution is extensible, configurable even at run time, and as long as you keep the keys and types of delegate values in typeProcessorMap correctly matched is also type safe.
See it in action.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: Grouping lists within lists in Python 3 I have a list of lists of strings like so:
List1 = [
['John', 'Doe'],
['1','2','3'],
['Henry', 'Doe'],
['4','5','6']
]
That I would like to turn into something like this:
List1 = [
[ ['John', 'Doe'], ['1','2','3'] ],
[ ['Henry', 'Doe'], ['4','5','6'] ]
]
But I seem to be having trouble doing so.
A: List1 = [['John', 'Doe'], ['1','2','3'],
['Henry', 'Doe'], ['4','5','6'],
['Bob', 'Opoto'], ['10','11','12']]
def pairing(iterable):
it = iter(iterable)
itn = it.next
for x in it :
yield (x,itn())
# The generator pairing(iterable) yields tuples:
for tu in pairing(List1):
print tu
# produces:
(['John', 'Doe'], ['1', '2', '3'])
(['Henry', 'Doe'], ['4', '5', '6'])
(['Bob', 'Opoto'], ['8', '9', '10'])
# If you really want a yielding of lists:
from itertools import imap
# In Python 2. In Python 3, map is a generator
for li in imap(list,pairing(List1)):
print li
# or defining pairing() precisely so:
def pairing(iterable):
it = iter(iterable)
itn = it.next
for x in it :
yield [x,itn()]
# produce
[['John', 'Doe'], ['1', '2', '3']]
[['Henry', 'Doe'], ['4', '5', '6']]
[['Bob', 'Opoto'], ['8', '9', '10']]
Edit: Defining a generator function isn't required, you can do the pairing of a list on the fly:
List1 = [['John', 'Doe'], ['1','2','3'],
['Henry', 'Doe'], ['4','5','6'],
['Bob', 'Opoto'], ['8','9','10']]
it = iter(List1)
itn = it.next
List1 = [ [x,itn()] for x in it]
A: This should do what you want assuming you always want to take pairs of the inner lists together.
list1 = [['John', 'Doe'], ['1','2','3'], ['Henry', 'Doe'], ['4','5','6']]
output = [list(pair) for pair in zip(list1[::2], list1[1::2])]
It uses zip, which gives you tuples, but if you need it exactly as you've shown, in lists, the outer list comprehension does that.
A: Here it is in 8 lines. I used tuples rather than lists because it's the "correct" thing to do:
def pairUp(iterable):
"""
[1,2,3,4,5,6] -> [(1,2),(3,4),(5,6)]
"""
sequence = iter(iterable)
for a in sequence:
try:
b = next(sequence)
except StopIteration:
raise Exception('tried to pair-up %s, but has odd number of items' % str(iterable))
yield (a,b)
Demo:
>>> list(pairUp(range(0)))
[]
>>> list(pairUp(range(1)))
Exception: tried to pair-up [0], but has odd number of items
>>> list(pairUp(range(2)))
[(0, 1)]
>>> list(pairUp(range(3)))
Exception: tried to pair-up [0, 1, 2], but has odd number of items
>>> list(pairUp(range(4)))
[(0, 1), (2, 3)]
>>> list(pairUp(range(5)))
Exception: tried to pair-up [0, 1, 2, 3, 4], but has odd number of items
Concise method:
zip(sequence[::2], sequence[1::2])
# does not check for odd number of elements
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ifstream can't locate file? I'm trying to read a file called "sample.txt" but whenever i try to do an ifstream, it can never locate the file. So my question is where do you put the file so that it can be located?
ifstream iFile("sample.txt");
A: Here is the solution.
1) Open your project in Xcode;
2) Locate the Products folder in the Groups & Files tree on the left side of your Project window;
3) When you expand that folder, you should see the icon for the Unix Executable File (usually a black rectangle);
4) Ctrl-click on that icon and select Show in Finder_ (If you accidentally choose Open With Finder, the Finder will start your program in a Terminal window);
5) Show in Finder should bring up a Finder window showing the contents of the folder which includes your executable. You should see your output files in that window.
Source: https://discussions.apple.com/thread/2145737?start=0&tstart=0
A: If you don't specify an absolute path the file name is interpreted to be relative to the working directory of the program.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: id comparison is not working correctly I am trying to compare the classes of an id object. However, if I try and compare the object's class to the class of NSNumber, it won't register as equal to, even though I have set some variables to NSNumbers. Please can you tell me why it isn't registering, here is my code.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:n.title forKey:@"title"];
[dict setObject:[NSNumber numberWithBool:n.allDay] forKey:@"allDay"];
[dict setObject:[NSNumber numberWithInt:n.availability] forKey:@"availability"];
[dict setObject:[NSNumber numberWithInt:n.createdBy] forKey:@"createdBy"];
[dict setObject:n.endDate forKey:@"endDate"];
[dict setObject:n.location forKey:@"location"];
[dict setObject:n.notes forKey:@"notes"];
[dict setObject:n.ownerUsername forKey:@"ownerUsername"];
[dict setObject:n.startDate forKey:@"startDate"];
[dict setObject:[NSNumber numberWithInt:n.status] forKey:@"status"];
NSMutableString *json = [NSMutableString string];
[json appendString:@"{"];
for (NSString *key in [dict allKeys]) {
id obj = [dict objectForKey:key];
if ([[dict allKeys] indexOfObject:key] == 0) {
if ([obj class] == [NSNumber class])
[json appendFormat:@"\"%@\":%@", key, obj];
else
[json appendFormat:@"\"%@\":\"%@\"", key, obj];
}
else {
if ([obj class] == [NSNumber class])
[json appendFormat:@",\"%@\":%@", key, obj];
else
[json appendFormat:@",\"%@\":\"%@\"", key, obj];
}
}
[json appendString:@"}"];
A: Use: if ([obj isKindOfClass:[NSNumber class]]) ...
A: This is because NSNumber is a cluster class, when you create an instance of NSNumber you actually get a instance of a subclass. As ott said you should use isKindOfClass:.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Check if facebook oauth 2.0 october 1st migration is done I'm using facebook connect on a website, it worked well with PHP SDK 3.0.1.
Now I've downloaded and started using PHP SDK v.3.1.1 and set Encrypted Access Token to enabled. It still works without problems. Is this enough for the migration? How can I check it? I don't use the js sdk.
A: According to the migration guide, it looks like you have done all the steps you need for Facebook on an external website by upgrading to 3.1.1 PHP SDK and set encrypted access token.
If you were hosting a fan page or app inside Facebook you would also need an SSL certificate. And there are several code changes required if you are using the javascript SDK which you say you aren't.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to compile OpenCL on Ubuntu? Question: What is needed headers and drivers are needed and where would I get them for compiling open CL on ubuntu using gcc/g++?
Info: for a while now I've been stumbling around trying to figure out how to install open CL on my desktop and if possible my netbook. There are a couple tutorials out there that I've tried but none seem to work. Also, they all just give a step by step with out really explaining why for the what, or even worse they are specific to a particular IDE so you have to learn the IDE to be able to do anything.
So I have an NVIDA GX465 in my desktop and integrated graphics in my netbook. my priority is of course my desktop, the netbook is just a convenience for development purposes(both run ubuntu 11.04 and will be running 11.10 as soon as it comes out). Can some one spell out for me what exactly is needed to get it so I can actually compile code and have it run. and if you could also explain what each piece does so that I can understand it's importance.
A: Ubuntu 20.04 with an NVIDIA Quadro M1200, Lenovo P51
The software integration got a lot better since I had last tried, so I will do an update.
First, at least for graphics, I needed to tweak some BIOS settings as mentioned at, not sure needed for OpenCL: https://askubuntu.com/questions/973605/ubuntu-17-10-boot-stuck-at-message-started-nvidia-persistence-daemon-after-ins/976578#976578
Then, I find and install the latest driver available:
apt-cache search nvidia-driver
sudo apt install nvidia-driver-435 nvidia-opencl-dev
You can also search under:
software-properties-gtk
in the "Additional Drivers" tab.
Now I can compile and run the following test program:
main.c
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#define CL_TARGET_OPENCL_VERSION 220
#define CL_USE_DEPRECATED_OPENCL_1_2_APIS
#include <CL/cl.h>
int main() {
cl_command_queue command_queue;
cl_context context;
cl_device_id device;
cl_int input = 1;
cl_int kernel_result = 0;
cl_kernel kernel;
cl_mem buffer;
cl_platform_id platform;
cl_program program;
const char *source = "__kernel void increment(int in, __global int* out) { out[0] = in + 1; }";
clGetPlatformIDs(1, &platform, NULL);
clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, NULL);
context = clCreateContext(NULL, 1, &device, NULL, NULL, NULL);
command_queue = clCreateCommandQueue(context, device, 0, NULL);
buffer = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, sizeof(cl_int), NULL, NULL);
program = clCreateProgramWithSource(context, 1, &source, NULL, NULL);
clBuildProgram(program, 1, &device, "", NULL, NULL);
kernel = clCreateKernel(program, "increment", NULL);
clSetKernelArg(kernel, 0, sizeof(cl_int), &input);
clSetKernelArg(kernel, 1, sizeof(cl_mem), &buffer);
clEnqueueTask(command_queue, kernel, 0, NULL, NULL);
clFlush(command_queue);
clFinish(command_queue);
clEnqueueReadBuffer(command_queue, buffer, CL_TRUE, 0, sizeof (cl_int), &kernel_result, 0, NULL, NULL);
assert(kernel_result == 2);
return EXIT_SUCCESS;
}
GitHub upstream
with:
gcc -ggdb3 -O0 -Wall -Wextra -pthread -std=c11 \
-pedantic-errors -o main.out main.c -lm -pthread -lOpenCL
./main.out
Notes:
*
*find your GPU model: https://askubuntu.com/questions/72766/how-do-i-find-out-the-model-of-my-graphics-card
*test that the driver is working: https://askubuntu.com/questions/68028/how-do-i-check-if-ubuntu-is-using-my-nvidia-graphics-card
*similar answer for CUDA: https://askubuntu.com/questions/917356/how-to-verify-cuda-installation-in-16-04/1215237#1215237
Ubuntu 15.10 with an NVIDIA NVS 5400M, Lenovo T430
sudo apt-get install nvidia-352 nvidia-352-dev nvidia-prime nvidia-modprobe
sudo ln -s /usr/include/nvidia-352/GL /usr/local/include
sudo ln -s /usr/lib/x86_64-linux-gnu/libOpenCL.so.1 /usr/local/lib/libOpenCL.so
Then use the header as:
#include <CL/cl.h>
And compile with:
gcc -o main main.c -lOpenCL
Notes:
*
*do not install the nvidia-current package. It is old. Either apt-cache search nvidia and get the latest one, or use software-properties-gtk "Additional Drivers" tab.
I really recommend upgrading to 15.10 to get this to work: I had never managed before.
A: Things that worked for me in Ubuntu 16.04
I have installed openCL on:
SandyBridge CPU: cpu only
IvyBridge GPU
Nvidia GTX 950
install packets
Generic ubuntu packages for OpenCL
Basic installation
sudo apt install ocl-icd-libopencl1
sudo apt install opencl-headers
sudo apt install clinfo
Package that allows to compile OpenCL code (1.2 I think)
Needed to link and compile
sudo apt install ocl-icd-opencl-dev
For Intel GT core
Package that enables runnig openCL on Intel GT, IvyBridge and up
sudo apt install beignet
For SandyBridge Intel CPU and possible others
Download this file
OpenCL™ Runtime 16.1.1 for Intel® Core™ and Intel® Xeon® Processors for Ubuntu* (64-bit)
On https://software.intel.com/en-us/articles/opencl-drivers#latest_linux_SDK_release
Install packages for turning rpm to deb
sudo apt-get install -y rpm alien libnuma1
Untar downloaded file
tar -xvf opencl_runtime_16.1.1_x64_ubuntu_6.4.0.25.tgz
cd opencl_runtime_16.1.1_x64_ubuntu_6.4.0.25/rpm/
Turn rpm files to deb
fakeroot alien --to-deb opencl-1.2-base-6.4.0.25-1.x86_64.rpm
fakeroot alien --to-deb opencl-1.2-intel-cpu-6.4.0.25-1.x86_64.rpm
Install .deb packages
sudo dpkg -i opencl-1.2-base_6.4.0.25-2_amd64.deb
sudo dpkg -i opencl-1.2-intel-cpu_6.4.0.25-2_amd64.deb
Touch local config file
sudo touch /etc/ld.so.conf.d/intelOpenCL.conf
Open the file
sudo vim /etc/ld.so.conf.d/intelOpenCL.conf
and add the line
/opt/intel/opencl-1.2-6.4.0.25/lib64/clinfo
Create a vendors dir and add intel.icd
sudo mkdir -p /etc/OpenCL/vendors
sudo ln /opt/intel/opencl-1.2-6.4.0.25/etc/intel64.icd /etc/OpenCL/vendors/intel64.icd
sudo ldconfig
test if this worked
clinfo should list your devices
Dowload this file
https://codeload.github.com/hpc12/tools/tar.gz/master
Run this code to make sure everything works
tar xzvf tools-master.tar.gz
cd tools-master
make
./print-devices
./cl-demo 1000 10
This should print out GOOD in the end
For Nvidia
install nvidia drivers (I used 370), this should include all the runtime dirvers
A: I've recently used similar process on a clean build on linux, setting up OpenCL with an NVIDIA card.
Steps I took:
1 - install the NVIDIA driver.
2 - install the CUDA tool kit - (follwing the steps in the guide, there are many ways to do it, but I used the .deb installer, guide can be found here: http://docs.nvidia.com/cuda/cuda-getting-started-guide-for-linux/)
3 - using apt-get install the OpenCL headers. Command: sudo apt-get install opencl-headers
Using the : CL/opencl.h header I was able to compile C/C++ code using gcc/g++ and the flag: -lOpenCL
Explaination of steps
1 - Self explanatory
2 - The CUDA toolkit also installs the OpenCL library (libOpencl.so) but not the header (at least not on my system)
3 - hence the header can be installed with apt-get. The header files get stored in the /usr/include/CL directory
A: To compile and run OpenCL code under Linux, you'll need four things:
1) An NVIDIA Driver which supports OpenCL. The drivers packaged with Ubuntu are somewhat
old, but they should still work just fine. Unless you have explicit need for current
drivers, you should stick with the ones packaged with Ubuntu. To be clear, these are
the same drivers installed through the restricted drivers manager. OpenCL libaries are shipped with driver, so to just run OpenCL programs driver should be enough.
2) The CUDA toolkit. This includes the headers necessary to compile OpenCL code. Install this to the default location.
3) The GPU Computing SDK (optional). This includes various NVIDIA specific support tools, as well as OpenCL code samples.
All three of these items may be found at http://developer.nvidia.com/cuda-toolkit-40.
4) OpenCL C++ bindings (optional). Strangely, they are not included with CUDA Toolkit, but in case you use C++, they could make your code much more redable. You can download them from http://www.khronos.org/registry/cl/api/1.1/cl.hpp, and just put it in /usr/local/cuda/include/CL an you desktop.
Once these are installed, you'll need to perform a few more steps to be able to compile and run OpenCL outside of the NVIDIA SDK.
1) The CUDA toolkit will have included the OpenCL headers (Listed at http://www.khronos.org/registry/cl/), likely they are in the directory /usr/local/cuda/include/CL. To make these headers available system wide, you should link this directory into /usr/include/, such that they may be accessed as /usr/include/CL/[headerfilename]. Instead of creating a symlink, you could add /usr/local/cuda/include to your C_INCLUDE_PATH and CPLUS_INCLUDE_PATH environment variables, but this would last for only currest session.
2) Make sure that the OpenCL library (libOpenCL.so) is present in /usr/lib. This should have been put in place by the driver, so you shouldn't have to do anything.
You're ready to write code. Make sure to include CL/cl.h (or CL/cl.hpp if you'd like to use C++ version of API) in any C(++) program which makes OpenCL API calls. When you compile, make sure to link against the OpenCL library (pass gcc the -lOpenCL flag).
As far as your netbook, integrated graphics don't generally support OpenCL. In theory, AMD's APP Acceleration supports running OpenCL on the CPU, but it's not clear that it actually works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Make gif from multiple PNG files I'm trying to combine about 45 png files to make a gif, or to make a video, or some type of movie or animated image.
Please provide ideas for how I can do this? Is there free software I can download? Is there Java code I can write to do this? etc.
Thanks
A: You can use a free program called GIMP.
There are plenty of videos on youtube saying how to do that.
A: You can use ImageMagick. There's plenty of documentation on creating GIF animations.
It may be as simple as:
convert -delay 20 -loop 0 *.png myanimation.gif
A: Both ImageMagick and GIMP will do it. With ImageMagick and PhotoStage I got an animation working and exported to an .mp4 file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Dynamically allocating length to an objective C static array Hi I am relatively new to programming on iOS and using objective C. Recently I have come across an issue I cannot seem to solve, I am writing a OBJ model loader to use within my iOS programming. For this I use two arrays as below:
static CGFloat modelVertices[360*9]={};
static CGFloat modelColours[360*12]={};
As can be seen the length is currently allocated with a hard coded value of 360 (the number of faces in a particular model). Is there no way this can be dynamically allocated from a value that has been calculated after reading the OBJ file as is done below?
int numOfVertices = //whatever this is read from file;
static CGFloat modelColours[numOfVertices*12]={};
I have tried using NSMutable arrays but found these difficult to use as when it comes to actually drawing the mesh gathered I need to use this code:
-(void)render
{
// load arrays into the engine
glVertexPointer(vertexStride, GL_FLOAT, 0, vertexes);
glEnableClientState(GL_VERTEX_ARRAY);
glColorPointer(colorStride, GL_FLOAT, 0, colors);
glEnableClientState(GL_COLOR_ARRAY);
//render
glDrawArrays(renderStyle, 0, vertexCount);
}
As you can see the command glVertexPointer requires the values as a CGFloat array:
glVertexPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
A: You could use a c-style malloc to dynamically allocate space for the array.
int numOfVertices = //whatever this is read from file;
CGFloat *modelColours = (CGFloat *) malloc(sizeof(CGFloat) * numOfVertices);
A: When you declare a static variable, its size and initial value must be known at compile time. What you can do is declare the variable as a pointer instead of an array, the use malloc or calloc to allocate space for the array and store the result in your variable.
static CGFloat *modelColours = NULL;
int numOfVertices = //whatever this is read from file;
if(modelColours == NULL) {
modelColours = (CGFloat *)calloc(sizeof(CGFloat),numOfVertices*12);
}
I used calloc instead of malloc here because a static array would be filled with 0s by default, and this would ensure that the code was consistent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should I use system_category or generic_category for errno on Unix? C++0x has two predefined error_category objects: generic_category() and system_category(). From what I have understood so far, system_category() should be used for errors returned by the operating system, and generic_category() should be used for the generic values found in std::errc, which correspond to errno values.
However, what should be done on Unix-like systems, where errno values are the errors returned by the operating system? Should I use system_category() (which would be wrong on non-Unix-like systems, needing an #ifdef), or should I use generic_category() (which would be wrong on Unix-like systems for non-standard errno values)?
A: You are meant to report errors from OS (any one, including POSIX-based OSes such as Unix) using system_category() as C++ standard library functions do - see the quote from C++11 standard below:
17.6.5.14 Value of error codes [value.error.codes]
1 Certain functions in the C++ standard library report errors via a std::error_code (19.5.2.1) object. That
object’s category() member shall return std::system_category() for errors originating from the operating
system, or a reference to an implementation-defined error_category object for errors originating
elsewhere. The implementation shall define the possible values of value() for each of these error categories.
[ Example: For operating systems that are based on POSIX, implementations are encouraged to define the
std::system_category() values as identical to the POSIX errno values, with additional values as defined
by the operating system’s documentation. Implementations for operating systems that are not based
on POSIX are encouraged to define values identical to the operating system’s values. For errors that do
not originate from the operating system, the implementation may provide enums for the associated values.
—end example ]
A: You should not use system_category unless you are in fact the operating system (or reporting an error from an OS-specific function). The category describes where the error originates from, not necessarily what the error code means. So it is perfectly legitimate to have the set of possible error codes from system_category be the same as generic_category.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Is it possible to customize RichTextBox.DetectUrls behaviour RichTextBox will highlight standard http urls and allow me to catch when someone clicks on this link. But the current project I'm working on requires me to make links with a custom url scheme so instead of http://foo.bat I have myapp://some.host/params.
Is it possible to customize the way RichTextBox's DetectUrls does it's thing?
Update: This is in context of a WinForms app.
A: Yes! it's possible. Check out this project in codeproject.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Database design duplicate column -websafe urls In the interest of good relational database design:
There are currently two columns in the DB: "GroupName" and "WebGroupName". The second column is used for simple url access to a profile. Eg: www.example.com/myWebGroupName the reason for this is that it avoids spaces being passed in the url for example: www.example.com/my Web Group Name would not work
To re-iterate the DB structure; column 1 would store "My Group Name" and column two would store "MyGroupName".
Possible solutions may err on the side of storing the group name without spaces then using some regular expression to add the spaces back. The focus of my question is how to eliminate the need for two columns storing near-duplicate date.
Thank you for your time
A: Assuming that you really have a problem with spaces in URLs (as Larry Lustig pointed out it isn't necessarily a problem) - Then it isn't bad relational database design to have two columns that often have very similiar information.
The kind of repetition that is to be avoided (normalized) deals with repetition across multiple rows. If you have two columns which are meant to contain different, but related information, then these two columns are perfectly OK and you aren't breaking any rules. The fact that sometimes these two columns are equal (coincidentally) is not a problem.
You said:
Possible solutions may err on the side of storing the group name
without spaces then using some regular expression to add the spaces
back. The focus of my question is how to eliminate the need for two
columns storing near-duplicate date.
From this I assume that what is most important to your system is the web group name. If the group name were the driver then writing an expression that removes spaces would be trivial. If the web group name is something that can be set arbitrarily based on the group name, then you should store the name with spaces and replace them with empty strings when you need a web group name. If the web group name is not completely arbitrary then you really do have two independent data points and they need to be stored in two separate columns.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "unrecognized selector sent to instance" when keyboard appears When I click a text field into my app screen and the keyboard is showing up xcode debugger shows this error:
[mainViewController keyboardWasShown]: unrecognized selector sent to instance 0x5867ac0
In the viewDidLoad method of the mainViewController I'm calling the registerForKeyboardNotifications method like that:
[self registerForKeyboardNotifications];
Here's its implementation (in mainViewController.m):
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
}
Any idea what could be wrong?
A: Make sure the notification selector has the colon at the end; this is important, keyboardWasShown and keyboardWasShown: are different selectors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: .NETLink Graphics producing PNG instead of EMF The C# code below should produce an EMF, but viewing the output (in Vim) shows it to be a PNG. Perhaps someone on S.O. knows a good work-around or solution.
MathKernel k = new MathKernel();
k.CaptureGraphics = true;
k.GraphicsFormat = "Metafile";
k.Compute("Show[Graphics[{Thick, Blue, Circle[{#, 0}] & /@ Range[4], Black, Dashed, Line[{{0, 0}, {5, 0}}]}]]");
k.Graphics[0].Save("C:\\Temp\\file.emf", System.Drawing.Imaging.ImageFormat.Emf);
So far I'm considering wrapping Show[Graphics...] in ExportString[... , "EMF"] and collecting the result using the MathKernel Result property.
Addendum
The MathKernel.Graphics property[1] is apparently a .Net Graphics method which only handles image files such as bitmaps, not vector graphic based enhanced metafiles.
*
*http://reference.wolfram.com/legacy/v7/NETLink/ref/net/Wolfram.NETLink.MathKernel.Graphics.html
Enhanced metafiles can be transferred through .NETLink one at a time though, in the following manner:
using System;
using System.IO;
using Wolfram.NETLink;
public class Example
{
public static void Main(String[] args)
{
MathKernel k = new MathKernel();
k.Compute("ExportString[Graphics[{Disk[]}], {\"Base64\", \"EMF\"}]");
byte[] decodedBytes = Convert.FromBase64String(k.Result.ToString());
// The transferred EMF can be used or simply written out to file.
File.WriteAllBytes("C:\\Temp\\file.emf", decodedBytes);
}
}
A: Here is a working solution:
using System;
using Wolfram.NETLink;
public class Example {
public static void Main(String[] args) {
MathKernel k = new MathKernel();
k.Compute("Export[\"c:/users/arnoudb/out.emf\", Graphics[{Disk[]}], \"EMF\"]");
}
}
I am not sure why you consider this part:
k.Graphics[0].Save("C:\\Temp\\file.emf", System.Drawing.Imaging.ImageFormat.Emf);
a Mathematica bug, since k.Graphics[0] is a pure C# System.Drawing.Image class. Perhaps you can clarify this part a bit?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Avoiding redirection I'm trying to parse a site(written in ASP) and the crawler gets redirected to the main site. But what I'd like to do is to parse the given url, not the redirected one. Is there a way to do this?. I tried adding "REDIRECT=False" to the settings.py file without success.
Here's some output from the crawler:
2011-09-24 20:01:11-0300 [coto] DEBUG: Redirecting (302) to <GET http://www.cotodigital.com.ar/default.asp> from <GET http://www.cotodigital.com.ar/l.asp?cat=500&id=500>
2011-09-24 20:01:11-0300 [coto] DEBUG: Redirecting (302) to <GET http://www.cotodigital.com.ar/default.asp> from <GET http://www.cotodigital.com.ar/l.asp?cat=1513&id=1513>
2011-09-24 20:01:11-0300 [coto] DEBUG: Redirecting (302) to <GET http://www.cotodigital.com.ar/default.asp> from <GET http://www.cotodigital.com.ar/l.asp?cat=476&id=476>
2011-09-24 20:01:11-0300 [coto] DEBUG: Redirecting (302) to <GET http://www.cotodigital.com.ar/default.asp> from <GET http://www.cotodigital.com.ar/l.asp?cat=472&id=472>
2011-09-24 20:01:11-0300 [coto] DEBUG: Redirecting (302) to <GET http://www.cotodigital.com.ar/default.asp> from <GET http://www.cotodigital.com.ar/l.asp?cat=457&id=457>
2011-09-24 20:01:11-0300 [coto] DEBUG: Redirecting (302) to <GET http://www.cotodigital.com.ar/default.asp> from <GET http://www.cotodigital.com.ar/l.asp?cat=1097&id=1097>
A: http://www.cotodigital.com.ar/l.asp?cat=1097&id=1097 redirects to http://www.cotodigital.com.ar/default.asp because HTTP response said to so. This happens because asp code is checking for some condition - a wrong page, or cookies, or user-agent, or referrer. Check the mentioned conditions.
UPDATE:
Just checked in my browser: the browser is also redirected to the main page, where i click 'Skip ads'. After that it works OK.
This means it sets some cookies, without which it redirects to the main page.
See also Scrapy - how to manage cookies/sessions
A: The original URL has nothing to scrape. It returned 302, meaning there is no body, and the Location header indicates where to redirect to. You need to figure out how to access the URL without being redirected, perhaps by authenticating.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Heroku help Permission denied how to open file? I get this error on Heroku:
←[36m2011-09-25T00:24:51+00:00 app[web.1]:←[0m Rendered admin/xml/index.rhtml wi
thin layouts/admin (87.7ms)
←[36m2011-09-25T00:24:51+00:00 app[web.1]:←[0m Completed in 89ms
←[36m2011-09-25T00:24:51+00:00 app[web.1]:←[0m
←[36m2011-09-25T00:24:51+00:00 app[web.1]:←[0m ActionView::Template::Error (Perm
ission denied - /app/public/xml/preview.xml):
←[36m2011-09-25T00:24:51+00:00 app[web.1]:←[0m 1: <% update_xml("preview") %
>
←[36m2011-09-25T00:24:51+00:00 app[web.1]:←[0m 2:
←[36m2011-09-25T00:24:51+00:00 app[web.1]:←[0m 3:
←[36m2011-09-25T00:24:51+00:00 app[web.1]:←[0m 4: <h2>Preview/publish</h2>
←[36m2011-09-25T00:24:51+00:00 app[web.1]:←[0m app/helpers/admin/xml_helper.rb
:88:in `initialize'
←[36m2011-09-25T00:24:51+00:00 app[web.1]:←[0m app/helpers/admin/xml_helper.rb
:88:in `open'
←[36m2011-09-25T00:24:51+00:00 app[web.1]:←[0m app/helpers/admin/xml_helper.rb
My helper:
File.open("#{RAILS_ROOT}/public/xml/#{output}.xml", "w") do |f|
f.puts("<?xml version='1.0' encoding='UTF-8'?>")
f.puts("<site>")
f.puts("<general name='general' type='general'><imagePath>photographer/image/</imagePath><moviePath>../photographer/flv/</moviePath></general>")
f.puts("#{xmlmenu.to_xml}")
f.puts("#{xmlmovies.to_xml}")
f.puts("#{xmltextpages.to_xml}")
f.puts("</site>")
end
end
How to fix this?
Or how to create this open file wit amazon S3 and authenticate.
A: The only directory you can write to on Heroku is tmp.
A: The Cedar stack has a writable file system but it's only persistent for the life of the dyno and anything that's been written is only available to the dyno that wrote the file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Localize a WP7 application using MVVM Light I'm using MVVM Light in my Windows Phone 7 application. The application is to be used in English and Spanish. Users can select a different language during runtime. I'm localizing the application using resource files. I've already been able to make the localization works, but only when I change the language from Settings. In the main page, I have a list for users to select the language during runtime, I'm setting the selected language to Thread.CurrentThread.CurrentCulture, but the text strings in the interface don't get updated. I have a set of properties in the ViewModel that I'm binding to the View to set the labels of the control, but something is missing. I've been reading that I need to implement the INotifyPropertyChanged in the ViewModel to make this works, but I don't know how to exactly do that nor if there is a different better way to implement this case using MVVM Light. Could anybody help me here please?
A: Hum, I wrote a blog post about it sometimes ago ( http://wp7wonders.wordpress.com/2010/10/17/localize-a-windows-phone-7-application/ - read the comments too!). The main point is that you have an object between the resource files and your viewmodels which allow to change the dynamically the language.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C++ linked list append method I am writing a linked list template class in C++ as an exercise for myself to help me get back into C++ programming. I've got the following class definition:
template <typename T>
class List
{
public:
List();
~List();
void append(T data);
void display();
int count();
private:
struct Node
{
T data;
Node *next;
} *head;
};
I have two versions of the append method - one that works and one that doesn't. I can't figure out what the difference, in terms of the operations performed, is, and why the second one doesn't work. Here's the one that works:
template <typename T>
void List<T>::append(T data)
{
if (head == NULL)
{
head = new Node;
head->data = data;
head->next = NULL;
}
else
{
Node *p = head, *q;
while (p != NULL)
{
q = p;
p = p->next;
}
p = new Node;
p->data = data;
p->next = NULL;
q->next = p;
}
}
And here's the one that doesn't seem to actually add any elements to the list:
template <typename T>
void List<T>::append(T data)
{
Node *p = head, *q = head;
while (p != NULL)
{
q = p;
p = p->next;
}
p = new Node;
p->data = data;
p->next = NULL;
if (q != NULL)
{
q->next = p;
}
}
Any ideas as to why the second version doesn't add any elements? I've been trying it with type T as int.
P.S. Neither version gives any errors or warnings during compilation, nor during runtime.
A: The second method only handles the case where the list is non-empty.
When the list is empty, the line q->next = p; is never reached, so the new element is leaked with no pointer existing to it after p goes out of scope.
What you want, if you would like to eliminate the special case for empty list, is a Node **, like thus:
template <typename T>
void List<T>::append(T data)
{
Node** q = &head; /* head acts as the first Node::next link */
/* invariant: q points to some Node::next field (or head, which acts like one) */
while (*q)
q = &(*q)->next;
/* invariant: q points to the Node::next field at the end of the chain, which is currently NULL */
*q = new Node { data, nullptr };
}
A: In the first version you change the head, in the second - you don't.
Simpler would be:
template <typename T>
void List<T>::append(T data)
{
p = new Node;
p->data = data;
p->next = head;
head = p;
}
That would also be more logical because entering an item to a linked list shouldn't take O(n) as it does for you...
If you absolutely have to add to the end, do this:
template <typename T>
void List<T>::append(T data)
{
p = new Node;
p->data = data;
p->next = NULL;
if (tail)
tail->next = p;
else // first time
tail = head = p;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: childNodes on has weird stuff in it, tripping me up <tr id='tt_info_entry_2'>
<th colspan=3>Read sigma[0]</th>
<th colspan=3>Read sigma[1]</th>
</tr>
But in Chrome I get:
Note mysterious "Text" objects getting in the way of my for loop. There's three of them too. (only two <th>'s)
What's this?
P.S. I will use getElementsByTagName('th') on the <tr> to get a clean array. But still, I didn't have these weird text thingies pop up when I was doing all sorts of ninja stuff with divs. I can has explanation?
A: Whitespaces are also textNodes.
There are whitespaces before the 1st TH,after the 1st TH and after the 2nd TH (the line-breaks).
Use Element.children instead of Element.childNodes to retrieve only element-nodes.
A: When it comes to table rows and cells, you should use:
*
*table.rows[docs]
*row.cells The MDN docs link for .cells is broken right now, but as @Šime Vidas noted, it is listed on this MDN page.
They have wide browser support, and eliminate text node issues.
These give you browser compatibility back to Firefox 3 and avoids some quirks IE8 and lower have with .children.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Compiler doesn’t locate GCD header file on Windows I need to use Grand Central Dispatch in my program but I don’t know how to use it on Windows.
The error I’m getting is
error: dispatch/dispatch.h: No such file or directory
#include <dispatch/dispatch.h>
int main (int argc, const char * argv[])
{
dispatch_group_t group;
dispatch_queue_t queue; // thread queues to use
group = dispatch_group_create();
queue= dispatch_queue_create("queue", NULL);
dispatch_sync(queue, ^{
puts("Dispatch test");
} );
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
dispatch_main();
return 0;
}
A: *
*Portable libdispatch
*[libdispatch-dev] Lion libdispatch sources posted & next steps for macosforge repo
You might be able to use GCD API (libdispatch) on Windows. However, for Blocks, Blocks supported compiler(gcc with Apple's patch or LLVM clang) is needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Regexp matching for some text I have the following text:
@title1
Some stuff here and some @junk@ here
@newheader
Multiple lines.
Multiple lines.
Multiple lines.
@title3
Extra stuff here.
I need a regexp that would match the text after the titles. First match should return
Some stuff here and some @junk@ here
Also, title is something that starts on a new line with @ and it's followed by some non space characters
http://jsfiddle.net/QCNfQ/2/
A: Fiddle: http://jsfiddle.net/u5Khe/
You're looking for this RE: /(?:^|\n)@([^@\n]+)\s*((?:[\S\s](?!\n@))+)/g.
Code:
var string = "@title1\n\nTest @case@ one\n\n@title2\n\nMulti" +
"\nline\nstring\n\n@title3\n\nfinal test";
var results = [];
var re = /(?:^|\n)@([^@\n]+)\s*((?:[\S\s](?!\n@))+)/g;
var matches = null;
while((matches = re.exec(string)) != null){
/* matches[0] = whole block
matches[1] = title
matches[2] = body
*/
var body = matches[2].replace(/\^s+|\s$/g,"");
results.push(body);
}
//results.length will be 3;
alert(results.join("\n-----------------------\n"));
//Shows an alert with all matches, separated by "\n----------------\n"
Explanation of RE:
*
*(?:^|\n)@ seeks for the beginning of the title (^@ = "@ at the beginning of a text", \n@ = "@ at the beginning of a new line"
*([^@\n]+) means: Match every character except for @ or newline (delimiter of title, as defined by OP)
*((?:[\S\s](?!\n@))+) means: Select all + characters \S\s, which are not followed by a newline + @ (?!\n@).
*/g is the "global" flag = "attempts to get as much matches as possible on a given string"
Your string should be formatted like this:
@title
Body
@title2
Anything, from @ to @, as long as the next line doesn't start with a @
@ (There's a whitespace before this @)
@custom title@ Delimited by the @
@Foo
bar
A: You might be able to do something like this:
/(@title\d)(\s)*(.*)/gi;
and then access the third ($3) group.
So...
var a = "@title1\n\nSome stuff here and some @junk@";
var a1 = "@title2\n\nExtra stuff here.";
var b = /(@title\d)(\s)*(.*)/gi;
var c = a.replace(b, '$3');
var d = a1.replace(b, '$3');
document.write(c + '<br />' + d);
Example: http://jsfiddle.net/jasongennaro/5Chjf/
fyi... this assumes that @title starts every other line.
A: Try this:
var text = "@title1
Some stuff here and some @junk@
@title2
Extra stuff here.";
var output = text.replace(/([^@]+@)(\w+@)/,
function (all, g1, g2) {
return [g2, g1].join('');
}
);
alert(output)
A: Try this
'\n@title1 test'.match(/(?:\n@title\d)(?:[\s|\n])*(.*)/)[1]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jquery function only working once? I have this function that is suppose to change the html of a span. It works the first time but anyclick after that it doesn't change anything. I know the query is working because the database is updating. Here's the code.
$('#availabilityicon').click(function() {
$.ajax({
type: "GET",
url: "includes/changeavailability.php",
success: function(msg) {
if(msg === "available") {
var vailspan = $('span#avail').html('<a id="availabilityicon" href="#"><img align="center" width="16px" height="16px" src="images/available.png" /></a>');
}
else if(msg === "unavailable") {
var availspan = $('span#avail').html('<a id="availabilityicon" href="#"><img align="center" width="16px" height="16px" src="images/unavailable.png" /></a>');
}
}
});
});
here is the php code
<?php
session_start();
$user = $_SESSION['username'];
include("dbcon.php");
$result = mysql_query("SELECT availability FROM user WHERE username='$user' ORDER BY id DESC") or die(mysql_error());
$row = mysql_fetch_assoc($result);
$availability = $row['availability'];
if($availability == 'yes') {
$query = mysql_query("UPDATE user SET availability='no' WHERE username='$user'") or die(mysql_error());
echo "unavailable";
}
elseif($availability == 'no' or $availability == "") {
$query = mysql_query("UPDATE user SET availability='yes' WHERE username='$user'") or die(mysql_error());
echo "available";
}
mysql_close($con);
?>
A: There's a spelling mistake in your javascript, you've put vailspan where you probably meant to put availspan after the if(msg === "available") { line.
If it's not that, try changing the click event to a live one:
$('#availabilityicon').live('click', function() {
just in case your javascript is overwriting that the #availabilityicon icon element and failing to re-attach the event to the new one
A: The "availabiltyicon" you click is being replaced with another with the same name. You can try using .live() or you can read up on event delegation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: zsh:vcs_info: branch name in branch format I use this zsh-theme
in this line
zstyle ':vcs_info:(sv[nk]|bzr):*' branchformat '%b%F{1}:%F{11}%r'
set the branch format.
In Git, when I are in master branch show
[master]
how I can change display string from master to M?
A: I don't think you can accomplish this using just a zstyle, but you can set a hook to modify the branch variable before it is printed like this:
zstyle ':vcs_info:git*+set-message:*' hooks git-abbrv-master
function +vi-git-abbrv-master() {
hook_com[branch]=${hook_com[branch]/#%master/M}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Monotouch OpenGL retina display support I am trying to create an OpenGL app for iOS using monotouch. I need the app to support the new retina display resolution of 480x960, as well as 240x320 for the 3GS and earlier.
The out of the box OpenGL sample solution does not support this. When I run on my iPhone 4 it just displays a blurry, upscaled 240x320 version of the OpenGL view.
Surprisingly, Google has help for OpenGL and retina, as well as monotouch and retina, but not OpenGL and monotouch and retina. I have tried inspecting and tweaking with the ContentScaleFactor of both the EAGLView and the main UIWindow to no avail.
Strangely the ContentScaleFactor for both is 1.0 and not 2.0 like related literature suggests. Additionally the Screen property of the UIWindow has bounds of 240x320 at runtime, even though it is running on an iPhone 4 retina display.
Does anyone know how to properly support retina with OpenGL on monotouch?
A: The Screen object also should have a Scale property, which should be equal to 2.0 on a retina display.
As an example, MonoGame sets the view's ContentScaleFactor to MainScreen.Scale explicitly (https://github.com/mono/MonoGame/blob/master/MonoGame.Framework/iOS/IOSGameWindow.cs#L109).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Compile errors with #include in Cocoa App I am trying to compile a Cocoa app in xcode 4.0 and I'm getting this error...
fatal error: 'string' file not found
...when trying to compile to .pch file on this line:
#include <string>
I have another xcode project that does the same thing, but does not get the error. I have scoured the build settings for some different, but I can't find one. The only difference is that the project that compiles OK was started as a command line project, not a Cocoa project, but the build setting are the same.
The target OS is Mac OS X 10.6
The error happens when compiling the precompiled header and doesn't get to any of the other files. The only framework that the compiling version has is Foundation.framework and the non-compiling one has it as well.
Why is it not finding in one project and not the other? Any advice?
A: What is the extension of your source files? If it is ".m", try to change it to obj-cpp ".mm", so that Xcode will deduce correct language.
Or just put c++-specific headers inside "#ifdef __cplusplus" block
Update
The guard must exist for each language compiled in the project because this specific include is in the pch. IOW, if it were all c++ and/or objc++ there would be no error. Evidently, there is at least one file that does not recognize C++ (e.g. C or ObjC sources are also compiled in the target). Therefore, you simply guard it like so:
// MONPrefix.pch
#ifdef __cplusplus
#include <string>
#endif
// same for objc, so your C and C++ sources compile with no error:
#ifdef __OBJC__
#include <Foundation/Foundation.h>
#endif
A: string is a C++ header (for std::string). If you are looking for stuff like strcpy you need to include string.h
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Problem :Debuging in Visual C++ 2008 for opencv C++ I am using openCV 2.1 on visual c++ 2008, I made a simple program and when I tried to debug it in an step into manner, since I want to know the source of the function but cvLoadImage, Its gives an error "the source is not found for this function " and it automatically goes to the next statement. This happens all the time for each line of the program.
I am new to this kind of setting to be specified for the debug to go into the libraries and work properly. can any one please help me on this.
the code I used is
int _tmain(int argc, _TCHAR* argv[])
{
IplImage *img = cvLoadImage("funny-pictures-cat-goes-pew.jpg");
cvNamedWindow("Image:",1);
cvShowImage("Image:",img);
cvWaitKey();
cvDestroyWindow("Image:");
cvReleaseImage(&img);
return 0;
}
A: I saw this on the OpenCV homepage. Did you include the headers and the picture? You might want to revise and check your code to see if it matches with the one on the bottom of http://opencv.willowgarage.com/wiki/VisualC%2B%2B_VS2010.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SimplyScroll breaks on this page Why can't simplyscroll handle this div which has nested divs?
ADDED INFO
The scrolling isn't done. You click on the buttons, and no scrolling happens. If I change the contents of the div, to plain text, the scrolling works. This is saying that simplyscroll has trouble with the nested divs and the tags in them.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta charset="utf-8">
<title>Simply Scroll</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<!-- script type="text/javascript" src="http://localhost/jquery/jquery-1.6.2.min.js"></script -->
<link rel="stylesheet" href="http://localhost/jquery/jquery-ui-1.8.16.custom.css">
<!-- script type="text/javascript" src="/simplyscroll/jquery.simplyscroll-1.0.4.js"></script -->
<script type="text/javascript" src="http://simplyscroll.googlecode.com/files/jquery.simplyscroll-1.0.4.min.js"></script>
<link rel="stylesheet" href="/simplyscroll/jquery.simplyscroll-1.0.4.css" media="all" type="text/css">
<script type="text/javascript">
(function($) {
$(function() {
$("#scroller").simplyScroll({
className: 'vert',
horizontal: false,
frameRate: 20,
speed: 5
});
});
})(jQuery);
</script>
</head>
<body>
<div id="scroller">
<div id="u0014" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=tf1.fr" align="middle" /> <a href="http://tf1.fr" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >TF1.fr</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" title="Delete" src="/icodeact/Delete16.png" onClick="delete_url('u0014');"/>
</div>
<div id="u0015" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=www.aol.com" align="middle" /> <a href="http://www.aol.com" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >AOL.com</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" src="/icodeact/Delete16.png" onClick="delete_url('u0015');"/>
</div>
<div id="u0016" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=www.facebook.com" align="middle" /> <a href="http://www.facebook.com" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >Facebook.com</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" src="/icodeact/Delete16.png" onClick="delete_url('u0014');"/>
</div>
<div id="u0017" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=tf1.fr" align="middle" /> <a href="http://tf1.fr" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >TF1.fr</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" title="Delete" src="/icodeact/Delete16.png" onClick="delete_url('u0014');"/>
</div>
<div id="u0018" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=www.aol.com" align="middle" /> <a href="http://www.aol.com" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >AOL.com</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" src="/icodeact/Delete16.png" onClick="delete_url('u0015');"/>
</div>
<div id="u0019" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=www.facebook.com" align="middle" /> <a href="http://www.facebook.com" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >Facebook.com</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" src="/icodeact/Delete16.png" onClick="delete_url('u0014');"/>
</div>
<div id="u0020" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=tf1.fr" align="middle" /> <a href="http://tf1.fr" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >TF1.fr</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" title="Delete" src="/icodeact/Delete16.png" onClick="delete_url('u0014');"/>
</div>
<div id="u0021" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=www.aol.com" align="middle" /> <a href="http://www.aol.com" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >AOL.com</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" src="/icodeact/Delete16.png" onClick="delete_url('u0015');"/>
</div>
<div id="u0023" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=www.facebook.com" align="middle" /> <a href="http://www.facebook.com" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >Facebook.com</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" src="/icodeact/Delete16.png" onClick="delete_url('u0014');"/>
</div>
<div id="u0024" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=tf1.fr" align="middle" /> <a href="http://tf1.fr" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >TF1.fr</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" title="Delete" src="/icodeact/Delete16.png" onClick="delete_url('u0014');"/>
</div>
<div id="u0025" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=www.aol.com" align="middle" /> <a href="http://www.aol.com" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >AOL.com</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" src="/icodeact/Delete16.png" onClick="delete_url('u0015');"/>
</div>
<div id="u0026" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=www.facebook.com" align="middle" /> <a href="http://www.facebook.com" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >Facebook.com</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" src="/icodeact/Delete16.png" onClick="delete_url('u0014');"/>
</div>
<div id="u0028" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=www.facebook.com" align="middle" /> <a href="http://www.facebook.com" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >Facebook.com</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" src="/icodeact/Delete16.png" onClick="delete_url('u0014');"/>
</div>
<div id="u0029" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=tf1.fr" align="middle" /> <a href="http://tf1.fr" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >TF1.fr</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" title="Delete" src="/icodeact/Delete16.png" onClick="delete_url('u0014');"/>
</div>
<div id="u0030" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=www.aol.com" align="middle" /> <a href="http://www.aol.com" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >AOL.com</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" src="/icodeact/Delete16.png" onClick="delete_url('u0015');"/>
</div>
<div id="u0031" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=www.facebook.com" align="middle" /> <a href="http://www.facebook.com" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >Facebook.com</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" src="/icodeact/Delete16.png" onClick="delete_url('u0014');"/>
</div>
<div id="u0032" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=www.facebook.com" align="middle" /> <a href="http://www.facebook.com" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >Facebook.com</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" src="/icodeact/Delete16.png" onClick="delete_url('u0014');"/>
</div>
<div id="u0033" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=tf1.fr" align="middle" /> <a href="http://tf1.fr" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >TF1.fr</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" title="Delete" src="/icodeact/Delete16.png" onClick="delete_url('u0014');"/>
</div>
<div id="u0034" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=www.aol.com" align="middle" /> <a href="http://www.aol.com" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >AOL.com</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" src="/icodeact/Delete16.png" onClick="delete_url('u0015');"/>
</div>
<div id="u0035" class="comurl"> <img class="dhandle" src="http://www.google.com/s2/favicons?domain=www.facebook.com" align="middle" /> <a href="http://www.facebook.com" target="_blank" onmouseOver="url_preview('show', this, 'editdiv');" onmouseOut="url_preview('hide', this, 'editdiv');" >Facebook.com</a> <img src="/images/spacer.png" class="spacer" /> <img class="urlbutton" title="Edit" src="/icodeact/Edit16.png" onClick=""/> <img class="urlbutton" src="/icodeact/Delete16.png" onClick="delete_url('u0014');"/>
</div>
</div>
</body>
</html>
A: Found different code to do the continuous scrolling like SimplyScroll.
<script type="text/javascript">
$(document).ready(function($) {
$(".scrolling_prev", $("#'.$node['ID'].'")).mousedown(function() {
startScrolling($(".link_drop_box", $("#'.$node['ID'].'")), "-=50px");
}).mouseup(function() {
$(".link_drop_box", $("#'.$node['ID'].'")).stop()
});
$(".scrolling_next", $("#'.$node['ID'].'")).mousedown(function() {
startScrolling($(".link_drop_box", $("#'.$node['ID'].'")), "+=50px");
}).mouseup(function() {
$(".link_drop_box", $("#'.$node['ID'].'")).stop();
});
});
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Suppress comparison always true warning for Macros? I'm wondering if there's a simple / sane way to get gcc to stop throwing this error when the opposing target of the comparison is a macro. Yes, I recognize that with this particular definition of the macro, the comparison is always true, but it obviously doesn't extend to the general case:
#define ROMBOT 0x00000000
#define ROMTOP 0x00002000
...
if (addr >= ROMBOT && addr < ROMTOP) {
simulator.c:517:2: error: comparison of unsigned expression >= 0 is always true
One solution would be something to the effect of:
#if ROMBOT == 0
if (addr < ROMTOP) {
#else
if (addr >= ROMBOT && addr < ROMTOP) {
#endif
But that seems really ungainly / high-maintenance.
Or the related:
#define CHECK_ROM_BOT(_addr) (... etc)
But that quickly escalates into a lot of ugly / unnecessary macros.
Anyone have any ideas?
A: One possible way is to use two variables which could, perhaps, be changed, thus:
uintptr_t rombot = ROMBOT;
uintptr_t romtop = ROMTOP;
if (addr >= rombot && addr < romtop)
If these variables are visible outside the current source file, they could change under circumstances that the compiler cannot see from compiling this file, so it cannot legitimately warn about the comparison.
#include <stdint.h>
#define ROMBOT 0x00000000
#define ROMTOP 0x00002000
uintptr_t rombot = ROMBOT;
uintptr_t romtop = ROMTOP;
extern int check_addr(uintptr_t addr);
int check_addr(uintptr_t addr)
{
if (addr >= ROMBOT && addr < ROMTOP)
return 1;
if (addr >= rombot && addr < romtop)
return 2;
return 0;
}
$ make xx.o
/usr/bin/gcc -g -std=c99 -Wall -Wextra -c -o xx.o xx.c
xx.c: In function ‘check_addr’:
xx.c:13: warning: comparison of unsigned expression >= 0 is always true
$
The warning (since I didn't compile with -Werror) appears for your original code and not for the suggested replacement code. You'll need to think about the types of the variables, but uintptr_t is probably reasonable.
A: Another option that someone else thought up is to cast ROMBOT to double in the comparison with 0. This may generate extra machine instructions depending on the compiler. The cast value may not be exact, but according to C11, 6.3.1.4 item 2, it will have the correct sign, which is all you care about.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: adding HUD to UIImageView I am pulling an UIImage asynchronously to show it in my UIImageView, while I am waiting for the image, I want to show a spinner/HUD inside the UIImageView. What is a good spinner/HUD to be shown inside a HUD? I've seen a few apps that does this, not sure what to use.
A: You mean something like UIActivityIndicatorView?
Take a look at this question which covers various alternatives.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Make sound stop when button is pressed iOS I have multiple buttons that play sounds using AVAudioPlayer. If you press one, and press another before the first ends, they are both playing at the same time. How would i make it so if you press two buttons, only the last pressed button's sound plays?
A: I don't know the exact code, but you may have to bool something or try AudioServicesDisposeSystemSoundID. It will stop the sound immediately.
A: Before you start the new song you have to do:
[song1 stop];
song1.currentTime = 0;
And do that for all the songs that could be possibly playing. Then you can make the new song play. (The current time sets it to start from the beginning if you play it again.) hope that helps :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: MPMoviePlayerController from a UITableview HI I have a UITableview , when a user clicks on a particular cell i play the video using the MPmovieplayercontroller , the view plays correctly and there is a done button on top . when i click on the done button i need to come back to the main view controller wchih has the UIble view. Please see the code below and suggest me what can be done.
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
NSString *surl = [videoSelected valueForKey:@"video_path"];
NSLog(@"Video :%@",surl);
NSURL *url = [NSURL URLWithString:@"http://localhost/MyWorks/files/videos/hit.mp4"];
MPMoviePlayerController *player =[[MPMoviePlayerController alloc] initWithContentURL: url];
[[player view] setFrame: [self.view bounds]]; // frame must match parent view
[self.view addSubview: [player view]];
[player play];
[msg release];
}
A: I haven't tested this, but try
[player.navigationItem.rightBarButtonItem setAction:@selector(removeFromSuperview)];
[player.navigationItem.rightBarButtonItem setTarget:player.view];
The code just sets the right navigation item's selector to remove the view from it's superview.
P.S You might wanna add an animation, as the deletion of the superview animation is rough.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Horizontal scroll-bar issue I've set width to 100% for all main divs but there is still horizontal scroll-bar. Can't fix that problem. How to remove it? I don't know why it's appearing. Please take a look at my test page. http://aquastyle.az?lang=en
A: I cannot get your test page to open but this is typically caused when you have padding, a shadow, or a border applied to the 100% width element causing it to render wider than 100%.
Without seeing the page, I can only give the following generic advice: This can be fixed by removing the style properties that are causing the problem or reducing the width until the problem disappears.
EDIT:
After looking at your page, you don't seem to have a problem as you described. You just have too much (too big/wide) content side by side. When I make my browser's window about 1700 pixels wide, the horizontal scroll-bar disappears. This is an issue of poor layout more than programming.
EDIT 2 (The Root Cause/Solution):
It seems that the OP's PHP program is calculating the "display" width and placing content accordingly. The problem is that the "browser window" width is not the same as the "display" width. My display is 1680 pixels wide and the OP's PHP program reports that correctly. Naturally, my browser window is not 1680 pixels wide, more like 1000-1200 pixels, so I get a long horizontal scroll-bar which disappears when I make the browser window exceed 1680 pixels. Taking the width of the vertical scroll-bar into account, you actually have to make the browser window about 20 pixels wider than the display in order to get the horizontal scroll-bar to disappear (for me that was about 1700 pixels total). I imagine the OP can fix this issue by looking at browser's "viewport" (window) width rather than the computer's "display" width.
A: You'll want to use
overflow:hidden
on the element you're trying to eliminate the scroll bars from.
Or, you could use jQuery:
$("body").css("overflow", "hidden");
EDIT:
Your layout is 1920x1200. I have that resolution right now and I NEVER max out my browser window. It's always 20 to 25% smaller.
Most if not 98% of website layouts are 960px max width. I looked at your CSS (nice try with disabling right-click BTW) and you're left and right columns are both 200px EACH, while your main-content width is 1460px. I think you see where I'm going with this. I'm sorry, but the only way you're going to get no scrollbars is to redo your layout where everything fits in a 1000px layout or less. Preferably less. An important thing to check is the screen resolution stats that help in determining what percentage of users is running at a certain screen resolution. This will help you in targeting your preferred audience.
TL;DR
You gotta redo your entire layout, it's too wide for the majority of users out there..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Sum the filesizes in a directory I'm having trouble wrapping my head around how to accomplish this. I'm relatively new to working with monads/IO, so excuse me if I'm missing something obvious. I searched google for a while and came up with nothing, and nothing I've read is making me figure out how to do this.
Here is what I have now:
import System.Path.Glob (glob)
import System.Posix.Files (fileSize, getFileStatus)
dir = "/usr/bin/"
lof = do files <- (glob (dir++"*"))
(mapM_ fileS files)
fileS file = do fs <- getFileStatus file
print (fileSize fs)
As you can see, this gets the sizes and prints them out, but I'm stuck on how to actually sum them.
A: You're almost there. You can have fileS return the file size instead of printing it:
return (fileSize fs)
Then, instead of mapM_ing (which throws away the result), do a mapM (which returns the list of results):
sizes <- mapM fileS files
Now sizes is a list of numbers corresponding to the sizes. summing them should be easy :-)
To deepen your understanding of this example (and practice good habits), try to write type signatures for your functions. Consult ghci with :t for help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to include one HTML file into another? I have tried every possible question here on stackoverflow but unable to resolve this issue ...
<!--#include virtual="include.shtml"-->
<!--#include virtual="include.html"-->
<!--#include file="include.shtml"-->
<!--#include file="include.html"-->
<!--#include virtual="/include.shtml"-->
<!--#include virtual="/include.html"-->
<!--#include file="/include.shtml"-->
<!--#include file="/include.html"-->
<? include("/include.shtml"); ?>
<? include("include.shtml"); ?>
<? include("/include.html"); ?>
<? include("include.html"); ?>
I tried with apache server running at localhost/include/index.html or file:///home/sahil/Desktop/include/index.html with all above includes but none of them is working for me :( .Now which method should i use to include one HTML file into another , considering my index.html and include.html both are in same directory ???
A: HTML is Static
It is not possible to include a HTML page within another HTML page with static HTML because it is simply not supported by HTML. To make your HTML dynamic, you have 2 possibilities: use a client side script or use a server side technology.
...Unless you start using frames (dropped with the HTML5 standard) or iframes that are most likely not a solution because of the fact that it is treated as a completely different web page.
Client Solution
You could create a JavaScript file and write your HTML with the document.write function and then include the JavaScript file where ever you need it. Also, you could use some AJAX for this, but there are JavaScript libraries out there that could ease your burden such as the popular jQuery library.
Yet, I would not suggest using a client solution because it is more trouble than it is worth...
Server Solution
There are many server side solutions out there: ASP, ASP.NET, ASP.NET MVC, Java, PHP, Ruby and the list goes on. What you need to understand is that a server a side technology could be described as a parser for a specific server side language to automate certain tedious tasks and to perform actions that would represent a security risk on the client.
Of course you will need to have the means to host such a site and to configure the hosting environment. For example, you could host a PHP website with Apache and even have a developer hosting environment such as /MAMP/LAMP/WAMP.
You can view an example of including a page in PHP in the online documentation.
Personally, I would be more inclined to use a server side solution.
A: HTML doesn't have an 'include' mechanism - I'm not sure where you've seen these solutions on StackOverflow. You've probably been looking at answers for a server side language such as PHP or ASP.
You do have the following options for 'pure' HTML where you only have static pages and JavaScript:
*
*Frames
*Ajax
See my answer here for sample code and more details (and also a caveat about SEO if that matters to you).
A: The former syntax is SSI, the latter is PHP. Both are server technologies and will only work if accessed from an HTTP server that supports and is configured to check the file for the syntax (which usually means you have to turn the support on and use a .shtml/.php file extension (or change the config from the default to determining which files to check)). Other server side technologies are available.
The only "include" mechanisms in HTML itself are (i)frames and objects.
You could also consider a template system such as TT that you could run as a build step to generate static HTML documents (NB: TT can also be used on the fly).
A: Make your html file you want to include to php file. (only change the extension - to .php). If the files are in one directory, include code is:
<?php include "nameoffile.php" ?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Make an HTML element 'float' I want an HTML element (let say a span or div) to be present on the page, but not take up any space, so I can switch on and off the visibility property, and nothing moves but the span disappears.
for example take a table. I want an 'edit' label to show at each row, when I move the mouse over. But I don't want it to take up space from the table width. I just want it to 'float' beside the table.
Any ideas how to achieve this?
*
*I can not to use javascript. So I'll be very glad if this is possible with CSS only.
*I have tried to use float, its not good because no element overlaps with it. (And i do want overlapping.)
A: I think you're after a CSS Tooltip. Here's an example of one:
http://psacake.com/web/jl.asp
A: div {
position: absolute;
left: 100px;
top: 100px;
}
This will take the div and position it relative to the first containing element with position other than static. If you have an item with a position of static (the default) or relative, it will affect the document flow and hence the position of other elements. If you set the position to absolute, it takes it out of the document flow and lets you 'drop' it onto the page at whatever pixel position you like. :D
Css position property
A: Without using javascript i suppose you could use CSS :hover. Like this:
<style type="text/css">
#world { display: none; }
#hello:hover #world { display: block; }
</style>
<div id="hello">
hello
<div id="world">world</div>
</div>
Demo: jsFiddle
A: The "float" property does not "float" an object over the other elements. It "float"s the element to one side or another.
To put an object over another object, use the z-index property combined with the position property.
z-index: 500;
position: absolute;
left: 50px;
top: 50px;
A: You can achieve this effect by making an additional column on the edge of your table that is invisible until its row is hovered over. You want to use visibility, not display, to hide and show because visibility maintains the allocated space of the cell.
Demo: http://jsfiddle.net/sCrS6/
You should be able to easily duplicate the code to make it work for your particular page.
This method also has the advantage of working more consistently across web browsers than using positioning, which often starts to have weird in IE behavior after a couple of elements are nested.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android Screen Burn - Droid X - Live wallpaper I am trying to figure out if this is a bug or a feature of Droid X and some wallpaper thing. Or perhaps this is some screen-burn problem.
My app is open. Then someone closes it with the home key. Then at some point this screen will appear. This is what the QA department reported, and I am assuming that they left the device sitting and a watery wallpaper came up. Not sure though. If it is a wallpaper, why would it show a picture of my "closed" app in the background? In any case, anyone know what is going on here?
A: Take a screen shot with ddms. If its image burn on the screen then you won't see the display problem. If you do see it then its a software problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Expected Expression before ']' token The code:
-(void) GoToMainMenu: (id) sender {
[[CCDirector sharedDirector] sendCleanupToScene];
[[CCDirector sharedDirector] popScene];
[[CCDirector sharedDirector] replaceScene:[CCTransitionFade
transitionWithDuration:1
scene:[HelloWorldLayer node: ]]
];
}
I repeatedly keep getting the error "Expected Expression before ']' token.
A: You aren't passing anything here.
[HelloWorldLayer node: ]
A: You need to give the parameter after HelloWorldLayer node::
scene:[HelloWorldLayer node:<your parameter here> ]]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: group mysql results into two separate divs I have a mysql query that retrieves all my topic results. I then have a pagination system where results are separated into pages and the query's limit #,# changes based on what page you are on.
What I want to do is put all those results into two separate div containers. I want 21 results on each page. The first 9 I will put in one div. The next 12 will go in the other. Does anyone know an efficient way to do this? Should I use two queries, or javascript, or another way? I am just looking for the best most efficient way to do this. Unfortunately the pagination system makes two queries difficult. Any suggestions highly appreciated.
$sql = "SELECT * FROM topics LIMIT ?,?";
$stmt2 = $conn->prepare($sql);
$result=$stmt2->execute(array(somenumber,somenumber2));
A: I don't see any reason why you can't do a single MySQL query and use JavaScript to sort the results. Understand that I don't understand here what your data is coming back looking like, so any example I provide will have to remain pretty agnostic in this regard.
I will, however, assert as an assumption that you have a JavaScript array of length 21 with some data that is the basis for your display.
Assuming that we're just talking about the first 9, and the last 12, the sorting code is as simple as:
// assume my_array is the array mentioned above
for (var i = 0; i < 9; i += 1) {
var html = code_to_transform_data_from_array(array[i]);
$('.div1').append($(html));
}
for (var i = 9; i < 21; i += 1) {
var html = code_to_transform_data_from_array_b(array[i]);
$('.div2').append($(html));
}
If your sorting condition is any more complicated, then you'd be better off with something like...
while (my_array.length > 0) {
var item = my_array.pop();
if (sorting_condition) {
$('.div1').append(f1(item));
}
else {
$('.div2').append(f2(item));
}
}
(In the second example, I became a lazy typist and assumed f1 and f2 to be complete transformation functions. sorting_condition is your criteria for determining in which bucket something goes.
Hope that sets you off on the right track.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ruby and Amazon S3 how to open file and authenticate? How do I open a file on Amazon S3 and authenticate?
I know how to do this with paperclip, but how is it done when having to open file?
My helper
File.open("#{RAILS_ROOT}/public/xml/#{output}.xml", "w") do |f|
f.puts("<?xml version='1.0' encoding='UTF-8'?>")
f.puts("<site>")
f.puts("<general name='general' type='general'><imagePath>photographer/image/</imagePath><moviePath>../photographer/flv/</moviePath></general>")
f.puts("#{xmlmenu.to_xml}")
f.puts("#{xmlmovies.to_xml}")
f.puts("#{xmltextpages.to_xml}")
f.puts("</site>")
end
UPDATE
My helper file:
module Admin::XmlHelper
require 'builder'
require 'aws/s3'
def update_xml(output)
AWS::S3::Base.establish_connection!(
:access_key_id => 'mykey',
:secret_access_key => 'mykey'
)
file = "xml/#{output}.xml"
content = "#{
f.puts("<?xml version='1.0' encoding='UTF-8'?>")
f.puts("<site>")
f.puts("<general name='general' type='general'><imagePath>photographer/image/</imagePath><moviePath>../photographer/flv/</moviePath></general>")
f.puts("#{xmlmenu.to_xml}")
f.puts("#{xmlmovies.to_xml}")
f.puts("#{xmltextpages.to_xml}")
f.puts("</site>")}"
AWS::S3::S3Object.store(file, content, "mybucket", :access => :public_read)
end
end
I get the error in view:
uninitialized constant AWS::S3::Base
http://pastie.org/2587071
Update:
Instead of gem "aws-s3"
Should it be: gem 'aws-s3', :require => 'aws/s3'
A: Is your question how to write a file to S3? If so, using the aws-s3 gem, you would do as follows:
AWS::S3::Base.establish_connection!(
:access_key_id => MY_ACCESS_KEY,
:secret_access_key => MY_SECRET_ACCESS_KEY
)
content = "this is the content";
AWS::S3::S3Object.store("any_file_name.html", content, "my_bucket_name", :access => :public_read)
A: Why not use the aws-s3 gem?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use Apple Script to control backlit keyboard? Is there a way to use an Apple Script to control the brightness of the backlit keyboard on a Macbook?
The backlit keys are the F5 and F6.
Edit:
Based on the suggestion of @Clark I tried the follow, but it does not work.
NSAppleScript *run = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to key code 96"];
[run executeAndReturnError:nil];
Any suggestions?
A: Amit Singh has a chapter on how to do this from C.
https://web.archive.org/web/20200103164052/https://osxbook.com/book/bonus/chapter10/light/
It'd be easy to compile the sample code on that page and call it from Applescript.
To make Applescript type a function key you have to use the key code. The key codes fore the function keys are:
*
*F1 = 122
*F2 = 120
*F3 = 99
*F4 = 118
*F5 = 96
*F6 = 97
*F7 = 8
*F8 = 100
*F9 = 101
*F10 = 109
*F11 = 103
To type one do something like this:
tell application "System Events" to key code 96
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Problem in multi-threaded Java application - synchronized method not working as expected I am coding a program similar to producer-consumer in java (but with the consumer only portion, with no producer thread). It looks like the critical region is being executed at the same time by multiple threads despite the fact that I am calling the code of a synchronized method.
Here is the code:
Class Main.java:
package principal;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
final int tamanho_buffer=10;
final int quantidade_threads=10;
Pedido buffer[] = new Pedido[tamanho_buffer];
Consumidor consumidor[] = new Consumidor[quantidade_threads];
for (int i=0;i<tamanho_buffer;i++) {
buffer[i]=new Pedido();
}
for (int i=0;i<quantidade_threads;i++) {
consumidor[i]=new Consumidor();
}
for (int i=0;i<tamanho_buffer;i++) {
int identificador[]=new int[Pedido.getTamanho_identificador()];
identificador[0]=i;
buffer[i].setIdentificador(identificador);
buffer[i].setTexto("pacote de dados");
}
Consumidor.setBuffer(buffer);
Consumidor.setTamanho_buffer(tamanho_buffer);
for (int i=0;i<quantidade_threads;i++) {
consumidor[i].start();
}
for (int i=0;i<quantidade_threads;i++) {
try {
consumidor[i].join();
}catch(InterruptedException e ){
System.out.println("InterruptedException lancada");
}
}
System.out.println("Processamento encerrado.");
}
}
Class Pedido.java:
package principal;
public class Pedido {
private int identificador[];
private String texto;
static int tamanho_identificador=10;
int ti=tamanho_identificador;
public Pedido() {
this.identificador= new int[this.ti];
}
public static int getTamanho_identificador() {
return tamanho_identificador;
}
public int[] getIdentificador() {
return identificador;
}
public void setIdentificador(int[] identificador) {
this.identificador = identificador;
}
public String getTexto() {
return texto;
}
public void setTexto(String texto) {
this.texto = texto;
}
}
Class Consumidor.java
package principal;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class Consumidor extends Thread {
private static Pedido buffer[];
private static int tamanho_buffer;
private static int posicao=0;
public static void setTamanho_buffer(int tamanhoBuffer) {
tamanho_buffer = tamanhoBuffer;
}
public static void setBuffer(Pedido[] buffer) {
Consumidor.buffer = buffer;
}
public void run() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
while (posicao < Consumidor.tamanho_buffer ) {
// int identificador;
// identificador=buffer[posicao].getIdentificador()[0];;
Date datainicio = new Date();
String inicio=dateFormat.format(datainicio);
try {
Consumidor.sleep(1000);
} catch(InterruptedException e) {
System.out.println("InterruptedException lancada");
}
Date datafim = new Date();
String fim=dateFormat.format(datafim);
consomebuffer(inicio,fim);
}
}
synchronized void consomebuffer(String inicio, String fim) {
if (posicao < Consumidor.tamanho_buffer ) {
int identificador;
identificador=buffer[posicao].getIdentificador()[0];
System.out.println("Thread: "+Thread.currentThread()+" Pedido: "+identificador+" Inicio: "+inicio+" Fim: "+fim+" posicao "+posicao);
posicao++;
}
}
}
The method consomebuffer is synchronized but it looks like the variable posicao (portuguese name for position) is being accessed by the other threads at the same time, that should not happen, coz it is a synchronized method. The program output is something like this:
Thread: Thread[Thread-7,5,main] Pedido: 0 Inicio: 2011/09/24 21:14:18 Fim: 2011/09/24 21:14:19 posicao 0
Thread: Thread[Thread-6,5,main] Pedido: 0 Inicio: 2011/09/24 21:14:18 Fim: 2011/09/24 21:14:19 posicao 0
Thread: Thread[Thread-2,5,main] Pedido: 0 Inicio: 2011/09/24 21:14:18 Fim: 2011/09/24 21:14:19 posicao 0
Thread: Thread[Thread-9,5,main] Pedido: 0 Inicio: 2011/09/24 21:14:18 Fim: 2011/09/24 21:14:19 posicao 0
Thread: Thread[Thread-3,5,main] Pedido: 4 Inicio: 2011/09/24 21:14:18 Fim: 2011/09/24 21:14:19 posicao 4
Thread: Thread[Thread-5,5,main] Pedido: 5 Inicio: 2011/09/24 21:14:18 Fim: 2011/09/24 21:14:19 posicao 5
Thread: Thread[Thread-0,5,main] Pedido: 0 Inicio: 2011/09/24 21:14:18 Fim: 2011/09/24 21:14:19 posicao 5
Thread: Thread[Thread-8,5,main] Pedido: 0 Inicio: 2011/09/24 21:14:18 Fim: 2011/09/24 21:14:19 posicao 5
Thread: Thread[Thread-4,5,main] Pedido: 5 Inicio: 2011/09/24 21:14:18 Fim: 2011/09/24 21:14:19 posicao 5
Thread: Thread[Thread-1,5,main] Pedido: 0 Inicio: 2011/09/24 21:14:18 Fim: 2011/09/24 21:14:19 posicao 0
Processamento encerrado.
Realize that the position value is appearing repeated between different threads. In the output posicao should have a different value in each thread that calls the synchronized method.
A: Each Thread instance is synchronising on itself. To make all of the threads mutually exclusive, they have to synchronise on a common object.
That is,
public synchronized method(int parameter)
{
//do some stuff
}
is shorthand for
public method(int parameter)
{
synchronized (this)
{
//do some stuff
}
}
If you want a bunch of Threads to synchronise with each other, you need to make available to them a common object to synchronize on.
For example, you could add in the constructor of Consumidor.java
public Consumidator(Object monitor)
{
myMonitor = monitor
}
then in run have
void consomebuffer(String inicio, String fim) {
synchronized (myMonitor)
{
if (posicao < Consumidor.tamanho_buffer ) {
int identificador;
identificador=buffer[posicao].getIdentificador()[0];
System.out.println("Thread: "+Thread.currentThread()+" Pedido: "+identificador+" Inicio: "+inicio+" Fim: "+fim+" posicao "+posicao);
posicao++;
}
}
}
Then when you create your array of Consumidadors, pass them a shared object to synchronize on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Solution for finding "duplicate" records involving STI and parent-child relationship I have an STI-based model called Buyable, with two models Basket and Item. The attributes of concern here for Buyable are:
*
*shop_week_id
*location_id
*parent_id
There's a parent-child relationship between Basket and Item. parent_id is always nil for basket, but an item can belong to a basket by referencing the unique basket id. So basket has_many items, and an item belongs_to a basket.
I need a method on the basket model that:
Returns true of false if there are any other baskets in the table with both the same number of and types of items. Items are considered to be the same type when they share the same shop_week_id and location_id.
For ex:
Given a basket (uid = 7) with 2 items:
item #1
*
*id = 3
*shop_week_id = 13
*location_id = 103
*parent_id = 7
item #2
*
*id = 4
*shop_week_id = 13
*location_id = 204
*parent_id = 7
Return true if there are any other baskets in the table that contain exactly 2 items, with one item having a shop_week_id = 13 and location_id = 103 and the other having a shop_week_id = 13 and location_id = 204. Otherwise return false.
How would you approach this problem? This goes without saying, but I am looking for a very efficient solution.
A: The following SQL seems to do the trick
big_query = "
SELECT EXISTS (
SELECT 1
FROM buyables b1
JOIN buyables b2
ON b1.shop_week_id = b2.shop_week_id
AND b1.location_id = b2.location_id
WHERE
b1.parent_id != %1$d
AND b2.parent_id = %1$d
AND b1.type = 'Item'
AND b2.type = 'Item'
GROUP BY b1.parent_id
HAVING COUNT(*) = ( SELECT COUNT(*) FROM buyables WHERE parent_id = %1$d AND type = 'Item' )
)
"
With ActiveRecord, you can get this result using select_value:
class Basket < Buyable
def has_duplicate
!!connection.select_value( big_query % id )
end
end
I am not so sure about performance however
A: If you want to make this as efficient as possible, you should consider creating a hash that encodes basket contents as a single string or blob, add a new column containing the hash (which will need to be updated every time the basket contents change, either by the app or using a trigger), and compare hash values to determine possible equality. Then you might need to perform further comparisons (as described above) in order
What should you use for a hash though? If you know that the baskets will be limited in size, and the ids in question are bounded integers, you should be able to hash to a string that is enough in itself to test for equality. For example, you could base64 encode each shop_week and location, concatenate with a separator not in base64 (like "|"), and then concatenate with the other basket items. Build an index on the new hash key, and comparisons will be fast.
A: To clarify my query, and somewhat vague description of the table columns of the "buyable" table, The "Parent_ID" is the basket in question. The "Shop_Week_ID" is the consideration for baskets to be compared... don't compare a basket from week 1 to week 2 to week 3. The #ID column appears to be a sequential ID in the table, but not the actual ID of the item to be compared... The Location_ID appears to be the common "Item". In the scenario, assuming a shopping cart, Location_ID = 103 = "Computer", Location_ID = 204 = "Television" (just for my interpretation of the data). If this is incorrect, minor adjustments may be needed, in addition to the original poster showing a list of say... a dozen entries of the data to show proper correlation.
So, now, on to my query.. I'm doing a STRAIGHT_JOIN so it joins in the order I've listed.
The first query for alias "MainBasket" is exclusively used to query how many items are in the basket in question ONCE, so it doesn't need to be re-joined/queried again for each possible basket to match. There is no "ON" clause as this will be a single record, and thus no Cartesian impact, as I want this COUNT(*) value applied to EVERY record in the final result.
The NEXT Query is to find a DISTINCT OTHER Basket where at LEAST ONE "Location_ID" (Item) within the same week as the parent in question... This could result in other baskets having 1, same or more entries than the basket. But if there are 100 baskets, but only 18 have at least 1 entry that matches 1 item in the original basket, you've just significantly cut down the number of baskets to do final compare against (SameWeekSimilar alias result).
Finally is a Join to the buyable table again, but based on a join for the SameWeekSimilar, but only on per "other" basket that had a close match... No specific items, just by the basket. The query used to get the SameWeekSimilar already pre-qualified the same week, and at least one matching item from the original basket in question, but specifically excluding the original basket so it doesn't compare to itself.
By doing a group at the outer level based on the SameWeekSimilar.NextBasket, we can get the count of actual items for that basket. Since a simple Cartesian join to the MainBasket, we just grab the original count.
Finally, the HAVING clause. Since this is applied AFTER the "COUNT(*)", we know how many items were in the "Other" baskets, and how many in the "Main" basket. So, the HAVING clause is only including those where the counts were the same.
If you want to test to ensure what I'm describing, run this against your table but DO NOT include the HAVING clause. You'll see which were all the POSSIBLE... Then re-add the HAVING clause and see which ones DO match same count...
select STRAIGHT_JOIN
SameWeekSimilar.NextBasket,
count(*) NextBasketCount,
MainBasket.OrigCount
from
( select count(*) OrigCount
from Buyable B1
where B1.Parent_ID = 7 ) MainBasket
JOIN
( select DISTINCT
B2.Parent_ID as NextBasket
from
Buyable B1
JOIN Buyable B2
ON B1.Parent_ID != B2.Parent_ID
AND B1.Shop_Week_ID = B2.Shop_Week_ID
AND B1.Location_ID = B2.Location_ID
where
B1.Parent_ID = 7 ) SameWeekSimilar
Join Buyable B1
on SameWeekSimilar.NextBasket = B1.Parent_ID
group by
SameWeekSimilar.NextBasket
having
MainBasket.OrigCount = NextBasketCount
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to list every file for every revision in Git (like Mercurial's hg manifest --all)? Mercurial has a command to list every file that the repository has for every revision:
hg manifest --all
Is there an equivalent command in Git? I know about git ls-files, but it only list files from the index (the current revision).
A: This should give all the files ever existed:
git log --pretty=format: --name-only | sort | uniq
A: You could do this with the following pipeline:
git rev-list HEAD | xargs -L 1 git ls-tree -r | awk '{print $4}' | sort | uniq
This does the following:
*
*use git rev-list to get a list of revisions backward from HEAD
*for each revision, use git ls-tree -r to show the list of files
*extract just the filenames from the list using awk
*using sort and uniq, filter out names that are listed more than once
This will give the name of every file that has ever been part of the history of the current HEAD.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Silverlight datagrid rebind entire column I wanted to add datagrid row indexes to my Silverlight MVVM application so I created an IValueConverter that will take the row object and return it's index. The converter itself is working properly and here's the simple row XAML.
<sdk:DataGridTextColumn Binding="{Binding Converter={StaticResource RowIndexConverter}}" />
The problem is when I add a new row I have to insert it at the top. This creates a new row at index 0 and pushes all of the other rows down one and their row numbers are not updating. Is there a way I can force it to rebind that entire column?
A: To solve this you should probably add RowIndex to the model which you bind to the DataGrid. Whenever rows are added / removed, update the index for each model item - your DataGrid will then be updated.
A: Detach and then reattach the datagrid.itemssource.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SVN - How to keep core source code confidential and give freelancers access to modules only I'm developing a modular propietary PHP application. As a project leader and owner, I want to keep the core engine confidential. The freelancers will work on modules (say 1 freelancer for 1 module where they can't see other's module).
I created repos for core (1 repo) and modules (1 repo for 1 module). AFAIK the repo should be placed outside htdocs. Now I think about this scenario: Using SVN, I'll give access to repo A for freelancer A, repo B for freelancer B, etc. When A checkout, he'll only have module A on his computer to edit. To test his module, he'll commit. But as it goes to svn dir instead of htdocs, he won't be able to test it instantly. He'll then need to export the commited code to htdocs. Well, I want to skip this export step.
(1) Is there a way he can commit his code to htdocs directly to test it to make it more practical?
(2) Is there any better scenario to achieve this (i.e. freelancer only allowed to read/write the module he worked on, and have no access - even read - to other module and core system)?
A: There are three places you're talking about:
*
*The Subversion repositories themselves. This is where all the source code will live. The repository will be accessible via a Subversion client which will talk to the server. The server can use the SVN protocol or HTTP/HTTPS. If you want to use HTTP/HTTPS, you'll need to setup an Apache server. If you want to run SVN, you will need to have the svnserve process running.
*The local working directory on the developer's system. This is where files are checked out to, and where the developer can make changes. It is not necessarily on same machine with the repository.
*The PHP Webserver. This is where the PHP files need to be in order to work and possibly to be tested.
Let's take this one at a time: With either SVN or HTTP/HTTPS, it is possible to limit who can see, checkout, and commit the code into the repository. In Subversion, you can specify this to a directory level. Thus, one developer can check in code to http://myserver/svnrepos/module1 while another can check in and out code from http://myserver/svnrepos/module2, and neither can see your code at http://myserver/svnrepos/core,
The tricky part is getting this information onto the server for testing. The question is how to allow developers to do commits without necessarily putting the code onto the server. There are a couple of ways to do this.
One is to create a server branch. If the developer wants the code on the PHP server, they would merge the code onto the server branch. Then, you need a mechanism to move the code from the repository to the PHP server.
I would not use a post-commit hook for this purpose. You don't want the developer to wait around for the hook to copy their code to the server. Besides, you probably want to bring the server up and down.
Instead, use a crontab which will watch the Subversion repository (especially the server branches), and then when it detects a change, take the server down, update the files in the server, and then bring the server back up. My method is to use two different directories. Have directory1 on the server. Use svn export to export the files to directory2. Thus the server is still up. Then, take the server down, and move directory2 to directory1, and bring the server back up. This keeps downtime to a minimum and the server in a more or less stable state.
However, you should look at Jenkins to help you with your project. Jenkins will allow you and your developers to see their changes (you can limit who sees what), do basic testing. For example, you can run PHPMD (see how messy the code is) and CPD (copy paste detector) after a commit, and Jenkins will show the results. You can then put a deploy button on Jenkins, and the developer can deploy their build to the server.
Jenkins is simple to setup and use. There are tons of plugins for various defect tracking systems, Subversion, and various testing modules. I don't know how much is available for PHP, though, but you can take a look.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Assembly to high-level language conversion Is there any way to convert assembly language to some high-level language?
I am trying to make linux port of application for retrieving school marks. Application downloads file from server and then decrypts it somehow. It is written in delphi but after decompilation i got an assembly language. Assembly language is totally unknown to me.
Here is the procedure that i think it is responsible for decription: https://gist.github.com/1240056
If there is any other way how to find out used algorithm i would be very thankful to you.
A: Decompilers are notoriously unreliable. Too much information is lost in the compilation process to reliably convert back to source code in most cases. To have any chance at all of working you must use a decompiler which matches (ie, knows how to reverse the compilation process of) the language, OS, and ideally the compiler of the original code. But even then, the resulting output is unlikely to be any more legible than the assembly code; and decompilers which can actually make it to real, compilable code are extremely rare.
I would recommend that you learn assembly code and try to reverse-engineer it that way, or just run this program in wine.
A: The code you supplied is definitively not doing any decryption by itself, IMHO.
This sounds like some high-level UI stuff and getting some content from a text file retrieved from internet, and refresh the UI. There is no decryption loop inside.
The decryption is certainly some of the internal calls, which reads some password from the UI, then make calls to retrieve some data from Internet, read the content, and update the UI. Check 0048E004 method for instance (or one other call around).
Search for such a pattern:
@loop:
mov al,[esi]
xor al,...
mov [edi],al
inc esi
inc edi
dec ecx
jnz @loop
Or
@loop:
xor [edx],...
inc edx
dec ecx
jnz @loop
Then maybe a call to LStrCmp for instance (it is a string comparison).
Of course, registers esi/edi/ecx/edx may be local variables [ebp+...] or other registers. But you may recognize this pattern.
Encryption may be MUCH more difficult this this loop, but there is quite always a xor ...,... during encryption/decryption, with a loop through all bytes.
I'm not talking about xor eax,eax lines, which are in fact eax := 0 but some xor al,... were ... is not al.
A: Perhaps try to write some code yourself that does what you want rather than recreating code from a decompiled exe. What you want doesn't sound all that complex so you should be able to recreate it.
If you are trying to get around encryption, decompiling is unlikely to help you.
A: try to learn IDA pro and it's plugin.
But it wont help you to port the proggy on linux.
analize the logic, better off to do the new implementation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Appending character to a variable if a certain character exists within it? How would I go about making the following also check if the last character of $word is equal to "h" if true then append "es"? This check for "h" would be before the check for "s" and if true there would be no need to check for "s".
<?php
$word = "watch";
$newword = "$word".(substr($word, -1)=="s"?"":"s")." is the new word";
echo $newword;
?>
A: switch (substr($word, -1)) {
case 'h':
$newword = $word . 'es';
break;
case 's':
$newword = $word;
break;
default:
$newword = $word;
}
Or some variation thereof. If you are trying to pluralize words, there are already a number of solutions, for example: pluralize method
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calling methods side by side in a table I'm making a table with Decimal, Binary, Octal and Hexadecimal columns. I wrote methods that display each of these types from a low number to a high number. My question is how do I display these methods side by side so they line up in the appropriate column?
I tried using the following, but it contains "invalid arguments":
Console.WriteLine("{0}\t{1}\t...", generate.buildDecimal(), generate.buildBinary(),...)
Here is my code:
using System;
public class Converter
{
int decimal0;
int decimal1;
int decimal2;
int decimal3;
int bottomLimit;
int topLimit;
// prompt user for range of numbers to display
public void PromptUser()
{
Console.Write("Enter bottom limit: ");
bottomLimit = Convert.ToInt32(Console.ReadLine());
decimal0 = bottomLimit;
decimal1 = bottomLimit;
decimal2 = bottomLimit;
decimal3 = bottomLimit;
Console.Write("Enter top limit: ");
topLimit = Convert.ToInt32(Console.ReadLine());
}
// display decimal values in range
public void buildDecimal()
{
while (decimal0 <= topLimit)
{
Console.WriteLine(decimal0);
decimal0++;
}
}
// display binary values in range
public void buildBinary()
{
while (decimal1 <= topLimit)
{
string binary = Convert.ToString(decimal1, 2);
Console.WriteLine(binary);
decimal1++;
}
}
// display octal values in range
public void buildOctal()
{
while (decimal2 <= topLimit)
{
string octal = Convert.ToString(decimal2, 8);
Console.WriteLine(octal);
decimal2++;
}
}
// display hexadecimal values in range
public void buildHex()
{
while (decimal3 <= topLimit)
{
string hex = Convert.ToString(decimal3, 16);
Console.WriteLine(hex);
decimal3++;
}
}
// call methods
public static void Main(string[] args)
{
Converter generate = new Converter();
generate.PromptUser();
Console.WriteLine("Decimal Binary Octal Hexadecimal");
generate.buildDecimal();
generate.buildBinary();
generate.buildOctal();
generate.buildHex();
}
}
As of right now, the program returns something like this:
Enter bottom limit: 1
Enter top limit: 10
Decimal Binary Octal Hexadecimal
1
2
3
4
5
6
7
8
9
10
1
10
11
100
101
110
111
1000
1001
1010
1
2
3
4
5
6
7
10
11
12
1
2
3
4
5
6
7
8
9
a
If you can't tell from my code, I'm a beginner, so please try not to go too far over my head. I'm actually supposed to put all of the methods in a separate class, but I couldn't figure out how to call the methods. I tried to call them in Converter with something like:
Converter callMethod = new Converter();
callMethod.buildDecimal();
But it didn't know what I was referring to.
A: Since the bottom limit/top limit are always the same you could just use a single method.
see below.
public void BuildNumbers()
{
while (decimal1 <= topLimit)
{
string binary = Convert.ToString(decimal1, 2);
string dec = Convert.ToString(decimal1);
string oct = Convert.ToString(decimal1, 8);
string hex = Convert.ToString(decimal1, 16);
Console.Write(binary);
Console.Write('\t');
Console.Write(dec);
Console.Write('\t');
Console.Write(oct);
Console.Write('\t');
Console.Write(hex);
Console.WriteLine();
decimal1++;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Digging deeper into DOMElement I've used Zend_Dom_Query to extract some <tr> elements and I want to now loop through them and do some more. Each <tr> looks like this, so how can I print the title Title 1 and the id of the second td id=categ-113?
<tr class="sometr">
<th><a class="title">Title1</a></th>
<td class="category" id="categ-113"></td>
<td class="somename">Title 1 name</td>
</tr>
A: You should just play around with the results. I've never worked with it, but this is how far i got (and im kinda new to Zend myself):
$dom = new ZEnd_Dom_Query($html);
$res = $dom->query('.sometr');
foreach($res as $dom) {
$a = $obj->getElementsByTagName('a');
echo $a->item(0)->textContent; // the title
}
And with this i think you're set to go. For further information and functions to be used of the result look up DOMElement ( http://php.net/manual/de/class.domelement.php ). With this information you should be able to grab all that. But my question is:
Why doing this so complicated, i don't really see a use-case for doing this. As the title and everything else should be something coming from the database? And if it's an XML there's better solutions than relying on Dom_Query.
Anyways, if this was helpful to you please accept and/or vote the answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: jquery toggle wont trigger again I have 2 functions I want to repeat again and again:
function rotation () {
plrotation();
function plrotation () {
alert('pl');
$('#pl').toggle(300).delay(10000).toggle(400).delay(2000, function (){errotation()});
alert('pl end');
}
function errotation () {
alert('er');
$('#er').toggle(300).delay(10000).toggle(400).delay(2000, function (){plrotation()});
alert('er end');
}
}
But after the first time, I get the "pl" and "pl end" alert, but the toggle wont happen, and also errotation is not started... Any Idea that I'm doing wrong?
Or maybe is there any other way to do what I need (show element 1 => wait => hide element1 => wait => show element 2 => wait => hide element 2 => wait => restart)
A: Your last call to jQuery.delay() isn't right. Delay only delays queues, it doesn't take a completion handler like the other animation functions. It's not to be used to replace setTimeout().
So use setTimeout(), not delay().
function rotate(el) {
var $el = $(el);
$el.toggle(300).delay(10000).toggle(400, function() {
var next = $el.is('#pl') ? '#er' : '#pl';
setTimeout(function() { rotate(next); }, 2000);
});
}
$(function() { rotate('#pl')});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails Sunspot gem: Usings facets with multiple model site-wide searches I'm trying to implement a sitewide search through the powerful Sunspot gem for Rails. This involves a search across multiple, very different models at once. What I WANT to do is use the faceting feature to allow the user to filter their search results on each model, or by default view all on the same page, interspersed with each other ordered by the :boost qualifier. Combining the faceting code from the Sunspot Railscast with the multiple model searching code from another Stackoverflow question (a variation upon the 'Multiple Type' code from the Sunspot documentation) gave me a solution that I'd think would work, but doesn't.
The multiple method search succeeds, but the facets always turn up null. My basic approach is to provide a virtual attribute on each model by the same name, :search_class, that is just the model's class name rendered into a string. I then try and use that as a facet. However, in the view logic the results of the facet (@search.facet(:search_class).rows) is always an empty array, including when @search.results returns many different models in the same query, despite each returned instance having a perfectly accessible Instance.search_class attribute.
I'm using Rails 3.1.0 and sunspot-rails 1.2.1.
What should I do to make this faceting code work?
Controller:
#searches_controller.rb
class SearchesController < ApplicationController
def show
@search = search(params[:q])
@results = @search.results
end
protected
def search(q)
Sunspot.search Foo, Bar, CarlSagan do
keywords q
#provide faceting for "search class", a field representing a pretty version of the model name
facet(:search_class)
with(:search_class, params[:class]) if params[:class].present?
paginate(:page => params[:page], :per_page => 30)
end
end
end
Models:
#Foo.rb
class Foo < ActiveRecord::Base
searchable do
text :full_name, :boost => 5
text :about, :boost => 2
#string for faceting
string :search_class
end
#get model name, and, if 2+ words, make pretty
def search_class
self.class.name#.underscore.humanize.split(" ").each{|word| word.capitalize!}.join(" ")
end
end
#Bar.rb
class Bar < ActiveRecord::Base
searchable do
text :full_name, :boost => 5
text :about, :boost => 2
#string for faceting
string :search_class
end
#get model name, and, if 2+ words, make pretty
def search_class
self.class.name.underscore.humanize.split(" ").each{|word| word.capitalize!}.join(" ")
end
end
#CarlSagan.rb
class CarlSagan < ActiveRecord::Base
searchable do
text :full_name, :boost => 5
text :about, :boost => 2
#string for faceting
string :search_class
end
#get model name, and, if 2+ words, make pretty
def search_class
self.class.name#.underscore.humanize.split(" ").each{|word| word.capitalize!}.join(" ")
end
end
View:
#searches/show.html.erb
<div id="search_results">
<% if @results.present? %> # If results exist, display them
# If Railscasts-style facets are found, display and allow for filtering through params[:class]
<% if @search.facet(:search_class).rows.count > 0 %>
<div id="search_facets">
<h3>Found:</h3>
<ul>
<% for row in @search.facet(:search_class).rows %>
<li>
<% if params[:class].blank? %>
<%= row.count %> <%= link_to row.value, :class => row.value %>
<% else %>
<strong><%= row.value %></strong> (<%= link_to "remove", :class => nil %>)
<% end %>
</li>
<% end %>
</ul>
</div>
<% end %>
<% @results.each do |s| %>
<div id="search_result">
<% if s.class.name=="Foo"%>
<h5>Foo</h5>
<p><%= link_to s.name, foo_path(s) %></p>
<% elsif s.class.name=="Bar"%>
<h5>Bar</h5>
<p><%= link_to s.name, bar_path(s) %></p>
<% elsif s.class.name=="CarlSagan"%>
<h5>I LOVE YOU CARL SAGAN!</h5>
<p><%= link_to s.name, carl_sagan_path(s.user) %></p>
<% end %>
</div>
<% end %>
<% else %>
<p>Your search returned no results.</p>
<% end %>
</div>
A: This
Sunspot.search(Foo, Bar){with(:about, 'a'); facet(:name)}
translates to the following in Solr
INFO: [] webapp=/solr path=/select params={facet=true&start=0&q=*:*&f.name_s.facet.mincount=1&facet.field=name_s&wt=ruby&fq=type:(Foo+OR+Bar)&fq=about_s:a&rows=30} hits=1 status=0 QTime=1
You can find the exact Solr query in the solr/log/ solr_production.log file
if you notice facet(:name) translated to f.name_s.facet and not f.foo.facet and f.bar.facet. That is why it did not work as you expected.
The following will work but that needs one to create 3 dummy methods in each model. The idea is you need a separate facet line for each of the types.
Sunspot.search Foo, Bar, CarlSagan do
keywords q
#provide faceting for "search class", a field representing a pretty version of the model name
facet(:foo)
facet(:bar)
facet(:carlsagan)
with(:search_class, params[:class]) if params[:class].present?
paginate(:page => params[:page], :per_page => 30)
end
Again, it is always better to look at the actual SOLR query log to debug the search issues. Sunspot makes many things magical but it has its limitations ;-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to write a lambda expression take in a collection of properties using a delimiter? I am not sure how to create this expression:
(e => e.Prop1, e.Prop2, e.Prop3)
I want to pass an expression like this into a method so I can iterate through the collection and pull out the property names.
pseudo method:
public void ParseProperties<T>(The_Expression_being_Passed_In)
{
foreach(var member in expression.members)
{
.....
}
}
A: You need to accept a parameter of type
params Expression<Func<T, object>>[] expressions
So you can say
public void ParseProperties<T>(params Expression<Func<T, object>>[] expressions) {
foreach(var expression in expressions) {
expression.GetPropertyName();
}
}
You'll have to write GetPropertyName; implementations abound on StackOverflow.
You can't quite call it like you desire. You'll have to say
ParseProperties(e => e.Prop1, e => e.Prop2, e => e.Prop3);
A: you could try something like this, but it may blow up on you if you try to use a value type property as the expression will most likely be a cast expression.
public PropertyInfo ParseProperty<T>(Expression<Func<T,object>> expr)
{
MemberExpression member;
if(expr == null)
throw new ArgumentNullException("expr");
if((member = expr.Body as MemberExpression) == null)
throw new ArgumentException("incorrect format");
return member.Member as PropertyInfo;
}
public PropertyInfo[] ParseProperties<T>(params Expression<Func<T,object>> expressions)
{
return Array.ConvertAll(expressions,ParseProperty);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Implementing multi-tenancy for a mature enterprise application I've been tasked with making an enterprise application multi-tenant. It has a Java/Glassfish BLL using SOAP web services and a PostgreSQL backend. Each tenant has its own database, so (in my case at least) "multi-tenant" means supporting multiple databases per application server.
The current single-tenant appserver initializes a C3P0 connection pool with a connection string that it gets from a config file. My thinking is that now there will need to be one connection pool per client/database serviced by the appserver.
Once a user is logged in, I can map it to the right connection pool by looking up its tenant. My main issue is how to get this far - when a user is first logged in, the backend's User table is queried and the corresponding User object is served up. It seems I will need to know which database to use with only a username to work with.
My only decent idea is that there will need to be a "config" database - a centralized database for managing tenant information such as connection strings. The BLL can query this database for enough information to initialize the necessary connection pools. But since I only have a username to work with, it seems I would need a centralized username lookup as well, in other words a UserName table with a foreign key to the Tenant table.
This is where my design plan starts to smell, giving me doubts. Now I would have user information in two separate databases, which would need to be maintained synchronously (user additions, updates, and deletions). Additionally, usernames would now have to be globally unique, whereas before they only needed to be unique per tenant.
I strongly suspect I'm reinventing the wheel, or that there is at least a better architecture possible. I have never done this kind of thing before, nor has anyone on my team, hence our ignorance. Unfortunately the application makes little use of existing technologies (the ORM was home-rolled for example), so our path may be a hard one.
I'm asking for the following:
*
*Criticism of my existing design plan, and suggestions for improving or reworking the architecture.
*Recommendations of existing technologies that provide a solution to this issue. I'm hoping for something that can be easily plugged in late in the game, though this may be unrealistic. I've read about jspirit, but have found little information on it - any feedback on it or other frameworks will be helpful.
UPDATE: The solution has been successfully implemented and deployed, and has passed initial testing. Thanks to @mikera for his helpful and reassuring answer!
A: Some quick thoughts:
*
*You will definitely need some form of shared user management index (otherwise you can't associate a client login with the right target database instance). However I would suggest making this very lightweight, and only using it for initial login. Your User object can still be pulled from the client-specific database once you have determined which database this is.
*You can make the primary key [clientID, username] so that usernames don't need to be unique across clients.
*Apart from this thin user index layer, I would keep the majority of the user information where it is in the client-specific databases. Refactoring this right now will probably be too disruptive, you should get the basic multi-tenant capability working first.
*You will need to keep the shared index in sync with the individual client databases. But I don't think that should be too difficult. You can also "test" the synchronisation and correct any errors with an batch job, which can be run overnight or by your DBA on demand if anything ever gets out of sync. I'd treat the client databases as the master, and use this to rebuild the shared user index on demand.
*Over time you can refactor towards a fully shared user management layer (and even in the end fully shared client databases if you like. But save this for a future iteration.....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Can XSL use only PHP function that returns a string? Why this is not working? Can XSL use only PHP function that returns a string?
<xsl:if test="string-length(substring-before(TipoImm, '/')) > 0">
<xsl:element name="test">
<xsl:value-of select="php:functionString('implode',
(php:function('explode', TipoImm, '/')), '-')" />
</xsl:element>
</xsl:if>
A: Nope, you can also return DOMDocument or basically any DOMNode derivative.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Difference in NSDateFormatter between iPad simulator and device i'm using the following code to parse a date string:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"EEE',' dd MMM yyyy HH:mm:ss ZZZ"];
NSDate *lastUpdate = [dateFormatter dateFromString:@"Fri, 16 Sep 2011 11:11:35 GMT"];
[dateFormatter release];
it works prefectly in the simulator but when i set a breakpoint and look at the value for lastUpdate on an actual device, i see an "invalid CFStringRef" there instead of the correct date like in the simulator.
what am i missing here?
A: Is the locale on the device the same as the simulator? You may need to force a US locale on the date formatter
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What problem does backbone.js solve? When I gloss over the backbone.js site, I'm not sure what is it trying to do.
It seems somewhat popular, but why should I want to learn it? What will it do for me? Why was it made? What problem does it solve?
A: From backbonejs.org
It's all too easy to create JavaScript applications that end up as
tangled piles of jQuery selectors and callbacks
And that's exactly what backbone does, a series of callbacks on model changes and jQuery selectors to bind events.
So to answer the question, it solves nothing only to provide a way (the backbone way) of structuring code with some slight automation in the REST side of things.
A: I find the question perfectly valid and from my point of view there is nothing wrong with inquiring about the potential use cases of a library/toolkit.
What Backbone.js does (so do several other javascript mvc implementations) is that it provides a means of organizing the code into a modular pattern known as MVC pattern which is all about separating your code into three loosely coupled layers:
*
*Model layer dealing purely with data and associated operations
*View layer being the presentational aspects
*Controller layer being the binding glue layer
(different frameworks deal with this differently : Backbone implementation of controller layer comprises of client side routing capabilities).
So, on the whole backbone provides you an infrastructure using which you can deal with data through models which contain encapsulated within them the data and associated validations, which can be observed ie. you can bind events to change events.
The View layer is mostly left for the user to separate the ui into manageable isolated sections.
A: Here are some problems that Backbone solves for me in the JS/HTML space:
*
*Separation of Concerns (SoC)
*Composability
*Testability
*Component Model
*Abstraction
That is not to say that this is the ONLY system that does this. There are others. Backbone does a pretty good job of helping with these things, though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
} |
Q: How do you change UIButton image alpha on disabled state? I have a UIButton with an image and on its disabled state, this image should have .3 alpha.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *arrowImage = [UIImage imageNamed:@"arrow.png"];
[button setImage:arrowImage forState:UIControlStateNormal];
// The arrow should be half transparent here
[button setImage:arrowImage forState:UIControlStateDisabled];
How do I accomplish this?
UPDATE: I noticed, by default UIButton does reduce the alpha of the image on disabled state (probably at .5?). But I'd like to know how to fine-tune this value.
A: You need two instances of UIImage, one for enabled and one for disabled.
The tough part is for the disabled one, you can't set alpha on UIImage. You need to set it on UIImageView but button doesn't take an UIImageView, it takes a UIImage.
If you really want to do this, you can load the same image into the disabled button state after creating a resultant image from the UIImageView that has the alpha set on it.
UIImageView *uiv = [UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png"];
// get resultant UIImage from UIImageView
UIGraphicsBeginImageContext(uiv.image.size);
CGRect rect = CGRectMake(0, 0, uiv.image.size.width, uiv.image.size.height);
[uiv.image drawInRect:rect blendMode:kCGBlendModeScreen alpha:0.2];
UIImage *disabledArrow = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[button setImage:disabledArrow forState:UIControlStateDisabled];
That's a lot to go through to get an alpha controlled button image. There might be an easier way but that's all I could find. Hope that helps.
A: Subclassing UIButton and extending the setEnabled: method seems to work:
- (void) setEnabled:(BOOL)enabled {
[super setEnabled:enabled];
if (enabled) {
self.imageView.alpha = 1;
} else {
self.imageView.alpha = .25;
}
}
I haven't tested it thoroughly, but did find the value resets if the screen is rotated. Adding the same code to the setFrame: method fixes that, but I'm not sure if there are other situations where this value is changed.
A: In case anyone needs it, here's an answer in Swift:
Subclass UIButton and override enabled
class MyCustomButton: UIButton {
override var enabled: Bool {
didSet{
alpha = enabled ? 1.0 : 0.3
}
}
Set the class of any button you want to have this property to "MyCustomButton" (or whatever you choose to name it)
@IBOutlet weak var nextButton: MyCustomButton!
A: If setting alpha while the button is disabled doesn't work, then just make your disabled image at the alpha value you desire.
Just tested this, you can set the alpha on the UIButton, regardless of state and it works just fine.
self.yourButton.alpha = 0.25;
A: I found that none of these solutions really work. The cleanest way of doing it is to subclass, and instead of using self.imageView, just add your own custom imageView like this:
_customImageView = [[UIImageview alloc] initWithImage:image];
Then add your custom alpha like so:
- (void)setEnabled:(BOOL)enabled {
[super setEnabled:enabled];
if (enabled) {
_customImageView.alpha = 1.0f;
} else {
_customImageView.alpha = 0.25f;
}
}
A: Swift 3:
extension UIImage {
func copy(alpha: CGFloat) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(at: CGPoint.zero, blendMode: .normal, alpha: alpha)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
Usage:
button.setImage(image.copy(alpha: 0.3), for: .disabled)
A: Credit goes to @bryanmac for his helpful answer. I used his code as a starting point, but found the same thing can be achieved without using a UIImageView.
Here's my solution:
- (UIImage *)translucentImageFromImage:(UIImage *)image withAlpha:(CGFloat)alpha
{
CGRect rect = CGRectZero;
rect.size = image.size;
UIGraphicsBeginImageContext(image.size);
[image drawInRect:rect blendMode:kCGBlendModeScreen alpha:alpha];
UIImage * translucentImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return translucentImage;
}
Set the button's background image for disabled state:
UIImage * disabledBgImage = [self translucentImageFromImage:originalBgImage withAlpha:0.5f];
[button setBackgroundImage:disabledBgImage forState:UIControlStateDisabled];
EDIT:
I refined my solution further by creating a category on UIImage with this method:
- (UIImage *)translucentImageWithAlpha:(CGFloat)alpha
{
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
[self drawInRect:bounds blendMode:kCGBlendModeScreen alpha:alpha];
UIImage * translucentImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return translucentImage;
}
Set the button's background image for disabled state:
UIImage * disabledBgImage = [originalBgImage translucentImageWithAlpha:0.5f];
[button setBackgroundImage:disabledBgImage forState:UIControlStateDisabled];
A: The button’s image view. (read-only)
@property(nonatomic, readonly, retain) UIImageView *imageView
Although this property is read-only, its own properties are read/write.
A: A swift 4 version of Steph Sharp's answer:
extension UIImage {
func translucentImageWithAlpha(alpha: CGFloat) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
let bounds = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
self.draw(in: bounds, blendMode: .screen, alpha: alpha)
let translucentImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return translucentImage!
}
}
Which you can use like this:
if let image = self.image(for: .normal) {
self.setImage(image.translucentImageWithAlpha(alpha: 0.3), for: .disabled)
}
A: - (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image; }
Use: [btnRegister setBackgroundImage:[self imageWithColor:[UIColor lightGrayColor]] forState:UIControlStateDisabled];
btnRegister.enabled = false;
A: Here's a solution that extends the UIButton class. No need to sub-class. In my example, button alpha is set to 0.55 if .isEnabled is false, and 1.0 if it's true.
Swift 5:
extension UIButton {
override open var isEnabled: Bool {
didSet {
self.alpha = isEnabled ? 1.0 : 0.55
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: Singly linked list in java i just found this difficult interview question online and I was hoping someone could help me make sense of it. It is a generic question...given a singly linked list, swap each element of the list in pairs so that 1->2->3->4 would become 2->1->4->3.
You have to swap the elements, not the values. The answer should work for circular lists where the tail is pointing back to the head of the list. You do not have to check if the tail points to an intermediate (non-head) element.
So, I thought:
public class Node
{
public int n; // value
public Node next; // pointer to next node
}
What is the best way to implement this? Can anyone help?
A: I agree with @Stephen about not giving the answer (entirely), but I think I should give you hints.
An important thing to understand is that Java does not explicitly specify pointers - rather, whenever a non-primitive (e.g. not char, byte, int, double, float, long, boolean, short) is passed to a function, it is passed as a reference. So, you can use temporary variables to swap the values. Try to code one yourself or look below:
public static void swapNodeNexts(final Node n1, final Node n2) {
final Node n1Next = n1.next;
final Node n2Next = n2.next;
n2.next = n1Next;
n1.next = n2Next;
}
Then you'll need a data structure to hold the Nodes. It's important that there be an even number of Nodes only (odd numbers unnecessarily complicate things). It's also necessary to initialize the nodes. You should put this in your main method.
public static final int NUMPAIRS = 3;
public static void main(final String[] args) {
final Node[] nodeList = new Node[NUMPAIRS * 2];
for (int i = 0; i < nodeList.length; i++) {
nodeList[i] = new Node();
nodeList[i].n = (i + 1) * 10;
// 10 20 30 40
}
// ...
}
The important part is to set the Node next values. You can't just loop through with a for loop for all of them, because then the last one's next would throw an IndexOutOfBoundsException. Try to make one yourself, or peek at mine.
for (int i = 0; i < nodeList.length - 1; i++) {
nodeList[i].next = nodeList[i + 1];
}
nodeList[nodeList.length - 1].next = nodeList[0];
Then run your swap function on them with a for loop. But remember, you don't want to run it on every node… think about it a bit.
If you can't figure it out, here is my final code:
// Node
class Node {
public int n; // value
public Node next; // pointer to next node
@Override
public String toString() {
return "Node [n=" + n + ", nextValue=" + next.n + "]";
}
}
// NodeMain
public class NodeMain {
public static final int NUMPAIRS = 3;
public static void main(final String[] args) {
final Node[] nodeList = new Node[NUMPAIRS * 2];
for (int i = 0; i < nodeList.length; i++) {
nodeList[i] = new Node();
nodeList[i].n = (i + 1) * 10;
// 10 20 30 40
}
for (int i = 0; i < nodeList.length - 1; i++) {
nodeList[i].next = nodeList[i + 1];
}
nodeList[nodeList.length - 1].next = nodeList[0];
// This makes 1 -> 2 -> 3 -> 4 -> 1 etc.
printNodes(nodeList);
for (int i = 0; i < nodeList.length; i += 2) {
swapNodeNexts(nodeList[i], nodeList[i + 1]);
}
// Now: 2 -> 1 -> 4 -> 3 -> 1 etc.
printNodes(nodeList);
}
private static void printNodes(final Node[] nodeList) {
for (int i = 0; i < nodeList.length; i++) {
System.out.println("Node " + (i + 1) + ": " + nodeList[i].n
+ "; next: " + nodeList[i].next.n);
}
System.out.println();
}
private static void swapNodeNexts(final Node n1, final Node n2) {
final Node n1Next = n1.next;
final Node n2Next = n2.next;
n2.next = n1Next;
n1.next = n2Next;
}
}
I hope you were able to figure out at least some of this with guidance. More importantly, however, it's important that you understand the concepts here. If you have any questions, just leave a comment.
A: Simple recursive solution in Java:
public static void main(String[] args)
{
Node n = new Node(1);
n.next = new Node(2);
n.next.next = new Node(3);
n.next.next.next = new Node(4);
n.next.next.next.next = new Node(5);
n = swap(n);
}
public static Node swap(Node n)
{
if(n == null || n.next == null)
return n;
Node buffer = n;
n = n.next;
buffer.next = n.next;
n.next = buffer;
n.next.next = swap(buffer.next);
return n;
}
public static class Node
{
public int data; // value
public Node next; // pointer to next node
public Node(int value)
{
data = value;
}
}
A: Methods needed to run this program :
public static void main(String[] args) {
int iNoNodes = 10;
System.out.println("Total number of nodes : " + iNoNodes);
Node headNode = NodeUtils.createLinkedListOfNElements(iNoNodes);
Node ptrToSecondNode = headNode.getNext();
NodeUtils.printLinkedList(headNode);
reversePairInLinkedList(headNode);
NodeUtils.printLinkedList(ptrToSecondNode);
}
Approach is almost same, others are trying to explain. Code is self-explainatory.
private static void reversePairInLinkedList(Node headNode) {
Node tempNode = headNode;
if (tempNode == null || tempNode.getNext() == null)
return;
Node a = tempNode;
Node b = tempNode.getNext();
Node bNext = b.getNext(); //3
b.setNext(a);
if (bNext != null && bNext.getNext() != null)
a.setNext(bNext.getNext());
else
a.setNext(null);
reversePairInLinkedList(bNext);
}
A: Algo(node n1) -
keep 2 pointers n1 and n2, at the current 2 nodes. n1 --> n2 --->...
*
*if(n1 and n2 link to each other) return n2;
*if(n1 is NULL) return NULL;
*if(n2 is NULL) return n1;
*if(n1 and n2 do not link to each other and are not null)
*change the pointer of n2 to n1.
*call the algorthm recursively on n2.next
*return n2;
Code (working) in c++
#include <iostream>
using namespace std;
class node
{
public:
int value;
node* next;
node(int val);
};
node::node(int val)
{
value = val;
}
node* reverse(node* n)
{
if(n==NULL) return NULL;
node* nxt = (*n).next;
if(nxt==NULL) return n;
if((*nxt).next==n) return nxt;
else
{
node* temp = (*nxt).next;
(*nxt).next = n;
(*n).next = reverse(temp);
}
return nxt;
}
void print(node* n)
{
node* temp = n;
while(temp!=NULL)
{
cout<<(*temp).value;
temp = (*temp).next;
}
cout << endl;
}
int main()
{
node* n = new node(0);
node* temp = n;
for(int i=1;i<10;i++)
{
node* n1 = new node(i);
(*temp).next = n1;
temp = n1;
}
print(n);
node* x = reverse(n);
print(x);
}
A: The general approach to take is to step through the list, and on every other step you reorder the list nodes by assigning the node values.
But I think you will get more out of this (i.e. learn more) if you actually design, implement and test this yourself. (You don't get a free "phone a friend" or "ask SO" at a job interview ...)
A: Yep, write an iterative routine that progresses two links in each iteration. Remember the link from the previous iteration so that you can back-patch it, then swap the current two links. The tricky parts are getting started (to a small extent) and knowing when to finish (to a larger one), especially if you end up having an odd number of elements.
A: public static Node swapInPairs(Node n)
{
Node two;
if(n ==null ||n.next.next ==null)
{
Node one =n;
Node twoo = n.next;
twoo.next = one;
one.next =null;
return twoo;
}
else{
Node one = n;
two = n.next;
Node three = two.next;
two.next =one;
Node res = swapInPairs(three);
one.next =res;
}
return two;
}
I wrote the code at atomic level. So i hope it is self explanatory. I tested it. :)
A: public static Node swapPairs(Node start)
{
// empty or one-node lists don't need swapping
if (start == null || start.next == start) return start;
// any list we return from here on will start at what's the second node atm
Node result = start.next;
Node current = start;
Node previous = null; // so we can fix links from the previous pair
do
{
Node node1 = current;
Node node2 = current.next;
// swap node1 and node2 (1->2->? ==> 2->1->?)
node1.next = node2.next;
node2.next = node1;
// If prev exists, it currently points at node1, not node2. Fix that
if (previous != null) previous.next = node2;
previous = current;
// only have to bump once more to get to the next pair;
// swapping already bumped us forward once
current = current.next;
} while (current != start && current.next != start);
// The tail needs to point at the new head
// (if current == start, then previous is the tail, otherwise current is)
((current == start) ? previous : current).next = result;
return result;
}
A: //2.1 , 2.2 Crack the code interview
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct Node{
int info;
struct Node *next;
};
struct Node *insert(struct Node *head,int data){
struct Node *temp,*ptr;
temp = (struct Node*)malloc(sizeof(struct Node));
temp->info=data;
temp->next=NULL;
if(head==NULL)
head=temp;
else{
ptr=head;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=temp;
}
return head;
}
struct Node* reverse(struct Node* head){
struct Node *current,*prev,*next;
current = head;
prev=NULL;
while(current!=NULL){
next=current->next;
current->next = prev;
prev=current;
current=next;
}
head=prev;
return head;
}
/*nth till last element in linked list*/
void nthlastElement(struct Node *head,int n){
struct Node *ptr;
int last=0,i;
ptr=head;
while(ptr!=NULL){
last++;
//printf("%d\n",last);
ptr=ptr->next;
}
ptr=head;
for(i=0;i<n-1;i++){
ptr=ptr->next;
}
for(i=0;i<=(last-n);i++){
printf("%d\n",ptr->info);
ptr=ptr->next;
}
}
void display(struct Node* head){
while(head!=NULL){
printf("Data:%d\n",head->info);
head=head->next;
}
}
void deleteDup(struct Node* head){
struct Node *ptr1,*ptr2,*temp;
ptr1=head;
while(ptr1!=NULL&&ptr1->next!=NULL){
ptr2=ptr1;
while(ptr2->next!=NULL){
if(ptr1->info==ptr2->next->info){
temp=ptr2->next;
ptr2->next=ptr2->next->next;
free(temp);
}
else{
ptr2=ptr2->next;
}
}
ptr1=ptr1->next;
}
}
void main(){
struct Node *head=NULL;
head=insert(head,10);
head=insert(head,20);
head=insert(head,30);
head=insert(head,10);
head=insert(head,10);
printf("BEFORE REVERSE\n");
display(head);
head=reverse(head);
printf("AFTER REVERSE\n");
display(head);
printf("NTH TO LAST\n");
nthlastElement(head,2);
//printf("AFTER DUPLICATE REMOVE\n");
//deleteDup(head);
//removeDuplicates(head);
//display(head);
}
A: public class Node
{
public int n; // value
public Node next; // pointer to next node
}
Node[] n = new Node[length];
for (int i=0; i<n.length; i++)
{
Node tmp = n[i];
n[i] = n[i+1];
n[i+1] = tmp;
n[i+1].next = n[i].next;
n[i].next = tmp;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: is python capable of running on multiple cores? Question: Because of python's use of "GIL" is python capable running its separate threads simultaneously?
Info:
After reading this I came away rather uncertain on whether or not python is capable of taking advantage of a multi-core processor. As well done as python is, it feels really weird to think that it would lack such a powerful ability. So feeling uncertain, I decided to ask here. If I write a program that is multi threaded, will it be capable of executing simultaneously on multiple cores?
A: As stated in prior answers - it depends on the answer to "cpu or i/o bound?",
but also to the answer to "threaded or multi-processing?":
Examples run on Raspberry Pi 3B 1.2GHz 4-core with Python3.7.3
--( With other processes running including htop )
*
*For this test - multiprocessing and threading had similar results for i/o bound,
but multi-processing was more efficient than threading for cpu-bound.
Using threads:
Typical Result:
. Starting 4000 cycles of io-bound threading
. Sequential run time: 39.15 seconds
. 4 threads Parallel run time: 18.19 seconds
. 2 threads Parallel - twice run time: 20.61 seconds
Typical Result:
. Starting 1000000 cycles of cpu-only threading
. Sequential run time: 9.39 seconds
. 4 threads Parallel run time: 10.19 seconds
. 2 threads Parallel twice - run time: 9.58 seconds
Using multiprocessing:
Typical Result:
. Starting 4000 cycles of io-bound processing
. Sequential - run time: 39.74 seconds
. 4 procs Parallel - run time: 17.68 seconds
. 2 procs Parallel twice - run time: 20.68 seconds
Typical Result:
. Starting 1000000 cycles of cpu-only processing
. Sequential run time: 9.24 seconds
. 4 procs Parallel - run time: 2.59 seconds
. 2 procs Parallel twice - run time: 4.76 seconds
compare_io_multiproc.py:
#!/usr/bin/env python3
# Compare single proc vs multiple procs execution for io bound operation
"""
Typical Result:
Starting 4000 cycles of io-bound processing
Sequential - run time: 39.74 seconds
4 procs Parallel - run time: 17.68 seconds
2 procs Parallel twice - run time: 20.68 seconds
"""
import time
import multiprocessing as mp
# one thousand
cycles = 1 * 1000
def t():
with open('/dev/urandom', 'rb') as f:
for x in range(cycles):
f.read(4 * 65535)
if __name__ == '__main__':
print(" Starting {} cycles of io-bound processing".format(cycles*4))
start_time = time.time()
t()
t()
t()
t()
print(" Sequential - run time: %.2f seconds" % (time.time() - start_time))
# four procs
start_time = time.time()
p1 = mp.Process(target=t)
p2 = mp.Process(target=t)
p3 = mp.Process(target=t)
p4 = mp.Process(target=t)
p1.start()
p2.start()
p3.start()
p4.start()
p1.join()
p2.join()
p3.join()
p4.join()
print(" 4 procs Parallel - run time: %.2f seconds" % (time.time() - start_time))
# two procs
start_time = time.time()
p1 = mp.Process(target=t)
p2 = mp.Process(target=t)
p1.start()
p2.start()
p1.join()
p2.join()
p3 = mp.Process(target=t)
p4 = mp.Process(target=t)
p3.start()
p4.start()
p3.join()
p4.join()
print(" 2 procs Parallel twice - run time: %.2f seconds" % (time.time() - start_time))
compare_cpu_multiproc.py
#!/usr/bin/env python3
# Compare single proc vs multiple procs execution for cpu bound operation
"""
Typical Result:
Starting 1000000 cycles of cpu-only processing
Sequential run time: 9.24 seconds
4 procs Parallel - run time: 2.59 seconds
2 procs Parallel twice - run time: 4.76 seconds
"""
import time
import multiprocessing as mp
# one million
cycles = 1000 * 1000
def t():
for x in range(cycles):
fdivision = cycles / 2.0
fcomparison = (x > fdivision)
faddition = fdivision + 1.0
fsubtract = fdivision - 2.0
fmultiply = fdivision * 2.0
if __name__ == '__main__':
print(" Starting {} cycles of cpu-only processing".format(cycles))
start_time = time.time()
t()
t()
t()
t()
print(" Sequential run time: %.2f seconds" % (time.time() - start_time))
# four procs
start_time = time.time()
p1 = mp.Process(target=t)
p2 = mp.Process(target=t)
p3 = mp.Process(target=t)
p4 = mp.Process(target=t)
p1.start()
p2.start()
p3.start()
p4.start()
p1.join()
p2.join()
p3.join()
p4.join()
print(" 4 procs Parallel - run time: %.2f seconds" % (time.time() - start_time))
# two procs
start_time = time.time()
p1 = mp.Process(target=t)
p2 = mp.Process(target=t)
p1.start()
p2.start()
p1.join()
p2.join()
p3 = mp.Process(target=t)
p4 = mp.Process(target=t)
p3.start()
p4.start()
p3.join()
p4.join()
print(" 2 procs Parallel twice - run time: %.2f seconds" % (time.time() - start_time))
A: The answer is "Yes, But..."
But cPython cannot when you are using regular threads for concurrency.
You can either use something like multiprocessing, celery or mpi4py to split the parallel work into another process;
Or you can use something like Jython or IronPython to use an alternative interpreter that doesn't have a GIL.
A softer solution is to use libraries that don't run afoul of the GIL for heavy CPU tasks, for instance numpy can do the heavy lifting while not retaining the GIL, so other python threads can proceed. You can also use the ctypes library in this way.
If you are not doing CPU bound work, you can ignore the GIL issue entirely (kind of) since python won't acquire the GIL while it's waiting for IO.
A: Python threads cannot take advantage of many cores. This is due to an internal implementation detail called the GIL (global interpreter lock) in the C implementation of python (cPython) which is almost certainly what you use.
The workaround is the multiprocessing module http://www.python.org/dev/peps/pep-0371/ which was developed for this purpose.
Documentation: http://docs.python.org/library/multiprocessing.html
(Or use a parallel language.)
A: example code taking all 4 cores on my ubuntu 14.04, python 2.7 64 bit.
import time
import threading
def t():
with open('/dev/urandom') as f:
for x in xrange(100):
f.read(4 * 65535)
if __name__ == '__main__':
start_time = time.time()
t()
t()
t()
t()
print "Sequential run time: %.2f seconds" % (time.time() - start_time)
start_time = time.time()
t1 = threading.Thread(target=t)
t2 = threading.Thread(target=t)
t3 = threading.Thread(target=t)
t4 = threading.Thread(target=t)
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
print "Parallel run time: %.2f seconds" % (time.time() - start_time)
result:
$ python 1.py
Sequential run time: 3.69 seconds
Parallel run time: 4.82 seconds
A: I converted the script to Python3 and ran it on my Raspberry Pi 3B+:
import time
import threading
def t():
with open('/dev/urandom', 'rb') as f:
for x in range(100):
f.read(4 * 65535)
if __name__ == '__main__':
start_time = time.time()
t()
t()
t()
t()
print("Sequential run time: %.2f seconds" % (time.time() - start_time))
start_time = time.time()
t1 = threading.Thread(target=t)
t2 = threading.Thread(target=t)
t3 = threading.Thread(target=t)
t4 = threading.Thread(target=t)
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
print("Parallel run time: %.2f seconds" % (time.time() - start_time))
python3 t.py
Sequential run time: 2.10 seconds
Parallel run time: 1.41 seconds
For me, running parallel was quicker.
A: Threads share a process and a process runs on a core, but you can use python's multiprocessing module to call your functions in separate processes and use other cores, or you can use the subprocess module, which can run your code and non-python code too.
A: CPython (the classic and prevalent implementation of Python) can't have more than one thread executing Python bytecode at the same time. This means compute-bound programs will only use one core. I/O operations and computing happening inside C extensions (such as numpy) can operate simultaneously.
Other implementation of Python (such as Jython or PyPy) may behave differently, I'm less clear on their details.
The usual recommendation is to use many processes rather than many threads.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "91"
} |
Q: Combine elements in a nested list - Python 3
Possible Duplicate:
Python3 Concatenating lists within lists
I have
Nested_List = [['John', 'Smith'], ['1', '2', '3', '4']]
I want to manipulate this list such that I get this output:
Nested_List = [['John Smith'], ['1', '2', '3', '4']]
Basically the two elements in the first list were combined. How do I do this?
A: newElement = [' '.join(NestedList[0])]
Nested_List[0] = newElement
(modifies list, bad practice, but simple)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
} |
Q: What is the length and type of PayPal's transaction ID (txn_id)? I want to store PayPal transaction IDs. What is the length and type I need to set on that field in the database? Currently, I set varchar(128). Is that sufficient?
A: In the transaction search API it suggests the maximum length of a transaction ID is 19 single bytes. The transaction id is alphanumeric so a varchar(19) would be fine.
Personally I'd go for varchar(20) just in case they max out on transaction ids and need to add an extra digit :)
A: parent_txn_id In the case of a refund, reversal, or canceled reversal, this variable contains the txn_id of the original transaction, while txn_id contains a new ID for the new transaction.
Length: 19 characters
Type: String
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: web form does not add or delete from mysql table I'm working on a basic web form (using PHP and smarty templates) that allows users to add and delete data from a mysql database table. The data and form display fine, but nothing happens when a user tries to add or delete records from the table(not even the "cannot delete/add record' error message displays). Here is what the code looks like:
<?php //smartytest.php
$path =$_SERVER['DOCUMENT_ROOT'];
require "$path/Smarty/Smarty.class.php";
$smarty = new Smarty();
$smarty->template_dir = "$path/temp/smarty/templates";
$smarty->compile_dir= "$path/temp/smarty/templates_c";
$smarty->cache_dir="$path/temp/smarty/cache";
$smarty->config_dir="$path/temp/smarty/configs";
require_once ("$path/phptest/login.php");
$db_server=mysql_connect($db_hostname, $db_username, $db_password);
if(!$db_server) die('unable to connect to MySQL: '. mysql_error());
mysql_select_db($db_database) or die("unable to select database: " . mysql_error());
if(isset($_POST['author'])&&
isset($_POST['title'])&&
isset($_POST['category'])&&
isset($_POST['year'])&&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$category=get_post('category');
$year = get_post('year');
$isbn =get_post('isbn');
if (isset($_POST['delete']) && $isbn !='')
{
$query= "DELETE FROM classics WHERE isbn='$isbn'";
if (!mysql_query($query))
{
echo "DELETE failed: $query<br>". mysql_error() . "<p>";
}
}
else
{
$query = "INSERT INTO classics VALUES" . "('$author','$title', '$category', '$year', '$isbn')";
if (!mysql_query($query))
{
echo "INSERT failed: $query<br>" . mysql_error() . "<p>";
}
}
}
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: ". mysql_error());
$rows = mysql_num_rows($result);
for ($j=0; $j < $rows; ++$j)
{
$results[] = mysql_fetch_array($result);
}
mysql_close($db_server);
$smarty->assign('results', $results);
$smarty->display("smartytest.tpl");
function get_post($var)
{
return mysql_escape_string($_POST[$var]);
}
?>
Also, here is the Smarty template file:
<html><head>
<title>Smarty Test</title>
</head><body>
<form action="/phptest/smartytest.php" method="post"><pre>
Author <input type="text" name="author">
Title<input type="text" name="title">
Category<input type="text" name="category">
Year<input type="text" name="year">
ISBN<input type="text" name="isbn">
<input type="submit" value="ADD RECORD">
</pre></form>
{section name=row loop=$results}
<form action="/phptest/smartytest.php" method="post">
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="isbn" value="{$results[row].isbn}">
<pre>
Author {$results[row].author}
Title {$results[row].title}
Category {$results[row].category}
Year {$results[row].year}
ISBN {$results[row].isbn}
<input type="submit" value="DELETE RECORD"></form>
</pre>
{/section}
</body></html>
My best guess is that there is something wrong with the nested if statements (which may be why not even the error message is displaying), but I've double checked the code and it looks good (at least to me). Does anyone notice anything wrong with this? I can post a screen of what the page looks like if that will help.
A: You are checking for the existence of author, title, category, year, isbn with isset(..) before checking to see what type of action was taken. There variables (like $_POST['author'] are not set. Reason is that you have multiple forms on the page. Only the inputs that are within the form that is submitted are available in $_POST.
In this case, you could simply do:
if (isset($_POST['delete'])
&& isset($_POST['isbn'])
&& strlen($_POST['isbn'])) {
// Remove record code here
}
else {
// Add record code here
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Shared memory Master/Slave process to access single serial port I am creating a Daemon in Unix that will have exclusive access to a serial port "/dev/tty01". I am planning to create a Master - Slave process paradigm where there is one master (the daemon) and multiple slaves.
I was thinking of having a structure in "Shared memory" where the slaves can access, and there is only one writer to the memory so I most likely wont need a semaphore. The data will be updated fairly slowly, once every minute for example.
I was looking into what would be the best possible way to do this, also if I have a structure in shared memory, how can I guarantee that the structure will be contiguous in memory? It is a requirement I must have.
The master program will have its own internal data structure that is being updated from the serial port, and then it will modify the data and send it out to a global structure that is in shared memory for the clients to use.
I dont have much experience in Unix IPC, but what would be the easiest way to do this? By the way the clients will all be different processes ran by other users locally on the system
It must used shared memory it is a requirement of the project. Also, is it possible to copy one structure into another if the second structure has different data types?
A: *
*A shared memory segment is a contiguous piece of memory from your process' view.
*The calls to create and handle shared memory are rather simple (shmctl/shmat/shmdt)
*The layout of the structures in the memory is up to you. Best is a fixed header like a type field and the rest as an union.
*For your client processes you could provide a little lib (static or shared) with a set of functions to retrieve data, thereby hiding the shared memory and the structures.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add timestamps to an existing table I need to add timestamps (created_at & updated_at) to an existing table. I tried the following code but it didn't work.
class AddTimestampsToUser < ActiveRecord::Migration
def change_table
add_timestamps(:users)
end
end
A: Migrations are just two class methods (or instance methods in 3.1): up and down (and sometimes a change instance method in 3.1). You want your changes to go into the up method:
class AddTimestampsToUser < ActiveRecord::Migration
def self.up # Or `def up` in 3.1
change_table :users do |t|
t.timestamps
end
end
def self.down # Or `def down` in 3.1
remove_column :users, :created_at
remove_column :users, :updated_at
end
end
If you're in 3.1 then you could also use change (thanks Dave):
class AddTimestampsToUser < ActiveRecord::Migration
def change
change_table(:users) { |t| t.timestamps }
end
end
Perhaps you're confusing def change, def change_table, and change_table.
See the migration guide for further details.
A: def change
add_timestamps :table_name
end
A: Using Time.current is a good style https://github.com/rubocop-hq/rails-style-guide#timenow
def change
change_table :users do |t|
t.timestamps default: Time.current
t.change_default :created_at, from: Time.current, to: nil
t.change_default :updated_at, from: Time.current, to: nil
end
end
or
def change
add_timestamps :users, default: Time.current
change_column_default :users, :created_at, from: Time.current, to: nil
change_column_default :users, :updated_at, from: Time.current, to: nil
end
A: @user1899434's response picked up on the fact that an "existing" table here could mean a table with records already in it, records that you might not want to drop. So when you add timestamps with null: false, which is the default and often desirable, those existing records are all invalid.
But I think that answer can be improved upon, by combining the two steps into one migration, as well as using the more semantic add_timestamps method:
def change
add_timestamps :projects, default: Time.zone.now
change_column_default :projects, :created_at, nil
change_column_default :projects, :updated_at, nil
end
You could substitute some other timestamp for DateTime.now, like if you wanted preexisting records to be created/updated at the dawn of time instead.
A: Your original code is very close to right, you just need to use a different method name. If you're using Rails 3.1 or later, you need to define a change method instead of change_table:
class AddTimestampsToUser < ActiveRecord::Migration
def change
add_timestamps(:users)
end
end
If you're using an older version you need to define up and down methods instead of change_table:
class AddTimestampsToUser < ActiveRecord::Migration
def up
add_timestamps(:users)
end
def down
remove_timestamps(:users)
end
end
A: I'm on rails 5.0 and none of these options worked.
The only thing that worked was using the type to be :timestamp and not :datetime
def change
add_column :users, :created_at, :timestamp
add_column :users, :updated_at, :timestamp
end
A: not sure when exactly this was introduced, but in rails 5.2.1 you can do this:
class AddTimestampsToMyTable < ActiveRecord::Migration[5.2]
def change
add_timestamps :my_table
end
end
for more see "using the change method" in the active record migrations docs.
A: This seems like a clean solution in Rails 5.0.7 (discovered the change_column_null method):
def change
add_timestamps :candidate_offices, default: nil, null: true
change_column_null(:candidate_offices, :created_at, false, Time.zone.now)
change_column_null(:candidate_offices, :created_at, false, Time.zone.now)
end
A: class AddTimestampsToUser < ActiveRecord::Migration
def change
change_table :users do |t|
t.timestamps
end
end
end
Available transformations are
change_table :table do |t|
t.column
t.index
t.timestamps
t.change
t.change_default
t.rename
t.references
t.belongs_to
t.string
t.text
t.integer
t.float
t.decimal
t.datetime
t.timestamp
t.time
t.date
t.binary
t.boolean
t.remove
t.remove_references
t.remove_belongs_to
t.remove_index
t.remove_timestamps
end
http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html
A: A lot of answers here, but I'll post mine too because none of the previous ones really worked for me :)
As some have noted, #add_timestamps unfortunately adds the null: false restriction, which will cause old rows to be invalid because they don't have these values populated. Most answers here suggest that we set some default value (Time.zone.now), but I wouldn't like to do that because these default timestamps for old data will not be correct. I don't see the value in adding incorrect data to the table.
So my migration was simply:
class AddTimestampsToUser < ActiveRecord::Migration
def change_table
add_column :projects, :created_at, :datetime
add_column :projects, :updated_at, :datetime
end
end
No null: false, no other restrictions. Old rows will continue being valid with created_at as NULL, and update_at as NULL (until some update is performed to the row). New rows will have created_at and updated_at populated as expected.
A: The timestamp helper is only available in the create_table block. You can add these columns by specifying the column types manually:
class AddTimestampsToUser < ActiveRecord::Migration
def change_table
add_column :users, :created_at, :datetime, null: false
add_column :users, :updated_at, :datetime, null: false
end
end
While this does not have the same terse syntax as the add_timestamps method you have specified above, Rails will still treat these columns as timestamp columns, and update the values normally.
A: I made a simple function that you can call to add to each table (assuming you have a existing database) the created_at and updated_at fields:
# add created_at and updated_at to each table found.
def add_datetime
tables = ActiveRecord::Base.connection.tables
tables.each do |t|
ActiveRecord::Base.connection.add_timestamps t
end
end
A:
add_timestamps(table_name, options = {}) public
Adds timestamps (created_at and updated_at) columns to table_name. Additional options (like null: false) are forwarded to #add_column.
class AddTimestampsToUsers < ActiveRecord::Migration
def change
add_timestamps(:users, null: false)
end
end
A: This is a simple one to add timestamp in existing table.
class AddTimeStampToCustomFieldMeatadata < ActiveRecord::Migration
def change
add_timestamps :custom_field_metadata
end
end
A: In rails 6 (and possibly earlier) if you try to add timestamps to an existing table with records already present like this:
def change
add_timestamps :table_name
end
you will get an error owing to the fact that add_timestamps by default declares the new colums as NOT NULL. You can work around this simply by adding null: true as an argument:
def change
add_timestamps :table_name, null: true
end
A: Nick Davies answer is the most complete in terms of adding timestamp columns to a table with existing data. Its only downside is that it will raise ActiveRecord::IrreversibleMigration on a db:rollback.
It should be modified like so to work in both directions:
def change
add_timestamps :campaigns, default: DateTime.now
change_column_default :campaigns, :created_at, from: DateTime.now, to: nil
change_column_default :campaigns, :updated_at, from: DateTime.now, to: nil
end
A: The issue with most of the answers here is that if you default to Time.zone.now all records will have the time that the migration was run as their default time, which is probably not what you want. In rails 5 you can instead use now(). This will set the timestamps for existing records as the time the migration was run, and as the start time of the commit transaction for newly inserted records.
class AddTimestampsToUsers < ActiveRecord::Migration
def change
add_timestamps :users, default: -> { 'now()' }, null: false
end
end
A: The answers before seem right however I faced issues if my table already has entries.
I would get 'ERROR: column created_at contains null values'.
To fix, I used:
def up
add_column :projects, :created_at, :datetime, default: nil, null: false
add_column :projects, :updated_at, :datetime, default: nil, null: false
end
I then used the gem migration_data to add the time for current projects on the migration such as:
def data
Project.update_all created_at: Time.now
end
Then all projects created after this migration will be correctly updated. Make sure the server is restarted too so that Rails ActiveRecord starts tracking the timestamps on the record.
A: You can use a migration like this to add a created_at and updated_at columns to an existing table with existing records. This migration sets the created_at and updated_at fields of existing records to the current date time.
For the sake of this example say the table name is users and the model name is User
class AddTimestampsToTcmOrders < ActiveRecord::Migration[6.0]
def up
# Add timestamps to the users table with null as true cause there are existing records
add_timestamps(:users, null: true)
# Update existing records with non-nil timestamp values
User.update_all(created_at: DateTime.now, updated_at: DateTime.now)
# change columns so they can't be nil
change_column(:users, :updated_at, :datetime, null: false, precision: 6)
change_column(:users, :created_at, :datetime, null: false, precision: 6)
end
def down
remove_column :users, :updated_at
remove_column :users, :created_at
end
end
A: For those who don't use Rails but do use activerecord, the following also adds a column to an existing model, example is for an integer field.
ActiveRecord::Schema.define do
change_table 'MYTABLE' do |table|
add_column(:mytable, :my_field_name, :integer)
end
end
A: It's change, not change_table for Rails 4.2:
class AddTimestampsToUsers < ActiveRecord::Migration
def change
add_timestamps(:users)
end
end
A: I personally used the following, and it updated all previous records with the current time/date:
add_column :<table>, :created_at, :datetime, default: Time.zone.now, null: false
add_column :<table>, :updated_at, :datetime, default: Time.zone.now, null: false
A: I ran into the same issue on Rails 5 trying to use
change_table :my_table do |t|
t.timestamps
end
I was able to add the timestamp columns manually with the following:
change_table :my_table do |t|
t.datetime :created_at, null: false, default: DateTime.now
t.datetime :updated_at, null: false, default: DateTime.now
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "194"
} |
Q: preg_replace capture group check I'm trying to add a new bbcode to my phpfusion application. Im using with preg_replace. Here's the code:
$text = preg_replace(
"#\[gameimg( float:(left|center|right))?\]((http|ftp|https|ftps)://)(.*?)(\.(jpg|jpeg|gif|png|JPG|JPEG|GIF|PNG))\[/gameimg\]#sie",
"'<span style=\"display: block; max-width: 350px; margin: 0 0 5px 5px; $1\"><img src=\"'
. (strlen('$3') > 0 ? '$3' : BASEDIR.GAMESDIR)
. '$5$6\" alt=\"$5$6\" style=\"border:0px; max-width: 350px;\" /></span>'",
$text
);
If I supply an absolute url (for ex. [gameimg]http://localhost/dirname/file.jpg[/gameimg]) everything works fine, the picture shows up as expected. But if i omit the protokol and hostname using relative url ([gameimg]dirname/file.jpg[/gameimg]) i expect to append the basedir.gamedir constant to the given url but it doesn't work at all, it prints out the original bbcode without any replacement, not the image. What am i doing wrong?
A: A couple things here:
*
*That is a giant preg_replace call. Maybe you could break this problem into smaller parts so that it is easier to understand/maintain?
*You are using the "ignore case" modifier (i), yet you have things like (jpg|JPG). This is redundant.
*Your question asks why [gameimg] tags without http://.. don't get matched. Well this is because of the required ((http|ftp|https|ftps)://) in your regex. You should make this section optional by adding a ?, like this:
((http|ftp|https|ftps)://)?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HashMap with int array (int[]) as value returns null on get? I have a Hashmap that stores a student name as the key and an int array of scores as the value. I know its creating the HashMap correctly but when trying to return the int array for a key I cant seem to get.
public int[] getQuizzes(String studentName)
{
int[] studentsQuizzes = quizMarks.get(studentName);
return studentsQuizzes;
}
It just ends up returning null. What am I missing, thanks for any help
This is how I am creating the hashmap
quizMarks = new HashMap<String, int[]>();
public void addStudent(String studentName)
{
String formattedName = formatName(studentName);
int[] quizzes = new int[NUM_QUIZZES];
for (int i = 0; i < quizzes.length; i++)
{
quizzes[i] = MIN_GRADE;
}
quizMarks.put(formattedName, quizzes);
}
A: Your keys in the map are the results of calling formatName on the student name passed in. You don't appear to be using the formatted name as the key when calling get on the map, meaning the keys you pass to get are not the same as those you passed to put.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Travel APIs how to integrate them all? I may start working on a project very similar to Hipmunk.com, where it pulls the hotel cost information by calling different APIs (like expedia, orbitz, travelocity, hotels.com etc)
I did some research on this, but I am not able to find any unique hotel id or any field to match the hotels between several API's. Anyone have experience on how can to compare the hotel from expedia with orbitz or travelcity etc?
Thanks
EDIT: Google also doing the same thing http://www.google.com/hotelfinder/
A: From what I have seen of GDS systems, and these API's there is rarely a unique identifier between systems for e.g. hotels
Airports, airlines and countries have unique ISO identifiers: http://www.iso-code.com/airports.2.html
I would guess you are going to have to have your own internal mapping to identify and disambiguate the properties.
:|
A: When you get started with hotel APIs, the choice of free ones isn't really that big, see e.g. here for an overview.
The most extensive and accessible one is Expedia's EAN http://developer.ean.com/ which includes Sabre and Venere with unique IDs but still each structured differently.
That is, you are looking into different database tables.
You do get several identifies such as Name, Address, and coordinates, which can serve for unique identification, assuming they are free of errors. Which is an assumption.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.