text
stringlengths
8
267k
meta
dict
Q: How to make a common subclass to remove duplicate code I have two classes one is derived from CheckBoxList and the second one from DropDownList. The code inside them is exactly the same. The only difference is that I need first one at places where I need to show checkboxlist and second one to show dropdownlist. Below is my code: using System; using System.Collections.ObjectModel; using System.Web.UI.WebControls; namespace Sample { public class MyCheckBoxList : CheckBoxList { public int A { get; set; } public int B { get; set; } protected override void OnLoad(EventArgs e) { //dummy task Collection<int> ints = new Collection<int>(); //........ this.DataSource = ints; this.DataBind(); } } } The second one using System; using System.Collections.ObjectModel; using System.Web.UI.WebControls; namespace Sample { public class MyDropDownList : DropDownList { public int A { get; set; } public int B { get; set; } protected override void OnLoad(EventArgs e) { //dummy task Collection<int> ints = new Collection<int>(); //........ this.DataSource = ints; this.DataBind(); } } } Now as you can see the internal code is exactly the same which I want to avoid. How can I make a common class for it so as to remove code duplicacy? A: You can create a third class public class Entity { public int A { get; set; } public int B { get; set; } Collection<int> GetCollection() { //dummy task Collection<int> ints = new Collection<int>(); //........ return ints; } } And then use it in other classes public class MyDropDownList : DropDownList { public MyDropDownList() { Entity = new Entity(); } public Entity {get;set;} protected override void OnLoad(EventArgs e) { this.DataSource = Entity.GetCollection(); this.DataBind(); } } A: you can not, because c# does not support multiple inheritance of implementation (and you are already subclassing). you could refactor some of the code into a third class and have each of your classes have an instance and delegate calls to it. you could try something like this: http://www.codeproject.com/KB/architecture/smip.aspx, but it looks like a lot of work. A: You use composition, Make another class that is not related to these two classes, then have the common code in that one, when you need to use the code in either classes you make an instance, you can also use it thorugh an interface. No need to use inheritnece. Update : Code Below ( Modified the code already provided by meziantou) internal interface IEntity { int A { get; set; } int B { get; set; } Collection<int> GetCollection { get; } } internal class Entity : TrialBalanceHTMLToDataTable.TrialBalance.IEntity { public int A { get; set; } public int B { get; set; } public Collection<int> GetCollection { get{ //dummy task Collection<int> ints = new Collection<int>(); //........ return ints; } } } public class MyDropDownList : DropDownList { public MyDropDownList() { _Entity = new Entity(); } private IEntity _Entity { get; set; } protected override void OnLoad(EventArgs e) { this.DataSource = _Entity.GetCollection; this.DataBind(); } } A: It would seem that what you are trying to accomplish is to have a single class, that is MyDropDownList, be able to inherit properties from the DropDownList, and to have the MyCheckBox class inherit properties from the CheckBox class, while having your two My* classes have some extra properties, which happen to be identical. As others have suggested, the easiest way to accomplish this would be through Multiple Inheritance. In your example specifically, that would mean creating a (possibly abstract) class that describes the shared attributes between MyDropDownList and MyCheckBox, and then have those two classes inherit from both their respective System.Web.UI.WebControls bases as well as this "shared" class. However, as it has been said, C# doesn't support multiple inheritance. From Chris Brumme via that link: The number of places where MI is truly appropriate is actually quite small. In many cases, multiple interface inheritance can get the job done instead. In other cases, you may be able to use encapsulation and delegation. You may have also considered using Interfaces. This, as you may have discovered, would be an inappropriate choice for your solution as an Interface only allows you to define that there are certain properties and methods in a class, but not how the properties or methods are defined. So again, this is an inappropriate choice for removing duplicate code. What does this mean for you? Well, if you're looking to write a MyDropDownList class that supports both myCustomDDLInstance.SelectedIndex and myCustomDDLInstance.A syntaxes, you will have to do a little bit of "magic". But the fact that your language doesn't support what you are trying to do should raise a red flag! It's not necessarily wrong, but it should be a strong indicator that you may want to reexamine your design. My guess is that the duplicated part of the two classes can stand alone as it's own logical entity. This means that you can justifiably create your own class to hold these shared properties and methods. Here's what we get: SampleControl.cs public class SampleControl { public int A { get; set; } public int B { get; set; } public Collection<int> MysteryCollection { get { Collection<int> ints = new Collection<int>(); //........ return ints; } } } If CSharp did in-fact support multiple inheritance, your MyDropDownList class could inherit from both DropDownList and SampleControl and you'd be done. But again, this isn't possible. So how do we accomplish your goal? It's a bit convoluted, but you can Encapsulate your shared properties and methods in each of your custom classes. Here's an example for the MyDropDownList class (note that MyCheckBoxList would be the same, just change the class name: public class MyDropDownList : DropDownList { private SampleControl mySampleControl { get; set; } public int A { get { return mySampleControl.A; } set { mySampleControl.A = value; } } public int B { get { return mySampleControl.B; } set { mySampleControl.B = value; } } public MyDropDownList() { mySampleControl = new SampleControl(); } protected override void OnLoad(EventArgs e) { //dummy task this.DataSource = mySampleControl.MysteryCollection; this.DataBind(); } } A class designed in this way, while a bit convoluted, should accomplish the type syntax that you are looking for. As a final note I would strongly encourage you to at least consider re-examining your design and seeing if there is a better way for you to approach your class hierarchy. My recommendation is that if your shared attributes can exist on their own as a logical entity, they probably should be their own class. And if so, that class is probably a rightful and logical member of your MyDropDownList and MyCheckBox classes. Which means that you should be using the myDropDownListInstance.SharedAttributesClassName.A syntax. It's both more explicit and more honest.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Swing shows empty tooltips, how to disable this? I'm creating a java Swing app and I'm new to that. The problem is that when I move cursor to menu item, for example, it shows me an empty tooltip. Is there any way to disable this? P.S. Using NetBeans, if it's important. Maybe it generated some odd code? A: Go to the properties of the menu or menu item that displays the empty tooltip and choose tooltip. Then add "null" as a String value for setTooltipText. The empty tooltip will then dissapear. If the toolTipText property in the designer is bold (changed), you can just press the Reset to Default button at the bottom of the above window, or even right-click on said property in the list and select Restore Default Value. A: I guess you're using the (now dead) Swing Application Framework. Netbeans automatically generates an entry in the properties file associated with each panel for the tooltip, with an empty value (instead of not generating the property at all if you leave the text box blank). Just remove the property in the properties file manually. The lines looking like the following should be removed: someAction.shortDescription=
{ "language": "en", "url": "https://stackoverflow.com/questions/7590038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Data saving as blank in CakePHP I have a foreach loop that saves a bunch of records into a table using cakePHP foreach($interests as $id){ $this->data['UserInterest']['user_id'] = $user_id; $this->data['UserInterest']['interest_id'] = $id; $this->data['UserInterest']['other_interest'] = $other; $UserInterest = new UserInterest; if(!$UserInterest->save($this->data)) { $this->Session->setFlash(__l('Failed to save Interests.') , 'default', null, 'error'); } } All saves fine except the other interest UPDATE: I've did the following I can exho it out perfectly if I do this $this->data['UserInterest']['other_interest'] = $other; echo $this->data['UserInterest']['other_interest']; $UserInterest = new UserInterest; But somehow it saves as blank? My database layout looks like this CREATE TABLE IF NOT EXISTS `users_interests` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user_id` bigint(20) NOT NULL, `interest_id` bigint(20) NOT NULL, `other_interest` varchar(150) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) and my model like this <?php class UserInterest extends AppModel { var $name = 'UserInterest'; var $useTable="users_interests"; //$validate set in __construct for multi-language support //The Associations below have been created with all possible keys, those that are not needed can be removed var $belongsTo = array( 'User' => array( 'className' => 'User', 'foreignKey' => 'user_id', 'conditions' => '', 'fields' => '', 'order' => '', ) , 'Interests' => array( 'className' => 'Interest', 'foreignKey' => 'interest_id', 'conditions' => '', 'fields' => '', 'order' => '', ) ); function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'user_id' => array( 'rule' => 'numeric', 'allowEmpty' => false, 'message' => __l('Required') ) ); } } ?> Am I doing something wrong? UPDATE: I did the following $this->data['UserInterest']['user_id'] = $user_id; $this->data['UserInterest']['interest_id'] = $id; $this->data['UserInterest']['other_interest'] = $other; echo '<pre>'; var_dump($this->data['UserInterest']); var_dump($other); var_dump($this->data['UserInterest']['other_interest']); $this->UserInterest = ClassRegistry::init('UserInterest'); And the var_dump results where the following, and still it did not save array(3) { ["user_id"]=> string(3) "659" ["interest_id"]=> string(2) "10" ["other_interest"]=> string(17) "Share Investments" } string(17) "Share Investments" string(17) "Share Investments" A: And old post but would like to add this here.... Always have $this->Modelname->create(); in loops to save multiple records with loop. An most often this is the case which causes the error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++ Class: Passing a parameter I'm just learning classes so I'm trying something basic. I have a class called Month as shown below. For my first test, I want to supply a number from 1 through 12 and output the name of the month ie. 1 = Jan. class Month { public: Month (char firstLetter, char secondLetter, char thirdLetter); // constructor Month (int monthNum); Month(); void outputMonthNumber(); void outputMonthLetters(); //~Month(); // destructor private: int month; }; Month::Month() { //month = 1; //initialize to jan } void Month::outputMonthNumber() { if (month >= 1 && month <= 12) cout << "Month: " << month << endl; else cout << "Not a real month!" << endl; } void Month::outputMonthLetters() { switch (month) { case 1: cout << "Jan" << endl; break; case 2: cout << "Feb" << endl; break; case 3: cout << "Mar" << endl; break; case 4: cout << "Apr" << endl; break; case 5: cout << "May" << endl; break; case 6: cout << "Jun" << endl; break; case 7: cout << "Jul" << endl; break; case 8: cout << "Aug" << endl; break; case 9: cout << "Sep" << endl; break; case 10: cout << "Oct" << endl; break; case 11: cout << "Nov" << endl; break; case 12: cout << "Dec" << endl; break; default: cout << "The number is not a month!" << endl; } } Here is where I have a question. I want to pass "num" into the outputMonthLetters function. How do I do this? The function is void, but there must be some way to get the variable into the class. Do I have to make the "month" variable public? int main(void) { Month myMonth; int num; cout << "give me a number between 1 and 12 and I'll tell you the month name: "; cin >> num; myMonth.outputMonthLetters(); } A: What you probably want to do is something like this: int num; cout << "give me a number between 1 and 12 and I'll tell you the month name: "; cin >> num; Month myMonth(num); myMonth.outputMonthLetters(); Note that myMonth isn't declared until it's needed, and the constructor taking the month number is called after you determine what month number you are looking for. A: Try using a parameter on the Method void Month::outputMonthLetters(int num); Than you could do: Month myMonth; int num; cout << "give me a number between 1 and 12 and I'll tell you the month name: "; cin >> num; myMonth.outputMonthLetters(num); I'm not the C++ guru, but don't you have to create an instance of Month? A: Change your void Month::outputMonthLetters() to static void Month::outputMonthLetters(int num) { switch(num) { ... } } i.e. add a parameter to the method, and (optionally) make it static. But this is not a very good example of a class to start with...
{ "language": "en", "url": "https://stackoverflow.com/questions/7590047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AppFabric vs asp.net cache with sqldependency performance I'm working on a plan to increase performance and scalability of a web app by caching a user database for a WCF web service. Goals are to increase performance by accessing this data inProc vs a round trip the database server, as well as increase scalability of the service by reducing the load on the database server, thus allowing more web servers to be added to increase scale. In researching AppFabric, I really don't see the value in my situation because it seems like for the most part, I'm just replacing a round trip to the database with a round trip to a cache cluster (which seems like it might even have more overhead than the db to keep nodes in synch). For the performance question, it seems like using the asp.net cache (in process) would be much faster than a round trip to the cache cluster, even though the data is in memory on those servers, and even if some of it is cached locally (I believe that would still be out of process from the web app). For the scalability issue, it also seems easier to be able to add identical web servers to a web farm (each caching the user data in process), rather than manage a cache cluster seperately which adds complexity. With that said, could someone explain why I would choose one approach over the other, given my stated goals? If you recommend the AppFabric approach, can you explain how the performance would be better than storing data in the asp.net cache in process. Thanks! A: You are right that the App fabric cache is stored out of process. When the request comes in for a app fabric cache item, there is first a lookup to find where the item is, then a wcf net.tcpip call to get the item. Therefore, it will be slower than asp.net caching. But there are times when appfabric caching is better: * *You do not loose the cache when the application pool is recycled. *If you have 100 web servers then you need to get the data from the database once, not 100 times *If you are running Enterprise Edition of windows you do not loose the cache if a machine goes down A: I found this topic on codeproject. Hope it can answer your question A: you should consider NCache as an other option. NCache is an extremely fast in-memory distributed cache which reduces the performance bottlenecks associates with the database enhance the scalability of the app. As far as use of asp.net cache is concerned, you should keep into mind its limitations as well. it is good for small web farms only. but when the number of servers grow, asp.net cache may ends up with some performance and scalability issues due to its in-process nature. in a larger web garden you need to have an in-memory distributed cache. Read this for reference
{ "language": "en", "url": "https://stackoverflow.com/questions/7590048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to make a Django template tag which expands into another (macro) We've got a third-party Django template tag like this: {% frobnicate "foo", "bar", "baz" %} do stuff with {{ frobnicator }} {% endfrobnicate %} Unfortunately, the do stuff with {{ frobnicator }} part is repeated every time we use the {% frobnicate %} tag. What's the easiest way to build a tag so that something like {% frobnicate2 "foo", "bar", "baz" %} ...expands into the first example? Update: Simple inclusion tags aren't enough. I didn't make it clear in the example above, but I need to be able to manipulate the parameters passed to the expansion. A: Create a template filter that will render your custom string instead of a template file. Declare it like this (this code is tested): #app_name/templatetags/frobnicative_tags.py from django.template import Template, Context register = Library() @register.tag(name = 'frobnicate2') def frobnicate2(parser, token): args = token.split_contents() template_string = """ {%% load my-third-party-frobnicator-lib %%} {%% frobnicate %s %%} do stuff with {{ frobnicator }} {%% endfrobnicate %%} """ return Frobnicate2(''.join(args[1:]), template_string) class Frobnicate2(template.Node): def __init__(self, frobnicative_args, template_string): self.template_string = template_string self.args = frobnicative_args def render(self, context): """ Dict inside a Context() is empty because we need to pass a context in order to render, even if the context is empty. """ return Template(self.template_string % self.args).render(Context({})) Don't forget to replace "my-third-party-frobnicator-lib" with a name of an actual third party library that you're loading. Then you can render the whole whird-party tag sequence using {% frobnicate2 "foo", "bar", "baz" %} just as you wanted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Complex Database Relations (Junction Tables) My Question is about the idea of combining two junction tables into one, for similarly related tables. Please read to see what I mean. Also note that this is indeed a problem I am faced with and therefore relevant to this forum. It is just a topic of broad consequence for which I'm hoping to elicit a bit more participation from various professionals to get a better census of "best practice" if you will. I have this rather challenging database design problem. I'm hoping this will be sort of a wiki that many people can contribute to and learn from. To make this easier, I've created a set of graphics, and will break the problem down into 1) Process, and 2) Structure. Process Steps * *A request (DocRequest) for documentation (Publication) is made. *A new publication is created IF said publication does not already exist. *A running log (StatusReport) is kept for progress on fulfilling the request. Note: For any given Publication there may be many DocRequests and StatusReports (including updates) Database Structure Note: Both the DocRequest and StatusReport tables have numerous fields and supporting tables not shown in the attached graphics. Furthermore, a particular Publication is the master record to which all records in those tables belong. --Current Implementation-- Note: The major flaw with this design is that whenever you create either a new DocRequest and StatusReport record, you have to also create a new record in the Publications table (which acts like a junction table), but this also creates a new Publication as a result. This is not the desired behavior. --Typical Implementation-- (for this type of relationship) Note: This is ok, and probably ideal, but handles updates to either the DocRequest and StatusReport tables, independently linking them to the Publication to which they belong. --My Preferred Implementation-- (for this special case) Note: The idea I had here, was simply to combine the dual junction tables into one. In this case the junction table would get a new record anytime either the DocRequest or StatusReport had a insert occur. I will likely handle this with a trigger. Discussion Now for the discussion. I would like to know from my fellow Database Developers if you think this is a bad idea, and what issues might arise from this. I think the net number of records should be identical as with the two separate junction tables, and in fact uses slightly less space by saving an extra ID column. :) Let me know what you guys think. I would really like to get many people involved in this discussion. Cheers! :) A: I think you're hurting yourself by thinking in terms of junction tables. Just think of tables. * *Since StatusReport has to do with the status of the document request, you need a table that relates those two somehow. *"StatusReport" is an awful name for a table that stores facts about the status of a document request. *"ID" is an awful name for any column in any table. *The id number of the publication seems to have more to do with the document request than with the status of the request. (You said, "A new publication is created IF said publication does not already exist." Frankly, that's skating pretty close to the edge of not making sense.) So the publication number almost certainly belongs in the DocRequest table. Referring to the diagram of your preferred implementation, I'd drop the table TripleJunction, and replace StatusReport with this. -- Predicate: Document request number (doc_request_id) has status (status) -- as of date and time (status_as_of). create table document_request_status ( doc_request_id integer not null references DocRequest (id), status_as_of timestamp not null default current_timestamp, status varchar(10) not null, -- other columns go here primary key (doc_request_id, status_as_of) );
{ "language": "en", "url": "https://stackoverflow.com/questions/7590051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to configure project in Hudson/Jenkins to report to Jira I have installed and configured this plugin: http://wiki.hudson-ci.org/display/HUDSON/JIRA+Plugin In Jira I have turned ON option "accept api calls" in Jira logs i can see that Hudson established connection but nothing else happens, ive got test builds and they're failing but hudson doesnt report anything to jira how to name job? how to name tests? do i need jiraID? how to create issue that works with hudson? how to actually tie hudson job with jira issue? A: I recommend you to use this plugin: Marvelution JIRA Hudson Integration. With it I hope yo could solve your problem. You have to install 2 different parts of the plugin, one in JIRA and another one in Jenkins (it enables a new API to allow JIRA to connect with Jenkins). Then, you have to go to JIRA Administration, Hudson, Servers, Add Server, configure there your Jenkins server. After that, go to Administration, Hudson, Associations, Add a Hudson Association and link your project in JIRA with your Jenkins task (a list of tasks will be shown). Finally, you only have to go to your JIRA project's page and you'll see a Hudson tab in which you can see the integration that you need. A: Jenkins cannot resolve Jira issues. It only can post comments. Also Jenkins does not post comments in Jira issues named as tests or jobs or anything in scans comments in commit to svn and if there is a Jira id then after build it posts comment. This is too poor and basic functionality for me so I gave up. I recently found this plugin: https://wiki.jenkins-ci.org/display/JENKINS/Jira+Issue+Updater+Plugin but I'm in the middle of a project and dont want do test it now A: If you want to create issues in Jira from e.g. failed tests in Jenkins, then the JiraTestResultReporter plugin will help you. See this link. A: I am currently attempting to integrate Jenkins (version 1.53+) with JIRA (v5.2) to have the i) create jira issue and ii) update jira issue capabilities. My source control is SVN and my user is configured with CROWD Currently, I am able to only update a JIRA issue from a post-build. The key is to have the latest SVN commit message begin with '-' as the format (i.e. 'PROJECT-3' denotes issue number 3 for jira project key = PROJECT) See the overall plugin and configuration process at this link: http://blog.dominikschadow.de/?p=313 output of jenkins updates the JIRA issue (referenced in the svn commit message as I indicated) with:i) STATUS ii)jenkins job output link iii) svn commit message and file(s) changes / removed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: DirectX 2D drawing with Vb.net I'm using using System.Graphics for my latest project (A simple 2D application). Problem is, it gets a horrible FPS and I'm only drawing 8x8 tiles (usually 10-12 is enough to bring it down to 12FPS). A friend of mine suggested that I use DirectX. He also suggested XNA but I opposed because I don't want my clients to have to install the XNA distributional. DirectX is common enough (to my knowledge) and I can just include the dll's if I need to. So, my search began. I've been looking only for DirectX 2D tutorials for VB.net. I've had no solid success thus far. In truth, all I need to do is be able to draw bitmap x at position pos. I've been using System.Graphics and a hacked up bitmap as my buffer thus far so I'll go for any improvement that I can get. I'm using VB.net so I'll be ok if you give my one for C#, I'm pretty good at being able to read it (and I have a nice converter too). I would just prefer VB.net to save time. Thanks! :) A: This article in MSDN Magazine was in 2003 edition had a nice example of managed DirectX code in action: http://msdn.microsoft.com/en-us/magazine/cc164112.aspx Sadly enough, currently, there's no managed library of DirectX (a.k.a. DirectX .NET wrapper) in DX 10 and DX 11. Microsoft only provided managed library for DX 9.0a and DX 9.0b. In Managed DirectX wikipedia, you'll see that it's being replaced by Microsoft XNA. If you download current/latest DirectX SDK, you will have samples only in C++ and HLSL codes. If you really need fancy UI and also nice animation and 3D drawing based on DirectX, you can go use WPF, especially WPF in .NET 3.0 SP2 (or simply download and install .NET 3.5 SP1). WPF is build on top of DirectX 9.0c stack, without worrying to know large libraries of DirectX 9 API. You'll also get 3D primitives support too. More on WPF, visit this: http://msdn.microsoft.com/en-us/library/ms754130.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7590059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: git merging local branch with remote branch I have a remote git repository where I have a tag (tag-1) that is several commits back from master. I'm trying to take the very last commit (6337dcb1) and add that to an updated tag-1, creating a new tag called tag-2. I'm pretty new to git so I'm getting confused about the process that I'm trying to piece together. So far I have cloned the remote repository and performed a: git checkout tag-1 which gives me the following message: Note: checking out 'tag-1'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. So far so good? After this, I am trying to cherry-pick the latest commit (6337dcb1) with git cherry-pick 6337dcb1 Ok, so after this I'm not sure how to proceed. It says that I'm not currently on any branch so I might have messed up when checking out the tag. Do I simply commit the files and apply a new tag or is there something else I'm supposed to do here? I'm fairly new to git and have only been dealing with pushes, pulls and merges so far so any help in understanding this would be greatly appreciated. A: Instead of doing git checkout tag-1 create a new branch to work on based on tag-1 using: git checkout -b branch-1 tag-1 After you have made the commit(s) you want, do git tag tag-2
{ "language": "en", "url": "https://stackoverflow.com/questions/7590064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Updating a file with library (overwriting just a specific section) I want to ask if there is any way to update say a text file with a content of "ooooo" to "ooXXo" using the fstream library. I know there is a way with cstdio but I don't want to use that one because of unsupported exception handling... Also, I don't want to read the file to memory, update the section I want and then write everything to a clean file...basically I'm looking for a way to do this with fstream: /* fseek example */ #include <stdio.h> int main () { FILE * pFile; pFile = fopen ( "example.txt" , "w" ); fputs ( "This is an apple." , pFile ); fseek ( pFile , 9 , SEEK_SET ); fputs ( " sam" , pFile ); fclose ( pFile ); return 0; } A: #include <fstream> int main() { std::ofstream os("example.txt"); os<<"This is an apple."; os.seekp(9); os<<" sam"; return 0; } A: #include <fstream> int main (){ std::fstream pFile("example.txt"); pFile << "This is an apple."; pFile.seekp(9); pFile << "sam"; pFile.close(); return 0; } fstream by default opens the file for both reading and writing. There's a second argument with a default value in the constructor which controls that behavior.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using NodeJS for real time live updating view using database I have been playing around with Nodejs and now wanted to know if i could create live update to a view/page as shown in this tutorial here The example above would apply to all users on site, what i want is to target my updates to certain users. Do i create a array storing all the client sockets, a socket is created when the users logs in. Another thing how can i update the webpage or the view if something has updated in the database do i poll the server every second? I am using MySQL has database, should i used Redis instead? EDIT: one more question I was wondering how can nodejs check if the database field/s have been updated or changed and than update the view or webpage? thanks A: Do i create a array storing all the client sockets, a socket is created when the users logs in. If you would use socket.io module for managing connection between clients and server, then you don't have to worry about the structure or stored clients since it would be managed for you in the background. It offers also various fallbacks (including long polling) if client browsers do not support advanced transports like WebSockets. Another thing how can i update the webpage or the view if something has updated in the database do i poll the server every second? DO NOT poll the server every second, since transports like long polling and WebSockets were introduced to AVOID this. Since you would have persistent connection between client and server with socket.io (which are using techniques and technologies like long polling or WebSockets), you can rather easily create evented system which updates or notifies certain client(s) about the change at the time when it happens. I am using MySQL has database, should i used Redis instead? Redis is very good Key/Value store for real-time, frequently updated data which do not require complex querying. If you need advanced querying support for your data, then try to look at MongoDB for example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: git: getting rid of previous commit so that you can amend the one before what happened: change1, git commit, git push, change2, git commit what should have happened: change1, git commit, git push, change2, git commit --amend It's not important that I retain change2, but it is important that I am able to amend the original commit. How do I do this? A: Since you have pushed it, be aware that this is tricky and you are rewriting history. You can git rebase -i to before the first commit and choose edit for the commit in the text that is presented to you. This way, you will be brought to the first commit state where you change / amend and then git will apply the next commit over it. Or you can git reset --soft first to go to first commit and amend it along with change2. Or git reset --hard first to go to the first commit and amend it without the change2 A: [I assume you know that Linus thinks this is evil] $ git reset --hard HEAD^ # remove last commit $ git commit --amend $ git push --force <remote> <branch> If you want the last commit to be applied afterward, then do $ SHA1=`git rev-parse master` $ git branch temp # now the three commands above $ git cherry-pick $SHA1 $ git branch -d temp
{ "language": "en", "url": "https://stackoverflow.com/questions/7590069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jquery Move Table Row but NOT past header I have table rows that move up and down, but my problem is that the data table rows replace the table header (first row). I want a fixed first row so that when you click the Up arrow you do not move the row up to replace the header. I have tried some conditional logic to check if the current row is the table's first row, but it is not working. $(document).ready(function(){ <!--- Move: click to move rows up or down ---> $(".up,.down").click(function(){ var row = $(this).parents("tr:first"); <!-- this var does not work --> var firstrow = $('table')[0].rows[0]; <!-- Check that is not the first row NEEDS FIXED --> if (row != firstrow){ if ($(this).is(".up")) { row.insertBefore(row.prev()); } else { row.insertAfter(row.next()); } } }); }); <table> <tr> <td>Do Not Replace Me</td> <td >&nbsp;</td> </tr> <tr> <td>Two</td> <td> <a href="#" class="up">Up</a> <a href="#" class="down">Down</a> </td> </tr> <tr> <td>Three</td> <td> <a href="#" class="up">Up</a> <a href="#" class="down">Down</a> </td> </tr> </table> The table must stay as is, and I cannot change td to th or anything like that. I am hoping there is just a way to fix those two lines of code. A: This would, as I suppose you know (given your disclaimer that the html must 'stay as is...'), be much easier if you could put the header/first row into a thead element and the remainder into a tbody, but one way that works with the html 'as is:' $(".up,.down").click(function() { var row = $(this).parents("tr:first"); var firstrow = $('table tr:first'); if ($(this).is(".up") && row.prevAll().length > 1) { row.insertBefore(row.prev()); } else if ($(this).is(".down") && row.nextAll().length > 0) { row.insertAfter(row.next()); } else { return false; } }); JS Fiddle demo. Incidentally, and as an aside, your script may have been generating errors from the comment (though I do suspect the were added for our benefit, rather than in your actual JavaScript) syntax: <!-- comment text --> is html syntax, and within the confines of the <script></script> tags is invalid, to comment JavaScript use either: // single-line comment // which needs to have the double-slash // preface each comment-line... or: /* This is a multi-line comment, and this text will happily remain commented-out until you get to one of these comment-close things, just to the right -> */ References: * *.prevAll(). *.nextAll(). *.length. A: The jQuery index function should be some help here. $(".up, .down").click(function() { // get parent tr var $row = $(this).parents('tr:first'); var $link = $(this); // count all tr var count = $('table tr').length; // if tr isn't the first if($row.index() !== 0) { // if direction is up and there is a tr above if($link.hasClass('up') && $row.index() > 1) { $row.insertBefore($row.prev()); } // if direction is down and there is a tr below else if($link.hasClass('down') && $row.index() < count - 1) { $row.insertAfter($row.next()); } } }); A: I recently ran into a similar issue where my rows were moving above the 'header' rows in my table. I solved it using a basic class call in the jquery and assigning the class to the table. This just adds another level of depth to the element specification so it ignores table rows that do not comply. Try this: var row = $(this).parents("tr.MoveableRow:first"); Then add to each tag, class = "MoveableRow". Ex: <tr class="MoveableRow">
{ "language": "en", "url": "https://stackoverflow.com/questions/7590070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Itextsharp: Adjust 2 elements on exactly one page So, I'm having this problem using C# (.NET 4.0 + WinForms) and iTextSharp 5.1.2. I have some scanned images stored on a DB and need to build on the fly PDF with those images. Some files have just one page and other ones hundreds. That is working just fine using: foreach (var page in pages) { Image pageImage = Image.GetInstance(page.Image); pageImage.ScaleToFit(document.PageSize.Width,document.PageSize.Height); pageImage.Alignment = Image.ALIGN_TOP | Image.ALIGN_CENTER; document.Add(pageImage); document.NewPage(); //... } The problem is: I need to add an small table at the bottom of the last page. I try: foreach (var page in pages) { Image pageImage = Image.GetInstance(page.Image); pageImage.ScaleToFit(document.PageSize.Width,document.PageSize.Height); pageImage.Alignment = Image.ALIGN_TOP | Image.ALIGN_CENTER; document.Add(pageImage); document.NewPage(); //... } Table t = new table.... document.Add(t); The table is successfully added but IF the size of the image fits the page size of the document then the table is added on the next page. I need to resize the last image of the document (if it has multiple ones, or the first if has only 1) in order to put the table directly on that page (with the image) and that both ocuppy just one page. I try to scale the image by percent BUT given that the image size of the image that'll be on the last page is unknow and that it must FILL the biggest portion of the page I need to do that dinamically. Any idea? A: Let me give you a couple of things that might help you and then I'll give you a full working example that you should be able to customize. The first thing is that the PdfPTable has a special method called WriteSelectedRows() that allows you to draw a table at an exact x,y coordinate. It has six overloads but the most commonly used one is probably: PdfPTable.WriteSelectedRows(int rowStart,int rowEnd, float xPos, float yPos, PdfContentByte canvas) To place a table with the upper left corner positioned at 400,400 you would call: t.WriteSelectedRows(0, t.Rows.Count, 400, 400, writer.DirectContent); Before calling this method you are required to set the table's width using SetTotalWidth() first: //Set these to your absolute column width(s), whatever they are. t.SetTotalWidth(new float[] { 200, 300 }); The second thing is that the height of the table isn't known until the entire table is rendered. This means that you can't know exactly where to place a table so that it truly is at the bottom. The solution to this is to render the table to a temporary document first and then calculate the height. Below is a method that I use to do this: public static float CalculatePdfPTableHeight(PdfPTable table) { using (MemoryStream ms = new MemoryStream()) { using (Document doc = new Document(PageSize.TABLOID)) { using (PdfWriter w = PdfWriter.GetInstance(doc, ms)) { doc.Open(); table.WriteSelectedRows(0, table.Rows.Count, 0, 0, w.DirectContent); doc.Close(); return table.TotalHeight; } } } } This can be called like this: PdfPTable t = new PdfPTable(2); //In order to use WriteSelectedRows you need to set the width of the table t.SetTotalWidth(new float[] { 200, 300 }); t.AddCell("Hello"); t.AddCell("World"); t.AddCell("Test"); t.AddCell("Test"); float tableHeight = CalculatePdfPTableHeight(t); So with all of that here's a full working WinForms example targetting iTextSharp 5.1.1.0 (I know you said 5.1.2 but this should work just the same). This sample looks for all JPEGs in a folder on the desktop called "Test". It then adds them to an 8.5"x11" PDF. Then on the last page of the PDF, or if there's only 1 JPEG to start with on the only page, it expands the height of the PDF by however tall the table that we're adding is and then places the table at the bottom left corner. See the comments in the code itself for further explanation. using System; using System.Text; using System.Windows.Forms; using iTextSharp.text; using iTextSharp.text.pdf; using System.IO; namespace Full_Profile1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public static float CalculatePdfPTableHeight(PdfPTable table) { //Create a temporary PDF to calculate the height using (MemoryStream ms = new MemoryStream()) { using (Document doc = new Document(PageSize.TABLOID)) { using (PdfWriter w = PdfWriter.GetInstance(doc, ms)) { doc.Open(); table.WriteSelectedRows(0, table.Rows.Count, 0, 0, w.DirectContent); doc.Close(); return table.TotalHeight; } } } } private void Form1_Load(object sender, EventArgs e) { //Create our table PdfPTable t = new PdfPTable(2); //In order to use WriteSelectedRows you need to set the width of the table t.SetTotalWidth(new float[] { 200, 300 }); t.AddCell("Hello"); t.AddCell("World"); t.AddCell("Test"); t.AddCell("Test"); //Calculate true height of the table so we can position it at the document's bottom float tableHeight = CalculatePdfPTableHeight(t); //Folder that we are working in string workingFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test"); //PDF that we are creating string outputFile = Path.Combine(workingFolder, "Output.pdf"); //Get an array of all JPEGs in the folder String[] AllImages = Directory.GetFiles(workingFolder, "*.jpg", SearchOption.TopDirectoryOnly); //Standard iTextSharp PDF init using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) { using (Document document = new Document(PageSize.LETTER)) { using (PdfWriter writer = PdfWriter.GetInstance(document, fs)) { //Open our document for writing document.Open(); //We do not want any margins in the document probably document.SetMargins(0, 0, 0, 0); //Declare here, init in loop below iTextSharp.text.Image pageImage; //Loop through each image for (int i = 0; i < AllImages.Length; i++) { //If we only have one image or we are on the second to last one if ((AllImages.Length == 1) | (i == (AllImages.Length - 1))) { //Increase the size of the page by the height of the table document.SetPageSize(new iTextSharp.text.Rectangle(0, 0, document.PageSize.Width, document.PageSize.Height + tableHeight)); } //Add a new page to the PDF document.NewPage(); //Create our image instance pageImage = iTextSharp.text.Image.GetInstance(AllImages[i]); pageImage.ScaleToFit(document.PageSize.Width, document.PageSize.Height); pageImage.Alignment = iTextSharp.text.Image.ALIGN_TOP | iTextSharp.text.Image.ALIGN_CENTER; document.Add(pageImage); //If we only have one image or we are on the second to last one if ((AllImages.Length == 1) | (i == (AllImages.Length - 1))) { //Draw the table to the bottom left corner of the document t.WriteSelectedRows(0, t.Rows.Count, 0, tableHeight, writer.DirectContent); } } //Close document for writing document.Close(); } } } this.Close(); } } } EDIT Below is an edit based on your comments. I'm only posting the contents of the for loop which is the only part that changed. When calling ScaleToFit you just need to take tableHeight into account. //Loop through each image for (int i = 0; i < AllImages.Length; i++) { //Add a new page to the PDF document.NewPage(); //Create our image instance pageImage = iTextSharp.text.Image.GetInstance(AllImages[i]); //If we only have one image or we are on the second to last one if ((AllImages.Length == 1) | (i == (AllImages.Length - 1))) { //Scale based on the height of document minus the table height pageImage.ScaleToFit(document.PageSize.Width, document.PageSize.Height - tableHeight); } else { //Scale normally pageImage.ScaleToFit(document.PageSize.Width, document.PageSize.Height); } pageImage.Alignment = iTextSharp.text.Image.ALIGN_TOP | iTextSharp.text.Image.ALIGN_CENTER; document.Add(pageImage); //If we only have one image or we are on the second to last one if ((AllImages.Length == 1) | (i == (AllImages.Length - 1))) { //Draw the table to the bottom left corner of the document t.WriteSelectedRows(0, t.Rows.Count, 0, tableHeight, writer.DirectContent); } } A: Just use a method table.CalculateHeights() if you want to know the height of table.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iphone: how to add text above and below the image in the scrollvew? I would like to add a page number above the image such as "1 of 50" and description of the image below the image in the scrollview. I have looked at this LINK but still couldn't figure out how to make it happen. here is my sample code of the images scrollview. Im trying to find a sample that can add text and scroll with the images NSUInteger i; for (i = 1; i <= kNumImages; i++) { NSString *imageName = [NSString stringWithFormat:@"images%d.jpg", i]; UIImage *image = [UIImage imageNamed:imageName]; UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; // setup each frame to a default height and width, it will be properly placed when we call "updateScrollList" CGRect rect = imageView.frame; rect.size.height = kScrollObjHeight; rect.size.width = kScrollObjWidth; imageView.frame = rect; imageView.tag = i; // tag our images for later use when we place them in serial fashion [scrollView1 addSubview:imageView]; [imageView release]; } UPDATE: const CGFloat kScrollObjHeight = 320; const CGFloat kScrollObjWidth = 280.0; const NSUInteger kNumImages = 50; - (void)layoutScrollImages { UIImageView *view = nil; NSArray *subviews = [scrollView1 subviews]; // reposition all image subviews in a horizontal serial fashion CGFloat curXLoc = 0; for (view in subviews) { if ([view isKindOfClass:[UIImageView class]] && view.tag > 0) { CGRect frame = view.frame; frame.origin = CGPointMake(curXLoc, 0); view.frame = frame; curXLoc += (kScrollObjWidth); } } - (void)viewDidLoad { self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor]; // 1. setup the scrollview for multiple images and add it to the view controller // // note: the following can be done in Interface Builder, but we show this in code for clarity [scrollView1 setBackgroundColor:[UIColor blackColor]]; [scrollView1 setCanCancelContentTouches:NO]; scrollView1.indicatorStyle = UIScrollViewIndicatorStyleWhite; scrollView1.clipsToBounds = YES; // default is NO, we want to restrict drawing within our scrollview scrollView1.scrollEnabled = YES; // pagingEnabled property default is NO, if set the scroller will stop or snap at each photo // if you want free-flowing scroll, don't set this property. scrollView1.pagingEnabled = YES; // load all the images from our bundle and add them to the scroll view NSUInteger i; for (i = 1; i <= kNumImages; i++) { NSString *imageName = [NSString stringWithFormat:@"creative%d.jpg", i]; UIImage *image = [UIImage imageNamed:imageName]; UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; // setup each frame to a default height and width, it will be properly placed when we call "updateScrollList" CGRect rect = imageView.frame; rect.size.height = kScrollObjHeight; rect.size.width = kScrollObjWidth; imageView.frame = rect; imageView.tag = i; // tag our images for later use when we place them in serial fashion [scrollView1 addSubview:imageView]; [imageView release]; } [self layoutScrollImages]; I wanted to put this but unable to find the correct position or right offset to display at the top UILabel * topLabel = [[UILabel alloc] init]; topLabel.text = [NSString stringWithFormat:@"%d of %d", i, kNumImages]; rect.origin.x = offset; rect.size.height = 30; // however large you need the label to be topLabel.frame = rect; offset += 30; A: I would think something like this would work: float offset = 0; for (NSUInteger i = 1; i <= kNumImages; i++) { // load up the image NSString *imageName = [NSString stringWithFormat:@"images%d.jpg", i]; UIImage *image = [UIImage imageNamed:imageName]; UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; // image.size is important here and used to determine placement CGRect rect = imageView.frame; rect.size = image.size; // create top label, just basic will need to configure other settings like font UILabel * topLabel = [[UILabel alloc] init]; topLabel.text = [NSString stringWithFormat:@"%d of %d", i, kNumImages]; rect.origin.x = offset; rect.size.height = 30; // however large you need the label to be topLabel.frame = rect; offset += 30; // adding the label height // set image frame since we now know the location below top label rect.size = image.size; rect.origin.x += offset; imageView.frame = rect; imageView.tag = i; offset += image.size.height; // adding image height // add bottom label below image UILabel * bottomLabel = [[UILabel alloc] init]; bottomLabel.text = imageName; // just a sample description rect.origin.x += offset; rect.size.height = 30; // however large you need the label to be bottomLabel.frame = rect; offset += 30; // adding the label height [scrollView1 addSubview:topLabel]; [scrollView1 addSubview:imageView]; [scrollView1 addSubview:bottomLabel]; [imageView release]; [topLabel release]; [bottomLabel release]; offset += 20; // arbitrary spacing between images }
{ "language": "en", "url": "https://stackoverflow.com/questions/7590074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how can a clicked asp.net button open jQuery dialog and then resume default when Yes is clicked? I've got a jQuery dialog and an asp.net button (Delete). When the delete button is clicked I want the dialog to open a confirm window saying 'Are you sure you want to delete this record?'. When the user clicks yes I'd like to resume the asp.net postback. Here's my code so far: $("#dialog-delete").dialog({ autoOpen: false, height: 200, width: 400, modal: true, resizable: false, buttons: { 'Cancel': function () { $(this).dialog('close'); }, 'Yes': function () { $(this).dialog('close'); //__doPostBack('ctl00$cp1$btnDelete',''); } }, open: function () { $(":button:contains('Yes')").addClass("red"); } }); $("[id*=btnDelete]").live('click', function (e) { e.preventDefault(); $("#dialog-delete").dialog('open'); }); So I stop the postback with preventDefault the dialog opens and displays the message but I can't get the delete to fire without hardcoding the delete button, which is nasty. Is there anyway I can hold up the click event whilst the dialog displays and call preventDefault on Cancel and resume on Yes? A: You could change the live event type to mouseup instead of click and then use the click event to fire the postback. $("[id*=btnDelete]").live('mouseup', function (e) { ... ... $("[id*=btnDelete]").click(); Edit (based on comments) Another thought, you could stick with the original idea of handling the click event and upon confirmation of the delete call the .die() function to remove the live event handler previously attached, enabling you to call .click() and causing a postback. You can call the .die() function like so: $("#dialog-delete").dialog({ autoOpen: false, height: 200, width: 400, modal: true, resizable: false, buttons: { 'Cancel': function () { $(this).dialog('close'); }, 'Yes': function () { $(this).dialog('close'); $("[id*=btnDelete]").die('click'); $("[id*=btnDelete]").click(); } }, open: function () { $(":button:contains('Yes')").addClass("red"); } }); $("[id*=btnDelete]").live('click', function (e) { e.preventDefault(); $("#dialog-delete").dialog('open'); }); A: Submit the ASP.NET form when the appropriate button is clicked. ... buttons: { 'Cancel': function () { $(this).dialog('close'); }, 'Yes': function () { $(this).dialog('close'); $('#aspnetForm').submit(); // you may need to use a different selector based on your form name } } A: I got this working but I don't like the solution so far. I'd much prefer a cleaner solution where I can capture the event on the button click and pass it into my dialog in some way, if that's possible. So I'm holding out and hoping someone has a better answer. My code that got it working (for now) is: $("#dialog-delete").dialog({ autoOpen: false, height: 200, width: 400, modal: true, resizable: false, buttons: { 'Cancel': function () { $(this).dialog('close'); }, 'Yes': function () { $(this).dialog('close'); $("[id*=btnDelete]")[0].click(); //__doPostBack('ctl00$cp1$btnVoid',''); } }, open: function () { $(":button:contains('Yes')").addClass("red"); } }); $("[id*=btnDelete]").live('mousedown', function (e) { e.preventDefault(); $("#dialog-delete").dialog('open'); }); Based on the help from @jdavies above (and my comments to enhance the answer). I changed my button handler to a mousedown event and fired the click event in the Yes button handler. I'm wondering what will happen if the user fires the button via the keyboard, which is part of the reason this feels icky to me. :) Holding out for something better but it's running at least...
{ "language": "en", "url": "https://stackoverflow.com/questions/7590076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: append an element to another one and append all of them to another element I want to create a div and append one ul (with a class) and one h5 (with text) to it. then, append that div to another element. I think this code should do it: $("div").addClass( "nice" ) .append( $("ul").addClass("myclass") ) .append( $("h5").text("heading") ) .appendTo( $("#another_div") ); but it doesn't work and browser crashes! How? (i know i can use $("div").html(), but i don't like it!) Thank you. A: Your problem is that by using "div" and "ul" as your selectors, jQuery is searching the dom instead of creating elements. Try this: $("<div></div>").addClass( "nice" ) .append( $("<ul></ul>").addClass("myclass") ) .append( $("<h5></h5>").text("heading") ) .appendTo( $("#another_div") ); A: Live example: http://jsfiddle.net/kzLmp/ $(function(){ $("<div>").addClass( "nice" ) .append( $("<ul>").addClass("myclass") ) .append( $("<h5>").text("heading") ) .appendTo( $("#another_div") ); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7590078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calculating time for Android alarm In Android we set an alarm by setting the time until it goes off in milliseconds. Is there an easy way to find how many milliseconds there are until a certain time (hh:mm) or do I just have to calculate it mathematically? Thanks! A: Save your current time in milliseconds as Calandar calendar = Calendar.getInstance(); Long currenttime = calendar.getTimeInMillis(); Long settime= <your set time in milliseconds>; Here you can calculate the difference as follows: Long differencetime = settime - currenttime; int dif=(int)differencetime/1000; Here you can set the time in calendar: calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND) + dif); Here you can set the alarm for the settime. AlarmManager alarmManager1 = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarmManager1.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi1); A: Check out the first argument for AlarmManager.set(): With RTC/RTC_WAKEUP, you can specify a fixed time rather than an elapsed time. That said, if you need to use the elapsed time, it's pretty trivial to calculate the number of milliseconds that need to elapse. Worst case, you could use the Calendar and/or Date classes. A: Date now = new Date(), b = new Date(year, month, day, hour, min); b.getTime() - a.getTime(); A: And here's another way to get the time in milliseconds to a certain time: Calendar c = Calendar.getInstance(); c.set(c.YEAR, c.MONTH, c.DAY_OF_MONTH, 17, 1, 0); // 5:01 pm long alarmTime = c.getTimeInMillis(); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlarmNotification.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0); am.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 1000 * 60 * 60 * 24, pendingIntent); // Millisec * Second * Minute * Hour // Same time every day * *RTC_WAKEUP allows the alarm to still activate when the phone is asleep. Use RTC if you want to wait until the user wakes up the phone themself. *Use am.set() if you don't want the alarm to repeat Let me know if this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detected BIOS data in system (Delphi) How detected name of modern chipsets in system (Delphi) A: WMI (Windows Management Instrumentation) have routines to detect computer hardware. The best Delphi package for WMI is wmi-delphi-code-creator. Look for documentation for the calls Win32_BaseBoard and Win32_MotherboardDevice. They won't give you the chipset name though. A scan through the Win32_PnPEntity class looking for vendor/device ID and matching them with the correct chipset is probably the best way. Not an easy task. Some more info chipset-detection-in-delphi Edit : Credits to the author of the package, RRUZ A: As LU RD has pointed out, WMI is the way to go. Check out Rodrigo Ruz WMI code generator, it make access really easy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: RelativeLayout problem. ImageView scroll up when keyboard shown I'm trying to show a ImageView under a AdView like image 2. The problem is where the EditText is active, the keyboard is shown and if the AdView is loaded, all works perfect, but when the AdView isn't loaded, the ImageView scroll up out of the screen like image 1 Here is my xml layout: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="top"> <com.google.ads.AdView android:layout_width="wrap_content" android:id="@+id/adView" android:layout_height="wrap_content" ads:adUnitId="XXXXXXXXX" ads:adSize="BANNER" ads:loadAdOnCreate="true" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <ImageView android:src="@drawable/frame008" android:id="@+id/imageView1" android:scaleType="centerInside" android:layout_height="wrap_content" android:adjustViewBounds="true" android:focusable="false" android:layout_width="match_parent" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="50dip"></ImageView> The EditText and Submit button: <RelativeLayout android:id="@+id/linearLayout4" android:orientation="horizontal" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true"> <Button android:text="Submit" android:id="@+id/button2" android:onClick="submit" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignParentRight="true"></Button> <EditText android:layout_width="wrap_content" android:id="@+id/editText1" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_toLeftOf="@id/button2"> <requestFocus></requestFocus> </EditText> </RelativeLayout> Thanks for your time!! A: The code snippet below should be what you need to position the views as you want: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout > <com.google.ads.AdView android:id="@+id/adView" android:layout_alignParentTop="true" /> <RelativeLayout android:id="@+id/linearLayout4" android:layout_alignParentBottom="true"> </RelativeLayout> <ImageView android:layout_below="@+id/adView" android:layout_above="@+id/linearLayout4"> </ImageView> </RelativeLayout>
{ "language": "en", "url": "https://stackoverflow.com/questions/7590086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Make ASP.NET WCF convert dictionary to JSON, omitting "Key" & "Value" tags Here's my dilemma. I'm using a RESTful ASP.NET service, trying to get a function to return a JSON string in this format: {"Test1Key":"Test1Value","Test2Key":"Test2Value","Test3Key":"Test3Value"} But I'm getting it in this format instead: [{"Key":"Test1Key","Value":"Test1Value"}, {"Key":"Test2Key","Value":"Test2Value"}, {"Key":"Test3Key","Value":"Test3Value"}] My method looks like this: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] public Dictionary<string, string> Test(String Token) { if (!IsAuthorized(Token)) return null; if (!IsSecure(HttpContext.Current)) return null; Dictionary<string, string> testresults = new Dictionary<string, string>(); testresults.Add("Test1Key", "Test1Value"); testresults.Add("Test2Key", "Test2Value"); testresults.Add("Test3Key", "Test3Value"); return testresults; } Is there any way I can get rid of those "Key" and "Value" tags using only built in ASP.NET tools? (i.e., I'd rather not use JSON.NET, if it's avoidable) Thanks very much! :) A: Expanding slightly on @MarkisT's excellent solution, you can modify the serialization constructor to recreate one of these dictionaries from the same JSON (thus allowing you to take an AjaxDictionary as a service parameter), as follows: public AjaxDictionary( SerializationInfo info, StreamingContext context ) { _Dictionary = new Dictionary<TKey, TValue>(); foreach (SerializationEntry kvp in info) { _Dictionary.Add((TKey)Convert.ChangeType(kvp.Name, typeof(TKey)), (TValue)Convert.ChangeType(kvp.Value, typeof(TValue))); } } A: The .NET dictionary class won't serialize any other way than the way you described. But if you create your own class and wrap the dictionary class then you can override the serializing/deserializing methods and be able to do what you want. See example below and pay attention to the "GetObjectData" method. [Serializable] public class AjaxDictionary<TKey, TValue> : ISerializable { private Dictionary<TKey, TValue> _Dictionary; public AjaxDictionary() { _Dictionary = new Dictionary<TKey, TValue>(); } public AjaxDictionary( SerializationInfo info, StreamingContext context ) { _Dictionary = new Dictionary<TKey, TValue>(); } public TValue this[TKey key] { get { return _Dictionary[key]; } set { _Dictionary[key] = value; } } public void Add(TKey key, TValue value) { _Dictionary.Add(key, value); } public void GetObjectData( SerializationInfo info, StreamingContext context ) { foreach( TKey key in _Dictionary.Keys ) info.AddValue( key.ToString(), _Dictionary[key] ); } } A: In case anyone has that problem on the client side: conversion from that weird {Key: "x", Value:"y"} Array to a { x: "y" } object can be done in a single line of JS: var o = i.reduce(function (p, c, a, i) { p[c.Key] = c.Value; return p }, {}); with i being the array returned from the service, and o being what you actually want. best regards A: I ran up against this problem a number of months ago and posted a somewhat less-than-optimally succinct question here: Configuring WCF data contract for proper JSON response The problem I had back then turned out to be same as the much more precisely posted question here, in short: within the context of WCF the standard asp.net serialization tools will, for a dictionary, return an ARRAY rather than a key/value pair json OBJECT. I am posting my solution which worked for me although I did resort to using JSON.NET (which I realize the poster was trying to avoid). Nevertheless, maybe this will be helpful to someone. Function myDictionaryFunction () As Stream Implements IMywebservice.myDictionaryFunction Dim myKeyValuePairObject As Object = New Dynamic.ExpandoObject Dim myDictionary = DirectCast(myKeyValuePairObject, IDictionary(Of String, Object)) myDictionary.Add("Test1Key", "Test1Value") myDictionary.Add("Test2Key", "Test2Value") myDictionary.Add("Test3Key", "Test3Value") strJson = JsonConvert.SerializeObject(myKeyValuePairObject) Dim resultBytes As Byte() = Encoding.UTF8.GetBytes(strJson) WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain" Return New MemoryStream(resultBytes) End Function The result: {"Test1Key":"Test1Value","Test2Key":"Test2Value","Test3Key":"Test3Value"} The expando object works like a charm. But to make it work you have to force WCF to return plain text which one would think is easy but it is not. You have to implement a RawContentTypeMapper as suggested here: http://referencesource.microsoft.com/#System.ServiceModel.Web/System/ServiceModel/Channels/RawContentTypeMapper.cs ...And then you have to mess around with your web.config file something like this: <customBinding> <binding name="RawReceiveCapable"> <webMessageEncoding webContentTypeMapperType="myNamespace.RawContentTypeMapper, myLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> <httpTransport manualAddressing="true" maxReceivedMessageSize="524288000" transferMode="Streamed" /> </binding> </customBinding> I am the first to admit that this solution will likely not receive any awards for elegance. But it worked and returning raw content from a WCF webservice will, if needed, give you some extra control how to serialize your WCF data payload. Since implementing this, I have migrated more and more to ASP.NET Web API (which makes returning RESTful anything much easier than WCF, IMO). A: avoiding the "__type" in json... in the webapi.config, there are several options (look to the last one): // To disable tracing in your application, please comment out or remove the following line of code // For more information, refer to: http://www.asp.net/web-api //config.EnableSystemDiagnosticsTracing(); // Use camel case for JSON data. config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // The setting will let json.net to save type name in the payload if the runtime type is different with the declare type. // When you post it back, json.net will deserialize the payload to the type you specified in the payload. // source: http://stackoverflow.com/questions/12858748/asp-net-webapi-posting-collection-of-subclasses //config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects;
{ "language": "en", "url": "https://stackoverflow.com/questions/7590088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: Array structure for Shopping Basket I am trying to implement multidimensional array that hold data of Pizza id's with options and extras id's. Let look at the following scenario... Customer wants * *Two 'Chicken Pizza' (ProductID:12) - '10 inches' (OptionsID:4) with extras of Ham and Tuna (ExtrasID: 5,10) *One 'Chicken Pizza' (ProductID:12) - '10 inches' (OptionsID:4) with extras of Sweet Corn (ExtrasID: 2) *One 'Chicken Pizza' (ProductID:12) - '14 inches' (OptionsID:2) with no extras *Eleven 'Vegetarian Pizza' (ProductID:35) - '7 inches' (OptionsID:52) with no extras See the following code below that match the scenario... Im I doing it right? or what can be done to improve it and readable? //Two 'Chicken Pizza' (ProductID:12) - '10 inches' (OptionsID:4) //With extras of Ham and Tuna (ExtrasID: 5,10) $option4[] = array( 'quantity' => 2, 'extras_id' => array(5, 10) ); //One 'Chicken Pizza' (ProductID:12) - '10 inches' (OptionsID:4) //With extras of Sweet Corn (ExtrasID: 2) $option4[] = array( 'quantity' => 1, 'extras_id' => array(2) ); //One 'Chicken Pizza' (ProductID:12) - '14 inches' (OptionsID:2) //With no extras $option2[] = array( 'quantity' => 1, 'extras_id' => array() ); //Eleven 'Vegetarian Pizza' (ProductID:35) - '7 inches' (OptionsID:52) //With no extras $option52[] = array( 'quantity' => 11, 'extras_id' => array() ); //Hold data of Customer Orders $shoppingBasket = array( "ShopID_24" => array( 'ProductID' => array( '12' => array( 'OptionID' => array( '4' => $option4, '2' => $option2 ) ), '35' => array( 'OptionID' => array( '52' => $option52 ) ), ) ) ); echo "<pre>"; print_r($shoppingBasket); echo "</pre>"; print_r output: Array ( [ShopID_24] => Array ( [ProductID] => Array ( [12] => Array ( [OptionID] => Array ( [4] => Array ( [0] => Array ( [quantity] => 2 [extras_id] => Array ( [0] => 5 [1] => 10 ) ) [1] => Array ( [quantity] => 1 [extras_id] => Array ( [0] => 2 ) ) ) [2] => Array ( [0] => Array ( [quantity] => 1 [extras_id] => Array () ) ) ) ) [35] => Array ( [OptionID] => Array ( [52] => Array ( [0] => Array ( [quantity] => 11 [extras_id] => Array () ) ) ) ) ) ) ) A: I would consider doing this by modeling the same data in a few custom PHP objects. In this case you might have a shop object with products, and product objects with options. This is really quick off the top of my head: class Shop { private $_products = array(); public function getProducts() { return $this->_products;} public function addProduct(Product $product) { $this->_products[] = $product; return $this; } } class Product { private $_options = array(); public function getOptions() { return $this->_options; } public function addOption(Option $option) { $this->_options[] = $option; return $this; } } class Option { private $_optionKey; private $_optionValue; public function getKey() { return $this->_optionKey; } public function getKey() { return $this->_optionValue; } public function setOption($key, $value) { $this->_optionKey = $key; $this->_optionValue = $value; return $this; } } What does this get you? For starters, you can define limits and parameters to what you can store in this, while with the nested array that you are using, there is absolutely no enforcement of structure or value. You can also define other methods that allow you to actually DO things with these bits of data. If you absolutely MUST have an array version of these, you can implement something like a toArray() method in each of these that will convert the objects into an array to be consumed by some other bit of code. You might also consider reading up on a few interfaces such as iterator and countable in the PHP manual. A: You set up one array on the beginning, fine. Now use it in the right way. $option['ShopID_'.$id]; //where $id is obviusly the id number; Now fill the $option array with the orders. $option['ShopID_'.$id]['ProductId_'.$pid][] = array( 'quantity' => 1, 'extras_id' => array(2), //maybe a string is enough here (?) (e.g. '2,5,etc..') 'inches' => $inches ); $pid is obviusly the pizza Id you are searching for.. as well this is just a "static" example! A: I recommend you to use OO programming, this saves you a lot of headache! Try something like this: <?php class Extra { var $id; var $name; var $amount; function __construct() { $this->id = 0; $this->name = ''; $this->amount = 0; } } class Option { var $id; var $name; function __construct() { $this->id = 0; $this->name = ''; } } class Pizza { var $id; var $name; var $options; var $extras; function __construct() { $this->id = 0; $this->name = ''; $this->options = array(); $this->extras = array(); } } ?> And to test it: <?php $pizzas = array(); for($i=0; $i<10; $i++) { $pizza = new Pizza(); $pizza->id = $i; $pizza->name = 'Pizza '.$i; for($j=0; $j<$i; $j++) { $option = new Option(); $option->id = $j; $option->name = 'Option '.$j; $pizza->options[] = $option; } for($k=$i; $k>0; $k--) { $extra = new Extra(); $extra->id = $k; $extra->name = 'Extra '.$k; $extra->amount = $k; $pizza->extras[] = $extra; } $pizzas[] = $pizza; } print_r($pizzas); ?> Good luck :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7590090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: find a particular function in a executable using dumpbin tools family Is it possible to know with dumpbin tools if a executable under windows use the command arp ? A: No, not really. If it has arp.exe as a string literal, and passes that string literal to WinExec, CreateProcess, etc., that'll be pretty easy to find. It could, however, do something like reading arp.exe in from a file at run-time, which will make it considerably more difficult to find.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replace a character in a char[] from a function How would I get my replace_char function to work properly? The way that I am trying it in the function below returns segmentation faults using gcc in Ubuntu. I have tried other ways, but each time I try to change the value, I get a fault. int main (void) { char* string = "Hello World!"; printf ("%s\n", string); replace_char(string, 10, 'a'); printf ("%s\n", string); } void replace_char(char str[], int n, char c) { str[n] = c; } A: There is nothing wrong with your replace_char function. The problem is that you are trying to modify a string literal ("Hello World!") and that's undefined behavior. Try making a copy of the string instead, like this: char string[] = "Hello World!"; A: Edit To get the 'suggestion' of editing string in place, you can edit the pointer inplace: void replace_char(char*& str, int n, char c) { str = strdup(str); str[n] = c; } int main() { char* string = "Hello World!"; string = replace_char(string, 10, 'a'); // ... free(string); } Note you now have to remember to call free on the string after calling this. I suggest, instead, that you do what I suggested before: wrap the literal in strdup if required. That way you don 't incur the cost of allocating a copy all the time (just when necessary). The problem is that "Hello World' is a const literal char array. const char* conststr = "Hello World!"; char * string = strdup(conststr); i assume the problem will be gone Explanation: Compilers can allocate string literals in (readonly) data segment. The conversion to a char* (as opposed to const char*) is actually not valid. If you use use e.g. gcc -Wall test.c you'd get a warning. Fun experiment: Observe here that (because it is Undefined Behaviour) compilers can do funny stuff in such cases: http://ideone.com/C39R6 shows that the program wouldn't 'crash' but silently fail to modify the string literal unless the string was copied. YMMV. Use -Wall, use some kind of lint if you can, and do unit testing :){
{ "language": "en", "url": "https://stackoverflow.com/questions/7590098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using SMO on web server with ASP.NET Is it required to have anything SQL Server related installed on a web server in order to make use of SMO? I've built a web app that programmatically creates a SQL Agent job, adds a step (which ultimately fires of dtexec to run an SSIS package), and executes. This works fine on my local machine which has SQL client tools installed, however when I move to a web server, I get reference issues and I'm starting to think it's due to something not being installed. Could not load file or assembly 'Microsoft.SqlServer.SqlClrProvider, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. A: This is a rat hole. The problem is that once you locate that assembly and copy it to the bin folder of your application it will complain about a completely different one.. or even the same file simply due to missing dependencies. For more information read this: http://www.sqldbadiaries.com/2010/10/20/how-i-fixed-could-not-load-file-or-assembly-microsoft-sqlserver-smo-version10-0-0-0-issue/ That site lists the files you need and the fact you need to register and gac a few files. Quite frankly, you are much better off just biting the bullet and install the client tools on your web server. A: Yes, your application requires this assembly in its bin directory to function. This error means that the server doesn't have the SMO (and its dependant) assemblies. Back in your solution in Visual Studio, right click on the assembly above, and select/change the "Copy Local" to "True". Copy this for each SMO assembly that you've referenced. When you publish your application, this will bring those .DLLs on your development machine along in your published bin directory. * *Check your web.config file for any references as well *search your code for SqlClrProvider
{ "language": "en", "url": "https://stackoverflow.com/questions/7590104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery clone() and 302 image sources -- how to avoid reloading in Firefox? I have a group of images within a <div>. All these images are served through a 302 instead of a 200 for security purposes (servlet serving image based on authentication). I would like to clone that <div> and append it to another container. When doing so in all browsers except Firefox, the images are not reloaded. It appears those browsers understand it's the same image. In Firefox, each image is reloaded after the clone/append. I'd like to avoid that. Does anyone have any recommendations on how? UPDATED with code example: <div> <p><button type="button" id="btn1">Clone 1</button> <button type="button" id="btn2">Clone 2</button></p> </div> <div id="group1"> <div id="imgs"> <p><img src="https://example.com/image/9c90434ed657427dad29"></p> <p><img src="https://example.com/image/977b5dfe5e064880b164"></p> <p><img src="https://example.com/image/8f22d7fd2a2343ab99c9"></p> <p><img src="https://example.com/image/898c022e20b742c88ae6"></p> <p><img src="https://example.com/image/8319fe1d23064b5d8011"></p> </div> </div> <div id="group2"></div> <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#btn1").click(function(){ $("#imgs").clone().appendTo("#group1"); }); $("#btn2").click(function(){ $("#imgs").clone().appendTo("#group2"); }); }); </script> A: Try adding prefetch tags for Firefox users. I believe FF still supports the prefetch relationship; they did come up with it. <link rel="prefetch" src="https://example.com/image/9c90434ed657427dad29"> <link rel="prefetch" src="https://example.com/image/977b5dfe5e064880b164"> <link rel="prefetch" src="https://example.com/image/8f22d7fd2a2343ab99c9"> <link rel="prefetch" src="https://example.com/image/898c022e20b742c88ae6"> <link rel="prefetch" src="https://example.com/image/8319fe1d23064b5d8011">
{ "language": "en", "url": "https://stackoverflow.com/questions/7590106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Ant: How to echo the name of targetfile within apply I'm not really familiar with Ant and i wonder how to print the name of the current processed file to the commandline. This is what i have so far... It's a part of a macro which minifys files with the yui-compressor. <apply executable="java" parallel="false" verbose="true" dest="@{target}"> <fileset dir="@{src}"> <include name="**/*.@{filetype}"/> </fileset> <arg line="-jar" /> <arg path="${yui.jar}" /> <arg value="--charset" /> <arg value="ANSI" /> <arg value="-o" /> <targetfile /> <mapper type="glob" from="*.@{filetype}" to="*.min.@{filetype}" /> </apply> What i'm trying to get: [echo] Start! [apply] Processed: filename-1.min.js [apply] Processed: filename-2.min.js [apply] Processed: filename-3.min.js [echo] Success! A: I don't have a lot of experience with apply but you could try defining your fileset out of the apply element , getting your printed results and then referring to it into your apply element. <fileset dir="@{src}" id="my.files"> <include name="**/*.@{filetype}"/> </fileset> <pathconvert pathsep="${line.separator}" property="processed.files" refid="my.files"/> <echo>Start!</echo> <echo message="${processed.files}"/> <apply executable="java" parallel="false" verbose="true" dest="@{target}"> <fileset refid="my.files"/> <arg line="-jar" /> <arg path="${yui.jar}" /> <arg value="--charset" /> <arg value="ANSI" /> <arg value="-o" /> <targetfile /> <mapper type="glob" from="*.@{filetype}" to="*.min.@{filetype}" /> </apply> <echo>Success!</echo> Of course this will only work if the apply executable doesn't print anything to clutter the output. A: The best way I've found to do this is to add the debug or verbose flag to ant: ant target-name -debug or ant target-name -verbose This will then print the executing command-line. For example: [apply] Executing 'lib\NUnit\bin\nunit-console-x86.exe' with arguments: [apply] '/noshadow' [apply] '/domain:multiple' [apply] '/labels' [apply] '/framework:net-4.5' [apply] '/nologo' [apply] 'C:\blah\foo.Tests.dll Unfortunately, this will verbosely log everything, and not just the specific apply.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Does this field need an index? I currently have a summary table to keep track of my users' post counts, and I run SELECTs on that table to sort them by counts, like WHERE count > 10, for example. Now I know having an index on columns used in WHERE clauses speeds things up, but since these fields will also be updated quite often, would indexing provide better or worse performance? A: If you have a query like SELECT count(*) as rowcount FROM table1 GROUP BY name Then you cannot put an index on count, you need to put an index on the group by field instead. If you have a field named count Then putting an index in this query may speed up the query, it may also make no difference at all: SELECT id, `count` FROM table1 WHERE `count` > 10 Whether an index on count will speed up the query really depends on what percentage of the rows satisfy the where clause. If it's more than 30%, MySQL (or any SQL for that matter) will refuse to use an index. It will just stubbornly insist on doing a full table scan. (i.e. read all rows) This is because using an index requires reading 2 files (1 index file and then the real table file with the actual data). If you select a large percentage of rows, reading the extra index file is not worth it and just reading all the rows in order will be faster. If only a few rows pass the sets, using an index will speed up this query a lot Know your data Using explain select will tell you what indexes MySQL has available and which one it picked and (kind of/sort of in a complicated kind of way) why. See: http://dev.mysql.com/doc/refman/5.0/en/explain.html A: Indexes in general provide better read performance at the cost of slightly worse insert, update and delete performance. Usually the tradeoff is worth it depending on the width of the index and the number of indexes that already exist on the table. In your case, I would bet that the overall performance (reading and writing) will still be substantially better with the index than without but you would need to run tests to know for sure. A: It will improve read performance and worsen write performance. If the tables are MyISAM and you have a lot of people posting in a short amount of time you could run into issues where MySQL is waiting for locks, eventually causing a crash. A: There's no way of really knowing that without trying it. A lot depends on the ratio of reads to writes, storage engine, disk throughput, various MySQL tuning parameters, etc. You'd have to setup a simulation that resembles production and run before and after. A: I think its unlikely that the write performance will be a serious issue after adding the index. But note that the index won't be used anyway if it is not selective enough - if more than for example 10% of your users have count > 10 the fastest query plan might be to not use the index and just scan the entire table.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating new blog with tags Im trying to setup a blog with tagging, and i've run into a problem when trying to save. I got 3 models blog model has_many :blog_tags has_many :tags, :through => :blog_tags blog_tag model belongs_to :blog belongs_to :tag tag model [nothing] When i post my blog form, i got an input field with a comma seperated list of tags that i would like to create in the blog_tags tabel. I've been trying out some different stuff and ended up with this @blog_tags = params[:blog][:tags].split(",") @blog_tags.each do |tag| @tag = Tag.find_by_tag(tag) @blog.tags.push(@tag) end Seemed to be working besides it complained that the parent wasn't created, and in the 2nd try it gave me an error for trying to split the string "string1" which i guess is caused by not having any commas. I really hope one of you out there can help me out here, or atleast point me in the right direction :-) Thanks! A: I'd go for a gem. Try https://github.com/mbleigh/acts-as-taggable-on for example. A: I think you just need to handle the cases where params[:blog][:tags] has no commas. In this case, the whole string is one tag, so just add it. You might also need to deal with cases like "ruby, ,rails" i.e making sure the tags aren't empty.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery div content partial hide, show all I have this solution I am trying to use but it uses ID's. I want multiple divs on the same page using the same classes. I changed the ID references to classes but I can not get them to fire independently of each other. They all fire at the same time. How would I get them to fire independently. I thought by wrapping the function in a .each() that would fix it but it seems to still be firing all my divs to open at the same time. Any suggestions are very helpful. Thanks. $(function(){ var slideHeight = 75; // px var defHeight = $('.wrap').height(); if(defHeight >= slideHeight){ $('.wrap').css('height' , slideHeight + 'px'); $('.read-more').append('<a href="#">Click to Read More</a>'); $('.read-more a').click(function(){ var curHeight = $('.wrap').height(); if(curHeight == slideHeight){ $('.wrap').animate({ height: defHeight }, "normal"); $('.read-more a').html('Close'); $('.gradient').fadeOut(); }else{ $('.wrap').animate({ height: slideHeight }, "normal"); $('.read-more a').html('Click to Read More'); $('.gradient').fadeIn(); } return false; }); }// end if }); my HTML <div class="container"> <h1>jQuery slide with minimum height</h1> <h2>About Billabong</h2> <div class="wrap"> <div> <p>Gordon Merchant founded Billabong in Burleigh Heads on the Gold Coast in 1973. Combining his passion for surfing with hard work, Gordon designed boardshorts, manufacturing them on the kitchen table and selling through local surf shops and markets.</p> <p>Gordon developed his own stitching technique, which made the garments more durable, cost effective and less labor intensive. He employed machinists, moved the operation into a factory, set up a distribution network and sponsored a team of renowned Australian surfers. The business thrived.</p> <p>Since those beginnings, Billabong has expanded its product range to include boardsport products such as wetsuits, watches, surfboards, snowboard outerwear and skateboarding apparel.</p> <p>Information courtesy of <a title="Billabong" href="http://www.billabong.com/us/">Billabong</a>.</p> </div> <div class="gradient"></div> </div> <div class="read-more"></div> <div class="container"> <h1>jQuery slide with minimum height Content 2</h1> <h2>About Billabong</h2> <div class="wrap"> <div> <p>Gordon Merchant founded Billabong in Burleigh Heads on the Gold Coast in 1973. Combining his passion for surfing with hard work, Gordon designed boardshorts, manufacturing them on the kitchen table and selling through local surf shops and markets.</p> <p>Gordon developed his own stitching technique, which made the garments more durable, cost effective and less labor intensive. He employed machinists, moved the operation into a factory, set up a distribution network and sponsored a team of renowned Australian surfers. The business thrived.</p> <p>Since those beginnings, Billabong has expanded its product range to include boardsport products such as wetsuits, watches, surfboards, snowboard outerwear and skateboarding apparel.</p> <p>Information courtesy of <a title="Billabong" href="http://www.billabong.com/us/">Billabong</a>.</p> </div> <div class="gradient"></div> </div> <div class="read-more"></div> </div> A: use all classes and replace your code with this. I hope it is self explanatory why it works. var slideHeight = 75; $(".container").each(function() { var $this = $(this); var $wrap = $this.children(".wrap"); var defHeight = $wrap.height(); if (defHeight >= slideHeight) { var $readMore = $this.find(".read-more"); $wrap.css("height", slideHeight + "px"); $readMore.append("<a href='#'>Click to Read More</a>"); $readMore.children("a").bind("click", function(event) { var curHeight = $wrap.height(); if (curHeight == slideHeight) { $wrap.animate({ height: defHeight }, "normal"); $(this).text("Close"); $wrap.children(".gradient").fadeOut(); } else { $wrap.animate({ height: slideHeight }, "normal"); $(this).text("Click to Read More"); $wrap.children(".gradient").fadeIn(); } return false; }); } }); Or see a live demo here A: You can use ":first" selector, then remove the class from that object, then call again. Or if you don't want to remove a class, add a class and use the ":first" and ":not" selectors
{ "language": "en", "url": "https://stackoverflow.com/questions/7590118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Route events from one dom node to another WITHOUT JQUERY My question is totally like: How do I pass javascript events from one element to another? except for the fact that I need a raw JS solution. I've got a webos app whose UI features a layering of elements that scroll in conjunction with eachother on a page. Basically I have what amounts to an iframe (not quite, but in principle), and a floating header that lives in a z-layer above it. When I scroll the elements in the iframe, it also moves the floating header up. However, I also need to scroll the underlying doc when the header is dragged. This is a touchscreen interface, so I'm trying onmousemove and ontouchmove events. I've got the following code, but it doesn't seem to do anything: setupScrollFromHeader: function setupScrollFromHeader() { // webos enyo stuff. Don't worry about it. just know that I get the // raw dom elements through the this.$.elem.node syntax var body = this.$.body, header = this.$.mailHeaderUnit; if (!header.hasNode() && !body.hasNode()) { return; } body = body.node; // end enyo specific stuff header.node.addEventListener('touchmove', function(event) { console.log("### touch move"); event.preventDefault(); body.dispatchEvent(event); var touch = event.touches[0]; console.log("Touch x:" + touch.pageX + ", y:" + touch.pageY); }, true); console.log("### set this stuff up"); } I'm using dispatchEvent to forward the event, per: https://developer.mozilla.org/en/DOM/element.dispatchEvent I've tried this with either touchmove and mousemove events by themselves, toggling prevent default, and also changing the bubbling behavior with the true/false flags. In all cases I see the log print out, but the events are never passed to the underlying element. What am I doing wrong? Is it even possible to pass the events around this way? A: So this is the right way to route events. Looks like the widget I'm talking to needed a mousedown event before receiving the touchmove events. For maximum compatibility, I added listeners for both mouse and touch, for testing in browser and on device. I came up with the following: setupScrollFromHeader: function setupScrollFromHeader() { if (setupScrollFromHeader.complete) { return; } var body = this.$.body, header = this.$.mailHeaderUnit; if (!header.hasNode() && !body.hasNode()) { return; } var header = header.node; var forwarder = function forwarder(event) { body.$.view.node.dispatchEvent(event); }; ['mousedown', 'mousemove', 'touchstart', 'touchmove', 'touchend'].forEach(function(key) { header.addEventListener(key, forwarder, true); }); setupScrollFromHeader.complete = true; }, In the general browser case, you can test such forwarding with with two buttons, routing the click event from one to the other works as expected through dispatchEvent(...). ie: var button1 = document.getElementById('button1'); var button2 = document.getElementById('button2'); button1.addEventListener('click', function(event) { button2.dispatchEvent(event); }, true); button2.addEventListener('click', function(event) { alert("Magnets. How do they work?"); }, true); clicking button1 will fire the handler of button2.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Cycle.js IE7/8 clicking pager causes it to blink, not fade I'm using Cycle.js for a project. I have created a static navigation area and using the pager: in Cycle allow the user to click which slide to see. Everything looks fine in all major browsers, FF, Safari, Chrome, IE9 etc. However in IE 7 and 8 it doesn't fade as expected. It blinks to white, then the next slide blinks into view. I'm mystified as to why that is. If I remove the paging altogether and put in a timout of 3000 for example it fades just fine. Is something wrong with the pager? I basically just used it straight from the Cycle.js project site example (except modified the index value as commented below) seen here. jQuery(function($){ $('.Slides').cycle({ fx: 'fade', timeout: 0, pager: '#nav', pagerAnchorBuilder: function(idx,slide){ idx -= 1 // we don't want the first slide so reduce the index # by 1 return '#nav div:eq(' + idx + ') '; } }); The HTML looks pretty straight forward, something like this: <div id="nav"> <div id="stage_1"></div> <div id="stage_2"></div> <div id="stage_3"></div> </div> This mark up will be changing soon, but don't see how that could be related to the issue at hand right now. Any ideas? Thanks. A: I figured out what my error was. The HTML containing the slides featured a container and two other elements, img and a. Pretty simple stuff: <div class="slide"> <img src="path_to_my_img" /> <a href="path_to_another_page">Link Text</a> </div> And the transition was just causing a blink, and the next slide would appear after a moment of showing white only. No transition would work (fade, turnDown, etc). To fix this I just had to add a background color to the container div, which I did in an IE conditional. For me this works out since the img is the same size as the div and the anchor is absolutely positioned.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Updating Multiple ComboBoxes In my project I have about 100 comboboxes, every combobox holds the same items. I want to "update" every combobox like this: When an item is selected in combobox A, all other comboboxes shouldn't hold this item anymore. Likewise, when the selected item from combobox A changes again, the previous item should appear on the other comboboxes again, etc etc, and I want this to happen for every single combobox. What's the best way to accomplish this? With as less code and without timers, if possible. A: Use a helper class that handles the changing and keeps track of the current selected items. Something like this: public class ComboboxSwitcher { List<ComboBox> boxlist = new List<ComboBox>(); Dictionary<ComboBox, object> olditems = new Dictionary<ComboBox, object>(); public void Add(params ComboBox[] boxes) { boxlist.AddRange(boxes); boxes.ToList().ForEach(box => box.SelectedIndexChanged += handler); } private void handler(object sender, EventArgs e) { ComboBox trigger = (ComboBox) sender; object item = trigger.SelectedItem; object olditem = null; if (olditems.ContainsKey(trigger)) olditem = olditems[trigger]; boxlist.ForEach(box => { if (box != trigger) { if (olditem != null) box.Items.Add(olditem); box.Items.Remove(item); } }); olditems[trigger] = item; } } Add all combo boxes via the Add method like this: List<string> items = new List<string> { "A", "B", "C", "D" }; comboBox1.Items.AddRange(items.ToArray()); comboBox2.Items.AddRange(items.ToArray()); comboBox3.Items.AddRange(items.ToArray()); new ComboboxSwitcher().Add(comboBox1, comboBox2, comboBox3); The class registers a SelectedIndexChanged handler for all comboboxes to be informed of changes. In case of a selection change it checks, if there is a previously selected value for this combox (using the internal dictionary structure). It then iterates all comboboxes and changes the items, ie. removes the newly selected one and adds the old one to all boxes except the box that had the change. Finally it updates ints internal dictionary. You didnt need to keep track of current selections in the other comboboxes as the selection there doesn't change. And you may build distinctive groups of comboboxes by using multiple instances of this class. A: I would try it with an DataBinding on the ComboBox so i don't have to control the ComboBoxs itself. You could control the ComboBox Data by controlling the source directly. So only show a non marked DataEntry in the DataSource, or something like that. Sample for DataBinding: http://msdn.microsoft.com/en-us/library/x8ybe6s2%28v=vs.80%29.aspx A: One way.... I think you need three lists: AvailableItems, SelectedItems and ComboBoxes. When an item is selected, you take it out of AvailableItems and put it in SelectedItems. Then iterate the ComboBoxes and rebind each one to AvailableItems. The tricky part is having each ComboBox keep it's selected item. Before rebinding, save it's selected item, do the rebinding, put the selected item back and re-select it. You may need to do a Suspendlayout() while all this is happening to avoid screen updates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Memory alignment (Using C specifically) If you've got a struct within a struct, say: struct { double a; struct { char *b[20]; char c; }d; }e; will struct e need to start on a multiple of the size of struct d, or a multiple of the size of the largest member of d (char *b[20])? A: The struct e will start at whatever alignment is necessary for the members, and the struct as a whole, to be accessible. That alignment will vary for different implementations. We know that the alignment for e will be at least as strict as the alignmentf for double and at least as strict as the alignment for e.d -- and the alignment of e.d will be at least as strict as the alignment for its members. Contrary to the other answers, the alignment of a scalar type is not necessarily the same as its size. For example, it's possible that double might be 8 bytes, but only require 4-byte alignment. Aligning each scalar type (integer, floating-point, pointer) to its full size is fairly common, but it's not universal. And note that the optimal alignment may be more strict than the required alignment. On the x86, as I understand it, the CPU can access objects on any byte boundary -- but access to properly aligned objects is more efficient. (On other CPUs, misaligned access may require software support.) Compilers will typically align objects for maximum efficiency (but may provide non-standard extensions to save space). But the alignment for a type cannot exceed its size. For example, you can't have a 3-byte type that requires 4-byte alignment. Arrays cannot have gaps between their elements. (In such a case, the compiler would probably pad the type to 4 bytes; the padding would be part of the object, not inserted between objects.) A: It's compiler- and settings-dependent. In most cases will start at the first member's granularity, which in your case is sizeof(char*). Note, that it's not sizeof(char*) * 20, since it's an array and not a native type. Also note that in your case, the struct e will always start at least at granularity of sizeof(double), and therefore struct d will do too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Silverlight Treeview DisplayMemberPath not working I have a ObservableCollection of Patient objects. Each Patient object has a Name property, an Id (int) and a List of Therapies. Each Therapy has a TherapyName(string). I'm using the TreeView to display the data like this <sdk:TreeView ItemsSource="{Binding PatientList}" DisplayMemberPath="Name" > <sdk:TreeView.ItemTemplate> <sdk:HierarchicalDataTemplate ItemsSource="{Binding Therapies}" > <TextBlock Text="{Binding TherapyName}"/> </sdk:HierarchicalDataTemplate> </sdk:TreeView.ItemTemplate> When I run it, it crashes inside the browser.When i remove the DisplayMemberPath, it runs but I only get the TherapyNames, the parent elements for Patient Names are empty. A: you shouldnt have display member path there as this is used if you are using item source and the in that obejct wanting to select values are used for the tree. you want to do some thing like this <sdk:TreeView ItemsSource="{Binding PatientList}" DisplayMemberPath="Name" > <sdk:TreeView.ItemTemplate> <sdk:HierarchicalDataTemplate ItemsSource="{Binding Therapies}" > <Stackpanel> <TextBlock Text="{Binding TherapyName}"/> <TextBlock Text="{Binding Name}"/> </Stackpanel> </sdk:HierarchicalDataTemplate> </sdk:TreeView.ItemTemplate> I havnt tested that bit of xaml but it should be nearly right
{ "language": "en", "url": "https://stackoverflow.com/questions/7590135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dividing decimals yields invalid results in Python 2.5 to 2.7 After a very thorough read of the Python's decimal module documentation, I still find myself puzzled by what happens when I divide a decimal. In Python 2.4.6 (makes sense): >>> import decimal >>> decimal.Decimal(1000) / 10 Decimal("100") In Python 2.5.6, Python 2.6.7, and Python 2.7.2 (puzzling): >>> import decimal >>> decimal.Decimal(1000) / 10 Decimal('0.00000-6930898827444486144') More confusing yet, that result doesn't even appear to be valid: >>> decimal.Decimal('0.00000-6930898827444486144') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 548, in __new__ "Invalid literal for Decimal: %r" % value) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 3844, in _raise_error raise error(explanation) decimal.InvalidOperation: Invalid literal for Decimal: '0.00000-6930898827444486144' The result is the same using decimal.Decimal(1000) / decimal.Decimal(10), so it's not an issue with using an int as the divisor. Part of the issue is clearly around precision: >>> decimal.Decimal("1000.000") / decimal.Decimal("10.000") Decimal('0.00000-6930898827444486144') >>> decimal.Decimal("1000.000") / decimal.Decimal("10") Decimal('0.000200376420520689664') But there should be ample precision in decimal.Decimal("1000.000") to divide safely by 10 and get an answer that's at least in the right ballpark. The fact that this behavior is unchanged through three major revisions of Python says to me that it is not a bug. What am I doing wrong? What am I missing? How can I divide a decimal (short of using Python 2.4)? A: From your MacPorts bug, you have installed Xcode 4 and your version of Python 2.7.2 was built with the clang C compiler, rather than gcc-4.2. There is at least one known problem with building with clang on OS X that has been fixed in Python subsequent to the 2.7.2. release. Either apply the patch or, better, ensure the build uses gcc-4.2. Something like (untested!): sudo bash export CC=/usr/bin/gcc-4.2 port clean python27 port upgrade --force python27 prior to the build might work if MacPorts doesn't override it. UPDATE: The required patch has now been applied to the MacPorts port files for Python 2. See https://trac.macports.org/changeset/87442 A: Just for the record: For python 2.7.3 compiled with clang (via Homebrew on OS X), this seems to be fixed. Python 2.7.3 (default, Oct 10 2012, 13:00:00) [GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import decimal >>> decimal.Decimal(1000) / 10 Decimal('100')
{ "language": "en", "url": "https://stackoverflow.com/questions/7590137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How to sort text column by number sorting in Access? I have a column with address numbers (1, 1a, 3, 12b, ...etc). I need to sort them as numbers (result as above), not text (such as 1, 1a, 12b, 3, ...etc). What would be the sorting clause for this issue? Help appreciated. A: Try this: Val(iif( /columnName/ IS NULL, 0, /columnName/ )) /order/
{ "language": "en", "url": "https://stackoverflow.com/questions/7590141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Embed a web browser in a Python program How can I embed a web browser in a Python program? It needs to run on Linux (GTK, Qt are fine), or cross-platform. I have looked at embedding pywebgtk and Qt's WebKit widget. But these seem to have little more than a rendering engine. In particular, I'd like support for back/forward and tabbed browsing. Is something like this pre-packaged, or do I have to implement it myself? wxWebConnect seems to be roughly what I was thinking of, but it has no Python bindings. A: http://pypi.python.org/pypi/selenium/2.7.0 You can install the selenium package and run a server (same machine, just a different process) with it which you connect to with your python code: java -jar selenium-server-standalone-2.7.0.jar then: from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.keys import Keys import time browser = webdriver.Firefox() # Get local session of firefox browser.get("http://www.yahoo.com") # Load page assert "Yahoo!" in browser.title elem = browser.find_element_by_name("p") # Find the query box elem.send_keys("seleniumhq" + Keys.RETURN) time.sleep(0.2) # Let the page load, will be added to the API try: browser.find_element_by_xpath("//a[contains(@href,'http://seleniumhq.org')]") except NoSuchElementException: assert 0, "can't find seleniumhq" browser.close() You could use subprocess to start the server inside your python code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Use application or activity context in CookieSyncManager.createInstance Is it a good idea to use application context instead of activity context in CookieSyncManager.createInstance() call? CookieSyncManager.createInstance(activity.getApplicationContext()); In Facebook's SDK, it uses activity context, which I think will cause memory leak: CookieSyncManager.createInstance(activity); So I decided to change it to CookieSyncManager.createInstance(activity.getApplicationContext()); Is there any problem of using application context in this case? Thanks. A: Old question, but I was just looking for the same thing. Turns out it doesn't matter what Context you provide it in createInstance() because internally it just takes the provided context and calls getApplicationContext() on it. So either way it will end up using the application-context. Here's the source code. I was curious about this because I wasn't sure if the CookieSyncManager class would sync/save all cookies in the entire App, or just those in the Activity that created it (if you only provided an activity-context instead of application-context). But even after knowing it's using the application-context internally, I'm still not sure about this. I really wish the documentation would be more clear about what context-level they want/expect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mimicking class-based OOP constructors in Javascript Quick Note: OOP in Javascript is a topic that is beaten to death on Stackoverflow and elsewhere, but I cannot find this specific question answered anywhere. The "hanging code" in Javascript objects has always bothered me, as it seems to break the flow of the code. What I mean by "hanging code" is the following: function newObject() { var thisObject = this; // HANGING CODE DOING VARIOUS THINGS SUCH AS // $('#someDiv').click(function(){}); OR // var someObjectLiteral = {value:'value'}; } I wanted to mimic class-based OOP constructors by doing the following: function newObject() { var thisObject = this; function construct() { //WHAT USED TO BE HANGING CODE } construct(); } Is any of the following true or likely to be true about the second methodology: * *It is significantly slower *It will simply not work at all in certain situations *It breaks proper coding practice *It will be harder to debug *There is a superior methodology to achieve the same result Thank you. A: There is nothing wrong per-se about wrapping code inside an inner function. The only thing you have to watch out is that you can't use this inside other functions (you need to use an intermediate variable such as yout thisObject. Having taken that out of the way, I see no problem at all in having "hanging code" (at least the kind shown in your example). A language such as Java may have trained you to put everything inside a class but in Javascript you only really need to oop-things-up in cases where you explicitly want to take advantage of inheritance or polymorphism. You probably need to get away from the oop mindset a little. For example, in your case, "hanging code" inside a new object constructor might look bad but I would instead just rename the function to "addClickHandler" or "setLiterals" and call it a day. A: You could use something like the MooTools Class which will be slower than your method with the 'hanging' code. This is mostly due to the fact that the MooTools Class has overhead associated with their 'Native' structure. A lot of stuff you may not, and will likely not, need. It sounds like you want something straight-to-the-point. You could do something like: var Klass = function(attrs) { var key, newClass; attrs = attrs || {}; newClass = function() { if(this.init) { this.init.apply(this, Array.prototype.slice.call(arguments)); } }; for(key in attrs) { newClass.prototype[key] = attrs[key] } return newClass; }; Then, you could do something like: var Person = new Klass({ init: function(name, bg) { this.name = name; document.getElementById('container').styles.background = bg; }, speak: function() { 'I am ' + this.name; } }); var tim = new Person('tim', 'blue'); // background now blue tim.speak(); // 'I am tim' var jane = new Person('jane', 'purple'); // background now purple jane.speak(); // 'I am jane' So, this code will fire off the init() when you make a new instance of a class. Passing it whatever arguments. In which you can put your 'hanging' code. Node that, due to the way prototypes work, this does not allow you to make a new instance of a new instance. And you would need to change it further to allow for things like building off of a parent class. But this is a pretty simple way of building a class structure. This should work fine for what you want. If you were to come across something it "can't do" there will certainly be a way to correct that. You may just have to finagle the code. As I said in the previous paragraph. There will be a little overhead since a class is basically a function being returned, which you then make a new instance of. But nothing too significant. As for best practices, I would say it is not bad. There are a number of JS libraries that have quite extensive class structures in place for you to use. And a lot of people do use classes. But there are and will be arguments over the use of them since they are not real native JS types.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make a class object instance to return a predefined value? I am using Ruby on Rails 3.1.0 and the rspec-rails 2 gem. I am testing my controller code (BTW: I am newbie to rspec) and I would like to make possible that a class object instance returns a predefined value. That is, in my controller I have: def create ... if @current_user.has_authorization? ... else ... end end In order to test the "else part" of the if statement I would like to make possible that (for the current spec example that I am working on - read below for a sample implementation) the @current_user.has_authorization? returns false. How can I make that? I tried the following in my spec file, but it seems do not work as expected: it "should have no authorization" do @current_user.stub(:has_authorization?).and_return(false) # I also tried the following and it still doesn't work # @current_user.should_receive(:has_authorization?).and_return(false) post :create ... end A: @current_user in the context of your rspec test is not the same as @current_user in the context of your controller. One is an instance variable, in the instance of your controller class that Rails is running. The other is an instance variable in your rspec test. You aren't supposed to poke at your user variable, but rather need to make it so Rails finds a User supplied by the test framework. Take a look at this example. A: To avoid that issue you could use mocha, to do that do the following: Add the mocha gem to your Gemfile and run bundle install. Then change the Rspec mock configuration framework in your spec_helper.rb file RSpec.configure do |config| config.mock_with :mocha # config.mock_with :rspec end Then in your spec you can do this it "should have no authorization" do User.any_instance.stubs(:has_authorization?).returns(false) post :create ... end This (or the correct answer from Coderer) will solve your issue. Notice that as far as I know there is no any_instance equivalent in Rspec mocking functions. A: When your spec is running, self is pointing to a test object (try p self or puts self.class inside a spec sometime and see for yourself), so @current_user is referring to an instance variable on that test object. It has nothing whatsoever to do with the @current_user instance variable on your controller. One way to do what you want is to create a current_user method or accessor on your controller, and call it instead of accessing @current_user directly. Then you can stub or mock that method from your spec, assuming you can get a pointer to your controller instance. Another way is to set the @current_user variable directly from inside your spec. Again, get a pointer to your controller instance, then do x = mock("user"); controller.instance_variable_set(:@current_user, x) then you can mock/stub methods on x.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to merge all web.configs at once for a mvc3 app I've got a mvc3 app with several configurations (debug, ci, qa, client-dev, client-qa, release). I've got web.configs merging nicely within visual studio for whatever configuration is currently selected in the ide. So I've got this in my project. web.config -web.ci.config -web.qa.config - etc.. I've also got the configs merging properly in cruise control. Unfortunately, I've got to build the entire product to get each config. Here is what my cruise control config looks like for a single environment. <msbuild> <executable>C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe</executable> <workingDirectory>C:\Projects\Source\foo.SwsFall2011</workingDirectory> <projectFile>msbuild.xml</projectFile> <buildArgs>/noconsolelogger /p:Configuration=Dev;DeployOnBuild=true;DeployTarget=Package;PackageAsSingleFile=false /v:d "/l:ThoughtWorks.CruiseControl.MsBuild.XmlLogger,C:\Program Files\CruiseControl.NET\server\ThoughtWorks.CruiseControl.MsBuild.dll;C:\Projects\Artifacts\foo.SwsFall2011\msbuild-results.xml" </buildArgs> <targets>BuildCI;ConfigMerge</targets> <timeout>600</timeout> </msbuild> Is there a way just to merge the web.configs into a set of config directories with a single task that doesn't do the entire build? Something like: configs \dev\web.config \qa\web.config \client-dev\web.config A: The various web configs as per the functionality built in to visual studio only merge upon a publish. We have a post-build task to merge them upon build. Customize as you see fit. Realize the options are slim though - so don't shoot the messenger - this is just one way. There may be others, but nothing that I know of 'built in' Visual studio 2010 - Per Developer/machine/environment Web.Config settings
{ "language": "en", "url": "https://stackoverflow.com/questions/7590157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rendering a partial in a collection with Rails counter I'm rendering a partial in a collection: <%= render :partial => 'superlative', :collection => @profile.superlatives, :locals => {:superlative_count => @profile.superlatives.length} %> Here is the partial: <li class="superlative"><span title="<%= superlative.name %>"> <%= superlative.body %> </span></li> I want to render the collection so that: * *Every item except the last renders with a comma and space at the end *The last item starts with and So that the collection looks like this in its entirety: body, body, body, and body I have some of that working with the code below but can't get the spacing right. Can someone help? Maybe there's also an easier way to do it? Thanks! <% if superlative_counter + 1 == superlative_count %> <li class="superlative"><span title="<%= superlative.name %>"> <%= "and #{superlative.body}" %> </span></li> <% else %> <li class="superlative"><span title="<%= superlative.name %>"> <%= "#{superlative.body}," %> </span></li> <% end %> A: It occurs to me there's another way to do this. Using CSS pseudo-elements you can just insert commas and "and" where you want them. Take a look in this fiddle. The major caveat here is that, at least in some browsers, if someone copy-and-pastes the list the pseudo-elements' content won't be included (i.e. they get "foo bar baz" even though they saw "foo, bar, and baz." Assuming you want to do it in Ruby, though, what spacing issues are you seeing? I assume you're using CSS to turn a <ul> into a sentence--is there a particular reason you need each word to be inside an <li>? Your code looks fine, but I might be tempted to tweak it by moving those commas and 'and's outside the <span>s: <% if superlative_counter + 1 == superlative_count %> <li class="superlative"> and <span title="<%= superlative.name %>"><%= superlative.body %></span> </li> <% else %> <li class="superlative"> <span title="<%= superlative.name %>"><%= superlative.body %></span>,&nbsp; </li> <% end %> ...but I'm not sure that'll have any effect on a spacing issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android + Use LoaderManager with an ArrayAdapter? I might be way off here, but I have an ArrayAdapter managing static data for a ListFragment. Very simple stuff. However, I'm interested in taking advantage of the new LoaderManager class. Can I still use my ArrayAdapter and write my own loader? The documents seem to suggest this is true: "...the most common use of this is with a CursorLoader, however applications are free to write their own loaders for loading other types of data." If this is the case, how might I work with the overridden LoaderManager.LoaderCallbacks interface methods? @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {return null;} @Override public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {} @Override public void onLoaderReset(Loader<Cursor> arg0) {} A: If you are creating a new type of Loader you might need to use a different type for the data rather than Cursor (unless your new loader also returns Cursors). Your callbacks should look something like @Override public Loader<MyDataType> onCreateLoader(int id, Bundle args) { return new MyCustomLoader(...); } @Override public void onLoadFinished(Loader<MyDataType> loader, MyDataType data) { myArrayAdapter.add(data.something()); // etc } @Override public void onLoaderReset(Loader<MyDataType> loader) { myArrayAdapter.clear(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7590161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Display Dynamic Content in ASP.NET MVC 3 I have the following structure: * *Site.Master *Home - View *HomeController - Controller In the Site.Master I have a header that contains several ActionLinks, one of which is a Faq. In the Home view I have HTML that essentially displays static content, but, in the center pane/div I want to have dynamic content, based on certain HTML.ActionLinks that the user clicks on. So, for example, initially, I want the center DIV to display an intro - but if the user clicks on my Faq ActionLink, I want the center DIV to display content specific to my Faq. In the HomeController I have the following: [HttpGet] public ActionResult Intro() { var introRequest = _gatewayService.GetContent(new GetContentRequest { Content = ContentTypes.Introduction }); ViewData["content"] = introRequest.Result; return View(); } [HttpGet] public ActionResult Faq() { var faqRequest = _gatewayService.GetContent(new GetContentRequest { Content = ContentTypes.Faq }); ViewData["content"] = faqRequest.Result; return View(); } The idea would be that the action link for Faq would look something like: <%= Html.ActionLink("Faq","Faq","Home") %> A: As @Valamas said, use Ajax.ActionLink. For example, In markup: <div id=”faqContent”> @Ajax.ActionLink(“Click here to see FAQ!”, “Faq”, new AjaxOptions{ UpdateTargetId=”faqContent”, InsertionMode=InsertionMode.Replace, HttpMethod=”GET” }) </div> And in controller: public ActionResult Faq() { var faqRequest = _gatewayService.GetContent(new GetContentRequest { Content = ContentTypes.Faq }); return PartialView("Faq", faqRequest.Result); } And finally have a partial view Faq.chtml with required html for FAQ. A: First you will need to change the result of your action methods in your controller,instead of actionresult you can use jsonresult Second, in the view you can use jquery to load the dynamic content
{ "language": "en", "url": "https://stackoverflow.com/questions/7590163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linux/C: Get ip address from device name? Possible Duplicate: Get IP address of an interface on linux How can I get the ip address from the device name (Example: eth0)? A: DISCLAIMER: Your application SHOULD NOT depend on this kind of information. The application must see and use IP addresses ONLY. Ethernet devices are operating system plumbing. Keep in mind that you may have IP addresses not associated with any device, or devices with multiple IP addresses, multiple protocols (IPv4, IPv6), etc. Recheck the design of your application if it is really expecting to use IP addresses associated to Ethernet device names. If you still want to associate IP addresses and Ethernet device names, check getifaddrs(3), which is a simple frontend to netlink(7) kernel sockets. A: ip addr or ip addr show eth0 or the obsolete ifconfig eth0 And this is a question or serverfault.com A: Look here. If you need to use your result in a C program, you can use system(yourCommand) and then fopen() stdout to read the result.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: send commands to a webapp running on tomcat I'm new with java and tomcat, so, excuse me if it's silly. I would like to send commands (from the console) to a servlet that is already running on tomcat. The webapp will run the command in the tomcat context and return the appropiate answer. i.e: $ consoleApp status running Is it possible?, if yes, how? thanks in advance. A: You can make HTTP GET (or POST) requests to your servlet from the command line using tools like curl or wget and then process the servlet's response. Advantage: If properly set up, you can run those commands also from a remote location. A: Yes, you can use several command line tools such as curl or wget to call your servlet and obtain the response. A: and if you want to more than simple, you can make a simple program that communicate with servlet by HTTP Post or GET request. The key is : How to communicate with servlet, we can use several http method and any other protocol.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bringing convenience of Java code assistant from Eclipse to Visual Studio 2010 for native C++ projects Eclipse has many features which saves a developer much time, for example: 1) Override/Implement Methods... 2) TODO lists... 3) Fast access to documentation... (There might be also something else) Is there any plugin for VS 2010 which brings approximately the same functionality to native C++ projects? A: VisualAssist X provides refactoring, navigation and code assistance. When you're moving from Eclipse to VisualStudio, it drastically reduces the feeling that you're working with stone knives and bearskins.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UIScrollView wheel effect I need a scrollview in my iPad application that has two specific features, one of them is easy to find on much sample projects that is infinite scrolling. The second feature is, which is the problematic one, i need that scrollview seems as a circle (like a wheel) with a 3D depth effect, the current page is on tap of the screen with a big frame, and others can still be seen at the back, like far away in depth. You can see what i mean in this review video of TNT for iPad app. http://www.youtube.com/watch?v=Pv5EYliCciU Any idea will be greatly appreciated,thanks. A: What that video is displaying was probably not done with a UIScrollView. Most likely look into CoreAnimation and putting each of those screens into a layer for the background navigation screen. A: After EricLeaf's answer i moved my focus on animating those windows and found a solution on the net. You can find the sample code here Basically; As the above sample does, i use a uiview as the container instead of uiscrollview and custom layers for my views. Catch pangesturerecognizer and concat rotation and translation transformations on those layers as the users scrolls within a circle by using angles.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP string key in array gives Undefined index I have the following array: Array ( [A3L791B03M-YLWS] => 1 [A3L791B03MBLKS5] => 1 [A3L791B05M-BLKS] => 2 [A3L791B05M-BLU] => 1 [A3L791B05M-BLUS] => 1 [A3L791B05M-GRY] => 2 [A3L791B05M-H-S] => 1 [A3L791B05M-REDS] => 1 [A3L791B05M-S] => 2 [A3L791B05M-WHTS] => 2 [A3L791B05M-YLWS] => 2 [A3L791B10M-BLKS] => 2 [A3L791B10M-BLUS] => 2 [A3L791B10M-GRNS] => 1 [A3L791B10M-GRY] => 2 [A3L791B10M-REDS] => 1 [A3L791B10M-S] => 3 [A3L791B10M-S?KIT] => 1 [A3L791B10M-WHTS] => 2 [A3L791B10M-YLWS] => 1 ) However, when I try to call for the data of A3L791b10M-S via: echo $array_mysku_count['A3L791b10M-S']; However, when I do so, I get the following error: Fatal error: Uncaught exception 'Exception' with message 'Notice: Undefined index: A3L791b10M-S in... All the other keys seems to be fine. Anything that is specific about this key that is causing this? A: You're using the key A3L791b10M-S but it's actually A3L791B10M-S. Note the uppercase B there. A: A3L791B10M-S is different from A3L791b10M-S. Watch the case... A: Change the b to upper case. A3L791B10M-S You also may be interested in the strtoupper function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When I call Count method in Entity Framework, does it process all the columns or just one or what? Im looking for otimization. When I call Count method in Entity Framework, does it process all the columns or only one or what? If you also have any official site talking about this, I would appreciate. Thank you. A: I did some tests a while ago and found out that EF does a count on the server, it sends a query with a SELECT COUNT so it does not load all records for sure. about the columns, if you are referring to the difference between COUNT(*) or COUNT(Id) or COUNT(1) I have read somewhere a while ago that for SQL Server there is no difference, the COUNT(*) is optimized as COUNT(1) anyway. you could read many articles online or question here on SO... not excatly 100% what you asked but similar topics on performances of EF and ORM... How to COUNT rows within EntityFramework without loading contents? http://ayende.com/blog/4387/what-happens-behind-the-scenes-nhibernate-linq-to-sql-entity-framework-scenario-analysis How to optimize Entity Framework Queries
{ "language": "en", "url": "https://stackoverflow.com/questions/7590192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Put a Thread to sleep but keep animations going - is this possible? This might be a strange question but there might be a different solution for what I'm trying to achieve, I'm open to anything that works as needed! Facts: I have a UITableView with a UISearchBar handled by a UISearchDisplayController. Above said TableView I have some buttons and a small UIScrollView. When the user taps the SearchBar and the keyboard comes up, there is very little space to show the search results while typing. Therefore I want to move the TableView all the way to the top (covering the buttons and the ScrollView) when the user begins a search. My code and the problem: - (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller { ... [UIView beginAnimations:@"Search" context:nil]; [UIView setAnimationDuration:0.6]; [self.attractionsTableView setFrame:CGRectMake(0, 0, 320, 400)]; [UIView commitAnimations]; ... return; } Now the problem is that since the distance my UITableView has to travel is about 100 points, the SearchDisplayController is faster with putting the black overlay on top of the TableView and thus the black overlay is already on top while the TableView is still sliding up there. The result is a screen that looks kinda like this: problem http://img833.imageshack.us/img833/9186/problemqdu.png So the user sees the TableView sliding up (which would be fine) but the black overlay is already up there waiting because the searchDisplayController's animation is faster than mine. So I have a possible idea but don't know how to do this: Is there a way to set the duration of the animation of the searchDisplayController putting the black overlay on top of the search tableView? EDIT: I know I can set the animationDuration to 0.01 or even 0, but the speed of 0.6 seems pretty ok for a distance of 100 points, so I'm trying to find a different solution that lowering the duration. A: The trick is not let the run loop run normally until your animation is done. Animations are performed when the run loop is running in a certain mode. Luckily, the overlay animation is performed in a different run loop mode than other animations, which run in the default run loop mode. So, all you have to do is run the run loop from within your method until the animation is complete. - (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller { BOOL done = NO; // Pass the done variable's address as the context so we can be notified [UIView beginAnimations:@"SearchExpand" context:&done]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(animationDone:finished:context:)]; [UIView setAnimationDuration:0.6]; // Expend the table view to fill its superview self.attractionsTableView.frame = [[self.attractionsTableView superview] bounds]; [UIView commitAnimations]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; // Run the run loop until the animation completes while(!done) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if(![runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) break; [pool drain]; } } - (void)animationDone:(NSString *)name finished:(NSNumber *)finished context:(void *)context { // Set the done flag to YES *((BOOL*)context) = YES; // and kill the run loop CFRunLoopStop(CFRunLoopGetCurrent()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7590194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django setting for default template tag output when variable is None? I am looking for a django setting or programmatic way to make all django template tags show the empty string when the value is None. For example, imagine that I have some django template: {{cat}} chases {{mouse}} if both cat and mouse are None, it will render as: None chases None I am aware that I can set each one using {{cat|default:""}} or {{mouse|default_if_none:""}} However, I am looking for some sort of setting that would allow me to set the default for all tags, without explicitly adding |default:"" to every tag. I am also aware of a setting called TEMPLATE_STRING_IF_INVALID. However, this setting applies only to invalid strings. None is considered valid. A: No such thing exists. That's why the default and default_if_none filters exist. This is a feature; it makes you think about what you're doing instead of relying on some behavior that would often times be misleading. If there's a potential for a variable to be None, then you should plan for that contingency. If the variable should always have some value, then the "None" indicates something is not right. If the default was to just render a blank string, then you would not know whether the value is not defined or is actually a blank string. Write coherent code and forget about shortcuts. A: "Explicit is better than implicit" Think of how enraged you would be when things wouldn't render properly because you forgot that you had enabled the magic "render everything with a false value as a null string" setting. If you find you're using the default_if_none filter a lot, you might want to consider changing casting None to '' BEFORE it's passed to the template. Your template will be simpler, and you will have explicitly made this decision to stringify null values. A: This should do the trick, put it somewhere in the initialization code, for eg. in wsgi.py # Patch template Variable to output empty string for None values from django.template.base import Variable _resolve_lookup = Variable._resolve_lookup def new_resolve_lookup(self, *args, **kwargs): o = _resolve_lookup(self, *args, **kwargs) return o or u"" Variable._resolve_lookup = new_resolve_lookup
{ "language": "en", "url": "https://stackoverflow.com/questions/7590198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: Windows Mercurial global keychain I'm in the middle of trying to get mercurial working on a windows build server and am having issues. I went to the trouble of setting up the mercurial keychain (I had to install tortoisehg), and it works on a per-user basis. The problem is that I'm using Bamboo to run the builds, and it runs as an NT service owned by SYSTEM. Thus, any time it tries to do anything with hg, it gets prompted for a password. Obviously, I could put the password into a config file, but I want to avoid a plaintext password just sitting around. As far as I can tell, there are two ways of attacking this problem. Neither of which I know how to do: * *Make the mercurial keychain global, rather than per-user. This may not even be possible. *Somehow log in as the SYSTEM user and do a few mercurial commands with it, so that its keychain gets seeded with the user/password information. *Something completely different...? Thanks in advance for any insights you might have! -Ben A: I realize you've already found a solution, but in case future Googlers wind up here, I'll post what I did. First, you can have the bamboo service run as any user you want. I needed it to run as a normal user so that some of the registry entries that my compiler needs were available. To set the user for the bamboo service, you need to edit the wrapper.conf (C:\Program Files\Bamboo\conf\wrapper.conf on a normal install.) Obviously, before editing this, you'll need to uninstall the existing service if it is installed. The easiest way to set the login account is by adding this to the bottom of the file wrapper.ntservice.account=domain\username wrapper.ntservice.password=s3cr3t.p@ssw0rd Obviously, you may not want your login password in a plain text file. There are several ways around this, so I'll just point you to: http://wrapper.tanukisoftware.com/doc/english/props-nt.html . wrapper.ntservice.password.prompt may be of particular interest. If you use ssh for Mercurial, there is another option: you can set your ssh command in a Mercurial.ini. For the build server, I set most of these commands for the entire system at once by configuring them in a file in C:\Program Files\TortoiseHg\hgrc.d . I have a line that looks like: ssh=TortoisePlink.exe -batch -i "C:/Users/autobuilder/hgPrivKey.ppk" -l autobuilder For me, autobuilder is the normal user that things run as. The hgPrivKey.ppk is a private key file created with PuttyGen. I have the public key in the authorized_keys file on the server. Hopefully, these suggestions will get somebody on the right track. A: I ended up having to revert the bamboo remote agent from a NT service back down to a regular old process running under a normal user. This obviously comes with its own set of gotchas as far as management of the server goes, but it will have to do for now. I'll mark this as the answer in a day or so unless someone comes up with something better.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: selectRowAtIndexPath failing in viewWillAppear I've got a menu that's a UITableview in a UIPopovercontroller that when selected scrolls the parent view's UIScollView to a specific frame. It's working great. The problem is if you use the pageControl to scroll the frame I need to update the selected row in the table [_delegate returnPageNumber] returns the current pageControl.currentPage No errors, NSLog is reporting the correct page number: scrollIndexPath is <NSIndexPath 0x1a3380> 2 indexes [0, 3] But the correct cell doesn't highlight... why???? - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; //[tableView reloadData]; int isPage = [_delegate returnPageNumber]; NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:(isPage) inSection:0]; NSLog(@"scrollIndexPath is %@",scrollIndexPath); [tableView selectRowAtIndexPath:scrollIndexPath animated:NO scrollPosition:UITableViewScrollPositionNone]; } I've tried putting [tableView reloadData] before and after and having the code in viewDidAppear... nothing works A: try calling [super viewWillAppear] after everything else, in viewWillAppear: - (void)viewWillAppear:(BOOL)animated { NSIndexPath *selection = [self.tableView indexPathForSelectedRow]; [[self tableView] reloadData]; if (selection) { [[self tableView] selectRowAtIndexPath:selection animated:NO scrollPosition:UITableViewScrollPositionNone]; } [super viewWillAppear:animated]; //Trick is calling super last in this case. Then you can retrieve previously selected row to --> NSIndexPath *selection } A: Now working! - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [[self tableView] reloadData]; int isPage = [_delegate returnPageNumber]; NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:(isPage) inSection:0]; NSLog(@"viewDidAppear scrollIndexPath is %@",scrollIndexPath); [[self tableView] selectRowAtIndexPath:scrollIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone]; } The thing that made the difference was disconnecting the view outlet and then reconnecting it to the tableview. Not sure why this made a difference? I tried adding a view controller to the nib but it made no difference, so deleting it and reconnecting the view to the the tableview suddenly produced results. Voodoo.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: format a number to a character with css I'm working with a list of numbers in a table, specifically golf scores. And I want to replace occurrences of '0' with 'E'. I was doing this at the application level but the javascript I'm currently using to do some sorting gets very confused finding a letter in the middle of all the numbers. I look at it as a presentation problem and was hoping there's a css based solution. A: There isn't, unfortunately. You'll have to do it with JavaScript or on the server side. A: Not really. There was an effort to allow for a :contains() selector but that got removed. Here's a sneaky way to get the effect you want, though I suspect what you really need to do is fix the way your JavaScript executes sorts. So what you can do is add an attribute to your list, I've called mine data-score and replicate the scores. Then using the CSS attribute match selectors, you add some content, the "E", and alongside that you make the "E" black, and the original content ("O") white. <style type="text/css"> ul { list-style-type: none; } /* turn the "0" white */ li[data-score="0"] { color: #fff; } /* make an E, in black */ li[data-score="0"]:before { content: "E"; color: #000; } </style> <ul> <li data-score="100">100</li> <li data-score="0">0</li> <li data-score="10">10</li> <li data-score="5">5</li> <li data-score="100">100</li> </ul> Which will display as: 100 E 10 5 100 With the "0" really being there, but not visible. Read more about: :before selector, content, data attributes. Additionally, if you just plain output the "E" for a "0", and use data attributes for the sort, you can avoid the CSS hackery I'm suggesting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Moving controls from one stackpanel to another I have a bunch of buttons on a stackpanel which I want to programmatically move back and forth on demand. I'm struggling to get the visibility/alignment correct. It appears that the buttons seem to have some setting which occurs when they are initially rendered in the first stackpanel as they don't appear next to each other...and yet, if I add(new Button()) instead of add(btn) I see button images stacked together as I expect. The buttons are very basic 24x24 with an image. No styling/margins etc. They are moving from a stackpanel with horizontal alignment to one with vertical. Anyone know what's going on here? A: you should be able to do stackpane1.Children.Remove(button) and then stackpanel2.children.add(button) i suspect you must remove it from one then put into another or you will get funny results
{ "language": "en", "url": "https://stackoverflow.com/questions/7590205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Aptana Studio 3 content assist is black text on black background(unreadable) I have tried to change this by going to preferences-> General-> Appearance-> Colors and Fonts and in the basic folder changes the Content assist foreground color to white and click apply but each time I go back it has changed back to black :( Anyone know how to fix this? The content assist is unreadable. and yes I have tried restarting aptana and reebooting A: I fixed this by clicking the theme button and choosing a different theme. I ran into this problem, and this question came up in a search, so thought I better put an answer up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: When does Ninject's OnActivation get fired? I am sure this is a stupid question, as I am assuming the answer is "When the object is instantiated by Ninject"... But I want to double check... To give a little more context as to why I am asking the question, I have an asp mvc app which implements NinjectHttpApplication. However within the OnApplicationStarted override I need to activate a method on a singleton instance that is bound within Ninject. The problem is that the Kernel is exposed but shouldn't be used as a service locator, so I could get the object back from it and call DoSomeSetup(); method, but that seems like a fail. To my knowledge the NinjectHttpApplication instance isn't DI'd as the Global.asax file uses it directly, so I couldn't DI it into the application that way. This leaves me with one other option which would be to add the OnActivation(x=>x.DoSomeSetup()); call to the binding, however this object is only used in certain places, so it's not like the first time you load a page it would be required by the controller, so if OnActivation waits for the first instance to be created it may not happen for a while. Hopefully that's not too confusing :) A: Yes your asumption is correct (or at least mostly correct). The activation actions are run the first time an instance is resolved even if not created by Ninject (e.g. Constants) For HttpApplication you can use property injection by the way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Strategy for loading SQLite DB's into Android App I have a SQLite DB with 20,000 records. I cannot load the DB in the Emulator and it Force Closes on some installed devices. I can load the full DB on my Test Device (HTC Inspire). I have cut down the records to apprx 5,000 records and distribute the app and it installs and runs on the Emulator, other devices and my HTC with no problems. But I have sacrificed considerable content. I am looking for a "strategy" that will optimize the number of records that can be installed on different devices. How would you create and distribute an Android App with a pre-existing database to achieve the greatest number of installed records? Is there some magic way to know what the capacity of the device is that will help my situation? TIA A: One can load db effiecently of records up to 40,000.Try to load database at the beginning and only once in a public static array and access throughout your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why drupal adds version number to js path? Why the drupal adds the version number (like ?v=XXX) into the .js libraries? For example: <script type="text/javascript" src="http://localhost/misc/jquery.js?v=1.4.4"></script> And what means strange text at the end of path to .css files (after the '?' sign): @import url("http://localhost/modules/system/system.menus.css?lrrru5"); A: About dummy text (about versions Peter point to link), let's look comments on common.inc file in drupal/includes folder: function drupal_get_js($scope = 'header', $javascript = NULL) { .. // A dummy query-string is added to filenames, to gain control over // browser-caching. The string changes on every update or full cache // flush, forcing browsers to load a new copy of the files, as the // URL changed. Files that should not be cached (see drupal_add_js()) // get time() as query-string instead, to enforce reload on every // page request. $query_string = '?'. substr(variable_get('css_js_query_string', '0'), 0, 1); .. } function drupal_get_css($css = NULL) { .. // A dummy query-string is added to filenames, to gain control over // browser-caching. The string changes on every update or full cache // flush, forcing browsers to load a new copy of the files, as the // URL changed. $query_string = '?'. substr(variable_get('css_js_query_string', '0'), 0, 1); common.inc .. } A: Like they say here : http://drupal.org/node/82831 : it was not simple before to track the jquery version. Since you can use jquery functionality in the drupal page, you have to know which version you are using to know exactly which functionality is present.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you control event firing in C#? I wrote a program that does some processing on an image delivered via a web cam. There is an event that fires whenever a new frame is received from the camera. However, this happens more frequently than I'd like - so frequently that my image processing function doesn't complete before a new event appears and calls the same function again. How can I control when the event fires? Can I execute my image processing, say, every 5 events instead? I believe I have the pseudo code figured out, but I would prefer to see some examples in C#. A: Place the event callback "guarded" as follows. Then it won't be doing the processing many times at the same time. private bool m_active; void YourCallback(object sender, EventArgs args) { if(!m_active) { try { m_active = true; // Do the work here... } finally { m_active = false; } } } EDIT : Thread safe if using f.i. Semaphore. private System.Threading.Semaphore m_Semaphore = new System.Threading.Semaphore(0, 1); void YourCallback(object sender, EventArgs args) { if(m_Semaphore.WaitOne(0)) { try { // Do the work here... } finally { m_Semaphore.Release(); } } } A: You could use IObservable.SkipWhile to skip the event reaching your handler while your image processing is happening. This question has a similar problem: Filtering a Touch.FrameReported IObservable using arbitrary boolean condition that changes over time A: Supposing that you are attaching to the event using something similar to: public MyObject() { MyImageObject.Update += new UpdateEventHandler(ImageDataUpdated); } private void ImageDataUpdated(object sender, EventArgs e) { // do stuff } You could detach from the event in the beginning of the event handler and then use a timer to re-attach after a certain time interval. This would give you a somewhat exact control of the update rate. Something like: public MyObject() { MyTimer = new System.Timers.Timer(100); // 10 Hz MyTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); MyTimer.Enabled = true; } private void ImageDataUpdated(object sender, EventArgs e) { // detach from the event to keep it from fireing until the timer event has fired. MyImageObject.Update -= new UpdateEventHandler(ImageDataUpdated); // do stuff } private static void OnTimedEvent(object source, ElapsedEventArgs e) { // (re-)attach to the event handler. MyImageObject.Update += new UpdateEventHandler(ImageDataUpdated); } Using this strategy there is a good change that you are preventing the underlying image object to do additional work while the event handler is detached (of course this depends on the implementation of the image object). Chances are that you are saving CPU-cycles for your own image processing. A: Then what's the psuedo code you've got? I'd love to translate it to C#. ;-) You could use a DateTime variable in which you store the last occurrence of the event, and then skip out of the event if less than the desired time has passed. So, something like this if you want it to work once a second, no matter how many times it's being fired: private DateTime _lastEvent = DateTime.Now; public void Event() { if (_lastEvent + new TimeSpan(0, 0, 1) > DateTime.Now) return; _lastEvent = DateTime.Now; // Now do your event Console.WriteLine("Tick! " + _lastEvent); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7590232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: disable a jQuery .toggle() method I am looking for a way to disable a .toggle() attached to a div if (condition) { $("#div").toggle( function() { do this }, function() { do that } ); } else { // How do I achieve this? $("#div").disableToggle( ); } More explanation: This is a map application. The toggle in question is bound to an image button. The map loads at zoom level 4. The user zooms in, and the button in question becomes active only when the user is zoomed in more than zoom level 6. Once the user zooms out to less than level 6, I want the toggle button to become inactive again. A: Why not just unbind the click? $('#div').unbind('click'); A: You could put condition inside of the function: $("#div").toggle( function() { if (condition) { //do this } }, function() { if (condition) { //do that } } ); A: You can use .cleanData(): // this will destroy all data bound to that element $.cleanData($("#div")); Demo. A: Here's a way: Remove the class that is selected for toggling. Fiddle here : http://jsfiddle.net/leifparker/rSP34/2/ HTML <div class="button_toToggle"> Toggle it! </div> <div class="button_disableToggle"> Disable Toggle </div> <div class="happyDiv togglable">&nbsp;</div> JS $('.button_toToggle').click(function(){ $('.togglable').toggle(); }); $('.button_disableToggle').click(function(){ $('.happyDiv').removeClass('togglable'); }); A: If you weren't passing anonymous functions to toggle(), you could use the technique described on this forum post to unbind the events.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do I return an array in a response I'm trying to return an array in HTTP response. I'm thinking to return array as JSON objects. I'm doing echo json_encode($arr) but I get nothing in the response. UPDATE: I'm running a version of PHP that does not have json_encode method. json_encode was introduced in PHP 5.2. So I guess question is how would you return an array without using json_encode? $arr = array(); foreach($_POST['ids'] as $id) { $arr[$id] = $id; } echo json_encode($arr); return; Here are contents of my array: array(18) { [156795]=> string(6) "156795" [156800]=> string(6) "156800" [4292]=> string(4) "4292" [796053]=> string(6) "796053" [660520]=> string(6) "660520" ... A: Make sure to set the proper MIME type when sending back JSON: header('Content-Type: application/json'); echo json_encode($arr); A: json_encode() requires PHP 5.2.0 or above. Make sure your host hasn't compiled PHP with the --disable-json flag. Both of these can be checked with the phpinfo() function. The code you've posted so far works fine for me. A: json encode should do it with no problems. When I pump that data into an array it works fine. Can you post some code for building the array? What version of PHP are you using? A: plz use json validator to make sure ur json is correct look I did this & it worked fine $arr = array(); $i=0; while($i<10) { $arr[$i] = $i; $i++; } echo json_encode($arr); return;
{ "language": "en", "url": "https://stackoverflow.com/questions/7590237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: FancyBox onload show is not working with normal click I'm creating a little JavaScript game. When the page loads, it is supposed to display a Fancybox over the page. Here is my jQuery for the Fancybox: $(document).ready(function() { $('#test').fancybox({ 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'showCloseButton' : false, 'overlayOpacity' : 1 }).click(); }); Here is my HTML: <a id="test" href="#test2" style="display:none;">Test the Popup</a> <div style="display:none;"> <div id="test2" style='padding:10px; background:#fff;width:550px;'> <b style="color:#FF9C21;font-size:24px;">HTML Jeoprady</b><br> <span style="font-size:15px;"> You think your good at HTML? Well test your skill here.<br> Please know there is more to HTML than 2 tags ;)<br> Are you ready?<br><br> <b style="color:#FF9C21;font-size:24px;">Name:</b> <input type="text" id="team1" /> </span> <br><br> <span id="start" onclick="loop();" style="cursor:pointer;color:#FF9C21;font-size:20px;"> <center>Start Game!</center></span> </div> </div> All of my FancyBoxes that activate onclick show, but then it automatically closes about 5 seconds after it opens. Is there a way I can fix this? A: Instead of .click() you should probably just use .open() Edit: Silly me, there is no .open(). I have had issues with firing click programmatic click events before. If the method you are trying is causing issues, try this $('#test').trigger('click') or alternatively use a manual call $.fancybox('html content here',{options}) A: If you did a manual call you could do: var theContent = $('#div-id').html(); $.fancybox(theContent, { 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'showCloseButton' : false, 'overlayOpacity' : 1 }); And then, the contents of #div-id would be in the manual call. I hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Foreign Key Constraint fail I'm trying to insert a new row in the table but I'm getting below error: Cannot add or update a child row: a foreign key constraint fails (`wmetools_restool_dev/keywords`, CONSTRAINT `keywords_ibfk_1` FOREIGN KEY (`link_id`) REFERENCES `links` (`link_id`) ON DELETE CASCADE ON UPDATE CASCADE) I have supplied all the fields required. Does it mean I need to insert more fields? A: The table has a foreign key contraint to another table called links. You have to first insert a row in the links table with the correct link_id before you can insert the row into your table.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Read a text file and create a 'Page' every 7 lines How may I accomplish the task above? What I have been trying to do is separate the pages into different arrays but failed terribly. Code by request (does not even close to work) int a = 1; int b = 5; File folder = new File("c:/files"); File[] listOfFiles = folder.listFiles(); String[] page1 = new String[7]; String[] page2 = new String[7]; String[] page3 = new String[7]; String[] page4 = new String[7]; String[] page5 = new String[7]; String[] page6 = new String[7]; int c = 0; for (int i = 0;i<listOfFiles.length; i++) { if(i>=0 && i <= 7) { page1[i] = listOfFiles[i].getName(); } else if(i>=8 && i<=15) { page2[i] = listOfFiles[i].getName(); } else if(i>=16 && i<=23) { page3[i] = listOfFiles[i].getName(); } else if(i>=24 && i<=31) { page4[i] = listOfFiles[i].getName(); } else if(i>=32 && i<=39) { page5[i] = listOfFiles[i].getName(); } } A: This might help you: * *Read text file in java *Use the modulo operator A: Your code can't work, because when you do page2[i] = xxx, the variable named i should take a value between 0 and 6, and its value goes from 8 to 15. The same for the other pages. Even page1 will fail because the last index you use is 7, that is not in the range 0-6. Try something like: for (int i=0; i<listOfFiles.length; i++) { if(i>=0 && i<7) { page1[i] = listOfFiles[i].getName(); } else if(i>=7 && i<15) { page2[i-7] = listOfFiles[i].getName(); } else if(i>=16 && i<23) { page3[i-16] = listOfFiles[i].getName(); } ... } I hope you get the idea. Even this way your code is a little ugly to maintain, you should think about how to define only one bidimensional array, and to use the modulus (%) operator to access it in a simpler way and with less code. The following code is untested, but I hope it guides you: int NUM_PAGES = 7; File folder = new File("c:/files"); File[] listOfFiles = folder.listFiles(); String[][] pages = new String[NUM_PAGES][listOfFiles.length/NUMPAGES]; for (int i=0; i<listOfFiles.length; i++) { int currentPage = i % 7; int currentPosition = pages[currentPage].length; pages[currentPage][currentPosition] = listOfFiles[i].getName(); } You can also use Java Collections that would simplify your code even more;
{ "language": "en", "url": "https://stackoverflow.com/questions/7590245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Combine three grayscale images into RGB with MATLAB I have three grayscale images where each image represents a single channel from a RGB image of 16-bit resolution. I would like to convert them to obtain one single RGB image. I have tried cat and ind2rgb but it is not working. Should we index our grayscale images before using ind2rgb? Is there any other way of doing it? Thanks A: Assuming you have three matrices R,G,B of type int16. If you try RGB = cat(3,R,G,B); imshow(RGB) IMSHOW will complain that: RGB images must be uint8, uint16, single, or double.. In fact if you check the documentation: A truecolor image can be uint8, uint16, single, or double. An indexed image can be logical, uint8, single, or double. A grayscale image can be logical, uint8, int16, uint16, single, or double. A binary image must be of class logical. So if you concatenate three int16 grayscale images, and you want to use IMSHOW, you have to convert the resulting truecolor image to something it supports: imshow( im2double(RGB) )
{ "language": "en", "url": "https://stackoverflow.com/questions/7590246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: create expression designer in java I'm trying to create a expression designer in Java, any idea if there are something like that in the market? The expression that i need to build are like this: * *Var >= 5 Or Var = null *Var2 > 20 And Var2 < 50 *Var3 = 15 How can i do this? Thanks. A: Is this what you need? if (Var >= 5 || var == null) if (Var2 > 20 && Var2<50) Var3 = 15; A: I doubt there is any out-of-the-box tool that lets you define your own expression language (or do you have a specific language in mind?) and provides you a generic GUI for that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the difference between xmalloc and malloc? What is the difference between xmalloc() and malloc() for memory allocation? Is there any pro of using xmalloc()? A: xmalloc is part of libiberty https://gcc.gnu.org/onlinedocs/libiberty/index.html which is a GNU utils library. malloc is ANSI C. xmalloc is often included in-source in many important GNU projects, including GCC and Binutils, both of which use it a lot. But it is also possible to build it as a dynamic library to use in your programs. E.g. Ubuntu has the libiberty-dev package. xmalloc is documented at: https://gcc.gnu.org/onlinedocs/libiberty/Functions.html and on GCC 5.2.0 it is implemented on libiberty/xmalloc.c PTR xmalloc (size_t size) { PTR newmem; if (size == 0) size = 1; newmem = malloc (size); if (!newmem) xmalloc_failed (size); return (newmem); } void xmalloc_failed (size_t size) { #ifdef HAVE_SBRK extern char **environ; size_t allocated; if (first_break != NULL) allocated = (char *) sbrk (0) - first_break; else allocated = (char *) sbrk (0) - (char *) &environ; fprintf (stderr, "\n%s%sout of memory allocating %lu bytes after a total of %lu bytes\n", name, *name ? ": " : "", (unsigned long) size, (unsigned long) allocated); #else /* HAVE_SBRK */ fprintf (stderr, "\n%s%sout of memory allocating %lu bytes\n", name, *name ? ": " : "", (unsigned long) size); #endif /* HAVE_SBRK */ xexit (1); } /* This variable is set by xatexit if it is called. This way, xmalloc doesn't drag xatexit into the link. */ void (*_xexit_cleanup) (void); void xexit (int code) { if (_xexit_cleanup != NULL) (*_xexit_cleanup) (); exit (code); } Which as others mentioned, is pretty straightforward: * *try malloc *if it fails * *print error messages *call exit A: xmalloc() is a non-standard function that has the motto succeed or die. If it fails to allocate memory, it will terminate your program and print an error message to stderr. The allocation itself is no different; only the behaviour in the case that no memory could be allocated is different. Use malloc(), since it's more friendly and standard. A: an primitive example of xmalloc.c in K&R C #include <stdio.h> extern char *malloc (); void * xmalloc (size) unsigned size; { void *new_mem = (void *) malloc (size); if (new_mem == NULL) { fprintf (stderr, "fatal: memory exhausted (xmalloc of %u bytes).\n", size); exit (-1); } return new_mem; } then in your code header (early) you put #define malloc(m) xmalloc(m) to silently rewrite the source before compilation. (you can see the rewritten code by invoking the C preprocessor directly and saving the output. ) if crashing your program is not what you want you can do something different * *Use a garbage collector *redesign your code to be less of a memory hog *have error checking code in your program to handle an Out of Memory or other allocation error gracefully. Users don't enjoy losing their data to a built-in crash command in their program. A: xmalloc is not part of the standard library. It's usually the name of a very harmful function for lazy programmers that's common in lots of GNU software, which calls abort if malloc fails. Depending on the program/library, it might also convert malloc(0) into malloc(1) to ensure that xmalloc(0) returns a unique pointer. In any case, aborting on malloc failure is very very bad behavior, especially for library code. One of the most infamous examples is GMP (the GNU multiprecision arithmetic library), which aborts the calling program whenever it runs out of memory for a computation. Correct library-level code should always handle allocation failures by backing out whatever partially-completed operation it was in the middle of and returning an error code to the caller. The calling program can then decide what to do, which will likely involve saving critical data. A: As others have mentioned, it's true that xmalloc is very often implemented as a wrapper function that invokes the OS-supplied malloc and blindly calls abort or exit if it fails. However, many projects contain an xmalloc function that tries to save application state before exiting (see, for example, neovim). Personally, I think of xmalloc as a kind of project-specific extended malloc rather than an exiting malloc. Though I don't recall ever seeing a version that didn't wind up calling abort or exit, some of them do a lot more than that. So the answer to the question "What's the difference between xmalloc and malloc is: it depends. xmalloc is a non-standard, project-specific function, so it could do anything at all. The only way to know for sure is to read the code. A: I have seen xmalloc while working on IBM AIX. xmalloc is a kernel service provided by AIX. Nothing can explain a function better than the function's man page in my opinion. So I am pasting the below details from the man page Purpose: Allocates memory. Syntax: caddr_t xmalloc ( size, align, heap) Parameters: size: Specifies the number of bytes to allocate. align: Specifies the alignment characteristics for the allocated memory. heap : Specifies the address of the heap from which the memory is to be allocated. Description: The xmalloc kernel service allocates an area of memory out of the heap specified by the heap parameter. This area is the number of bytes in length specified by the size parameter and is aligned on the byte boundary specified by the align parameter. The align parameter is actually the log base 2 of the desired address boundary. For example, an align value of 4 requests that the allocated area be aligned on a 2^4 (16) byte boundary. There are multiple heaps provided by the kernel for use by kernel extensions. Two primary kernel heaps are kernel_heap and pinned_heap. Kernel extensions should use the kernel_heap value when allocating memory that is not pinned, and should use the pinned_heap value when allocating memory that should always be pinned or pinned for long periods of time. When allocating from the pinned_heap heap, the xmalloc kernel service will pin the memory before a successful return. The pin and unpin kernel services should be used to pin and unpin memory from the kernel_heap heap when the memory should only be pinned for a limited amount of time. Memory from the kernel_heap heap must be unpinned before freeing it. Memory from the pinned_heap heap should not be unpinned. If one is interested in knowing more about this function can visit the following link: IBM AIX Support
{ "language": "en", "url": "https://stackoverflow.com/questions/7590254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "66" }
Q: Are there any known algorithms, open source programs, or white papers for cracking a password given a known portion of the password? Essentially a a friend of mine locked himself out of an encrypted container he created. He must have made a typo when entering his password, because he cannot access the container. We know what it is supposed to be, and the actual password is sure to be a variation of this and/or very similar to it. I'm looking for code or a white paper dealing with this notion of "fuzzy" password cracking given a known portion of the password or known pattern that the password follows. The language is unimportant. I've already developed a way to brute force the password prompt, what I need is to develop an algorithm that will let me intelligently attempt to crack it so I don't have to try every possible combination. I would think someone else has already done this, however. I understand the concepts behind this to an extent, but am looking for code or a white paper where someone might have already solved this issue. UPDATE So I've constructed a dictionary (Python, but feel free to send examples in any language) using characters that might be in the passphrase. Considerations were keystroke proximity on a standard QWERTY keyboard, 1337 speak equivalents, and an accidental '/' character for each letter since it is near the shift key. From there the sample pass phrase is supplied, and each letter is tried. This is following this example: http://code.activestate.com/recipes/535171-password-cracker/ import os from commands import getoutput known = { '_': ('_', ' ', '-', '.', '/'), 'b': ('b', 'B', '3', '8', '*', 'v', 'V', 'n', 'N', 'g', 'G', 'h', 'H', ' ', '/'), 'g': ('g', 'G', '6', '^', 'f', 'F', 'h', 'H', 'b', 'B', 'v', 'V', 't', 'T', '/'), 'l': ('l', 'L', '1', '!', ';', ':', 'k', 'K', 'o', 'O', '.', '>', ',', '<', 'p', 'P', '/'), 'e': ('e', 'E', '3', '#', '4', '$', 'r', 'R', 'w', 'W', 'd', 'D', '/'), 'h': ('h', 'H', '4', '$', 'g', 'G', 'j', 'J', 'y', 'Y', 'b', 'B', 'n', 'N', '/'), 'i': ('i', 'I', '1', '|', '!', '\\', 'u', 'U', 'o', 'O', 'k', 'K', '8', '*', '9', '(', '/'), 't': ('t', 'T', '7', '&', '+', 'r', 'R', 'y', 'Y', 'g', 'G', '4', '5', '%', '6', '^', '/'), 'r': ('r', 'R', 'e', 'E', 't', 'T', 'f', 'F', '4', '$', '5', '%', '/'), } command = 'open-sesame %s' # hey, use your imagination ;) # I obviously supplied only needed letters for this example, I can't tip you # off to the real pass phrase ;) This conveys the general idea.... passwdBasic = 'Big_Leg_Hitter' def main(): arrays = [known[ltr] for ltr in passwdBasic] start = [ltrs[0] for ltrs in arrays] end = [ltrs[-1] for ltrs in arrays] indexes = [0] * len(arrays) maxes = [len(ltrs)-1 for ltrs in arrays] chrs = [ltrs[i] for ltrs, i in zip(arrays, indexes)] while chrs != end: passx = ''.join(chrs) open('tries.txt', 'a+').write(passx + '\n') out = getoutput(command) if 'wrong password' not in out: print 'GOT IT!', passx return # Next letter for i in range(len(indexes)-1, -1, -1): if indexes[i] <= maxes[i]-1: indexes[i] += 1 break else: indexes[i] = 0 # Make up the chrs chrs = [ltrs[i] for ltrs, i in zip(arrays, indexes)] if __name__ == '__main__': main() The fictitious 'open-sesame' is a modified utility that mounts this particular type of encrypted volume, it was not written in python but has been made into a command line tool so that this script can interact with it. A couple of challenges / research directions: * *If the '/' character was accidentally hit instead of the shift key, this would actually add a character to the pass phrase and thus could appear before any of the letters. This needs to be accounted for in the solution. *It would be nice to integrate this with the spellchecker utility proposed by @rrenaud: http://norvig.com/spell-correct.html *I'm fascinated by the application of Baye's Theorum of probability statistics which was applied to solve the spellcheck problem; I'm wondering if any research is available on erroneous keystrokes and the probability of hitting certain keys over others when typing certain words and/or phrases. This logic could be applied to password cracking in much the same fashion as the spellcheck utility, which benefits from known lists of common misspellings. I have no erroneous keystroke data with which to "train" a neural net utility. I appreciate all the great help, I just wanted to share where I'm at so far for everyone's benefit. A: Have you tried enumerating edits from the given known faulty password? If you are only a few edits away (like it would be if it was a typo), there isn't really that many possibilities. It's enumerating one level of edits is solved by this beautiful code by Norvig for spelling correction in the edits1() function. You could just apply that in a deepening depth first kind of way, so you try single edits first, and then edits of edits, and edits of edits of edits etc. A: * *First you need your character set. Were special characters a possibility? Upper and lower case? Numbers? *Next you need your original guess. Maybe 2 guesses, the second one would have your upper and lower cases inverted for the chance that the CAPS LOCK key was down. (fuzzY v. FUZZy) *Now you need to iterate all possibilities of... an edit, a delete and an insert. * * *You have 3 sets of initial guesses *Now you decide how far you want to take this. Maybe 2 edits, 2 deletes, or 2 inserts... or 1 edit and 1 insert, or 1 delete and 1 insert etc. Some JavaScript code to illustrate: var charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; var guesses = {"passWORD":true, "PASSword":true}; function getProps(obj) { var lst = []; for(var g in obj) lst.push(g); return lst; } function transformEdit(guesses) { var lst = getProps(guesses); for(var x=0; x<lst.length; x++) { var guess = lst[x]; for(var y=0; y<guess.length; y++) { for(var z=0; z<charset.length; z++) { guesses[guess.slice(0,y) + charset.charAt(z) + guess.slice(y+1)]=true; } } } } function transformDelete(guesses) { var lst = getProps(guesses); for(var x=0; x<lst.length; x++) { var guess = lst[x]; for(var y=0; y<guess.length; y++) { guesses[guess.slice(0,y) + guess.slice(y+1)]=true; } } } function transformInsert(guesses) { var lst = getProps(guesses); for(var x=0; x<lst.length; x++) { var guess = lst[x]; for(var y=0; y<guess.length+1; y++) { for(var z=0; z<charset.length; z++) { guesses[guess.slice(0,y) + charset.charAt(z) + guess.slice(y)]=true; } } } } // not the most efficient way // but you'll get every possible edit, delete and insert transformDelete(guesses); transformInsert(guesses); transformEdit(guesses); getProps(guesses).length; //1759604 The code doesn't present the MOST EFFICIENT solution since there is a lot of overlap that could of been avoided, but this is to generate a password list for a one shot problem so... I used the JS object property list as a Hash Set of guesses. You could output the guesses to a password list by iterating the array returned by getProps(guesses).
{ "language": "en", "url": "https://stackoverflow.com/questions/7590263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: vertically center text in tabs How do I center the text vertically in tabs within a TabHost? The text sits at the bottom right now. I seemed to have tried everything but nothing works. I've tried using things like android:layout_gravity="center" and android:gravity="center" but they do nothing. Thanks A: Some people ask it without solution . The best thing I can suggest you is to make your custom tabHost. Like this A: See the answer from kocus to my question Controlling Tab colour-state / size in a TabActivity. It's not exactly what you want but it explains how to customize Tabs and hopefully it will help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use multiple RewriteRule rules in htaccess? I'm using 2 RewriteRule rules in my htaccess RewriteEngine on RewriteBase / # if a directory or a file exists, use it directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d #if it has member/photo/render_fast forward to photo_render.php RewriteRule ^member/photo/render_fast(.*) /photo_render.php?r=$1 [L] # otherwise forward it to index.php RewriteRule . index.php [L] However this doesn't work, when I'm trying in my local machine, my Apache always use the second rule, and in my hosting server Apache always display an error. What am I doing wrong ? A: What's happening is the 2nd time around (after the URI has been rewritten to /photo_render.php) the 2nd rule is being applied, thus /photo_render.php is getting rewritten to index.php. You need to add a few conditions when you try to match something like . or .*. This should work: RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^member/photo/render_fast(.*) /photo_render.php?r=$1 [L] # otherwise forward it to index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php [L] Note that this will also fail if for some reason you don't have photo_render.php.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ignoring Compilation errors - Java I have around 1500 files to compile, in which 15-20 files have compilation errors. These files are not under my control, so I could not do any modification/update/delete. So, i have two questions here. 1) how do i ignore the compilation errors from these 15-20 files and continue to produce the .class file for rest of them. is there any javac commandline option or anything which will ignore the compliation errors and produce the .class files for all other non error files. 2)will the java compiler abort compilation as soon as it sees these errors or will it continue compiling(producing .class files) everything else and at the end then complain about these files with errors. A: You cannot ignore compile errors. They will always fail the build. Your only choices are to talk to whoever controls the files to get them fixed or find a way to otherwise replace them. If you try to remove them from the build, you will also have to remove any files that use those files. For example class A { B b; } If B has a compile error, your build script can skip B.java, but when you hit A.java, it's going to try to compile B anyway, so A has to be removed. This may prove to be a non-trivial task. A: You could write yourself a script that traverses your source tree and calls javac for each java file individually. This way you will end up with all files compiled correctly that do not depend on the files with errors. This would be a horrendously slow operation, though. I would expect it to take several 100 times longer than a single call to javac (considering you would end up with about 1500 calls). A: You can use Eclipse. Its internal compiler is - at least in some cases - able to keep going with the rest of the build, even when some classes don't compile fully. It will even produce class files for the broken classes if possible, generating methods which throw an exception as soon as they're called. I would strongly recommend that you simply take a copy of all the source and fix the errors at least in your own copy as early as possible, but Eclipse's partial compilation may help you. A: You can exclude certain source files from compiling using an exclude tag in the ant task. <target name="compile" description="Compile Java source files"> <javac destdir="classes" classpathref="classpath"> <src path="src"/> <exclude name="**/excluded_folder/**"/> </javac> </target> EDIT: But of course any java files that are dependent on the excluded classes will also fail to compile unless you already have a pre-compiled version of excluded files in the classpath. A: Create mockups of the offending files. Basically the same idea as a C header file, include the function signatures and reasonable default return values (null, false, 0). This will allow javac to compile everything, just make sure the mock classes don't get included in the final distribution, or you'll have strange bugs when they end up first in the classpath. This works for implementing broken interfaces and inheriting from broken classes too. A: * *Tell the one who broke the code (diplomatically, of course) to fix it ASAP. Others have suggested (see 2nd comment there) to make these occurrences public (within a team/company), which greatly reduces the number of such compilation errors *Comment everything that prevents the code from compiling (supposed that you don't need those parts) You should not have to deal with not-compiling code, but the one who committed it. If there are more people working on that project, everyone has to deal with that same problem on his local machine (find out why it didn't compile, track down the erroneous classes, exclude/comment those classes if your code does not depend on them, rebuild, etc.) It is much more efficient to have only 1 person to fix the problem, and everyone else just updates his local repository. A: What do you mean which will ignore the compliation errors and produce the .class files for all other non error files Do you realise that if these files are related ( as if in a single project ) then the dependent source files will not compile too.. ? There is no way to by-pass that except to correct the compilation errors and retrying !
{ "language": "en", "url": "https://stackoverflow.com/questions/7590275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Rolling log file in PHP I'd like to write/read a rolling log file with PHP, where only the latest ~300 lines are stored/read and anything older is discarded. I'm not sure of the most efficient way of going about it - it needs to work fast as it's recording page hits on high traffic web sites. Another PHP script will be regularly reading the log files and using the data for calculations. There are so many PHP file functions I'm confused as to where to start! I don't think my hosting environment has access to commands such as tail or awk or similar, so a pure PHP solution is preferred. Any help appreciated! A: You can use fopen: http://us3.php.net/manual/en/function.fopen.php $mode = 'a+'; // opens the file with read/write access and sets the pointer to the end of the file $handle = fopen ($filename, $mode); Next you pump the file into an array and lob off everything except the last 300 lines. If you are really interested in just keeping the file down to a certain size (you said ~300 lines) then you can use fseek http://us3.php.net/manual/en/function.fseek.php (From the manual): <?php $fp = fopen('somefile.txt', 'r'); // read some data $data = fgets($fp, 4096); // move back to the beginning of the file // same as rewind($fp); fseek($fp, 0); ?> A: For performance comparisons, you'll have to do some benchmarking, but here's one possible way to do it: <?php function writeToLog($file, $str, $maxLines = 300) { $linesToWrite = explode("\n", $str); $numLinesToWrite = count($linesToWrite); $logLines = explode("\n", file_get_contents($file)); array_splice($logLines, $maxLines - $numLinesToWrite, $numLinesToWrite, $linesToWrite); file_put_contents($file, implode("\n", $logLines)); } A: Not sure about the performance of this either, but here's my take on it: // read lines in file as array $lines = file( 'log.log', FILE_IGNORE_NEW_LINES ); // log file equal to or larger than 300 lines? if( count( $lines ) >= 300 ) { // remove everything from line 0 to 299 from the end // in other words keep last 299 lines array_splice( $lines, 0, -299 ); } // append a new line of data $lines[] = 'Test data ' . time() . "\n"; // put the lines back, first imploding the lines array with a newline char file_put_contents( 'log.log', implode( "\n", $lines ) ); A: PHP function for doing so. Makes sure log is writeable. Creates log if not exists: // keeps log_file <= max_log_lines lines function logTruncated($report, $log_file, $max_log_lines = 1000) { if (!$report || !$log_file) return; if (!touch($log_file)) die('Cant write log: '.$log_file); $lines = array_merge(file($log_file), preg_split('/\r?\n/', $report)); $lines = array_slice($lines, -1 * $max_log_lines); file_put_contents($log_file, implode("\n", $lines)); } A: Just checks if the log file exists already and if it's bigger than the max size (4Mb in my code) it will read it, remove some text at the beginning and add the new text in order to keep the size within the max size $text = "Your text to log"; //if file exists and it's bigger than 4Mb then remove some text at the beginning to limit size $log_file = __DIR__ . DIRECTORY_SEPARATOR . 'LOGS' . 'log.txt'; if(file_exists($log_file)){ clearstatcache(); $size = filesize($log_file); if($size >= 4194304){ $chunk = file_get_contents($log_file, FALSE, NULL, -(4194304 - strlen($text))); $text = $chunk . $text; $mode = 0; //overwrite } else $mode = FILE_APPEND; } $file_exc = file_put_contents($log_file, $text . PHP_EOL , $mode | LOCK_EX); A: Append line and rename maxed out file Sometimes the best solution involves tweaking the requirements a little bit. Rather than jump through hoops parsing and modifying a single log file, just append each new event to the log file and roll-over the file whenever it hits the size limit. function logEvent($line) { $maxLogFileSize = 24000; //24K (about 300 lines) $logFilename = "events.log"; //latest events $archiveFilename = "events-archive.log"; //older events if (filesize($logFilename) > $maxLogFileSize) rename($logFilename, $archiveFilename); file_put_contents($logFilename, $line . PHP_EOL, FILE_APPEND); } By rolling over your log file into an archive log file, you can achieve all the goals plus: * *Simplify the code *Improve performance *Reduce risk of file corruption
{ "language": "en", "url": "https://stackoverflow.com/questions/7590276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is it possible to change the UriTemplate at runtime I have the following WebInvoke Attribute: [OperationContract] [WebInvoke( Method = "POST", UriTemplate = "", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] I would like the UriTemplate value to be set based on a runtime value. Is there any way to set the UriTemplate in the service implementation at runtime? A: Yes, you can do that, if you use an endpoint behavior which is added before the WebHttpBehavior. This behavior can change the properties of the WebGetAttribute/WebInvokeAttribute. The code below shows an example of a behavior which changes the UriTemplate property of a [WebGet], but it would work just as well for [WebInvoke]. public class StackOverflow_7590279 { [ServiceContract] public class Service { [WebGet(UriTemplate = "/Add?x={x}&y={y}", ResponseFormat = WebMessageFormat.Json)] public int Add(int x, int y) { return x + y; } } public class MyBehavior : IEndpointBehavior { public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { foreach (OperationDescription od in endpoint.Contract.Operations) { if (od.Name == "Add") { WebGetAttribute wga = od.Behaviors.Find<WebGetAttribute>(); if (wga != null) { wga.UriTemplate = "/Add?first={x}&second={y}"; } } } } public void Validate(ServiceEndpoint endpoint) { } } public static void Test() { string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); var endpoint = host.AddServiceEndpoint(typeof(Service), new WebHttpBinding(), ""); // This has to go BEFORE WebHttpBehavior endpoint.Behaviors.Add(new MyBehavior()); endpoint.Behaviors.Add(new WebHttpBehavior()); host.Open(); Console.WriteLine("Host opened"); WebClient c = new WebClient(); Console.WriteLine("Using the original template (values won't be received)"); Console.WriteLine(c.DownloadString(baseAddress + "/Add?x=45&y=67")); c = new WebClient(); Console.WriteLine("Using the modified template (will work out fine)"); Console.WriteLine(c.DownloadString(baseAddress + "/Add?first=45&second=67")); Console.Write("Press ENTER to close the host"); Console.ReadLine(); host.Close(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7590279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where to put core resources in Symfony2? I started to build a website with Symfony2, and I had a little bit of a quandary about resources. The Symfony2 Book says that every resource file have to be in a Bundle, but what about the most essential images, .js and .css files that I use in the base.html.twig file on every page? Should I make a CoreBundle or something similiar, just for these files, or should I put these in the app\Resources folder (or directly in the web folder, maybe)? If I can use the app\Resources folder for these, how can I reference these files from the template? Making a Bundle just for this seems a little unnecesary, and the asset urls for these files are ugly too (e.g. '/bundles/projectcore/images/logo.jpg') in my opinion. What's the best practice here? A: I've had situations where I've kept all files in /web (i.e. /web/js) and others where I've kept them within an 'Assets' bundle. If you're developing a bundle that's going to be reused in numerous projects, it makes sense to store the assets in that bundle. I think you would then publish/install those assets to the web folder using the command line. For example, let's say you had a BlogBundle that required specific css. You would store the css in that bundle, so the next time you use BlogBundle for a project you could easily reuse the css. As with many other things with Symfony2, your personal preference plays a big part in these decisions. I recommend staying consistent though with where you store your assets. Having to manage assets split in three different locations (web, AssetsBundle, other bundles) could be a big headache. So pick a location, and try to stay consistent. As for accessing assets from app/Resources... you may be able to use Assetic for this. I'm not very familiar with it, but I believe you can load assets from anywhere within your project. I'd actually recommend taking a look at the core Assetic code (look in vendor\Assetic) instead of the Symfony2 Assetic helper because you'll get a better idea of just what's possible. A: We used a symlink in Linux so that /web/bundles/projectcore/images points to src/Bundle/Resources/public/images With Subversion in Netbeans, it does work. The nice thing is that all your application remains in the /src/Bundle folder
{ "language": "en", "url": "https://stackoverflow.com/questions/7590280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to display certificate of HTTPS request in embedded WebView In my Mac OS X app I'm using an embedded WebView to do OAuth logins for different services. Most of them use a HTTPS request for the authorization form that's displayed in the WebView. Now I need to display a small lock like in Safari, as soon as the connection is secure. A click on that lock should open a SFCertificatePanel that displays the certificate used for that request. Can that be done in WebView for OS X? I checked all delegates but didn't find a usable message sent to them to display that lock-icon or to get the certificate. Thanks for your help! A: This sounds like a pretty dubious idea to me. I suspect it would not be secure in practice, given likely user behavior and user understanding (e.g., the mental models that users have about security). Here's the core problem. There is no place in your app window to display a lock that users can trust, and that users will understand and know is unspoofable, and that users know to focus their attention on. It would be too easy for a malicious website to include an image of a lock icon on their page, and this might fool users into thinking that HTTPS has been used when it actually hasn't. The malicious website could even make the icon clickable, and if the user clicks on it, have spoofed certificate information pop up. Most users would have no hope of detecting such an attack. Instead, if you know that a particular site needs to use HTTPS, I suggest that you load the original URL using a https:// URL. Since you specified the URL to be loaded in the WebView, you know that it will be using SSL. As far as I know, that's realistically about the best you can do from within your app. At least, I can't think of anything better, given the problem description specified here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Sharing projects with VS and TFS I'm running into a lot of problems sharing projects between solutions with VS 2010 and TFS 2010. First issue is that everyone sets up their machine different, and create workspaces differently. Some use a single workspace for all projects. Some use a different workspace for each project. When you put two different projects into a solution from different parts of the tree, they don't necessarily map to the TFS tree structure (and generally don't). So one person might have: C:\Users\User\Documents\Projects\Project1 C:\Users\User\Documents\Projects\Project2 Another might have C:\Users\User\Documents\Projects\Project1 C:\Users\User\Documents\SharedProjects\Project2 Another even does C:\SharedProjects\Project2 C:\Projects\Project1 The problem is that the solution holds physical project locations, and everytime users get latest, they fight and create conflicts about project location. I know, the easy solution is to mandate a single structure, but that's not going to work here. Second problem: We have some shared libraries that are the projects are included in different solutions across our tree. Some of these projects have different build configurations. One might have Dev, Test, Stage, Prod and another has Debug, Release, Prod. This causes problems because the build configurations are stored in the project files. If a project tries to use a shared project, and the shared project does not contain a build configuration to match the solution, then VS locks up and causes all kinds of weird behavior. Does anyone have any solutions to these problems? Is there any way to create local overrides for locations that do not affect all users? (Similar to the way you can set web server configurations on a per user basis) Seems like these problems should have been figured out by now. A: Recommendation 1 - seperate usage of solution files from your actual build system... Read the "Building Large Source Trees" section of this MSBuild Best Practices document below http://msdn.microsoft.com/en-us/magazine/dd483291.aspx Recommendation 2 - Do exactly what you said you couldn't do... Enforce some semblance of uniformity. Provide a TFS workspace template and/or state the 'build-approved' configurations. At some point people have to buy into this stuff or it's just not going to work. A: I had the same issue. It was taking so long to build the projects. I created master solution that hosts all web app and class library just for build and build time is really improved using that. You can refer this post it might helps you. TFS Build strategies for large projects
{ "language": "en", "url": "https://stackoverflow.com/questions/7590290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Some of my NSStrings are alphanumeric. How do I tell which ones contain numbers and which ones don't? NSString *test = @"example"; NSString *test2 = @"ex12am243ple"; Is there any easy way to determine which string contains a number in it (0-9) and which one doesn't? Thanks. A: if([testString rangeOfCharacterFromSet:characterSetOfNumbers].location == NSNotFound) { //there are no numbers in this string } else { //there is at least 1 number in this string } p.s. you can look at the docs of NSCharacterSet for the available ones, but the one you probably want is decimalDigitCharacterSet so you would use [NSCharacterSet decimalDigitCharacterSet] in place of "characterSetOfNumbers" in the above code. A: if ([test isMatchedByRegEx:@"\d+"]) { // string contains numbers } EDIT: also worth noting that you need to import regex.h A: Just to add to Jesse's code, it is definitely easier to put it into a category. @interface NSString (Numeric) - (BOOL) isNumeric; @end @implementation NSString (numeric) - (BOOL) isNumeric { NSCharacterSet *numbers = [NSCharacterSet decimalDigitCharacterSet]; return ([self rangeOfCharactersFromSet:numbers].location == NSNotFound ? YES : NO); } @end A: You could use a regular expression to test for numbers. Here is an example but you may need to change it for your needs. - (BOOL)stringContainsNumbers:(NSString *)string { NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:0 error:NULL]; NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])]; return numberOfMatches > 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7590292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I get the request body? I am trying to implement a simple JSON-RPC server. The client part is handled by the jquery.jsonrpc. This seems to work fine, sending a JSON-RPC message as the payload of a post message. My JSON-RPC 'server' currently just wants to echo the data so I can see the result in the FireBug http response. The code is this: <?php class jsonrpc { var $requestData; function jsonrpc() { if (isset($_SERVER["REQUEST_URI"]) && isset($_SERVER["REQUEST_METHOD"])) { if (isset($_SERVER["CONTENT_LENGTH"]) && $_SERVER["CONTENT_LENGTH"] > 0) { $this->requestData = ""; $httpContent = fopen("php://input", "r"); echo "httpcontent=".$httpContent; while ($data = fread($httpContent, 1024)) { $this->requestData .= $data; } fclose($httpContent); } } echo "jsonrpc::jsonrpc()\n"; } } ?> And the Response tab shows: POST http://api.localhost/index.php?tm=1317246797964 200 OK 6ms <br /> <b>Warning</b>: fopen("php://input", "r") - No error in <b>C:\Develop\ZeroSumGames\api\htdocs\rpc.php</b> on line <b>9</b><br /> httpcontent=<br /> <b>Warning</b>: fread(): supplied argument is not a valid File-Handle resource in <b>C:\Develop\ZeroSumGames\api\htdocs\rpc.php</b> on line <b>11</b><br /> <br /> <b>Warning</b>: fclose(): supplied argument is not a valid File-Handle resource in <b>C:\Develop\ZeroSumGames\api\htdocs\rpc.php</b> on line <b>14</b><br /> jsonrpc::jsonrpc() Object { error="Internal server error", version="2.0"} I can see there is data there because on the FireBug request headers tab I can see this: Host api.localhost User-Agent Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 Accept application/json, text/javascript, */* Accept-Language en-gb,en;q=0.5 Accept-Encoding gzip,deflate Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive 115 Connection keep-alive Content-Type application/json; charset=UTF-8 X-Requested-With XMLHttpRequest Referer http://api.localhost/index.html Content-Length 72 And also I can see this on the post tab: {"jsonrpc":"2.0","method":"example.method.name","id":1,"params":[1,2,3]} My server is too old for file_get_contents (4.2.2) but the replacement functions I have found on the net internally do the same as what I have written above (more or less) and also have the issue regarding opening of php://input. So my question is why can't I open php://input for reading? A: I upgraded my local machine to 4.4.2 and that works fine so I guess it is a bug in 4.2.2. Not quite the fix I was hoping for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UDP NAT hole punching example I try search in google and here but i still cant find simple C\C++ example udp hole punching algorithm. Please help if you know where i can find it. Thanks! A: You can browse this open source code for it: http://www.codeproject.com/KB/IP/stunner.aspx You should googled 'STUN'
{ "language": "en", "url": "https://stackoverflow.com/questions/7590298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why are bitmap index operations high CPU bound? Why are bitmap index operations have a tradeoff being high CPU bound?
{ "language": "en", "url": "https://stackoverflow.com/questions/7590300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can GitSharp return a Leaf (blob) object directly given the leaf's hash? I noticed that I can get the contents of a particular Leaf (blob) object from a specific branch by iterating over a Tree's children like so: _repository = new Repository(git_url); IEnumerable<AbstractObject> currentBranchItems = _repository.CurrentBranch.CurrentCommit.Tree.Children; foreach (var currentBranchItem in currentBranchItems) { var currentBranchLeaf = currentBranchItem as Leaf; _lastLeafHash = currentBranchLeaf.Hash; Console.WriteLine("Name: " + currentBranchLeaf.Name + " Hash: " + currentBranchLeaf.Hash); } However, this seems pretty inefficient if I have the hash of the leaf that I would like to retrieve. Is there a way that I can access a Leaf directly from the repository if I have the hash? The following does not work: private static void GetLeafByHash(string hash) { var leafAbs = _repository.Get<AbstractObject>(hash); var leaf = leafAbs as Leaf; Console.WriteLine("Found Leaf Named: " + leaf.Name); Console.WriteLine("The data is this big: " + leaf.RawData.Length); Console.Read(); } The Get method always returns NULL. So is there a way to accomplish the direct retrieval of a Leaf by hash? The documentation states the following about the Get method: Access a git object by name, id or path. Use the type parameter to tell what kind of object you like to get. Supported types are Branches, Commits or Tags may be accessed by name or reference expression. Currently supported are combinations of these: Not supported is Tree or Leaf (Blob) objects can be addressed by long hash or by their relative repository path It's not clear.. does this mean that Tree or Leaf objects can or cannot be accessed via a hash? Thanks a lot! A: You can get any object in the repo as Blob like this var blob=repo.Get<Blob>(sha_hash); If you know the type of the object (tree, tag or commit) you can also substitute the type parameters Tree, Tag and Commit for T in Get(). Sidenote: In GitSharp a Leaf is a Blob that knows it's path in the tree of the current revision. However since a file can be in many places on different branches and revisions you can not get a Leaf via Repository.Get().
{ "language": "en", "url": "https://stackoverflow.com/questions/7590304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Accessing one character in a string I am using something like SPIMS or MARS with syscall functions. I am reading in a string (and it works because I can print it out) as follows: li $v0, 8 la $a0, string li $a1, 256 syscall However, I am having a problem accessing a single character of the string. So if I want to access the first character and print it, I am trying this: la $t0, string lb $a0, ($t0) li $v0, 4 sys call If I try something like this: la $a0, string li $v0, 4 syscall This prints out the whole string as string points to the whole string. If I try something like: la $a0, string lb $a0, ($t0) li $v0, 4 syscall It gives me an out of bound error. I don't understand why though - isn't a character a byte long and this just loads the first byte from the string into $a0? Thank you A: Looking at the documentation for the MARS syscall functions you can see that service 4, which you're using, expects $a0 to be "[the] address of null-terminated string to print", which explains the behavior you're seeing. What you want is function 11 "print character", which prints the low-order byte as a character. In other words the following should work (not tested): la $t0, string lb $a0, ($t0) li $v0, 11 syscall
{ "language": "en", "url": "https://stackoverflow.com/questions/7590310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Regular expression to detect line that starts with an asterisk The code below fails to detect a single instance of the occurance. =O Whats wrong? =\ How do I detect the following lines (which begin with a newline) that begin with an asterisk ? I'm at a loss. This isn't behaving as I expected. $text ="Nothing here to detect...though it is the first line. * '' [[test]] * Another line that starts with an asterisk ** yet another...though it has two...but who cares about the 2nd one?"; $t = preg_match_all('#^\*.*#', $text, $match); echo "found=".$t."\n"; print_r($match); A: add the m modifier to specify that this has a multi line subject like #^\*.*#m http://php.net/manual/en/reference.pcre.pattern.modifiers.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7590315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Trying to populate POST data in a lightbox I have a form on my master page and I am submitting the data using POST to another page . <form id="Form2" action="index.aspx" method="post" name="Form2"> <asp:ContentPlaceHolder ID="form_right_top" runat="server"> </asp:ContentPlaceHolder> <div id="page_form"> <!-- sample error here --> <div style="color: red; font-size: 11px; margin-left: 110px; clear: both; padding-top: 6px;"> </div> <!-- end sample error --> <div style="float: left; position: relative; width: 110px; height: 30px;"> First Name*</div> <div style="float: left; position: relative; width: 148px; height: 30px;"> <input type="text" tabindex="100" id="FIRST_NAME" maxlength="14" name="FIRST_NAME"> </div> <div style="color: red; font-size: 11px; margin-left: 110px; clear: both; padding-top: 6px;"> </div> <div style="float: left; position: relative; width: 110px; height: 30px;"> Last Name*</div> <div style="float: left; position: relative; width: 148px; height: 30px;"> <input type="text" tabindex="101" id="LAST_NAME" maxlength="14" name="LAST_NAME"> </div> <div style="color: red; font-size: 11px; margin-left: 110px; clear: both; padding-top: 6px;"> </div> <div style="float: left; position: relative; width: 110px; height: 30px;"> Billing Address*</div> <div style="float: left; position: relative; width: 148px; height: 30px;"> <input type="text" tabindex="102" id="ADDRESS" maxlength="30" name="ADDRESS"></div> <div style="color: red; font-size: 11px; margin-left: 110px; clear: both; padding-top: 6px;"> </div> <div style="float: left; position: relative; width: 110px; height: 30px;"> City*</div> <div style="float: left; position: relative; width: 148px; height: 30px;"> <input type="text" tabindex="104" id="CITY" maxlength="18" name="CITY"></div> <div style="color: red; font-size: 11px; margin-left: 110px; clear: both; padding-top: 6px;"> </div> <div style="float: left; position: relative; width: 110px; height: 30px;"> State* </div> <div style="float: left; position: relative; width: 148px; height: 30px;"> <select style="width: 145px;" size="1" tabindex="105" id='STATE' name='STATE' > <option value="AK">AK</option> <option value="AL">AL</option> <option value="AR">AR</option> <option value="AZ">AZ</option> <option value="CA">CA</option> <option value="CO">CO</option> <option value="CT">CT</option> <option value="DE">DE</option> <option value="DC">DC</option> <option value="FL">FL</option> <option value="GA">GA</option> <option value="HI">HI</option> <option value="IA">IA</option> <option value="ID">ID</option> <option value="IL">IL</option> <option value="IN">IN</option> <option value="KS">KS</option> <option value="KY">KY</option> <option value="LA">LA</option> <option value="MA">MA</option> <option value="MD">MD</option> <option value="ME">ME</option> <option value="MI">MI</option> <option value="MN">MN</option> <option value="MO">MO</option> <option value="MS">MS</option> <option value="MT">MT</option> <option value="NC">NC</option> <option value="ND">ND</option> <option value="NE">NE</option> <option value="NH">NH</option> <option value="NJ">NJ</option> <option value="NM">NM</option> <option value="NV">NV</option> <option value="NY">NY</option> <option value="OH">OH</option> <option value="OK">OK</option> <option value="OR">OR</option> <option value="PA">PA</option> <option value="RI">RI</option> <option value="SC">SC</option> <option value="SD">SD</option> <option value="TN">TN</option> <option value="TX">TX</option> <option value="UT">UT</option> <option value="VA">VA</option> <option value="VT">VT</option> <option value="WA">WA</option> <option value="WI">WI</option> <option value="WV">WV</option> <option value="WY">WY</option> </select> </div> <div style="color: red; font-size: 11px; margin-left: 110px; clear: both; padding-top: 6px;"> </div> <div style="float: left; position: relative; width: 110px; height: 30px;"> Zip Code*</div> <div style="float: left; position: relative; width: 148px; height: 30px;"> <input type="text" tabindex="106" id="POSTAL_CODE" name="POSTAL_CODE"></div> <div style="color: red; font-size: 11px; margin-left: 110px; clear: both; padding-top: 6px;"> </div> <div style="float: left; position: relative; width: 110px; height: 30px;"> Phone*</div> <div style="float: left; position: relative; width: 148px; height: 30px;"> <input type="text" tabindex="107" id="Form1_TextBoxPhone" maxlength="15" name="Form1$TextBoxPhone"></div> <div style="color: red; font-size: 11px; margin-left: 110px; clear: both; padding-top: 6px;"> </div> <div style="float: left; position: relative; width: 110px; height: 30px;"> E-mail Address*</div> <div style="float: left; position: relative; width: 148px; height: 30px;"> <input type="text" tabindex="110" id="EMAIL" name="EMAIL_ADDRESS"></div> <div style="clear: both;"> </div> <div style="clear: both"> </div> <div style="position: relative; width: 270px; height: 53px; text-align: center;"> <input type="image" style="border-width: 0px;" src="images/form_ordernow_btn.jpg" tabindex="129" id="Form1_ImageButton1" name="Form1$ImageButton1" > </div> <asp:ContentPlaceHolder ID="Return_shipping" runat="server"> </asp:ContentPlaceHolder> </div> When I just submit it by using an ordinary submit button a shown in the code ,the data gets passed on the redirected page and I am able to view it on the screen by using the below code in the index.aspx page <table> <tr> <td><% Response.Write(Page.Request.Form["FIRST_NAME"]); %></td> <td><% Response.Write(Page.Request.Form["LAST_NAME"]); %></td> </tr> </table> However the requirement is that I display this page in a lightbox which pops open when I hit the submit on the form .However if I change the code for the submit to the form to this : <a href="index.aspx?iframe=true&width=100%&height=100%" rel="prettyPhoto[iframes]" title="New form page"> <input type="image" style="border-width: 0px;" src="images/form_ordernow_btn.jpg" tabindex="129" id="Form1_ImageButton1" name="Form1$ImageButton1" ></a> None of the Post values are getting passed through .I am not sure,but I guess the lighbox is overriding the Post back and hence I am just getting an empty page which pops up when I click the button ,but the question is how do I pass these POST values while using a lightbox Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7590316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Asynchronous HTTPrequest from PHP Possible Duplicate: Asynchronous HTTP requests in PHP I want to be able to do a POST or GET request from scriptA.php to scriptB.php. But I don't want scriptA.php to have to wait until scriptB.php is done doing its job. I want to be able to send the request, and don't expect for the result.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SVN:Externals equivalent for Git Possible Duplicate: SVN external in GIT Is there an equivalent way to include other repository locations in a Git Branch, like how SVN:Externals works? A: Git submodules and to an extent Git subtree merge.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Java array problem. Cant pass values Wen I have this code: import java.util.Scanner; import java.util.Arrays; public class Ex02 { /** * @param args the command line arguments */ public static void main(String[] args) { int [] matrixSize = new int [4]; System.out.println("Insert the values matrix (matrixA_lines,MatrixA_Rows,matrixB_lines,MatrixB_Rows"); matrixSize = matrixFill(4); System.out.println(Arrays.toString(matrixSize)); } public static int[] matrixFill(int sizeOne){ int i; Scanner sc = new Scanner(System.in); int [] matrixTemp = new int [sizeOne]; for (i = 0; i<sizeOne; i++){ matrixTemp[i] = sc.nextInt(); } return matrixTemp; } } It all works as expected. An unidimensional array is created, filled with 1,2,3,4 and them the array is print. The problem is that i want to use an bidimentsional array. I've modified the code and it gives error. Here is the modified code: import java.util.Scanner; import java.util.Arrays; public class Ex02 { /** * @param args the command line arguments */ public static void main(String[] args) { int [][] matrixSize = new int [1][4]; System.out.println("Insert the values matrix (matrixA_lines,MatrixA_Rows,matrixB_lines,MatrixB_Rows"); matrixSize[][] = matrixFill(1,4); System.out.println(Arrays.deepToString(matrixSize)); } public static int[][] matrixFill(int sizeOne, int sizeTwo){ int i; Scanner sc = new Scanner(System.in); int [][] matrixTemp = new int [sizeOne][sizeTwo]; for (i = 0; i<sizeOne; i++){ matrixTemp[0][i] = sc.nextInt(); } return matrixTemp[sizeOne][sizeTwo]; } } On line 21 (matrixSize[][] = matrixFill(1,4);) the error is: cannot find symbol symbol: class matrixSize location: class Ex02.Ex02 not a statement ';' expected And on line 34(return matrixTemp[sizeOne][sizeTwo];) the error is: incompatible types required: int[][] found: int Can someone tell me what I'm doing wrong? Just started to learn Java. Regards, favolas A: Remove the [][] from matrixSize, and from your return value. matrixSize = matrixFill(1,4); And return matrixTemp; A: matrixSize[][] = matrixFill(1,4); That's not a valid place for the [][]. The first example had it right: matrixSize = matrixFill(1,4); A: You added "[sizeOne][sizeTwo]" to the return statement in the new code; you do not need this because matrixTemp has already been declared as a 2d array. The way you changed it, you are sending one element within the array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: rails 3.1 template specific layouts via template resolver? I've got a pretty straight forward template resolver returning templates from the database: class MyResolver < ActionView::PathResolver def query path, details, formats template = MyTemplate.find_by_path path ... ActionView::Template.new template.source, identifier, handler, details end end That part works great... What I can't figure out is how to tell rails to use a layout associated with the template that's been pulled from the database (i.e., template.layout_name or some such). class MyResolver < ActionView::PathResolver def query path, details, formats template = MyTemplate.find_by_path path layout template.layout_name # ??? yes? no? ActionView::Template.new template.source, identifier, handler, details end end Is there something I can call in the above query method to set the layout? Should I not be returning a ActionView::Template, but instead return my Template class with the appropriate AV::T methods included and then override some other part of the rendering stack and have that use template.layout_name? A: You'd have to do something like this: pages_controller.rb: class PagesController < ApplicationController prepend_view_path PageTemplate::Resolver.instance def render_page #Some logic to retrieve the @site & @current_page records.... render :layout => @site.layout.path, :template => @current_page.template.path end . . . models/page_template.rb: class Resolver < ActionView::Resolver require "singleton" include Singleton def find_templates(name, prefix, partial, details) if prefix.empty? #If this is not a layout, look it up in the views table and pass that record to the init function initialize_template('Template', record) end elsif prefix === 'layouts' #If this is a layout, look it up in the layouts table and pass that record to the init function initialize_template('Layout', record) end end end # Initialize an ActionView::Template object based on the record found. def initialize_template(type, record) source = record.body identifier = "#{type} - #{record.id} - #{record.path.inspect}" handler = ActionView::Template.registered_template_handler(record.handler) details = { :format => Mime[record.format], :updated_at => record.updated_at, :virtual_path => virtual_path(record.path, record.partial) } ActionView::Template.new(source, identifier, handler, details) end # Make paths as "users/user" become "users/_user" for partials. def virtual_path(path, partial) return path unless partial if index = path.rindex("/") path.insert(index + 1, "_") else "_#{path}" end end end Of course this can be refactored quite a bit, but this is the general idea. Also you would need 1 or 2 database tables depending weather you prefer to store the templates and layouts separately or together with the following columns: title, body, path, format, locale, handler, partial Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7590341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Best Practice for reserved words? renaming vars in rails Often I've found my model/var names highlighted in textmate as a reserved word (i.e service, attr, etc.) I'm afraid this might cause troubles and I usually change the name to something else (service -> srvice, attr -> atr) I googled a bit on the subject but the search terms are a bit tricky so I didn't find much Is there a best practice on how to rename a variable that is a reserved word? such as prefixing an underscore or whatever (_service, _attr) A: get more creative or descriptive with the name... for example, I was converting a database to rails that had a column named type which is reserved for rails magic, so I renamed it to facility_type. It's longer, but the name further documents what it contains. Using an underscore at the front or omitting letters makes it less readable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Updating HTML File No Domain Name I have an HTML file that I gave to a couple of friends. I want to update the file, and want them to see the update, but I don't want to give them each the file again, and again (every time I make an update). Besides making it public with a domain name, what else can I do? A: How about making it private "with a domain name" (meaning hosting it on a web-site)? Just post it on the site and put a password on the directory, and tell your friends the password. I'm assuming your issue is with the public aspect, not hosting it on a web site per se. If you don't want the trouble of setting up a website, just setup a gMail account and upload it to Google Documents and share it there with only the people you want to see it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to simulate keyboard input to a console application? I have developed an application in bash that uses "whiptail" to display dialogs in a terminal. (I personnally don't like this kind of UI but i'm only a developer, i don't make decisions ...). Anyway, now i have to test it, and i would like to simulate a user that types values, press "Enter", "Echap", "Tab", "down arrow", "up arrow" I didn't get expect working and it seems it is not possible (http://oldsite.debianhelp.org/node/11812). Edit: There is no X on the machine, so xdotool is not suitable. I'm looking for a solution that doesn't need to install anything (because we are not allowed to add programs to the system to test it). Long story made short, i'm looking for a solution like "writing bytes to the process's stdin" or "writing on the keyboard device in /dev", something like that. Thanks A: You should be able to pass in an input file like $ yourscript.sh < inputfile A: Your Bash application requires a pseudo terminal in order to run properly. It needs a screen size and a cursor position, but if you run it with piped input (< or |), no pseudo terminal gets created. Pseudo terminals get created in Unix by everyday applications like ssh, xterm, and screen. (Expect will create a pseudo terminal for your application and allow you to run automated tests. It supports test generation with autoexpect, and there is a paper on using Expect for terminal screen-scraping.) If you can't use Expect, you can try using screen for automated terminal I/O: # Create a detached screen screen -S screenname -d -m -s ./my_app # Send input to it screen -S screenname -p windownum -X eval \ "register . \"arbitrary\ntext, newlines and control chars\n\"" paste # Wait for the application to process the input sleep 0.1s # Dump the screen to a file screen -S screenname -p windownum -X hardcopy ./screen_dump # Check the dump grep 'Login successful' ./screen_dump || exit 1 # Rinse and repeat # Close the screen screen -S screenname -X quit
{ "language": "en", "url": "https://stackoverflow.com/questions/7590355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Possible Javascript selector (no framework) to get array of elements using array key naming syntax I have a form where the inputs have names such as: unit_price[1] unit_price[2] The only way I've found to access them from javascript is using: document.getElementsByName("unit_price[1]")[0] I was wondering if there is a way to access them as a single array in one selector. I'm looking for a pure javascript way to do this, but the page does have the YUI 2 framework loaded, in case there is a one step way of doing it using yui syntax. A: From the YUI2 docs: var nodes = YAHOO.util.Selector.query('input[name^=unit_price]'); A: Here's a native solution using querySelectorAll()[docs] : document.querySelectorAll("[name^=unit_price]"); Has pretty good browser support. http://www.quirksmode.org/dom/w3c_core.html Good idea to prefix the selector with input like @davin did in his answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there any difference between f:ajax and a4j:ajax? Is there any significant difference between f:ajax and a4j:ajax tags? I know about a4j:ajax from Richfaces 4 is based on native f:ajax JSF2 tag adding some attributes not found in f:ajax like onbegin, onbeforedoupdate, bypassUpdates, limitRender, status and focus but which one to use when I only need to send a simple ajax request or partial rendering ? Is there performance issues between f:ajax and a4j:ajax? A: Here is more information on the differences between f:ajax and a4j:ajax: http://mkblog.exadel.com/2010/08/what-richfaces-a4jajax-adds-on-top-jsf-2-fajax-tag/ A: The <a4j:ajax> tag is just the more convenient form of the basic <f:ajax> tag. You can find a nice overview of all differences in this page. The execute attribute supports an extra @region value pointing to the <a4j:region>. Any EL in execute and render attributes is resolved in current request instead of in initial request. The JS function of the onevent attribute of both tags will be invoked 3 times (the passed-in data.status has then the values begin, complete, success). This forces you to use a switch or if when you're only interested in one of them or want to treat them differently. The <a4j:ajax> makes this more convenient with onbegin, onbeforedomupdate and oncomplete attributes respectively. See also this related question: JSF 2: How show different ajax status in same input? If you're not interested in any of those enhancements, then using <f:ajax> should be perfectly fine as well. The performance difference is (and must be) totally negligible and not be the reason to choose one over the other.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Getting setuptools/easy_install to play nicely with PYTHONPATH Why do setuptools/easy_install .pth files not place nicely with PYTHONPATH, and how do I get them to play nicely, and keep the directories in my PYTHONPATH before those .pth shoves in the sys.path? My current problem is I've created a package for our project, with the both PyYAML and PyCrypto as requirements. install_requires=["PyYAML", "pycrypto >= 2.3"] As we've been developing, we've installed PyYaml in the standard directory (/usr/lib64/python2.6/site-packages) with pip. We installed an older version of PyCrypto in there, then discovered we needed the newer one, which we installed under /opt/devtools/lib64/python2.6/site-packages. We've had already been setting our PYTHONPATH to read from /opt first, before /usr/lib64. And that all worked fine in development. When we ran, we got PyCrypto 2.3 from /opt, and PyYaml from /usr/lib64/.... But now, when I'm trying installing in a virtualenv, and when I run python setup.py develop, setuptools/distribute ends up adding /usr/lib64/python2.6/site-packages to the easy-install.pth, but not /opt/devtools/lib64/python2.6/site-packages. It's finding the right versions, as seen in the output: Using /home/s3447/projects/wsrs.git/emp_parsing Searching for pycrypto==2.3 Best match: pycrypto 2.3 Adding pycrypto 2.3 to easy-install.pth file Using /opt/wsrs-devtools/stow/pycrypto-2.3/lib64/python2.6/site-packages Searching for PyYAML==3.10 Best match: PyYAML 3.10 Adding PyYAML 3.10 to easy-install.pth file But not adding /opt/... to the easy-install.pth. (Only /usr/lib64... and the directory I ran setup.py in is added to the path.) The end result is, although I setuptools thinks it was successfully, when I run my code, easy-install.pth decides it knows what I want better than I do, inserts itself before my PYTHONPATH, and I end up importing the wrong version of PyCrypto. Two questions: * *Why is setuptools inconsistent about which directories it adds to the .pth file? I would expect either both directories or neither directory to be installed. *Is there any way to get setuptools to not try to override my PYTHONPATH? Why was that even considered a good idea in the first place? A: From what I understand of your question, this may be where to take your concerns about that: https://github.com/pypa/setuptools/issues/397 Sounds like others have had a similar problem. I could be wrong, I just use pip. I never use easy_install if I can help it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: populate dropdownlist Hi i need to populate a dropdownlist. I designed a datasource and assigned it to dropdownlist. The dropdown populated correctly. But the problem is that i need to add a default value say "default" at the starting of the dropdownlist( and this value default is not in the database. I did this : <asp:DropDownList ID="classInstructor" runat="server" DataSourceID="SqlDataSource3" DataTextField="InstrName" DataValueField="InstrName"> <asp:ListItem Value="Default" Text="Default" Selected="True"></asp:ListItem> </asp:DropDownList> But default doesn't show up on dropdown. Probably, the way i did was wrong. Can u let me know the best way to handle this. A: Set the AppendDataBoundItems property to true on the dropdown list and the items from the data source will appear after any ListItems you add in the markup e.g. <asp:DropDownList ID="classInstructor" runat="server" DataSourceID="SqlDataSource3" DataTextField="InstrName" DataValueField="InstrName" AppendDataBoundItems="true"> <asp:ListItem Value="Default" Text="Default" Selected="True"/> </asp:DropDownList> A: you cannot use this approach if the DropDownList is bound to a datasource at runtime this Default item you have in the markup at design time will be washed away in the binding. what you need to do is an Insert after the call to the DataBind() method. see here for the examples and more comments on this: Asp.net - Add blank item at top of dropdownlist
{ "language": "en", "url": "https://stackoverflow.com/questions/7590365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Keymap/lmap and recursive mapping in vim I'm using a keymap to type non-latin characters in vim. Like that: set keymap=russian-jcukenwin. E.g. that maps q to й and @ to ". The problem is that I can neither redefine/remove such mapping with lmap/lunmap nor define a recursive mapping, e.g. to map " to something else (and that breaks all mappings in vim-latexsuite and makes me sad). The only idea I've got now is not to use keymap - and lmap all the keys manually. So, is there any better workaround?
{ "language": "en", "url": "https://stackoverflow.com/questions/7590366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }