text
stringlengths
8
267k
meta
dict
Q: To use auto-increment in MySQL or not? I have read certain places that it is a good practice to typically use an auto-incrementing Primary key for most MySQL tables, rather than simply relying on a non-increment field that will be enforced to be unique. My question is specifically about a User table, and a table connected to it by a Foreign Key. Here's the schema: TABLE Users { id name ... } TABLE Authors { user_id (FK) author_bio } Should the Authors table have its own auto-incrementing primary key as well, or should it rely on the user_id foreign key as a primary key? ALSO Are there noticeable performance reasons to NOT use the auto-incrementing id as the Primary? A: It's not either-or. If you use an auto increment primary key, and you have candidate keys that need to enforce constraints, then your schema should have both. Both your user and author tables should have individual primary keys. (Every table must have a primary key.) I would not use the foreign key as the primary key. If that truly is the case, I wouldn't have a separate author table; I'd put those columns in the user table. PS - My naming preference is singular for tables. It should be user and author tables. They happen to contain multiple rows, but a single row means a single entity. A: You most definitely want the Authors table to have its own primary key such as authors_id, and then have user_id as a foreign key. A: It depends on what you're trying to accomplish. If every author maps to exactly one user (and you're sure this isn't going to change), you can get away with having user_id as a primary key. If not, you'll need an independent primary key for Authors. (Note that the reverse relation doesn't have to be true: not every user has to map to an author.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7549720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Delphi 7 IDE Stack Overflow Error Could anyone tell me, why I keep getting the following errors? Background: The project has 320 Embedded Forms. The projects search path has 205 folders, at a length of just over 11,000 chars. If I remark out just 1 of the embedded form units, then it compiles without an error. IMAGE #1 - From Delphi IDE IMAGE #2 - From DCC32.EXE Here is the unit I use for my embedded forms unit EmbeddedForm; interface {$INCLUDE '..\INCLUDE\BUILD.INC'} uses Windows, Controls, Messages, Forms; type TEmbeddedForm = class(TForm) procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } procedure StopFlicker(var theMessage: TWMEraseBkgnd); message WM_ERASEBKGND; protected { Protected declarations } procedure CreateParams(var Params: TCreateParams); override; public { Public declarations } procedure InitializeForm(); virtual; abstract; procedure FinalizeForm(); virtual; abstract; end; implementation {$R *.DFM} procedure TEmbeddedForm.StopFlicker(var theMessage: TWMEraseBkgnd); begin theMessage.Result := 1; end; procedure TEmbeddedForm.CreateParams(var Params: TCreateParams); const ParamStyle = WS_VISIBLE or WS_POPUP or WS_OVERLAPPED or WS_OVERLAPPEDWINDOW; begin inherited CreateParams(Params); Params.ExStyle := (Params.ExStyle and (not WS_EX_WINDOWEDGE) and (not WS_EX_STATICEDGE) and (not WS_EX_DLGMODALFRAME) and (not WS_EX_CLIENTEDGE)); Params.Style := (Params.Style and (not WS_CAPTION) and (not DS_MODALFRAME) and (not WS_DLGFRAME) and (not WS_THICKFRAME)); Params.Style := Params.Style and not ParamStyle; end; procedure TEmbeddedForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := False; end; procedure TEmbeddedForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caNone; end; end. A: You could try using a PE editor to increase the stack size of IDE or dcc32. But make backups first! Editbin should do the trick. A: Try to change these values: Project->Options->Linker->Memory sizes Min stack size as hex value Max stack size as hex value
{ "language": "en", "url": "https://stackoverflow.com/questions/7549722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: TimeStamp Standard PHP I am working on creating a log file where log details including timestamp should be written to the log file. But is there any standard timestamp function which I can use in the php code which does not show any sort of errors like "You cannot rely on SYstem's timezone' etc . Thanks A: You could try this: date_default_timezone_set('GMT'); $stamp = time(); A: See date_default_timezone_set(..) to get rid of that error. Otherwise use time() and date(..).
{ "language": "en", "url": "https://stackoverflow.com/questions/7549735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Refactor rename field in many database tables I am faced with renaming a field where the same fieldname is replicated across many tables. Looking for a script or free/low cost tool which will go through all the tables and if fieldA exists, rename it to fieldB. thanks A: You can use SQL Server metadata tables to create dynamic sql statements for your purpose. For list of available tables you can sys.tables for list of tables and sys.columns for list of columns. using these tables you can create a table of sql statements. For executing dynamic sqls you need to sp_executesql stored procedure. This is a sample code just to show how to use metadata tables and sp_executesql: And note that I used other metadata tables which I am more comfortable with. also you may use a cursor to run all the scripts returned by query. CREATE Database TestDB CREATE Table Table1 (Id int , fieldA varchar(50) ) Declare @update_query nvarchar(max) select @update_query = 'sp_rename ''' + t.TABLE_NAME + '.' + c.COLUMN_NAME + ''',''' + 'fieldB' + '''' From INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.Tables t ON c.TABLE_CATALOG = t.TABLE_CATALOG AND c.TABLE_SCHEMA = t.TABLE_SCHEMA AND c.TABLE_NAME = t.TABLE_NAME WHERE c.COLUMN_NAME = 'fieldA' SELECT @update_query EXEC sp_executesql @update_query A: Take a look at the Database project type in VS2010, if you haven't already. It has a lot of features that make DB refactoring easier than working SQL Server Management Studio. For example if you rename a column, it will give you build errors for all the FKs that reference the old column name. And it does a lot of build-time validation to make sure your database objects don't reference objects which no longer exist. And because all of the database objects are just kept as text files, actions like rename are pretty much just search/replace. Also, it has very handy "sync" feature which compares the DB project scripts & databases, generates a DIFF report, and generates the scripts to move selected changes between the two (either DB project to SQL Server, or vice versa). Having said all that, it won't automatically do the renames for you -- in other words, when you rename a column it won't fix up all references to that column throughout the project. But if you make a mistake you will get build errors when it validates the database structure. So at least makes it easy to find the places that you need to change. A: If you're using Azure SQL Server, you can use Sam's answer with another input parameter to sp_rename, @objtype = 'COLUMN'. Declare @update_query nvarchar(max) select @update_query = 'sp_rename ''' + t.TABLE_NAME + '.' + c.COLUMN_NAME + ''',''' + 'fieldB' + ''',''' + 'COLUMN' + '''' From INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.Tables t ON c.TABLE_CATALOG = t.TABLE_CATALOG AND c.TABLE_SCHEMA = t.TABLE_SCHEMA AND c.TABLE_NAME = t.TABLE_NAME WHERE c.COLUMN_NAME = 'fieldA' SELECT @update_query EXEC sp_executesql @update_query
{ "language": "en", "url": "https://stackoverflow.com/questions/7549739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery image-background chrome problem This doesn't seem to work in chrome: $(function(){ $('body').css('background-image','url(/static/img/b1_left.png'); } when I apply it in css it works fine: background-image: url('/static/img/b1_left.png'); in firefox both work fine. I need it to work in jquery, to process hover events (when something is hovered, it and another element has to change background) A: Missing a parentheses: $(function(){ $('body').css('background-image','url("/static/img/b1_left.png")'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: python: check function parameter types Since I just switched to Python from C++, I feel like python does not care much about type safety. For example, can anyone explain to me why checking the types of function parameters is not necessary in Python? Say I defined a Vector class as follows: class Vector: def __init__(self, *args): # args contains the components of a vector # shouldn't I check if all the elements contained in args are all numbers?? And now I want to do dot product between two vectors, so I add another function: def dot(self,other): # shouldn't I check the two vectors have the same dimension first?? .... A: Well, as for necessity of checking the types, that may be a topic that's a bit open, but in python, its considered good form to follow "duck typing". The function just uses the interfaces it needs, and it's up to the caller to pass (or not) arguments that properly implement that interface. Depending on just how clever the function is, it may specify just how it uses the interfaces of the arguments it takes. A: It is true that in python there is no need to check the types of the parameters of a function, but maybe you wanted an effect like this... These raise Exception occur at runtime... class Vector: def __init__(self, *args): #if all the elements contained in args are all numbers wrong_indexes = [] for i, component in enumerate(args): if not isinstance(component, int): wrong_indexes += [i] if wrong_indexes: error = '\nCheck Types:' for index in wrong_indexes: error += ("\nThe component %d not is int type." % (index+1)) raise Exception(error) self.components = args #...... def dot(self, other): #the two vectors have the same dimension?? if len(other.components) != len(self.components): raise Exception("The vectors dont have the same dimension.") #.......
{ "language": "en", "url": "https://stackoverflow.com/questions/7549746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: command line node.js; running script with modules I'm doing some testing with node.js and several modules\libraries. For simplicity I'll focus on underscore.js. When I run node.exe with the following source: require("./underscore.js"); _.each({one : 1, two : 2, three : 3}, function(num, key){ console.log(num); }); I get: C:\Dropbox\personal-work\foo\test code>node library-tests.js node.js:208 throw e; // process.nextTick error, or 'error' event on first tick ^ ReferenceError: _ is not defined at Object.<anonymous> (C:\Dropbox\personal-work\foo\test code\library-tests.js:2:1) at Module._compile (module.js:425:26) at Object..js (module.js:443:10) at Module.load (module.js:344:31) at Function._load (module.js:303:12) at Array.<anonymous> (module.js:463:10) at EventEmitter._tickCallback (node.js:200:26) What is also strange is that when I run it like this: node underscore.js library-tests.js It doesn't seem to do anything at all...I've even added log statements, they don't seem to execute. I've also tried pasting in the underscore.js source into the top of my source and I get the same error... Does anyone know what I'm doing wrong here? Thanks. A: try assigning it: var _ = require('../underscore.js'); You can see here in the annotated source code that underscore will not add itself to the global namespace if it is running in a CommonJS implementation (of which, Node.JS is one).
{ "language": "en", "url": "https://stackoverflow.com/questions/7549756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: togglebutton remember state In AIR, I'm create a nativewindow component that will generate a set of togglebutton, as each time the code below is run whether I open a nativewindow, the togglebutton will be reset to the default state. How do I make the state persistent? for(var i:int=0;i<10;++) toggbtn.label = "Power "+1; stage.addElement(toggbtn); } A: This is surprisingly (and happily) simple. Create a variable, like this: var toggbtnVar:String; Then, drop the following line of code into your button click event: togglebtnVar = togglebtn.state; In the above code, you are simply setting the string variable you created to the state of the togglebtn. The .state will be either "on" or "off". Thus, to retrieve the last saved state of the button, just reverse the previous line of code. togglebtn.state = togglebtnVar; I will warn you, the above lines of code are UNTESTED, so you may have to tweak it a little. But you get the general idea. I'm fairly sure by inference that .state accepts a string, however, if it does not, you can set up the variable as a boolean, and set the state inside an if, else if statement. Now, the only thing you have to do is ensure you save that variable. There are a number of ways to do that, so I'll leave that part of the research to you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Express session store and reapInterval I have a question about express session store memory with setting the reapInterval value. I have an example code, which will output the values of a memorystore every 5 seconds. If i now set a reapinterval of 5000, it should clean up expired session every 5 seconds right? So my example looks like this: /** * Module dependencies. */ var express = require('express'); var app = module.exports = express.createServer(); var MemStore = require('express/node_modules/connect/lib/middleware/session/memory'); var store = new MemStore({reapInterval: 5000}); // Configuration app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(express.session({secret: 'your secret here', store: store, cookie: {maxAge: 30000}})); app.use(app.router); app.use(express.static(__dirname + '/public')); }); setInterval(function(){ console.log(new Date()); console.log(store); }, 5000); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ app.use(express.errorHandler()); }); // Routes app.get('/', function(req, res){ res.render('index', { title: 'Express' }); }); app.listen(3000); console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); And now the problem is, that if I revisit the page after 30 seconds, I get a new SID, but the old session in memorystore is still there... should it not be checked every 5 seconds and deleted? Thx for your help! A: So the first problem is a misunderstanding here. reapInterval does not do anything. MemoryStore clears cookies based on the expire time of session cookie. So there is in fact a bug in Connects MemoryStore. The way I see it the broken flow goes like this. * *Set cookie to expire in X. *Get session data, has X gone by? No, ok. *(cookie expires) *Get session data, session doesn't exist, generate new one. *X has gone by but the session ID is missing because the browser expired it already. There is a discussion regarding this here. https://github.com/senchalabs/connect/issues/328 And a juicy quote "short cookie sessions would be screwed I guess" --visionmedia
{ "language": "en", "url": "https://stackoverflow.com/questions/7549770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What mysql data type should I use for encrypted text? Here's the type of text my encryption function throws out: I generated several strings and they're never bigger than 50 characters, but I would like to give it 75 characters in mysql. I tried using varchar, but the string gets cut off because it doesn't like some characters. Any idea what data type I should use? A: If it's binary data (it looks like it is), you probably should store it in a BLOB. A: You can use a blob, but for short data, that will make your selects slow. Use binary(75) or varbinary(75).
{ "language": "en", "url": "https://stackoverflow.com/questions/7549773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Controller show action code is flawed, but error is silent Here is my User controller show action def show @public_groups = Group.public @groups_member = @user.groups_as_member @groups_as_owner = @user.groups_as_owner @random_items = [] @assignments = [] unless @groups_member.nil? until @random_items.count == 5 do random_groups = @groups_member.sort_by{rand}.slice(0,5) random_groups.each do |group| assignments = Assignment.where(:group_id => group.id).limit(5).all #assignments = Assignment.find_by_group_id(group.id) y = Post.find_by_id(assignments.rand.post_id) @random_items << y end end end end I think it might be the way I am declaring the instance variable arrays @random_items and @assignments. I have no idea what the problem is though because my development and production servers don't give any compilation errors or anything. When I comment out the big block of logic starting with the array declarations the site works. A: I'd suggest you to perform a refactoring before you can find an error. Some principles before: * *Any dataflow is about model layer responsibility *instance variables are use to share objects between ActionPack layers (controller and view) *use object's attributes instead of instance variables to easy to test *use associations and minimize Arel method and just find in controllers With according to your code, it can be rewritten with: # User model def random_items return unless groups_as_member random_groups = groups_member.sort_by{rand}.slice(0,5) random_groups.each do |group| return if randorm_groups.length > 5 assignments = group.assignments.limit(5) if y = Post.rand_by_post(assignments) random_groups << y end end return random_groups end # Post model def self.rand_by_post(assignments) find_by_id(assignments.rand.post_id) end Once you have the logic clear, you can find the bug and cover it with tests.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: browse button missing from input file in IE8? I've taken a screenshot of my file input method for both IE 9 and 8. Why would IE not show the browse button? the table sits inside a form like so: <table> <tr> <td colspan="2"><h3>Upload Photo</h3></td> </tr> <tr> <td colspan="2"><input type="file" name="mapimage" id="mapimage"/></td> </tr> <tr> <td><input type="submit" value="Upload" name="update_image" id="update_image"/> </td> <td><img id="loading" src="images/loading.gif" alt="working.." style="visibility: hidden;" /></td> </tr> </table> I've tried adding a size attribute but it still isn't showing up. Are there any work arounds for IE 8 and below or is this a known issue? A: I saw this as well when I was testing in IE Tester. Asked someone who had a native version of IE8 and saw it looks fine. I believe it's just a bug in IE Tester. A: Unless you have some css somewhere doing this I see no problem. It works for me in IE8.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: jQuery Ajax not returning success I have this code that goes to form.php instead of pulling the echoed php into a #success div on my main page: <script type="text/javascript"> data = $(form).serialize(); $('#form').submit(function() { $.ajax({ url: '../wp-content/themes/MC/form.php', type: 'POST', data: data, success: function(result) { $('#success').html('').html(result); } }); }); </script> <div id="form"> <br> <form action="http://www.mcfilmmakers.com/wp-content/themes/MC/form.php" method="post"> Name / Nom:<input type="text" name="fullname" /><br /> E-mail / Courriel:<input type="text" name="email" /><br /> Your Daily URL / Votre URL Quotidien:<input type="text" name="link" /><br /> Voting Instructions / Instructions de Vote:<textarea name="instr" style="width: 450px; height: 100px;"/></textarea><br /> <input type="submit" value="Submit" /> </form> </div> <div id="success"> </div> The form.php does recieve the post information because it is echoing the input. For some reason though, it's just not being inserted into #success. A: Try this: $('#form').submit(function(event) { $.ajax({ url: '../wp-content/themes/MC/form.php', type: 'POST', data: data, success: function(result) { $('#success').html(result); } }); event.preventDefault(); }); When submitting your form, by default it will post the form the the action attribute of the form. You want to prevent that post from happening, and instead do it with ajax. So event.preventDefault() will prevent that. Also no need to chain .html('') because it sets the entire content. See http://api.jquery.com/html/ A: your code: $('#form').submit(function() #form points to `div id="form"` You register onsubmit event to div. try adding id=form like this: <form action="http://www.mcfilmmakers.com/wp-content/themes/MC/form.php" method="post" id="form"> and delete id="form" from div.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PhotoShop Define Brush Preset I'm trying to make a brush that gives a sparkle effect. It's just a circle brush with a cross in the middle. Any way, when I try to define the brush preset, it says "Could not complete the command Define Brush Preset because the selected area is empty." Anyone know why this is happening? A: Press CTRL + D and deselect whatever you have selected. If you attempt to define a brush preset without anything selected, it should turn the whole image into a brush, but if you are trying to make a selection then make sure that you are selected on the correct layer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Seeding database from engine root fails to locate db/seeds.rb After creating a new Rails 3.1 gem plugin via: rails plugin new core --full I am trying to seed the database with: rake db:seed I am running into the following error: rake aborted! can't convert nil into String Moving the seeds.rb file into the test/dummy/db directory seems to resolve the problem. Is there any way to let the db:seed task know what the current working directory is, or where to find the seeds.rb file? The ideal solution would be to keep seeds.rb within my engines db directory A: I got this error when I made a mistake naming my seed file "seed.rb", not "seeds.rb". Hope, this helps. A: Try creating your engine as rails plugin new core --full --mountable You should now be able to do rake db:migrate from your engine root. If it's not a mountable engine, since the generators would typically deploy to your app (in this case test/dummy or spec/dummy) it makes sense that the rake task would be run from the host application. A: I solved this by creating a seeds.rb in my dummy/db directory. In the seeds.rb file I created, I just added: require File.expand_path('../../../../db/seeds.rb', __FILE__) This basically extends and runs the seeds.rb file in the engines db directory. Please Note * *I am using both --full and --mountable and rake db:seed did not work (plus various other things) *I am using rspec for my tests, so my dummy is in the spec/dummy directory of the engine *I modified my rake and rails so that I could get rspec working useful posts I have found * *rails 3.1 engines with rspec Hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7549784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: xcode Search Locations on MapKit I want to search places like google map in my app with using MKMapView. I searched and find that i should use webview with integrating google map api. However, i don't want that. Is there any service that i can send place name as input and it returns appropriate results with locations,names,address etc. When i look for google map service, i think it is not free , thus i can not use it. For example: I send boston university as input it will return Boston University lat:xxxxx lng:xxxxx Address:xxxxxx Thanks A: Check out BSForwardGeocoder it makes the process incredibly easy. https://github.com/bjornsallarp/BSForwardGeocoder
{ "language": "en", "url": "https://stackoverflow.com/questions/7549787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VBA for loop addition I am trying to write a loop that adds odd numbers up to a certain point. How can I get the integer i to go up by 2. I know there is a way, it's something like i by 2, but I don't remember the exact command. If anyone could please help me, I would appreciate it A: Do you mean: For i = 1 To 9 Step 2 Next i Or: For i = 1 To 10 If i Mod 2 = 1 Then '// Odd End If Next i
{ "language": "en", "url": "https://stackoverflow.com/questions/7549791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I use JAXRS annotations(for example @Produces) in an interface class in Grails I am trying to create an interface class in Grails and implement that in a resource. I wanted to use the @Produces annotation in the interface class and use(implement) that in my resources class. I created my interface in src/groovy. But, it doesn't like the @Produces annotation, gives syntax error. My interface is something like this: import javax.ws.rs.Produces public interface annotationInterface { @Produces(['application/xml','application/json']) } Could anyone please tell me what I am doing wrong? thanks A: Your annotation does not annotate anything, that is why the compiler complains. javax.ws.rs.Produces can annotate methods or classes, so in your case I would think that import javax.ws.rs.Produces @Produces(['application/xml','application/json']) public interface annotationInterface { } I cannot say if it makes sense though, because annotations are not inherited, so any class implementing the interface won't have that annotation. So unless there is a lookup for this annotation on implementing interfaces and/or super classes it won't work. A: Did you used the Jax-rs plug-in ? If not, there will be a class path problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scala Parallel Sort Using java.util.Arrays and scala.concurrent.ops.par I think I have implemented some of my code wrong. I cannot figure out why my sort (using arrays.sort) is taking longer in the "parallel" version than in the non-parallel version (it's obviously in putting the two arrays back together, but I didn't think it would add that much more time on). If someone could point out any mistakes that I am making or any tips to improve the parallel version over the non-parallel version I would appreciate it. Am I able to do the array merge more efficiently, or maybe even in parallel? If so, what is the best practice for implementation. Any help would be greatly appreciated. import java.util.Arrays import scala.concurrent._ import scala.collection._ trait Sorts { def doSort(a: Array[Double]): Array[Double] } object Simple extends Sorts { def doSort(a: Array[Double]) = { Arrays.sort(a) a } } object Parallel extends Sorts { def doSort(a: Array[Double]) = { val newArray = new Array[Double](a.length) val aLength = (a.length) val aSplit = ((a.length / 2).floor).toInt ops.par(Arrays.sort(a, 0, aSplit), Arrays.sort(a, (aSplit + 1), aLength)) def merge(w: Int, x: Int, y: Int) { var i = w var j = x var k = y while (i <= aSplit && j <= aLength) { if (a(i) <= a(j)) { newArray(k) = a(i) i = i + 1 } else { newArray(k) = a(j) j = j + 1 } k = k + 1 } if (i < aSplit) { for (i <- i until aSplit) { newArray(k) = a(i) k = k + 1 } } else { for (j <- j until aLength) { newArray(k) = a(j) k = k + 1 } } } merge(0, (aSplit + 1), 0) newArray } } object Main { def main(args: Array[String]): Unit = { val simpleNumbers = Array.fill(10000)(math.random) println(simpleNumbers.toList + "\n") val simpleStart = System.nanoTime() Simple.doSort(simpleNumbers) val simpleEnd = System.nanoTime() println(simpleNumbers.toList + "\n") val simpleDifference = ((simpleEnd - simpleStart) / 1e9).toDouble val parallelNumbers = Array.fill(10000)(math.random) println(parallelNumbers.toList + "\n") val parallelStart = System.nanoTime() Parallel.doSort(parallelNumbers) val parellelEnd = System.nanoTime() println(parallelNumbers.toList + "\n") val parallelDifference = ((parellelEnd - parallelStart) / 1e9).toDouble println("\n Simple Time Taken: " + simpleDifference + "\n") println("\n Parallel Time Taken: " + parallelDifference + "\n") } } Output on an Intel Core i7: Simple Time Taken: 0.01314 Parallel Time Taken: 0.05882 A: I think you've got a couple of different things going on here. First, on my system the ops.par(Arrays.sort(...)) line by itself takes longer than all of Simple.doSort(). So there must be some overhead (thread creation?) that dominates the performance gain for a smallish array. Try it for 100,000 or a million elements. Second, Arrays.sort is an in-place sort, so it doesn't have to incur the cost of creating a new 10k element array for the results. To avoid creating the second array, you can do the partition first and then sort the two halves in parallel, as recommended here def doSort(a: Array[Double]) = { val pivot = a(a.length-1) var i = 0 var j = a.length-2 def swap(i: Int, j: Int) { val temp = a(i) a(i) = a(j) a(j) = temp } while(i < j-1) { if(a(i) <= pivot) { i+=1 } else { swap(i,j) j-=1 } } swap(j-1, a.length-1) ops.par(Arrays.sort(a,0,a.length/2), Arrays.sort(a,a.length/2+1,a.length)) a } After upping the array size to 100k, I do see the parallel version performing around twice as fast on an Intel E5300 CPU.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Obtaining results from MongoDB with PHP (working with command line) I'm trying to obtain a simple collection doing the next: <?php echo "<pre>"; $mongo = new Mongo(); var_dump($mongo); $db = $mongo->testdb; var_dump($db); $cursor = $db->users->find(); var_dump($cursor); ?> And I get the next output: object(Mongo)#1 (4) { ["connected"]=> bool(true) ["status"]=> NULL ["server":protected]=> string(0) "" ["persistent":protected]=> NULL } object(MongoDB)#2 (2) { ["w"]=> int(1) ["wtimeout"]=> int(10000) } object(MongoCursor)#4 (0) { } IF in the command line I do this: use testdb; db.users.find(); I obtain: { "_id" : ObjectId("4e7fca596803fa4b53000000"), "username" : "test4", "password" : "md5pass", "email" : "test4@email.tld", "group" : 1, "profile_fields" : "a:0:{}" } { "_id" : ObjectId("4e7fca6e6803fa4a53000000"), "username" : "test4", "password" : "md5pass", "email" : "test4@email.tld", "group" : 1, "profile_fields" : "a:0:{}" } { "_id" : ObjectId("4e7fca726803fa4a53000001"), "username" : "test4", "password" : "md5pass", "email" : "test4@email.tld", "group" : 1, "profile_fields" : "a:0:{}" } { "_id" : ObjectId("4e7fca736803fa4a53000002"), "username" : "test4", "password" : "md5pass", "email" : "test4@email.tld", "group" : 1, "profile_fields" : "a:0:{}" } { "_id" : ObjectId("4e7fcae26803fa4c53000000"), "username" : "test4", "password" : "md5pass", "email" : "test4@email.tld", "group" : 1, "profile_fields" : "a:0:{}" } { "_id" : ObjectId("4e7fcb076803fa4953000000"), "username" : "test1", "password" : "md5pass", "email" : "test1@email.tld", "group" : 1, "profile_fields" : "a:0:{}" } What I'm doing wrong? Thank you in advance! A: Do a foreach on the Cursor in your first example. The reason being you do not see anything in the var_dump is that it is a resource. Resources are pointers, they do not hold real data by themselves.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android Graphical Layout Editor in eclipse can't see my custom class I have created a new class that extends the RelativeLayout and when viewing this using the Grahical Layout editor, I always see this error: The following classes could not be found: - eg.package.StripedBackgroundLayout Has anyone experience this before and how to resolve it please? I'm using ADT 12.0.0 A: Yes, you currently cannot resolve this. The Graphical Layout Editor is not equipped to handle custom classes at the moment. It can be achieved with some hefty modification, but it isn't worth the time. It will be included in later Graphical Layout editor updates. A: Another funny thing about eclipse is that, when I we open the graphical layout view for the first time it shows your custom view's when you clear the project.. till any modification in layout, then you just need to clear it again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Save login details(preferences) android I have one android app with login, logout functions. The login form contains Username and password and the login button. I want to save the username and the password when the user checks the "Remember me" check box. My project.java file is shown below: public class project extends Activity { private static final int IO_BUFFER_SIZE = 4 * 1024; /** Called when the activity is first created. */ public int user_id,current_user_id; public String access_token,username,current_username; public boolean user_logged_in=false; public ProgressDialog progdialog; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); progdialog = new ProgressDialog(this); progdialog.setMessage("loading..."); initLogin(); } public void initLogin(){ setContentView(R.layout.login); Button button = (Button) findViewById(R.id.login_login); button.setOnClickListener(new View.OnClickListener(){ public void onClick(View v) { login(); } }); } public void login(){ try{ String login_username=(((EditText) findViewById(R.id.login_username)).getText()).toString(); String login_password=(((EditText) findViewById(R.id.login_password)).getText()).toString(); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("username",login_username)); nameValuePairs.add(new BasicNameValuePair("password",login_password)); String content=postUrlContent(api_url+"landing/authenticate",nameValuePairs); JSONObject jObject = new JSONObject(content); JSONObject respObject = jObject.getJSONObject("response"); Boolean success=respObject.getBoolean("success"); String message=respObject.getString("message"); Boolean logged_in=respObject.getBoolean("logged_in"); if(logged_in){ user_id=respObject.getInt("user_id"); access_token=respObject.getString("access_token"); username=respObject.getString("username"); current_username=username; current_user_id=user_id; user_logged_in=true; //initFeeds(username); test(0); }else{ createDialog("Error",message); } }catch(Exception e){ } } A: You can use your apps shared preferences. The prefs can be accessed anytime using the key you set for these prefs static final String KEY_USERNAME = "username"; static final String KEY_PASSWORD = "password"; if (rememberMe) { //save username and pw to prefs SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); Editor ed = prefs.edit(); ed.putString(KEY_USERNAME, theUsername); ed.putString(KEY_PASSWORD, thePW); ed.commit(); } To access the information, like in your onCreate method: SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String username = prefs.getString(KEY_USERNAME, "Default Value if not found"); String password = prefs.getString(KEY_PASSWORD, ""); //return nothing if no pass saved
{ "language": "en", "url": "https://stackoverflow.com/questions/7549802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using multiple vertex shaders on the same program I'm trying to implements projection, using a vertex shader. Is there a way to have a separate vertex shader to handle set the gl_Position, and having another vertex shader to set the values required for the fragment shader? The problem I have it that only the main() function of the first vertex shader is called. Edit: I found a way to make it work, by combining the shader sources instead of using multiple independant shaders. I'm not sure if this is the best way to do it, but it seems to work nicely. main_shader.vsh attribute vec4 src_color; varying vec4 dst_color; // forward declaration void transform(void); void main(void) { dst_color = src_color; transform(); } transform_2d.vsh attribute vec4 position; void transform(void) { gl_Position = position; } Then use it as such: char merged[2048]; strcat(merged, main_shader_src); strcat(merged, transform_shader_src); // create and compile shader with merged as source A: in OpenGL ES, the only way is to concatenate shader sources, but in OpenGL, there are some interesting functions that allow you to do what you want: GL_ARB_shader_subroutine (part of OpenGL 4.0 core) - That does pretty much what you wanted GL_ARB_separate_shader_objects (part of OpenGL 4.1 core) - This extension allows you to use (mix) vertex and fragment shaders in different programs, so if you have one vertex shader and several fragment shaders (e.g. for different effects), then this extensions is for you. I admit this is slightly offtopic, but i think it's good to know (also, might be useful for someone).
{ "language": "en", "url": "https://stackoverflow.com/questions/7549805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android Animation for hightlight I am trying to learn how to do animation on Android. I want to use tween from my understanding via XML. I want to just highlight a text view, but I can't seem to find any simple examples that work, most seem to go for rotating. Anyone have an idea? Also once I make the animation work does it block while the animation happens? Should I thread it if I am waiting for it to finish to run another event? I haven't been able to figure this out from reading the documentation. My java threading is very rusty. Thanks A: Animations thread themselves. You won't be able to do this animation directly, because property animations are only available in Honeycomb. This animation is unnecessarily complicated because of the lack of animations. What you would have to do in order to accomplish this is to place the TextView in a FrameLayout. Create and LinearLayout with the highlight color you would like and Scale or Alpha animate that LinearLayout. If you would REALLY want to do this, I can show you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: push empty array as value of an array key I need to push a new array as the value of a parent array key. this is my array. asd[ [hey], [hi] ] i would like to return. asd[ [hey]=>[], [hi] ] i do: var asd = new Array(); asd.push(hey); asd.push(hi); asd[hey].push(new Array()); so obviously is not ok my code A: Instead of new Array(); you should just write []. You can create a nested array like this myarray = [ "hey", "hi", [ "foo" ] ] Remember that when you push things into an array, it's given a numerical index. Instead of asd[hey] write asd[0] since hey would have been inserted as the first item in the array. A: You could do something like this: function myArray(){this.push = function(key){ eval("this." + key + " = []");};} //example test = new myArray(); //create a few keys test.push('hey'); test.push('hi'); //add a value to 'hey' key test['hey'].push('hey value'); // => hey value alert( test['hey'] ); Take notice that in this example test is not an array but a myArray instance. If you already have an array an want the values to keys: function transform(ary){ result= []; for(var i=0; i< ary.length; i++){result[ary[i]] = [];} return result; } //say you have this array test = ['hey','hi']; //convert every value on a key so you have 'ary[key] = []' test = transform(test); //now you can push whatever test['hey'].push('hey value'); // => hey value alert( test['hey'] ); In this case test remains an array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Run two commands in a row after an if statement in Clojure Why does the following Clojure program throw a NullPointerException? user=> (defn x [] "Do two things if the expression is true." (if true ((println "first expr") (println "second expr")) false)) user=> (x) first expr java.lang.NullPointerException (NO_SOURCE_FILE:0) second expr This is a simplified version of my actual use case, where I want to execute maybe three statements (pull values from the DB) before returning a map - {:status 200, :body "Hello World"} inside of the branch. A: Not that it matters in your particular case, but do know the difference between (do ...) which will load each form in its own classloader, and an empty let form (let [] ...) which evaluates the whole form in a single classloader. A: It is trying to treat the result of the first println as a function to call on the second println function. You need a do. (defn x [] "Do two things if the expression is true." (if true (do (println "first expr") (println "second expr")) false)) (x) The do special form (progn in CL, begin in Scheme) executes each of its arguments in sequence and returns the result of the last one. A: If nil is ok as a return value in the else case, consider using when which has an implicit do block: (defn x [] "Do two things if the expression is true." (when true (println "first expr") (println "second expr")))
{ "language": "en", "url": "https://stackoverflow.com/questions/7549820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Comparing arrays of strings for similarity I have available to me hundreds of JSON strings. Each of these contains an array of 15-20 words sorted by some predetermined weight. This weight, if it's worth noting, is the amount of times these words are found in some chunk of text. What's the best way of finding similarity between arrays of words that are structured like this? First idea that came to my head was to create a numerical hash of all the words together and basically compare these values to determine similarity. I wasn't very successful with this, since the resulting hash values of very similar strings were not very close. After some research regarding string comparison algorithms, I come to Stackoverflow in hopes of receiving more guidance. Thanks in advance, and please let me know if you need more details of the problem. Edit 1: Clarifying what I'm trying to do: I want to determine how similar two arrays are according to the words each of these have. I would also like to take into consideration the weight each word carries in each array. For example: var array1 = [{"word":"hill","count":5},{"word":"head","count":5}]; var array2 = [{"word":"valley","count":7},{"word":"head","count":5}]; var array3 = [{"word":"head", "count": 6}, {"word": "valley", "count": 5}]; var array4 = [{"word": "valley", "count": 7}, {"word":"head", "count": 5}]; In that example, array 4 and array 2 are more similar than array 2 and array 3 because, even though both have the same words, the weight is the same for both of them in array 4 and 2. I hope that makes it a little bit easier to understand. Thanks in advance. A: I think that what you want is "cosine similarity", and you might also want to look at vector space models. If you are coding In Java, you can use the open source S-space package. (added on 31 Oct) Each element of the vector is the count of one particular string. You just need to transform your arrays of strings into such vectors. In your example, you have three words - "hill", "head", "valley". If your vector is in that order, the vectors corresponding to the arrays would be // array: #hill, #head, #valley array1: {5, 5, 0} array2: {0, 5, 7} array3: {0, 6, 5} array4: {0, 5, 7} A: Given that each array has to be compared to every other array, you are looking at a serious amount of processing along the lines of ∑(n-1) times the average number of "words" in each array. You'll need to store the score for each comparison, then make some sense of it. e.g. var array1 = [{"word":"hill","count":5},{"word":"head","count":5}]; var array2 = [{"word":"valley","count":7},{"word":"head","count":5}]; var array3 = [{"word":"head", "count": 6}, {"word": "valley", "count": 5}]; var array4 = [{"word": "valley", "count": 7}, {"word":"head", "count": 5}]; // Comparison score is summed product of matching word counts function compareThings() { var a, b, i = arguments.length, j, m, mLen, n, nLen; var word, score, result = []; if (i < 2) return; // For each array while (i--) { a = arguments[i]; j = i; // Compare with every other array while (j--) { b = arguments[j]; score = 0; // For each word in array for (m=0, mLen = b.length; m<mLen; m++) { word = b[m].word // Compare with each word in other array for (n=0, nLen=a.length; n<nLen; n++) { // Add to score if (a[n].word == word) { score += a[n].count * b[m].count; } } } // Put score in result result.push(i + '-' + j + ':' + score); } } return result; } var results = compareThings(array1, array2, array3, array4); alert('Raw results:\n' + results.join('\n')); /* Raw results: 3-2:65 3-1:74 3-0:25 2-1:65 2-0:30 1-0:25 */ results.sort(function(a, b) { a = a.split(':')[1]; b = b.split(':')[1]; return b - a; }); alert('Sorted results:\n' + results.join('\n')); /* Sorted results: 3-1:74 3-2:65 2-1:65 2-0:30 3-0:25 1-0:25 */ So 3-1 (array4 and array2) have the highest score. Fortunately the comparison need only be one way, you don't have to compare a to b and b to a. A: Here is an attempt. The algorithm is not very smart (a difference > 20 is the same as not having the same words), but could be a useful start: var wordArrays = [ [{"word":"hill","count":5},{"word":"head","count":5}] , [{"word":"valley","count":7},{"word":"head","count":5}] , [{"word":"head", "count": 6}, {"word": "valley", "count": 5}] , [{"word": "valley", "count": 7}, {"word":"head", "count": 5}] ] function getSimilarTo(index){ var src = wordArrays[index] , values if (!src) return null; // compare with other arrays weighted = wordArrays.map(function(arr, i){ var diff = 0 src.forEach(function(item){ arr.forEach(function(other){ if (other.word === item.word){ // add the absolute distance in count diff += Math.abs(item.count - other.count) } else { // mismatches diff += 20 } }) }) return { arr : JSON.stringify(arr) , index : i , diff : diff } }) return weighted.sort(function(a,b){ if (a.diff > b.diff) return 1 if (a.diff < b.diff) return -1 return 0 }) } /* getSimilarTo(3) [ { arr: '[{"word":"valley","count":7},{"word":"head","count":5}]', index: 1, diff: 100 }, { arr: '[{"word":"valley","count":7},{"word":"head","count":5}]', index: 3, diff: 100 }, { arr: '[{"word":"head","count":6},{"word":"valley","count":5}]', index: 2, diff: 103 }, { arr: '[{"word":"hill","count":5},{"word":"head","count":5}]', index: 0, diff: 150 } ] */ A: Sort the arrays by word before attempting comparison. Once this is complete, comparing two arrays will require exactly 1 pass through each array. After sorting the arrays, here is a compare algorithm (psuedo-java): int compare(array1, array2) { returnValue = 0; array1Index = 0 array2Index = 0; while (array1Index < array1.length) { if (array2Index < array2.length) { if (array1[array1Index].word == array2[array2Index].word) // words match. { returnValue += abs(array1[array1Index].count - array2[array2Index].count); ++array1Index; ++array2Index; } else // account for the unmatched array2 word. { // 100 is just a number to give xtra weight to unmatched numbers. returnValue += 100 + array2[array2Index].count; ++array2Index; } } else // array2 empty and array1 is not empty. { // 100 is just a number to give xtra weight to unmatched numbers. returnValue += 100 + array1[array1Index].count; } } // account for any extra unmatched array 2 values. while (array2Index < array2.length) { // 100 is just a number to give xtra weight to unmatched numbers. returnValue += 100 + array2[array2Index].count; } return returnValue; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Testing custom standard compliant containers I am making custom versions of the standard containers (many reasons, the main one being educational). The containers have the same interface as the standard containers. Now I want to test the containers properly. Is there perchance tests written for the standard library that can potentially be used on any standard compliant container to make sure the containers are working as they should? I am currently writing my own tests and going with some examples found on www.cplusplus.com but they are definitely not exhaustive. A: Yeah, take a look in libstdc++ and libc++. You should find something there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to make classes in NACHOS (C++) I am trying to implement a player class, so I created two files in my threads folder, player.cc and player.h player.h goes like this : #ifndef PLAYER_H #define PLAYER_H #include "utility.h" class Player() { public: //getPlayerID(); }; #endif then player.cc goes like #include "player.h" class Player() { string playerID; int timeCycle; } Then in my main.cc and threadtest.cc , I add in #include player.h and then I start to errors and it fails to compile. I am new to nachos and a little bit unfamiliar with c++, so I am confused as to how to resolve this problem. Nachos does not provide a solution through the compiler either. When I type gmake, it says two things for errors. 1. parse error before '(' in player.h (referring to Player()) 2. * [main.o] Error 1 A: Let's go through line-by-line: #ifndef PLAYER_H #define PLAYER_H #include "utility.h" So far so good, you might check if your compiler supports #pragma once, but the macro will work perfectly fine. class Player() () aren't allowed in a class name, take them off { public: //getPlayerID(); }; #endif The rest of the header file is ok. Let's look at the implementation file: #include "player.h" Perfect. Putting a class in a header is the best way to make sure you only have one definition used in your whole program. class Player() Parentheses aren't allowed, but here you have a bigger problem. You already have a class with that name. Let the header provide the class definition, the implementation file just needs to provide the non-inline member functions (and any helper code). { string playerID; int timeCycle; } Here's a complete corrected version: #if !defined(PLAYER_H) #define PLAYER_H #include <string> #include "utility.h" class Player { std::string player_id; int time_cycle; public: // this is how you make a constructor, the parenthesis belong here, not on the class name Player(std::string id, int time); std::string getPlayerId() const; }; #endif /* !defined(PLAYER_H) */ and implementation file #include "player.h" // and this is how you write a non-inline constructor Player::Player(std::string id, int time) : player_id(id) , time_cycle(time) {} std::string Player::getPlayerId() const { return player_id; } All of these problems are really basic C++ stuff, nothing to do with NachOS. A: Did you modify the Makefile.common in the root nachos directory? I think you should add some value to THREAD_H, THREAD_O and THREAD_C.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Possible design strategies for login for multi-tenant cloud application? I am working on a multi-tenant cloud application and considering using E-mail addresses/passwords for general login credentials. However, I may have the same user (same E-mail address) associated with multiple tenants based on the planned sales model for this application. For example, multiple departments in the same company might be separate tenants, or separate companies must be separate tenants. In either case the same user (with same E-mail address) might be a user of these different tenants. What are possible design strategies for handling such situation? One approach I am considering is separating creation and update of the user E-mail credentials from the tenants. In this approach a tenant could invite a user (by sending an E-mail) and the user can use the same login credentials for access to all tenants, merely switching between tenants as desired. What I have typically seen in current web applications is that the user has to have separate E-mail addresses for each tenants, which seems a burden for the user. Thanks. A: Assuming your question is about the technical design (and not the user experience), this is a pretty straight forward solution. Create the users independently from the tenants, and allow for a many to many relationship that represents the "has access to" phrase. Depending on your chosen backend, there are different manifestations of the design pattern: * *RDBMS: Create a user table, tenant table and a user_has_access_to relationship table *Directory Server (LDAP): Place the users into a single OU within the directory, and create the tenants as group objects. The users could then have the memberOf attribute set for each tenant they are able to access. The LDAP option above has the limitation of overloading the group entity. If you are comfortable enough with LDAP schema definitions, you could just as easily create a tenant object and add a hasAccessToTenant attribute to your user object. Taking this approach would allow you to use groups to represent actual user groups (as the object type was intended to be used). A more advanced design option would include the creation of a "has access to" relationship between tenants. Adding this, along with the user to tenant relationship, would open up more advanced relationship modeling. For example: a tenant with departments or divisions, allowing users with permission to the top level tenant to automatically "have access to" the divisions. A: Using the same credential across namespaces in multi-tenant applications is technically possible. For example, when a user logs in, the application can check across the namespaces and determine which all namespaces he belongs to. There is a possibility, the user may have different levels of authorizations against these namespaces. This is also implementable. The real problem is the experience the application can offer to such users. They will require a special landing page which will allow them to chose between the namespaces. The chosen namespace should be made quasi-permanent during the session, that is, until the user logs out. ( I am trying to implement this in a new application on GAE/Python27 ) Other possibilities are restricting the user to a single namespace and asking the user to use different credentials against each namespace, which seems to be the prevailing practice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Where should I put the Google Analytics asynchronous snippet Google says The asynchronous snippet should appear at the top of your page before the closing tag. And gives this: <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXX-X']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> Can I make that an external .js file, or does it have to be in the html page itself? A: The snippet can be loaded in any way. If you want to include it in an external file, knock yourself out. Google recommends putting it in the <head> to maximize the number of pageviews that get tracked, but you could just as easily load it in the <body> without trouble, or from an external JavaScript file, or even a dynamically injected JavaScript file. All that needs to happen is that the snippet needs to execute; ga.js takes care of the rest. Even if your browser caches the code itself, it will still execute ga.js (which itself may be cached), but the data it sends to Google Analytics is very heavily cache busted. There's no way your browser could cache that request, even in the strictest of proxy environments. The way your analytics data gets "sent" to Google Analytics is that ga.js, after gathering all of the analytics data from the environment, your configurations and the cookies it sets, concatenates all of those values onto a query string on a dynamic image request (requested via JavaScript and never actually injected into the DOM.) Those requests feature cache-busting parameters, as well as data that is generally unique to each request. Further, the image that is requested specifically instructs the browser to avoid caching it by setting these headers: Cache-Control:private, no-cache, no-cache=Set-Cookie, proxy-revalidate Expires:Wed, 19 Apr 2000 11:43:00 GMT Pragma:no-cache A: The snippet must be on the page itself. If the snippet is in an external JS file, the browser will cache the file and the snippet would generate hit only the first loaded page from your site. There are more delicated ways to call the snippet API from Javascript if needed - these are mainly used for track special events, like button presses, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python program treating dictionary like a string I set up a dictionary, and filled it from a file, like so: filedusers = {} # cheap way to keep track of users, not for production FILE = open(r"G:\School\CS442\users.txt", "r") filedusers = ast.literal_eval("\"{" + FILE.readline().strip() + "}\"") FILE.close() then later I did a test on it, like this: if not filedusers.get(words[0]): where words[0] is a string for a username, but I get the following error: 'str' object has no attribute 'get' but I verified already that after the FILE.close() I had a dictionary, and it had the correct values in it. Any idea what's going on? A: literal_eval takes a string, and converts it into a python object. So, the following is true... ast.literal_eval('{"a" : 1}') >> {'a' : 1} However, you are adding in some quotations that aren't needed. If your file simply contained an empty dictionary ({}), then the string you create would look like this... ast.literal_eval('"{}"') # The quotes that are here make it return the string "{}" >> '{}' So, the solution would be to change the line to... ast.literal_eval("{" + FILE.readline().strip() + "}") ...or... ast.literal_eval(FILE.readline().strip()) ..depending on your file layout. Otherwise, literal_eval sees your string as an ACTUAL string because of the quotes. A: >>> import ast >>> username = "asd: '123'" >>> filedusers = ast.literal_eval("\"{" + username + "}\"") >>> print filedusers, type(filedusers) {asd} <type 'str'> You don't have a dictionary, it just looks like one. You have a string. A: Python is dynamically typed: it does not require you to define variables as a specific type. And it lets you define variables implicitly. What you are doing is defining filedusers as a dictionary, and then redefining it as a string by assigning the result of ast.literal_eval to it. EDIT: You need to remove those quotes. ast.literal_eval('"{}"') evaluates to a string. ast.literal_eval('{}') evaluates to a dictionary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Rails where date is greater than given date query Trying to search where movies coming out have a release date greater than today's date Movie.where('release > ?', Date.today) ActiveRecord::StatementInvalid: Mysql::ParseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'release > '2011-09-25')' at line 1: SELECT `movies`.* FROM `movies` WHERE (release > '2011-09-25') A: In recent versions of rails, you can do this: User.where(created_at: 3.days.ago..Time.now) See some other examples here: https://stackoverflow.com/a/24150094 A: Ruby beginless/endless ranges can also be used as an out-of-the-box solution: Post.where(id: 1..) => Post Load (0.4ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" >= $1 [["id", 1]] Post.where(id: ..9) => Post Load (0.3ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" <= $1 [["id", 9]] Post.where(id: ...9) => Post Load (0.3ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" < $1 [["id", 9]] Note: Replace id with your date column release Replace value with Date.today A: Update Rails core team decided to revert this change for a while, in order to discuss it in more detail. See this comment and this PR for more info. I am leaving my answer only for educational purposes. new 'syntax' for comparison in Rails 6.1 (Reverted) Movie.where('release >': DateTime.now) Here is a link to PR where you can find more examples. A: Rails 3+ : Movie.where('release > ?', DateTime.now) Pre Rails 3 Movie.where(['release > ?', DateTime.now]) A: In Ruby 2.7, you can try this: License.where(expiration: Time.zone.today..) SELECT "licenses".* FROM "licenses" WHERE "licenses"."expiration" >= '2021-07-06 15:12:05'
{ "language": "en", "url": "https://stackoverflow.com/questions/7549851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "82" }
Q: Why does a process started in a DLL file work when tested using console application, but not when called by another DLL file? Last week I posted the question How can I obtain console application output when running it as a process in a C# DLL file? as I was trying to find out the cause of a problem I was having. However, I have not been able to find the reason I was getting an error, so I thought I would ask a follow up that is directly about the problem I am having. I am working on method in a DLL file and I have to start a process in it. The code used to do this is: ProcessStartInfo psi = new ProcessStartInfo(); psi.UseShellExecute = false; psi.ErrorDialog = false; psi.RedirectStandardError = true; psi.RedirectStandardOutput = true; psi.RedirectStandardInput = true; psi.CreateNoWindow = true; psi.FileName = @"C:\Program Files\OpenMS-1.6\XTandemAdapter.exe"; psi.Arguments = @"-ini C:\XTandemAdapter.ini"; Process getIDs = new Process(); getIDs.StartInfo = psi; getIDs.Start(); StreamWriter inputWriter = getIDs.StandardInput; StreamReader outputReader = getIDs.StandardOutput; StreamReader errorReader = getIDs.StandardError; getIDs.WaitForExit(); System.Diagnostics.EventLog.WriteEntry("FMANWiff", "ID output: " + outputReader.ReadToEnd()); System.Diagnostics.EventLog.WriteEntry("FMANWiff", "ID error: " + errorReader.ReadToEnd()); The application XTandemAdapter.exe is normally run as a console application and the FileName and Arguments are meant to reproduce this format: XtandemAdapter.exe -ini XTandemAdapter.ini I have a console test application that calls my method in this DLL file. When I use this I am able to see the results of the redirect of standoutput and I can see that the process executed successfully (the executable that is called also produces an XML file as output and I can see that this was created). However, the normal mode of operation has a application call a method in a DLL which in turn ends up calling mine. When I run it this way I can see that the process was created by looking in the task manager, but it quickly exits and there is no output to the eventlog and no output file is created by the executable that was run. Why would it run properly in one case, but not in another? Is something done differently when called via console application vs. being called by a method in a DLL file? I noticed that the Exitcode returned by the process is Exitcode: -529697949 so I guess something is going wrong within the process. I will take a look at the code for xtandemadapter and try to figure out where this is coming from. When I run it from the console application it returns 0. When I added the debugger break statement, I ended up stepping through the method and watched the value of the process objects, both when using the console test application and the real world use. I found differences, but I am not sure what to make of them. Working console test application: - getIDs {System.Diagnostics.Process (XTandemAdapter)} System.Diagnostics.Process + base {System.Diagnostics.Process (XTandemAdapter)} System.ComponentModel.Component {System.Diagnostics.Process} BasePriority 8 int EnableRaisingEvents false bool ExitCode 9 int + ExitTime {10/4/2011 1:21:33 AM} System.DateTime + Handle 1036 System.IntPtr HandleCount 53 int HasExited true bool Id 2732 int MachineName "." string + MainModule 'getIDs.MainModule' threw an exception of type 'System.ComponentModel.Win32Exception' System.Diagnostics.ProcessModule {System.ComponentModel.Win32Exception} + MainWindowHandle 0 System.IntPtr MainWindowTitle "" string + MaxWorkingSet 'getIDs.MaxWorkingSet' threw an exception of type 'System.InvalidOperationException' System.IntPtr {System.InvalidOperationException} + MinWorkingSet 'getIDs.MinWorkingSet' threw an exception of type 'System.InvalidOperationException' System.IntPtr {System.InvalidOperationException} + Modules 'getIDs.Modules' threw an exception of type 'System.ComponentModel.Win32Exception' System.Diagnostics.ProcessModuleCollection {System.ComponentModel.Win32Exception} NonpagedSystemMemorySize 3240 int NonpagedSystemMemorySize64 3240 long PagedMemorySize 3010560 int PagedMemorySize64 3010560 long PagedSystemMemorySize 120196 int PagedSystemMemorySize64 120196 long PeakPagedMemorySize 3010560 int PeakPagedMemorySize64 3010560 long PeakVirtualMemorySize 137424896 int PeakVirtualMemorySize64 137424896 long PeakWorkingSet 9064448 int PeakWorkingSet64 9064448 long + PriorityBoostEnabled 'getIDs.PriorityBoostEnabled' threw an exception of type 'System.InvalidOperationException' bool {System.InvalidOperationException} + PriorityClass 'getIDs.PriorityClass' threw an exception of type 'System.InvalidOperationException' System.Diagnostics.ProcessPriorityClass {System.InvalidOperationException} PrivateMemorySize 3010560 int PrivateMemorySize64 3010560 long + PrivilegedProcessorTime {00:00:00.0937500} System.TimeSpan ProcessName "XTandemAdapter" string + ProcessorAffinity 'getIDs.ProcessorAffinity' threw an exception of type 'System.InvalidOperationException' System.IntPtr {System.InvalidOperationException} Responding true bool SessionId 0 int + StandardError {System.IO.StreamReader} System.IO.StreamReader + StandardInput {System.IO.StreamWriter} System.IO.StreamWriter + StandardOutput {System.IO.StreamReader} System.IO.StreamReader + StartInfo {System.Diagnostics.ProcessStartInfo} System.Diagnostics.ProcessStartInfo + StartTime {10/4/2011 1:21:32 AM} System.DateTime SynchronizingObject null System.ComponentModel.ISynchronizeInvoke + Threads {System.Diagnostics.ProcessThreadCollection} System.Diagnostics.ProcessThreadCollection + TotalProcessorTime {00:00:00.8125000} System.TimeSpan + UserProcessorTime {00:00:00.7187500} System.TimeSpan VirtualMemorySize 132001792 int VirtualMemorySize64 132001792 long WorkingSet 9064448 int WorkingSet64 9064448 long + Static members + Non-Public members When I call the dll as I expect to and when it does not work: - getIDs {System.Diagnostics.Process} System.Diagnostics.Process + base {System.Diagnostics.Process} System.ComponentModel.Component {System.Diagnostics.Process} + BasePriority 'getIDs.BasePriority' threw an exception of type 'System.InvalidOperationException' int {System.InvalidOperationException} EnableRaisingEvents false bool ExitCode -529697949 int + ExitTime {10/4/2011 1:03:09 AM} System.DateTime + Handle 4176 System.IntPtr + HandleCount 'getIDs.HandleCount' threw an exception of type 'System.InvalidOperationException' int {System.InvalidOperationException} HasExited true bool Id 596 int MachineName "." string - MainModule 'getIDs.MainModule' threw an exception of type 'System.ComponentModel.Win32Exception' System.Diagnostics.ProcessModule {System.ComponentModel.Win32Exception} + base {"Access is denied"} System.Runtime.InteropServices.ExternalException {System.ComponentModel.Win32Exception} NativeErrorCode 5 int + Non-Public members - MainWindowHandle 'getIDs.MainWindowHandle' threw an exception of type 'System.InvalidOperationException' System.IntPtr {System.InvalidOperationException} + base {"Process has exited, so the requested information is not available."} System.SystemException {System.InvalidOperationException} + MainWindowTitle 'getIDs.MainWindowTitle' threw an exception of type 'System.InvalidOperationException' string {System.InvalidOperationException} + MaxWorkingSet 'getIDs.MaxWorkingSet' threw an exception of type 'System.InvalidOperationException' System.IntPtr {System.InvalidOperationException} + MinWorkingSet 'getIDs.MinWorkingSet' threw an exception of type 'System.InvalidOperationException' System.IntPtr {System.InvalidOperationException} + Modules 'getIDs.Modules' threw an exception of type 'System.ComponentModel.Win32Exception' System.Diagnostics.ProcessModuleCollection {System.ComponentModel.Win32Exception} + NonpagedSystemMemorySize 'getIDs.NonpagedSystemMemorySize' threw an exception of type 'System.InvalidOperationException' int {System.InvalidOperationException} + NonpagedSystemMemorySize64 'getIDs.NonpagedSystemMemorySize64' threw an exception of type 'System.InvalidOperationException' long {System.InvalidOperationException} + PagedMemorySize 'getIDs.PagedMemorySize' threw an exception of type 'System.InvalidOperationException' int {System.InvalidOperationException} + PagedMemorySize64 'getIDs.PagedMemorySize64' threw an exception of type 'System.InvalidOperationException' long {System.InvalidOperationException} + PagedSystemMemorySize 'getIDs.PagedSystemMemorySize' threw an exception of type 'System.InvalidOperationException' int {System.InvalidOperationException} + PagedSystemMemorySize64 'getIDs.PagedSystemMemorySize64' threw an exception of type 'System.InvalidOperationException' long {System.InvalidOperationException} + PeakPagedMemorySize 'getIDs.PeakPagedMemorySize' threw an exception of type 'System.InvalidOperationException' int {System.InvalidOperationException} + PeakPagedMemorySize64 'getIDs.PeakPagedMemorySize64' threw an exception of type 'System.InvalidOperationException' long {System.InvalidOperationException} + PeakVirtualMemorySize 'getIDs.PeakVirtualMemorySize' threw an exception of type 'System.InvalidOperationException' int {System.InvalidOperationException} + PeakVirtualMemorySize64 'getIDs.PeakVirtualMemorySize64' threw an exception of type 'System.InvalidOperationException' long {System.InvalidOperationException} + PeakWorkingSet 'getIDs.PeakWorkingSet' threw an exception of type 'System.InvalidOperationException' int {System.InvalidOperationException} + PeakWorkingSet64 'getIDs.PeakWorkingSet64' threw an exception of type 'System.InvalidOperationException' long {System.InvalidOperationException} + PriorityBoostEnabled 'getIDs.PriorityBoostEnabled' threw an exception of type 'System.InvalidOperationException' bool {System.InvalidOperationException} + PriorityClass 'getIDs.PriorityClass' threw an exception of type 'System.InvalidOperationException' System.Diagnostics.ProcessPriorityClass {System.InvalidOperationException} + PrivateMemorySize 'getIDs.PrivateMemorySize' threw an exception of type 'System.InvalidOperationException' int {System.InvalidOperationException} + PrivateMemorySize64 'getIDs.PrivateMemorySize64' threw an exception of type 'System.InvalidOperationException' long {System.InvalidOperationException} + PrivilegedProcessorTime {00:00:00.0468750} System.TimeSpan + ProcessName 'getIDs.ProcessName' threw an exception of type 'System.InvalidOperationException' string {System.InvalidOperationException} + ProcessorAffinity 'getIDs.ProcessorAffinity' threw an exception of type 'System.InvalidOperationException' System.IntPtr {System.InvalidOperationException} + Responding 'getIDs.Responding' threw an exception of type 'System.InvalidOperationException' bool {System.InvalidOperationException} + SessionId 'getIDs.SessionId' threw an exception of type 'System.InvalidOperationException' int {System.InvalidOperationException} + StandardError {System.IO.StreamReader} System.IO.StreamReader + StandardInput {System.IO.StreamWriter} System.IO.StreamWriter + StandardOutput {System.IO.StreamReader} System.IO.StreamReader + StartInfo {System.Diagnostics.ProcessStartInfo} System.Diagnostics.ProcessStartInfo + StartTime {10/4/2011 1:03:09 AM} System.DateTime SynchronizingObject null System.ComponentModel.ISynchronizeInvoke + Threads 'getIDs.Threads' threw an exception of type 'System.InvalidOperationException' System.Diagnostics.ProcessThreadCollection {System.InvalidOperationException} + TotalProcessorTime {00:00:00.0781250} System.TimeSpan + UserProcessorTime {00:00:00.0312500} System.TimeSpan + VirtualMemorySize 'getIDs.VirtualMemorySize' threw an exception of type 'System.InvalidOperationException' int {System.InvalidOperationException} + VirtualMemorySize64 'getIDs.VirtualMemorySize64' threw an exception of type 'System.InvalidOperationException' long {System.InvalidOperationException} + WorkingSet 'getIDs.WorkingSet' threw an exception of type 'System.InvalidOperationException' int {System.InvalidOperationException} + WorkingSet64 'getIDs.WorkingSet64' threw an exception of type 'System.InvalidOperationException' long {System.InvalidOperationException} + Static members System.Diagnostics.Process System.Diagnostics.Process + Non-Public members {System.Diagnostics.Process} System.Diagnostics.Process 'getIDs.MainModule' threw an exception of type 'System.ComponentModel.Win32Exception' Too many characters in character literal I found that I was getting this error in the system event viewer. I had not noticed it until now. "Application popup: XTandemAdapter.exe - Application Error : The application failed to initialize properly (0xe06d7363). Click on OK to terminate the application." Does this help anyone understand the problem? I should note, the executable does need to make use of a few DLL files, though according to dependency walker these are all found. A: Why you aren't getting an event logged is far more interesting though. I suggest that you put a System.Diagnostics.Debugger.Break(); in your application's first line. This will allow you to attach the debugger after it is invoked and then you can observe the behaviour. A: I would start with a "Hello, World!!" console application and debug the process stuff separately from your real application. That might help you nail down what is causing the return code (i.e., your calling code, or the console application). A: It works when run from a console application, but it fails when run from a DLL file running from a different program. To me, it sounds like a problem with security context. Your console application may be running with higher privileges than the other program.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Using a combination of SESSION Vars and COOKIE Vars in PHP Heyo, Odd question... is it possible/ ok. To use a combination of SESSION variables and COOKIE variables... in PHP? I know SESSIONS are stored server side and COOKIES client side... Is there any chance of interference? What is the best practise? Christopher A: Actually, sessions are a combination between sessions and cookies since the session ID is stored in a cookie client side. You are free to do pretty much what ever you want with both as long as you remember: * *Cookies are stored on the client computer. A savvy user has absolutely full control of the contents of a cookie, so don't make assumptions about it's content *Session variables are stored in memory on your server, so keep in mind the amount of data you hold for each visitor PHP's documentation on sessions A: You can mix them. By default, the session cookie is set to PHPSESSID that contains the unique session identifier used to associate the client to the session data on the server. As long as you don't interfere with this cookie, it is okay. A: In terms of interference it is like just any other two arrays in PHP. There are some specific issues with each you need to know, like at what phase you can assign variables to each of them etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Load String of comma-separated-values (csv) into Quickoffice or Google Doc I am writing an Android App that collects data as a String of comma-separated-values (terminating each line with '\n') and then emails me the data once a month. One of my beta-testers has informed me that he would like to be able to view the intermediate data between uploads. The natural way to do this (to my mind) would be to load the data to an "excel-like" app (such as QuickOffice or google doc's viewer). I tried writing the String out to a file and then loading it into QuickOffice. I can get QuickOffice to launch, but the file comes up blank. Also, when I look for the file on my SD card, I can't find it. My code: File root = Environment.getExternalStorageDirectory(); try { BufferedWriter out = new BufferedWriter(new FileWriter(root.toString() + "/ww.csv")); out.write(getPreferences(MODE_PRIVATE).getString("allTrips", "")); out.flush(); // Probably not necessary out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Intent i1 = new Intent(android.content.Intent.ACTION_VIEW); Uri data = Uri.fromFile(new File(root.toString() + "/ww.csv")); i1.setDataAndType(data, "application/vnd.ms-excel"); startActivity(i1); Please let me know what I'm doing wrong. I'm open to small tweaks to my code above, as well as completely different approaches that get the job done. Before you ask, I remembered to add <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> to my manifest. Also, I'm as happy to write to the Internal File System instead of the SD card (my data are small) but I couldn't get that to even open QuickOffice. An example of the data: 09/19/2011,AP2,Home,GW Parkway,12:03 PM,12:41 PM,38,Dry,Day 09/20/2011,Home,AP2,MacArthur Blvd,7:18 AM,8:32 AM,74,Rain,Day 09/20/2011,AP2,Home,Rock Creek Pkwy (Blagden),4:51 PM,5:45 PM,54,Dry,Day 09/21/2011,Home,AP2,Rte 295,6:44 AM,7:36 AM,52,Rain,Day Thanks. UPDATE (OCT 09 2011): Sometimes when writing code, you need to take a step back and rethink what you're trying to accomplish. All I want to do is reformat my interim data and make an easy-to-read table to the user can see the data in-between monthly uploads. I thought the easiest way to do this would be to load my .csv file into a spreadsheet. Nikolay's suggestion of using an outside library to ensure that my file was properly formatted might have worked, but I'm trying to keep this app as lean as possible, so I want to avoid using (and learning to use) external libraries unnecessarily. So, my end solution has been to write a slightly larger file to the SD card using html format and then opening the file as text/html rather than text/plain or application/vnd.ms-excel. That took about an hour of coding and has solved the issue nicely, so I'm going to consider the problem closed. A: First, you need to debug your code and figure out why the file doesn't get written to the SD card properly (or maybe you are just looking for it in the wrong place?). After you find it, mount the SD card, and try to open in Excel/Open/LibreOffice to make sure it's correctly formatted. You might want to use a CSV library, such as opencsv, to produce the CSV file. Handling spaces, escapes, etc., can be tricky, and QuickOffice may not tolerate malformed CSV. Google Docs is another matter altogether, you need to authenticate with the user's Google account, and use the GDocs API/client library to upload the file. A: At least part of the problem is file format. When I change "application/vnd.ms-excel" to "text/plain" I am able to open the data in a text file. This is less than ideal, because it's harder to read than if it opened in a spreadsheet. I'll keep looking for a better answer. UPDATE (OCT 09 2011): In the end, my better answer was "Use HTML table as a work-around". It turned out to be the path of least resistance. See my updated question for a longer explanation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Help with inner loop in Python method I'm having trouble understanding why an inner loop in my method isn't producing the desired behavior I'm expecting and I'm hoping someone can help me understand the problem. My method takes a series of arguments (*args) and if the argument is an integer I want to add dollar signs around the integer (eg. $5$). def t_row(*args): columns = 5 if len(args) == columns: count = 0 for value in args: if type(value) is int: value = ''.join(('$', str(value), '$')) count += 1 if count < len(args): penult_args = args[:-1] line_prefix = [''.join((str(value), " & ")) for value in penult_args] elif count == len(args): line_suffix = [''.join((str(value), " \\\\", "\n"))] count += 1 line_list = line_prefix + line_suffix line = ''.join(item for item in line_list) return(line) The above code is used like this: >>> s = q.t_row('data1', 'data2', 3, 'data4', 5) >>> print s data1 & data2 & 3 & data4 & $5$ \\ Why don't I get dollar signs around the integer 3? How can I fix my code to correct this problem? A: The problem is because in this line: line_prefix = [''.join((str(value), " & ")) for value in penult_args] You are overwriting value with the original (non-dollar-signed) value. It works for the last argument only because the above line is not called for args[-1]. Use a different variable name for your loop. (Python's scoping is only within functions and classes, for loops and if statements are not independently scoped.) A: Because on this line: line_prefix = [''.join((str(value), " & ")) for value in penult_args] you pull the values out of the original list (minus the last item), while on this line: value = ''.join(('$', str(value), '$')) You added $ but never stored the value back into the list. The 5 only gets $ because it's the last item, so you reference it directly in: line_suffix = [''.join((str(value), " \\\\", "\n"))] A better way to do all this is: def t_row(self, *args): if len(args) == self.columns: result = [] for value in args: if isinstance(value, int): result.append('$%d$' % value) else: result.append(value) return ' $ '.join(result) + r' \\' As a one-liner, it would be t_row = lambda self, *args: (' $ '.join('$%d$' % value if isinstance(value, int) else value for value in args) + r' \\' if len(args) == self.columns else None) but that's not actually a good idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to write long formatted text in a Text View with xCode I feel strange asking a question about what's probably the simplest page in my iPhone app but here it is anyway: I have a controller that a user can invoke to display the rules of the game and some acknowledgment information. I set up a Text View object filling up the whole page in Interface Builder and am wondering what's the best way of entering the text I need. I can do all of this in the m file but entering large text sections in a programming language is never fun. I can also simply overwrite the default "Lorem ipsum dolor..." text in Interface Builder but then my return characters don't seem to be taken into account when I run the app. Is there a better way to fill my Text View with my own formatted text? And how can I format my text neatly and easily (i.e. make titles in bold, underline some words, etc.)? Thanks. A: There is no way to easily display formatted text in a UITextView. The best approach for this kind of problem is to use a UIWebView and store the text as an HTML file. A: Use the NSTextStorage class to store the formatted text in your NSTextView. A: Use Core Text Core Text Tutorial for iOS: Making a Magazine App
{ "language": "en", "url": "https://stackoverflow.com/questions/7549862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change the screen orientation before layout / drawing happens? I want to set the orientation of a subactivity when it starts. The orientation has to be set in run-time and not in XML. So I put the code for it in onCreate(). I also have android:configChanges="orientation|screenSize" in the manifest for the activity. But when the activity starts, it draws the screen in the wrong orientation first, then does the change. How do I eliminate this flikering? It's kinda related to this thread: how to define the screen orientation before the activity is created? . Also, I know my activity only starts once since I am handling the config changes. Here's my code in onCreate: SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); orientation = sharedPref.getString("orientation_pref", "Auto"); setOrientation(orientation); setContentView(R.layout.grid); For some reason it changes the orientation after it loads the R.layout file. A: Simply define the orientation in your android-manifest xml <activity android:name=".MyActivity" android:screenOrientation="portrait"> If you are moving between Activities and you're get flickering due to that, add this xml attribute to your activity android:launchMode="singleTask" Try setContentView using user pref in onCreate SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); boolean portrait = prefs.getBoolean(KEY_ORIENTATION, true); if (portrait) { setContentView(R.layout.myactivity); else { setContentView(R.layout-land.myactivity); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to implement php facebook sdk into cakephp? All the guides online are self-labeled out of date, and the most popular plugin I assume is Nick Baker's which currently isn't working. So is there anything recent? Haven't found anything that really explains this after hours of searching google and tinkering with this plugin. A: You could always chuck the facebook API in /vendors and use it yourself: https://developers.facebook.com/docs/reference/php/ or checkout the latest master of Nick's github: https://github.com/webtechnick/CakePHP-Facebook-Plugin
{ "language": "en", "url": "https://stackoverflow.com/questions/7549869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Reachability code blocking main thread I'm currently working on an app that requires me to check for reachability. Owing to that, I started looking stuff up and found DDG and Apple's code. I decided to go with Apple's latest reachability code. I imported that, and as suggested in Apple's sample, I came up with the following way to register: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationHandler:) name:kReachabilityChangedNotification object:nil]; //check for local connection and start notifier client = [[Reachability reachabilityForInternetConnection] retain]; [client startNotifier]; //check for server connection and start notifier server = [[Reachability reachabilityWithHostName:SERVER_HOST_NAME] retain]; [server startNotifier]; //check for other server and start notifier otherServer = [[Reachability reachabilityWithHostName:OTHER_SERVER_HOST_NAME] retain]; [otherServer startNotifier]; What I observed when I ran the app was that this code started blocking the UI (blocking the main thread). I could not interact with other UI elements till the host name was resolved. Now I know that Apple has stated a warning about DNS resolution and making it asynchronous. My question would be, how do I go ahead and make it asynchronous? Do I spawn another thread and keep it running so as to not "release" the Reachability object? Thanks in advance for your help! :) A: Okay. Well, I found out what the problem was. >_< The code posted above does indeed work asynchronously. However, the code that I had written under notificationHandler: was making a synchronous call to a service. It was written by someone else, owing to which it took me some time to figure out that that was the source of the UI freeze. However, problem has been solved. I thought I'd write this post so as to give a closure to this question. :) Thanks again!
{ "language": "en", "url": "https://stackoverflow.com/questions/7549870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using SQL to Aggregate and Calculate Stats I have shoot 'em game where users compete against each other over the course of a week to accumulate the most points. I want to write a query that aggregates statistical data from the shots table. The tables and relationships of concern here are: * *user has many competition_periods *competition_period belongs to user *competition_period has many shots *shot belongs to competition_period In the shots table I have the following fields to work with: * *result --> string values: WON, LOST or TIED *amount_won --> integer values: e.g., -100, 0, 2000, etc. For each user, I want to return a result set with the following aggregated stats: * *won_count *lost_count *tied_count *total_shots_count (won_count + lost_count + tied_count) *total_amount_won (sum of amount_won) *avg_amount_won_per_shot (total_amount_won / total_shots_count) I've worked on this query for few hours now, but haven't made much headway. The statistical functions trip me up. A friend suggested that I try to return the results in a new virtual table called shot_records. A: Here is the basic solution, computing the statistics across all shots for a given player (you didn't specify if you want them on a per-competition-period basis or not): SELECT user, SUM(IF(result = 'WON', 1, 0)) AS won_count, SUM(IF(result = 'LOST', 1, 0)) AS lost_count, SUM(IF(result = 'TIED', 1, 0)) AS tied_count, COUNT(*) AS total_shots_count, SUM(amount_won) AS total_amount_won, (SUM(amount_won) / COUNT(*)) AS avg_amount_won_per_shot FROM user U INNER JOIN competition_periods C ON U.user_id = C.user_id INNER JOIN shots S ON C.competition_period_id = S.competition_period_id GROUP BY user Note that this includes negatives in calculating the "total won" figure (that is, the total is decreased by losses). If that's not the correct algorithm for your game, you would change SUM(Amount) to SUM(IF(Amount > 0, Amount, 0)) in both places it occurs in the query.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I fix an "ambiguous" function call? I'm working on a C++ program for class, and my compiler is complaining about an "ambiguous" function call. I suspect that this is because there are several functions defined with different parameters. How can I tell the compiler which one I want? Aside from a case-specific fix, is there a general rule, such as typecasting, which might solve these kinds of problems? Edit: In my case, I tried calling abs() inside of a cout statement, passing in two doubles. cout << "Amount is:" << abs(amountOrdered-amountPaid); Edit2: I'm including these three headers: #include <iostream> #include <fstream> #include <iomanip> using namespace std; Edit3: I've finished the program without this code, but in the interest of following through with this question, I've reproduced the problem. The verbatim error is: Call to 'abs' is ambiguous. The compiler offers three versions of abs, each taking a different datatype as a parameter. A: The abs function included by <cstdlib> is overloaded for int and long and long long. Since you give a double as the argument, the compiler does not have an exact fit, so it tries to convert the double to a type that abs accepts, but it does not know if it should try to convert it to int, long, or long long, hence it's ambiguous. But you probably really want the abs that takes a double and returns a double. For this you need to include <cmath>. Since the double argument matches exactly, the compiler will not complain. It seems that <cstdlib> gets included automatically when you include the other headers which should not happen. The compiler should have given error: ‘abs’ was not declared in this scope or something similar. A: What's happened is that you've included <cstdlib> (indirectly, since it's included by iostream) along with using namespace std;. This header declares two functions in std with the name abs(). One takes and returns long long, and the other returns long. Plus, there's the one in the global namespace (that returns int) that comes from <stdlib.h>. To fix: well, the abs() that takes double is in <cmath>, and that will actually give you the answer you want! A: Try using fabs defined in <cmath>. It takes float, double and long double as arguments. abs is defined both in <cmath> and <cstdlib>. The difference is abs(int), abs(long) and abs(long long) are defined in <cstdlib> while other versions are defined in <cmath>. A: Not sure why this isn't calling the int version of abs but you could try type casting the expression (amountOrdered - amountPaid) as int i.e. cout <<"Amount is: "<< abs( (int)(amountOrdered - amountPaint) );
{ "language": "en", "url": "https://stackoverflow.com/questions/7549874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Java - Read from socket? SO I just tried to read text from a socket, and I did the following: import java.io.*; import java.net.*; public class apples{ public static void main(String args[]) throws IOException{ Socket client = null; PrintWriter output = null; BufferedReader in = null; try { client = new Socket("127.0.0.1", 2235); output = new PrintWriter(client.getOutputStream(), false); in = new BufferedReader(new InputStreamReader(client.getInputStream())); while (true) { System.out.println("Line: " + client.getOutputStream()); } } catch (IOException e) { System.out.println(e); } output.close(); in.close(); client.close(); } } This prints out weird numbers and stuff like: java.net.SocketOutputStream@316f673e I'm not really sure of all the Java functions and things, so how would I make the output print out as text? A: look at: while (true) { System.out.println("Line: " + client.getOutputStream()); } getOutputSteam() returns an object that represents a stream. you can use this object to send data through the stream. here's an example: BufferedOutputStream out = new BufferedOutputStream(this._socket.getOutputStream()); out.write("hello"); out.flush(); this will send the message "hello" through the socket to read the data, you will use the inputstream instead let me just point out - this is a client that you are creating. You also need to create a server. Use java's ServerSocket class for creating a server EDIT: you want to write a client/server application in java. you need to implement 2 processes: a client and a server. the server will listen on some port (using ServerSocket). the client will connect to that port, and send a message. first object you need to understand is ServerSocket. Server code: ServerSocket s = new ServerSocket(61616); // this will open port 61616 for listening Socket incomingSocket = s.accept(); // this will accept new connections s.accept method is blocking - it waits for incoming connections, and goes to the next line only after a connection has been accepted. it creates a Socket object. for this socket object you will set up an input stream and output stream (to send/receive data). on the client: Socket s = new Socket(serverIp, serverPort); this will open a socket to the server. ip in your case will be "127.0.0.1" or "localhost" (local machine), and port will be 61616. you will again, set up input/output stream, to send/receive messages if you are connecting to a server that already exists, you only need to implement the client of course you can find many examples online A: You aren't reading anything with this code: while (true) { System.out.println("Line: " + client.getOutputStream()); } should be: String line; while ((line = in.readLine()) != null) { System.out.println("Line: " + line); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to distribute directories? Let us say I have a list of directories: archive_1 archive_2 archive_a ... Is there a simple way to distribute these directories into a specified number of directories? For instance something like: distribute -t10 archive_* should produce 10 directories: sub_1, sub_2, ... sub_10 and contain total number of archive_* directories/10 in each. Something like how split works but for directories instead of files. Any suggestions? A: I don't think there is a Unix command for this, but you can use a simple Python script like this. To distribute all files in a directory, invoke as distribute.py -c10 -p sub * #!/usr/bin/python import sys, os, shutil from optparse import OptionParser p = OptionParser() p.add_option("-c", "--count", type="int", default=10, help="Number of dirs to distribute into", metavar="NUM") p.add_option("-p", "--prefix", type="string", default="sub", help="Directory prefix", metavar="PREFIX") (options, args) = p.parse_args() for x in range(0, options.count): os.mkdir("%s_%d" % (options.prefix, x)) c = 0 for f in args: shutil.move(f, "%s_%d" % (options.prefix, c)) c += 1 c %= options.count A: #!/usr/bin/ksh dirs=$(ls ${3}) for i in dirs do cd $i for j in 1..$2 do mkdir sub_$j done cd .. done execute it this way: distribute -t 10 archive_
{ "language": "en", "url": "https://stackoverflow.com/questions/7549876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Link error while building a C++ Unit test project in VS.NET 2010 I am trying to build a very simple C++ unit test project. The setup is just so happened to be exactly the same as what this blog described. I built a static library TestLib.lib and a C++ unit test project called TestProject. Both projects are using platform toolset v100. The Testlib contains only one class. BaseClass.h #pragma once class BaseClass { public: void Method1(); }; BaseClass.cpp #include "BaseClass.h" #include <iostream> #include <list> using namespace std; void BaseClass::Method1() { list<int> dummy(0); cout << "Hello world"; } The TestProject has only one test case. #include "BaseClass.h" #include <list> . . . [TestMethod] void TestMethod1() { BaseClass b; b.Method1(); }; It looks like if I have a #include <list> after #include "BaseClass.h" (in the test.cpp) I will have the following link error. If I take out the #include <list>, I have no link error at all. TestLib.lib(BaseClass.obj) : warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/INCREMENTAL:NO' specification MSVCMRT.lib(locale0_implib.obj) : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (std.basic_string<char,std::char_traits<char>,std::allocator<char> >): (0x0200003d). MSVCMRT.lib(locale0_implib.obj) : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (std.basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >): (0x02000063). LINK : fatal error LNK1255: link failed because of metadata errors The link error will be gone if I add one more line to the test program, like this: #include "BaseClass.h" #include <list> . . . [TestMethod] void TestMethod1() { std::list<int> dummy(0); BaseClass b; b.Method1(); }; However, now, I have two link warnings. I am not sure whether they are related to the previous link errors. TestLib.lib(BaseClass.obj) : warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/INCREMENTAL:NO' specification LINK : warning LNK4098: defaultlib 'MSVCRTD' conflicts with use of other libs; use /NODEFAULTLIB:library Can anybody explain why? Do I miss something obvious here? A: Does the error only show up when compiling the Debug configuration? If so, it may be related to your C++ run-time library linkage: http://social.msdn.microsoft.com/Forums/eu/vclanguage/thread/e5a78770-4d99-40b7-951f-e4466d2744a8
{ "language": "en", "url": "https://stackoverflow.com/questions/7549878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Thunderbird "Tags" in IMAP / PHP Thunderbird allows to flag messages with predefined (or own) Tags, e.g. "To Do", "Later". (Press "1" while reading a msg to see.) These tags are replicated to the IMAP server (I verified that by using two TB clients: I saw the same tags on both clients). How can I access the tag information in PHP using the standard IMAP class (e.g.: msg has set tag "To Do")? I found an old reference http://www.wynia.org/wordpress/2007/02/alternate-imap-solution-for-php-pear-net_imap to net_imap http://pear.php.net/package/Net_IMAP, claiming the "standard" IMAP class cannot do this - but the Net_IMAP package doesn't seem to be updated for quite some time, so I am skeptical to adopt it... A: Not a perfect answer how to do that via PHP but good enough where to start: * *Server-Side Message Labels *idea how to handle via IMAP A: $messages = imap_search($imap_stream, 'To Do'); PHP.net: imap_search
{ "language": "en", "url": "https://stackoverflow.com/questions/7549879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Smoothing issue with Diamond-Square algorithm I am using the diamond-square algorithm to generate random terrain. It works fine except I get these large cone shapes either sticking out of or into the terrain. The problem seems to be that every now and then a point gets set either way too high or way too low. Here is a picture of the problem And it can be better seen when I set the smoothness really high And here is my code - private void CreateHeights() { if (cbUseLand.Checked == false) return; int Size = Convert.ToInt32(System.Math.Pow(2, int.Parse(tbDetail.Text)) + 1), SideLength = Size - 1, d = 1025 / (Size - 1), HalfSide; Heights = new Point3D[Size, Size]; float r = float.Parse(tbHeight.Text), Roughness = float.Parse(RoughnessBox.Text); //seeding all the points for (int x = 0; x < Size; x++) for (int y = 0; y < Size; y++) Heights[x, y] = Make3DPoint(x * d, 740, y * d); while (SideLength >= 2) { HalfSide = SideLength / 2; for (int x = 0; x < Size - 1; x = x + SideLength) { for (int y = 0; y < Size - 1; y = y + SideLength) { Heights[x + HalfSide, y + HalfSide].y = (Heights[x, y].y + Heights[x + SideLength, y].y + Heights[x, y + SideLength].y + Heights[x + SideLength, y + SideLength].y) / 4 - r + ((float)(random.NextDouble() * r) * 2); } } for (int x = 0; x < Size - 1; x = x + SideLength) { for (int y = 0; y < Size - 1; y = y + SideLength) { if (y != 0) Heights[x + HalfSide, y].y = (Heights[x, y].y + Heights[x + SideLength, y].y + Heights[x + HalfSide, y + HalfSide].y + Heights[x + HalfSide, y - HalfSide].y) / 4 - r + ((float)(random.NextDouble() * r) * 2); if (x != 0) Heights[x, y + HalfSide].y = (Heights[x, y].y + Heights[x, y + SideLength].y + Heights[x + HalfSide, y + HalfSide].y + Heights[x - HalfSide, y + HalfSide].y) / 4 - r + ((float)(random.NextDouble() * r) * 2); } } SideLength = SideLength / 2; r = r / Roughness; } } A: Gavin S. P. Miller gave a SIGGRAPH '86 talk about how Fournier, Fussel & Carpenter's original algorithm was fundamentally flawed. So what you're seeing is normal for any naive implementation of the Diamond Square algorithm. You will require a separate approach for smoothing, either post each Diamond-Square compound step, or as a post-process to all diamond-square iterations (or both). Miller addressed this. Weighting and box or gaussian filtering are one option; seeding the initial array to a greater degree than just the initial 4 points (i.e., replicating the resultsets of the first few steps of diamond-square either manually or using some built-in intelligence, but instead supplying unbiased values); the more initial information you give the array before increasing the detail using diamond-square, the better your results will be. The reason appears to be in how the Square step is performed. In the Diamond step, we've taken the average of the four corners of a square to produce that square's centre. Then, in the subsequent Square step, we take the average of four orthogonally-adjacent neighbours, one of which is the square's centre point we just produced. Can you see the problem? Those original corner height values are contributing too much to the subsequent diamond-square iteration, because they are contributing both through their own influence AND through the midpoint that they created. This causes the spires (extrusive and intrusive), because locally-derived points tend more strongly toward those early points... and because (typically 3) other points do as well, this creates "circular" influences around those points, as you iterate to higher depths using Diamond-Square. So these kinds of "aliasing" issues only appear when the initial state of the array is underspecified; in fact, the artifacting that occurs can be seen as a direct geometric consequence of using only 4 points to start with. You can do one of the following: * *Do local filtering -- generally expensive. *Pre-seed the initial array more thoroughly -- requires some intelligence. *Never smooth too many steps down from a given set of initial points -- which applies even if you do seed the initial array, it's all just a matter of relative depths in conjunction with your own maximum displacement parameters. A: I believe the size of the displacement r in each iteration should be proportional to the size of the current rectangle. The logic behind this is that a fractal surface is scale invariant, so the variation in height in any rectangle should be proportional to the size of that rectangle. In your code, the variation in height is proportional to r, so you should keep it proportional to the size of your current grid size. In other words: multiply r by the roughness before the loop and divide r by 2 in each iteration. So, instead of r = r / Roughness; you should write r = r / 2; A: The actual flaw in the above algorithm is an error in conceptualization and implementation. Diamond square as an algorithm has some artifacting but this is range based artifacts. So the technical max for some pixels is higher than some other pixels. Some pixels are directly given values by the randomness while others acquire their values by the diamond and squared midpoint interpolation processes. The error here is that you started from zero. And repeatedly added the value to the current value. This causes the range of diamond squared to start at zero and extend upwards. It must actually start at zero and go both up and down depending on the randomness. So the top range thing won't matter. But, if you don't realize this and naively implement everything as added to the value, rather than starting at zero and fluctuating from there, you will expose the hidden artifacts. Miller's notes were right, but the flaw is generally hidden within the noise. This implementation is shows those problems. That is NOT normal. And can be fixed a few different ways. This was one of the reasons why after I extended this algorithm to remove all the memory restrictions and size restrictions and made it infinite and deterministic1, I then still switched away from the core idea here (the problems extending it to 3d and optimizing for GPUs also played a role.2 A: Instead of just smoothening with an average, you can use a 2-D median filter to take out extremes. It is simple to implement, and usually generates the desired effect with a lot of noise.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: try & catch blocks with implement & interface I tried this tutorial : http://about-android.blogspot.com/2010/02/create-custom-dialog.html There is no "hello" debug message when doing try & catch blocks with implement & interface. Do you think that i can do the try catch block with implement & interface?? private class OnReadyListener implements MyCustomDialog.ReadyListener { @Override public void ready(String name) { try { String sentence = "hello"; Log.d(TAG, "OnReadyListener ready" + " " + sentence ); } catch (UnknownHostException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } } A: There is no semi-colon after Log.d()
{ "language": "en", "url": "https://stackoverflow.com/questions/7549884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery post inside another javascript function I have some code like: function duplicatecheck(value, colname) { var invoiceLineId = $('tr[editable="1"]').attr('id'); var invoiceLine = { InvoiceLineId: invoiceLineId, InvoiceId: invoiceId, ActivityId: value }; $.post('/Invoice/InvoiceLineExistsForThisActivity/', invoiceLine, function (data) { if(data == true) { return[ false, "An invoice line already exists with this activity"] } else { return[ true, ""]; } }); } The problem is that duplicatecheck is supposed to return a value. The value is inside the post callback function. So duplicatecheck runs and doesn't return anything because post is asynchronous and duplicatecheck finishes before the callback has even run. Is there a way to make duplicatecheck wait until the callback has finished and return what the callback returns. Am I going about this completely the wrong way and should be doing something else? A: If you use jQuery.ajax you have the power to set async to false. That being said, preferably your web application should be structured in such a way that asynchronism is possible. You should look into callbacks. If you run a function you know might take a while, provide it with a function that it will call when it's done. Useful links: Understanding callback functions in Javascript Getting a better understanding of callback functions in JavaScript A: * *I think you go the wrong way, JS is event driven, mostly *The $.POST has a sync/async flag, check here
{ "language": "en", "url": "https://stackoverflow.com/questions/7549886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't figure out how to overlap images in java So I decided to pick up programming as a hobby, and am now working on creating a slot machine with help from tutorials. However, I ran into problems with overlapping images. I used a photo editor to create a .png file of what I want to be the background with three transparent boxes for the slot animators. The code to paint the background: public class SlotMachineBackground extends JPanel { private ImageIcon image; public void paintComponent (Graphics g) { super.paintComponent (g); image = new ImageIcon ("/Users/Documents/slotmachine.png"); image.paintIcon (this, g, 0,0); } }//end class then I made slot animators: public class SlotAnimator extends JPanel implements ActionListener { private Timer animator; private ImageIcon imageArray []= new ImageIcon [22]; int currentFrame = 0; int slotNumber = 1; int box = 1; SlotMachine m = new SlotMachine (); String [] mP = m.returnTurn(); public SlotAnimator (int delay) { for (int i = 1; i < 22; i += 2) imageArray [i] = new ImageIcon ("/Users/Documents/blank.gif"); for (int i = 0; i < 21; i ++) { if (i == 0 || i == 8 || i== 12) imageArray [i] = new ImageIcon ("/Users/Documents/cherry.gif"); if ( i == 2 || i == 6 || i == 16) imageArray[i] = new ImageIcon ("/Users/Documents/1bar.gif"); if (i == 4) imageArray [i] = new ImageIcon ("/Users/Documents/seven.gif"); if (i== 10 || i == 14) imageArray[i] = new ImageIcon ("/Users/Documents/2bar.gif"); if (i == 18) imageArray[i] = new ImageIcon ("/Users/Documents/3bar.gif"); if (i==20) imageArray [i] = new ImageIcon ("/Users/Documents/jackpot.gif"); } animator = new Timer (delay, this); animator.start(); } public void paintComponent (Graphics g) { super.paintComponent (g); if (currentFrame >= imageArray.length) { animator.stop(); ImageIcon im = m.findPicture (mP[box]); box++; im.paintIcon (this, g, 0, 0); } imageArray [currentFrame].paintIcon (this, g, 0, 0); } public void actionPerformed (ActionEvent e) { repaint(); currentFrame ++; } }//end class Next, I tried to combine the two into a JFrame: public class SlotAnimatorTest { public static void main (String [] args) { JFrame frame = new JFrame (); SlotMachineBackground b = new SlotMachineBackground (); SlotAnimator a0 = new SlotAnimator (45); SlotAnimator a1 = new SlotAnimator (90); SlotAnimator a2 = new SlotAnimator (180); frame.add (b); frame.add(a0); frame.setSize (1500,1500); frame.setVisible (true); } } However, only the animator comes up. I'm stumped, as you can tell I am still an amateur. Anyways, thank you in advance for any advice!! A: It's mostly a matter of layouts, and I suggest that you read the tutorial on them: The Layout Tutorials In your situation a JLayeredPane might work well. It uses a default null layout, and so you would need to specify your component's sizes and positions if you were to use this, but you can also tell it the z-order of your components and thus be able to place the slot machine in the lowest position and things that go on top in higher positions. Again, the tutorial will help with the details: JLayeredPane Tutorial Also, you really shouldn't be reading in any files from within a paintComponent method, especially a file of an image that doesn't change -- what's the sense of re-reading an image slowing down the drawing each time you repaint the image when the image doesn't change and you can just store it in a variable in the class? So read it once in the class's constructor, and then save it in a variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: NSPredicate that calls test method to fetch results from Core Data I am not quite sure how to word this question without explaining what I am trying to do. I have a managed object context filled with (essentially) circles that have an x,y coord for the center point and a radius. I would like to construct a predicate for my core data retrieval that will find all circles that overlap with a given circle. I can write a boolean method that tests this and returns true or false, but my problem is that I don't know how to call this testing method in my predicate. in pseudo-code, I am trying to do this: NSPredicate *pred = [NSPredicate (if [testOverlapWithCenterAt:centerOfGivenObjectInContext andRadius:radiusOfGivenObjectInContext]); Perhaps NSPredicate isn't even the best way to do this. Any help would be much appreciated. A: You can use the predicateWithBlock instance method of NSPredicate. Give it a try.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting the actual type from reflection fieldInfo I'm writing a generic wrapper around a software's GUI API which has the ability to process quite a few of its own 'built-in' types but I can't figure out how to get it what it needs. For example, I'm doing this to handle strings: ("MakeTextField" and "MakeField" are pseudo-code, which take a value, display a GUI element and then return the value from the GUI for storage) public static void FieldInfoMakeField<T>(T instance, System.Reflection.FieldInfo fieldInfo) { string label = fieldInfo.Name; if (fieldInfo.FieldType == typeof(string)) { var val = (string)fieldInfo.GetValue(instance); val = MakeTextField(label, val); fieldInfo.SetValue(instance, val); return; } //else if ... more types This is what I have for the API's type where A and B are derrived from a common type, which I can also test for, but I need the derrived type: ... else if (fieldInfo.FieldType == typeof(APITypeA)) { var val = (APITypeA)fieldInfo.GetValue(instance); val = MakeField<APITypeA>(label, val); // My version, casts internally fieldInfo.SetValue(APITypeA, val); return; } else if (fieldInfo.FieldType == typeof(APITypeB)) { var val = (APITypeB)fieldInfo.GetValue(instance); val = MakeField<APITypeB>(label, val); // My version, casts internally fieldInfo.SetValue(APITypeB, val); return; } ... This all works, but I have about 10 more copy&paste code blocks for other "APITypes". If I wasn't doing this generically, I would just pass in any type derived from the API's base type and it would work, but I can't figure out how to get the fieldInfo's actual type. If I print it, it will print the name of the derived types, but I can't seem to get them out. I hope I'm stating my problem well enough. This is highly situational but seems like it should be possible. If I could just get the type that FieldType() prints, I would be gold. Otherwise I have #regions full of else if statements, which certainly isn't as generic as I would like! A: Are you able to provide the Type of the field to the FieldInfoMakeField function? public static void FieldInfoMakeField<T, V>(T instance, FieldInfo fieldInfo) { string label = fieldInfo.Name; var val = (V)fieldInfo.GetValue(instance); val = MakeField<V>(label, val); fieldInfo.SetValue(instance, val); return; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CGI PHP server any examples availble windows It not hard to write in C++ some support statements to PHP with a DLL as I need them. Is it possible for me to view a copy of a web server with its own CGI scripts made from PHP, which I can use as an example from somewhere? I'm doing this for web site security reasons as I know my site will be attacked because of jealousy reasons. Apache simply does not offer the restrictive control I need (yet it’s a good product). Does anyone know of any examples please? It would be good to stay in PHP if it’s possible or I convert it to PHP my self. I want to use the HTML post statment heavly with just a few entry pages to the site. I'm looking at googles SSL a bit can be a nice addtion. thanks in advance A: Writing your own web server in PHP is not going to improve your site's security or reliability. It's much more likely to do the opposite.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django: Custom Model Manager queries in abstract classes I am working on a django project in which I create a set of three abstract models that I will use for a variety of apps later on all of which will contain this hierarchy of three models. E.g.: class Book(models.Models): name = models.CharField(...) author = models.CharField(...) ... objects = BookManager() class Meta: abstract = True class Page(models.Models): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') chapter = models.CharField(...) ... objects = PageManager() class Meta: abstract = True class Word(models.Models): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') line = models.IntegerField(...) ... objects = WordManager() class Meta: abstract = True Besides these abstract classes, I want to provide customized Model Manager classes for each abstract class that will come in handy later on in the apps that inherit the managers class BookManager(models.Manager): def computePrice(self, user, printJob): price = 0 ... class PageManager(models.Manager): def getPagesOfBook(self, book): return self.filter(content_type=book, object_id=book.id) ... .... General question: Is this generally possible to create customized model managers for abstract classes and to use those in the models that inherit the abstract class? The reason why I am asking is because I have not been able to implement this without receiving a hole set of exceptions every time I would run queries. I also tried a different way by running the queries in the abstract view (I also create an abstract view) though same exceptions occur. If I am not mistaken, then part of the reason why this is not working is because abstract models cannot be queried. What I am asking is basically if there is a way how I can implement what I described above and if so, how that could be done. Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 1.3 Exception Type: AttributeError Exception Value: 'Options' object has no attribute '_join_cache' Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py in setup_joins, line 1267 Python Executable: /usr/bin/python Python Version: 2.7.1 A: Here is the information on custom managers and model inheritance: https://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers-and-model-inheritance General question: Is this generally possible to create customized model managers for abstract classes and to use those in the models that inherit the abstract class? Answer: Yes You are right that abstract base classes can't be queried though. I'm not exactly sure what you're doing (how Options looks, or how you're querying it) but hopefully the general information will help Try this as an example class Encyclopedia(Book): pass And then query: > Encyclopedia.objects.computePrice(me, some_print_job) A: Part if not all of the problem is that objects is not inherited between Django model classes. It's a "feature" not a bug : ).
{ "language": "en", "url": "https://stackoverflow.com/questions/7549898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using FormCollection to take and use each value for any one specific key I have a bunch of listboxes in the view, each listbox has a unique name/id. When submitted the action method receives the data accordingly that is key = listbox name and value(s) = all selected values for that listbox. How can I take all values for any one key and perform the desired operation on each value with foreach statement etc.? Looking at the available methods in formcollection they have get(index) and not get(key)... Thanks... A: This should do the trick as well public ActionResult YourAction(FormCollection oCollection) { foreach (var key in oCollection.AllKeys) { //var value = oCollection[key]; } return View(); } } or public ActionResult YourAction(FormCollection oCollection) { foreach (var key in oCollection.Keys) { //var value = oCollection[key.ToString()]; } return View(); } Not sure about this one thou: public ActionResult YourAction(FormCollection oCollection) { foreach (KeyValuePair<int, String> item in oCollection) { //item.key //item.value } return View(); } A: Ok, this gets the job done. But hoping there's more efficient means to do this? [HttpPost] public ActionResult Edit(FormCollection form) { var count = form.Count; int i = 0; while(i <= count) { var ValueCollection = form.Get(i); var KeyName = form.GetKey(i); foreach(var value in ValueCollection) { //Your logic } i++; } return View(); } A: Probably you are wrong about that there is no Get(key) method, because FormCollection is actually a class derived from NameValueCollection and both it has indexer property which accepts name(or key) and a Get method which accepts name argument. A: You can get a key value pair like the one below: public ActionResult YourAction(FormCollection oCollection) { var Item = new List<KeyValuePair<string, string>>(); foreach (var key in oCollection.AllKeys) { Item.Add(new KeyValuePair<string, string>(key, oCollection[key])); } return View(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: serve text/html file with fread() in HTTP response in c When building a HTTP response, I need to read the file I want to serve in memory. For binary files, like jpeg, I use //Setup and other headers omitted stat(file, &fileStat); int fileSize=fileState.st_size sprintf(headerBuffer, "content-length: %u\r\n\r\n", fileSize) fread(fileBuffer, fileSize, 1, filePtr); //combine headerBuffer and fileBuffer, then send to socket However I don't know how to deal with text files, like html. I'm confused about these two things: * *Is the content-length still the file size or strlen(whole file as a string)? or are they the same thing? *Can I still use fread() to load an text file or do I read it line by line with fgets()? I thought fread() was only for reading binary files, wasn't it? A: Content-length is the full length of the entity sent in the response. If you're sending a file, it's the file size (unless you're applying any content encoding like gzip, in that case it's the size of the file after encoded). The concept of "letters" doesn't enter the picture and it wouldn't make sense. HTTP is not used just to transfer text and what constitutes a letter is in itself problematic (e.g. encoding, Unicode version if applicable, ...). Finally, you can of course, use fread instead of fgets. There's no reason to send the response line-by-line.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to take video stream from user's webcam, process it with c++ program and send back I want to take video stream from user's webcam in web browser, process it with c++ program and send back. Can you give me same advise, link or code example?
{ "language": "en", "url": "https://stackoverflow.com/questions/7549917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Paged retrieval of a large ResultSet A database query returns a large ResultSet, and I would like to page the result, something like a cursor where I can choose how many results to retrieve and then in a next loop retrieve the remainders. What is the best way to do this? Thanks A: You may try javax.sql.rowset.CachedRowSet. CachedRowSet crs = CachedRowSetImpl(); crs.setPageSize(100); crs.execute(conHandle); while(crs.nextPage()) { while(crs.next()) { } } A: Do you want to display large ResultSet by multiple pages? I think may be you can use mysql syntax LIMIT.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show/Hide Div or Element I have visited a site and a feature entertained me a lot but I can't figure out how to replicate it! XD Can someone help me out? I'd like to replicate the functionality of this site's copyright notification my sites to give credit towards me and my co-worker. I will really appreciate it. Thank you. A: The site you're referring uses the jQuery library. It really is very simple. A statement such as this $("#mydiv").hide(); will hide the <div> with id "mydiv". You can also show instead of hide, and you can pass a number to the function, e.g. hide(200) to animate the action. In this case, animate the hiding of the div over 200 ms. There is also the toggle effect that hide or show the element alternatively. I recommend you read about jQuery events and selectors in the jQuery documentation. Also in the future, Googling your question before you ask it might save you some time ;-) Edit Actually the specific feature you're describing on the site you linked is handled using the HTML5 element andronikus talks about. Arguably HTML5 isn't ready for use on the web yet since there still are lots of browsers that can't handle it. In my opinion using jQuery show/hide is a better solution at this point in time. A: If you're using a browser or extension that allows you to "Inspect Element" on right-click, you can look at the code for page elements directly. Here, the page is using the new [<details>][1] tag, which is new in HTML5. It seems to look like this: <details> <summary>Always show this</summary> <p>This stuff is hidden until you click the arrow.</p> <p>Woooo!</p> </details> No Javascript/jquery to mess with, although there's probably some CSS happening too. This is a very cool new element! (Normally this would be done with a jQuery show()/hide() as described in the other answers and comments. I suspect it was added to HTML5 because it's a very common feature.) A: You can implement using jQuery slideToggle(). <div id="inner"> <div class="text"> Your Text </div> </div $(document).ready(function(){ $(".text").hide(); $("#inner").click(function(){ $(".text").slideToggle(); }); }); You can see more information here http://www.sendesignz.com/index.php/jquery/72-how-to-implement-toggle-search-box-in-jquery
{ "language": "en", "url": "https://stackoverflow.com/questions/7549923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Should I use NoSQL instead of MySQL? I'm using PHP to develop web applications. I've used MySQL as my RDMS. For many things an RDMS works, and many problems can be solved by normalization, among other things. But some situations just don't work well with an RDMS, so other solutions such as NoSQL have been devised. What isn't clear to me is what situations would NoSQL be a better fit. How do some of the different NoSQL options differ, what situations one might be better than another, and which are compatible with PHP 5.3 or above (API wise)? So I'm looking for a list of NoSQL server software I can use (such as MySQL as an RDMS) and why I would use one over the other (any Hybrids?). Also specific examples of problems that are solved by using NoSQL instead of an RDMS. Finally, I want to know if a NoSQL server would work better in this situation: A table of data where each row can have different columns/fields. One row might have 5 columns, another might have 5 completely different columns, and another might have 10. But out of all these rows, there is a single primary auto-incremented numerical ID. Millions of "rows". (Just with the above I'm assuming that NoSQL is perfect as it's a collection of objects, not rows in a table. Not sure about A.I primary key). In an RDMS you might create the columns that are most used, then use PHP's serialize/unserialize to store other columns.. But this is very inefficient and complicates things when you have to run reports on columns that exist in this "serialized array", such as a SUM on all rows of a column called "birthday_pledge" (with each row where that is used). In my situation every "column", other than the primary key, is custom and user defined. But I need to be able to run reports (sums, filters, searches) on these "columns". So if NoSQL isn't the solution, the only thing I can think of doing is creating custom tables for the user (that can get complicated though). I also want to point out that scalability (multiple database servers, redundancy, and failover) is very important. A: http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis This article compare most populars nosql database system and theire pro/con. Hope it can help. PS : In my idea what you are looking for is couchdb or mongodb but I can be wrong.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Winamp Plugin - Can I detect a redirect in minibrowser? I am developing a Winamp plugin that requires a user a to authenticate on a website that I display in the minibrowser. After the user authenticates I would then like control to be given back to my plugin. My question is: is there a way to detect when the user has been redirected in the minibrowser or can I somehow capture events from the minibrowser so that I can determine when the users authentication has been completed? If someone can point me to the correct header functions needed (from the SDK) or provide me with an example I would really appreciate it. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7549925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to save file app data folder Im working on a project and I need the program to store some of the property files and some text files. How could I save a file in the appdata folder on windows in java also what would be the linux equivalent of appdat? Thanks in advance A: Save the file to System.getenv("APPDATA") AppData Java Docs A: Consider using a sub-directory of user.home to store the data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to get touch event on CPTLayer? I'm using core plot to draw a bar chart, I was wondering is there a way I can have touch events on the bars? Thanks. A: You use a delegate object to receive notification of touch events in Core Plot plots. For bar plots, implement the -barPlot:barWasSelectedAtRecordIndex: method. The first parameter is the plot that was touched (so you can use the same delegate for more than one plot) and the second parameter is the index of the bar. Several of the example apps demonstrate usage.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What kind of algorithms are used to break down data? I have a table with a large amount of data and need to do lookups on each and break down each of the data. Here's a simplified numeric example. I have this table: 1 [1] 2 [1, 1] 4 [2, 2] now I want to break down 4. I look up and see 2+2=4. so then I look up 2 and see if breaks down into 1+1 so I know 2+1+1=4 and 1+1+1+1=4. For this problem, I should break it down(using the computed table) into 4 results(the 3 mentioned and 4 *1 =4). I am not sure but is this a graph problem? or some other type? I think I can solve this by just using a recursions that break this down, but I want to learn if there's an general accepted way and this process will deal with large amounts of data so I'll need to design it in a way that the breakdown can be distributed over multiple CPUs. Any idea what type of problem this is or the logic to solve it? A: As close as I can understand your specific example, it could be recursion, it could be a graph problem, it could be several other things, or a combination. Not every programming problem can be sorted into a single neat category, and there are generally at least a half-dozen different valid approaches to any problem. In terms of dealing with large amounts of data specifically, there are many, many different strategies that may be employed, depending on how it needs to be accessed (sequentially? randomly by offset? randomly by key or some sort of search?), how frequently it will be updated, how much data there is in relationship to the sizes of the various levels of the storage hierarchy, etc. And then there's multiple CPUs -- parallel processing -- where data synchronization becomes an important issue, in addition to the other problems. A: Your example is really too vague - you present it not as a real scenario or problem to be solved, but as an algorithm - I look up and see 2+2=4. so then I look up 2 and see if breaks down into 1+1 so I know 2+1+1=4 and 1+1+1+1=4. For this problem, I should break it down(using the computed table) into 4 results(the 3 mentioned and 4 *1 =4). You aren't asking how to do something - you're telling us what you want to do and asking the name of that activity. From your question it's clear that you know what you need to do. Your process should be * *write the program to do whatever needs to be done *if you get stuck at a particular point then research or ask a specific question *and if it doesn't work or needs improvement then ask a specific question related to the problem area
{ "language": "en", "url": "https://stackoverflow.com/questions/7549929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: when to release object that is used throughout the class? I know that the basic rule of memory management in objective-C is that for every object you do an alloc, you need to release it somewhere. Say I have the following: @interface NewPollViewController : UIViewController { NSMutableArray * myArray; } @property (nonatomic, retain) NSMutableArray * myArray; @implementation NewPollViewController @synthesize myArray = _myArray; - (void) viewDidLoad { [super viewDidLoad]; self.myArray = [[NSMutableArray alloc] init]; } Say that this self.myArray is used as a dataSource of a UITableView, so when and where should I release this? In the dealloc? I guess that the release in the dealloc corresponds to the retain that I've set in my property, so where do I release A: In your example you technically need to release it twice - once in dealloc, and once immediately after setting the property: NSMutableArray *a = [[NSMutableArray alloc] init]; self.myArray = a; [a release]; The reasoning for this is because you are specifically allocating memory in viewDidLoad, and then also increasing the retain count when setting the property. A way to avoid this is to use one of the static NSMutableArray constructors or use autorelease i.e. self.myArray = [[[NSMutableArray alloc] init] autorelease]; Alternatively, bypass the property altogether: myArray = [[NSMutableArray alloc] init]; This would avoid the extra retain generated by the property (in fact you could get rid of the property statement if it was only used locally). A: If I want to expose a NSMutableArray I would do this: @interface NewPollViewController : UIViewController { NSMutableArray * myArray; } @property (nonatomic, readonly) NSMutableArray * myArray; @implementation NewPollViewController @synthesize myArray; - (void) viewDidLoad { [super viewDidLoad]; self.myArray = [[NSMutableArray alloc] init]; } - (void) dealloc { [myArray release],myArray = nil; } Changed the property to readonly because its mutable array you don't want other classes to change this array and you are properly alloc and releasing it. A: In your case I would often release it in the viewDidUnload, and also in dealloc. I like to maintain a mirror with respect to where the memory is allocated. When its done in viewWillAppear, I release in viewWillDisappear. Now since you are saying this is used thru-out the class, I would allocate in an init method, or the awakeFromNib, and then just release it once in dealloc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MSBuild community task GacUtil silently failing for me I have an open source .NET project whose main artefact is a DLL that needs to be installed to the GAC for its primary use case. Therefore I want to install it during the AfterBuild task. I am using the GacUtil msbuild task from the MSBuild Community Extensions. It is not working. My MSBuild code, which I got from here is: <Target Name="AfterBuild"> <GacUtil Assemblies="$(TargetName)" /> </Target> The command I am using is msbuild /t:AfterBuild /verbosity:diagnostic. The error I get is: Done building target "_CheckForInvalidConfigurationAndPlatform" in project "JustAProgrammer.ADPR.csproj". Target "AfterBuild" in project "e:\src\JustAProgrammer.ADPR\JustAProgrammer.ADPR\JustAProgrammer.ADPR.csproj" (entry point): Using "GacUtil" task from assembly "C:\Program Files (x86)\MSBuild\MSBuildCommunityTasks\MSBuild.Community.Tasks.dll". Task "GacUtil" Done executing task "GacUtil" -- FAILED. Done building target "AfterBuild" in project "JustAProgrammer.ADPR.csproj" -- FAILED. Done Building Project "e:\src\JustAProgrammer.ADPR\JustAProgrammer.ADPR\JustAProgrammer.ADPR.csproj" (AfterBuild target(s)) -- FAILED. I am executing this command from a copy of cmd.exe running as administrator with gacutil.exe in its path. I used this very same command prompt to successfully install and uninstall this assembly from the GAC, and double checked that the assembly is not in the c:\windows\assembly folder. How do I figure out why GacUtil is failing? A: It looks like the path it's trying to use to get to the tool is wrong (or at least it was in my case). Set the "ToolPath" property on the "GacUtil" task to "$(FrameworkSDKDir)bin" like so: <Target Name="BeforeBuild"> <GacUtil Command="Uninstall" ToolPath="$(FrameworkSDKDir)bin" Assemblies="$(TargetName)" ContinueOnError="true"/> </Target> <Target Name="AfterBuild"> <GacUtil ToolPath="$(FrameworkSDKDir)bin" Assemblies="$(TargetPath)"/> </Target> A: Have you verified the value of $(TargetName) using the Message task? You may have to specify a property in the build.proj file: <PropertyGroup> <AssemblyPath></AssemblyPath> </PropertyGroup> <Target Name="AfterBuild"> <GacUtil Assemblies="$(AssemblyPath)" /> </Target> Then pass the property value in from the Visual Studio post-build event: msbuild /t:AfterBuild /verbosity:diagnostic /p:AssemblyPath="$(TargetPath)"
{ "language": "en", "url": "https://stackoverflow.com/questions/7549936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Could someone explain these code snippets? In the following code, could someone explain to me how the following works? /* * sniffex.c * * Sniffer example of TCP/IP packet capture using libpcap. * * Version 0.1.1 (2005-07-05) * Copyright (c) 2005 The Tcpdump Group * * This software is intended to be used as a practical example and * demonstration of the libpcap library; available at: * http://www.tcpdump.org/ * **************************************************************************** * * This software is a modification of Tim Carstens' "sniffer.c" * demonstration source code, released as follows: * * sniffer.c * Copyright (c) 2002 Tim Carstens * 2002-01-07 * Demonstration of using libpcap * timcarst -at- yahoo -dot- com * * "sniffer.c" is distributed under these terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. The name "Tim Carstens" may not be used to endorse or promote * products derived from this software without prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * <end of "sniffer.c" terms> * * This software, "sniffex.c", is a derivative work of "sniffer.c" and is * covered by the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Because this is a derivative work, you must comply with the "sniffer.c" * terms reproduced above. * 2. Redistributions of source code must retain the Tcpdump Group copyright * notice at the top of this source file, this list of conditions and the * following disclaimer. * 3. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. The names "tcpdump" or "libpcap" may not be used to endorse or promote * products derived from this software without prior written permission. * * THERE IS ABSOLUTELY NO WARRANTY FOR THIS PROGRAM. * BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY * FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN * OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES * PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED * OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS * TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE * PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, * REPAIR OR CORRECTION. * * IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING * WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR * REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, * INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING * OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED * TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY * YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER * PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGES. * <end of "sniffex.c" terms> * **************************************************************************** * * Below is an excerpt from an email from Guy Harris on the tcpdump-workers * mail list when someone asked, "How do I get the length of the TCP * payload?" Guy Harris' slightly snipped response (edited by him to * speak of the IPv4 header length and TCP data offset without referring * to bitfield structure members) is reproduced below: * * The Ethernet size is always 14 bytes. * * <snip>...</snip> * * In fact, you *MUST* assume the Ethernet header is 14 bytes, *and*, if * you're using structures, you must use structures where the members * always have the same size on all platforms, because the sizes of the * fields in Ethernet - and IP, and TCP, and... - headers are defined by * the protocol specification, not by the way a particular platform's C * compiler works.) * * The IP header size, in bytes, is the value of the IP header length, * as extracted from the "ip_vhl" field of "struct sniff_ip" with * the "IP_HL()" macro, times 4 ("times 4" because it's in units of * 4-byte words). If that value is less than 20 - i.e., if the value * extracted with "IP_HL()" is less than 5 - you have a malformed * IP datagram. * * The TCP header size, in bytes, is the value of the TCP data offset, * as extracted from the "th_offx2" field of "struct sniff_tcp" with * the "TH_OFF()" macro, times 4 (for the same reason - 4-byte words). * If that value is less than 20 - i.e., if the value extracted with * "TH_OFF()" is less than 5 - you have a malformed TCP segment. * * So, to find the IP header in an Ethernet packet, look 14 bytes after * the beginning of the packet data. To find the TCP header, look * "IP_HL(ip)*4" bytes after the beginning of the IP header. To find the * TCP payload, look "TH_OFF(tcp)*4" bytes after the beginning of the TCP * header. * * To find out how much payload there is: * * Take the IP *total* length field - "ip_len" in "struct sniff_ip" * - and, first, check whether it's less than "IP_HL(ip)*4" (after * you've checked whether "IP_HL(ip)" is >= 5). If it is, you have * a malformed IP datagram. * * Otherwise, subtract "IP_HL(ip)*4" from it; that gives you the length * of the TCP segment, including the TCP header. If that's less than * "TH_OFF(tcp)*4" (after you've checked whether "TH_OFF(tcp)" is >= 5), * you have a malformed TCP segment. * * Otherwise, subtract "TH_OFF(tcp)*4" from it; that gives you the * length of the TCP payload. * * Note that you also need to make sure that you don't go past the end * of the captured data in the packet - you might, for example, have a * 15-byte Ethernet packet that claims to contain an IP datagram, but if * it's 15 bytes, it has only one byte of Ethernet payload, which is too * small for an IP header. The length of the captured data is given in * the "caplen" field in the "struct pcap_pkthdr"; it might be less than * the length of the packet, if you're capturing with a snapshot length * other than a value >= the maximum packet size. * <end of response> * **************************************************************************** * * Example compiler command-line for GCC: * gcc -Wall -o sniffex sniffex.c -lpcap * **************************************************************************** * * Code Comments * * This section contains additional information and explanations regarding * comments in the source code. It serves as documentaion and rationale * for why the code is written as it is without hindering readability, as it * might if it were placed along with the actual code inline. References in * the code appear as footnote notation (e.g. [1]). * * 1. Ethernet headers are always exactly 14 bytes, so we define this * explicitly with "#define". Since some compilers might pad structures to a * multiple of 4 bytes - some versions of GCC for ARM may do this - * "sizeof (struct sniff_ethernet)" isn't used. * * 2. Check the link-layer type of the device that's being opened to make * sure it's Ethernet, since that's all we handle in this example. Other * link-layer types may have different length headers (see [1]). * * 3. This is the filter expression that tells libpcap which packets we're * interested in (i.e. which packets to capture). Since this source example * focuses on IP and TCP, we use the expression "ip", so we know we'll only * encounter IP packets. The capture filter syntax, along with some * examples, is documented in the tcpdump man page under "expression." * Below are a few simple examples: * * Expression Description * ---------- ----------- * ip Capture all IP packets. * tcp Capture only TCP packets. * tcp port 80 Capture only TCP packets with a port equal to 80. * ip host 10.1.2.3 Capture all IP packets to or from host 10.1.2.3. * **************************************************************************** * */ #define APP_NAME "sniffex" #define APP_DESC "Sniffer example using libpcap" #define APP_COPYRIGHT "Copyright (c) 2005 The Tcpdump Group" #define APP_DISCLAIMER "THERE IS ABSOLUTELY NO WARRANTY FOR THIS PROGRAM." #include <pcap.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> /* default snap length (maximum bytes per packet to capture) */ #define SNAP_LEN 1518 /* ethernet headers are always exactly 14 bytes [1] */ #define SIZE_ETHERNET 14 /* Ethernet addresses are 6 bytes */ #define ETHER_ADDR_LEN 6 /* Ethernet header */ struct sniff_ethernet { u_char ether_dhost[ETHER_ADDR_LEN]; /* destination host address */ u_char ether_shost[ETHER_ADDR_LEN]; /* source host address */ u_short ether_type; /* IP? ARP? RARP? etc */ }; /* IP header */ struct sniff_ip { u_char ip_vhl; /* version << 4 | header length >> 2 */ u_char ip_tos; /* type of service */ u_short ip_len; /* total length */ u_short ip_id; /* identification */ u_short ip_off; /* fragment offset field */ #define IP_RF 0x8000 /* reserved fragment flag */ #define IP_DF 0x4000 /* dont fragment flag */ #define IP_MF 0x2000 /* more fragments flag */ #define IP_OFFMASK 0x1fff /* mask for fragmenting bits */ u_char ip_ttl; /* time to live */ u_char ip_p; /* protocol */ u_short ip_sum; /* checksum */ struct in_addr ip_src,ip_dst; /* source and dest address */ }; #define IP_HL(ip) (((ip)->ip_vhl) & 0x0f) #define IP_V(ip) (((ip)->ip_vhl) >> 4) /* TCP header */ typedef u_int tcp_seq; struct sniff_tcp { u_short th_sport; /* source port */ u_short th_dport; /* destination port */ tcp_seq th_seq; /* sequence number */ tcp_seq th_ack; /* acknowledgement number */ u_char th_offx2; /* data offset, rsvd */ #define TH_OFF(th) (((th)->th_offx2 & 0xf0) >> 4) u_char th_flags; #define TH_FIN 0x01 #define TH_SYN 0x02 #define TH_RST 0x04 #define TH_PUSH 0x08 #define TH_ACK 0x10 #define TH_URG 0x20 #define TH_ECE 0x40 #define TH_CWR 0x80 #define TH_FLAGS (TH_FIN|TH_SYN|TH_RST|TH_ACK|TH_URG|TH_ECE|TH_CWR) u_short th_win; /* window */ u_short th_sum; /* checksum */ u_short th_urp; /* urgent pointer */ }; void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet); void print_payload(const u_char *payload, int len); void print_hex_ascii_line(const u_char *payload, int len, int offset); void print_app_banner(void); void print_app_usage(void); /* * app name/banner */ void print_app_banner(void) { printf("%s - %s\n", APP_NAME, APP_DESC); printf("%s\n", APP_COPYRIGHT); printf("%s\n", APP_DISCLAIMER); printf("\n"); return; } /* * print help text */ void print_app_usage(void) { printf("Usage: %s [interface]\n", APP_NAME); printf("\n"); printf("Options:\n"); printf(" interface Listen on <interface> for packets.\n"); printf("\n"); return; } /* * print data in rows of 16 bytes: offset hex ascii * * 00000 47 45 54 20 2f 20 48 54 54 50 2f 31 2e 31 0d 0a GET / HTTP/1.1.. */ void print_hex_ascii_line(const u_char *payload, int len, int offset) { int i; int gap; const u_char *ch; /* offset */ printf("%05d ", offset); /* hex */ ch = payload; for(i = 0; i < len; i++) { printf("%02x ", *ch); ch++; /* print extra space after 8th byte for visual aid */ if (i == 7) printf(" "); } /* print space to handle line less than 8 bytes */ if (len < 8) printf(" "); /* fill hex gap with spaces if not full line */ if (len < 16) { gap = 16 - len; for (i = 0; i < gap; i++) { printf(" "); } } printf(" "); /* ascii (if printable) */ ch = payload; for(i = 0; i < len; i++) { if (isprint(*ch)) printf("%c", *ch); else printf("."); ch++; } printf("\n"); return; } /* * print packet payload data (avoid printing binary data) */ void print_payload(const u_char *payload, int len) { int len_rem = len; int line_width = 16; /* number of bytes per line */ int line_len; int offset = 0; /* zero-based offset counter */ const u_char *ch = payload; if (len <= 0) return; /* data fits on one line */ if (len <= line_width) { print_hex_ascii_line(ch, len, offset); return; } /* data spans multiple lines */ for ( ;; ) { /* compute current line length */ line_len = line_width % len_rem; /* print line */ print_hex_ascii_line(ch, line_len, offset); /* compute total remaining */ len_rem = len_rem - line_len; /* shift pointer to remaining bytes to print */ ch = ch + line_len; /* add offset */ offset = offset + line_width; /* check if we have line width chars or less */ if (len_rem <= line_width) { /* print last line and get out */ print_hex_ascii_line(ch, len_rem, offset); break; } } return; } /* * dissect/print packet */ void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) { static int count = 1; /* packet counter */ /* declare pointers to packet headers */ const struct sniff_ethernet *ethernet; /* The ethernet header [1] */ const struct sniff_ip *ip; /* The IP header */ const struct sniff_tcp *tcp; /* The TCP header */ const char *payload; /* Packet payload */ int size_ip; int size_tcp; int size_payload; printf("\nPacket number %d:\n", count); count++; /* define ethernet header */ ethernet = (struct sniff_ethernet*)(packet); /* define/compute ip header offset */ ip = (struct sniff_ip*)(packet + SIZE_ETHERNET); size_ip = IP_HL(ip)*4; if (size_ip < 20) { printf(" * Invalid IP header length: %u bytes\n", size_ip); return; } /* print source and destination IP addresses */ printf(" From: %s\n", inet_ntoa(ip->ip_src)); printf(" To: %s\n", inet_ntoa(ip->ip_dst)); /* determine protocol */ switch(ip->ip_p) { case IPPROTO_TCP: printf(" Protocol: TCP\n"); break; case IPPROTO_UDP: printf(" Protocol: UDP\n"); return; case IPPROTO_ICMP: printf(" Protocol: ICMP\n"); return; case IPPROTO_IP: printf(" Protocol: IP\n"); return; default: printf(" Protocol: unknown\n"); return; } /* * OK, this packet is TCP. */ /* define/compute tcp header offset */ tcp = (struct sniff_tcp*)(packet + SIZE_ETHERNET + size_ip); size_tcp = TH_OFF(tcp)*4; if (size_tcp < 20) { printf(" * Invalid TCP header length: %u bytes\n", size_tcp); return; } printf(" Src port: %d\n", ntohs(tcp->th_sport)); printf(" Dst port: %d\n", ntohs(tcp->th_dport)); /* define/compute tcp payload (segment) offset */ payload = (u_char *)(packet + SIZE_ETHERNET + size_ip + size_tcp); /* compute tcp payload (segment) size */ size_payload = ntohs(ip->ip_len) - (size_ip + size_tcp); /* * Print payload data; it might be binary, so don't just * treat it as a string. */ if (size_payload > 0) { printf(" Payload (%d bytes):\n", size_payload); print_payload(payload, size_payload); } return; } int main(int argc, char **argv) { char *dev = NULL; /* capture device name */ char errbuf[PCAP_ERRBUF_SIZE]; /* error buffer */ pcap_t *handle; /* packet capture handle */ char filter_exp[] = "ip"; /* filter expression [3] */ struct bpf_program fp; /* compiled filter program (expression) */ bpf_u_int32 mask; /* subnet mask */ bpf_u_int32 net; /* ip */ int num_packets = 10; /* number of packets to capture */ print_app_banner(); /* check for capture device name on command-line */ if (argc == 2) { dev = argv[1]; } else if (argc > 2) { fprintf(stderr, "error: unrecognized command-line options\n\n"); print_app_usage(); exit(EXIT_FAILURE); } else { /* find a capture device if not specified on command-line */ dev = pcap_lookupdev(errbuf); if (dev == NULL) { fprintf(stderr, "Couldn't find default device: %s\n", errbuf); exit(EXIT_FAILURE); } } /* get network number and mask associated with capture device */ if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) { fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf); net = 0; mask = 0; } /* print capture info */ printf("Device: %s\n", dev); printf("Number of packets: %d\n", num_packets); printf("Filter expression: %s\n", filter_exp); /* open capture device */ handle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf); if (handle == NULL) { fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf); exit(EXIT_FAILURE); } /* make sure we're capturing on an Ethernet device [2] */ if (pcap_datalink(handle) != DLT_EN10MB) { fprintf(stderr, "%s is not an Ethernet\n", dev); exit(EXIT_FAILURE); } /* compile the filter expression */ if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) { fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle)); exit(EXIT_FAILURE); } /* apply the compiled filter */ if (pcap_setfilter(handle, &fp) == -1) { fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle)); exit(EXIT_FAILURE); } /* now we can set our callback function */ pcap_loop(handle, num_packets, got_packet, NULL); /* cleanup */ pcap_freecode(&fp); pcap_close(handle); printf("\nCapture complete.\n"); return 0; } Questions: (struct sniff_ethernet*)(packet) // <== A char casted to a struct = a struct with valid data? (struct sniff_tcp*)(packet + SIZE_ETHERNET + size_ip); // <== A char plus a couple ints casted to a struct = a struct with valid data? A: If you look in the definition of got_packet, you'll see const u_char *packet. packet is a pointer to a char (or generally, to a location in memory). In both cases, a pointer gets casted to a respective struct sniff_ethernet or struct sniff_tcp pointer, in the first case without manipulation (it accesses the packet from the start), in the second case by adding some offset, ie. the size of the ethernet header and the size of the ip packet. It accesses the tcp data in the packet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Get json value from a function that has an ajax call in it I'm trying to get json value from a function that has an ajax call in it. This is my function: function getVariables(){ $.ajax({ type: "post", url: "db/functions.php", data: "func=getvars, dataType: "json", success: function(response) { return { 'var1': response.var1, 'var2': response.var2 }; } }); } I am trying to use this in my javascript to get var1 var firstvar = getVariables().var1; when I set an alert in getVariables function it returns var1 and var2, already checked that out. So the only part which is not working properly is: var firstvar = getVariables().var1; A: There are two problems with this: Ajax calls, by default, are asynchronous. This means that the success function will not be invoked until sometime after getVariables has returned. You need to alter the settings of you ajax call so that it is synchronous. Your second problem is that the values are returned from the success function, but that does not return them from the getVariables function. You need to return the variables from function scope. Below is the same function, but with the async option set to false and with the values returned from the function's scope. function getVariables(){ var rv = undefined; $.ajax({ async : false, type: "post", url: "db/functions.php", data: "func=getvars", dataType: "json", success: function(response) { rv = { 'var1': response.var1, 'var2': response.var2 }; } }); return rv; } A: Your anonymous success function returns var1 and var2 (to nowhere), but getVariables is not returning them. It cannot in fact, because it has exited before the asynchronous JSON call is complete. Even if it was synchronous, you still aren't returning the return value of the anonymous "sub-function". EDIT: You could do something like this: function getVariables(){ var response = $.ajax({ type: "post", url: "db/functions.php", data: "func=getvars, dataType: "json", async: false }); return {'var1': response.var1, 'var2': response.var2} } See how the return statement is now in getVariables, not in a function INSIDE getVariables? So now getVariables will return the values. Although be careful of using async: false, it can lock the browser. A: That's not going to work. The AJAX call is asynchronous, and needs to wait for the http request to complete before you can use it's return values. You can make the AJAX call synchronous, but that's probably going to introduce an unnecessary delay. Typically the better option is to use the variables directly in your callback "success" function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to update secure URL's of apps created by our users? We are trying to beat the October 1 deadline. However, we need to update thousands of apps' Secure URL's for apps created by our users . In the past, we have used Admin.setAppProperties , but there is no way to update the Secure URL. A: In a comment to a bug posted about this issue, Facebook's Matthew Johnston wrote: We are actively working on this and will have this ready for you on Tuesday.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detect IE Browser and Alert only once I just grabbed this code from various sites and came out with my own to accomplish the following. I want to detect an IE Browser and would like to alert the members ONLY Once through out their session. How Do I Do this? Following is the code, which I'm using. <SCRIPT language="JavaScript"> <!-- var once_per_session=1 function get_cookie(Name) { var search = Name + "=" var returnvalue = ""; if (document.cookie.length > 0) { offset = document.cookie.indexOf(search) if (offset != -1) { // if cookie exists offset += search.length // set index of beginning of value end = document.cookie.indexOf(";", offset); // set index of end of cookie value if (end == -1) end = document.cookie.length; returnvalue=unescape(document.cookie.substring(offset, end)) } } return returnvalue; } function alertornot(){ if (get_cookie('alerted')==''){ loadalert(alert) document.cookie="alerted=yes" } } function loadalert(){ var browserName=navigator.appName; if (browserName=="Microsoft Internet Explorer") { alert("Our Web Panel best viewed in Google Chrome and Firefox 3+ You may still continue but some features may not work properly.."); } } if (once_per_session==0) loadalert() else alertornot() //--> </SCRIPT> Is this really possible to alert once by detecting the browser? Please help. A: You can use Conditional comments of IE. Browser's userAgent is not reliable. #1: <!--[if IE]> You are using IE (IE5+ and above). <![endif]--> #2: <![if !IE]> You are NOT using IE. <![endif]> Or, you can use this trick var ie = !-[1,]; alert(ie); I prefer the Conditional comments solution, you can choose either one
{ "language": "en", "url": "https://stackoverflow.com/questions/7549952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF MessageContract formatting issue I have a problem of WCF definition of MessageContact and client calling function. Scenario; Client called the service with a string type reference ID and server responds instance of type of AudioObject. AudioObject consists of Stream as MessageBodyMember and FormatObject as a MessageHeader. Following is WCF code snippet. [ServiceContract] public interface IAudioStreamService { [OperationContract] AudioObject GetAudioDataStream(StringMessage RefID); } //StringMessageContract [MessageContract] public class StringMessage { [MessageBodyMember] public string Name; } [MessageContract] public class AudioObject { Stream _audioStream; AudioFormat _audioFormat; [MessageBodyMember (Order=1)] public Stream AudioStream { get { return _audioStream; } set { _audioStream = value; } } [MessageHeader(MustUnderstand=true)] public AudioFormat AudioFormat { get { return _audioFormat; } set { _audioFormat = value; } } } [DataContract] public class AudioFormat { int _nChannels; int _nKilloBitsPerSec; int _nSamplesPerSec; [DataMember(Name="nChannels", Order=0, IsRequired=true)] public int nChannels { get { return _nChannels; } set { _nChannels = value; } } [DataMember(Name = "nKilloBitsPerSec", Order = 1, IsRequired = true)] public int nKilloBitsPerSec { get { return _nKilloBitsPerSec; } set { _nKilloBitsPerSec = value; } } [DataMember(Name = "nSamplesPerSec", Order = 2, IsRequired = true)] public int nSamplesPerSec { get { return _nSamplesPerSec; } set { _nSamplesPerSec = value; } } } The client side code is as follows, BasicHttpBinding binding = new BasicHttpBinding(); binding.MaxReceivedMessageSize = 176160768; EndpointAddress endpointAddress = new EndpointAddress("URLToService"); AudioStreamServiceClient client = new AudioStreamServiceClient(binding, endpointAddress); AudioFormat audioFormat = client.GetAudioDataStream("000", out serverStream); The above code is worked fine. But the issue is, In order to the format of the OperationContract, I expected the client code as follows, AudioObject audioObject = client.GetAudioDataStream("0000"); But my ServiceReference generated the client-stub other way round(as shown in code). Can anybody explain me the reason for this matter. A: Either write a client yourself by deriving a class from ClientBase or write an extension method with the method signature of your choice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .click() doesn't fire function? I have checkboxes that toggle on/off select option values. This part works fine. Now I want to "check" the check box after page load by default. I tried .click() that checks the checkbox but doesn't run the click code that is linked to it. Tested on firefox 6.0.2, Safari & Chrome. Any suggestion how to do so? jsfiddle example is here or below $(function(){ $selectClone = $("select[name=db2_timestamp]").clone(true); $("input[name=hideit]").click(function(){ var $this; $selectClone.find("option").attr("disabled", false); $("input[name=hideit]").each(function(){ var value = $(this).attr('value'); if($(this).is(":checked")){ $selectClone.find("option").each(function(){ $this = $(this); if($this.val().indexOf(value) != -1){ $this.attr("disabled", true); } }); } }) var $select = $("select[name=db2_timestamp]") $select.children().remove(); $selectClone.find("option:enabled").each(function(){ $select.append($(this).clone(true)); }); }); $("input[value=w]").click(); }); A: Move the hide/show bits into a function and call the function both in the click handler and in an initialize function. Fiddle here A: Um... works for me on Safari 5.0.4. I suspect that on whatever browser you are running, .click() doesn't work for checkboxes for some reason. Try running the code on change as well, maybe. A: I believe you need to call your function separately. The following should work: $(function(){ $selectClone = $("select[name=db2_timestamp]").clone(true); var $click = function(){ var $this; $selectClone.find("option").attr("disabled", false); $("input[name=hideit]").each(function(){ var value = $(this).attr('value'); if($(this).is(":checked")){ $selectClone.find("option").each(function(){ $this = $(this); if($this.val().indexOf(value) != -1){ $this.attr("disabled", true); } }); } }) var $select = $("select[name=db2_timestamp]") $select.children().remove(); $selectClone.find("option:enabled").each(function(){ $select.append($(this).clone(true)); }); }; $("input[name=hideit]").click($click); $("input[value=w]").click(); $click(); }); Here's a working jsfiddle A: Your click function is getting called, but when it runs the checkbox has not been checked yet. This can be confirmed with an alert at the top of your click function. The problem is that your click function is running before Firefox actually checks the box, so your selector that finds the ":checked" inputs does not yet include the checkbox you triggered. There are a number of ways you could fix this, either of these should get you started: 1. setting the checked property within your click function 2. only work with the checkbox that was clicked, not each checkbox A: When you call the click() method, it seems to be running the Javascript methods bound to that event before actually setting the checked property. I believe this is the root of the problem in your initial post. By setting the checked property manually first, then running the standard callback associated with a click event, we can mimic the standard behavior. I've written this code out and posted it in this Fiddle. I also cleaned up the code a bit and made it so the select box retains the selected option when other options are shown or hidden.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cocos2d Project Within UINavigationController I know there are a few questions on this already - but none pertain to my problem. I'm trying to attach part of an old Cocos2d game to my app via a UINavigationController. (the main point of this is so I can pop back to my root view controller when I want to return to the main screen of my app. I think there's a very straightforward solution to this.. *I want to attach the game to a view controller that is an element of my UINavigationController. The below code works if I simply run the game from my root view controller, but for some reason it gives me an "EXC_BAD_ACCESS Director @synchronized" error if I try to run the game from a separate view controller. Currently, I am using the following code to initiate my game from the main screen (root VC) of my app (via a button tap). MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; UIWindow *window = appDelegate.window; [[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleBlackTranslucent]; Director *director = [Director sharedDirector]; [director setPixelFormat:kRGBA8]; [director attachInView:self.view withFrame: window.frame]; [director setAnimationInterval:1.0/kFPS]; [Texture2D setDefaultAlphaPixelFormat:kTexture2DPixelFormat_RGBA8888]; Scene *scene = [[Scene node] addChild:[Game node] z:0]; [director runWithScene: scene]; Which runs the game fine. However, I need some way to get back to app's main screen once I finish the game. How do I open init this game WITHIN a view controller that's not the root view controller? [ROOT VC] --> [GAME CONTROLLER: INITIATES THE GAME] I'm very new to Cocos2d.. Any help is extremely appreciated! A: I resolved this issue quite easily by using the Cocos2d Director method: [[Director sharedDirector] end] which ends all running scenes and detaches the project from its window or view. Since I was needing the game to run full screen and was using a navigation controller, I just used the below to make it work. [appDelegate.navigationController setNavigationBarHidden:NO animated:YES]; [appDelegate.navigationController setNavigationBarHidden:YES animated:YES]; Note: You can call any Director methods from anywhere in your project by invoking the [Director sharedDirector] reference. Hope this helps others and can save some time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does ADO.net return results after the specified stored procedure call only or does it wait until all triggers are executed? I am trying to record each words used in a nvarchar(max) field in my database and each word will become a data row and it takes a lot of time when I do it in one stored procedure. SO I have created another stored procedure which adds all the words as new data rows in another table but it takes very long and I dont want the user to wait for this operation. My solution was to run the time consuming insert into query in a separate process(system.thread) but now I am thinking of triggers. If I trigger the insertion of all words in a trigger, will the user still wait for all the insert queries, including the triggers? or will the sql run the stored procedure, return the results to the user and then the triggers will run? assuming triggers are after triggers. A: That's right - stored procedure waits until the trigger is complete (to support transaction commit/rollback). If you need asynchronous behavior, you can get rid of trigger and use SQL server service broker to handle it in a asynchronous way. Check this thread for more information. A: Triggers will run sequentially along with the stored procedure and the user will have to wait for the m to complete. You either want to run the stored procedure in a separate thread as you indicated or have a separate background process run on a schedule to pull out updated records and then apply the updates to the related tables on a delay. Batching the changes like this would improve overall performance, but it means a longer delay in when the data is fully updated. Another thing to look at is if the words table is fully normalized if you're taking advantage of caching appropriately. Perhaps you can simply speed up these inserts, which solves the problem without the multithreaded complications or delays.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What does "?:" do in regex? I wanted to match anything but a string using regex. I did some Googling and found this: ^(?:(?!test).)* What do ?: and ?! do? Thanks. A: (?:) is non-capturing. That means that a match occurs as usual, but the parentheses are only for grouping (in this case to attach a * operator to the entire thing); the matched value cannot be pulled out later with $1 or \1. (?!) is a negative lookahead assertion. That means that it matches if the string in the parentheses does not exist there. See http://docs.python.org/library/re.html for some more operators. While regex varies in different languages, they're fairly similar. A: yes ... and (?!) is a "zero-width negative look-ahead assertion." according to "perldoc perlre". It means don't match the thing in the parens. Tje example from the docs is: For example "/foo(?!bar)/" matches any occurrence of "foo" that isn’t followed by "bar". So in this example foobar wouldn't match, but fooxbar would, as would foo and foofoo and so on. Oh yes, so the example you gave should match anything not containing "test". I think it's clearer to match /test/ and negate outside the regex evaluation, as in "grep -v test" A: The ?! indicates a negative look ahead. The expression containing the negative look ahead will only return a match if the expression inside the negative look ahead fails to match. This means that "(?!test)." will only return a match if "test" is not matched. The outer grouping "(?:(?!test).)" is called a passive grouping and is functionally equivalent to "((?!test).)". The difference is that with a passive grouping, no back references are created, so it's more efficient.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: elisp conditional based on hostname I have a shared .emacs file between different Linux systems. I would like to execute an expression based on the hostname of the system I'm running: (color-theme-initialize) ;; required for Ubuntu 10.10 and above. I suppose one way to avoid checking the hostname would be to factor out the system dependencies from .emacs, but it's been convenient having .emacs in version control. Alternative suggestions are welcome. A: The system-name variable might be the simplest way to achieve what you're looking for in Emacs below 25.1: (when (string= system-name "your.ubuntu.host") (color-theme-initialize)) This variable is obsolete since 25.1; use (system-name) instead So in newer Emacs use this: (when (string= (system-name) "your.ubuntu.host") (color-theme-initialize))
{ "language": "en", "url": "https://stackoverflow.com/questions/7549978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: How freeze the ScrollViewer in WPF? i have a Canvas (WPF) where i can Zoom and Pan but when i want zoom in/zoom out the Canvas holding the key Ctrl + the wheel of MiddleButtonMouse in the same time also the ScrollViewer move up or down creating an undesirable effect so i ask you if there is a way meantime i zoom in/zoom out the Canvas and can make freezable the ScrollViewer without create that undesirable effect. Thanks so much for attention Cheers A: Subscribe to the PreviewMouseWheel event of the ScrollViewer and do e.Handled = true when you don't need it to scroll. This will prevent ScrollViewer from handling MouseWheel event.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Questions about glDrawRangeElements() I am trying to render some old level data using the glDrawRangeElements() command. My vertices are set up correctly, my indices are set up correctly, but I can't seem to get it to render. I finally checked online and came across the example found here: http://www.songho.ca/opengl/gl_vertexarray.html From the example, I think I have been doing it incorrectly. Apparently the start is an index value and the ending is an index value, rather than an index into the indices array. I assumed that for example if you wanted to render 10 triangles, the start would be 0 and the ending would be 29 and the count would be 30. But I am apparently wrong? That would only be correct if the index value at 0, and 29 were in fact 0 and 29. So if the indices started with 400 and ended with 452, the call to that same array would instead be glDrawRangeElements(GL_TRIANGLES, 400, 452, 29, GL_UNSIGNED_BYTE, indices); Is that correct? Does anyone else think this is a little counter intuitive? Any other advice about vertex arrays? A: First, let's talk about glDrawElements, because the Range version is just a modification of that. The count is the number of indices to pull from the source index array to render. Each index pulled maps to a vertex. So if your count is "29", then you are trying to render 29 vertices. This will only render 27 vertices if you use GL_TRIANGLES, since each triangle requires three vertices. OpenGL will discard the extras. So if you want to render 30 indices, you put 30 in as the count. Now that we know how to use glDrawElements, let's talk about glDrawRangeElements. When normally using glDrawElements, you specify a location in the source index array to pull from. The indices and count parameters tell OpenGL where to find the indices. But the actual indices pulled from this array could be anywhere within the boundaries of the source vertex array indices. glDrawRangeElements allows you to give OpenGL a range (inclusive, because that makes sense) of vertex index values. What you are saying is that the indices it gets during this draw call will not exceed that range. This could allow the driver to perform useful optimizations. The start value should be the lowest index value that will be gotten from the index array, and the end should be the highest. It should not simply be the index of the first and last vertices.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Can AJAX content be ready by entering the url? I have created a page using some AJAX to call the embed video streaming. By every click on the image it will show the embed of that channel I use <li><a href="#" onClick="showtv('30')"> Before I use php; So if I enter the website what I use to have is the echo which in that case I use to use the else option to make the default option to one of the channel I set it up so it will auto play one of the channel right away. So come to my question in the case of php if the default in the else was one of my channel that will show on the first index page when my visitors entering the site. but with AJAX nothing unless you click on of the channel where the onClick and everytime you click on any of the AJAX items it will just have the # sign but with php I can set something like ?showtv=30 I want to know if with AJAX also can be possible the same way I'm just curious because I wish to make a twitter and facebook share button for each of the channel but if with only # on AJAX it will never link to the channel people wish to share. Thanks! /I hope that my question didn't confuse you guys, if so I can give a better explanation [if required]\ EDIT""" an example of what I have for the AJAX right now is in this page http://tv.yoursn0w.com but each of the click on the channel it will just be like http://tv.yoursn0w.com/# and can't go directly to specific channel but with the php use I can make something like http://tv.yoursn0w.com/?channel=sports and it will bring me to sport channel directly A: I feel hesitant to answer this question since I don't really get what you're asking, but I gather that you wonder if hash tags can be used the same way in JavaScript as query tags in PHP. And the answer to that is yes. In fact, that's exactly what's being answered here Retrieve specific hash tag's value from url Edit If you want to be informed when the hash part of the URL changes, check out the "hashchange" event. Described here On - window.location.hash - Change?
{ "language": "en", "url": "https://stackoverflow.com/questions/7549993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you call web service in android such that it will continue waiting for response even when activity is on background? What approach do I have to take if I need to connect to a web service and make sure it will continue downloading even after the screen has been rotated or a phone call suddenly pops up or the activity has been put on the background? I've read from some of the answers here that it is either you use AsyncTask or a Service to connect to the web service. Is it really the proper approach when connecting to web service? What is the more suggested approach and the commonly used approach? I'll appreciate it if you could also give me some explanation and sample codes regarding the approach that you will be suggesting. A: It really depends on your requirements: Service If your request is taking a long time to finish and your application is heavily depending on the result (persistent data) I would suggest to use a service because the android system can decide to kill an application which was pushed to the background and your request will be simply gone. AsyncTask For small requests with data which your application is only needing for a current state (data which can pe thrown away after real application close) I would use a AsyncTask. This could get really tricky to handle when orientation changes occur so I provide an example (note - it's a blueprint to get the idea, not a final solution). When is my Application and my AsyncTask getting killed? When you push your application to the background it will be still active. If you use antoher application and this request more memory, the android system can dicide to kill your active application to free needed resources. From this moment your activity and your task is gone. But there is still a chance for the task to finish and persit it's results in a database or on the SD card. public class YourActivity extends Activity { private MyReqeustTask mRequestTask; public void onCreate(Bundle state) { // your activity setup // get your running task after orientation change mRequestTask = (MyRequestTask) getLastNonConfigurationInstance(); if (mRequestTask != null) { mRequestTask.mActivity = new WeakReference<MyActivity>(this); processRequest(); } } // call that somewhere - decide what implementation pattern you choose // if you need more than a single request - be inventive ;-) public startRequest() { mRequestTask = new MyRequestTask(); mRequestTask.mActivity = new WeakReference<MyActivity>(this); mRequestTaks.execute(your, params); } // this is a request to process the result form your actual request // if it's still running, nothing happens public processResult() { if (mRequestTask == null || mRequest.getStatus() != Status.FINISHED) { return; } Result result = mRequest.getResult(); // update and set whatever you want here mRequestTask = null; } public Object onRetainNonConfigurationInstance() { // retain task to get it back after orientation change return mRequestTask; } private static MyRequestTaks extends AsyncTask<Params, Progress, Result> { WeakReference<MyActivity> mActivity; protected Result doInBackground(Params... params) { // do your request here // don't ever youe mActivity in here, publish updates instead! // return your final result at the end } protected void onProgressUpdate(Progress... progress) { MyActivity activity = mActivity.get(); if (activity != null) { // do whatever your want to inform activity about undates } } protected void onPostExecute(Result result) { MyActivity activity = mActivity.get(); if (activity != null) { // this will update your activity even if it is paused activity.processRequest(); } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to produce multiple rows into 1 column value or sql statement with comma seperated in T-sql ColumnName IsOrdered Seq_ID ABC 2 2 DEF 1 1 GHI 0 NULL JKL 1 4 MNO 1 3 PQR 0 5 I have a table (table1) in the database with above values stored in it. Note: - I. Is_Ordered column: 2 --> Desc; 1 --> Asc; 0 --> Default. II. Seq_ID column: Column names 'order by' sequence These values are stored in the above table by user.(i.e. on User interface). I want to produce a 'order by' clause from the multiple rows to a single statement with comma ',' seperated (one single column). eg: select * from Table1 order by DEF asc, ABC desc, MNO asc, JKL asc Here I want to write a sql statement to produce just the order by statement as above shown i.e. (order by DEF asc, ABC desc, MNO asc, JKL asc) Here you will notice that GHI column and PQR columns are not included since these two are not selected in the order by selections in the user interface. I thank you in advance who tried to understand my question and given an appropriate solution for this. A: Hope this helps DECLARE @OrderBySetting VARCHAR(max) = '' DECLARE @OrderByString VARCHAR(max) = '' DECLARE MY_CURSOR CURSOR FOR SELECT ColumnName + ' ' + case IsOrdered WHEN 1 THEN 'ASC' WHEN 2 THEN 'DESC' END + ',' FROM Table1 WHERE (IsOrdered <> 0) ORDER BY Seq_ID DESC OPEN My_Cursor Fetch NEXT FROM MY_Cursor INTO @OrderBySetting WHILE @@FETCH_STATUS = 0 BEGIN SET @OrderByString = @OrderBySetting + @OrderByString FETCH NEXT FROM MY_Cursor INTO @OrderBySetting END CLOSE MY_Cursor DEALLOCATE MY_Cursor SET @OrderByString = 'SELECT * FROM TABLE1 ORDER BY ' + SUBSTRING(@OrderByString, 1, LEN(@OrderByString)-1) A: Here you go (may need to add a CAST) SELECT 'ORDER BY ' + SUBSTRING( ( SELECT ',' + ColumnName + CASE IsOrdered WHEN 1 THEN 'ASC' WHEN 2 THEN 'DESC' END FROM MyTable WHERE IsOrdered > 0 -- why have "IsIncluded" column ? ORDER BY Seq_ID FOR XML PATH ('') ) , 2, 7999)
{ "language": "en", "url": "https://stackoverflow.com/questions/7549999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prevent floating content in two divs from overlapping? In a FAQ page I'm trying to make I have a page with this structure: <section id="container"> <div id="faq_primary"></div> <div id="faq_sidebar"></div> </section> <footer> <div id="directory"> <div id="col_a"></div> <div id="col_b"></div> <div id="col_c"></div> </div> </footer> Here is the relevant CSS: #container { width:960px; margin: 0px auto; position:relative; } #faq_primary { width:720px; margin:20px 40px 0 0; position:relative; float:left; display:inline; } #faq_sidebar { left:760px; position:absolute; } footer { width:1111px; height:250px; margin:90px auto 0px; position:relative; background-image:url(../images/footer/bg.png); color:#7d7d7d; } #directory { width:960px; margin:0px auto; padding-top:25px; font-size:13px; } #directory ul li{ padding-bottom:4px; } #dir-cola, #dir-colb, #dir-colc, #dir-cold, #dir-cole { width:174px; height:140px; float:left; } #dir-cola { width:150px; } #dir-cole { width:143px; } My page content is found in the section container, and the footer is directly below. The faq_sidebar is much shorter than faq_primary, and because the columns in the footer are all floating left, they end up to the right of the faq_primary, below the faq_sidebar. Here's a screenshot: Any advice so I can prevent the content in the footer and container from overlapping? A: Its hard to know without getting the same content as when i try thhis i can't produce the same as the screenshot. (Due to differences in content). But I'm pretty sure if you: #container { // ... *snip* overflow: hidden; } Will cause the container to include the floated children in its calculation for height. Also I would suggest you change the sidbar left: ... to right: 0 if you are trying to p[osition it on the right (alternatively float: right might be correct instead of positioning absolute). EDIT:- I noticed one of the related questions had the same answer and i might be inclined to suggest that this is a duplicate. Question: Make outer div be automatically the same height as its floating content A: You could add a clearing div here <div id="faq_sidebar"></div> <div class="clear"></div> </section> and then style it like this .clear{ clear:both; } If that doesn't do it, you may need to add it after the </section> A: clear:both; clear:left; clear:right; There are the property used to regulate and avoid to go to the image into adjust right side or left side of a previous div or image. A: If this is in a container: <section id="container"> <div id="faq_primary"></div> <div id="faq_sidebar"></div> </section> and you want them laid out inline why not style #container with display: inline. You are using absolute positioning for #faq_sidebar and that might be why the footer content is overlapping A: Remove left:760px; from #faq_sidebar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to locate error after MalformedByteSequenceException thrown by XML parser I'm getting a MalformedByteSequenceException when parsing an XML file. My app allows external customers to submit XML files. They can use any supported encoding but most specify ...encoding="UTF-8"... at the top of the file as per the examples that were provided to them. But then some will use windows-1252 to encode their data which will cause a MalformedByteSequenceException for non-ascii characters. I want to use the XML parser to identify the file encoding and decode the file so I don't want to have a preliminary step of testing the encoding or of converting the InputStream to a Reader. I feel that the XML parser should handle that step. Even though I have declared a ValidationEventHandler, it is not called when a MalformedByteSequenceException. Is there any way of getting the Unmarshaller to report the location in the file where the error occurs? Here is my Java code: InputStream input = ... JAXBContext jc = JAXBContext.newInstance(MyClass.class.getPackage().getName()); Unmarshaller unmarshaller = jc.createUnmarshaller(); SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI); Source source = new StreamSource(getClass().getResource("my.xsd").toExternalForm()); Schema schema = sf.newSchema(sources); unmarshaller.setSchema(schema); ValidationEventHandler handler = new MyValidationEventHandler(); unmarshaller.setEventHandler(handler); MyClass myClass = (MyClass) unmarshaller.unmarshal(input); and the resulting stack-trace javax.xml.bind.UnmarshalException - with linked exception: [com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 2 of 4-byte UTF-8 sequence.] at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:202) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:173) at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137) at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:184) at (my code) Caused by: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 2 of 4-byte UTF-8 sequence. at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.invalidByte(UTF8Reader.java:684) at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.read(UTF8Reader.java:470) at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(XMLEntityScanner.java:1742) at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.scanContent(XMLEntityScanner.java:916) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2788) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119) at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205) at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:200) ... 51 more A: I haven't tested but I would * *use a SAXSource (javax.xml.transform.sax.SAXSource) instead of a StreamSource *associate to the SAXSource my own implementation of org.xml.sax.ErrorHandler (SAXSource.getXMLReader().setErrorHandler) Like that I would get informed of SAXParseException in which there is the location of the parsing error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery delay error with Form Validator Plugin I have a pop-up box using the ZURB.org script (working perfectly fine). Within this reveal box I have a Form which the user can fill out certain information. This validates perfectly using the plugin - presenting the nice looking error messages aligned fine. My problem is, with this been a reveal box, when the user clicks out of the reveal box (to exit) the validation icons still appear there until the user manually clicks them. I've managed to figure out if they click the 'Exit' icon at the top of the box, it will close them by means of this code: <a class="close-reveal-modal" onclick="$('#jobForm').validationEngine('hideAll');">Exit</a> How ever, I now want to use a bit of jQuery to automatically 'Hide' these error messages after, lets say, 3 seconds. The code I have so far is: <script> $(document).ready(function() { $("#job_submit").click(function() { $('#jobForm').validationEngine('hideAll').delay(3000); }); }); </script> job_submit is the ID and name of the Submit button within the form. I went one step further with Chromes debugging tool and wrote within the console the following code: $('#jobForm').validationEngine('hideAll').delay(3000); When the form validation errors were present. This came back with the error 'Type Error'. From this point on I am unsure as to how to solve this Type Error. As always, many thanks for your help. Update The Div Classes are not named the same, for some reason, the first part of the div is the name of the form field itsself e.g jdesformError parentFormjobForm formError How ever, the last 2 sections appear to be consistent. I tried this in the console - $('.jdesformError parentFormjobForm formError').delay(1000).trigger('click'); and it passed with flying colours however, the 'error' field didn't vanish when it does when i physically click it, would it be something to do with the reveal box i'm using? A: Here's an approach: $(document).ready(function() { $("#job_submit").click(function() { // click all the errors at once $('.formError').delay(3000).trigger('click'); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7550002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Create a slideshow with ImageViewe - Android I need to know how to create a slideshow of images using a ImageView, the names of image files are loaded from an array. So far I have tried this: for(i=0;i<bL.length;i++){ imgView.setImageBitmap(bitmap); a = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, +1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f); a.setDuration(5000); imgView.startAnimation(a); } But only managed to load the last image of the array, not seeing themselves full animation. Thanks for the help. A: You should use Gallery Wigdet for this particular project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook FQL bug SELECT eid, start_time, name FROM event WHERE (eid IN (SELECT eid FROM event_member WHERE (uid = me() AND start_time < 1317006752))) This FQL query is supposed to return events that began before 1317006752 However, it returns valid events IN ADDITION to this one { "eid": 239526399426862, "start_time": 1317448800, "name": "Nick Grimshaw, The 2 Bears, S.C.U.M. & more! Friday 30th Sept, Only £4.50" } Now correct me if I'm wrong, but 1317448800 is bigger than 1317006752. You might be able to verify this by going to the event page, click on something (i.e not attend), then run the query here A: I think your issue might be the difference in timezone between the event creator and the active user. Facebook provides this notice: Note that the start_time and end_time are the times that were inputted by the event creator. Facebook Events have no concept of timezone, so, in general, you can should not treat the value returned as occurring at any particular absolute time. When an event is displayed on facebook, no timezone is specified or implied. A: Apparently start_time in event_member is used purely to speed up queries on event_member table which can return many results. Seems like it is not updated when the event's start_time is updated. Your query should be like the following to work properly, note the difference: SELECT eid, start_time, name FROM event WHERE eid IN (SELECT eid FROM event_member WHERE uid = me() AND start_time < 1317006752) AND start_time < 1317006752 I agree this is a bug though. A: I had this problem today getting upcoming events : The correct FQL should be SELECT eid,name,description,location,start_time,end_time,pic_big FROM event WHERE eid IN (SELECT eid FROM event_member WHERE start_time>=PLACE_UNIX_TIMESTAMP AND uid=PLACE_UID_HERE) ORDER BY start_time ASC EDIT Fetching the result of this query is done by : $sql = '/fql?q=SELECT+eid,name,description,location,start_time,end_time,pic_big+FROM+event+WHERE+eid+IN+(SELECT+eid+FROM+event_member+WHERE+start_time>={time}+AND+uid={id})+ORDER+BY+start_time+ASC'; $fql_query_result = file_get_contents('https://graph.facebook.com/' . $sql '&access_token={token}'); $data = json_decode($fql_query_result,true, 512, JSON_BIGINT_AS_STRING)); Important to add the JSON_BIGINT_AS_STRING option to the json_decode to prevent the eid of becoming a shortend float representation EDIT 2: As the const JSON_BIG... is only available from php5.4.X+ : if (defined('JON_BIGINT_AS_STRING')) return json_decode($fql_query_result,true, 512, JSON_BIGINT_AS_STRING); return json_decode(preg_replace('/([^\\\])":([0-9]{10,})(,|})/', '$1":"$2"$3', $fql_query_result),true); source : http://www.pixelastic.com/blog/321:fix-floating-issue-json-decode-php-5-3
{ "language": "en", "url": "https://stackoverflow.com/questions/7550006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does Objective-C have reflection? I'm doing research about Objective-C, and I'd like to know if it has the concept of reflection. None of the documents I've found so far describes reflection. A: There are runtime functions described in Runtime Reference which allows not only querying for features of a class or an instance, but also adding a method, or even creating a new class at runtime. I say this is a very dynamic kind of reflection, which was not usually available to C-based languages. Mike Ash's wrappers is an Objective-C wrapper around that. Again, it can even add methods! The base class of Cocoa, NSObject, also provide wrappers for many of the runtime functions, see NSObject protocol reference. For example [foo respondsToSelector:@selector(bar:)]; if([foo isKindOfClass:[NSString class]]){ ... } does what the method names say. You can even add a method on the fly. For example, #import <Foundation/Foundation.h> #import <objc/runtime.h> @interface Foo:NSObject { } @end @implementation Foo -(void)sayHi { NSLog(@"Hi! from %@",NSStringFromSelector(_cmd)); } +(BOOL)resolveInstanceMethod:(SEL)sel { Method method=class_getInstanceMethod(self,@selector(sayHi)); class_addMethod(self,sel,method_getImplementation(method),method_getTypeEncoding(method)); return YES; } @end int main(){ NSAutoreleasePool*pool=[[NSAutoreleasePool alloc] init]; Foo* foo=[[Foo alloc] init]; [foo aeiou]; [foo bark]; [foo mew]; [pool drain]; return 0; } This produces the output Hi! from aeiou Hi! from bark Hi! from mew What it does is as follows: * *SEL is the variable which represents the sent message (or method call, in the other terminology.) *Objective-C runtime calls resolveInstanceMethod: of a class if a message sent to an instance is not implemented in the class *So, in this case, I just copy an implementation of a predefined method called sayHi to that method's implementation. *From the method, you can use _cmd to see what was the selector used in calling the method. So, even from a single sayHi implementation, we can get different output. Some of the standard Cocoa's implementation (Key-Value-Coding, Key-Value-Observing and Core Data in particular) uses the runtime to dynamically modify the class. A: Yes, Objective-C has reflection (and abstract classes). Whether that reflection fits your needs or not is a different question. Reflection in Objective-C is surprisingly flexible for a C derived language. You can ask a class what methods it implements or you can modify and/or add methods to existing classes. You can even create new classes on the fly or change the class of any instance at any time. A typical Objective-C program does none of theses things (at least not directly) save for occasionally calling respondsToSelector: or conformsToProtocol:. While Objective-C is a fully dynamic, reflective, object oriented language, that doesn't mean that such patterns are encouraged or typically used. You might find my answers to these questions interesting: In Objective C, how to find out the return type of a method via reflection? Does Objective-C have a Standard Library? Smalltalk runtime features absent on Objective-C? And, of course, the runtime is very well documented. As is the language. Or you could read the source. A: I guess I don't know what aspect of reflection you're looking for. Are you looking for how to determine which class a given variable is? If so, check this out: Objective-C class -> string like: [NSArray className] -> @"NSArray" // Get a object's class name if ([NSStringFromClass([foo class]) compare:@"NSSomeObject"] == NSOrderedSame) {...} // Does an object have a method [foo respondsTo:@selector(method:)] Are you looking for more than just this? A: There are a flock of methods that can access various properties of a class and, presumably, "peek" and "poke" at some object internals. I've never played with them, and a little reading that I've done suggests that they're far from perfect, but they do appear to offer some ability for "reflection", similar to the Java concept.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Unlock System Preferences using GUI Applescript I am trying to unlock the System Preferences using applescript. I have managed to get my script to click the "Click the lock to make changes" part, and I was trying to get the applescript to enter the user name, but I keep getting the error error "System Events got an error: Can’t get window 1 of process \"SecurityAgent\". Invalid index." number -1719 from window 1 of process "SecurityAgent" Here is my code, can anyone give me a hand? activate application "System Preferences" tell application "System Events" set preferencesLocked to false tell process "System Preferences" delay 1 click menu item "Security & Privacy" of menu "View" of menu bar 1 delay 2.5 if title of button 4 of window 1 is "Click the lock to make changes." then set preferencesLocked to true click button "Click the lock to make changes." of window 1 end if end tell if preferencesLocked is true then delay 2.5 activate application "SecurityAgent" tell application "System Events" tell process "SecurityAgent" set value of text field 1 of scroll area 1 of group 1 of window 1 to "username" end tell end tell end if end tell Please help. Thank you. A: This can be done using the System Events' "keystroke" command to type in a password. Yosemite version (UI elements have moved around): set thePW to "MY_PASSWORD" set thePane to "Security & Privacy" activate application "System Preferences" delay 1 tell application "System Events" tell process "System Preferences" click menu item thePane of menu "View" of menu bar 1 delay 3 if title of button 1 of window 1 is "Click the lock to make changes." then click button 1 of window 1 delay 2 keystroke thePW keystroke return end if end tell end tell A: The authentication dialog is a special sort of thing in OS X; it is implemented in a secure way where it at least cannot be read by key loggers. I would be surprised if it was possible to script, both as a side effect of this and because it seems to introduce potential security holes. So you're probably out of luck, sorry.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: asp.net open source solution to "Adding a row to a specific SQL table"? I'm doing a web interface using asp.net, where user can add a row to a table in a SQL database. It's the same as add a row directly in MS access. It seems I'm reinventing the wheels. So is there any open source solutions or classes that can reduce my work? Like the validation part.. A: I am not exactly sure if that fits your needs, but I would recommend you to have a look at the Stack Exchange Data Explorer by Sam Saffron. Technically you can send any kind of SQL statements and therefore also add rows. It does not have a strict validation implemented but it uses CodeMirror for syntax highlighting. To get an idea about it you can check it out here. Hope that helps. Update If it's an "Access like" interface I would recommend you to have a look at the ASP.NET's DataGrid or the newer DataView. A: please correct me if i'm wrong. I do remember SQL server having a web management tool that allows you to modify SQL databases like an installed management component.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CodeIgniter: Accessing view variables from helper I am extending form_helper that will populate data from an array in view. E.g: //Controller - user_controller.php User_Controller extends CI_Controller{ function edit(){ $data['record'] = array('username'=>'robert','email'=>'simplerobert@google.com'); $this->load->view('edit',$data); } } //View - edit.php <?= $record['username']; ?> >> 'robert' <?= simple_input('halo'); ?> //Helper - MY_form_helper.php function simple_input($name){ var_dump($record); >> Undefined variable: record return "<input type='text'/>"; } I thought helper should load up the variables from view. Didn't really understand how it works. How can I access the view variables from helper? A: Try passing the variable in the function: //... //View - edit.php <?= $record['username']; ?> >> 'robert' <?= simple_input('halo', $record); ?> //Helper - MY_form_helper.php function simple_input($name, $record){ var_dump($record); return "<input type='text'/>"; } A: helper is function, so you need to pass the var into the function to use it. (tttony wrote about this.) I think you'd better make another view. in that case you don't need to pass the vars. //View - edit.php <?= $record['username']; ?> >> 'robert' <?= $this->load->view('simple_input'); ?> //View simple_input.php var_dump($record); echo "<input type='text'/>"; A: helper is function, so you need to pass the var into the function to use it. (tttony wrote about this.) I think you'd better make another view. in that case you don't need to pass the vars. //View - edit.php <?= $record['username']; ?> >> 'robert' <?= $this->load->view('simple_input'); ?> //View simple_input.php var_dump($record); echo "<input type='text'/>";
{ "language": "en", "url": "https://stackoverflow.com/questions/7550024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: New to PHP frameworks, how about this approach? I'm about to start a new PHP project of my own, let say is a CRM SaaS. I'm no PHP expert, I've been developing very simple PHP/MySQL websites for several years. I know CSS, jQUERY, etc. enough to figure out how to do specifically what I need at that moment. Few months a go I found out about the existence of PHP frameworks so I was thinking to check them out. I haven't got into the project yet, and I haven't use a Framework before, I will study OOP and Secure PHP before getting into it. Now, how about having my project in 2 main stages: A) For the sake of having the project up and running fast to our (local first)market, we could use the essential data managing features the Framework already offers. We'll be sticking with its own way of "showing" and "linking" stuff(the "views" I guess). After all, the Project is mainly logging in and managing good amount of data(contacts, products, blog, messages, purchasing orders, users, etc. etc.) So, our customers having the ability to manage this, is already a good situation as they don´t have used other online applications to compare it. This stage will be solid, secure and promptly delivered. B) Now, stage A) is NOT the main idea, my plan is to have it the best way possible specially in its interface, for example like how facebook manages every click and option as easy and fast as possible. So this interface and functionality improvements will be added latter, I'm talking about how the table grid reacts in certain regions or links, a dashboard with certain data, etc... and here is what I don't know how hard is going to be, but, I suppose that because the views and html is customizable, I will be able to do whatever I need to integrate jquery, ajax, css, etc etc. right? what you guys think? Or should I even consider to use a Framework at all? (Yii is on my top option) A: A framework simply provides an architecture to help you develop code faster and make it easier to maintain. A framework is not going to restrict what you can do in the general sense; it will simply give you proven tools to build an application. A: I have wrote a blog article about UI Frameworks and it seems exactly what you are looking for. If you plan to manipulate with data a lot and you don't mind the framework to do interface for you, then finding a framework which can save you from looking into a HTML / AJAX / CSS / JavaScript / JSON is very realistic. With the right choice you can focus on the code and when you come to the point when you need dash-board you can add some HTML templates. Implementing all the other base stuff is just reinventing the wheel. Learning OOP is right choice too. A: I strongly recommend a framework or constructing some framework before you start.. Build a true MVC setup, Smarty 3 makes a great view layer and lets you maximize template reuse.. anticipate tasks you'll need to commonly do - like minimize all your js and upload to a CDN and make these as automated as possible. Stay object oriented and try to approach 100% autoloaded code so you don't need to waste time remembering the paths to your files. A little forethought can save you a ton of time and lead to much butter code quality..
{ "language": "en", "url": "https://stackoverflow.com/questions/7550025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use projection to select where x.val1=1, x.val2=2, etc.? How can use projection to select with where clause specification? Perhaps something like?: List<string> Titles = iEnumerableResultSet.Select(x => x.Title = "Whatever", x=> x.Id =5).ToList(); A: In my opinion, Select is poorly named. It is suppose to remind you of SELECT from SQL. That is, you specify the values that you want for each object in collection that you are Selecting over (if you know functional programming Select is the same as map). To filter, what you want is Where: var filteredResultSet = iEnumerableResultSet .Where(x => x.Title == "Whatever" && x.Id == 5) .ToList(); How can use projection to select with where clause specification? Now, your question seems to be asking how to both filter and project. You can say var titles = iEnumerableResultSet .Where(x => x.Id == 5) // filter .Select(x => x.Title) // project .ToList(); You can think of this as being like the SQL query SELECT Title FROM SomeTable WHERE Id = 5 A: 'Select' isn't the extension method you want for filtering, you want to use 'Where' instead. In this sense, the 'Select' is for selecting parts of the input objects to pass along ('projection' creation), not for deciding which objects do and don't get filtered out. So, you want something like: var title = enumerableResultSet.Where(x => x.Title == "Whatever" || x.Id == 5).ToList();
{ "language": "en", "url": "https://stackoverflow.com/questions/7550026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySql insert binary data to db without errors I have a problem. When I do an insert like so in php: sql = "INSERT INTO mytable (id, value) VALUES ('sds83','".$EncryptedString."')"; When I run the following query it sometimes works and sometimes it doesn't. The problem is that sometimes the $EncryptedString contains characters like this: ')') which causes syntax errors. The $EncryptedString contains binary data, how can I go about this issue? A: Escape your encrypted string mysql-real-escape-string mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a. See StripSlashes A: Use PDO (or another database layer) that supports prepared statements. When you use query parameters instead of executing raw SQL, you gain speed improvements (the database only has to plan and optimize for one query) and all the data you write to it's parameters are immediately and completely isolated from the query itself. It's surprising how many people don't have this in place! Take the initiative and update your code. A: You need to escape your $EncryptedString. Depending on the type of MySQL connection object/functions you are using, it could be like this: $sql = " INSERT INTO mytable (id, value) VALUES ('sds83','" . mysql_real_escape_string($EncryptedString) . "')";
{ "language": "en", "url": "https://stackoverflow.com/questions/7550030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using LINQ to SQL to update database? When I execute the following code I don't get any error, but it doesn't update the changes on the database either. I have 5 entries in the table user, and after executing the following code there is no user with "Active" state in the database. Am I supposed to write the update statement myself or does it do it for me? What can be the problem here? var dbContext = new DataClasses1DataContext(); List<user> users = (from u in dbContext.users where u.age < 30 select u).ToList(); users[0].state = "Active"; dbContext.SubmitChanges(); EDIT: So I know what the problem is. I change the State on my object, and the update statement contains the state as a where clause. So when executing the query it can't find an item that matches - it fails on [state] = @p4. Why is it using all parameters in my update statement when I have a primary key? UPDATE [dbo].[user] SET [state] = @p5 WHERE ([id] = @p0) AND ([firstName] = @p1) AND ([lastName] = @p2) AND ([age] = @p3) AND ([state] = @p4) -- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1] -- @p1: Input NChar (Size = 10; Prec = 0; Scale = 0) [firstName ] -- @p2: Input NChar (Size = 10; Prec = 0; Scale = 0) [lastName ] -- @p3: Input Int (Size = -1; Prec = 0; Scale = 0) [25] -- @p4: Input NChar (Size = 10; Prec = 0; Scale = 0) [Active ] -- @p5: Input NChar (Size = 10; Prec = 0; Scale = 0) [Active] A: You need to change the concurrency pattern on your DBML. This website about Updating LINQ-to-SQL entities explains a bit about it. Anything you don't want to include in the WHERE clause should have their Update Check set to Never on the DBML. * *Open DBML *Select the state property on your user object *Press F4 (to see properties) *Change Update Check (the last setting in the properties) to Never *Save and try again Normally I'd turn off Update Check for all columns but you should do more reading to understand exactly how it works in case you need concurrency. A: Apparently, you don't have a primary key on the user table or you didn't specify it in your dbml file. LINQ to SQL only throws exceptions when you insert or delete a record with no primary key. It doesn't throw an exception when updating for some reason.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to efficiently utilize multiple vertex buffers? Ok, so I've had a lot of success in creating procedural planet terrain with vertex buffers. The only problem is, the planets I'm looking at are too big for the XNA HiDef profile's buffer limit. Granted, I haven't gotten into much culling yet, but I"m going to go ahead and try to nip this in the bud. I've read before that I should consider splitting up my vertex buffer regardless. So I have. My planet uses a cubemap projection so it was logical to do one buffer per cube face (this has an added benefit of streamlining manipulation of terrain, so I like it so far). My question is, how should I give the graphics device my buffers? My roommate spoke vaguely about being able to read a new buffer to the device while it renders the old one, or something like that. Is there a very efficient technique for quickly rendering multiple buffers? Or, what is the most efficient way, besides just iterating through them, setting them on the device, and drawing them?
{ "language": "en", "url": "https://stackoverflow.com/questions/7550034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can we leverage browsers' "text-search" feature in an HTML5 app? We are working on a HTML5 app feature that does exactly like the 'text search' feature in a browser: highlighting the targeted texts. We are wondering, since browsers already have this feature, can we just leverage its ability and call the feature directly from HTML5 libs? We are using sencha-touch. But we love to add in more libs if there is any lib that does this. A: I'm 99.9% sure that's not a thing, sorry. Browser searching occurs outside of the HTML/rendering world.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scoping Rails Routes to Specific Properties of a Model So I have a resource type Post, that can be associated with a resource of type Category. I have the following in my routes.rb file: resources "code", :controller => :posts, :as => :code resources "sports", :controller => :posts, :as => :sports resources "gaming", :controller => :posts, :as => :gaming resources "personal", :controller => :posts, :as => :personal So this gives me the desired effect of accessing particular categories through a friendly URL, like http://host.domain/sports, and that will collect all the posts with a category of sports. However, I'm not entirely sure how to scope those resources to be particular to individual categories. I suppose I could do something like: match ":category_name", :to => posts#index But that is problematic because it will catch everything. So I guess in summary what I'm looking for is to maintain friendly URLs (of the exact structure I've specified) for accessing posts with a particular category. Thoughts? A: You have a number of resources, should be accessible per each own url. Four of resources are the same type and can be determine as posts. It's ok to provide their functionality by one controller and it's easy to detect the current path, then parse and add number of active record scopes. But let's look a little bit deeper. You have the same type of data, probably with same attributes, so the common pattern is "Single Table Inheritance", it equal the one table and more models, the column "type" differs the models. Controllers are provide interface between user interaction and data flow, so I'd suggest you to use independent controller per each resource. It's a general practice. If you don't like to type more typical code, use Resourceful Controller plugin or so. Then you can have the structure: #routes resources :code, sports, :gaming, :personal # STI parent and children models model Post < ActiveRecord::Base model Sport < Post ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7550040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: css hide button until div hover We want to hide button until we hover over the div layer. FIDDLE here > Click to view Essentially, I would like to be able to apply this to other elements also, but this will do for now, any help appreciated A: Simply use the :hover pseudo-class on the outer div: .resultContainer .viewThisResult { display: none; } .resultContainer:hover .viewThisResult { display: inline; } Here's the fiddle: http://jsfiddle.net/dTLaF/1/ A: .resultContainer:hover .viewThisResult { display: block; } :hover pseudoselector on the parent. Though it's nice when the code for the question is included in the question, for posterity. A: when using this feature and trying to hover most of the time it doesn't work because when something is hidden it is no longer there to activate hover, the simplest way to solve this is by making it transparent and using hover to remove the transparency.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Wrong body width in Linux Firefox I try to get body width in Linux Firefox. document.body.scrollWidth is equal to width which I can see in firefox window. So when I changed window size, document.body.scrollWidth is changed. But in Google Chrome, It is equal to body width. My Firefox version is 6.0. How can I get body width in Firefox/Linux? A: I believe you're looking for offsetWidth which computes the width of the contents of the body. A: Per http://dev.w3.org/csswg/cssom-view/#dom-element-scrollwidth scrollWidth on the <body> returns the 'window size' (or more precisely the actual width of the body box) in standards mode and the document content width in quirks mode (item 3 in the list). It sounds like your page is in standards mode. In which case document.documentElement.scrollWidth should do what you wan (item 2 in the list).
{ "language": "en", "url": "https://stackoverflow.com/questions/7550051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }