text
stringlengths
8
267k
meta
dict
Q: How do I override some functions in the Queue STL object? I am trying to override the push and pop functions from the STL queue. I think I need to use templates. I get a 'MyQueue' does not name a type (this error is in my main.cpp file) and an error saying expected initializer before '<' token. Here is the snippet of code: #include "MyQueue.h" sem_t EmptySem; sem_t PresentSem; sem_t mutex; MyQueue::MyQueue() { sem_init(&EmptySem, PTHREAD_PROCESS_SHARED, QSIZE); sem_init(&PresentSem, PTHREAD_PROCESS_SHARED, 0); sem_init(&mutex, PTHREAD_PROCESS_SHARED, 1); } template <class Elem> void queue<Elem>::push(const Elem &Item) { sem_wait(EmptySem); sem_wait(mutex); super.push(Item); sem_post(mutex); sem_post(PresentSem); } template <class Elem> Elem queue<Elem>::pop(void) { Elem item; sem_wait(PresentSem); sem_wait(mutex); item = super.front(); super.pop(); signal(mutex); signal(EmptySem); return item; } Thanks! A: You cannot override functions that are not defined as virtual. So you gain nothing by publicly inheriting from std::queue. It would be best if MyQueue stored a member that was a std::queue. That way, you can do whatever you want and just forward the functions to the std::queue member. Also, C++ has no keyword super; that's Java.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scala passing a reference to this class I have a class, with multiple methods and members. When I create an instance of this class, I create an instance of another class within the first class. Some of the methods in this second class require to know which instance of the first class is running. Currently, I am trying to pass "this" into the argument that accepts type firstClass. What am I doing wrong? Again, I simply want the second class instance knowing what first class instance it belongs to so that it can call public methods and members from it. EDIT: Code example: def main(args:Array[String]) : Unit = { val objectOne = new classOne } class classOne { val mutableBuffer = mutable.Buffer[String] val objectTwo = new classTwo objectTwo.doThis(this) } class classTwo { def doThis (exA:classOne) = { exA.mutableBuffer += "Adding text to a Buffer in object One" } } A: Self-typing is often the cleanest solution here class Bippy { outer => ... class Bop { def demoMethod() = println(outer) } ... } UPDATE The example code changes everything, this clearly isn't about inner classes. I believe your problem is in this line: val mutableBuffer = mutable.Buffer[String] It isn't doing what you think it's doing, mutableBuffer is now pointing to the mutable.Buffer singleton, it isn't actually an instance of a Buffer Instead, try one of these two: val mutableBuffer = mutable.Buffer[String]() //or val mutableBuffer = mutable.Buffer.empty[String] You should also stick to the convention of starting class/singleton/type names with an uppercase letter, turning your example code into: import collection.mutable.Buffer def main(args:Array[String]) : Unit = { val one = new ClassOne() } class ClassOne { val mutableBuffer = Buffer.empty[String] val two = new ClassTwo() two.doThis(this) } class ClassTwo { def doThis(one: ClassOne) = { one.mutableBuffer += "Adding text to a Buffer in object One" } } A: I had to make some superficial changes to your example code in order to make it run: import scala.collection.mutable class classOne { val mutableBuffer : mutable.Buffer[String] = new mutable.ArrayBuffer[String] val objectTwo = new classTwo objectTwo.doThis(this) } class classTwo { def doThis (exA : classOne) = { exA.mutableBuffer += "Adding text to a Buffer in object One" } } val objectOne = new classOne println(objectOne.mutableBuffer(0)) But it works as expected. The classTwo object is able to modify the classOne object. Do you need something beyond this functionality?
{ "language": "en", "url": "https://stackoverflow.com/questions/7542031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to instruct XmlSerializer to serialize a DateTime instance using a particular date time pattern? I have many types, which are (de)serialized using the XmlSerializer. My problem is that I want the timestamps (DateTime instances) appearing in these types to be serialized to the respective strings using a particular date time pattern. How do I do it? A: You can't do that with DateTime. In XSD there is a specific type for dates defining a specific format. You will be violating the specification if you do that. If you want to handle some custom format use strings as properties of the object you are serializing, not dates, and format those strings however you like. A: If there's specific requirement to achieve such thing you can try something like this: private DateTime actualDateObject; public string FormattedDate { get { return actualDateObject.ToString("format"); } set { DateTime.TryParse(value, out actualDateObject); } } A: I would rather go Automapper route - create a parallel class with string properties for serialization only, map it somewhere with Mapper.CreateMap<DateTime, string>().ConvertUsing<DateTimeStringTypeConverter>(); and make a converter public class DateTimeStringTypeConverter : ITypeConverter<DateTime, string> { public string Convert(ResolutionContext context) { if (context.IsSourceValueNull) return null; else { var source = (DateTime)context.SourceValue; return source.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); } } } and then do map - Mapper.Map<DateStringClass>(DateClass); It is more work, but keeps the domain clean...
{ "language": "en", "url": "https://stackoverflow.com/questions/7542034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Overwriting and Extending Prototype I'm not sure why when I overwrite the prototype below with an object(Gadget.prototype = { price: 100;}, only new instances of Gadget(theGadget) have access to the new properties. But when extended(Gadget.prototype.price = 100) All instances have access. function Gadget(name, color) { this.name = name; this.color = color; this.brand = "Sony"; this.whatAreYou = function(){ return 'I am a ' + this.color + ' ' + this.name; } } myGadget = new Gadget(); myGadget.brand; //Gadget.prototype.price = 100; Gadget.prototype = { price: 100, rating: 3, }; myGadget.price; theGadget = new Gadget(); theGadget.price A: It seems pretty obvious to me - each object has a reference to its prototype which is set when the object is first constructed. If you set the prototype to something new: Gadget.prototype = {price: 100}; you haven't changed any references to the old prototype. Only objects created afterwards will have their prototype set to the new value. Think of it like the difference between this: var a = {foo: true}; var b = a; a = {baz: 'quux'}; // b refers to the original value of a and this: var a = {foo: true}; var b = a; a.baz = 'quux'; // a and b refer to the same object
{ "language": "en", "url": "https://stackoverflow.com/questions/7542036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Getting an error when uploading the apk to the market " An unexpected error occurred. Please try again later. " is the error that I am getting when I try uploading my signed apk.. Once I was done with my app, I used Export signed application tool to generate the key. Why am I getting this error? A: Try to use a different browser, or just wait. This can help: http://www.google.com/support/forum/p/Android+Market/thread?tid=7fff4999197c33c7&hl=en A: Just log out . Log in again. And yep now it works :) . If not still working clear history and then try again logging in it will surely do. However google should look on to this issue A: I found that just SIGNING OUT and back int fixed the issue for me. Using Firefox. A: I just experienced the same problem using FireFox, so I just switch to IE and it worked fine ... A: I logged out and then logged in again. The new version is listed but a couple more steps involved. Deactivate the currently published version and click the "Publish Now" button. They need to fix this. It is not intuitive by any stretch of the imagination. A: I just had this issue, and solved it by: * *Saving the apk as draft (instead of publishing it). *Deactivating the currently published version. *Publishing the draft apk. Signing out and back in again didn't help. A: Changing the browser (IE/Opera) and re login didn;t work. So I logged out, remove all signed in gmail accounts from the browser(Chrome) and then logged in. It worked. A: I just spent hours trying to upload and publish a new version of my app using Firefox on the Google Developer site. Eventually I too found that just signing out and back in solved the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Can I use a gradient as the selected color in a box-shadow I would like to make a box-shadow appear darker on one side than another. I would like to do something like the following: box-shadow: 2px 3px 6px linear-gradient(90deg, #ccc, #fff); Is this possible? A: Firefox, at least, won't let you do this. Firefox only supports linear-gradient in a background-image style. Even for browsers that may allow gradients in more places than Firefox does, they probably wouldn't allow this particular usage. In general, the gradient properties are only meant to work in places in CSS where images are allowed, not to replace "normal" colors. You could do something sneaky like making a gradient the background-image of an element that's behind the one you're setting this box-shadow on, which you could use make it appear like the shadow is darker on one side. That's going to be quite a bit more complicated in terms of markup and styling, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C/C++ FLAC tagging library Is there any C/C++ FLAC tagging library that work on streams? Wherever I look I only find ones that work on files. It's kinda weird to me - why use something limited like file instead of more abstract stream. Well, maybe I'm just spoiled by managed languages neatness (I'm more of a Java guy, but this time I need unmanaged code solution). A: I'm not familiar with any FLAC libraries, but the reference FLAC library supports an interface for custom I/O. This allows you to write a small stub that will convert I/O calls to a custom data source, which needn't be a file. It seems to require capacity to seek, though. If that is the case, then you might not be able to wrap a socket without a high-level protocol that allows you to seek.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to load not active customers in magento I need to load only inactive customers from magento collection. $collection = Mage::getModel('customer/customer') ->getCollection() ->addNameToSelect() ->addAttributeToSelect('email') ->addAttributeToSelect('created_at') ->addAttributeToSelect('group_id') ->addAttributeToSelect('confirmation') ->addAttributeToSelect('*');` $collection ->joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left') ->joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left') ->joinAttribute('billing_telephone', 'customer_address/telephone', 'default_billing', null, 'left') ->joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left') ->joinAttribute('billing_country_id', 'customer_address/country_id', 'default_billing', null, 'left'); And from this collection i tried to add $collection->getSelect()->where("e.is_active = 0 "); But it throws exception and am not able to load only inactive customers inside admin custom module. Please help me on loading inactive customers. Note: From front-end by default i setup all the customers registration as "is_active" to be 0 , so after admin approval only customers will be active. For that i need to load all those inactive customers. A: Try $collection->addAttributeToFilter('is_active', 0) A: According to this magento thread there could be a bug in definition of default attributes of Customer Entity. Try to look into Mage_Customer_Model_Entity_Customer, in this method: protected function _getDefaultAttributes() { return array( 'entity_type_id', 'attribute_set_id', 'created_at', 'updated_at', 'increment_id', 'store_id', 'website_id' ); } there should be: protected function _getDefaultAttributes() { return array( 'entity_type_id', 'attribute_set_id', 'created_at', 'updated_at', 'increment_id', 'store_id', 'website_id', 'is_active' ); } If this is the case then Zyava's solution neither this one: $collection->addFieldToFilter('is_active', 0) won't probably work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Learning Single Responsibility Principle with C# I am trying to learn the Single Responsibility Principle (SRP) but it is being quite difficult as I am having a huge difficult to figure out when and what I should remove from one class and where I should put/organize it. I was googling around for some materials and code examples, but most materials I found, instead of making it easier to understand, made it hard to understand. For example if I have a list of Users and from that List I have a class Called Control that does lots of things like Send a greeting and goodbye message when a user comes in/out, verify weather the user should be able to enter or not and kick him, receive user commands and messages, etc. From the example you don't need much to understand I am already doing too much into one class but yet I am not clear enough on how to split and reorganize it afterwards. If I understand the SRP, I would have a class for joining the channel, for the greeting and goodbye, a class for user verification, a class for reading the commands, right ? But where and how would I use the kick for example ? I have the verification class so I am sure I would have all sort of user verification in there including weather or not a user should be kicked. So the kick function would be inside the channel join class and be called if the verification fails ? For example: public void UserJoin(User user) { if (verify.CanJoin(user)) { messages.Greeting(user); } else { this.kick(user); } } Would appreciate if you guys could lend me a hand here with easy to understand C# materials that are online and free or by showing me how I would be splitting the quoted example and if possible some sample codes, advice, etc. A: Let’s start with what does Single Responsibility Principle (SRP) actually mean: A class should have only one reason to change. This effectively means every object (class) should have a single responsibility, if a class has more than one responsibility these responsibilities become coupled and cannot be executed independently, i.e. changes in one can affect or even break the other in a particular implementation. A definite must read for this is the source itself (pdf chapter from "Agile Software Development, Principles, Patterns, and Practices"): The Single Responsibility Principle Having said that, you should design your classes so they ideally only do one thing and do one thing well. First think about what “entities” you have, in your example I can see User and Channel and the medium between them through which they communicate (“messages"). These entities have certain relationships with each other: * *A user has a number of channels that he has joined *A channel has a number of users This also leads naturally do the following list of functionalities: * *A user can request to join a channel. *A user can send a message to a channel he has joined *A user can leave a channel *A channel can deny or allow a user’s request to join *A channel can kick a user *A channel can broadcast a message to all users in the channel *A channel can send a greeting message to individual users in the channel SRP is an important concept but should hardly stand by itself – equally important for your design is the Dependency Inversion Principle (DIP). To incorporate that into the design remember that your particular implementations of the User, Message and Channel entities should depend on an abstraction or interface rather than a particular concrete implementation. For this reason we start with designing interfaces not concrete classes: public interface ICredentials {} public interface IMessage { //properties string Text {get;set;} DateTime TimeStamp { get; set; } IChannel Channel { get; set; } } public interface IChannel { //properties ReadOnlyCollection<IUser> Users {get;} ReadOnlyCollection<IMessage> MessageHistory { get; } //abilities bool Add(IUser user); void Remove(IUser user); void BroadcastMessage(IMessage message); void UnicastMessage(IMessage message); } public interface IUser { string Name {get;} ICredentials Credentials { get; } bool Add(IChannel channel); void Remove(IChannel channel); void ReceiveMessage(IMessage message); void SendMessage(IMessage message); } What this list doesn’t tell us is for what reason these functionalities are executed. We are better off putting the responsibility of “why” (user management and control) in a separate entity – this way the User and Channel entities do not have to change should the “why” change. We can leverage the strategy pattern and DI here and can have any concrete implementation of IChannel depend on a IUserControl entity that gives us the "why". public interface IUserControl { bool ShouldUserBeKicked(IUser user, IChannel channel); bool MayUserJoin(IUser user, IChannel channel); } public class Channel : IChannel { private IUserControl _userControl; public Channel(IUserControl userControl) { _userControl = userControl; } public bool Add(IUser user) { if (!_userControl.MayUserJoin(user, this)) return false; //.. } //.. } You see that in the above design SRP is not even close to perfect, i.e. an IChannel is still dependent on the abstractions IUser and IMessage. In the end one should strive for a flexible, loosely coupled design but there are always tradeoffs to be made and grey areas also depending on where you expect your application to change. SRP taken to the extreme in my opinion leads to very flexible but also fragmented and complex code that might not be as readily understandable as simpler but somewhat more tightly coupled code. In fact if two responsibilities are always expected to change at the same time you arguably should not separate them into different classes as this would lead, to quote Martin, to a "smell of Needless Complexity". The same is the case for responsibilities that never change - the behavior is invariant, and there is no need to split it. The main idea here is that you should make a judgment call where you see responsibilities/behavior possibly change independently in the future, which behavior is co-dependent on each other and will always change at the same time ("tied at the hip") and which behavior will never change in the first place. A: My recommendation is to start with the basics: what things do you have? You mentioned multiple things like Message, User, Channel, etc. Beyond the simple things, you also have behaviors that belong to your things. A few examples of behaviors: * *a message can be sent *a channel can accept a user (or you might say a user can join a channel) *a channel can kick a user *and so on... Note that this is just one way to look at it. You can abstract any one of these behaviors until abstraction means nothing and everything! But, a layer of abstraction usually doesn't hurt. From here, there are two common schools of thought in OOP: complete encapsulation and single responsibility. The former would lead you to encapsulate all related behavior within its owning object (resulting in inflexible design), whereas the latter would advise against it (resulting in loose coupling and flexibility). I would go on but it's late and I need to get some sleep... I'm making this a community post, so someone can finish what I've started and improve what I've got so far... Happy learning! A: I had a very easy time learning this principle. It was presented to me in three small, bite-sized parts: * *Do one thing *Do that thing only *Do that thing well Code that fulfills those criteria fulfills the Single-Responsibility Principle. In your above code, public void UserJoin(User user) { if (verify.CanJoin(user)) { messages.Greeting(user); } else { this.kick(user); } } UserJoin does not fulfill the SRP; it is doing two things namely, Greeting the user if they can join, or rejecting them if they cannot. It might be better to reorganize the method: public void UserJoin(User user) { user.CanJoin ? GreetUser(user) : RejectUser(user); } public void Greetuser(User user) { messages.Greeting(user); } public void RejectUser(User user) { messages.Reject(user); this.kick(user); } Functionally, this is no different from the code originally posted. However, this code is more maintainable; what if a new business rule came down that, because of recent cybersecurity attacks, you want to record the rejected user's IP address? You would simply modify method RejectUser. What if you wanted to show additional messages upon user login? Just update method GreetUser. SRP in my experience makes for maintainable code. And maintainable code tends to go a long ways toward fulfilling the other parts of SOLID.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "56" }
Q: Global vector emptying itself between calls? I have a vector in a header, like so: extern std::vector<Foo> g_vector; In the associated cpp file I have this: std::vector<Foo> g_vector; I also have a class Bar, and in it's constructor it will add some stuff to g_vector, like so: Bar::Bar(/* stuff */) { // do things std::cout << g_vector.size() << std::endl; g_vector.push_back(somefoo); std::cout << g_vector.size() << std::endl; } If I declare a Bar inside a function, like a sane person, it appears to work fine. However, if I want to declare a Bar outside of a function, weird things happen. For example, I have a Bar declared in MyFile1.cpp and in MyFile2.cpp, and because of my cout statements in Bar I can see the Foo get pushed into the vector, but when the next Bar runs its constructor the vector's size is 0 again. In other words, my output is 0 1 0 1 What gives? Just to be extra double sure, I also tried printing out &g_vector to make sure it was actually push_backing into the right vector, and the addresses all match. For what it's worth, it doesn't matter what order these things go in to the vector. I'm not concerned with the initialization order or anything. A: Not sure what the issue really is, but I guess the following pattern will help solve it: define an accessor to the global variable and allocate it as a static function variable as shown below. In the header file: std::vector<Foo> &getGlobalVector(); In the cpp file: std::vector<Foo> &getGlobalVector() { static std::vector<Foo> s_vector; return s_vector; } This pattern is inspired from Andrei Alexandrescu's "generic singleton" implementation in Modern C++ design. I've taken the habit of systematically using this pattern whenever I fell upon an existing global variable while maintaining existing applications (or in the rare occasions I actually chose to use one myself), and it may have helped in eliminating a couple of hard-to-reproduce bugs in said applications. At any rate, this should really help avoiding any multiple-initialization or order-of-initialization related issue. A: Order of initialization of global values is not defined. Read here about the static initialization fiasco. When you declare Bar in a function - the g_vector will be initialized before, because its promised to be initialized before the program runs. If Bar is a global variable - then you have a problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Most efficient way of reading data from a stream I have an algorithm for encrypting and decrypting data using symmetric encryption. anyways when I am about to decrypt, I have: CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Read); I have to read data from the cs CryptoStream and place that data into a array of bytes. So one method could be: System.Collections.Generic.List<byte> myListOfBytes = new System.Collections.Generic.List<byte>(); while (true) { int nextByte = cs.ReadByte(); if (nextByte == -1) break; myListOfBytes.Add((Byte)nextByte); } return myListOfBytes.ToArray(); another technique could be: ArrayList chuncks = new ArrayList(); byte[] tempContainer = new byte[1048576]; int tempBytes = 0; while (tempBytes < 1048576) { tempBytes = cs.Read(tempContainer, 0, tempContainer.Length); //tempBytes is the number of bytes read from cs stream. those bytes are placed // on the tempContainer array chuncks.Add(tempContainer); } // later do a for each loop on chunks and add those bytes I cannot know in advance the length of the stream cs: or perhaps I should implement my stack class. I will be encrypting a lot of information therefore making this code efficient will save a lot of time A: You could read in chunks: using (var stream = new MemoryStream()) { byte[] buffer = new byte[2048]; // read in chunks of 2KB int bytesRead; while((bytesRead = cs.Read(buffer, 0, buffer.Length)) > 0) { stream.Write(buffer, 0, bytesRead); } byte[] result = stream.ToArray(); // TODO: do something with the result } A: Since you are storing everything in memory anyway you can just use a MemoryStream and CopyTo(): using (MemoryStream ms = new MemoryStream()) { cs.CopyTo(ms); return ms.ToArray(); } CopyTo() will require .NET 4
{ "language": "en", "url": "https://stackoverflow.com/questions/7542059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Is it possible to create a motion tween in as2 code Is it possible to make a motion tween with as2 code only ( not with timeline). If it is, then can you please tell me how to do it? A: There's the Tween class: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/2/help.html?content=00000350.html But I believe most ActionScript developers prefer to use the third party libraries TweenNano/TweenLite/TweenMax or Tweener, and that they still support AS2: http://www.greensock.com/tweenmax/ http://code.google.com/p/tweener/
{ "language": "en", "url": "https://stackoverflow.com/questions/7542068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Question about mongodb capped collections + tailable cursors I'm building a queueing system that passes a message from one process to another via a stack implemented in mongodb with capped_collections and tailable cursors. The receiving processes loops infinitely looking for new documents in the capped_collection, and when it finds one it performs an operation. My question is, if I implement multiple receiving processes is there a way to guarantee that a new document will only be read once by one of the processes using a tailable cursor? The goal is to avoid the operation being performed twice if there are two receiving processes looking for new messages in the queue. I'm relatively new to mongodb programming so I'm still getting a feel for all of its features. A: MongoDB documents contain a thorough description of ways to achieve an atomic update. You cannot ensure that only one process receives the new document but you can implement an atomic update after receiving it to ensure that only one process acts on it. A: I have recently been looking into this problem and I would be interested to know if there are other ways to have multiple readers (consumers) without relying on atomic updates. This is what I have come up with: divide your logic into two "modules". The first module will be responsible for fetching new documents from the tailable cursor. The second module will be responsible for working with an arbitrary document. In this manner, you can have only one consumer (module one) fetching documents which later sends the document to multiple document workers (second module). Both modules can be implemented in different processes and even in different languages. For example, a Node.js app could be fetching the documents and sending them to a pool of scripts written in Python ready to process documents concurrently.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Jquery create array problem with for Hello I have a prboblem with the next code: function loadOptions(num){ listTabs = new Array(); for(var i = 1 ; i < parseInt(num) + 1 ; i++){ var tabActu = { 'name':'tab'+i, 'src':'urlImatge' }; listTabs.add(tabActu); $.each(listTabs,function(key,value){ alert(key+" : "+value); }); } } I need to create an list of elements equal to the num parameter. I can't find the error. A: Did you look in the error console for javascript errors? Javascript arrays don't have a .add() method. You can use .push(). function loadOptions(num){ listTabs = new Array(); var len = parseInt(num, 10); for (var i = 1 ; i < len + 1 ; i++) { var tabActu = { 'name':'tab' + i, 'src':'urlImatge' }; listTabs.push(tabActu); $.each(listTabs,function(key,value){ alert(key+" : "+value); }); } } In addition to change to .push(), parseInt must always be passed the radix value and you should remove the function call to parseInt from the loop so it's not called on every iteration. Also, you haven't delcared listTabs here so that makes it a global variable. Is that what you intended? A: Sup Francesc Arrays dont have a add method ..... use push
{ "language": "en", "url": "https://stackoverflow.com/questions/7542075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way to asynchronously load underscore templates I'm planning to use backbone.js and underscore.js for creating website, and I will have lots of underscore templates: <script type="text/template" id="search_template"> <p id="header"> //header content will go here </p> <p id="form"> <label>Search</label> <input type="text" id="search_input" /> <input type="button" id="search_button" value="Search" /> </p> <p id="dynamic_date"> //dynamic data will be displayed here </p> </script> Of course my templates will be much more complicated. Since I will have lots of them, I don't want to load all templates every time when page loads. I want to find a solution, where I can load specific template only when it will be used. Another thing is that most of my templates will have same structure, only <p id="form"></p> and <p id="dynamic_date"></p> content will differ. Could you please suggest me how should I do it? Thanks, A: Edit: I did some research and ported my iCanHaz code to underscore it also uses localStorage is available Here is a github repository: https://github.com/Gazler/Underscore-Template-Loader The code is: (function() { var templateLoader = { templateVersion: "0.0.1", templates: {}, loadRemoteTemplate: function(templateName, filename, callback) { if (!this.templates[templateName]) { var self = this; jQuery.get(filename, function(data) { self.addTemplate(templateName, data); self.saveLocalTemplates(); callback(data); }); } else { callback(this.templates[templateName]); } }, addTemplate: function(templateName, data) { this.templates[templateName] = data; }, localStorageAvailable: function() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } }, saveLocalTemplates: function() { if (this.localStorageAvailable) { localStorage.setItem("templates", JSON.stringify(this.templates)); localStorage.setItem("templateVersion", this.templateVersion); } }, loadLocalTemplates: function() { if (this.localStorageAvailable) { var templateVersion = localStorage.getItem("templateVersion"); if (templateVersion && templateVersion == this.templateVersion) { var templates = localStorage.getItem("templates"); if (templates) { templates = JSON.parse(templates); for (var x in templates) { if (!this.templates[x]) { this.addTemplate(x, templates[x]); } } } } else { localStorage.removeItem("templates"); localStorage.removeItem("templateVersion"); } } } }; templateLoader.loadLocalTemplates(); window.templateLoader = templateLoader; })(); Calling it would look something like: templateLoader.loadRemoteTemplate("test_template", "templates/test_template.txt", function(data) { var compiled = _.template(data); $('#content').html(compiled({name : 'world'})); }); Here is my original answer Here is a method I wrote for ICanHaz (mustache) that performs this exact function for the same reason. window.ich.loadRemoteTemplate = function(name, callback) { if (!ich.templates[name+"_template"]) { jQuery.get("templates/"+name+".mustache", function(data) { window.ich.addTemplate(name+"_template", data); callback(); }); } else { callback(); } } I then call it like so: ich.loadRemoteTemplate(page+'_page', function() { $('#'+page+'_page').html(ich[page+'_page_template']({}, true)); }); A: I really like the way the stackoverflow team has done templating with the mvc-miniprofiler. Take a look at these links: Includes.js (Github link) Includes.tmpl (Github link) They use the local storage to cache the templates locally if your browser supports local storage. If not they just load it every time. Its a pretty slick way to handle the templates. This also allows you to keep your templates that aren't required immediately in a separate file and not clutter up your html. Good luck. A: Although both of the above answers work, I found the following to be a much simpler approach. Places your templates wrapped in script tags into a file (say "templates.html") as follows: <script type="text/template" id="template-1"> <%- text %> </script> <script type="text/template" id="template-2"> oh hai! </script> Then the following bit of javascript: $(document).ready(function() { url ='http://some.domain/templates.html' templatesLoadedPromise = $.get(url).then(function(data) { $('body').append(data) console.log("Async loading of templates complete"); }).fail(function() { console.log("ERROR: Could not load base templates"); }); }); Which then let's you select your templates quite simply using the IDs you previously defined. I added the promise $.when(templatesLoadedPromise).then(function() { _.template($('#template-1').html(), {'text':'hello world'} ) }); You can then extend this and load multiple files if you want. As a side note, I've found that any core templates needed for initial page render are better embedded in the HTML (I use tornado modules on the server) but that the above approach works very nicely for any templates needed later (e.g., in my case the templates for a registration widget which I want to use across pages is perfect for this as it'll only be loaded on user interaction and is non-core to the page)
{ "language": "en", "url": "https://stackoverflow.com/questions/7542089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: acts_as_taggable_on find existing tags to suggest from content We're using the (brilliant) acts_as_taggable_on Rails gem, allowing users to add tags to content they write (e.g. blog comment). We auto-suggest on as they type, but would also like to identify tags that we can suggest based on the user's content. So if the user typed "We really loved the aquarium in Boston" and we had existing tags for "boston" and "aquarium" we might suggest those. I think this is simple conceptually (iterate words, check the tags list, order by frequency of use), but there are little nuances, performance implications, and well, you know -- always harder than it looks. Any suggestions for existing code or examples that might help me avoid recreating a wheel? Thanks! A: Well, I don't really know acts_as_taggable... But I think you can use something like : Tag.find(:all, :conditions => { :name => title.split(' ').map(&:downcase) })
{ "language": "en", "url": "https://stackoverflow.com/questions/7542092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ActiveMQ "Scheduler" Daemon Threads not terminating I'm using ActiveMQ 5.5 with an embedded broker. All messages are non persistent. Producer and Consumer both run within same JVM. Advisory Support is disabled. Everything is working fine. My question is about these "Scheduler" threads running as daemon threads and why they are not terminated. I ran a test where I created about 10 consumers (no producers started) and closed them. I've confirmed that my consumers close successfully, by using advisory support etc... So inspite of the consumers closing successfully, I see that there's a scheduler Daemon thread created for each consumer, and its not terminated, even if I wait for a long time. Why is that so? Is there anything I'm not doing? Here's how my stack stack looked like in Eclipse...there's 10 daemon scheduler threads, each created for a consumer. Daemon Thread [ActiveMQ Broker[MDASJ_BROKER] Scheduler] (Running) Thread [New I/O server boss #1 ([id: 0x008730b8, /0.0.0.0:5555])] (Running) Thread [DestroyJavaVM] (Running) Daemon Thread [ActiveMQ Task-1] (Running) Daemon Thread [BrokerService[MDASJ_BROKER] Task-1] (Running) Daemon Thread [ActiveMQ Task-2] (Running) Daemon Thread [ActiveMQConnection[ID:Sprouts-53743-1316899960679-1:1] Scheduler] (Running) Daemon Thread [ActiveMQConnection[ID:Sprouts-53743-1316899960679-1:2] Scheduler] (Running) Thread [New I/O server worker #1-1] (Running) Daemon Thread [ActiveMQ Task-3] (Running) Thread [New I/O server worker #1-2] (Running) Daemon Thread [ActiveMQConnection[ID:Sprouts-53743-1316899960679-1:3] Scheduler] (Running) Thread [New I/O server worker #1-3] (Running) Daemon Thread [ActiveMQConnection[ID:Sprouts-53743-1316899960679-1:4] Scheduler] (Running) Thread [pool-4-thread-4] (Running) Daemon Thread [ActiveMQConnection[ID:Sprouts-53743-1316899960679-1:5] Scheduler] (Running) Daemon Thread [ActiveMQConnection[ID:Sprouts-53743-1316899960679-1:6] Scheduler] (Running) Daemon Thread [ActiveMQConnection[ID:Sprouts-53743-1316899960679-1:7] Scheduler] (Running) Daemon Thread [ActiveMQConnection[ID:Sprouts-53743-1316899960679-1:8] Scheduler] (Running) Daemon Thread [ActiveMQConnection[ID:Sprouts-53743-1316899960679-1:9] Scheduler] (Running) Daemon Thread [ActiveMQConnection[ID:Sprouts-53743-1316899960679-1:10] Scheduler] (Running)
{ "language": "en", "url": "https://stackoverflow.com/questions/7542093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django user profile form validation problem I'm trying to implement user profile module to my django project, but I'm getting this error: Form 'SignupForm' could be validated, while 'ProfileForm' couldn't. Please make sure the two classes are compatible. Validation errors were: * user * Обязательное поле.(can't be blank) My code: http://pastie.org/2586199 Can anyone help me? Thanks in advance. A: You should probably just set the Model meta attribute to your profile class manually instead of grabbing it from the settings: from some.module import MyProfile class ProfileForm(forms.ModelForm): pass class Meta: model = MyProfile That code seems to be vastly over complicating a fairly simple operation
{ "language": "en", "url": "https://stackoverflow.com/questions/7542094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to handle stylesheet links when local and server directory structures don't match The document root of my website is directly the server webroot (public_html), and not in a separate subdirectory. This creates a problem for me, because my local website is in a project folder (which is required by my editor, NetBeans), which means that href links to stylesheets need to be of the form: /projectfolder/stylesheets/stylesheet.css But on the server, since the website is directly in the webroot, the href url would have to be: /stylesheets/stylesheet.css When I asked my host about this, they said I would have to refactor my project to change all the stylesheet links. But I don't know; it seems kind of funny to have to refactor (then "unrefactor") the local website every time I want to upload it to the server. Any other solutions out there? A: You don't have to use absolute paths to your stylesheets. Use relative paths instead. Then it won't matter where your files are hosted, so long as they stay in the same positions relative to each other.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby gem for writing formulas in xls/xlsx spreadsheets? Is there a Ruby gem that can write formulas to an xls/xlsx spreadsheet? The Spreadsheet gem doesn't appear to allow this, at least not in the latest version. Are there any gems out there that allow this or am I stuck doing it in a csv file? Thanks, Ben A: I had this exact same problem and there is a gem that will do this for you! Check out writeexcel. It will write all those formulas you have been missing. Here is an example of how it works: worksheet.write('B5', '=SIN(B4/4)') Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7542099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SyncAdapter and wifi color I'm using a syncadapter in my app. I've noticed that the app syncs properly when the wifi icon is green, but fails to sync when it is white, even though there is internet connection available in both cases. How can I request sync when the wifi is white?
{ "language": "en", "url": "https://stackoverflow.com/questions/7542100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run a Linux/C program in a customized way? I need to write a program that is to be run as follows: <program_name>_ <space> _<file_name>_ <space> _<stuff to be written into the file>. I am new to Linux/C/Unix programming and so I need your help. From what I can understand, I need to write a program titled <program_name>, pass two parameters in the main function which are <file_name> and <stuff to be written in the file>, and then go through the code as usual, writing all the required lines. Am I going about this the right way? Also, it is mentioned that I am to create a make file out of the program. As I am thoroughly unfamiliar with Linux, I would like to know if that this would change anything. That is, would my approach to the program change because I am to make a make file out of it? Thanks for the help! :) A: You should search for "beginning linux" to get some web sites that will give you the basics of navigating around in Linux, notably on the command line. Then I'd search for "beginning vi" to learn the basics of the vi editor. If you're using a GUI, then you can simply use their simple GUI text editor. Then I would search on "Beginning C programming linux". That will give you several links, and will get you through the basics of creating a C program and compiling it with GCC. That should keep you in enough trouble for the short term until something clicks or you learn enough new terms to keep searching for. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7542101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Restart Jetty through Eclipse I'm new to Eclipse and Google App Engine development. I am unable to refresh my localhost to display changes in my code. Clicking Run doesn't seem to rebuild it. I can't find the option to refresh the server in the Eclipse IDE to reflect the changes. Refreshing the browser / clearing my browser cache doesn't work, so it's clearly server side. A: At first you should stop launched application -> red rectangle in console window. After that click at the top menu Project -> Clean. Choose your project and set check box "Start build immediatly" if it present. Then run again your project and see your changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show a DIV when sitting a mouse on it using jquery? How to show a DIV when the mouse is over another div (I have multiple divs, when I have the mouse over one of them I want a "info" window appears ) , and keeping it appear until the mouse it moved out of the area of the div. I want the din to appear in the position of the mouse ? A: I would suggest using qTip. They have done most of the work for you, leaving you to just styling and formatting contents. A: When the div is hidden, mouseover would not fire to make it visible. So you can play with background color instead. Something like this demo. Here is the code: Markup Some text here. <div id="area"></div> CSS #area { position: absolute; top: 0; width: 130px; height: 80px; background-color: transparent; border: 1px solid gray; } JS $("#area").mouseover(function() { $(this).css('background-color', 'red'); }); $("#area").mouseout(function() { $(this).css('background-color', 'transparent'); }); A: I have solved it by myself ! Check the demo
{ "language": "en", "url": "https://stackoverflow.com/questions/7542106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: CSS table inside a table? i was trying to put table inside a table like this: <table> <tr> <td>Filename</td> <td>Size</td> </tr> <tr> <table> <tr> <td>my cool file name</td> <td>654 KB</td> </tr> </table> </tr> </table> the reason i want to do this is to set the second table a height and than overflow:auto so the second table have a scroll bar to scroll down is that possible , and it it does , how? A: You still need a <td>/<th> within a <tr> tag, so add either of those between your <tr> & nested <table> (and probably apply colspan="2") Also, off the top of my head I'm not sure if the <td>/<th> supports an overflow with scrolling, but if not you can always wrap the nested <table> in a <div> and style it. A: <table> isn't valid inside <tr>. Put it inside a <td> inside a <tr> instead. Like this: <table> <tr> <td>Filename</td> <td>Size</td> </tr> <tr> <td> <!-- ** add this ** --> <table> <tr> <td>my cool file name</td> <td>654 KB</td> </tr> </table> </td> <!-- ** add this ** --> </tr> </table>
{ "language": "en", "url": "https://stackoverflow.com/questions/7542112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Typed dataset codebehind What can you add to the codebehind file of a typed dataset? I thought the dataset classes were generated at runtime. The codebehind file is always an empty partial class. A: You can probably add anything you like as it is a class but since an autogenerated file could be regenerated again if you touch the dataset designer, in case you want to add some methods i would add another file by hand having it to extend the same partial class so visual studio will never overwrite this last file as it was added by you. Anyway what do you want to add? dont make same mistake I did long ago to consider these st datasets as business objects or business managers they are ONLY typed data containers...
{ "language": "en", "url": "https://stackoverflow.com/questions/7542114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: looping text in file python I have 2 files i am trying to put together one has about 300 lines and the other has mabey 85. I want to have the file with 85 to loop until it adds a line of text onto each of the other files lines. Here is my code i put together so far name_file = open("names.txt", "r") year_file = open("years.txt", "r") for line in name_file: print line.strip()+(year_file.readline()) Here are some examples of what the output looks like when it runs out of numbers LLOYD1999 TOMMY2000 LEON2001 DEREK2002 WARREN2003 DARRELL2004 JEROME FLOYD LEO I want it to output like this LLOYD1999 LLOYD2000 LLOYD2001 LLOYD2002 LLOYD2003 LLOYD2004 TOMMY1999 TOMMY2000 TOMMY2001 TOMMY2002 TOMMY2003 TOMMY2004 ect... A: # Get a list of all the years so we don't have to read the file repeatedly. with open('years.txt', 'r') as year_file: years = [year.strip() for year in year_file] # Go through each entry in the names. with open('names.txt', 'r') as name_file: for name in name_file: # Remove any extra whitespace (including the newline character at the # end of the name). name = name.strip() # Add each year to the name to form a list. nameandyears = [''.join((name, year)) for year in years] # Print them out, each entry on a new line. print '\n'.join(nameandyears) # And add in a blank line after we're done with each name. print A: with open('years.txt') as year: years = [yr.strip() for yr in year] with open('names.txt') as names: for name in names: name = name.strip() for year in years: print("%s%s" % (name, year)) A: name_file = open("names.txt", "r") for line in name_file: year_file = open("years.txt", "r") for year in year_file: print line.strip()+year.strip() year_file.close() name_file.close() A: name_file = open("names.txt", "r") year_file = open("years.txt", "r") for line in name_file: year = year_file.readline().strip() if year == '': # EOF, Reopen and re read Line year_file = open("years.txt", "r") year = year_file.readline().strip() print line.strip() + year
{ "language": "en", "url": "https://stackoverflow.com/questions/7542118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Perl: how to make variables from requiring script available in required script example out.pl: (my|our|local|global|whatever???) var = "test"; require("inside.pm"); inside.pm: print $var; I don't want to use packages - it's overwhelming my needs :) thanks! A: You are always using a package, even if you don't use the package declaration. By default, you're working in package main. All variables you declare with our are package variables and should be available package wide. Here's an example: #! /usr/bin/env perl # test2.pl use strict; use warnings; our $foo = "bar"; 1; Since $foo is declared as a package variable, it will be available in other programs: #! /usr/bin/env perl use strict; use warnings; require "test2.pl"; our $foo; print "The value of \$foo is $foo\n"; Now I've given you enough rope, I'm going to tell you not to hang yourself with it. This is a REALLY, REALLY BAD IDEA. Notice that $foo gets a value from some sort of mysterious mechanism that's almost impossible to figure out? Packages are too complex? Really? It's not that hard! Look at this example: #! /usr/bin/env perl # test2.pm package test2; use strict; use warnings; our $foo = "bar"; 1; Not much different than before except I added the package declaration and now call my program test2.pm instead of test2.pl. Here's how I access it: #! /usr/bin/env perl use strict; use warnings; use test2; print "The value of \$foo from package test2 is $test2::foo\n"; All I had to do was use the package name in the variable. This is a BAD IDEA, but it's way better than the REALLY, REALLY BAD IDEA shown above. At least, you know where the value came from. It came from test2.pm. And, you could access the variable if you set it in a subroutine. #! /usr/bin/env perl # test2.pm package test2; use strict; use warnings; sub fooloader { our $foo = "bar"; } 1; Notice that $foo is set in the subroutine fooloader. And, here's my other program to access it: #! /usr/bin/env perl use strict; use warnings; use test2; &test2::fooloader(); print "The value of \$foo from package test2 is $test2::foo\n"; Now, you could use the Exporter to export your subroutines (and even variables), but that's not something you see too much anymore. Mainly because it is a REALLY BAD IDEA. Not as bad as the original REALLY REALLY BAD IDEA, but worse than the BAD IDEA above: #! /usr/bin/env perl # test2.pm package test2; use base qw(Exporter); our @EXPORT = qw(fooloader); use strict; use warnings; sub fooloader { our $foo = "bar"; } 1; Now, I can use subroutine fooloader without the package name: #! /usr/bin/env perl use strict; use warnings; use test2; fooloader(); print "The value of \$foo from package test2 is $test2::foo\n"; The problem, of course, is that you have no real idea where the subroutine fooloader is coming from. If you used @EXPORT_OK instead of @EXPORT, you could have then use use test2 qw(fooloader); and document where the fooloader function was coming from. It'll also help you to know not to create your own fooloader function in your own program and override the one you imported. Then, wonder why your program no longer works. By the way, you could also export variables and not just functions. However, that becomes a REALLY, REALLY, REALLY BAD -- NO TERRIBLE IDEA because it violates every reason why you use packages in the first place. If you're going to do that, why bother with packages? Why not simple take a gun and shoot yourself in the foot? The best and preferred way is to use object oriented Perl and do it in the THOROUGHLY CORRECT WAY. A way where you know exactly what's going on and why. And, makes it easy to figure out what your code is doing. A way that keeps errors at a minimum. Behold the thoroughly object oriented Test2 class: #! /usr/bin/env perl # Test2.pm package Test2; sub new { my $class = shift; my $self = {}; bless $self, $class; return $self; } sub FooValue { return "bar"; } 1; And using that Test2 class: #! /usr/bin/env perl use strict; use warnings; use Test2; my $tester = Test2->new; print "The value of foo from package test2 is " . $tester->FooValue . "\n"; The reason this is the best way to do it is because even if you use packages, you could manipulate the value of $test2::foo and it will be changed in your entire program. Imagine if this was say $constants::pi and somewhere you changed it from 3.14159 to 3. From then on, using $constants::pi would give you the wrong value. If you use the object oriented method, you couldn't change the value of the method Constant->Pi. It will always be 3.14159. So, what did we learn today? We learned that it is very easy in Perl to do something that's a REALLY, REALLY BAD IDEA, but it doesn't take all that much work to use packages, so it merely becomes a BAD IDEA. And, if you start learning a bit of object oriented Perl, you can actually, without too much effort, do it all in the THOROUGHLY CORRECT WAY. The choice is yours to make. Just remember the foot you're shooting will probably be your own. A: It will work with our. $ cat out.pl our $var = "test"; require("inside.pm"); $ cat inside.pm print "Testing...\n"; print "$var\n"; $ perl out.pl Testing... test This works because our makes $var global, and inside.pm is being executed in the scope with $var defined. Not sure it is recommended technique, but it is an interesting question nevertheless! EDIT: Need to clarify (okay patch) the answer based on a comment: From the documentation on the Perl function our: our associates a simple name with a package (read: global) variable in the current package, for use within the current lexical scope. In other words, our has the same scoping rules as my or state, but does not necessarily create a variable. So using our, we get $var with the current package (here probably main) and we can use it in its scope. In effect it is then "global" to the code in the file you are requiring-in. A true global is introduced without the our, because variables default to global. But I don't know anyone that would recommend them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: BG image with Swing without overriding paintComponent I'm currently designing a menu with several screens with multiple buttons on each screen. To use buttons on top of the background image, which is in a jLabel (by default, I can't put buttons on TOP of the jLabel), I used GridBagLayout with two panels/menu screen, one panel containing the buttons (opaque = false) and one panel with the background image, or jLabel. In order to switch the current panels being displayed, depending on where the user is in the menu, I made each menu screen (aka. every 2 panels) in separate methods, not classes. Now, I've come to the point where I'm working on parts of the interface that are unnecessarily complicated, and I don't feel GridBag will serve my purposes, so I was wondering if there was a different way to draw my background image, still being able to use my buttons on top of the image. The most popular way I looked up was overriding the paintComponent method, but I can't do that, since I've made my JPanels in separate methods, not classes. They're all contained in my original JFrame. Help would be greatly appreciated, thank you! Just added this code, but my background remains white for some reason? Trying the other suggestion right now, thanks guys! private void mainPanel() { icon = new ImageIcon(getClass().getResource("/phantasma/menuv1.png")); mainContainer1 = new javax.swing.JPanel() { @Override protected void paintComponent(Graphics g) { g.drawImage(icon.getImage(), 0,0, null); super.paintComponent(g); } }; A: BG image with Swing without overriding paintComponent I have no idea why all the postings suggest doing custom painting for this. You would only do custom painting if you need to automatically scale the background image. If you want the image painted at its real size then use a JLabel. I can't put buttons on TOP of the jLabel), Sure you can. Just set a LayoutManager for the JLabel and then you can add any component to it the same way you add components to a panel. A: In my comment above I state: You can always create an anonymous inner JPanel-derived class and override the paintComponent method there if need be. As an example of what I mean, you can override paintComponent in any JPanel that you create whether it's derived from a stand-alone class or created within a method. For e.g., import java.awt.Dimension; import java.awt.Graphics; import javax.swing.*; public class AnonInnerPanel { private static void createAndShowGui() { JPanel mainPanel = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); } @Override public Dimension getPreferredSize() { return new Dimension(300, 200); } }; JFrame frame = new JFrame("AnonInnerPanel"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(mainPanel); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7542124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pushing Django updates to production server I need some advice on pushing Django updates, specifically the database updates, from my development server to my production server. I believe that updating the scripts, files, and such will be easy -- simply copy the new files from the dev server to the production server. However, the database updates are what have me unsure. For Django, I have been using South during initial web app creation to change the database schema. If I were to have some downtime on the production server for updates, I could copy all the files over to the production server. These would include and changed models.py files which describe the database tables. I could then perform a python manage.py schemamigration my_app --auto and then a python migrate my_app to update the database based on the new files/models.py I've copied over. Is this an OK solution or are there more appropriate ways to go about updating a database from development to production servers? Your thoughts? Thanks A: Actually, python manage.py schemamigration my_app --auto will only create the migration based on the changes in models.py. To actually apply the migration to the database, you need to run python manage.py migrate my_app. Another option would be to create migrations (by running schemamigration) on the development server, and then copy over the migration files to the production server and apply migrations by running migrate. Of course, having a source code repository would be way better than copying the files around. You could create migrations on your development server, commit them to the repository, on the production server pull the new files from repository, and finally apply migrations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Sliding window using as_strided function in numpy? As I get to implement a sliding window using python to detect objects in still images, I get to know the nice function: numpy.lib.stride_tricks.as_strided So I tried to achieve a general rule to avoid mistakes I may fail in while changing the size of the sliding windows I need. Finally I got this representation: all_windows = as_strided(x,((x.shape[0] - xsize)/xstep ,(x.shape[1] - ysize)/ystep ,xsize,ysize), (x.strides[0]*xstep,x.strides[1]*ystep,x.strides[0],x.strides[1]) which results in a 4 dim matrix. The first two represents the number of windows on the x and y axis of the image. and the others represent the size of the window (xsize,ysize) and the step represents the displacement from between two consecutive windows. This representation works fine if I choose a squared sliding windows. but still I have a problem in getting this to work for windows of e.x. (128,64), where I get usually unrelated data to the image. What is wrong my code. Any ideas? and if there is a better way to get a sliding windows nice and neat in python for image processing? Thanks A: There is an issue in your code. Actually this code work good for 2D and no reason to use multi dimensional version (Using strides for an efficient moving average filter). Below is a fixed version: A = np.arange(100).reshape((10, 10)) print A all_windows = as_strided(A, ((A.shape[0] - xsize + 1) / xstep, (A.shape[1] - ysize + 1) / ystep, xsize, ysize), (A.strides[0] * xstep, A.strides[1] * ystep, A.strides[0], A.strides[1])) print all_windows A: Check out the answers to this question: Using strides for an efficient moving average filter. Basically strides are not a great option, although they work. A: For posteriority: This is implemented in scikit-learn in the function sklearn.feature_extraction.image.extract_patches. A: I had a similar use-case where I needed to create sliding windows over a batch of multi-channel images and ended up coming up with the below function. I've written a more in-depth blog post covering this in regards to manually creating a Convolution layer. This function implements the sliding windows and also includes dilating or adding padding to the input array. The function takes as input: input - Size of (Batch, Channel, Height, Width) output_size - Depends on usage, comments below. kernel_size - size of the sliding window you wish to create (square) padding - amount of 0-padding added to the outside of the (H,W) dimensions stride - stride the sliding window should take over the inputs dilate - amount to spread the cells of the input. This adds 0-filled rows/cols between elements Typically, when performing forward convolution, you do not need to perform dilation so your output size can be found be using the following formula (replace x with input dimension): (x - kernel_size + 2 * padding) // stride + 1 When performing the backwards pass of convolution with this function, use a stride of 1 and set your output_size to the size of your forward pass's x-input Sample code with an example of using this function can be found at this link. def getWindows(input, output_size, kernel_size, padding=0, stride=1, dilate=0): working_input = input working_pad = padding # dilate the input if necessary if dilate != 0: working_input = np.insert(working_input, range(1, input.shape[2]), 0, axis=2) working_input = np.insert(working_input, range(1, input.shape[3]), 0, axis=3) # pad the input if necessary if working_pad != 0: working_input = np.pad(working_input, pad_width=((0,), (0,), (working_pad,), (working_pad,)), mode='constant', constant_values=(0.,)) in_b, in_c, out_h, out_w = output_size out_b, out_c, _, _ = input.shape batch_str, channel_str, kern_h_str, kern_w_str = working_input.strides return np.lib.stride_tricks.as_strided( working_input, (out_b, out_c, out_h, out_w, kernel_size, kernel_size), (batch_str, channel_str, stride * kern_h_str, stride * kern_w_str, kern_h_str, kern_w_str) )
{ "language": "en", "url": "https://stackoverflow.com/questions/7542135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to split audio encoding across multiple application launches? My app needs to encode a large amount of audio data to an M4A file. I am currently using AVAssetWriter, which works fine, except that it takes a few minutes to encode all the data. Instead of asking the user to keep the app running until the process has finished, I would like to pause the encoding when the app terminates and continue on relaunch. Unfortunately, AVAssetWriter doesn't seem to support this, as it always creates a new file when initializing. Do you know any other APIs that I could use? Maybe a third-party library? A: This is exactly what background processing is intended for. As long as you can complete within 10 minutes, you can use beginBackgroundTaskWithExpirationHandler: to ask the system to let you keep running after the user switches applications. See Completing a Finite-Length Task in the Background in the iOS Application Programming Guide. Not only is this the easiest to use, but it'll give the best user experience. The only issue you'd face is if it's possible for an audio file to take longer than 10 minutes in a non-resumable way. If that's a real possibility, then you'll need another solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TCP Window size libnids My intent is to write a app. layer process on top of libnids. The reason for using libnids API is because it can emulate Linux kernel TCP functionality. Libnids would return hlf->count_new which the number of bytes from the last invocation of TCP callback function. However the tcp_callback is called every time a new packet comes in, therefore hlf->count_new contains a single TCP segment. However, the app. layer is supposed to receive the TCP window buffer, not separate TCP segments. Is there any way to get the data of the TCP window (and not the TCP segment)? In other words, to make libnids deliver the TCP window buffer data. thanks in advance! A: You have a misunderstanding. The TCP window is designed to control the amount of data in flight. Application reads do not always trigger TCP window changes. So the information you seek is not available in the place you are looking. Consider, for example, if the window is 128KB and eight bytes have been sent. The receiving TCP stack must acknowledge those eight bytes regardless of whether the application reads them or not, otherwise the TCP connection will time out. Now imagine the application reads a single byte. It would be pointless for the TCP stack to enlarge the window by one byte -- and if window scaling is in use, it can't do that even if it wants to. And then what? If four seconds later the application reads another single byte, adjust the window again? What would be the point? The purpose of the window is to control data flow between the two TCP stacks, prevent the buffers from growing infinitely, and control the amount of data 'in flight'. It only indirectly reflects what the application has read from the TCP stack. It is also strange that you would even want this. Even if you could tell what had been read by the application, of what possible use would that be to you?
{ "language": "en", "url": "https://stackoverflow.com/questions/7542137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I apply a Style Setter for ListBoxItems of a certain DataType? My WPF ListBox contains two types of object: Product and Brand. I want my Products selectable. I want my Brands not selectable. Each of the two types has its own DataTemplate. By default, anything may be selected: <ListBox ... > <ListBox.Resources> <DataTemplate DataType="{x:Type local:Product}"> ... </DataTemplate> <DataTemplate DataType="{x:Type local:Brand}"> ... </DataTemplate> </ListBox.Resources> </ListBox> I can set Focusable with a Setter, but then nothing may be selected: <ListBox ... > <ListBox.Resources> ... <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="Focusable" Value="False" /> </Style> </ListBox.Resources> </ListBox> I cannot put the Setter within the DataTemplate. I cannot put a DataType onto the Style. How do I style only the ListBoxItems of type Brand? A: Thanks to the StyleSelector class you can attach styles depending on type of data for the ItemContainerStyle. There is a really good example here : http://www.telerik.com/help/wpf/common-data-binding-style-selectors.html A: Can you use a data trigger on your ListBoxItem style? If so, bind to the DataContext (your class) and use a value converter to test the type. If it's the one you're interested in, style the ListBoxItem so that it cannot appear selected. I don't think you can disallow selection of an item in a Selector (parent of ListBox) without codebehind or a custom Behavior.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: which diagram to use in NoSql (Mcd, Merise, UML) again, sorry for my silly question, but it seems that what i've learned from Relation Database should be "erased", there is no joins, so how the hell will i draw use Merise and UML in NoSql? http://en.wikipedia.org/wiki/Class_diagram this one will not work for NoSql? A: How you organize your project is an independent notion of the technology used for persistence; In particular; UML or ERD or any such tool doesn't particularly apply to relational databases any more than it does to document databases. The idea that NoSQL has "No Joins" is both silly and unhelpful. It's totally correct that (most) document databases do not provide a join operator; but that just means that when you do need a join, you do it in the application code instead of the query language; The basic facts of organizing your project stay the same. Another difference is that document databases make expressing some things easier, and other things harder. For example, it's often easier to an entity relationship constraint in a relational database, but it's easier to express an inheritance heirarchy in a document database. Both notions can be supported by both technologies, and you will certainly use them when your application needs them; regardless of the technology you end up using. In short, you should design your application without first choosing a persistence technology. Once you've got a good idea what you want to persist, You may have a better idea of which technology is a better fit. It may be the case that what you really need is both, or you might need something totally different from either. EDIT: The idea of a foreign key is no more magical than simply saying "This is a name of that kind of thing". It happens that many SQL databases provide some very terse and useful features for dealing with this sort of thing; specifically, constraints (This column references this other relation; so it cannot take a value unless there is a corresponding row in the referant), and cascades, (If the status of the referent changes, make the corresponding change to the reference). This does make it easy to keep data consistent even at the lowest level, since there's no way to tell the database to enter a state where the referent is missing. The important thing to distinguish though, is that the idea of giving a database entity (A row in a relational database, document in document databases) is distinct from the notion of schema constraints. One of the nice things about document databases is that they can easily combine or reorient where data lives so that you don't always have to have a referant that actually exists; Most document databases use the document class as part of the key, and so you can still be sure that the key is meaningful, even if when the referent doesn't actually exist. But most of the time, you actually do want the referent to exist; you don't want a blog post to have an author unless that author actually exists in your system. Just how well this is supported depends a lot on the particular document database; Some databases do provide triggers, or other tools, to enforce the integrity of the reference, but many others only provide some kind of transactional capability, which requires that the integrity be enforced in the application. The point is; for most kinds of database, every value in the database has some kind of identifier; in a relational database, that's a triple of relation:column:key; and in a document database it's usually something like the pair document_class:path. When you need one entity to refer to another, you use whatever sort of key you need to identify that datum for that kind of database. Foreign Key constraints found in RDBMses are just (really useful) syntactic sugar for "if not referant exists then raise ForeignKeyError", which could be implemented with equal power in other ways, if that's helpful for your particular use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Moving between XIBs iOS I have a view-based application with three xib files, each with its own view controllers. How do I change from one to another? I use this to move from xib 1 to xib 2, but when I use the same code to move from xib 2 to xib 1, i get a EXC_BAD_ACCESS on the [self presentModal....] line. MapView *controller = [[MapView alloc] initWithNibName:@"MapView" bundle:nil]; controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical; [self presentModalViewController:controller animated:YES]; How can I freely move from one xib to another? A: What I think you are trying to do is is present a modal view and then dismiss it, right? If that is the case then you put the code below in the method that you use to dismiss it(e.g. -(IBAction)dissmissModalView) [self.parentViewController dismissModalViewControllerAnimated:YES]; Hopefully that works. Let me know. A: initWithNibName isn't really necessary... you can change that to nil. So, here is the correct code (without animation): MapView *mapView = [[MapView alloc] initWithNibName:nil bundle:nil]; [self presentModalViewController:mapView animated:NO]; You should not be receiving EXC_BAD_ACCESS when trying to go back to view 1 using present. If you cannot resolve it, just use this instead: [self dismissModalViewControllerAnimated:YES]; The second view controller will disappear and the first view controller will be visible again. A: Note that presenting modal view controllers like the other answers here will mean that you have an ever-accumulating stack of view controllers. Use the application long enough and it will crash. Instead, you can swap out the view from the application's window. Here's one way of doing that: Add a data member to your app delegate to store the current view: @class MyAppDelegate : NSObject <...> { UIViewController* currentVC; } and add a message there to swap VCs: -(void)setCurrentVC:(UIViewController*)newVC { if (newVC==currentVC) return; if (currentVC!=nil) [currentVC.view removeFromSuperview]; currentVC = newVC; if (newVC!=nil) [self.window addSubview:newVC.view]; } and to swap from one screen to another: MapView* mapView = [[MapView alloc] init]; [[[UIApplication shared] delegate] setCurrentVC:mapView];
{ "language": "en", "url": "https://stackoverflow.com/questions/7542143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XAML Binding to Sql Server I have a SQL Server DB with the following tables and relationships: Jobs which contains many sessions. Sessions which contains many breaks. First of all, dont be frightened by the large amount of code posted here. The relevant parts are the highlighted parts dealing with the list, the rest is just for comparison to see where I am going wrong. In XAML I am trying and succeeding when binding jobs. I get it to filter out the correct sessions. No problem there. My problem is that when I try to get it to filter the breaks that belong to each session it wont work but I am using all the same principles. I am not using (nor interested in using) Linq2Sql as it creates too many additional classes that bloat my code. I am just using direct databinding. I have asked this question before and posted code, but I never got any reply because the code was simply too long to read in a reasonable timeframe. My question here is, what am I doing wrong. I was with the impression that since I can successfully bind and filter sessions, then I should be able to do likewise with sessions and filter breaks. But it doesnt work. I am getting somewhat desparate for help and appreicate any answers. EDIT: Once again I have included code samples. I am not trying to hide the code for secrecy and copyright. It is just an exercise I am doing to learn so I wouldnt mind posting the full code. But it is very long. So I will just post the parts I think are relevant. If you want more just ask. For those of you interested in skipping to the good part where the problems are, look under the part of the Breaks list box. The rest is just there for comparison to help you debug. There is also C# code below to help further. Again, look at the list part the rest is just for debugging. Below is the relevant XAML <!--Jobs List box - Works fine--> <ListBox Name="lstJobs" DockPanel.Dock="Top" MinWidth="150" MinHeight="200" MaxHeight="250" ScrollViewer.VerticalScrollBarVisibility="Visible" SelectionChanged="lstJobs_SelectionChanged" IsSynchronizedWithCurrentItem="True" DataContext="{Binding Tables[JobDetails]}" ItemsSource="{Binding}" > <ListBox.ItemTemplate> <DataTemplate> <Grid> <StackPanel Orientation="Horizontal" Margin="3,0,3,0"> <TextBlock Text="{Binding Path=Title}"/> <TextBlock Text=" "/> <TextBlock Text="{Binding Path=ID}"/> </StackPanel> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <!--How Jobs listbox is bound to relevant fields in jobs table. This works fine--> <TextBox Text="{Binding ElementName=lstJobs, Path=SelectedItem.ID, UpdateSourceTrigger=PropertyChanged}" Name="txtJobNo" Grid.Row="1" IsEnabled="False"/> <TextBox Text="{Binding ElementName=lstJobs, Path=SelectedItem.Title, UpdateSourceTrigger=PropertyChanged}" Name="txtJobTitle" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2"/> <TextBox Text="{Binding ElementName=lstJobs, Path=SelectedItem.Description, UpdateSourceTrigger=PropertyChanged}" Name="txtJobDesc" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="3" Grid.RowSpan="2"/> <!--Sessions List box, Automatically filtered based on relationship (see last binding line). This works fine too--> <ListBox Name="lstSessions" DockPanel.Dock="Top" MinWidth="150" MinHeight="200" MaxHeight="220" ScrollViewer.VerticalScrollBarVisibility="Visible" SelectionChanged="lstSessions_SelectionChanged" IsSynchronizedWithCurrentItem="True" DataContext="{Binding Path=Tables[JobDetails]}" ItemsSource="{Binding Path=relJobDetailsSessionDetails}" > <ListBox.ItemTemplate> <DataTemplate> <Grid> <StackPanel Orientation="Horizontal" Margin="3,0,3,0"> <TextBlock Text="{Binding Path=Title}" /> <TextBlock Text="{Binding Path=ID}" /> </StackPanel> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <!--How Sessions listbox is bound to relevant fields in Sessions table. This works fine--> <TextBox Name="txtSessionNo" Text="{Binding ElementName=lstSessions, Path=SelectedItem.ID, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" Grid.Column="0"/> <TextBox Name="txtSessionTitle" Text="{Binding ElementName=lstSessions, Path=SelectedItem.Title, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="3"/> <TextBox Name="txtSessionDesc" Text="{Binding ElementName=lstSessions, Path=SelectedItem.Description, UpdateSourceTrigger=PropertyChanged}" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="3" Grid.RowSpan="2"/> <!--Breaks List box, Should be automatically filtered (it is), but it does not change when a job or session is selected. Why?? --> <ListBox Name="lstBreaks" MinWidth="150" MinHeight="140" MaxHeight="140" ScrollViewer.VerticalScrollBarVisibility="Visible" SelectionChanged="lstBreaks_SelectionChanged" IsSynchronizedWithCurrentItem="True" DataContext="{Binding Path=Tables[SessionDetails]}" ItemsSource="{Binding Path=relSessionDetailsBreakDetails}" > <ListBox.ItemTemplate> <DataTemplate> <Grid> <StackPanel Orientation="Horizontal" Margin="3,0,3,0"> <TextBlock Text="{Binding Path=Title}" /> <TextBlock Text="{Binding Path=ID}" /> </StackPanel> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <!--How Breaks listbox is bound to relevant fields in Breaks table. This works fine as before--> <TextBox Name="txtBreakNo" Text="{Binding ElementName=lstBreaks, Path=SelectedItem.ID, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" Grid.Column="0"/> <TextBox Name="txtBreakTitle" Text="{Binding ElementName=lstBreaks, Path=SelectedItem.Title, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2"/> <ComboBox Name="cbxBreakType" Text="{Binding ElementName=lstBreaks, Path=SelectedItem.Description, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" Grid.Column="3"/> Following is the C# Code behind (Once again, the highlighted part is the breaks and the rest is just for comparison, so you can skip directly to that if you like): //Connection String string conString = "XYZ Works ok, no prob here"; //Data Adaptors for various tables SqlDataAdapter daJobDetails = new SqlDataAdapter(); SqlDataAdapter daSessionDetails = new SqlDataAdapter(); SqlDataAdapter daBreakDetails = new SqlDataAdapter(); //The dataset to hold all of the data DataSet dsDataSet = new DataSet(); //Step 1: Create Connection SqlConnection conn = new SqlConnection(conString); //Open Connection conn.Open(); //Load Job Details Table - works fine. daJobDetails.SelectCommand = new SqlCommand("Select * From JobDetails", conn); daJobDetails.Fill(dsDataSet, "JobDetails"); //Load Session Details table - works fine. daSessionDetails.SelectCommand = new SqlCommand("SELECT * FROM SessionDetails", conn); daSessionDetails.Fill(dsDataSet, "SessionDetails"); //Relation: JobDetails.ID = SessionDetails.JobID. - Works fine dsDataSet.Relations.Add("relJobDetailsSessionDetails", dsDataSet.Tables["JobDetails"].Columns["ID"], dsDataSet.Tables["SessionDetails"].Columns["JobID"]); //**** Possible problem code ***** //Load Break Details table - could there be something wrong here. daBreakDetails.SelectCommand = new SqlCommand("SELECT * FROM BreakDetails", conn); daBreakDetails.Fill(dsDataSet, "BreakDetails"); //**** Possible problem code ***** //Relation: SessionDetails.ID = BreakDetails.SessionID - Could there be something wrong here dsDataSet.Relations.Add("relSessionDetailsBreakDetails", dsDataSet.Tables["SessionDetails"].Columns["ID"], dsDataSet.Tables["BreakDetails"].Columns["SessionID"]); //Set the DataContext to the DataSet expJobs.DataContext = dsDataSet; //Close connection conn.Close(); A: As requested, here is a full repro case. Update: updated with the working code from your link. Looks like the answer was binding to SelectedItem => relation. Very logical, actually. XAML: <Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width=".5*"/> <ColumnDefinition Width=".5*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height=".33*"/> <RowDefinition Height=".33*"/> <RowDefinition Height=".33*"/> </Grid.RowDefinitions> <!--Jobs List box - Works fine--> <ListBox Name="lstJobs" Grid.Column="0" Grid.Row="0" MinWidth="150" MinHeight="200" MaxHeight="250" ScrollViewer.VerticalScrollBarVisibility="Visible" SelectionChanged="lstJobs_SelectionChanged" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Path=JobDetails}" > <ListBox.ItemTemplate> <DataTemplate> <Grid> <StackPanel Orientation="Horizontal" Margin="3,0,3,0"> <TextBlock Text="{Binding Path=ID}"/> <TextBlock Text="{Binding Path=Title}"/> </StackPanel> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <!--How Jobs listbox is bound to relevant fields in jobs table. This works fine--> <StackPanel Orientation="Vertical" Grid.Column="1" Grid.Row="0"> <TextBox Text="{Binding ElementName=lstJobs, Path=SelectedItem.ID, UpdateSourceTrigger=PropertyChanged}" Name="txtJobNo" Grid.Row="1" IsEnabled="False"/> <TextBox Text="{Binding ElementName=lstJobs, Path=SelectedItem.Title, UpdateSourceTrigger=PropertyChanged}" Name="txtJobTitle" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2"/> <TextBox Text="{Binding ElementName=lstJobs, Path=SelectedItem.Description, UpdateSourceTrigger=PropertyChanged}" Name="txtJobDesc" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="3" Grid.RowSpan="2"/> </StackPanel> <!--Sessions List box, Automatically filtered based on relationship (see last binding line). This works fine too --> <ListBox Name="lstSessions" Grid.Column="0" Grid.Row="1" DockPanel.Dock="Top" MinWidth="150" MinHeight="200" MaxHeight="220" ScrollViewer.VerticalScrollBarVisibility="Visible" SelectionChanged="lstSessions_SelectionChanged" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding ElementName=lstJobs, Path=SelectedItem.relJobDetailsSessionDetails}" > <ListBox.ItemTemplate> <DataTemplate> <Grid> <StackPanel Orientation="Horizontal" Margin="3,0,3,0"> <TextBlock Text="{Binding Path=Title}" /> <TextBlock Text="{Binding Path=ID}" /> </StackPanel> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <!--How Sessions listbox is bound to relevant fields in Sessions table. This works fine--> <StackPanel Orientation="Vertical" Grid.Column="1" Grid.Row="1"> <TextBox Name="txtSessionNo" Text="{Binding ElementName=lstSessions, Path=SelectedItem.ID, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" Grid.Column="0"/> <TextBox Name="txtSessionTitle" Text="{Binding ElementName=lstSessions, Path=SelectedItem.Title, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="3"/> <TextBox Name="txtSessionDesc" Text="{Binding ElementName=lstSessions, Path=SelectedItem.Description, UpdateSourceTrigger=PropertyChanged}" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="3" Grid.RowSpan="2"/> </StackPanel> <!--Breaks List box, Should be automatically filtered (it is), but it does not change when a job or session is selected. Why?? --> <ListBox Name="lstBreaks" Grid.Column="0" Grid.Row="2" MinWidth="150" MinHeight="140" MaxHeight="140" ScrollViewer.VerticalScrollBarVisibility="Visible" SelectionChanged="lstBreaks_SelectionChanged" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding ElementName=lstSessions, Path=SelectedItem.relSessionDetailsBreakDetails}" > <ListBox.ItemTemplate> <DataTemplate> <Grid> <StackPanel Orientation="Horizontal" Margin="3,0,3,0"> <TextBlock Text="{Binding Path=Title}" /> <TextBlock Text="{Binding Path=ID}" /> </StackPanel> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <!--How Breaks listbox is bound to relevant fields in Breaks table. This works fine as before--> <StackPanel Orientation="Vertical" Grid.Column="1" Grid.Row="2"> <TextBox Name="txtBreakNo" DockPanel.Dock="Bottom" Text="{Binding ElementName=lstBreaks, Path=SelectedItem.ID, UpdateSourceTrigger=PropertyChanged}" Grid.Row="2" Grid.Column="1"/> <TextBox Name="txtBreakTitle" DockPanel.Dock="Bottom" Text="{Binding ElementName=lstBreaks, Path=SelectedItem.Title, UpdateSourceTrigger=PropertyChanged}" Grid.Row="2" Grid.Column="2"/> <ComboBox Name="cbxBreakType" DockPanel.Dock="Bottom" Text="{Binding ElementName=lstBreaks, Path=SelectedItem.Description, UpdateSourceTrigger=PropertyChanged}" Grid.Row="2" Grid.Column="3"/> </StackPanel> </Grid> </Window> Code behind: using System; using System.Data; using System.Windows; using System.Windows.Controls; namespace WpfApplication2 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); CreateData(); this.DataContext = Data; } public DataSet Data { get; set; } private void CreateData() { Data = new DataSet(); Data.Tables.Add(CreateJobTable()); Data.Tables.Add(CreateSessionsTable()); Data.Tables.Add(CreateBreaks()); DataRelation relation = GetJobSessionRelations(); DataRelation relation2 = GetSessionBreakRelations(); Data.Relations.AddRange(new[] {relation, relation2}); } private DataTable CreateJobTable() { var jobs = new DataTable(); jobs.TableName = "JobDetails"; var col1 = new DataColumn("ID"); var col2 = new DataColumn("Title"); var col3 = new DataColumn("Description"); col1.DataType = Type.GetType("System.Int32"); col2.DataType = Type.GetType("System.String"); col3.DataType = Type.GetType("System.String"); jobs.Columns.Add(col1); jobs.Columns.Add(col2); jobs.Columns.Add(col3); DataRow row = jobs.NewRow(); row["ID"] = 1; row["Title"] = "Job 1"; row["Description"] = "Job Desc 1"; jobs.Rows.Add(row); DataRow row2 = jobs.NewRow(); row2["ID"] = 2; row2["Title"] = "Job 2"; row2["Description"] = "Job Desc 2"; jobs.Rows.Add(row2); return jobs; } private DataTable CreateSessionsTable() { var sessions = new DataTable(); sessions.TableName = "SessionDetails"; var col1 = new DataColumn("ID"); var col2 = new DataColumn("Title"); var col3 = new DataColumn("Description"); var col4 = new DataColumn("JobID"); col1.DataType = Type.GetType("System.Int32"); col2.DataType = Type.GetType("System.String"); col3.DataType = Type.GetType("System.String"); col4.DataType = Type.GetType("System.Int32"); sessions.Columns.Add(col1); sessions.Columns.Add(col2); sessions.Columns.Add(col3); sessions.Columns.Add(col4); DataRow row = sessions.NewRow(); row["ID"] = 1; row["Title"] = "Session 1"; row["Description"] = "Session Desc 1"; row["JobID"] = 1; sessions.Rows.Add(row); DataRow row2 = sessions.NewRow(); row2["ID"] = 2; row2["Title"] = "Session 2"; row2["Description"] = "Session Desc 2"; row2["JobID"] = 1; sessions.Rows.Add(row2); DataRow row3 = sessions.NewRow(); row3["ID"] = 3; row3["Title"] = "Session 3"; row3["Description"] = "Session Desc 3"; row3["JobID"] = 2; sessions.Rows.Add(row3); DataRow row4 = sessions.NewRow(); row4["ID"] = 4; row4["Title"] = "Session 4"; row4["Description"] = "Session Desc 4"; row4["JobID"] = 2; sessions.Rows.Add(row4); return sessions; } private DataTable CreateBreaks() { var breaks = new DataTable(); breaks.TableName = "BreakDetails"; var col1 = new DataColumn("ID"); var col2 = new DataColumn("Title"); var col3 = new DataColumn("Description"); var col4 = new DataColumn("SessionID"); col1.DataType = Type.GetType("System.Int32"); col2.DataType = Type.GetType("System.String"); col3.DataType = Type.GetType("System.String"); col4.DataType = Type.GetType("System.Int32"); breaks.Columns.Add(col1); breaks.Columns.Add(col2); breaks.Columns.Add(col3); breaks.Columns.Add(col4); DataRow row = breaks.NewRow(); row["ID"] = 1; row["Title"] = "Break 1"; row["Description"] = "Break Desc 1"; row["SessionID"] = 1; breaks.Rows.Add(row); DataRow row2 = breaks.NewRow(); row2["ID"] = 2; row2["Title"] = "Break 2"; row2["Description"] = "Break Desc 2"; row2["SessionID"] = 2; breaks.Rows.Add(row2); DataRow row3 = breaks.NewRow(); row3["ID"] = 3; row3["Title"] = "Break 3"; row3["Description"] = "Break Desc 3"; row3["SessionID"] = 3; breaks.Rows.Add(row3); DataRow row4 = breaks.NewRow(); row4["ID"] = 4; row4["Title"] = "Break 4"; row4["Description"] = "Break Desc 4"; row4["SessionID"] = 4; breaks.Rows.Add(row4); return breaks; } private DataRelation GetSessionBreakRelations() { return new DataRelation("relJobDetailsSessionDetails", Data.Tables["JobDetails"].Columns["ID"], Data.Tables["SessionDetails"].Columns["JobID"]); } private DataRelation GetJobSessionRelations() { var dataRelation = new DataRelation("relSessionDetailsBreakDetails", Data.Tables["SessionDetails"].Columns["ID"], Data.Tables["BreakDetails"].Columns["SessionID"]); return dataRelation; } private void lstJobs_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void lstSessions_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void lstBreaks_SelectionChanged(object sender, SelectionChangedEventArgs e) { } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7542146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WSDL XML rendered by 'ADOM XML v4' in Delphi XE2 I have been trying to implement a very simple webservice running under OSX ( and windows) with XE2, but it seems that the XML that 'ADOM XML v4' generates/renders for the webservice is invalid in some way. The only obvious difference I noticed compared to what is generated with 'MSXML' is that the encoding seem to be set to 'UTF-16LE' no matter what I try to change. Anyone run in to the same problem and know how to fix it? Update: The easiest way to recreate this is to create a trivial 'SOAP Server Application' and change the generated WebModuleUnit to the following: unit WebModuleUnit1; interface uses System.SysUtils, System.Classes, Web.HTTPApp, Soap.InvokeRegistry, Soap.WSDLIntf, System.TypInfo, Soap.WebServExp, Soap.WSDLBind, Xml.XMLSchema, Soap.WSDLPub, Soap.SOAPPasInv, Soap.SOAPHTTPPasInv, Soap.SOAPHTTPDisp, Soap.WebBrokerSOAP, Xml.xmldom, Xml.adomxmldom; type TWebModule1 = class(TWebModule) HTTPSoapDispatcher1: THTTPSoapDispatcher; HTTPSoapPascalInvoker1: THTTPSoapPascalInvoker; WSDLHTMLPublish1: TWSDLHTMLPublish; procedure WebModule1DefaultHandlerAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); private { Private declarations } public { Public declarations } end; var WebModuleClass: TComponentClass = TWebModule1; implementation {$R *.dfm} procedure TWebModule1.WebModule1DefaultHandlerAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); begin WSDLHTMLPublish1.ServiceInfo(Sender, Request, Response, Handled); end; initialization DefaultDOMVendor := 'ADOM XML v4'; // DefaultDOMVendor := 'MSXML'; end. Using DOMVendor 'MSXML' the service works, but using 'ADOM XML v4' it blows up. Added this to QC please vote for it if you feel webservices on OSX is important. http://qc.embarcadero.com/wc/qcmain.aspx?d=99412 A: You can try to activate the XMLDocument before setting its XML... Let's show the code I mean: procedure TForm1.btn2Click(Sender: TObject); var s: string; begin xmldoc1.Active := False; xmldoc1.XML.Text := '<root><child>value</child></root>'; xmldoc1.Active := True; s := xmldoc1.XML.Text; ShowMessage(s); end; procedure TForm1.btn3Click(Sender: TObject); var s: string; begin xmldoc1.Active := False; xmldoc1.Active := True; xmldoc1.XML.Text := '<?xml version="1.0" encoding="UTF-8"?>' + sLineBreak + '<root><child>value</child></root>'; s := xmldoc1.XML.Text; ShowMessage(s); end; With btn2Click, I have: With btn3Click, I have: As I see the BOM for the first, but not with the second, I think it's ok... If any insert/update with a node on the TXMLDocument resets it to UTF-16LE, you can still replace the first line just before exporting the XML: procedure TForm1.btn2Click(Sender: TObject); var s: string; begin xmldoc1.Active := False; xmldoc1.XML.Text := '<root><child>value</child></root>'; xmldoc1.Active := True; // do what you need //before getting the xml xmldoc1.XML[0] := '<?xml version="1.0" encoding="UTF-8"?>'; s := xmldoc1.XML.Text; ShowMessage(s); end;
{ "language": "en", "url": "https://stackoverflow.com/questions/7542148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to retrieving a thumbnail of a video placed in a folder excluded from the media scan I'm trying to get a thumbnail of a video. I'm following this answer. My problem is that the video I want to make the thumbnail is an file in a cache folder with an .nomedia file and for that reason the video doesn't appear in the media scan and the returned cursor is empty. How can I solve that problem keeping the min sdk level =7? Thanks! Edit: Starting a bounty for the answer to that question: Retrieve a thumbnail for a video file in a folder at the filesystem which is excluded from media scan keeping the project Min SDK =7 A: Try force the scan of media file with a broadcast: sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); A: If you can make the video folder , i tell you to do this : Context ctx = getContext(); File folder = ctx.getDir("NewFolder", Context.MODE_PRIVATE); But like this answer says: You can't create such a folder on sdcard. Everything that's saved onto sdcard can be accessed by other applications. extracted from here
{ "language": "en", "url": "https://stackoverflow.com/questions/7542151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Accurately and seamlessly splitting text into two UILabels I'm trying to create a "wrapping" like effect for text around an image that has set dimensions. ___________ ........| ........| image label.1.| ........|___________ .................... .......label.2...... .................... .................... Here is the method im using right now: - (NSArray *)splitString:(NSString*)str maxCharacters:(NSInteger)maxLength { //this will split the string to add to two UILabels NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:1]; NSArray *wordArray = [str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; NSInteger numberOfWords = [wordArray count]; NSInteger index = 0; NSInteger lengthOfNextWord = 0; while (index < numberOfWords) { NSMutableString *line = [NSMutableString stringWithCapacity:1]; while ((([line length] + lengthOfNextWord + 1) <= maxLength) && (index < numberOfWords)) { lengthOfNextWord = [[wordArray objectAtIndex:index] length]; [line appendString:[wordArray objectAtIndex:index]]; index++; if (index < numberOfWords) { [line appendString:@" "]; } } [tempArray addObject:line]; } return tempArray; } I give it the maxCharacters value of where I want to split the text, which is the max height of the first UILabel. This method is essentially what I want, but sometimes the last line of the first UILabel is "higher" than others leaving a gap between the first UILabel and the second UILabel. Here is how I use the method: NSArray *splitStringArray = [self splitString:eventRecord.summary maxCharacters:280]; UILabel *firstSumValue = [[UILabel alloc] init]; NSString *firstSumString = [splitStringArray objectAtIndex:0]; CGSize maxFirstSumSize = CGSizeMake(185.0,150.0); UIFont *firstSumFont = [UIFont fontWithName:@"HelveticaNeue-Bold" size:12]; CGSize firstSumStringSize = [firstSumString sizeWithFont:firstSumFont constrainedToSize:maxFirstSumSize lineBreakMode:firstSumValue.lineBreakMode]; CGRect firstSumFrame = CGRectMake(10.0, presentedValue.frame.origin.y + presentedValue.frame.size.height, 185.0, firstSumStringSize.height); firstSumValue.frame = firstSumFrame; firstSumValue.font = [UIFont fontWithName:@"HelveticaNeue" size:12]; firstSumValue.lineBreakMode = UILineBreakModeWordWrap; firstSumValue.numberOfLines = 0 ; [self.mainScrollView addSubview:firstSumValue]; firstSumValue.text = [splitStringArray objectAtIndex:0]; UILabel *secondSumValue = [[UILabel alloc] init]; NSInteger isSecond = 0; //no if([splitStringArray count] > 1){ isSecond = 1; //yes NSString *secondSumString = [splitStringArray objectAtIndex:1]; CGSize maxSecondSumSize = CGSizeMake(310.0,9999.0); UIFont *secondSumFont = [UIFont fontWithName:@"HelveticaNeue-Bold" size:12]; CGSize secondSumStringSize = [secondSumString sizeWithFont:secondSumFont constrainedToSize:maxSecondSumSize lineBreakMode:secondSumValue.lineBreakMode]; CGRect secondSumFrame = CGRectMake(10.0, firstSumValue.frame.origin.y + firstSumValue.frame.size.height, 310.0, secondSumStringSize.height); secondSumValue.frame = secondSumFrame; secondSumValue.font = [UIFont fontWithName:@"HelveticaNeue" size:12]; secondSumValue.lineBreakMode = UILineBreakModeWordWrap; secondSumValue.numberOfLines = 0 ; [self.mainScrollView addSubview:secondSumValue]; secondSumValue.text = [splitStringArray objectAtIndex:1]; } How do I keep everything consistent and aligned properly. Perhaps, there is a better method one could recommend. Not core text because it's out of my scope of knowledge. A: Consider using a UIWebView instead, with the layout defined in a local HTML file. It can save you a lot of headache rather than trying to deal with complex layouts by hand.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Cocoa Design Patterns for Authentication After developing for iOS for some time now, I have gotten comfortable with the language and am trying to get better at designing well-structured applications. Initially my focus was on seeing something functional, so I ended up with gigantic view controllers which were horribly architected. Now, I'm learning to separate my model classes and trying to keep my architecture more modular. I would greatly appreciate any advice on the following sample situation: I am developing an app which (among other things) pulls a list of articles from a server and displays them. However, the user has to be authenticated to be able to retrieve this list. Because other aspects of the application utilize the same authentication, I want a single class to manage the authentication. The goal is that when any controller requests data from the model which requires authentication, if the user is not authenticated, the authentication prompt will automatically be presented. I expect to create the following: VIEW - ArticlesView - AuthenticationView CONTROLLER - ArticlesViewController - AuthenticationViewController - ArticleManager (singleton) - AuthenticationProvider (singleton) MODEL - Article When the application first loads, execution will reach the ArticlesViewController's viewDidLoad method. In this method, I get a shared instance of the ArticleManager, specify the authentication class to be the authentication provider, and ask it for a list of recent articles. // ArticlesViewController.m -(void) viewDidLoad { ... AuthenticationProvider *authProvider = [AuthenticationProvider sharedInstance]; [[ArticleManager sharedInstance] setAuthenticationProvider:authProvider]; [[ArticleManager sharedInstance] fetchNewArticles]; } If no authentication was necessary, the ArticleManager would successfully retrieve the list from the server and post a notification letting anyone interested know that the articles have been retrieved. The ArticlesViewController would handle this notification: // ArticlesViewController.m - (void) handleNewArticlesNotification:(NSNotification *)note { [self updateUI]; } However, if authentication is required, the user needs to be presented with a login screen before the articles can be fetched and displayed. So I imagine the ArticleManager doing something like this: // ArticleManager.m - (void) fetchNewArticles { if( [self.authenticationProvider isAuthenticated] ){ // go fetch list from the web } else { [self.authenticationProvider presentAuthenticationRequest]; } } Now, at this point I run into some difficulty fleshing out the remainder of the details. The AuthenticationProvider could present the AuthenticationViewController as a modal view controller from the AppDelegate's window's rootViewController and AuthenticationProvider would be the delegate of AuthenticationViewController. The AuthenticationViewController would probably be dumb to the actual actions that it is taking, and would have it's delegate (AuthenticationProvider) do the work to authenticate the user. Once the user is authenticated, AuthenticationProvider would dismiss the modal view controller (AuthenticationViewController). But how does ArticleManager get notified that the authentication that it requested has completed? It would need to be able to handle both successful and failed authentication attempts separately. A successful authentication would eventually result in fetchNewArticles being called again. One thought is for ArticleManager to be a delegate of AuthenticationProvider. This seems to work in this case, but there are other Model Managers which could also rely on AuthenticationProvider. Presumably this would be resolved if AuthenticationProvider is not a singleton. Would that be a decent design approach? Thanks for taking the time to help me understand a good design approach. I have coded this a couple of times, but always get stuck/confused toward the end. Also, if the entire approach needs to be re-architected, please feel free to point me in another direction. Many thanks! A: I have always used Global NSNotifications to post when a user has logged in or logged out. Every view controller that presents data differently can subscribe to those notifications and update themselves accordingly when an event happens. This is nice, because you may already have other views (perhaps in other tabs) that have already loaded and will need to refresh when a user has logged in or out. A: One thought is for ArticleManager to be a delegate of AuthenticationProvider. This seems to work in this case, but there are other Model Managers which could also rely on AuthenticationProvider. Presumably this would be resolved if AuthenticationProvider is not a singleton. Would that be a decent design approach? Perhaps instead you could have the AuthenticationProvider singleton provide AuthenticationSession objects, set the caller as the delegate of the AuthenticationSession, and ask the AuthenticationSession to perform the authentication.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why did the Git "source" change from "refs/heads/qux" to "refs/remotes/origin/qux"? The following commands reveal what I just did: Z:\www\gg\web\tests\sample-repo-cloned>git log --all --source --graph * commit ce7ae79a2b993b780002dbc5eac650fa49427df0 refs/heads/qux | Author: myname <myemail@gmail.com> | Date: Sun Sep 25 00:24:42 2011 +0300 | | qux another | * commit ef2ea79f40d8e77e47cba31954ef2093c534cc17 refs/heads/qux | Author: myname <myemail@gmail.com> | Date: Sun Sep 25 00:15:56 2011 +0300 | | qux | Z:\www\gg\web\tests\sample-repo-cloned>git branch * master qux Z:\www\gg\web\tests\sample-repo-cloned>git checkout qux Switched to branch 'qux' Z:\www\gg\web\tests\sample-repo-cloned>notepad2 qux.txt Z:\www\gg\web\tests\sample-repo-cloned>git add qux.txt Z:\www\gg\web\tests\sample-repo-cloned>git commit -m "qux more stuff" [qux 1d18327] qux more 1 files changed, 2 insertions(+), 1 deletions(-) Z:\www\gg\web\tests\sample-repo-cloned>git log --all --source --graph * commit 1d183278e78b8896d882822dacb4aad5bb8cf1bd refs/heads/qux | Author: myname <myemail@gmail.com> | Date: Sun Sep 25 00:39:06 2011 +0300 | | qux more | * commit ce7ae79a2b993b780002dbc5eac650fa49427df0 refs/remotes/origin/qux | Author: myname <myemail@gmail.com> | Date: Sun Sep 25 00:24:42 2011 +0300 | | qux another | * commit ef2ea79f40d8e77e47cba31954ef2093c534cc17 refs/remotes/origin/qux | Author: myname <myemail@gmail.com> | Date: Sun Sep 25 00:15:56 2011 +0300 | | qux | My question is this: why did the first two commits change their "source" from refs/heads/qux to refs/remotes/origin/qux? They did that after the third commit. I don't understand this. What's the logic behind that "source"? It seems to be changing randomly. A: The --source parameter to git log is just a bit confusing, I'm afraid. It means that each commit will be shown with the ref by which it was found - it doesn't mean that it will list all refs that contain that commit. In your case, the hypothetical output of a similar option that included all of refs that contain that commit would be: * commit 1d1832 refs/heads/qux | Author: myname <myemail@gmail.com> | Date: Sun Sep 25 00:39:06 2011 +0300 | | qux more | * commit ce7ae7 refs/heads/qux refs/remotes/origin/qux | Author: myname <myemail@gmail.com> | Date: Sun Sep 25 00:24:42 2011 +0300 | | qux another | * commit ef2ea7 refs/heads/qux refs/remotes/origin/qux | Author: myname <myemail@gmail.com> | Date: Sun Sep 25 00:15:56 2011 +0300 | | qux ... and you can confirm that by browsing the history with gitk --all, or trying git branch -a --contains ef2ea7, etc. So, all that's happening is that when you ran the git log the second time was that it checked the origin/qux remote-tracking branch first, and then the qux branch that you're working on. As to why that order should be different between the two invocations, I'm afraid I'm not sure. The remote-tracking branch is one behind since you haven't updated it via a git push or a git fetch.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python: Tkinter Menu entries do not pass correct value I am currently working on a GUI (Tkinter) for my application. I am having problems with creating a couple of dropdown menus that should be used to choose a date. The application that I have written creates the desired menus with labels, however, by clicking any of the buttons only the value of the last menu entry gets passed to the tkinter mutable IntVar. This is a portion of the code that emphasizes my problem. year should be the year that the user clicks upon, however, it is always 2011. from Tkinter import * import tkFileDialog as dialog import datetime import calendar window = Tk() text = Text(window) text.pack() year = IntVar() list_of_years = [1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011] def year_seter(value): year.set(value) menubar = Menu(window) yearmenu = Menu(menubar) for the_year in list_of_years: yearmenu.add_command(label=str(the_year), command=lambda : year_seter(the_year)) menubar.add_cascade(label = 'Year', menu=yearmenu) window.config(menu=menubar) label = Label(window, textvariable=year) label.pack() window.mainloop() Can somebody please explain to me, why is this happening? Thank you for your time! A: Change the command to: lambda the_year=the_year: year_seter(the_year) The problem has to do with how Python looks up the value of the_year. When you use lambda : year_seter(the_year) the_year is not in the local scope of the lambda function, so Python goes looking for it in the extended, global, then builtin scopes. It finds it in the global scope. The for-loop uses the_year, and after the for-loop ends, the_year retains its last value, 2011. Since the lambda function is executed after the for-loop has ended, the value Python assigns to the_year is 2011. In contrast, if you use a parameter with a default value, the default value is fixed at the time the function (lambda) is defined. Thus, each lambda gets a different value for the_year fixed as the default value. Now when the lambda is called, again Python goes looking for the value of the_year, but this time finds it in the lambda's local scope. It binds the default value to the_year. PS. * *You could also forgo defining year_seter and just do: lambda the_year=the_year: year.set(the_year) *list_of_years = range(1995,2012) also works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Ruby EventMachine with PostgreSQL I know that for mysql em-mysql exists as an asynchronous interface driver to MySQL and that Active Record, with some modification, can make immediate use of. I believe Sequel has this capability already. I also understand that the pg gem exposes PostgreSQL's native async API. My question: is there any Ruby ORM that natively interoperates with EventMachine when the backing database is PostgreSQL? If not, what needs to be done to retrofit Sequel to support async PostgreSQL? ActiveRecord? A: This looks like it works with ActiveRecord: https://github.com/mperham/em_postgresql
{ "language": "en", "url": "https://stackoverflow.com/questions/7542167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Find public key from certificate as a xml string i need to find the public key from certificate as xml string. I can take the public key only as a string with this method: public string CelesiPublik() { X509Certificate cer; cer = X509Certificate.CreateFromCertFile("C://certificate//EdonBajrami.crt"); string Celesi = cer.GetPublicKeyString(); return Celesi; } and then i take this value to the another method. Celesi value now has take celesiPublik celesiPublik = e.Result; string NrTelefonit = "044-419-109"; string salt = "VotimiElektronikKosove"; AesManaged aes = new AesManaged(); Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(celesiPublik,Encoding.UTF8.GetBytes(salt)); aes.Key = rfc2898.GetBytes(aes.KeySize / 8); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(celesiPublik); rsa.Encrypt(aes.Key, false); but it shows me error. How can i resolve this problem? GregS i cannot use in Windows Phone 7 X509Certificate2. I take my public key with the method: `X509Certificate cer = new X509Certificate("C://certificate//EdonBajrami.crt"); string publicKey = cer.GetPublicKeyString();` i can take the public key. Then in another method i take value of the publicKey to another string variable Key: `string Key = publicKey; //-----First------ RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); //---------- RSAParameters RSAKeyInfo = new RSAParameters(); byte[] celesibyte = System.Text.Encoding.UTF8.GetBytes(celesiPublik); byte[] Exponent = { 1, 0, 1 }; RSAKeyInfo.Modulus = celesibyte; RSAKeyInfo.Exponent = Exponent; rsa.ImportParameters(RSAKeyInfo); //----------- /* rsa.FromXmlString(celesi2Publik); */ string edon = "Edon"; byte[] edon1 = Encoding.UTF8.GetBytes(edon); byte[] edon2 = rsa.Encrypt(edon1, false);' but it sends me data that is 506 byte, i dont understand why, what is a problem ? A: As far as I can tell the X509Certificate class is nearly useless. Perhaps that is why there is a class X509Certificate2? Use the X509Certificate2 class. You can create an RSACryptoServiceProvider directly from the public key like the following: X509Certificate2 cert = new X509Certificate2(X509Certificate.CreateFromCertFile("C://certificate//EdonBajrami.crt")); RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) cert.PublicKey.Key;
{ "language": "en", "url": "https://stackoverflow.com/questions/7542169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Incorrect file permissions when calling C's open() function from fortran I have a fortran program which calls a C function and opens a file using open() main.f90: PROGRAM TEST integer :: oflag, mode !Set oflag to O_CREAT|O_RDWR oflag = 66 mode = 600 call test2("test.txt", oflag, mode) END PROGRAM test.c: #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #pragma weak test2_ = test2 #pragma weak test2__ = test2 #pragma weak TEST2 = test2 void test2(char* filename, int* flag, int* mode) { int fd; if(-1 == (fd = open(filename, *flag, *mode))) puts("Returned -1"); } I compile as: gcc -c test.c gfortran main.f90 test.o When I run the program, it creates the file test.txt, but with incorrect permissions: ---x--x--T 1 xyz users 0 2011-09-24 16:40 test.txt when it should have been -rw------- 1 xyz users 0 2011-09-24 16:45 test.txt If I call this function from another C program, it works fine. Can someone point out what is going wrong? Specs: 64 bit linux GNU Fortran (SUSE Linux) 4.5.0, GCC (SUSE Linux) 4.5.0 Thanks, Kshitij A: Your constants are wrong because permissions are typically specified in octal. Try this program: #include <stdio.h> #include <fcntl.h> int main(void) { printf("oflag=%d mode=%d\n", O_CREAT|O_RDWR, S_IRUSR|S_IWUSR); } I get: oflag=66 mode=384 600 octal eqals 384 decimal. A: open expects you to give it a value for the mode in octal, not decimal (this is why you basically always see an extra leading zero when dealing with modes in C code, since in C you write an octal literal with a leading zero). 600 in decimal is 1130 in octal. 1130 would correspond to ---x-wx--T, and you likely have a umask of 022, leaving you with ---x--x--T. I believe you can specify an octal value in Fortran like this: o'600' (that's the letter o and then the octal value inside single quotes). Or, as David Schwartz suggested in his answer, you can just use the decimal equivalent of the mode you want. That's likely to be confusing when you look back at it later, though. Edit: M. S. B. has pointed out that, while GNU Fortran may be more permissive, to comply with the standard you'd have to declare an octal constant in a data statement or (since Fortran 2003) as int(o'600'). A: Here is an example using the Fortran ISO C Binding for a standard & portable interface between the Fortran and C portions. On my computer I found O_CREAT|O_RDWR to have a different value, i.e., 514, so setting flag to a specific value is not portable. PROGRAM TEST use iso_c_binding implicit none interface test2_interface subroutine test2 ( filename, flag, mode ) bind (C, name="test2") import character (kind=c_char, len=1), dimension (100), intent (in) :: filename integer (c_int), intent (in), VALUE :: flag, mode end subroutine test2 end interface test2_interface integer (c_int) :: oflag, mode character (kind=c_char, len=100) :: filename !Set oflag to O_CREAT|O_RDWR oflag = 66 ! incorrect value ... not used mode = int ( o'600', c_int) filename = "test.txt" // C_NULL_CHAR call test2 (filename, oflag, mode) END PROGRAM and #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <fcntl.h> void test2(char* filename, int flag, int mode) { int fd; printf ( "filename = '%s'\n", filename ); flag = O_CREAT | O_RDWR; printf ( "flag = %d\n", flag ); printf ( "mode = octal %o\n", mode ); if(-1 == (fd = open(filename, flag, mode))) puts("Returned -1"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7542179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: User permissions based MEF components I did my first steps toward MEF few month ago and everything seemed to be okay till now. What I want to do is to use MEF in now of my real applications and load or we can say display UI components based on authenticated users permissions. I am developing patient management system for clinic and I want to implement scenario where MEF composed UI components are displayed based on user type. for example if authenticated user is doctor I want to show particular components and hid others. What I am trying to achieve is something like ISystemComponent which has some properties and methods so administration can control each user access level and based on DB records MEF composed controls will be displayed to the end-user. I also think of using MetaData interface while exporting components so using this how can I get the desired result? any right direction will be appreciated A: I did this by using an metadata attribute for a module ID and a table that has the permissions . Do a ImportMany on the interface then filter it based on the metadata attribute using reflection and compare to the permissions in the table. This blog post describes all the MEF involved. http://blogs.microsoft.co.il/blogs/bnaya/archive/2010/01/20/mef-for-beginner-metadata-part-8.aspx Other Links.. http://blogs.microsoft.co.il/blogs/bnaya/archive/2010/01/09/mef-for-beginner-toc.aspx http://mef.codeplex.com/wikipage?title=Exports%20and%20Metadata&referringTitle=Guide MEF Plugins with Security and Profiles Efficency MEF with ImportMany and ExportMetadata This will show how to import from xaml http://blogs.microsoft.co.il/blogs/bnaya/archive/2010/03/20/mef-for-beginner-import-from-xaml-part-11.aspx A: The article here details using AOP to inject security concerns into MEF. This could be one way of doing this - I havent' found anything in MEF that would allow this sort of functionality elsewhere. A: I think PRISM can do exactly what you've described. Take a look at this Code Project article. You can create several module catalogs (according to user permissions), and load catalog dynamically from XML as described Here: var catalog = ModuleCatalog.CreateFromXaml(new Uri("catalog.xaml", UriKind.Relative)); A: I implemented this in WPF / MVVM using Cinch and backend SQL tables that mapped controls to roles and view permissions. This allows you to control permissions through the viewmodel and change visibility at any point. Cinch assists with some of the drudgery of MVVM while allowing you to leverage MEF through MeffedMVVM or Prism.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Need help converting PRISM Unity Module Init to PRISM MEF Module Init I need help converting the following class for use in a program that I am developing. The original was a demo program from IdeaBlade called "PRISM EXPLORER" based on Unity. I need help converting one part from UNITY to MEF. I handled everything else. Just stuck on this one. I already marked my classes with the MEF "[EXPORT(typeof(XXX))]" and I think I need to use the "ComposeExportedValue" somehow. The confusing part is finding the equivelant for this line: var provider = (IEntityManagerProvider) _container.Resolve<IPersistenceGateway>(); _container.RegisterInstance<IEntityManagerProvider>(provider); THANKS! The following is the entire class I need to convert. You can find the original here: Ideablade PRISM Page using Microsoft.Practices.Composite.Modularity; using Microsoft.Practices.Composite.Regions; using Microsoft.Practices.Unity; using PrismExplorer.Infrastructure; namespace ModelExplorer.Explorer { public class ExplorerModule : IModule { private readonly IUnityContainer _container; public ExplorerModule(IUnityContainer container) { _container = container; } public void Initialize() { InitializeContainer(); SetViews(); } // ToDo: Consider getting from configuration private void InitializeContainer() { RegisterGatewayAndEntityManagerProvider(); _container.RegisterType<IQueryRepository, QueryRepository>( new ContainerControlledLifetimeManager()); // singleton } private void RegisterGatewayAndEntityManagerProvider() { _container.RegisterType<IPersistenceGateway, PrismExplorerPersistenceGateway>( new ContainerControlledLifetimeManager()); // singleton var provider = (IEntityManagerProvider) _container.Resolve<IPersistenceGateway>(); _container.RegisterInstance<IEntityManagerProvider>(provider); } private void SetViews() { var regionManager = _container.Resolve<IRegionManager>(); var view = _container.Resolve<ExplorerView>(); regionManager.AddToRegion(RegionNames.MainRegion, view); regionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(ExplorerView)); } // Destructor strictly to demonstrate when module is GC'd //~MevModule() { // System.Console.WriteLine("Goodbye, MevModule"); //} } } A: The two corresponding methods on a CompositionContainer are ComposeExportedValue<T>(...), which allows you to add a specific instance to the container, and GetExportedValue<T>(...) which gets an instance of T from the container. If you can design your types in a way to reduce this use of service location and try and prefer constructor injection, it will make your code much easier to maintain and test. E.g., could your code be transformed into: [Export(typeof(IModule))] public class ExplorerModule : IModule { [ImportingConstructor] public ExplorerModule(IPersistenceGateway gateway) { } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7542185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which model is the fastest using linq, foreign key relationships or local lists? Some basics I have two tables, one holding the users and one holding a log with logins. The user table holds something like 15000+ users, the login table is growing and is reaching 150000+ posts. The database is built upon SQL Server (not express). To administer the users I got a gridview (ASPxGridView from Devexpress) that I populate from an ObjectDatasource. Is there any general do’s and donts I should know about when summarizing the number of logins a user made. Things are getting strangely slow. Here is a picture showing the involved tables. I’ve tried a few things. DbDataContext db = new DbDataContext(); // Using foregin key relationship foreach (var proUser in db.tblPROUsers) { var count = proUser.tblPROUserLogins.Count; //... } Execution time: 01:29.316 (1 minute and 29 seconds) // By storing a list in a local variable (I removed the FK relation) var userLogins = db.tblPROUserLogins.ToList(); foreach (var proUser in db.tblPROUsers) { var count = userLogins.Where(x => x.UserId.Equals(proUser.UserId)).Count(); //... } Execution time: 01:18.410 (1 minute and 18 seconds) // By storing a dictionary in a local variable (I removed the FK relation) var userLogins = db.tblPROUserLogins.ToDictionary(x => x.UserLoginId, x => x.UserId); foreach (var proUser in db.tblPROUsers) { var count = userLogins.Where(x => x.Value.Equals(proUser.UserId)).Count(); //... } Execution time: 01:15.821 (1 minute and 15 seconds) The model giving the best performance is actually the dictionary. However I you know of any options I'd like to hear about it, also if there's something "bad" with this kind of coding when handling such large amounts of data. Thanks ======================================================== UPDATED With a model according to BrokenGlass example // By storing a dictionary in a local variable (I removed the FK relation) foreach (var proUser in db.tblPROUsers) { var userId = proUser.UserId; var count = db.tblPROUserLogins.Count(x => x.UserId.Equals(userId)); //... } Execution time: 02:01.135 (2 minutes and 1 second) In addition to this I created a list storing a simple class public class LoginCount { public int UserId { get; set; } public int Count { get; set; } } And in the summarizing method var loginCount = new List<LoginCount>(); // This foreach loop takes approx 30 secs foreach (var login in db.tblPROUserLogins) { var userId = login.UserId; // Check if available var existing = loginCount.Where(x => x.UserId.Equals(userId)).FirstOrDefault(); if (existing != null) existing.Count++; else loginCount.Add(new LoginCount{UserId = userId, Count = 1}); } // Calling it foreach (var proUser in tblProUser) { var user = proUser; var userId = user.UserId; // Count logins var count = 0; var loginCounter = loginCount.Where(x => x.UserId.Equals(userId)).FirstOrDefault(); if(loginCounter != null) count = loginCounter.Count; //... } Execution time: 00:36.841 (36 seconds) Conclusion so far, summarizing with linq is slow, but Im getting there! A: Perhaps it would be useful if you tried to construct an SQL query that does the same thing and executing it independently of your application (in SQL Server Management Studio). Something like: SELECT UserId, COUNT(UserLoginId) FROM tblPROUserLogin GROUP BY UserId (NOTE: This just selects UserId. If you want other fields from tblPROUser, you'll need a simple JOIN "on top" of this basic query.) Ensure there is a composite index on {UserId, UserLoginId} and it is being used by the query plan. Having both fields in the index and in that order ensures your query can run without touching the tblPROUserLogin table: Then benchmark and see if you can get a significantly better time than your LINQ code: * *If yes, then you'll need to find a way to "coax" the LINQ to generate a similar query. *If no, then you are already as fast as you'll ever be. --- EDIT --- The follwing LINQ snippet is equivalent to the query above: var db = new UserLoginDataContext(); db.Log = Console.Out; var result = from user_login in db.tblPROUserLogins group user_login by user_login.UserId into g select new { UserId = g.Key, Count = g.Count() }; foreach (var row in result) { int user_id = row.UserId; int count = row.Count; // ... } Which prints the following text in the console: SELECT COUNT(*) AS [Count], [t0].[UserId] FROM [dbo].[tblPROUserLogin] AS [t0] GROUP BY [t0].[UserId] -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1 --- EDIT 2 --- To have the "whole" user and not just UserId, you can do this: var db = new UserLoginDataContext(); db.Log = Console.Out; var login_counts = from user_login in db.tblPROUserLogins group user_login by user_login.UserId into g select new { UserId = g.Key, Count = g.Count() }; var result = from user in db.tblPROUsers join login_count in login_counts on user.UserId equals login_count.UserId select new { User = user, Count = login_count.Count }; foreach (var row in result) { tblPROUser user = row.User; int count = row.Count; // ... } And the console output shows the following query... SELECT [t0].[UserId], [t0].[UserGuid], [t0].[CompanyId], [t0].[UserName], [t0].[UserPassword], [t2].[value] AS [Count] FROM [dbo].[tblPROUser] AS [t0] INNER JOIN ( SELECT COUNT(*) AS [value], [t1].[UserId] FROM [dbo].[tblPROUserLogin] AS [t1] GROUP BY [t1].[UserId] ) AS [t2] ON [t0].[UserId] = [t2].[UserId] -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1 ...which should be very efficient provided your indexes are correct: A: The second case should always be the fastest by far provided you drop the ToList() so counting can be done on the database side, not in memory: var userId = proUser.UserId; var count = db.tblPROUserLogins.Count(x => x.UserId == userId); Also you have to put the user id into a "plain" primitive variable first since EF can't deal with mapping properties of an object. A: Sorry, doing this blind since I'm not on my normal computer. Just a couple of questions * *do you have an index on the user id in the logins table *have you tried a view specifically crafted for this page? *are you using paging to get the users, or trying to get all counts at once? *have you run sql profiler and watched the actual sql being sent? Does something like this work for you? var allOfIt = from c in db.tblProUsers select new { User = c, Count = db.tblProUserLogins.Count(l => l.UserId == c.UserId) } .Skip(pageSize * pageNumber) .Take(pageSize) // page size
{ "language": "en", "url": "https://stackoverflow.com/questions/7542190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to use Opencv for Document Recognition with OCR? I´m a beginner on computer vision, but I know how to use some functions on opencv. I´m tryng to use Opencv for Document Recognition, I want a help to find the steps for it. I´m thinking to use opencv example find_obj.cpp , but the documents, for example passport, has some variables, name, birthdate, pictures. So, I need a help to define the steps for it, and if is possible how function I have to use on the steps. I'm not asking a whole code, but if anyone has any example link or you can just type a walkthrough, it is of great help. A: There are two very different steps involved here. One is detecting your object, and the other is analyzing it. For object detection, you're just trying to figure out whether the object is in the frame, and approximately where it's located. The OpenCv features framework is great for this. For some tutorials and comprehensive sample code, see the OpenCv features2d tutorials and especially the feature matching tutorial. For analysis, you need to dig into optical character recognition (OCR). OpenCv does not include OCR libraries, but I recommend checking out tesseract-ocr, which is a great OCR library. If your documents have a fixed structured (consistent layout of text fields) then tesseract-ocr is all you need. For more advanced analysis checking out ocropus, which uses tesseract-ocr but adds layout analysis.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: how do I create list of unique values and systematically store them in localstorage I'm trying to build a history list of clicked clicked page elements and store that list into HTML local storage, to be later displayed back to the user. The main pre-requisite is that the list cannot contain duplicates, so for example if the user clicks on item A and then on item B and again back on item A, only A and B are recorded. The third click is not recorded because it is not unique. I'm also using persist.js. I noticed that I am able to name the storage and give it a key and both are stored together in the real key of the localstorage thus: myStorageName>myKeyand my value is whatever I put there. Here's the thing. I know you can store stringyfied JSON there but my list is built up from simple javascript variables one at at time. I know what to do for the first click: myStorageName.set(myKey, myCurrentElementId); // myCurrentElementId = this.id now on the second click this is where I'm beginning to getting stuck. There is the original variable value already stored, now I want to append the new variable value. Assume that I can get the value from the store like this: var dataExtract = myStorageName.get(myKey); myObject = JSON.parse(dataExtract); But how do I then turn this into a JSONstring -able thing (sorry I don't even know what it should be) that contains only a list of unique values. Does this make any sense to anyone? A: First of all, you don't want to keep writing to/from localStorage everytime a link is clicked, because this'll slow down your page. Keep an updated Array populated with the element ids, then write to localStorage before the user navigates away from the page (by binding to the window's onbeforeunload event, for instance). First: var clickedLinks = []; // this Array will hold the ids of the clicked links function uniqueClick(id){ return !~clickedLinks.indexOf(id); // this tests whether the id is already in the Array }; In your click handler: if(uniqueClick(this.id)){ clickedLinks.push(this.id); // append the new element id to the Array } Bind to window.onunload to save the Array before the user navigates from the page: window.onunload = function(){ localStorage.setItem('clickedLinks',JSON.stringify(clickedLinks)); // stringify the Array and save to localStorage } To retrieve clickedLinks on subsequent page visit: // convert the String back to an Array; try/catch used here in case the value in localStorage is modified and unable to be parsed, in which case clickedLinks will be initialized to an empty Array try{ var clickedLinks = JSON.parse(localStorage.getItem('clickedLinks')) || []; }catch(e){ var clickedLinks = []; } You may want to replace the first line (var clickedLinks = [];) with this last bit of code, as it will initialize the Array if it doesn't exist. UPDATE: IE8 does not support Array.indexOf. Alternatives might be: * *use jQuery's $.inArray by replacing !~clickedLinks.indexOf(id); with !~$.inArray(id, clickedLinks); *Detect whether Array.prototype.indexOf is supported. If not, shim it with the code provided on this page. A: Your model has an error. At the first time, you save a primitive value. Then, you want to "append" another value to it. Seems like you actually want to use an object: var myObj = localStorage.getItem("myName"); if(myObj) myObj = JSON.parse(myObj); //Variable exists else myObj = {}; //Elsem create a new object function appendNewValue(name, value){ myObj[name] = value; localStorage.setItem("myName", JSON.stringify(myObj)); /* Saves data immediately. Instead of saving every time, you can also add this persistence feature to the `(before)unload` handler. */ } A: I suggest to define in your code this: localStorage.set= function(key,val) { localStorage.setItem(JSON.stringify(val)); } localStorage.get = function(key,defval) { var val = localStorage.getItem(key); if( typeof val == "undefined" ) return defval; return JSON.parse(val); } and use them instead of get/setItem. They will give you ready to use JS values that you can use in the way you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to prevent timer reset on page refresh? I'm using jQuery countdown in a script, but I can't figure out how to prevent the timer from resetting on a page reload. I'm hoping someone knows how or can give me a suggestion? I'm using PHP, so I thought maybe at some point I can add a variable to a $_SESSION, but is that enough? A: If you want to persist a count value from one page to the next, you will have to store the current counter somewhere before the page refresh and read it back in from the new page and initialize your counter with the saved value. The classic place to store something like that would be in a cookie, but you could also store it in HTML5 local storage (newer browsers only) or by passing it in a query parameter when loading the new page. Since the counter is a client-side counter, I'm not sure how you could use a server session to help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to avoid UAC for autorun app in Program Files? Firstly I want to emphasize that I'm not trying to do anything "nasty" or "hackerish", nor am I trying to hide anything from user here. During installations (using InstallShield LE) of my application user is prompted by Windows UAC to allow it to run in Administrator mode; If user accepts it - installation continues (standard behavior) and user again can check the option to add this program to autorun list (by adding a registry key to HKLM/../Run). All is fine and normal. But after every Windows restart, when this application starts, UAC kicks in and asks for user permission. Question is, how to avoid it, since it's a bit annoying (yet my app needs Administrator privileges to run)? I mean user already granted such permissions on installation, so I cannot see a reason why it needs to be prompted on every startup? Moreover, I believe most antivirus software and such, also require elevated permissions to operate, but UAC doesn't prompt for it at Windows Startup. Thank you for any advises, information, comments or solutions. A: * *Does your application really need to start elevated? Or will it need to elevated access later when the user uses it to perform an action? If you can, drop the later admin task into a separate exe, allowing the main exe to start with no elevation - when you shellexecute the worker process later it will UAC on demand. *At install time, as you have noted, you have elevated the installer. If you want to run elevated code on subsequent runs, automatically, this is the point to install a service - which is what all those other apps you mentioned do. A: You can't get around UAC for a process started in an interactive session. You could use a service running as a privileged user but you would be far better off finding a way to do whatever you do without requiring admin rights. A: It's not possible for a program to run elevated without prompting. What you want to do is factor those portions of your application that need elevation into a windows service that runs as system. Then your autostarting application can make remoting calls to the service to delgate those activities that the user can't do without elevating. A: Not done it but I found this article Selectively disable UAC for your trusted Vista applications that says use 'Application Compatibility Toolkit' from microsoft. The Compatibility Administrator allows you to create a database of compatibility fixes that will allow you to run certain applications without an accompanying UAC. * *Run the Compatibility Administrator as admin *select a new database template *Click the Fix button on the toolbar. When you see the Create New Application Fix wizard ... enter details about your app *Select a Compatibility Level *Select RunAsInvoker as the fix It seems that the last one Selecting the RunAsInvoker option will allow the application to launch without requiring the UAC prompt. Should do what you want provided that the invoker is admin and I think you can do this at start up using the scheduler : Create Administrator Mode Shortcuts Without UAC Prompts in Windows 7 or Vista As you can see it runs your app in the compatibility mode which may or may not be acceptable for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Texture transform matrix in a constantbuffer not working properly I'm trying to clip a texture by hardcoding the texture coordinates through 0 and 1, and then sending a constantbuffer containing a 3x3 texture transform matrix to the vertexshader. However, the texture is not rendering as I expected it to. I'm not sure where I went wrong. Could someone help? See code below. For testing, I'm trying to use an Identity matrix to keep the texture coordinates untouched, but the texture shows up transformed in a very weird way. This is the texture: (the colours showing up are actually transparent areas, except the black colour and the softer red colour of the heart) Transformed texture: HLSL: cbuffer cbChangesPerFrame : register( b0 ) { matrix g_Mvp; }; cbuffer cbTexTransform : register( b2 ) { float3x3 g_TexTransform; }; Texture2D g_ColorMap : register(t0); SamplerState g_ColorSampler : register(s0); struct VS_Input { float4 pos : POSITION0; float2 tex0 : TEXCOORD0; }; struct PS_Input { float4 pos : SV_POSITION0; float2 tex0 : TEXCOORD0; }; PS_Input VS_Main(VS_Input vertex) { PS_Input vsOut = (PS_Input)0; vsOut.pos = mul(vertex.pos,g_Mvp); //vsOut.tex0 = vertex.tex0; float3 coord = float3(vertex.tex0, 1.0); coord = mul(coord, g_TexTransform); vsOut.tex0 = coord.xy ; return vsOut; } float4 PS_Main( PS_Input frag ) : SV_TARGET { return g_ColorMap.Sample( g_ColorSampler, frag.tex0 ); } VBuffer hardcoded: Vertex::PosTex vertices[]= { {XMFLOAT3( 0.5f, 0.5f, 1.0f ), XMFLOAT2( 1.0f, 0.0f )}, {XMFLOAT3( 0.5f, -0.5f, 1.0f ), XMFLOAT2( 1.0f, 1.0f )}, {XMFLOAT3( -0.5f, -0.5f, 1.0f ), XMFLOAT2( 0.0f, 1.0f )}, {XMFLOAT3( -0.5f, -0.5f, 1.0f ), XMFLOAT2( 0.0f, 1.0f )}, {XMFLOAT3( -0.5f, 0.5f, 1.0f ), XMFLOAT2( 0.0f, 0.0f )}, {XMFLOAT3( 0.5f, 0.5f, 1.0f ), XMFLOAT2( 1.0f, 0.0f )} }; Matrix definition: XMFLOAT3X3 f3x3; f3x3.m[0][0] = 1.0f; f3x3.m[0][1] = 0.0f; f3x3.m[0][2] = 0.0f; f3x3.m[1][0] = 0.0f; f3x3.m[1][1] = 1.0f; f3x3.m[1][2] = 0.0f; f3x3.m[2][0] = 0.0f; f3x3.m[2][1] = 0.0f; f3x3.m[2][2] = 1.0f; GAME_MANAGER->GMSetTexTransformMatrix(f3x3); Game_Manager GMSetTransformMatrix() definition: void GameManager::GMSetTexTransformMatrix( const XMFLOAT3X3& rkTexTransform ) { m_pContext->UpdateSubresource(m_pTexTransformCB,0,0,&rkTexTransform,0,0); m_pContext->VSSetConstantBuffers(2,1,&m_pTexTransformCB); } Buffer Initialisation: ZeroMemory(&constDesc, sizeof(constDesc)); constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; constDesc.ByteWidth = 48; constDesc.Usage = D3D11_USAGE_DEFAULT; result = m_pDevice->CreateBuffer(&constDesc,0,&m_pTexTransformCB); A: The problem is the 16 byte alignment. An XMFLOAT3X3 is just 9 floats in a row. When this gets stored in registers, its just going to take the first four floats and put them in c0, the next four in c1, and the remaining float in c2.x. You can see this yourself with the following: cbuffer cbChangesEveryFrame : register( b1 ) { float a1 : packoffset(c0.x); float a2 : packoffset(c0.y); float a3 : packoffset(c0.z); float b1 : packoffset(c0.w); float b2 : packoffset(c1.x); float b3 : packoffset(c1.y); float c1 : packoffset(c1.z); float c2 : packoffset(c1.w); float c3 : packoffset(c2.x); }; PS_INPUT VS( VS_INPUT input ) { PS_INPUT output = (PS_INPUT)0; output.Pos = mul( input.Pos, World ); output.Pos = mul( output.Pos, View ); output.Pos = mul( output.Pos, Projection ); float3 coord = float3(input.Tex, 1.0); float3x3 g_TexTransform = {a1, a2, a3, b1, b2, b3, c1, c2, c3}; coord = mul(coord, g_TexTransform); output.Tex = coord.xy; return output; } Now when you pass your XMFLOAT3X3, the texture appears normally. The problem was that because of the register allocation, your texture transform matrix became screwed up. When you look at the registers, this is how your data looks coming in: c0: 1 0 0 0 c1: 1 0 0 0 c2: 1 float3x3's are probably an array of float3's, so it would take the first three components of each register, giving you: 1, 0, 0 1, 0, 0 1, 0, 0 Its scaling your Y to 0, which is giving that wierd stretchy look. To solve this, you're going to either have to store your transform in a 4x4 matrix, or manually assign each part of the register. Switching to three float3's wouldn't work either, because they can't cross the 16-byte boundary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does TFS Record the Parameters to a Build? When queueing a new build, we get the option to change the default parameters. Do these changes get recorded somewhere, either in the TFS Operational Store or in the TFS Data Warehouse? A: These parameters should be available in the Team Foundation Build Operational Store, according to the behavior described in http://msdn.microsoft.com/en-us/library/ms244687.aspx. A: My advice is to log them as part of the build workflow, then the log will be stored with the build outputs. If you read the ALM Ranger Build Guidance they suggest taking this approach, and I believe the BRDLite customized Build Process Template that ships with the guidance does this: http://rabcg.codeplex.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7542213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to force usage of custom fonts for text rendering on a given web page? Is it possible to use Javascript or any other technology to force the rendering of text on a given web page with a custom font? Downloading the font as a resource is ok. In other words, one would/should not rely on fonts installed in the users' browser. Has anyone tried this? Is it possible at all? If yes, how? A: CSS has the @font-face. I think this is what you are talking about... @font-face is a css rule which allows you to download a particular font from your server to render a webpage if the user hasn't got that font installed. This means that web designers will no longer have to adhere to a particular set of "web safe" fonts that the user has pre-installed on their computer. Read more here: http://www.font-face.com/#lime_content You can create your own fonts for embedding here http://www.fontsquirrel.com/fontface/generator A: I don't know how to do it, but it is possible. Google has a whole bunch of fonts you can have the user load using javascript http://www.google.com/webfonts#ChoosePlace:select
{ "language": "en", "url": "https://stackoverflow.com/questions/7542214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook Like Button Code won't work in HTML Email I am trying to add the like button code into a html newsletter but it won't display, only displays on the online version. Is it possible to have it display in the email newsletter as well, if so, how? A: No this is not possible. The best you can do is a static like button image that takes you to your fan page or website where they can then click on a real like button. You can't embed scripts into email and have them execute, which is required to convert the like button code into the necessary rendered iframe. A: An alternative to using the 'like button' is using the html only share button. Technically its not supported, but hey it works. http://www.facebook.com/sharer.php?u=http://mylink.com A: You cannot use javascript directly on emails. But you can put a button/link to a page of your own, whose purpose is to hold the actual like button.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: add whitespace on space bar I currently have this function: if (e.keyCode == 32){ var $cursor = $("#cursor") $cursor.val(""); this.append("<span class = 'space'>-</span>"); $cursor.insertAfter(".space:last"); $cursor.focus(); } I was wondering how one would add a whitespace for the span, right now I add a dash for testing. A: Have you tried just using a space character? //... this.append("<span class = 'space'> </span>"); //... If that doesn't work, you can use &nbsp; (nonbreaking space) instead of -. //... this.append("<span class = 'space'>&nbsp;</span>"); //... A: Another way could be to use CSS: Test<span class="spacer"></span>Test .spacer { padding-left: 1em; } http://jsfiddle.net/Byy2e/
{ "language": "en", "url": "https://stackoverflow.com/questions/7542216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I determine which JCheckBox caused an event when the JCheckBox text is the same I am working on a program that needs to determine which JCheckBox was selected. I am using three different button groups, two of which have overlapping text. I need to be able to determine which triggered the event so I can add the appropriate charge (COSTPERROOM vs COSTPERCAR) to the total(costOfHome). What I cant figure out is how to differentiate the checkbox source if the text is the same. I was thinking of trying to change the text on one button group to strings like "one" "two" etc, but that introduces a bigger problem with how I have created the checkboxes in the first place. Any ideas would be appreciated, thanks in advance! import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JMyNewHome extends JFrame implements ItemListener { // class private variables private int costOfHome = 0; // class arrays private String[] homeNamesArray = {"Aspen", "Brittany", "Colonial", "Dartmour"}; private int[] homeCostArray = {100000, 120000, 180000, 250000}; // class constants private final int MAXROOMS = 3; private final int MAXCARS = 4; private final int COSTPERROOM = 10500; private final int COSTPERCAR = 7775; JLabel costLabel = new JLabel(); // constructor public JMyNewHome () { super("My New Home"); setSize(450,150); setLayout(new FlowLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Font labelFont = new Font("Time New Roman", Font.BOLD, 24); setJLabelString(costLabel, costOfHome); costLabel.setFont(labelFont); add(costLabel); JCheckBox[] homesCheckBoxes = new JCheckBox[homeNamesArray.length]; ButtonGroup homeSelection = new ButtonGroup(); for (int i = 0; i < homeNamesArray.length; i++) { homesCheckBoxes[i] = new JCheckBox(homeNamesArray[i], false); homeSelection.add(homesCheckBoxes[i]); homesCheckBoxes[i].addItemListener(this); add(homesCheckBoxes[i]); } JLabel roomLabel = new JLabel("Number of Rooms in Home"); add(roomLabel); ButtonGroup roomSelection = new ButtonGroup(); JCheckBox[] roomCheckBoxes = new JCheckBox[MAXROOMS]; for (int i = 0; i < MAXROOMS; i++) { String intToString = Integer.toString(i + 2); roomCheckBoxes[i] = new JCheckBox(intToString); roomSelection.add(roomCheckBoxes[i]); roomCheckBoxes[i].addItemListener(this); add(roomCheckBoxes[i]); } JLabel carLabel = new JLabel("Size of Garage (number of cars)"); add(carLabel); ButtonGroup carSelection = new ButtonGroup(); JCheckBox[] carCheckBoxes = new JCheckBox[MAXCARS]; for (int i = 0; i < MAXCARS; i++) { String intToString = Integer.toString(i); carCheckBoxes[i] = new JCheckBox(intToString); carSelection.add(carCheckBoxes[i]); carCheckBoxes[i].addItemListener(this); add(carCheckBoxes[i]); } setVisible(true); } private void setJLabelString(JLabel label, int cost) { String costOfHomeString = Integer.toString(cost); label.setText("Cost of Configured Home: $ " + costOfHomeString + ".00"); invalidate(); validate(); repaint(); } public void itemStateChanged(ItemEvent e) { JCheckBox source = (JCheckBox) e.getItem(); String sourceText = source.getText(); //JLabel testLabel = new JLabel(sourceText); //add(testLabel); //invalidate(); //validate(); //repaint(); for (int i = 0; i < homeNamesArray.length; i++) { if (sourceText == homeNamesArray[i]) { setJLabelString(costLabel, costOfHome + homeCostArray[i]); } } } } A: I would * *Use JRadioButtons for this rather than JCheckBoxes since I think it is GUI standard to have a set of JRadioButtons that only allow one selection rather than a set of JCheckBoxes. *Although you may have "overlapping text" you can set the button's actionCommand to anything you want to. So one set of buttons could have actionCommands that are "room count 2", "room count 3", ... *But even better, the ButtonGroup can tell you which toggle button (either check box or radio button) has been selected since if you call getSelection() on it, it will get you the ButtonModel of the selected button (or null if none have been selected), and then you can get the actionCommand from the model via its getActionCommand() method. Just first check that the model selected isn't null. *Learn to use the layout managers as they can make your job much easier. For instance, if you had two ButtonGroups: ButtonGroup fooBtnGroup = new ButtonGroup(); ButtonGroup barBtnGroup = new ButtonGroup(); If you add a bunch of JRadioButtons to these ButtonGroups, you can then check which buttons were selected for which group like so (the following code is in a JButton's ActionListener): ButtonModel fooModel = fooBtnGroup.getSelection(); String fooSelection = fooModel == null ? "No foo selected" : fooModel.getActionCommand(); ButtonModel barModel = barBtnGroup.getSelection(); String barSelection = barModel == null ? "No bar selected" : barModel.getActionCommand(); System.out.println("Foo selected: " + fooSelection); System.out.println("Bar selected: " + barSelection); Assuming of course that you've set the actionCommand for your buttons. A: Checkboxes have item listeners like any other swing component. I would decouple them, and simply add listeners to each { checkBox.addActionListener(actionListener); } http://www.java2s.com/Code/Java/Swing-JFC/CheckBoxItemListener.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7542218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Bitmap getPixels returns -1 for the whole array am creating temp Bitmap to draw a Text on it, and the i want to get it Pixels so i can manipulate these pixels (i don't show this image on screen). this is the code Bitmap tempBitmap=Bitmap.createBitmap(200, 400, Bitmap.Config.ARGB_8888);//i've tested all Configs Canvas tempCanvas=new Canvas(tempBitmap); tempCanvas.drawColor(Color.WHITE); tempCanvas.drawText("Hello", 0, 0, mPaint);//mPaint color set to Black int[] pixels=new int[tempBitmap.getWidth() * tempBitmap.getHeight()]; tempBitmap.getPixels(pixels, 0, tempBitmap.getWidth(), 0, 0, tempBitmap.getWidth(), tempBitmap.getHeight()); but when i print all pixels they all -1 value !! why? A: You're positioning the baseline of the text at (0,0), so you're drawing it just off the top of the bitmap. Move it down a bit. You can use Paint.getTextBounds to measure the text size, and then use the returned height to move your text downwards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Buttons like radio buttons I'd like to have the user choose between a set of choices, but rather than a list of radio buttons and descriptions i'd like buttons which have the descriptions on the buttons (looks better and less ambiguous). But there would also be preferably some way to know what the group of buttons is "set" to. This is to make it work just like the radio buttons would. Is there a standard way to do this? I'd like to be able to guarantee that the currently selected option will be easily identifiable (assigning colors manually if I must do it that way). What I'm not sure about at the moment is if it'll work (on most browsers) if I just try to assign multiple buttons with the same name, like I would do with the radio buttons. A: Use labels to extend the click area of a radio button. <label class="radioLabel"><input type="radio" value="0" /> None</label> Now, style the label to make it look like a button. To give the label other visuals, such as mouseover/inactive/selected, use javascript to add/remove classes to the label and subscribe to mouse events (hover, click etc) You can hide the radio buttons with CSS, but unless you have images to set as backgrounds for the various states (inactive/selected/mouseover), I wouldn't recommend it. A: Visual display is an issue for CSS and HTML. The label can be associated with the radio button by having a box border around both to group them visually. A slight change of background colour will help too. To pack them close together, put the button under the label. It shouldn't take up any more room than a button and you save a slab of script. Like: <style type="text/css"> .aButton { border: 1px solid #bbbbbb; background-color: #eeeeee; margin: 1px; } </style> <table> <tr> <td><label class="aButton" for="b0">Yes<input type="radio" name="group1" id="b0"></label> <label class="aButton" for="b1">No<input type="radio" name="group1" id="b1"></label> <label class="aButton" for="b2">Maybe<input type="radio" name="group1" id="b2"></label> </table>
{ "language": "en", "url": "https://stackoverflow.com/questions/7542222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Boost iterator_facade dereference I'm trying to use boost iterator facade to implement an iterator for a class that stores a sorted vector of elements of type data_t. Currently I'm having troubles with dereferencing it. I only need the iterator for traversal and searching, the iterator doesn't need to change any of the internal state of the Range object. Here's the range.hpp: #include <algorithm> #include <vector> #include <sstream> #include <stdexcept> #include <functional> #include <boost/iterator/iterator_facade.hpp> struct testRangeImpl{ typedef unsigned int data_t; struct RangeOrdering : public std::binary_function< data_t const &, data_t const &, bool >{ bool operator()(data_t const& a, data_t const& b){ return a < b; } }; }; template< typename ImplT > class SortedRange: public boost::iterator_facade< SortedRange< ImplT >, //this type because of the CRTP typename ImplT::data_t, //The type of the data boost::bidirectional_traversal_tag //iterators can be incremented and decremented >{ public: /*! this type */ typedef SortedRange< ImplT > type; /*! The type of the implementation policy */ typedef ImplT impl_t; /*! The internal representation of an element */ typedef typename impl_t::data_t data_t; /*! The internal representation of a range */ typedef std::vector< data_t > range_t; /*! A member variabe to keep track of if the range has been sorted */ bool m_sorted; /*! The actual range itself in its internal representation */ range_t m_range; /*! The actual range itself in its internal representation */ size_t m_range_size; /*! An exception indicating an invalid range */ struct InvalidRangeException{}; /*! Current element for iterator */ size_t m_current_combo; enum class PositionClass { NOT_END, END, REND }; explicit SortedRange( ) : m_sorted(false), m_range(), m_range_size(0), m_current_combo(0) , m_posclass(PositionClass::END){ } explicit SortedRange(std::vector < data_t > const& rg, size_t const& current_combo, PositionClass const& p ) : m_sorted(false), m_range(rg), m_range_size(rg.size()), m_current_combo(current_combo) , m_posclass(p){ if(rg.empty()){ throw InvalidRangeException(); } std::sort(m_range.begin(),m_range.end(),typename ImplT::RangeOrdering()); m_sorted = true; //initialise(); } protected: explicit SortedRange(std::vector < data_t > const& rg) : m_sorted(false), m_range(rg), m_range_size(rg.size()), m_current_combo(0) , m_posclass(PositionClass::NOT_END){ if(rg.empty()){ throw InvalidRangeException(); } std::sort(m_range.begin(),m_range.end(),typename ImplT::RangeOrdering()); m_sorted = true; //initialise(); } /*! Implementation policy object */ impl_t m_impl; /*! construct a range with a specific internal state */ explicit SortedRange(std::vector < data_t > const& rg, size_t const& current_combo) : m_sorted(false), m_range(rg), m_range_size(rg.size()), m_current_combo(current_combo) , m_posclass(PositionClass::NOT_END){ if(rg.empty()){ throw InvalidRangeException(); } std::sort(m_range.begin(),m_range.end(),typename ImplT::RangeOrdering()); m_sorted = true; //initialise(); } public: size_t size(){ m_range_size = m_range.size(); return m_range_size; } /* Return first data */ type begin() const { return type(m_range, 0); } type end() const { return type(m_range, m_current_combo, PositionClass::END); } type rend() const { return type(m_range, m_current_combo, PositionClass::REND); } /* Return last data */ type rbegin() const { return type(m_range, m_range_size -1 ); } private: friend class boost::iterator_core_access; /*! Position class */ PositionClass m_posclass; /*! set up the initial state */ void initialise() { std::sort(m_range.begin(),m_range.end()); m_sorted == true; } /*! the first element */ data_t first() const { return m_range[0]; } /*! the last element */ data_t last() const { return m_range[m_range_size - 1]; } /*! return the current element */ const data_t& dereference() const { if(m_posclass == PositionClass::NOT_END) { return m_range[m_current_combo]; }else { throw std::out_of_range("Attempt to dereference past the valid range"); } } /*! get the next combination */ void increment() { if(m_posclass != PositionClass::NOT_END) throw std::out_of_range("Cannot increment past the valid range"); if(m_current_combo == m_range_size ) { //current combination is the last m_posclass = PositionClass::END; } m_current_combo++; } /*! get the previous combination */ void decrement() { if(m_posclass != PositionClass::NOT_END) throw std::out_of_range("Cannot decrement past the valid range"); if(m_current_combo == 0) { //current combination is the first m_posclass = PositionClass::REND; } m_current_combo--; } /*! check for equality between two iterators. */ bool equal(type const& other) const { if(m_posclass == PositionClass::NOT_END && other.m_posclass == PositionClass::NOT_END) { return m_current_combo == other.m_current_combo && m_range == other.m_range; } else { return m_posclass == other.m_posclass && m_range == other.m_range; } } }; struct Range : public SortedRange< testRangeImpl>{ /*! An exception we throw if someone tries to construct an invalid range */ struct InvalidRangeException : public SortedRange< testRangeImpl >::InvalidRangeException {}; /*! Construct a range from a vector of unsigned ints */ explicit Range(std::vector<unsigned int> const& r) : SortedRange<testRangeImpl>(r) { if(r.empty()){ throw InvalidRangeException(); } } }; Here's the main.cpp: #include <vector> #include <iostream> #include "range.hpp" int main(void){ std::vector<unsigned int> rg = { 2 , 5 , 1 , 3 , 4 }; Range test(rg); for(auto elem: test){ std::cout << elem << " " ; } return 0; } Compiling gives this error: /usr/include/boost/iterator/iterator_facade.hpp: In static member function ‘static typename Facade::reference boost::iterator_core_access::dereference(const Facade&) [with Facade = SortedRange<testRangeImpl>, typename Facade::reference = unsigned int&]’: /usr/include/boost/iterator/iterator_facade.hpp:643:67: instantiated from ‘boost::iterator_facade<I, V, TC, R, D>::reference boost::iterator_facade<I, V, TC, R, D>::operator*() const [with Derived = SortedRange<testRangeImpl>, Value = unsigned int, CategoryOrTraversal = boost::bidirectional_traversal_tag, Reference = unsigned int&, Difference = long int, boost::iterator_facade<I, V, TC, R, D>::reference = unsigned int&]’ main.cpp:9:17: instantiated from here /usr/include/boost/iterator/iterator_facade.hpp:517:32: error: invalid initialisation of reference of type ‘boost::iterator_facade<SortedRange<testRangeImpl>, unsigned int, boost::bidirectional_traversal_tag, unsigned int&, long int>::reference {aka unsigned int&}’ from expression of type ‘const data_t {aka const unsigned int}’ How do I get this to be a usable iterator type? A: You are trying to take a non-const reference to a const value. For some reason you have decided that dereference returns a const reference, instead of honoring the facade reference type. Fix that, and it should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Send fast textinput to another process (Window) I am writing a C# WPF program which sends text messages to another program's window. I have a macro program as part of my keyboard drivers (Logitech g15) which already does this, though it does not send keystrokes directly to the process, but to the currently focused window. It works well but i need to be able to send inputs from my program as well. There are other people using the process so the input text messages from my program needs to be fast enough so that my text does not interfere with their input. The problem is that when I try to do this with a c# program I get too much delay. The macro program (Logitech G-Series Profiler) sends a command instantly. I have tried the following three commands for sending messages to process. (Listed by order of slowest to fastest) SetForegroundWindow(_hWnd); SendKeys.SendWait("{Enter}This is a keystroke input.{Enter}"); It is probably in the name, but this performs the command so slowly that I can actually follow with my eyes the text as it is input letter by letter. I have tried using the “SendKeys.Send” method but I get an error saying: “SendKeys cannot run inside this application because the application is not handling Windows messages.” PostMessage((IntPtr)_hWnd, (uint)WMessages.WM_KEYUP, (int)key, (int)key); PostMessage is a bit faster but still not fast enough for the purpose of my program. Besides the method returns before the message has been read by the process, which means two sequential PostMessage calls may not send sequential messages. SendMessage(_hWnd, 0x100, (int) VKeys.VK_2, (int) VKeys.VK_2); This is faster than the PostMessage but not nearly as fast as the macro program from Logitech. Also, the receiving program handles the input strangely, apparently not treating it the same way it does "genuine" input from the keyboard. SetForegroundWindow(_hWnd); const string text = "This is a keystroke input."; IInputElement target = Keyboard.FocusedElement; IInputElement target = InputManager.Current.PrimaryKeyboardDevice.FocusedElement; var routedEvent = TextCompositionManager.TextInputEvent; target.RaiseEvent(new TextCompositionEventArgs(InputManager.Current.PrimaryKeyboardDevice, new TextComposition(InputManager.Current, target, text)) { RoutedEvent = routedEvent }); This is the last thing I have tried. It seems instant with the way the text is sent to a process. However, I have only been able to send this to my own program since Keyboard.FocusedElement returns null when I have another program set as foreground window. If someone can tell me how to get an IInputElement of another window I would sure like to know. Alternatively, if someone has a suggestion for a better method of sending input, I would dearly like to hear it. Specs: Windows 7, 64bit Visual Studio 2010, Framework 4 A: First of all, are you intentionally using WM_KEYDOWN (0x0100) instead of WM_KEYUP (0x0101) in your SendMessage example? This would just press the keys, and never release them, so the application would not process them properly. Another way worth trying would be to send WM_SETTEXT, assuming the control interprets it correctly (like edit controls or combo boxes). A last option would be to use SendInput which synthesizes keyboard and mouse input on a very low level, but similarly to you keyboard's macro program, this requires you to activate the correct window and set the focus, which can be quite painful. A: Depending on your other's program window type, you could use UI Automation. See this example here: Add Content to a Text Box Using UI Automation
{ "language": "en", "url": "https://stackoverflow.com/questions/7542226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Are class methods the best way in Objective-C to implement a factory method? It seems like I see a lot of class methods in Objective C that are like +(NSString*)stringWithString:(NSString *)string or +(NSArray)arrayWithArray:(NSArray *)array, etc. I am just starting to consider design patterns and to me these methods look like little factories that produce specific implementations of strings or arrays based on the paramaters provided (stringWith string , string ByAppendingString). In essence this looks a lot like the factory method with parameters demonstrated in the book Design Patterns. Is there a better way to do this? Should I be creating interfaces that mix these class methods and instance methods, or create Factory only objects that do not have any instance methods? I am confused. A: While Apple claims that these methods are factory methods, I argue that they're not the same as the Factory Method pattern in Design Patterns. The DP Factory Method pattern uses an abstract Creator class, with concrete subclasses that generate concrete Product classes. The methods you're describing (which are often called "convenience constructors") are almost never implemented that way. Apple's definition of a factory method is "a class method that, as a convenience to clients, creates an instance of a class. A factory method combines allocation and initialization in one step and returns an autoreleased instance of the class." That's why I believe the term "convenience constructor" is more appropriate and less confusing that "factory method." NSString is a class cluster, which has some passing similarities to the Factory Method pattern, in that you can receive different concrete classes from the same method call. But class clusters are different than Factory Method in that the superclass knows about all the subclasses, and it is the superclass that callers interact with. In the Factory Method pattern, callers interact with subclasses of the Creator class. So to your question: you should create convenience methods when it is convenient to the caller. It supplements: Foo *foo = [[[Foo alloc] initWithSomething:something] autorelease]; with Foo *foo = [Foo fooWithSomething:something]; My experience building these is that 90% of the time you shouldn't. It's not worth the extra code. You should wait until you see that initWithSomething: is being called a lot with an autorelease right after it, and then you add a convenience constructor to make things more convenient. Things like stringWith... are in this class. They're called a lot. A: By definition, a factory method has to be a class method, because you need the class to generate a new instance. Apple's frameworks use a mix of factory methods (arrayWithObjects, for example), and non-factory initialization (initWithObjects). Other than that, I'm not really sure I understand your question. For most non-trivial classes, you'll have both class factory methods and instance initialization methods. A: These methods are usually described by the documentation as convenience methods - Writing [NSString stringWithString:s] is just shorter then writing [[[NSString alloc] initWithString:s] autorelease], but they do the same thing. Regarding the factory angle, I feel that whether or not you treat these methods as a sort of factory is a matter of taste and depends on what your exact definition of a factory is. A: Class in Objective-C are also objects (Class Objects), the factory class design pattern is part of the language.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: EXC_BAD_ACCESS disappears with zombies enabled I'm getting an EXC_BAD_ACCESS crash at startup and Xcode says the crash is at the NSApplicationMain line in my main.m file. The crash happens 99% of the time and when I run it with zombies enabled the crash never happens. Has anyone seen this before? How can I possibly debug this? A: If you are running Xcode4 there default is to show very little of the call stack, move the slider at the bottom to the right. You may well not find any of your code but you should be able to get a good idea of what was going on. If it was a notification or selector after delay you will see that the Runloop dispatch and that will also give you a clue. Finally, go old school, the way we did it in the day of coding forums, punch cards and only a couple of compiles a day: study your code. Know what every line of code does and why it is there. As @Danra said, do run the Xcode Analyzer and fix all complaints. A: The reason why running with zombies enabled resolves the bad access is probably that a) In this mode objects don't really get deallocated when their retain count reaches zero, and b) That your original crash is due to accessing an already deallocated object. However with zombies enabled, instead of the crash I think you should see in the debug console the access to the deallocated object. I also recommend using the static analyzer ("Analyze" in the XCode menus) in hope that it finds the culprit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: read specific number of bytes from NetworkStream I am trying to read a message of known length from the network stream. I was kinda expecting that NetworkStream.Read() would wait to return until buffer array I gave to it is full. If not, then what is the point of the ReadTimeout property? Sample code I am using to test my theory public static void Main(string[] args) { TcpListener listener = new TcpListener(IPAddress.Any, 10001); listener.Start(); Console.WriteLine("Waiting for connection..."); ThreadPool.QueueUserWorkItem(WriterThread); using (TcpClient client = listener.AcceptTcpClient()) using (NetworkStream stream = client.GetStream()) { Console.WriteLine("Connected. Waiting for data..."); client.ReceiveTimeout = (int)new TimeSpan(0, 1, 0).TotalMilliseconds; stream.ReadTimeout = (int)new TimeSpan(0, 1, 0).TotalMilliseconds; byte[] buffer = new byte[1024]; int bytesRead = stream.Read(buffer, 0, buffer.Length); Console.WriteLine("Got {0} bytes.", bytesRead); } listener.Stop(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(true); } private static void WriterThread(object state) { using (TcpClient client = new TcpClient()) { client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10001)); using (NetworkStream stream = client.GetStream()) { byte[] bytes = Encoding.UTF8.GetBytes("obviously less than 1024 bytes"); Console.WriteLine("Sending {0} bytes...", bytes.Length); stream.Write(bytes, 0, bytes.Length); Thread.Sleep(new TimeSpan(0, 2, 0)); } } } Result of that is: Waiting for connection... Sending 30 bytes... Connected. Waiting for data... Got 30 bytes. Press any key to exit... Is there a standard way of making a sync read that returns only when specified number of bytes was read? I am sure it is not too complicated to write one myself, but presence of the timeout properties on both TcpClient and NetworkStream kinda suggests it should be already working that way. A: All you are guaranteed is (one of): * *0 bytes (end of stream) *at least 1 byte (some data available; does not mean there isn't more coming or already available) *an error (timeout, etc) To read a specified number of bytes... loop: int read = 0, offset = 0, toRead = ... while(toRead > 0 && (read = stream.Read(buffer, offset, toRead)) > 0) { toRead -= read; offset += read; } if(toRead > 0) throw new EndOfStreamException(); A: TCP is a byte-stream protocol that does not preserve application message boundaries. It is simply not able to "glue" bytes together in that way. The purpose of the read timeout is to specify how long you would like the read to block. But as long as at least one byte of data can be returned, the read operation will not block. If you need to call read in a loop until you read a complete message, do that. The TCP layer doesn't care what you consider to be a full message, that's not its job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Difference between new and override? I have a base class which I want to provide some 'base' functionality for methods for all inheriting classes. In my inheriting classes I want to do: public override void Setup() { base.Setup(); } But at the moment it says I have to use the new keyword. How to I have it so I have to use the override keyword? Is there any difference between how it is currently with me using the new keyword and using override? A: It says so because you have not declared the base method virtual. Once you do so, the base virtual/derived override pair of keywords will make sense. Right now, the compiler is complaining that you cannot override a non-virtual method. A: When you use the override keyword the derived method is used even when the instance is passed as a Base class type. Hence there needs to be a virtual in the base class so that the programme knows it has to make a runtime check of what the actual type of the instance is. It then looks up what the actual type is and if it is a derived type it checks if their is an override in the derived class for that particular method in the base class. Member hiding is different. The base member will only be hidden if it is actually passed as an instance of the derived class. If the object is passed as a base class, the base class method will still be used. If you hide a member, you get a warning if you haven't use the new keyword. The new keyword is merely to tell the complier, that you really do mean to hide the base type method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Subversion repository gap I need to fill I have a situation where my main subversion machine died. I have resorted to an older machine. My latest checkout is version 240, but the old machine is only up to version 200? Subversion won't let me checkin and I need help fixing the gap. A: You could try this: 1) Check out version 200 from the old machine into a new working copy. 2) Use svn export to copy the changes from your old working copy across to your new working copy. 3) Check the changes in as version 201 on the old machine. You'll lose the history between versions 200 and 240, but unless you have a backup of them somewhere else then you might not be able to avoid that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Managing Configuration Changes in WCF What is the preferable way to manage configuration file changes in WCF webservices? I know usually in desktop applications people use a FileSystemWatcher to watch for changes in App.config, but how exactly does one go about configuring one in WCF? I tried using something like the following code: public class Service : IService { private static readonly FileSystemWatcher ConfigurationWatcher = new FileSystemWatcher(PathToRootDirectory); private void ReloadConfiguration(object sender, FileSystemEventArgs e) { ConfigurationManager.RefreshSection("appSettings"); ConfigurationManager.RefreshSection("connectionStrings"); } // IService implementation goes here. static Service() { ConfigurationWatcher.Filter = "web.config"; ConfigurationWatcher.NotifyFilter = NotifyFilter.LastWrite; ConfigurationWatcher.Change += ReloadConfiguration; } } However, that didn't seem to work since ConfigurationWatcher seemed to being initialized upon every call to the service... How does one go about accomplishing this? A: This happens automatically for a service hosted in IIS. Any change to the web.config or any assembly in the bin folder will cause the current AppDomain to shut down and a new AppDomain to be started for subsequent requests - just like with ASP.NET.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is the Flash video fallback for HTML5 video built into the Flash plugin? I understand how to use the HTML5 video tag except for one part: the flash fallback. In order to use a flash fallback do I just simply include the .flv file last in the list of source tags or is there some sort of special flash player I need to include like Flowplayer or that other one that reminds of a kangaroo (forgot the name). My plan was to include the following code. Please let me know if the flash won't work this way: <video controls width="400" poster="img/video/placeholder.png"> <source src="img/video/ssi_intro.webm" type="Not Sure" /> <source src="img/video/ssi_intro.mp4" type="video/mp4" /> <source src="img/video/ssi_intro.flv" type="Note Sure Again" /> </video> I saw a ton of HTML5 video questions but not pertaining to this. This one makes me feel kind of dumb but thanks in advance for any advice. A: For an implementation, heck out Video for Everybody. For background info, check out Mark Pilgrim's Dive into HTML5 video chapter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ScheduledAgent and GeoCoordinateWatcher - how to make them work? I'm trying to get GPS position via GeoCoordinateWatcher running in ScheduledAgent. Unfortunately only location I get is some old one, recorded when application was running. How to get current (latest) location in ScheduledAgent? A: I have come across the same problem. Unfortunaty, this is intended behaviour according to the WP7.1 APIs According to the documentation, "This API, used for obtaining the geographic coordinates of the device, is supported for use in background agents, but it uses a cached location value instead of real-time data. The cached location value is updated by the device every 15 minutes." http://msdn.microsoft.com/en-us/library/hh202962(v=VS.92).aspx A: My 2 Centlys. it is probably becoz the GeoCoordinateWatcher takes some time (2 seconds or so) to get the new coordinate values and to lock to GPS or Cellular Mast or Wifi or whatever. And it will give you the last recordered position in the meantime. So, try to hook to the following events watcher.StatusChanged += new EventHandler< GeoPositionStatusChangedEventArgs>(watcher_StatusChanged); watcher.PositionChanged += new EventHandler< GeoPositionChangedEventArgs< GeoCoordinate>>(watcher_PositionChanged); where watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); and call the NotifyComplete(); in your "watcher_PositionChanged" event handler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using reCaptcha with Rails 2.3.12 So I'm trying to get reCaptcha to render on a partial form view that uses HAML. I have tried using the :ruby filter and then adding <%= recaptcha_tags %> but that didn't work, neither has anything else that I've found. Is there a way to implement this? *Revision Ahem, more specifically, can anyone tell me what I need to have for the <%= recaptcha_tags %> helper? Every thing I find on this subject just says "Add <%= recaptcha_tags %> wherever you want it to appear!" and absolutely nothing on what the helper should contain. *Another Revision I am indeed trying to use Ambethia. I tried using just = recaptcha_tags but that didn't work, I got an error saying it was an undefined variable or method. I installed the Ambethia/reCaptcha as a plugin using script/plugin install git://github.com/ambethia/recaptcha.git and I put config.gem "ambethia-recaptcha", :lib => "recaptcha/rails", :source => "http://gems.github.com" in environment.rb along with my public/private keys. *Started Over Okay, got rid of everything I had done initially. Can anyone help me with this? I follow all of the tutorials I can find on it, but none of them explain how to implement/create the helpers for <%= recaptcha_tags %> or <%= verify_recaptcha %>. I'm obviously new to RoR and implementing reCaptcha of any kind, so I'm sorry I'm asking for my hand to be held but I am honestly lost and am not finding any guidance anywhere! Thanks so much anyone and everyone. A: did you try simply: = recaptcha_tags You don't mention the plugin you're using. I'm assuming this one. If that's the case, the recaptcha_tags helper will return the HTML for the captcha, and you'd insert it into whichever forms you wanted the captcha to appear on. The <%= %> around recaptcha_helper aren't part of the helper, but rather the way you insert content into erb templates (and other templating languages resembling erb). In Haml you don't need the surrounding tag. It's just =. A: I had the same problem and I finally solved it realizing that my form was called asynchronously. I added: = recaptcha_tags :ajax => true and captcha appeared. Hope this could help the original question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Active Admin undefined methodgenerate_association_input_name I'm using this active_admin on Rails. I had one model: Page. But then I ran some migrations. When I came back to the login panel on active admin, whenever I would click on the Pages button at the top navigation bar, I get this error: NoMethodError in Admin/pages#index Showing /home/username/.rvm/gems/ruby-1.9.2-p290/gems/activeadmin-0.3.1/app/views/active_admin/resource/index.html.arb where line #1 raised: undefined method `generate_association_input_name' for # Extracted source (around line #1): 1: render renderer_for(:index) Another model I created works fine. I don't know what I did to break the Page model on Active Admin. I'm going to try to regenerate active admin. A: The problem is that Formtastic (which is a Active Admin dependency) was just updated to version 2.0.0 4 days ago. Previously Active Admin depended on Formtastic >= 1.1.0, which includes v2. But v2 have changed so much that it breaks Active Admin. 3 days ago mattvague made an update to Active Admin to reflect this issue, binding Active Admin to Formtastic < 2.0.0. So if if you don't mind upgrading Active Admin you can fix this by upgrading to Active Admin 0.3.2 which includes this fix: gem 'activeadmin', '~> 0.3.2' Alternatively you can force Active Admin to use an older version of Formtastic by adding it manually to your Gemfile: gem 'formtastic', '1.2.4' # an activeadmin dependency gem 'activeadmin', '< 0.3.2' # or whatever version below 0.3.2 you depend on
{ "language": "en", "url": "https://stackoverflow.com/questions/7542256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way to know if a folder has specified file types I have a loop procedure in VB6 which explores all the folders from a specified file path. I then need to know if each detected folder contains MP3 files. I don't want to use the dir command because it takes up a lot of resources. I've tried doing this using FSO, APIs, etc, but I can't find a solution. Thanks for any help. A: VB6's Dir$() function is a pretty light wrapper on FindFirstFile and friends. I'm not sure why you think the FSO would be any lighter or faster. The biggest serious limitations of Dir$() are that it is an ANSI function and it cannot be "interrupted" by a second search while one is already in progress without resetting the state of the first search. What does "takes up a lot of resources" mean anyway? I posted a Class wrapping the process at DirLister lightweight Dir() wrapper. A: Have you tried the FindFirstFile API function? It should be your best shot. There's a C# example at codeproject A Faster Directory Enumerator The VB signature goes like this: <DllImport("kernel32.dll", CharSet := CharSet.Auto)> _ Private Shared Function FindFirstFile(ByVal lpFileName As String, ByRef lpFindFileData As WIN32_FIND_DATA) As IntPtr End Function Here's a sample VB implementation http://www.ask-4it.com/how-to-use-findfirstfile-win32-api-from-visual-basic-code-2-ca.html You can also find a nice microsoft article on usage of the API here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can you get access to the firing dom node inside a dojo.xhrPost load? I have an html fragment like the following: <li> <img src="/jsafe/gallery/item/83/thumb" /> <span class="tools"> <a href="/jsafe/gallery/item/83/rotate/left"> <img src="/jsafe/img/rotate_left_small.png" alt="Rotate Left"/> </a> <a href="/jsafe/gallery/item/83/rotate/right"> <img src="/jsafe/img/rotate_right_small.png" alt="Rotate Right"/> </a> </span> </li> I have a dojo fragment like the following: dojo.query(".tools a:nth-child(1)").forEach(function(node,index,arr){ dojo.connect(node, "onclick", null, function(e){ e.preventDefault(); dojo.xhrPost({ url: dojo.attr(e.currentTarget, "href"), handleAs: "json", load: function(data) { //TODO } }, error: function(error) { var u = ""; } }); }) }); Inside the load function how can I get to the e.currentTarget dom node? I know load is a separate callback function but I need to get to that dom node to do more manipulation. A: Did you try just referring to e.currentTarget from within the load function? :) Since your load function is defined within the event handler function which has access to e, you still have access to it. Perhaps the explanation here will help: https://developer.mozilla.org/en/JavaScript/Guide/Closures
{ "language": "en", "url": "https://stackoverflow.com/questions/7542269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adobe Air - Self signed certificate I need to generate a self signed Adobe Air certificate. How to do that? (I'm using Flash CS5 - AIR 2.0/2.5) I came across this tutorial - what stands ADT for and where do I enter the command line? Thanks. A: ADT is "Air Developer Tool". You enter the command lines at a command prompt. Make sure the directory that contains the ADT program is in your path or specify the path to it in the command line. A: Flash CS5 will create a certificate for you. Next to the to the box where you enter your certificate, there should be a button labeled "Create". (I have Flash CS4 open, but I don't think they removed the feature in CS5.) That will create a certificate for you. (Oh, and Flash uses ADT behind the scenes to generate the certificate.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7542273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: show div on form submit with no redirect I'm using a WordPress sidebar widget to capture email addresses. The thing is, it redirects after form submission. I want the visitor to stay on the page they were on after form submission with just a hidden div giving a successful signup message. I've tried something with javascript like this -- <script type="text/javascript"> function showHide() { var div = document.getElementById("hidden_div"); if (div.style.display == 'none') { div.style.display = ''; } else { div.style.display = 'none'; } } </script> And that works perfectly for showing the hidden div on submit, but the actual form then doesn't work :( The form (with what I was trying to do) is like this -- <div id="wp_email_capture"><form name="wp_email_capture" method="post" onsubmit="showHide(); return false;" action="<?php echo $url; ?>"> <label class="wp-email-capture-name">Name:</label> <input name="wp-email-capture-name" type="text" class="wp-email-capture-name"><br/> <label class="wp-email-capture-email">Email:</label> <input name="wp-email-capture-email" type="text" class="wp-email-capture-email"><br/> <input type="hidden" name="wp_capture_action" value="1"> <input name="submit" type="submit" value="Submit" class="wp-email-capture-submit"> </form> <div id="hidden_div" style="display:none"><p>Form successfully submitted.</p> </div> The problem is coming in somewhere between 'return false' and the form action (which is where the plugin's coder has made it redirect I think). If I remove 'return false', it redirects. With 'return false' there, the form doesn't work. I can't figure out a way to get the form to work but not redirect, ie. just show the hidden div, work, and that's it! No redirect :) Would appreciate your help. A: I will show how to submit the form with jQuery, as this is what you have available to you: First of all, you should make one small change to the form HTML. Namely, change showHide() to showHide(this), which will give showHide() access to the form element. The HTML should be: <div id="wp_email_capture"><form name="wp_email_capture" method="post" onsubmit="showHide(this); return false;" action="<?php echo $url; ?>"> <label class="wp-email-capture-name">Name:</label> <input name="wp-email-capture-name" type="text" class="wp-email-capture-name"><br/> <label class="wp-email-capture-email">Email:</label> <input name="wp-email-capture-email" type="text" class="wp-email-capture-email"><br/> <input type="hidden" name="wp_capture_action" value="1"> <input name="submit" type="submit" value="Submit" class="wp-email-capture-submit"> </form> <div id="hidden_div" style="display:none"><p>Form successfully submitted.</p> </div> The javascript to submit the form and display the div on successful submit is: function showHide(form) { var serial = $(form).serialize(); $.post(form.action, serial, function(){ $('#hidden_div').show(); }); }; What this does: * *Serializes the form data, i.e. converts it to one long string such as wp-email-capture-name=&wp-email-capture-email=&wp_capture_action=1 that is stored in serial. *Submits the serialized data to the the form's action url (form.action) *If the form submit was successful, it runs the success handler, which is the third parameter to $.post(). This handler takes care of displaying the hidden div. I changed the code to use jQuery's .show() function, which takes care of browser inconsistencies. Hope this is helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can i make an mysql id appear on a link? I mean, I'm trying the web link to look like something.com/newpage.php?id=123.... What I have is a form, and a JavaScript function on load that runs this AJAX: $.ajax({ type: "POST", url: "postear.php", data: "addcontentbox=" + addcontent, success: function() { $("ul#wall").prepend("<li><a href='newpage.php?id=<?php echo $rows['id']; ?>' target='_blank'>"+addcontent+"</a></li>"); $("ul#wall li:first").fadeIn(); document.postbar_add_post.addcontent.value=''; $('form#postbar_add_post input[type="submit"]').removeAttr('disabled'); } }); and this is the PHP function that is calls on the url: <?php if(isset($_POST['addcontent'])) { // Connection to Database include('config.php'); // No Query Injection $message = mysql_real_escape_string($_POST['addcontent']); // echo $sql = 'INSERT INTO test.wall (message) VALUES("' . $message . '")'; $result = mysql_query($sql); $rows = mysql_fetch_array($result); mysql_query($sql); echo $message; } else { echo '0'; } ?> also, tried to place there a _GET [id].. but nothing. Any help ? pd:the dabase is: CREATE TABLE `test`.`wall` ( `id` INT( 6 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , `message` VARCHAR( 255 ) NOT NULL ) ENG A: I'm pretty sure you need a call to mysql_insert_id instead of mysql_fetch_array. i.e. You haven't pulled back the autoincrement ID from mysql (and that's making the assumption your wall table has an autoincrement primary key..?) A: first u need to change this lines success: function() { $("ul#wall").prepend("<li><a href='newpage.php?id=<?php echo $rows['id']; ?>' target='_blank'>"+addcontent+"</a></li>"); to success: function(data) { $("ul#wall").prepend("<li><a href='newpage.php?id="+data+" target='_blank'>"+addcontent+"</a></li>"); and in the php file instead of this three lines $rows = mysql_fetch_array($result); mysql_query($sql); echo $message; u should write echo mysql_insert_id(); of course you have to set the id fild in the database to autoincrement first it doesn't hurt to change this $sql = 'INSERT INTO test.wall (message) VALUES("' . $message . '")'; to $sql = "INSERT INTO test.wall (`message`) VALUES('$message')"; i mean it's easier this way
{ "language": "en", "url": "https://stackoverflow.com/questions/7542282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run Pthreads on windows I used to use a mac to write some C programs but it's not working now. I have to use an old windows laptop for a while. I installed codeblocks and tested a simple program using Pthreads. Unfortunately it didn't work. pthread_create(&thrd1, NULL, thread_execute, (void *)t); It keeps saying undefined reference to _imp__pthread_create How can i fix it? A: You need to grab pthreads-win32 as pthreads is a Unix component not a Windows one. A: You've clearly got a version of pthreads for Windows. You just haven't included the .lib file in your linker settings. Do that and you should be golden. A: If you are using MinGW you can MinGW installation manager and install packages that need to execute pthreads and openmp related tasks. Here is the procedure. After opening the installation manager go to all packages and select the select packages named using mingw32-pthreads-w32 and select them for installation. Then go to the installation -> Apply changes to install new packages. The you can use pthread.h and omp.h inside your c or c++ program without any problem. A: This code works fine in an MSYS2 terminal on Windows. All you need to do is to install gcc. (See further below.) // hello.c #include <omp.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> void *print_hello(void *thrd_nr) { printf("Hello World. - It's me, thread #%ld\n", (long)thrd_nr); pthread_exit(NULL); } int main(int argc, char *argv[]) { printf(" Hello C code!\n"); const int NR_THRDS = omp_get_max_threads(); pthread_t threads[NR_THRDS]; for(int t=0;t<NR_THRDS;t++) { printf("In main: creating thread %d\n", t); pthread_create(&threads[t], NULL, print_hello, (void *)(long)t); } for(int t=0;t<NR_THRDS;t++) { pthread_join(threads[t], NULL); } printf("After join: I am always last. Byebye!\n"); return EXIT_SUCCESS; } Compile and run as follows: gcc -fopenmp -pthread hello.c && ./a.out # Linux gcc -fopenmp -pthread hello.c && ./a.exe # MSYS2, Windows As you can see, the only difference between Linux and MSYS2 on Windows is the name of the executable binary. Everything else is identical. I tend to think of MSYS2 as an emulated (Arch-)Linux terminal on Windows. To install gcc in MSYS2: yes | pacman -Syu gcc Expect output similar to: Hello C code! In main: creating thread 0 Hello World. - It's me, thread #0 In main: creating thread 1 Hello World. - It's me, thread #1 After join: I am always last. Bye-bye! Reference * *https://www.msys2.org/wiki/MSYS2-installation/
{ "language": "en", "url": "https://stackoverflow.com/questions/7542286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: asp.net bug? ResouceManager.GetString(string) when string not found, aspx file is executed twice I tracked down a very weird ... bug... I found that for some reason, an ASPX page always executed twice. I tracked it down to this line in a user (asxc) control, I had : <img src='<%=RS("buildhover")%>' /> RS is just a helper function that resolves to ResouceManager.GetString("buildhover") I found that "buildhover" was simply missing from the resx file that was being read. When added, the ASPX page is no longer run twice... This is very strange and since I use resource files extensively, I am really interested to find out why this is... A: When you have an image element with a blank url for the string then it makes a request to the current page. When the resource doesn't exist you get a blank string. So the result of ResouceManager.GetString("buildhover") is an empty string. Look at the html produced. You will have something like <img src="" /> A: If you are observing load event twice in a post back in ASP.Net page, check the following: 1.If Page_Load handler defined in Codebehind then AutoEventWireup property should be “false” * *Check if you have mistakenly multiple event handlers registered for an event *Src or ImageURL attribute of your image control are defined and not empty (you can put %20 for blank) *bgColor or background is empty Last two problems usually appears in one browser while disappears in other. http://devshop.wordpress.com/2008/06/02/aspnet-page-loading-twice/
{ "language": "en", "url": "https://stackoverflow.com/questions/7542288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Center padded, full-width DIV horizontally and vertically using jQuery The following code works wonders to center my div as long as there's no padding or 100% width in the css: jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px"); this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px"); return this; } $(element).center(); Unfortunately, this screws up the padding of my (width: 100%) div in the latests versions of Safari, Firefox, and Chrome (probably all browsers too). The padding on the left is gone, and the padding on the right still exists, but it's off the page, creating a scrollbar. Any suggestions? Live demo: http://www.pillerdesigns.com/ A: When I want to center something I normally do this: jQuery.fn.center = function () { this.css({ position: 'absolute', top: 50+'%', left: 50+'%', marginTop: -(this.outerHeight()/2), marginLeft: -(this.outerWidth()/2) }); return this; } Anyway, do you have a reset.css? Since your problems are browser specific. $(element).center(); EDIT: Add box-sizing: border-box; to your #content div css. Problem is you're using padding on a 100% width element. box-sizing method will work in all browsers but not IE7 and lower. -- OR -- Wrap your #content div inside another div, make that one 100% and add the padding to the inner div.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP strtotime failure after 00:00 am Why does strtotime() failure after 00:00 am? Example: strtotime("24.09.") works while strtotime("25.09.") does not. Btw: These are Dates. My whole script crashed after I got myself something to drink lol. A: Even 24:00 working is a relatively new behavior. (As of PHP 5.3, according to the PHP manual.) I would assume that the special case that was added to allow 24:00 to work simply extends to all 24:xx times, but no other, higher hours. If you must work with strange time strings like these, you could do a little conversion and use "tomorrow 01:09" instead. A: Because that is not a valid time. You can read about what values it will accept here. A: Because "24" is sometimes used instead of "00" to indicate the first hour of the day. 25 is never used.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Import JSON file from URL into R I've been trying to import a JSON file into R for a while using both the rjson and RJSONIO package, but I can't get it to work. One of the variations of code I used: json_file <- "http://toolserver.org/~emw/index.php?c=rawdata&m=get_traffic_data&p1=USA&project1=en&from=12/10/2007&to=4/1/2011" json_data <- fromJSON(paste(readLines(json_file), collapse="")) This results in an error message: Error in fromJSON(paste(readLines(json_file), collapse = "")) : unexpected character '<' I think the problem is in the first line of code, because json_file contains the source of the website, not the actual content. I've tried getURL() and getURLContent(), but without any success. Any help would be much appreciated! Edit: as pointed out by Martin Morgan, the problem seems to be with the URL, not the code! A: library(rjson) fromJSON(readLines('http://toolserver.org/~emw/index.php?c=rawdata&m=get_traffic_data&p1=USA&project1=en&from=12/10/2007&to=4/1/2011')[1]) works for me, with a warning
{ "language": "en", "url": "https://stackoverflow.com/questions/7542300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Problem with Infinitest I'm using infinitest the eclipse plug-in. but sometimes it just do not work. I have a test for a method a(). The method a() calls method b() which calls method c(). if I change the method b() it runs the test for the method a. but it doesn't trigger if I change the method c(). A: Does b() always call c() or only sometimes? Do you have tests that cover the scenarios where c() is called?
{ "language": "en", "url": "https://stackoverflow.com/questions/7542301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to add a backgroundimage to my box2d app I was wondering how to add a background image to my box2d (cocos2d) iphone app. I have the image I just don't know how to add it to the background without it interfering with my touch events. A: This will help: http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:basic_concepts
{ "language": "en", "url": "https://stackoverflow.com/questions/7542305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails sanitize remove default allowed tags How would I use sanitize, but tell it to disallow some enabled by default tags? The documentation states that I can put this in my application.rb config.after_initialize do ActionView::Base.sanitized_allowed_tags.delete 'div' end Can I instead pass this as an argument to sanitize? A: Yes you can specify which tags and attributes to allow on a per-call basis. From the fine manual: Custom Use (only the mentioned tags and attributes are allowed, nothing else) <%= sanitize @article.body, :tags => %w(table tr td), :attributes => %w(id class style) %> But the problem with that is that :tags has to include all the tags you want to allow. The sanitize documentation says to See ActionView::Base for full docs on the available options. but the documentation is a lie, ActionView::Base says nothing about the available options. So, as usual, we have to go digging through the source and hope they don't silently change the interface. Tracing through the code a bit yields this: def tokenize(text, options) options[:parent] = [] options[:attributes] ||= allowed_attributes options[:tags] ||= allowed_tags super end def process_node(node, result, options) result << case node when HTML::Tag if node.closing == :close options[:parent].shift else options[:parent].unshift node.name end process_attributes_for node, options options[:tags].include?(node.name) ? node : nil else bad_tags.include?(options[:parent].first) ? nil : node.to_s.gsub(/</, "&lt;") end end The default value for options[:tags] in tokenize and the way options[:tags] is used in process_node are of interest and tell us that if options[:tags] has anything then it has to include the entire set of allowed tags and there aren't any other options for controlling the tag set. Also, if we look at sanitize_helper.rb, we see that sanitized_allowed_tags is just a wrapper for the allowed_tags in the whitelist sanitizer: def sanitized_allowed_tags white_list_sanitizer.allowed_tags end You should be able to add your own helper that does something like this (untested off-the-top-of-my-head code): def sensible_sanitize(html, options) if options.include? :not_tags options[:tags] = ActionView::Base.sanitized_allowed_tags - options[:not_tags] end sanitize html, options end and then you could <%= sensible_sanitize @stuff, :not_tags => [ 'div' ] %> to use the standard default tags except for <div>. A: I know you're looking for a way to pass the tags in, and for that mu's answer looks good! I was keen to set them up globally which was trickier than I'd hoped as ActionView::Base has overridden sanitized_allowed_tags= to append rather than replace! I ended up with the following to my application.rb: SANITIZE_ALLOWED_TAGS = %w{a ul ol li b i} config.after_initialize do ActionView::Base.sanitized_allowed_tags.clear ActionView::Base.sanitized_allowed_tags += SANITIZE_ALLOWED_TAGS end
{ "language": "en", "url": "https://stackoverflow.com/questions/7542312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: mix 2 real webcam into a fake webcam i need to get the streaming from 2 webcams on the same computer, and mix it as a fake webcam (so then i can use the fake webcam on any software). I have seen that camcamx is for mac, webcamstudio is for linux, but i need a solution for windows and i can't find it, so i was thinking to write my own small app. I can program with C#, Java and lazarus, but examples or library or whatever in any language will help anyway. i will need to make a fake webcam that can be used as a webcam (detected on my computer as a usb webcam), and some code to grasp the stream from two real webcam and mix everything together (there will be like a primary webcam that will be bigger and a secondary webcam that will be smaller, on a corner of the big image) Anyone can help me on that? A: This is not a trivial exercise but it can be done. I know because I've done it before. :) I implemented this in C++. What you need to do is to create what's known as a shared memory server. A shared memory server is a region of ram that more than one process can access. Here's how to create one using Named Shared Memory under Windows: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366551(v=vs.85).aspx In your application that mixes the video from the two cameras, you need to create a DirectShow rendering filter (CBaseRenderer) that writes the mixed video frame into this shared memory. On the other end, you need to create a separate Visual Studio DLL project that will implement a DirectShow capture filter (CSource and CSourceStream) that will read the video bitmaps your main application writes into this buffer. This VS project needs to be a registerable DLL that can be called to register it as a DirectShow capture device for windows. Your main application will create and maintain this shared memory buffer when it is operating. If another application (like a video conferencing program) accesses the capture device, all that will come from the device will be a blank buffer until you main application stars feeding real video frames into it. Tip #1: Since this is a multi-threaded operation, you will need an event handle to signal the capture filter that a frame is ready. You will also need a mutex to control access to the buffer by the "rendering" thread in your application and the "capture" thread in the capture device. Tip #2: You won't need to call UnmapViewOfFile or CloseHandle on the memory pointers until the rendering or capture filters are disposed. There is a lot of code you will need to grind out, so any useful examples will be beyond the scope of this discussion. This should get you going in the right direction. Good luck! A: I think your question is too far out of scope for what this site is all about. You're talking about thousands and thousands of lines of code and intimate knowledge of drivers, video decoding, mixing, etc., etc. if you're going to write this software on your own. With that said, there probably is software for this for Windows. I'd start here: * *http://alternativeto.net/software/webcamstudio/ A: Capture video from real webcam: Video Capture on MSDN Fake webcam: the well known starting point is Vivek's sample/project available at http://tmhare.mvps.org/downloads.htm, see also this post "Fake" DirectShow video capture device Getting all together is doable, though not trivial.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Chrome extension interaction with Java application I am learning to build Chrome extension and I have an idea to build something which requires complex computation (using many java libraries) which seems hard to be implemented by JavaScript. A general architecture I have in mind is: Chrome Extension (GE) extracts HTML elements and feeds HTML elements to Java application as input. Java application does the complex computation, and then feedback the results to GE. GE finally renders the results into the browser. Does anyone know is this feasible? Does this have to involve a server architecture? Could you also refer me to some further information? Note: It is a Java application, hopefully you can give me some Java specific answers. Thanks in advance. A: You would need to create java web application running on server (which can be accessed via URL) which you will be communicating with through ajax requests. Chrome extension (or any other js app) doesn't care what's running on server - java, php, or something else. It just sends HTTP POST/GET request to provided url and receives response back. If you are asking if you can pack some java into your extension then the answer is no. You can pack some C++ though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mysql Foreign Key Dilemma I have a column contactId on one table which is a foreign key, connected to the id of contacts table. I.e, every row in my 2nd table can be connected to a contact. However, some records don't have to be connected to any contacts. In such cases, the contact Id would be 0. When I try to insert such a record, I get this error: Error Number: 1452 Cannot add or update a child row: a foreign key constraint fails What should I do? A: If the column contactId that has the FK to the other table is nullable (and it can be) you should be able to just set those that don't have any contacts to NULL. A foreign key basically means that if the column has a non-NULL value, then that value has to exist in the primary key of the table referenced by the foreign key constraint. Otherwise, just set it to NULL. A: Use NULL as the contactId when it's irrelevant that the row reference a concact. Foreign key columns can be nullable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Thread safety guarantees for Objective-C runtime functions? What are the guarantees about thread safety for Objective-C runtime functions? Are there any? I am talking about the functions declared in runtime.h (e.g. class_lookupMethod, objc_setAssociatedObject). A: A lot of it is thread safe -- swizzling, and the like -- but some of it isn't. looking up a method should be. Associated objects may not be. If they aren't explicitly documented as such, then they should be treated as not being thread safe. Have a look at the source for the runtime. The comments therein may be illuminating. And please file a bug asking for clarification in the docs, if not already very clear.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Identifying names and places in literature I have been playing around with Markov Chain Text Generation and Naive Bayes classifiers. I am wondering if there is a way to apply either of those concepts towards identifying certain types of words in a novel. E.G. Last names or place names I can look through my markov chain and I see that certain words tend to relate the same way to certain other types of words. E.G. Mr. frequently comes before a last name, 'went to' tends to come before a place name and last names tend to follow first names. Is there a good way that I can write a program that will take a list of example names and then go through a large set of books and identify all words like those names with decent accuracy? Is English regular enough for this to work? Has this been done before? Would this method have a name? Thanks, Andrew A: In fact, there are only few patterns for names, e.g.: {FirstName}{Space}{Token with big first char} {BigCharacter}{Dot}{Space}{Token with big first char} {"Mr" | "Ms"}{Dot}{Space}{Token with big first char} and several more. All you need is a dictionary of first names and simple engine to catch such patterns. There's a good framework for this (and many other things) - GATE. It has very large dictionary of first names and special pattern language (JAPE) for manipulating token sequences. You can use it directly or just get the dictionary and implement the logic by yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Xdebug not working with PDT "waiting for Xdebug Session" I am trying to configure Xdebug with Eclipse PDT plugin. I have gone through lots of tutorial in web and also went through stackoverflow.com existing question. But didn't find the answer to this: i am using Eclipse 3.7 with the latest PDT plugin. Have done correct debug configuration in eclipse. Also i have changed the listening port of Eclipse xdebug to 9009. I have also given the same number to [xdebug] xdebug.remote_enable=1 xdebug.remote_host="localhost" xdebug.remote_port=9009 xdebug.remote_handler="dbgp" xdebug.remote_log = /tmp/xdebug.log xdebug.var_display_max_depth=10 xdebug.var_display_max_data=10240 xdebug.auto_trace=1 xdebug.trace_output_dir=/tmp zend_extension=/usr/lib/php5/20090626+lfs/xdebug.so at the end when i run netstat -anp --tcp --udp | grep LISTEN i get the following output tcp6 0 0 :::10000 :::* LISTEN 2949/eclipse tcp6 0 0 :::9009 :::* LISTEN 2949/eclipse i see eclipse in the list but not the apache or xdebug. and my session to the Xdebug in eclipse is hangs saying "Waiting for Xdebug Session"... anybody have idea how to debug this further A: I've been through this... I spent hours like you reading the same message... I learned a lot, but nothing worked. Does your Internet connection use a router? If this is true then you could have my problem. Just try to port forward port 9000. I don't know a lot about this ports and routers stuff... so I'll give you a pic of my router config. I really hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Make default landing tab load a 760px wide app Is it possible to setup a fan page to work as follows? * *User lands on my clients fan page *Sees a "Like me" graphic *User likes the page *User is then taken to a 760px wide app The two parts i am struggling with are: * *Creating a separate fan and none fan landing page *When liked, load up a 760px wide app Do I control the like/nonlike graphic from my app using either PHP or Javascript by seeing if the user has already liked my app? How do I force the liked page to load a 760px wide app? A: You can capture like button events. Facebook elements events Example: <script> window.fbAsyncInit = function() { FB.init({appId: '127654160646013', status: true, cookie: true, xfbml: true}); FB.Canvas.setSize({ width: 520, height: 742 }); FB.Event.subscribe('edge.create', function(response) { window.parent.location = ADDRESS; }); }; (function() { var e = document.createElement('script'); e.async = true; e.src = document.location.protocol + '//connect.facebook.net/lt_LT/all.js'; document.getElementById('fb-root').appendChild(e); })(); </script> Also you need get user fan status. Here is a solution: <? define('FACEBOOK_APP_ID', 'xxx'); define('FACEBOOK_APP_SECRET', 'xxx'); $is_fan = false; if (!empty($_REQUEST['signed_request'])) { list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2); $sig = base64_decode(strtr($encoded_sig, '-_', '+/')); $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true); $expected_sig = hash_hmac('sha256', $payload, FACEBOOK_APP_SECRET, true); if ($sig == $expected_sig) { if (!empty($data['page']['liked'])) { $is_fan = true; } } } ?> There is everything you need. And just remember, you can redirect only via javascript: window.parent.location = ADDRESS;
{ "language": "en", "url": "https://stackoverflow.com/questions/7542332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Change margin/padding based on height of total HTML document via JavaScript? I saw a trick on a stack-overflow solution a couple months ago (I can't seem to find it by searching now though). Anyway, it basically said that if you wanted two divs the same height, you could do something along these lines: <div id="wrapper"> <div id="nav" style="padding-bottom: 500px; margin-bottom: -500px;"> </div> <div id="content" style="padding-bottom: 500px; margin-bottom: -500px;"> </div> </div> The padding and negative margin seem to cancel each other out, rendering the proper height as long as the data content inside the divs doesn't spill over the 500px limit (pretty nifty, but it obviously has a huge limitation as is). We'll just assume that the divs are set up style wise to be next to each other like one's taking 20% of screen width and the other is taking 80%. That works pretty well for me, though I'll admit I don't understand it as well as I'd like to. But here's my problem - I could set an absurdly large value for the margin/padding to make this work for a very long page length, but I think that's probably very inefficient and poor programming. How can I set the style of a div to the height of the total HTML document using JavaScript so I can do this programatically and properly? And where should I call the line of JavaScript that would do that? Here was my closest shot so far: function varPageHeight() { document.getElementById('nav').style.padding-bottom = self.innerHeight + 'px'; document.getElementById('nav').style.margin-bottom = self.innerHeight + 'px'; document.getElementById('content').style.padding-bottom = self.innerHeight + 'px'; document.getElementById('content').style.margin-bottom = self.innerHeight + 'px'; } It doesn't work though - it looks like it does screen height instead of document height or something like that. A: If you use CSS properties in JavaScript you can't use dash. CSS property: padding-bottom is paddingBottom in JavaScript so your code should look like: function varPageHeight() { document.getElementById('nav').style.paddingBottom = self.innerHeight + 'px'; document.getElementById('nav').style.marginBottom = self.innerHeight + 'px'; document.getElementById('content').style.paddingBottom = self.innerHeight + 'px'; document.getElementById('content').style.marginBottom = self.innerHeight + 'px'; } or you can use jQuery: function varPageHeight() { var innerHeight = self.innerHeight; $('#nav').css({ 'padding-bottom': self.innerHeight, 'margin-bottom': self.innerHeight }); $('#content').css({ 'padding-bottom': self.innerHeight, 'margin-bottom': self.innerHeight }); } A: To be honest, if you're trying to get equal height floated columns and you're using javascript for the solution anyway, don't depend on padding / margin. It's ugly as hell and brings its own set of problems. Best thing is just to set the height of all the columns to w/e is highest. Here is a solution that does this in jQuery: http://jsfiddle.net/sg3s/6W4wb/ Pure javascript could be done but you'll have a hell of a job making it work properly/cross-browser (old versions of IE specifically) with all their interpetations of what height should be. If you really want that padding/margin solution I want to know why because I can't really think of a good reason to do that. That specific solution was designed as a workarround for a css limitation... When you're using javascript that limitation is no longer there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How should I optimize/structure my database for collecting webshop price development? I have a small personal project, which is supposed to collect data from different webshops. What I basically do, is run a cron script every night. This script uses the Simple HTML DOM Parser for PHP to fetch prices for products in selected product groups. As of now, my database consists of three tables: - stores Name, URL etc for each webshop - products URL, product names etc for each product - prices Prices for every day each product My question is the prices table. Every time the cron script runs, it saves new entries with price data for each product (300+), even if the products price is unchanged. I know I can prevent saving unnecessary data with a check to see wether the price is changed or not. But then again a product can be taken out of stock, leaving me no information of when it went out of stock (which it would if I saved the price each day). How would you guys do this more effective? The cron script would potentially take a long time to execute because of the DOM parsing, and I want to be sure everything is parsed and added to database as expected. A: I guess you could keep track of each DOM you parsed, and store a checksum of it to see if it has changed when you load it again the next night. If the checksum is the same, you'll know you need no parsing and no updating because nothing will have changed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Form working locally, and not in heroku? Rails 3 My form seems to work perfectly fine locally, but gives me a syntax error on heroku. Here is my code thats causing the error: <%= form_for (@item, {:url => [@company, @item]}) do |item_form| %> The error is: syntax error, unexpected '}', expecting keyword_end 2011-09-24T22:25:25+00:00 app[web.1]: ...e, {:url => [@company, @item]}) do |item_form| @output_buf... Then when I tried <%= form_for (@item, :url => [@company, @item]) do |item_form| %> It gave me this error: syntax error, unexpected ',', expecting ')' 2011-09-24T22:18:01+00:00 app[web.1]: ...ffer.append= form_for (@share, :url => [@company, @share]) Any ideas? A: You should remove the space between the method call form_for and the opening parenthesis (. As a general rule, never do this. It's ambiguous and may result in the parser thinking that you're calling form_for with one argument, like this: <%= form_for((@item, :url => [@company, @item])) do |item_form| %> ... which would be a syntax error, resulting in the errors you're seeing (e.g. unexpected comma) # it should be: <%= form_for(@item, :url => [@company, @item]) do |item_form| %> # or, remove the parentheses altogether (up to your usage tastes): <%= form_for @item, :url => [@company, @item] do |item_form| %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7542338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What kind of function is this in JavaScript? I saw this on a forum and I was wondering what it was. If I can get anybody's response it would be very appreciated. var fso = new ActiveXObject ("Scripting.FileSystemObject"); Can you tell me what it does and what browsers support it. Thanks. A: What it does is give access to your local filesystem on your PC. It is only supported by Internet Explorer. A: It's a function which constructs a FileSystemObject in JScript (Microsoft's version implementationcitation from MSDN of JavaScript). This sort of object provides access to a computer's file system. ActiveX is only supported by Internet Explorer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I retrieve the full newsfeed of a user via the Facebook API? I would like to retrieve the full newsfeed including historical data of a given user. In principal, this is straight forward using either an authenticated call to the Graph API or to the FQL API. With the Graph API, I access the me/home endpoint. This results in 25 entries. I can iterate over the pages and retrieve around 8 pages back into history giving me around 200 entries. I write around 200 entries, because with each run through this I get a different number of total entries. Sometimes more, sometimes less. With the FQL API, I call SELECT post_id, created_time, actor_id, message FROM stream WHERE filter_key = 'nf' AND is_hidden=0 AND created_time > 1262304000 LIMIT 500 where the created time reflects 1 Jan 2010. This gives me around 150 entries. Both methods don't seem to allow to work your way backwards into history. In the FQL query, I also tried to play around with the created_time field and LIMIT to go backwards in small chunks but it didn't work. The documentation of the stream table http://developers.facebook.com/docs/reference/fql/stream/ says somehow cryptically: The profile view, unlike the homepage view, returns older data from our databases. Homepage view - as far as I understand - is another word for Newsfeed, so that might mean that what I want is not even possible at all? To make things worse (but that's not the main topic of this question) the returned datasets from the two methods differ. Both contain entries that the other does not show but they also have many entries in common. Even worse, the same is true in comparison to the real newsfeed on the Facebook website. Does anyone have any experience or deeper insights on this? A: Maybe I am mis-understanding your question, but can't you simply call the graph api with /me/home?limit=5000 and then ?limit=5000&offset=5000 or whatever the max limit value Facebook allows is?
{ "language": "en", "url": "https://stackoverflow.com/questions/7542346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Weird~Apache can not find the actually existing "bash" to execute my cgi file~ May be it's too easy for you to answer. My problem is about cgi and apache web server. Make it simple, I have a html "form.html" containing a form in it. To access it, typing "127.0.0.1/form.html" in browser. After clicking "submit" in this html file, it is supposed to adress to "127.0.0.1\cgi-bin\cginame.cgi", the content of "cginame.cgi" is as below: #!/bin/bash if [ $REQUEST_METHOD="GET" ] then data=$QUERY_STRING else data='cat' fi java mortcal $data "mortcal" is a java program calculating and return a HTML page containing results to user. I'm using apache 2.2 and ubuntu 10.04. The problem is when I click the "submit" button in "form.html", I got these in error log: [Sat Sep 24 15:00:20 2011] [error] (2)No such file or directory: exec of '/usr/lib/cgi-bin/mortcgi.cgi' failed [Sat Sep 24 15:00:20 2011] [error] [client 127.0.0.1] Premature end of script headers: mortcgi.cgi I know it's because apache can not find "/bin/bash" to execute the cgi file. But I do have "/bin/bash". It's so weird. Please help me out. Thank you in advance. A: To execute CGI scripts, you need to configure Apache to allow this, and your script has to follow the HTTP protocol by sending back data in the right format, and right permissions, and on and on and on. Here's a great tutorial with an example: http://httpd.apache.org/docs/2.2/howto/cgi.html ... however, I need to say: running a java program from within a shell script via Apache is a bad idea, in general. Each request loads the java runtime engine (JRE), runs the program, then unloads it. There are issues with environment, file ownership and so on -- all of this is why there are application servers like tomcat for java. So if you're just trying something, that's fine. If you're thinking this is a good way to get something done in a professional production environment, I would reconsider. A: As noted, this seems like a poor way to do things, but: * *Do the script file permissions allow execution for the web server user? *Are you using any security framework such as selinux which would apply additional restrictions? A: I checked my configuration files. They are ok. So I kept searching on the web and finally I saw this: "If you've copied over the script from a Windows machine, you may be being tripped up by ^M at end of line. You can use cat -v /usr/lib/cgi-bin/printenv.pl | head -1 to verify that there isn't a ^M at the end of the line. " I did copy my cgi file from windows! I forgot to mention it because I did not think it's a big deal. Now I have removed the ^M by typing this" :%s/^V^M//g in vi. This problem is resolved. Thanks very much for your answer, Mr.Harrison and Dark Falcon, Thank you all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to select multi words in window.getSelection How to select multi words in window.getSelection. In this code, if I choose tweenen paragrap, it will locked word paragraphs and missed `between. And I need select both 2 words. Or even I choose 3 words dd 2 spa, it will select 3 words add 2 spaces. thanks. <script type="text/javascript"> function Selected() { var sel; if ((window.getSelection) && (sel = window.getSelection()).modify) { sel = window.getSelection(); if (!sel.isCollapsed) { sel.modify("move", "backward", "word"); sel.modify("extend", "forward", "word"); } } } </script> <p>put returns between paragraphs, for linebreak add 2 spaces at end</p> <input type="button" onclick="Selected();" value="selected"> A: If I understand you correctly, you want the button to snap the selection to whole words. If so, here's how you can do it: Live demo: http://jsfiddle.net/uCHVQ/1/ Code: function Selected() { var sel; if ((window.getSelection) && (sel = window.getSelection()).modify) { sel = window.getSelection(); if (!sel.isCollapsed) { // Detect if selection is backwards var range = document.createRange(); range.setStart(sel.anchorNode, sel.anchorOffset); range.setEnd(sel.focusNode, sel.focusOffset); var backwards = range.collapsed; range.detach(); // modify() works on the focus of the selection var endNode = sel.focusNode, endOffset = sel.focusOffset; sel.collapse(sel.anchorNode, sel.anchorOffset); if (backwards) { sel.modify("move", "forward", "word"); sel.extend(endNode, endOffset); sel.modify("extend", "backward", "word"); } else { sel.modify("move", "backward", "word"); sel.extend(endNode, endOffset); sel.modify("extend", "forward", "word"); } } } } (By the way, is that code originally from something I've posted? It looks familiar but I can't find it).
{ "language": "en", "url": "https://stackoverflow.com/questions/7542352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }