qid
int64
1
3.11M
question
stringlengths
10
32.1k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
33.7k
response_k
stringlengths
3
34.7k
2,630,186
I am trying to work with an HTML.DropDownList in MVC and am not getting the expected return values. Here is my implementation for the selectList to bind to the drop down - ``` IEnumerable<status> stat = _provider.GetAllStatuses(); Statuses = new SelectList(stat.ToList(), "id", "name", i.status.id); ``` And here is my view - ``` <%= Html.DropDownList("Status",Model.Statuses) %> ``` I am getting an error when trying to run updatemodel in my controller. I then tried to individually set each object. It turns out that I am not getting a single int from the formvalue as I would expect to. Instead, I am getting a value like "5,10,2,3". I think this is coming from how I set up my selectlist, but I'm not exactly sure. Can anyone see an error in the way I am setting up this dd? Thanks for any help, and let me know if I can clarify anything.
2010/04/13
[ "https://Stackoverflow.com/questions/2630186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/306894/" ]
you don't give much to go in in your question: > > I am trying to add an additional > column and value to an existing insert > query - both integers, and running > into trouble. > > > Anything to look out for? > > > it is best practice to list all columns you intend to include values for in the list of columns, so make sure you add them there, as well as the VALUES list: ``` insert into YourTable (col1, col2,..., newCol1, newCol2) VALUES (1,2,...,new1, new2) ``` make sure the you get the column names spelled correct and that the table actually has those new columns in it.
make sure the column name sequence is the same as your insert data sequence. Example INSERT INTO TABLENAME (ColumnName1,ColumnName2) VALUES (1,'data') Becomes INSERT INTO TABLENAME (ColumnName1,ColumnName2,**ColumnNameNEW**) VALUES (1,'data','**newcolumndata**') Notice both the new column name and the new data are in the third position in the sequence.
1,689,138
I'm working on a project with 2 other developers and I need to host it online. I need a site to host it for me with features such as version control, and others neat features. can you suggest any ? the project is not an open source one. thanks.
2009/11/06
[ "https://Stackoverflow.com/questions/1689138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91607/" ]
I believe [XP-Dev](http://www.xp-dev.com), would work well for you, they offer a free plan that has two private projcets. [Pricing is here.](http://www.xp-dev.com/pricing)
BitBucket, with Mercurial-based source control, has private repositories: <http://bitbucket.org/plans/>
1,689,138
I'm working on a project with 2 other developers and I need to host it online. I need a site to host it for me with features such as version control, and others neat features. can you suggest any ? the project is not an open source one. thanks.
2009/11/06
[ "https://Stackoverflow.com/questions/1689138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91607/" ]
I believe [XP-Dev](http://www.xp-dev.com), would work well for you, they offer a free plan that has two private projcets. [Pricing is here.](http://www.xp-dev.com/pricing)
I'm using [unfuddle](http://unfuddle.com/) and highly recommend it. It's free for 200MB/2 users. Subversion and Git are supported and the interface is nice and clean.
1,689,138
I'm working on a project with 2 other developers and I need to host it online. I need a site to host it for me with features such as version control, and others neat features. can you suggest any ? the project is not an open source one. thanks.
2009/11/06
[ "https://Stackoverflow.com/questions/1689138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91607/" ]
I believe [XP-Dev](http://www.xp-dev.com), would work well for you, they offer a free plan that has two private projcets. [Pricing is here.](http://www.xp-dev.com/pricing)
A lot of webhosts include these features as part of the normal monthly hosting plans. For example I use dreamhost.com and get subversion and trac included.
1,689,138
I'm working on a project with 2 other developers and I need to host it online. I need a site to host it for me with features such as version control, and others neat features. can you suggest any ? the project is not an open source one. thanks.
2009/11/06
[ "https://Stackoverflow.com/questions/1689138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91607/" ]
I use projectlocker.com They have a free version. One of the nice features is the monthly report that shows you what everyone on your team did.
BitBucket, with Mercurial-based source control, has private repositories: <http://bitbucket.org/plans/>
1,689,138
I'm working on a project with 2 other developers and I need to host it online. I need a site to host it for me with features such as version control, and others neat features. can you suggest any ? the project is not an open source one. thanks.
2009/11/06
[ "https://Stackoverflow.com/questions/1689138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91607/" ]
I use projectlocker.com They have a free version. One of the nice features is the monthly report that shows you what everyone on your team did.
I'm using [unfuddle](http://unfuddle.com/) and highly recommend it. It's free for 200MB/2 users. Subversion and Git are supported and the interface is nice and clean.
1,689,138
I'm working on a project with 2 other developers and I need to host it online. I need a site to host it for me with features such as version control, and others neat features. can you suggest any ? the project is not an open source one. thanks.
2009/11/06
[ "https://Stackoverflow.com/questions/1689138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91607/" ]
I use projectlocker.com They have a free version. One of the nice features is the monthly report that shows you what everyone on your team did.
A lot of webhosts include these features as part of the normal monthly hosting plans. For example I use dreamhost.com and get subversion and trac included.
329,838
I have, for my game, a Packet class, which represents network packet and consists basically of an array of data, and some pure virtual functions I would then like to have classes deriving from Packet, for example: StatePacket, PauseRequestPacket, etc. Each one of these sub-classes would implement the virtual functions, Handle(), which would be called by the networking engine when one of these packets is received so that it can do it's job, several get/set functions which would read and set fields in the array of data. So I have two problems: 1. The (abstract) Packet class would need to be copyable and assignable, but without slicing, keeping all the fields of the derived class. It may even be possible that the derived class will have no extra fields, only function, which would work with the array on the base class. How can I achieve that? 2. When serializing, I would give each sub-class an unique numeric ID, and then write it to the stream before the sub-class' own serialization. But for unserialization, how would I map the read ID to the appropriate sub-class to instanciate it? If anyone want's any clarifications, just ask. -- Thank you --- **Edit:** I'm not quite happy with it, but that's what I managed: Packet.h: <http://pastebin.com/f512e52f1> Packet.cpp: <http://pastebin.com/f5d535d19> PacketFactory.h: <http://pastebin.com/f29b7d637> PacketFactory.cpp: <http://pastebin.com/f689edd9b> PacketAcknowledge.h: <http://pastebin.com/f50f13d6f> PacketAcknowledge.cpp: <http://pastebin.com/f62d34eef> If someone has the time to look at it and suggest any improvements, I'd be thankful. --- Yes, I'm aware of the factory pattern, but how would I code it to construct each class? A giant switch statement? That would also duplicade the ID for each class (once in the factory and one in the serializator), which I'd like to avoid.
2008/12/01
[ "https://Stackoverflow.com/questions/329838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42029/" ]
For copying you need to write a clone function, since a constructor cannot be virtual: ``` virtual Packet * clone() const = 0; ``` Which each Packet implementation implement like this: ``` virtual Packet * clone() const { return new StatePacket(*this); } ``` for example for StatePacket. Packet classes should be immutable. Once a packet is received, its data can either be copied out, or thrown away. So a assignment operator is not required. Make the assignment operator private and don't define it, which will effectively forbid assigning packages. For de-serialization, you use the factory pattern: create a class which creates the right message type given the message id. For this, you can either use a switch statement over the known message IDs, or a map like this: ``` struct MessageFactory { std::map<Packet::IdType, Packet (*)()> map; MessageFactory() { map[StatePacket::Id] = &StatePacket::createInstance; // ... all other } Packet * createInstance(Packet::IdType id) { return map[id](); } } globalMessageFactory; ``` Indeed, you should add check like whether the id is really known and such stuff. That's only the rough idea.
You need to look up the Factory Pattern. The factory looks at the incomming data and created an object of the correct class for you.
329,838
I have, for my game, a Packet class, which represents network packet and consists basically of an array of data, and some pure virtual functions I would then like to have classes deriving from Packet, for example: StatePacket, PauseRequestPacket, etc. Each one of these sub-classes would implement the virtual functions, Handle(), which would be called by the networking engine when one of these packets is received so that it can do it's job, several get/set functions which would read and set fields in the array of data. So I have two problems: 1. The (abstract) Packet class would need to be copyable and assignable, but without slicing, keeping all the fields of the derived class. It may even be possible that the derived class will have no extra fields, only function, which would work with the array on the base class. How can I achieve that? 2. When serializing, I would give each sub-class an unique numeric ID, and then write it to the stream before the sub-class' own serialization. But for unserialization, how would I map the read ID to the appropriate sub-class to instanciate it? If anyone want's any clarifications, just ask. -- Thank you --- **Edit:** I'm not quite happy with it, but that's what I managed: Packet.h: <http://pastebin.com/f512e52f1> Packet.cpp: <http://pastebin.com/f5d535d19> PacketFactory.h: <http://pastebin.com/f29b7d637> PacketFactory.cpp: <http://pastebin.com/f689edd9b> PacketAcknowledge.h: <http://pastebin.com/f50f13d6f> PacketAcknowledge.cpp: <http://pastebin.com/f62d34eef> If someone has the time to look at it and suggest any improvements, I'd be thankful. --- Yes, I'm aware of the factory pattern, but how would I code it to construct each class? A giant switch statement? That would also duplicade the ID for each class (once in the factory and one in the serializator), which I'd like to avoid.
2008/12/01
[ "https://Stackoverflow.com/questions/329838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42029/" ]
For copying you need to write a clone function, since a constructor cannot be virtual: ``` virtual Packet * clone() const = 0; ``` Which each Packet implementation implement like this: ``` virtual Packet * clone() const { return new StatePacket(*this); } ``` for example for StatePacket. Packet classes should be immutable. Once a packet is received, its data can either be copied out, or thrown away. So a assignment operator is not required. Make the assignment operator private and don't define it, which will effectively forbid assigning packages. For de-serialization, you use the factory pattern: create a class which creates the right message type given the message id. For this, you can either use a switch statement over the known message IDs, or a map like this: ``` struct MessageFactory { std::map<Packet::IdType, Packet (*)()> map; MessageFactory() { map[StatePacket::Id] = &StatePacket::createInstance; // ... all other } Packet * createInstance(Packet::IdType id) { return map[id](); } } globalMessageFactory; ``` Indeed, you should add check like whether the id is really known and such stuff. That's only the rough idea.
To have a Factory class that does not know about all the types ahead of time you need to provide a singleton where each class registers itself. I always get the syntax for defining static members of a template class wrong, so do not just cut&paste this: ``` class Packet { ... }; typedef Packet* (*packet_creator)(); class Factory { public: bool add_type(int id, packet_creator) { map_[id] = packet_creator; return true; } }; template<typename T> class register_with_factory { public: static Packet * create() { return new T; } static bool registered; }; template<typename T> bool register_with_factory<T>::registered = Factory::add_type(T::id(), create); class MyPacket : private register_with_factory<MyPacket>, public Packet { //... your stuff here... static int id() { return /* some number that you decide */; } }; ```
329,838
I have, for my game, a Packet class, which represents network packet and consists basically of an array of data, and some pure virtual functions I would then like to have classes deriving from Packet, for example: StatePacket, PauseRequestPacket, etc. Each one of these sub-classes would implement the virtual functions, Handle(), which would be called by the networking engine when one of these packets is received so that it can do it's job, several get/set functions which would read and set fields in the array of data. So I have two problems: 1. The (abstract) Packet class would need to be copyable and assignable, but without slicing, keeping all the fields of the derived class. It may even be possible that the derived class will have no extra fields, only function, which would work with the array on the base class. How can I achieve that? 2. When serializing, I would give each sub-class an unique numeric ID, and then write it to the stream before the sub-class' own serialization. But for unserialization, how would I map the read ID to the appropriate sub-class to instanciate it? If anyone want's any clarifications, just ask. -- Thank you --- **Edit:** I'm not quite happy with it, but that's what I managed: Packet.h: <http://pastebin.com/f512e52f1> Packet.cpp: <http://pastebin.com/f5d535d19> PacketFactory.h: <http://pastebin.com/f29b7d637> PacketFactory.cpp: <http://pastebin.com/f689edd9b> PacketAcknowledge.h: <http://pastebin.com/f50f13d6f> PacketAcknowledge.cpp: <http://pastebin.com/f62d34eef> If someone has the time to look at it and suggest any improvements, I'd be thankful. --- Yes, I'm aware of the factory pattern, but how would I code it to construct each class? A giant switch statement? That would also duplicade the ID for each class (once in the factory and one in the serializator), which I'd like to avoid.
2008/12/01
[ "https://Stackoverflow.com/questions/329838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42029/" ]
For copying you need to write a clone function, since a constructor cannot be virtual: ``` virtual Packet * clone() const = 0; ``` Which each Packet implementation implement like this: ``` virtual Packet * clone() const { return new StatePacket(*this); } ``` for example for StatePacket. Packet classes should be immutable. Once a packet is received, its data can either be copied out, or thrown away. So a assignment operator is not required. Make the assignment operator private and don't define it, which will effectively forbid assigning packages. For de-serialization, you use the factory pattern: create a class which creates the right message type given the message id. For this, you can either use a switch statement over the known message IDs, or a map like this: ``` struct MessageFactory { std::map<Packet::IdType, Packet (*)()> map; MessageFactory() { map[StatePacket::Id] = &StatePacket::createInstance; // ... all other } Packet * createInstance(Packet::IdType id) { return map[id](); } } globalMessageFactory; ``` Indeed, you should add check like whether the id is really known and such stuff. That's only the rough idea.
Why do we, myself included, always make such simple problems so complicated? --- Perhaps I'm off base here. But I have to wonder: Is this really the best design for your needs? By and large, function-only inheritance can be better achieved through function/method pointers, or aggregation/delegation and the passing around of data objects, than through polymorphism. Polymorphism is a very powerful and useful tool. But it's only one of many tools available to us. --- It looks like each subclass of Packet will need its own Marshalling and Unmarshalling code. Perhaps inheriting Packet's Marshalling/Unmarshalling code? Perhaps extending it? All on top of handle() and whatever else is required. That's a lot of code. While substantially more kludgey, it might be shorter & faster to implement Packet's data as a struct/union attribute of the Packet class. Marshalling and Unmarshalling would then be centralized. Depending on your architecture, it could be as simple as write(&data). Assuming there are no big/little-endian issues between your client/server systems, and no padding issues. (E.g. sizeof(data) is the same on both systems.) Write(&data)/read(&data) **is a bug-prone technique**. But it's often a very fast way to write the first draft. Later on, when time permits, you can replace it with individual per-attribute type-based Marshalling/Unmarshalling code. *Also:* I've taken to storing data that's being sent/received as a struct. You can bitwise copy a struct with operator=(), which at times has been VERY helpful! Though perhaps not so much in this case. --- Ultimately, you are going to have a *switch* statement somewhere on that subclass-id type. The factory technique (which is quite powerful and useful in its own right) does this switch for you, looking up the necessary clone() or copy() method/object. **OR** you could do it yourself in Packet. You could just use something as simple as: ( getHandlerPointer( id ) ) ( this ) --- Another advantage to an approach this kludgey (function pointers), aside from the rapid development time, is that you don't need to constantly allocate and delete a new object for each packet. You can re-use a single packet object over and over again. Or a vector of packets if you wanted to queue them. (Mind you, I'd clear the Packet object before invoking read() again! Just to be safe...) Depending on your game's network traffic density, allocation/deallocation could get expensive. Then again, **premature optimization is the root of all evil.** And you could always just roll your own new/delete operators. (Yet more coding overhead...) --- What you lose (with function pointers) is the clean segregation of each packet type. Specifically the ability to add new packet types without altering pre-existing code/files. --- Example code: ``` class Packet { public: enum PACKET_TYPES { STATE_PACKET = 0, PAUSE_REQUEST_PACKET, MAXIMUM_PACKET_TYPES, FIRST_PACKET_TYPE = STATE_PACKET }; typedef bool ( * HandlerType ) ( const Packet & ); protected: /* Note: Initialize handlers to NULL when declared! */ static HandlerType handlers [ MAXIMUM_PACKET_TYPES ]; static HandlerType getHandler( int thePacketType ) { // My own assert macro... UASSERT( thePacketType, >=, FIRST_PACKET_TYPE ); UASSERT( thePacketType, <, MAXIMUM_PACKET_TYPES ); UASSERT( handlers [ thePacketType ], !=, HandlerType(NULL) ); return handlers [ thePacketType ]; } protected: struct Data { // Common data to all packets. int number; int type; union { struct { int foo; } statePacket; struct { int bar; } pauseRequestPacket; } u; } data; public: //... bool readFromSocket() { /*read(&data); */ } // Unmarshal bool writeToSocket() { /*write(&data);*/ } // Marshal bool handle() { return ( getHandler( data.type ) ) ( * this ); } }; /* class Packet */ ``` --- PS: You might dig around with google and grab down cdecl/c++decl. They are very useful programs. Especially when playing around with function pointers. E.g.: ``` c++decl> declare foo as function(int) returning pointer to function returning void void (*foo(int ))() c++decl> explain void (* getHandler( int ))( const int & ); declare getHandler as function (int) returning pointer to function (reference to const int) returning void ```
1,669,958
SQL Server 2008 Database Question. I have 2 tables, for arguments sake called Customers and Users where a single Customer can have 1 to n Users. The Customers table generates a CustomerId which is a seeded identity with a +1 increment on it. What I'm after in the Users table is a compound key comprising the CustomerId and a sequence number such that in all cases, the first user has a sequence of 1 and subsequent users are added at x+1. So the table looks like this... * CustomerId (PK, FK) * UserId (PK) * Name ...and if for example, Customer 485 had three customers the data would look like... ``` CustomerId | UserId | Name ---------- 485 | 1 | John 485 | 2 | Mark 485 | 3 | Luke ``` I appreciate that I can manually add the 1,2,3,...,n entry for UserId however I would like to get this to happen automatically on row insert in SQL, so that in the example shown I could effectively insert rows with the CustomerId and the Name with SQL Server protecting the Identity etc. Is there a way to do this through the database design itself - when I set UserId as an identity it runs 1 to infinity across all customers which isn't what I am looking for - have I got a setting wrong somewhere, or is this not an option? Hope that makes sense - thanks for your help
2009/11/03
[ "https://Stackoverflow.com/questions/1669958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/202055/" ]
I can think of no automatic way to do this without implementing a custom Stored Procedure that inserted the rows and checked to increment the Id appropriately, althouh others with more knowledge may have a better idea. However, this smells to me of *naturalising a surrogate* key - which is not always a good idea. More info here: <http://www.agiledata.org/essays/keys.html>
That's not really an option with a regular identity column, but you could set up an insert trigger to auto populate the user id though. The naive way to do this would be to have the trigger select the max user id from the users table for the customer id on the inserted record, then add one to that. However, you'll run into concurrency problems there if more than one person is creating a user record at the same time. A better solution would be to have a NextUserID column on the customers table. In your trigger you would: 1. Start a transaction. 2. Increment the NextUserID for the customer (locking the row). 3. Select the updated next user id. 4. use that for the new User record. 5. commit the transaction. This should ensure that simultaneous additions of users don't result in the same user id being used more than once. All that said, I would recommend that you just don't do it. It's more trouble than it's worth and just smells like a bad idea to begin with.
1,669,958
SQL Server 2008 Database Question. I have 2 tables, for arguments sake called Customers and Users where a single Customer can have 1 to n Users. The Customers table generates a CustomerId which is a seeded identity with a +1 increment on it. What I'm after in the Users table is a compound key comprising the CustomerId and a sequence number such that in all cases, the first user has a sequence of 1 and subsequent users are added at x+1. So the table looks like this... * CustomerId (PK, FK) * UserId (PK) * Name ...and if for example, Customer 485 had three customers the data would look like... ``` CustomerId | UserId | Name ---------- 485 | 1 | John 485 | 2 | Mark 485 | 3 | Luke ``` I appreciate that I can manually add the 1,2,3,...,n entry for UserId however I would like to get this to happen automatically on row insert in SQL, so that in the example shown I could effectively insert rows with the CustomerId and the Name with SQL Server protecting the Identity etc. Is there a way to do this through the database design itself - when I set UserId as an identity it runs 1 to infinity across all customers which isn't what I am looking for - have I got a setting wrong somewhere, or is this not an option? Hope that makes sense - thanks for your help
2009/11/03
[ "https://Stackoverflow.com/questions/1669958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/202055/" ]
I can think of no automatic way to do this without implementing a custom Stored Procedure that inserted the rows and checked to increment the Id appropriately, althouh others with more knowledge may have a better idea. However, this smells to me of *naturalising a surrogate* key - which is not always a good idea. More info here: <http://www.agiledata.org/essays/keys.html>
So you want a generated user\_id field that increments within the confines of a customer\_id. I can't think of one database where that concept exists. You could implement it with a trigger. But my question is: WHY? Surrogate keys are supposed to not have any kind of meaning. Why would you try to make a key that, simultaneously, is the surrogate and implies order? My suggestions: 1. Create a date\_created field, defaulting to getDate(). That will allow you to know the order (time based) in which each user\_id was created. 2. Create an ordinal field - which can be updated by a trigger, to support that order. Hope that helps.
3,060,765
I've been looking into view models for mvc and I'm looking for the best way to do them. I've read loads of different articles but none seem to be clear as the "best way." So far example I might have a Customer model with the following properties: * First Name * Last Name * Title * Location Where location is a foreign key to a location table in the database. I want to be able to edit this customer but only the first name, last name and location. I'm not bothered about the title in the edit. So in my view I will need to pass a customer and a selected list. Now from what I've read I have the following options (there's probably many more). So my question is basically which is the best one? 1) Add a select list to the `ViewData["Location"]` and just create a strongly typed view of customer? 2) Create a view model where I pass a customer and select list (the data access is done in the controller): ``` public class ViewModelTest { public Customer Customer { get; set; } public SelectList Locations { get; set; } public ViewModelTest(Customer customer, SelectList locations) { Customer = customer; Locations = locations; } } ``` 3) Create a view model where I pass a customer and list of locations and create the select list in the view model. ``` public class ViewModelTest { public Customer Customer { get; set; } public SelectList Locations { get; set; } public ViewModelTest(Customer customer, List<Location> locations, string selectedLocation) { Customer = customer; Locations = new SelectList(locations, "LocationID", "LocationName", selectedLocation); } } ``` 4) Pass a customer and repository and do the data access in the view model. ``` public class ViewModelTest { public Customer Customer { get; set; } public SelectList Locations { get; set; } public ViewModelTest(Customer customer, IRepository repository, string selectedLocation) { Customer = customer; Locations = new SelectList(repository.GetLocations(), "LocationID", "LocationName", selectedLocation); } } ``` 5) Create the view model with just the properties I need: ``` public class ViewModelTest { public string FirstName { get; set; } public string LastName { get; set; } public SelectList Locations { get; set; } public ViewModelTest(Customer customer, SelectList locations) { FirstName = customer.FirstName; LastName = customer.LastName ; Locations = locations; } } ``` 6) Or some other combination of the above or another way. All opinions welcome.
2010/06/17
[ "https://Stackoverflow.com/questions/3060765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267174/" ]
Here's what I may suggest: have a view model which reflects the fields of strongly typed view: ``` public class SomeViewModel { public string FirstName { get; set; } public string LastName { get; set; } public string Location { get; set; } public IEnumerable<SelectListItem> PossibleLocations { get; set; } } ``` And in your controller action populate this view model: ``` public ActionResult Index() { var customer = Repository.GetCustomer(); var locations = Repository.GetLocations(); var viewModel = new SomeViewModel { FirstName = customer.FirstName, LastName = customer.LastName, Location = customer.Location, PossibleLocations = new SelectList(locations, "LocationID", "LocationName", customer.Location); }; return View(viewModel); } [HttpPost] public ActionResult Index(SomeViewModel viewModel) { // TODO: Handle the form submission return View(viewModel); } ``` Of course doing the mapping between the model and the view model manually as shown my example could become quite cumbersome and in this case I would recommend you looking at [AutoMapper](http://automapper.codeplex.com/).
I'd have my ViewModel as this ``` public class SomeViewModel { public Customer Customer { get; set; } public IEnumerable<Location> PossibleLocations { get; set; } } ``` My controller like this: ``` public ActionResult Index() { var viewModel = new SomeViewModel { Customer = Repository.GetCustomer(), PossibleLocations = Repository.GetLocations() }; return View(viewModel); } ``` and then you can access everything in your Customer object in the view like this: ``` Customer name - <%: Model.Customer.FirstName %> <%: Model.Customer.LastName %> Location - <%: Html.DropDownList("LocationID", new SelectList(Model.PossibleLocations as IEnumerable, "LocationID", "LocationName", Model.Location.LocationID))%> ```
1,680,649
Gitk has a nice habit of showing me Tags:, Follows: and Precedes: for commit. How do I get the same information from command line?
2009/11/05
[ "https://Stackoverflow.com/questions/1680649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51209/" ]
To show the tag of a commit: ``` $ git describe --tags <commit> ``` To show the preceding commit: ``` $ git rev-list -1 <commit>^ ``` To show the following commit: ``` $ git rev-list -1 <commit>..HEAD ```
To show the tags that contain a commit (i.e. the tags that the commit precedes): ``` git tag --contains <commit> ```
1,321,482
Here is the code which woks perfectly and validate to enter only digits in a TEXT BOX. Now i have a problem there. My problem is i need to enter decimal values there. So i need to enter 'DOT' in the TEXT BOX. This validation has been done by using ASCII values. I even use the ASCII value of 'DOT -> 249, 250'. But it doesn't work. Any help will be appreciated. ``` function enterNumerics(e) { if (!e) var e = window.event; if(!e.which) key = e.keyCode; else key = e.which; if((key>=48)&&(key<=57)||key==8||key==9||key==32||key==45 || key==43) { key=key; document.getElementById('bal').innerHTML =''; return true; } else { document.getElementById('bal').innerHTML = "&nbsp;&nbsp;Please Enter Numerical Values "; return false; } } ``` Thanks in Advance.....
2009/08/24
[ "https://Stackoverflow.com/questions/1321482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/154137/" ]
You can use regular expressions instead: ``` function validate(){ var val=document.getElementById("field").value; //Field value if(/^[0-9\.]+$/.test(val)){ document.getElementById('bal').innerHTML=''; return true; }else{ document.getElementById('bal').innerHTML=" Please Enter Numerical Values "; return false; } } ``` then you call the validate function with onKeyPress event
Using a masked input solves the problem and enhances the solution. There is a [jQuery-Plugin](http://plugins.jquery.com/project/maskedinput) available which can do that.
1,321,482
Here is the code which woks perfectly and validate to enter only digits in a TEXT BOX. Now i have a problem there. My problem is i need to enter decimal values there. So i need to enter 'DOT' in the TEXT BOX. This validation has been done by using ASCII values. I even use the ASCII value of 'DOT -> 249, 250'. But it doesn't work. Any help will be appreciated. ``` function enterNumerics(e) { if (!e) var e = window.event; if(!e.which) key = e.keyCode; else key = e.which; if((key>=48)&&(key<=57)||key==8||key==9||key==32||key==45 || key==43) { key=key; document.getElementById('bal').innerHTML =''; return true; } else { document.getElementById('bal').innerHTML = "&nbsp;&nbsp;Please Enter Numerical Values "; return false; } } ``` Thanks in Advance.....
2009/08/24
[ "https://Stackoverflow.com/questions/1321482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/154137/" ]
You can use regular expressions instead: ``` function validate(){ var val=document.getElementById("field").value; //Field value if(/^[0-9\.]+$/.test(val)){ document.getElementById('bal').innerHTML=''; return true; }else{ document.getElementById('bal').innerHTML=" Please Enter Numerical Values "; return false; } } ``` then you call the validate function with onKeyPress event
ascii code for dot(.) is 249 as per the [ascii table](http://www.asciitablechart.com) so i hope e.keyCode may not be representing ascii value.
1,321,482
Here is the code which woks perfectly and validate to enter only digits in a TEXT BOX. Now i have a problem there. My problem is i need to enter decimal values there. So i need to enter 'DOT' in the TEXT BOX. This validation has been done by using ASCII values. I even use the ASCII value of 'DOT -> 249, 250'. But it doesn't work. Any help will be appreciated. ``` function enterNumerics(e) { if (!e) var e = window.event; if(!e.which) key = e.keyCode; else key = e.which; if((key>=48)&&(key<=57)||key==8||key==9||key==32||key==45 || key==43) { key=key; document.getElementById('bal').innerHTML =''; return true; } else { document.getElementById('bal').innerHTML = "&nbsp;&nbsp;Please Enter Numerical Values "; return false; } } ``` Thanks in Advance.....
2009/08/24
[ "https://Stackoverflow.com/questions/1321482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/154137/" ]
~~The dot key is 46, just allow it in the if statement.~~ Oh, you're getting keyCode, not charCode so this is on keydown, not keypress. Ignore the above -- dot is 190.
Using a masked input solves the problem and enhances the solution. There is a [jQuery-Plugin](http://plugins.jquery.com/project/maskedinput) available which can do that.
1,321,482
Here is the code which woks perfectly and validate to enter only digits in a TEXT BOX. Now i have a problem there. My problem is i need to enter decimal values there. So i need to enter 'DOT' in the TEXT BOX. This validation has been done by using ASCII values. I even use the ASCII value of 'DOT -> 249, 250'. But it doesn't work. Any help will be appreciated. ``` function enterNumerics(e) { if (!e) var e = window.event; if(!e.which) key = e.keyCode; else key = e.which; if((key>=48)&&(key<=57)||key==8||key==9||key==32||key==45 || key==43) { key=key; document.getElementById('bal').innerHTML =''; return true; } else { document.getElementById('bal').innerHTML = "&nbsp;&nbsp;Please Enter Numerical Values "; return false; } } ``` Thanks in Advance.....
2009/08/24
[ "https://Stackoverflow.com/questions/1321482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/154137/" ]
~~The dot key is 46, just allow it in the if statement.~~ Oh, you're getting keyCode, not charCode so this is on keydown, not keypress. Ignore the above -- dot is 190.
ascii code for dot(.) is 249 as per the [ascii table](http://www.asciitablechart.com) so i hope e.keyCode may not be representing ascii value.
1,490,538
I am hosting a client's site while they are running an exchange server at their location to handle the email. Whenever I try to send email via PHP to one of their email addresses it fails as it is looking for the address on the local system. Can I force the mail function to look outside of the server for sending mail? I'm on a Media Temple dedicated virtual box.
2009/09/29
[ "https://Stackoverflow.com/questions/1490538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/154442/" ]
I'm guessing the easier way would be to not use the `mail` function, but a library that deals with sending mail by SMTP -- the SMTP being on your client's server. You can for instance take a look at [Swift Mailer](http://swiftmailer.org/) (which has a pretty good reputation, and is used by the Symfony Framework), or [`PEAR::Mail`](http://pear.php.net/package/Mail).
Media Temple has probably set it up this way to reduce the spam problems. You will have to ask Media Temple about the configuration. I've worked with Media Temple before. They are pretty responsive to their customers needs. Chances are they have been asked and answered this question before.
1,023,967
On a Rails project, I'm using Sphinx together with Thinking Sphinx plugin. I index a table with an attribute :foo that is a float. My desired behaviour when sorting for column :foo would be that nil values always appear at the end of the list, e.g. ``` id; foo (order foo desc) ------- 1; 5 2; 3 3; -4 4: -5 5: nil 6: nil id; foo (order foo asc) ------- 4: -5 3; -4 2; 3 1; 5 5: nil 6: nil ``` If it was normal sql, I'd sort like: ``` :order => "(foo IS NULL) ASC, foo DESC" ``` But it seems not to be possible, as I think NULL values are translated to 0 (is that true?). Using sphinx ordering expressions seems not to sort my floats properly. Did anybody solve this problem or has an idea on how to do it?
2009/06/21
[ "https://Stackoverflow.com/questions/1023967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117525/" ]
The solution you've provided is what I would suggest - as yes, you're correct, Sphinx treats NULLs as 0's.
One solution I came up with in the meantime is to index an extra attribute, like this: ``` define_index do indexes foo, :sortable => true has "foo IS NULL", :as => :foo_nil, :sortable => true end ``` what lets me order like this ``` :order => "foo_nil ASC, foo DESC" ``` It's a bit clumsy, especially as I have many attributes that I want to have ordered like this.
1,635,279
When I format a text field to be displayed in "Bold"..it appears as bold in the ireport output, but is not displayed in bold when the same is viewed as a PDF.. any suggestions...?
2009/10/28
[ "https://Stackoverflow.com/questions/1635279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196444/" ]
Just had the same problem... I don't know if it will help you, but... both the text field and the label have a property called "Pdf font name". You have to set this to a bold font (i.e. "Helvetica-Bold" instead of "Helvetica") to render the field bold in a PDF file. If you edit the JRXML file directly, this setting is contained in the textelement tag after the "size" and "isBold" properties.
PdfFont name is obsolete. Use font extension instead. Add jasperreports-fonts-xxx.jar into the classpath. Or try <http://sites.google.com/site/xmedeko/code/misc/jasperreports-pdf-font-mapping>
1,635,279
When I format a text field to be displayed in "Bold"..it appears as bold in the ireport output, but is not displayed in bold when the same is viewed as a PDF.. any suggestions...?
2009/10/28
[ "https://Stackoverflow.com/questions/1635279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196444/" ]
Just had the same problem... I don't know if it will help you, but... both the text field and the label have a property called "Pdf font name". You have to set this to a bold font (i.e. "Helvetica-Bold" instead of "Helvetica") to render the field bold in a PDF file. If you edit the JRXML file directly, this setting is contained in the textelement tag after the "size" and "isBold" properties.
An excellent article on here gives the answer... javaskeleton.blogspot.co.at/2010/12/embedding-fonts-into-pdf-generated-by.html So you have to add the TrueType file of the font you want from C:\Windows\Fonts into iReport. In the latest version of iReport, which is 4.01, you go to Tools -> Options -> iReport Tab -> Fonts tab -> Install Font. In Windows 7, the fonts aren't visible inside the File Explorer as opened by any other program. So, you'll need to copy the Fonts you want (whose normal, 'bold', 'italic' and 'bold italic' ttf files are clogged as one by Windows in the C:\Windows\Fonts folder under the typeface heading e.g. Verdana) into some other folder. Now choose the file containing the 'normal' version of the typeface (the file named same as the typeface name), under 'Install Font' in iReport. Follow the wizard, add the other typeface versions and finish it. After that, you need to make a jar extension and store it in a folder which preferable does not require Adminstrator permissions to perform an edit. You can't save it in the default folder shown unless you've opened iReport under Administrator permissions. After saving it, manually transfer it to the default folder shown earlier, which is the place for storage of extensions to iReport, (Installation folder)\ireport\modules\ext\ (yourfontfile.jar). After this process, open the iReport tab under Tools -> Options again in iReport, add the jar file to the classpath. And you're done!
1,635,279
When I format a text field to be displayed in "Bold"..it appears as bold in the ireport output, but is not displayed in bold when the same is viewed as a PDF.. any suggestions...?
2009/10/28
[ "https://Stackoverflow.com/questions/1635279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196444/" ]
Just had the same problem... I don't know if it will help you, but... both the text field and the label have a property called "Pdf font name". You have to set this to a bold font (i.e. "Helvetica-Bold" instead of "Helvetica") to render the field bold in a PDF file. If you edit the JRXML file directly, this setting is contained in the textelement tag after the "size" and "isBold" properties.
I had the same problem but I solved it by changing the version of jar file of Jasper in my web application.I compiled my jrxml file in Jaspersoft iReport 5.6.0 and the version of jar file of Jasper is also 5.6.0. Previously it was 5.5.0 that is why it was not appearing in bold through the web application.
1,635,279
When I format a text field to be displayed in "Bold"..it appears as bold in the ireport output, but is not displayed in bold when the same is viewed as a PDF.. any suggestions...?
2009/10/28
[ "https://Stackoverflow.com/questions/1635279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196444/" ]
PdfFont name is obsolete. Use font extension instead. Add jasperreports-fonts-xxx.jar into the classpath. Or try <http://sites.google.com/site/xmedeko/code/misc/jasperreports-pdf-font-mapping>
An excellent article on here gives the answer... javaskeleton.blogspot.co.at/2010/12/embedding-fonts-into-pdf-generated-by.html So you have to add the TrueType file of the font you want from C:\Windows\Fonts into iReport. In the latest version of iReport, which is 4.01, you go to Tools -> Options -> iReport Tab -> Fonts tab -> Install Font. In Windows 7, the fonts aren't visible inside the File Explorer as opened by any other program. So, you'll need to copy the Fonts you want (whose normal, 'bold', 'italic' and 'bold italic' ttf files are clogged as one by Windows in the C:\Windows\Fonts folder under the typeface heading e.g. Verdana) into some other folder. Now choose the file containing the 'normal' version of the typeface (the file named same as the typeface name), under 'Install Font' in iReport. Follow the wizard, add the other typeface versions and finish it. After that, you need to make a jar extension and store it in a folder which preferable does not require Adminstrator permissions to perform an edit. You can't save it in the default folder shown unless you've opened iReport under Administrator permissions. After saving it, manually transfer it to the default folder shown earlier, which is the place for storage of extensions to iReport, (Installation folder)\ireport\modules\ext\ (yourfontfile.jar). After this process, open the iReport tab under Tools -> Options again in iReport, add the jar file to the classpath. And you're done!
1,635,279
When I format a text field to be displayed in "Bold"..it appears as bold in the ireport output, but is not displayed in bold when the same is viewed as a PDF.. any suggestions...?
2009/10/28
[ "https://Stackoverflow.com/questions/1635279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196444/" ]
Just put this in your pom.xml: ``` <dependency> <groupId>net.sf.jasperreports</groupId> <artifactId>jasperreports-fonts</artifactId> <version>5.6.1</version> </dependency> ```
PdfFont name is obsolete. Use font extension instead. Add jasperreports-fonts-xxx.jar into the classpath. Or try <http://sites.google.com/site/xmedeko/code/misc/jasperreports-pdf-font-mapping>
1,635,279
When I format a text field to be displayed in "Bold"..it appears as bold in the ireport output, but is not displayed in bold when the same is viewed as a PDF.. any suggestions...?
2009/10/28
[ "https://Stackoverflow.com/questions/1635279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196444/" ]
PdfFont name is obsolete. Use font extension instead. Add jasperreports-fonts-xxx.jar into the classpath. Or try <http://sites.google.com/site/xmedeko/code/misc/jasperreports-pdf-font-mapping>
I had the same problem but I solved it by changing the version of jar file of Jasper in my web application.I compiled my jrxml file in Jaspersoft iReport 5.6.0 and the version of jar file of Jasper is also 5.6.0. Previously it was 5.5.0 that is why it was not appearing in bold through the web application.
1,635,279
When I format a text field to be displayed in "Bold"..it appears as bold in the ireport output, but is not displayed in bold when the same is viewed as a PDF.. any suggestions...?
2009/10/28
[ "https://Stackoverflow.com/questions/1635279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196444/" ]
Just put this in your pom.xml: ``` <dependency> <groupId>net.sf.jasperreports</groupId> <artifactId>jasperreports-fonts</artifactId> <version>5.6.1</version> </dependency> ```
An excellent article on here gives the answer... javaskeleton.blogspot.co.at/2010/12/embedding-fonts-into-pdf-generated-by.html So you have to add the TrueType file of the font you want from C:\Windows\Fonts into iReport. In the latest version of iReport, which is 4.01, you go to Tools -> Options -> iReport Tab -> Fonts tab -> Install Font. In Windows 7, the fonts aren't visible inside the File Explorer as opened by any other program. So, you'll need to copy the Fonts you want (whose normal, 'bold', 'italic' and 'bold italic' ttf files are clogged as one by Windows in the C:\Windows\Fonts folder under the typeface heading e.g. Verdana) into some other folder. Now choose the file containing the 'normal' version of the typeface (the file named same as the typeface name), under 'Install Font' in iReport. Follow the wizard, add the other typeface versions and finish it. After that, you need to make a jar extension and store it in a folder which preferable does not require Adminstrator permissions to perform an edit. You can't save it in the default folder shown unless you've opened iReport under Administrator permissions. After saving it, manually transfer it to the default folder shown earlier, which is the place for storage of extensions to iReport, (Installation folder)\ireport\modules\ext\ (yourfontfile.jar). After this process, open the iReport tab under Tools -> Options again in iReport, add the jar file to the classpath. And you're done!
1,635,279
When I format a text field to be displayed in "Bold"..it appears as bold in the ireport output, but is not displayed in bold when the same is viewed as a PDF.. any suggestions...?
2009/10/28
[ "https://Stackoverflow.com/questions/1635279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196444/" ]
An excellent article on here gives the answer... javaskeleton.blogspot.co.at/2010/12/embedding-fonts-into-pdf-generated-by.html So you have to add the TrueType file of the font you want from C:\Windows\Fonts into iReport. In the latest version of iReport, which is 4.01, you go to Tools -> Options -> iReport Tab -> Fonts tab -> Install Font. In Windows 7, the fonts aren't visible inside the File Explorer as opened by any other program. So, you'll need to copy the Fonts you want (whose normal, 'bold', 'italic' and 'bold italic' ttf files are clogged as one by Windows in the C:\Windows\Fonts folder under the typeface heading e.g. Verdana) into some other folder. Now choose the file containing the 'normal' version of the typeface (the file named same as the typeface name), under 'Install Font' in iReport. Follow the wizard, add the other typeface versions and finish it. After that, you need to make a jar extension and store it in a folder which preferable does not require Adminstrator permissions to perform an edit. You can't save it in the default folder shown unless you've opened iReport under Administrator permissions. After saving it, manually transfer it to the default folder shown earlier, which is the place for storage of extensions to iReport, (Installation folder)\ireport\modules\ext\ (yourfontfile.jar). After this process, open the iReport tab under Tools -> Options again in iReport, add the jar file to the classpath. And you're done!
I had the same problem but I solved it by changing the version of jar file of Jasper in my web application.I compiled my jrxml file in Jaspersoft iReport 5.6.0 and the version of jar file of Jasper is also 5.6.0. Previously it was 5.5.0 that is why it was not appearing in bold through the web application.
1,635,279
When I format a text field to be displayed in "Bold"..it appears as bold in the ireport output, but is not displayed in bold when the same is viewed as a PDF.. any suggestions...?
2009/10/28
[ "https://Stackoverflow.com/questions/1635279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196444/" ]
Just put this in your pom.xml: ``` <dependency> <groupId>net.sf.jasperreports</groupId> <artifactId>jasperreports-fonts</artifactId> <version>5.6.1</version> </dependency> ```
I had the same problem but I solved it by changing the version of jar file of Jasper in my web application.I compiled my jrxml file in Jaspersoft iReport 5.6.0 and the version of jar file of Jasper is also 5.6.0. Previously it was 5.5.0 that is why it was not appearing in bold through the web application.
1,853,181
I'm getting a fishy error when using glDrawElements(). I'm trying to render simple primitives (mainly rectangles) to speed up drawing of text and so forth, but when I call glDrawElements() the WHOLE screen blinks black (not just my window area) for one frame or so. The next frame it turns back to the same "Windows colors" as before. And so it flickers for a couple of seconds, ending up in a message box saying ``` The NVIDIA OpenGL Driver encountered an unrecoverable error and must close this application. Error 12 ``` Is there any setting for GL which I need to reset before calling glDrawElements()? I know it's not some dangling glEnableClientState(), I checked it (I used to have one of those, but then glDrawElements() crashed instead). Come to think of it, it almost looks like some back buffer error... Any ideas on what to try?
2009/12/05
[ "https://Stackoverflow.com/questions/1853181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87973/" ]
Obviously you are mixing VBO mode and VA mode. This is perfectly possible but must be use with care. When you call: ``` glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); ``` This means that next time you render something with `glDrawElements(..., ..., ..., x)`, it will use x as a pointer on the indices data, and the last call to glVertexPointer points on the vertices data. If you **don't** unbind the current VBO and IBO (with the above two glBindBuffer calls), this means that when rendering with the same glDrawElements, x will be use as an offset on the indices data **in the IBO**, and the last call to glVertexPointer as an offset on the vertices data **in the VBO**. Depending values of x and glVertexPointer you can make the driver crash because the offsets go out of bounds and/or the underlying data is of the wrong type (NaN). So for answering your question, after drawing with VBO mode and then drawing with VA mode: 1. unbind the current VBO 2. unbind the current IBO 3. specify the right vertices address with `glVertexPointer` 4. specify the right indices address with `glDrawElements` and then it will be fine.
Bah! Found it. When I did ``` glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); ``` before rendering the flickering+crashing stopped. Is this the expected behavior? Sorry for wasting time and space.
1,871,240
``` // strings is a 2D array (each string is 11 bytes long) char strings[][11] = {"0123456789", "2222244444", "3333366666"}; printf("String 3 Character 2 is %c\n", strings[2][1]); ``` How can I code this print statement using pointer arithmetic instead of the `strings[2][1]` ?
2009/12/09
[ "https://Stackoverflow.com/questions/1871240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227648/" ]
In C, `a[b]` is the same as `*(a+b)` (and since addition is commutative, that implies that it's also equivalent to `b[a]`. People writing for the International Obfuscated C Code Contest frequently rely on this, using things like `x["string"];`. Needless to say, it's best to avoid that sort of thing unless you're intentionally being evil though... Edit:For anybody who's sure their understanding of the subject is up to snuff should feel free to analyze the following and correctly predict its output before running it: ``` #include <stdio.h> char *c[] = { "ENTER", "NEW", "POINT", "FIRST" }; char **cp[] = { c+3, c+2, c+1, c }; char ***cpp = cp; main() { printf("%s", **++cpp); printf("%s ", *--*++cpp+3); printf("%s", *cpp[-2]+3); printf("%s\n", cpp[-1][-1]+1); return 0; } ``` If memory serves, the credit (blame?) for that particular code goes to Thad Smith.
How did I do with this? ``` char strings[][11] = { "0123456789", "2222244444", "3333366666" }; printf("String 3 Character 2 is %c\n", *(*(strings + 2) + 1)); ```
1,871,240
``` // strings is a 2D array (each string is 11 bytes long) char strings[][11] = {"0123456789", "2222244444", "3333366666"}; printf("String 3 Character 2 is %c\n", strings[2][1]); ``` How can I code this print statement using pointer arithmetic instead of the `strings[2][1]` ?
2009/12/09
[ "https://Stackoverflow.com/questions/1871240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227648/" ]
In C, `a[b]` is the same as `*(a+b)` (and since addition is commutative, that implies that it's also equivalent to `b[a]`. People writing for the International Obfuscated C Code Contest frequently rely on this, using things like `x["string"];`. Needless to say, it's best to avoid that sort of thing unless you're intentionally being evil though... Edit:For anybody who's sure their understanding of the subject is up to snuff should feel free to analyze the following and correctly predict its output before running it: ``` #include <stdio.h> char *c[] = { "ENTER", "NEW", "POINT", "FIRST" }; char **cp[] = { c+3, c+2, c+1, c }; char ***cpp = cp; main() { printf("%s", **++cpp); printf("%s ", *--*++cpp+3); printf("%s", *cpp[-2]+3); printf("%s\n", cpp[-1][-1]+1); return 0; } ``` If memory serves, the credit (blame?) for that particular code goes to Thad Smith.
``` *(*(strings+2)+1) ```
963,796
How does a digital clocking system deal with user error such as someone forgetting to clock out or someone erroneously entering their code causing them to clock someone else in/out (who might not even be on the schedule that day). Its obvious there could be issues of dishonesty, but what about human error?
2009/06/08
[ "https://Stackoverflow.com/questions/963796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The better T&A (time & attendance) programs actually let this be configured in any of a number of ways. (Btw, typically the clocking software itself just marks down a "transaction" - this employee at that time did this thing - with no further processing, leaving that to the T&A system.) * Have a "hard" clock out time - e.g. even if you forgot to clock out when you leave at 5, you're automatically clocked out at 6. * Rollover - leave the employee clocked in, even till tomorrow, and then just have extra clockin in the morning. * Mark the workday as "incomplete", and expect the employee to submit their actual times manually. * Cancel the entire workday * Dont clock the employee out automatically, but transfer him after a certain time to another, default charge code (where this is relevant). * Run some other custom scripted action... It's important to note, that all of these results are "legitimate", depending on the organization, contracts, etc. Now, wrt to entering the wrong employee code - most often it's based on an employee card (or even some form of biometric scanner), but when the employee is expected to manually type in their code, the console should display the employee's name, for verification, and then a second "approve" button. Also, to some extent this can be discovered automatically and flagged for manual followup, for instance in the case where night-shift employees are shown as clocking in the morning, or HQ personnel clocking at a remote branch office.
so if it is to prevent human error, a password which is actually a "verification code" can be used. So if Joe is 0123 and Mary is 0124, Joe's entering 0123 needs to be matched with his entering verification code of 8888 so that the system knows it is really Joe, not Mary entering 0123 by accident.
963,796
How does a digital clocking system deal with user error such as someone forgetting to clock out or someone erroneously entering their code causing them to clock someone else in/out (who might not even be on the schedule that day). Its obvious there could be issues of dishonesty, but what about human error?
2009/06/08
[ "https://Stackoverflow.com/questions/963796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The better T&A (time & attendance) programs actually let this be configured in any of a number of ways. (Btw, typically the clocking software itself just marks down a "transaction" - this employee at that time did this thing - with no further processing, leaving that to the T&A system.) * Have a "hard" clock out time - e.g. even if you forgot to clock out when you leave at 5, you're automatically clocked out at 6. * Rollover - leave the employee clocked in, even till tomorrow, and then just have extra clockin in the morning. * Mark the workday as "incomplete", and expect the employee to submit their actual times manually. * Cancel the entire workday * Dont clock the employee out automatically, but transfer him after a certain time to another, default charge code (where this is relevant). * Run some other custom scripted action... It's important to note, that all of these results are "legitimate", depending on the organization, contracts, etc. Now, wrt to entering the wrong employee code - most often it's based on an employee card (or even some form of biometric scanner), but when the employee is expected to manually type in their code, the console should display the employee's name, for verification, and then a second "approve" button. Also, to some extent this can be discovered automatically and flagged for manual followup, for instance in the case where night-shift employees are shown as clocking in the morning, or HQ personnel clocking at a remote branch office.
The system must allow to print a preview of the final time sheet. Employees then get a copy, can verify it and return fixes (signed by their boss). These get merged with the data that already exists. Unless you hijack your employees, force a RFID into their spine and make them crawl through a scanner tube four times a way, that's the most simple, secure and reality-prone solution.
1,898,987
In vim, I do search with vimgrep frequently. I have mapping like below: ``` map <leader>s :execute "noautocmd vimgrep /\\<" . expand("<cword>") . "\\>/gj **/*.*" <Bar> cw<CR> 5 ``` The problem is that there are some temporary subfolders (like obj, objd) that I don't want to search for. How can I exclude subfolders matching given patterns. For example, subfolders with prefix "objd" should not be included in searching.
2009/12/14
[ "https://Stackoverflow.com/questions/1898987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
You could try [ack](http://betterthangrep.com/) instead. It integrates nicely with vim and has lots of options for doing the sort of thing you want to do. There are several ack-vim integrations on GitHub. For example: [here](http://github.com/mileszs/ack.vim).
For example in Ubuntu just ``` sudo apt-get install ack-grep sudo ln -s /usr/bin/ack-grep /usr/bin/ack ``` then install <http://www.vim.org/scripts/script.php?script_id=2572> and now add next line to your .vimrc ``` noremap <C-f> :copen<CR>:Ack --ignore-dir #first_ignore_dir# --ignore-dir #second_ignore_dir# -ai ``` * its open search frame by Ctr+F, have fun
1,898,987
In vim, I do search with vimgrep frequently. I have mapping like below: ``` map <leader>s :execute "noautocmd vimgrep /\\<" . expand("<cword>") . "\\>/gj **/*.*" <Bar> cw<CR> 5 ``` The problem is that there are some temporary subfolders (like obj, objd) that I don't want to search for. How can I exclude subfolders matching given patterns. For example, subfolders with prefix "objd" should not be included in searching.
2009/12/14
[ "https://Stackoverflow.com/questions/1898987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
As of Vim 7.3.570, you can use wildignore to exclude patterns with vimgrep. For example, to ignore the objd subfolder: ``` :set wildignore+=objd/** ``` Additional exclusions can be added by separating patterns with a comma: ``` :set wildignore+=objd/**,obj/**,*.tmp,test.c ``` See Vim's help documentation for a few more details. ``` :help wildignore ```
You could try [ack](http://betterthangrep.com/) instead. It integrates nicely with vim and has lots of options for doing the sort of thing you want to do. There are several ack-vim integrations on GitHub. For example: [here](http://github.com/mileszs/ack.vim).
1,898,987
In vim, I do search with vimgrep frequently. I have mapping like below: ``` map <leader>s :execute "noautocmd vimgrep /\\<" . expand("<cword>") . "\\>/gj **/*.*" <Bar> cw<CR> 5 ``` The problem is that there are some temporary subfolders (like obj, objd) that I don't want to search for. How can I exclude subfolders matching given patterns. For example, subfolders with prefix "objd" should not be included in searching.
2009/12/14
[ "https://Stackoverflow.com/questions/1898987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
As of Vim 7.3.570, you can use wildignore to exclude patterns with vimgrep. For example, to ignore the objd subfolder: ``` :set wildignore+=objd/** ``` Additional exclusions can be added by separating patterns with a comma: ``` :set wildignore+=objd/**,obj/**,*.tmp,test.c ``` See Vim's help documentation for a few more details. ``` :help wildignore ```
For example in Ubuntu just ``` sudo apt-get install ack-grep sudo ln -s /usr/bin/ack-grep /usr/bin/ack ``` then install <http://www.vim.org/scripts/script.php?script_id=2572> and now add next line to your .vimrc ``` noremap <C-f> :copen<CR>:Ack --ignore-dir #first_ignore_dir# --ignore-dir #second_ignore_dir# -ai ``` * its open search frame by Ctr+F, have fun
1,898,987
In vim, I do search with vimgrep frequently. I have mapping like below: ``` map <leader>s :execute "noautocmd vimgrep /\\<" . expand("<cword>") . "\\>/gj **/*.*" <Bar> cw<CR> 5 ``` The problem is that there are some temporary subfolders (like obj, objd) that I don't want to search for. How can I exclude subfolders matching given patterns. For example, subfolders with prefix "objd" should not be included in searching.
2009/12/14
[ "https://Stackoverflow.com/questions/1898987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
As showed in <http://vimcasts.org/blog/2013/03/combining-vimgrep-with-git-ls-files/> you could instead of exclude files, include the files you want to search. So you can search in the files tracked by Git with ``` :noautocmd vimgrep /{pattern}/gj `git ls-files` ``` In this way you are not searching the files stated in the `.gitignore`. --- I use it so much I created a command for that, so I just need to ``` :Sch {pattern} ``` and I did it by adding the following line to my .vimrc ``` command -nargs=1 Sch noautocmd vimgrep /<args>/gj `git ls-files` | cw ```
For example in Ubuntu just ``` sudo apt-get install ack-grep sudo ln -s /usr/bin/ack-grep /usr/bin/ack ``` then install <http://www.vim.org/scripts/script.php?script_id=2572> and now add next line to your .vimrc ``` noremap <C-f> :copen<CR>:Ack --ignore-dir #first_ignore_dir# --ignore-dir #second_ignore_dir# -ai ``` * its open search frame by Ctr+F, have fun
1,898,987
In vim, I do search with vimgrep frequently. I have mapping like below: ``` map <leader>s :execute "noautocmd vimgrep /\\<" . expand("<cword>") . "\\>/gj **/*.*" <Bar> cw<CR> 5 ``` The problem is that there are some temporary subfolders (like obj, objd) that I don't want to search for. How can I exclude subfolders matching given patterns. For example, subfolders with prefix "objd" should not be included in searching.
2009/12/14
[ "https://Stackoverflow.com/questions/1898987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
As of Vim 7.3.570, you can use wildignore to exclude patterns with vimgrep. For example, to ignore the objd subfolder: ``` :set wildignore+=objd/** ``` Additional exclusions can be added by separating patterns with a comma: ``` :set wildignore+=objd/**,obj/**,*.tmp,test.c ``` See Vim's help documentation for a few more details. ``` :help wildignore ```
As showed in <http://vimcasts.org/blog/2013/03/combining-vimgrep-with-git-ls-files/> you could instead of exclude files, include the files you want to search. So you can search in the files tracked by Git with ``` :noautocmd vimgrep /{pattern}/gj `git ls-files` ``` In this way you are not searching the files stated in the `.gitignore`. --- I use it so much I created a command for that, so I just need to ``` :Sch {pattern} ``` and I did it by adding the following line to my .vimrc ``` command -nargs=1 Sch noautocmd vimgrep /<args>/gj `git ls-files` | cw ```
3,052,418
This is an odd one, not one I've come across before. My project complies and runs fine if I have my classes in the root folder (Not in App\_Code). As soon as I move them into the App\_Code folder then it will compile, but running it will bring up the old ``` CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System.Data' (are you missing an assembly reference?) ``` I don't understand how moving the class(es) to the App\_Code folder causes the whole thing to fall apart there? Project target is .Net 4 on VWD 2010 Express
2010/06/16
[ "https://Stackoverflow.com/questions/3052418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175407/" ]
You have to modify the web.config file of your web application to make it compile and use .net 3.5 (or maybe higher in your case): ``` <system.web> <compilation> <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /> </compilation> </system.web> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <providerOption name="CompilerVersion" value="v3.5" /> <providerOption name="WarnAsError" value="false" /> </compiler> </compilers> </system.codedom> ```
The reference is System.Linq, not System.Data.Linq. How is your reference declared?
3,052,418
This is an odd one, not one I've come across before. My project complies and runs fine if I have my classes in the root folder (Not in App\_Code). As soon as I move them into the App\_Code folder then it will compile, but running it will bring up the old ``` CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System.Data' (are you missing an assembly reference?) ``` I don't understand how moving the class(es) to the App\_Code folder causes the whole thing to fall apart there? Project target is .Net 4 on VWD 2010 Express
2010/06/16
[ "https://Stackoverflow.com/questions/3052418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175407/" ]
You have to modify the web.config file of your web application to make it compile and use .net 3.5 (or maybe higher in your case): ``` <system.web> <compilation> <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /> </compilation> </system.web> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <providerOption name="CompilerVersion" value="v3.5" /> <providerOption name="WarnAsError" value="false" /> </compiler> </compilers> </system.codedom> ```
I had the exact same problem. The answer for me was to set Local Copy to True in the Properties Window for System.Data.Linq.
3,052,418
This is an odd one, not one I've come across before. My project complies and runs fine if I have my classes in the root folder (Not in App\_Code). As soon as I move them into the App\_Code folder then it will compile, but running it will bring up the old ``` CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System.Data' (are you missing an assembly reference?) ``` I don't understand how moving the class(es) to the App\_Code folder causes the whole thing to fall apart there? Project target is .Net 4 on VWD 2010 Express
2010/06/16
[ "https://Stackoverflow.com/questions/3052418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175407/" ]
I had the exact same problem. The answer for me was to set Local Copy to True in the Properties Window for System.Data.Linq.
The reference is System.Linq, not System.Data.Linq. How is your reference declared?
2,931,819
I have an arbitrarily deep list of the form: ``` <ul> <li></li> <li> <ul> <li></li> </ul> </li> </ul> ``` I am trying to build a function "nextElement" that returns a jQuery selector. The first time the function is called, it returns the first li in the list. The second time it is called, it returns the next li in the page. Etc. I'd like this function to pay no attention to siblings, parents, children, etc. All I care about is that everytime it is called, the next li in the source gets chosen. Any suggestions on how to go about approaching this? Thanks
2010/05/28
[ "https://Stackoverflow.com/questions/2931819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/283510/" ]
The no-jQuery solution.. ``` function getIterator(){ var nodes = document.getElementByTagName("li"); var index = 0; return { next: function(){ return nodes[index++]; }, hasNext: function(){ return index < nodes.lenght - 1; } }; } ``` Then use ``` var iterator = getIterator(); while (iterator.hasNext()){ var node = iterator.next(); console.log(node.innerHTML); // if you want to just wrap the node in $(node).... } ``` or the more efficient ``` var iterator = getIterator(), node; while ((node = iterator.next())){ console.log(node.innerHTML); // if you want to just wrap the node in $(node).... } ```
Probably best to modify the concept of nextElement to be more like this: ``` (function($) { var index = -1; jQuery.fn.nextElement = function() { index = (index + 1) % this.length; return this.eq(index); } })(jQuery); ``` You can use it like this: ``` $("li").nextElement(); // returns first li $("li").nextElement(); // returns second li ``` etc...
10,264
I'd like some advice regarding defects on my print : [![enter image description here](https://i.stack.imgur.com/5x4u2.jpg)](https://i.stack.imgur.com/5x4u2.jpg) [![enter image description here](https://i.stack.imgur.com/3CgUe.jpg)](https://i.stack.imgur.com/3CgUe.jpg) Here some details : * Printer CR-10 S, nozzle 0.4 * Material PLA * Bed 60, Hotend 215, 50 mm/s speed * SLiced with cura 4.1, 5 walls (i can provide more detail of the profile if needed) * Layer height 0.1 * modeled on fusion 360 * The surface where the defect sits is actually tilted 45 degres Thanks !
2019/06/14
[ "https://3dprinting.stackexchange.com/questions/10264", "https://3dprinting.stackexchange.com", "https://3dprinting.stackexchange.com/users/16756/" ]
If you break up a large piece into multiple smaller pieces and properly glue them together, you basically add stiffeners (as a result of printing walls). This could lead to a more stiff model; this might have been confused by calling large prints more brittle opposed to constructed models. If printing is conducted at similar conditions on large printers, there shouldn't be a reason why the model becomes more brittle unless the conditions aren't the same. But that would be true for printing at small printers too, e.g. if one print was printed in a draft.
I'd recommend getting the object to fit together by design, rather than glue - though I tend (if the item is never to be disassembled) use Zap-a-gap - that stuff sticks like crazy though you must not squeeze the parts together but let it naturally sit.
2,206,607
I have built a cms from scratch in PHP and I need a little help with getting it more secure. Basically I have arranged all my important files as followed: ``` /var/www/TESTUSERNAME/includes/val.php ``` Is this a secure way to stop people from getting hold of my values ? Would it be a better to store these values in a database then run the query in this file ? could you also give me some tips on how to better secure my application ?
2010/02/05
[ "https://Stackoverflow.com/questions/2206607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123663/" ]
First of all, you configure the [php installation](http://www.securityfocus.com/infocus/1706) in such way that it becomes **less vulnerable**, you can also use the htaccess file to secure your directories. What about other security issues? **XSS CSFR SQL Injection Session hijacking Session Fixation etc etc** [See this for it.](http://phpsec.org/projects/guide/)
Check POST data for SQL injection, XSS:Filter script (and HTML) inserted to your page. These 2 are the most important. And of course update your installation. also you shouldn't rely on Session. If somebody stole a cookie of logged user he change into this user.
2,206,607
I have built a cms from scratch in PHP and I need a little help with getting it more secure. Basically I have arranged all my important files as followed: ``` /var/www/TESTUSERNAME/includes/val.php ``` Is this a secure way to stop people from getting hold of my values ? Would it be a better to store these values in a database then run the query in this file ? could you also give me some tips on how to better secure my application ?
2010/02/05
[ "https://Stackoverflow.com/questions/2206607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123663/" ]
First of all, you configure the [php installation](http://www.securityfocus.com/infocus/1706) in such way that it becomes **less vulnerable**, you can also use the htaccess file to secure your directories. What about other security issues? **XSS CSFR SQL Injection Session hijacking Session Fixation etc etc** [See this for it.](http://phpsec.org/projects/guide/)
If you put the values in the database then you have to worry about SQL Injection. If you aren't using parametrized quires, then you might have a serious problem with SQL Injection and moving the values to the database could be a bad idea due to this increased attack surface. In MySQL SQL injection can be used to read files like val.php, make sure your web application doesn't have "FILE" privileges. You also have to make sure your privileges are setup properly on this file. `chmod 750` is a good one of this file, the last number 0 denies all access to everyone that isn't you or in your group. by keeping the values in val.php you still have to worry about directory traversal vulnerabilities like this: ``` print file_get_contents("/var/www/whatever/".$_GET['FILE_NAME']); ``` Go though your code and pay attention to where you are reading and writing to files. Make sure you aren't passing in user control variables. If you want to get an attackers preservative on PHP and learning other ways of how files can be read i recommend reading [A Study In Scarlet](http://www.securereality.com.au/studyinscarlet.txt).
1,817,640
Is there a way to use the PHP `=>` operator (?) without using the `array()` "constructor"? To be specific, I want to create a function that will get a list of keys and values without wrapping it into an array: ``` function keysAndValues($items) { /* ... */ } keysAndValues( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' ); ``` Instead of ``` keysAndValues(array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' )); ``` Is there a way to do this?
2009/11/30
[ "https://Stackoverflow.com/questions/1817640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41983/" ]
These would be named arguments. Nope, not possible in PHP. You will have to wrap an array() around them. If it's not the array that's bothering you but the fact that you have to work with an array inside the function, try ``` function my_function($array) { extract($array); ... if (isset($number)) echo "Number is: ".$number; } ``` to unpack the options into the function's scope: ``` my_function(array("number" => "one")); // Will output "Number is: one" ``` it saves the hassle of unpacking them one by one using `foreach().`
well, specifically, the '=>' operator denotes the key, value pair inside an array, so there's really **no reason** to use it outside the array constructor. that said, it is used inside things like a 'foreach' loop to grab the key and value for each item in an array ``` foreach ($arr as $key=>$val) ```
1,817,640
Is there a way to use the PHP `=>` operator (?) without using the `array()` "constructor"? To be specific, I want to create a function that will get a list of keys and values without wrapping it into an array: ``` function keysAndValues($items) { /* ... */ } keysAndValues( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' ); ``` Instead of ``` keysAndValues(array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' )); ``` Is there a way to do this?
2009/11/30
[ "https://Stackoverflow.com/questions/1817640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41983/" ]
These would be named arguments. Nope, not possible in PHP. You will have to wrap an array() around them. If it's not the array that's bothering you but the fact that you have to work with an array inside the function, try ``` function my_function($array) { extract($array); ... if (isset($number)) echo "Number is: ".$number; } ``` to unpack the options into the function's scope: ``` my_function(array("number" => "one")); // Will output "Number is: one" ``` it saves the hassle of unpacking them one by one using `foreach().`
The closest thing you can get to what you want is by using dynamic arguments. Using [this tutorial/overview](http://oreilly.com/pub/a/php/2001/05/17/php_foundations.html) as a base, here is a hack to provide a potential solution: ``` function keysAndValues() { for($i = 0 ; $i < func_num_args(); $i++) { list($key, $value) = explode('=>', func_get_arg($i)); // Do something with the $key and $value } } ``` It would then be called like this: ``` keysAndValues('key1=>value1','key2=>value2','key3=>value3'); keysAndValues('key1=>value1'); ``` Basically, you can have any amount of parameters... they are dynamic!
1,817,640
Is there a way to use the PHP `=>` operator (?) without using the `array()` "constructor"? To be specific, I want to create a function that will get a list of keys and values without wrapping it into an array: ``` function keysAndValues($items) { /* ... */ } keysAndValues( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' ); ``` Instead of ``` keysAndValues(array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' )); ``` Is there a way to do this?
2009/11/30
[ "https://Stackoverflow.com/questions/1817640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41983/" ]
The closest thing you can get to what you want is by using dynamic arguments. Using [this tutorial/overview](http://oreilly.com/pub/a/php/2001/05/17/php_foundations.html) as a base, here is a hack to provide a potential solution: ``` function keysAndValues() { for($i = 0 ; $i < func_num_args(); $i++) { list($key, $value) = explode('=>', func_get_arg($i)); // Do something with the $key and $value } } ``` It would then be called like this: ``` keysAndValues('key1=>value1','key2=>value2','key3=>value3'); keysAndValues('key1=>value1'); ``` Basically, you can have any amount of parameters... they are dynamic!
well, specifically, the '=>' operator denotes the key, value pair inside an array, so there's really **no reason** to use it outside the array constructor. that said, it is used inside things like a 'foreach' loop to grab the key and value for each item in an array ``` foreach ($arr as $key=>$val) ```
153,724
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations. I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes. I know one method of doing this is to use the `String.format` method: ``` String.format("%.5g%n", 0.912385); ``` returns: ``` 0.91239 ``` which is great, however it always displays numbers with 5 decimal places even if they are not significant: ``` String.format("%.5g%n", 0.912300); ``` returns: ``` 0.91230 ``` Another method is to use the `DecimalFormatter`: ``` DecimalFormat df = new DecimalFormat("#.#####"); df.format(0.912385); ``` returns: ``` 0.91238 ``` However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this: ``` 0.912385 -> 0.91239 0.912300 -> 0.9123 ``` What is the best way to achieve this in Java?
2008/09/30
[ "https://Stackoverflow.com/questions/153724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12149/" ]
Assuming `value` is a `double`, you can do: ``` (double)Math.round(value * 100000d) / 100000d ``` That's for 5 digits precision. The number of zeros indicate the number of decimals.
If you Consider 5 or n number of decimal. May be this answer solve your prob. ``` double a = 123.00449; double roundOff1 = Math.round(a*10000)/10000.00; double roundOff2 = Math.round(roundOff1*1000)/1000.00; double roundOff = Math.round(roundOff2*100)/100.00; System.out.println("result:"+roundOff); ``` **Output will be:** 123.0**1** this can be solve with loop and recursive function.
153,724
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations. I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes. I know one method of doing this is to use the `String.format` method: ``` String.format("%.5g%n", 0.912385); ``` returns: ``` 0.91239 ``` which is great, however it always displays numbers with 5 decimal places even if they are not significant: ``` String.format("%.5g%n", 0.912300); ``` returns: ``` 0.91230 ``` Another method is to use the `DecimalFormatter`: ``` DecimalFormat df = new DecimalFormat("#.#####"); df.format(0.912385); ``` returns: ``` 0.91238 ``` However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this: ``` 0.912385 -> 0.91239 0.912300 -> 0.9123 ``` What is the best way to achieve this in Java?
2008/09/30
[ "https://Stackoverflow.com/questions/153724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12149/" ]
Assuming `value` is a `double`, you can do: ``` (double)Math.round(value * 100000d) / 100000d ``` That's for 5 digits precision. The number of zeros indicate the number of decimals.
Keep in mind that String.format() and DecimalFormat produce string using default Locale. So they may write formatted number with dot or comma as a separator between integer and decimal parts. To make sure that rounded String is in the format you want use java.text.NumberFormat as so: ``` Locale locale = Locale.ENGLISH; NumberFormat nf = NumberFormat.getNumberInstance(locale); // for trailing zeros: nf.setMinimumFractionDigits(2); // round to 2 digits: nf.setMaximumFractionDigits(2); System.out.println(nf.format(.99)); System.out.println(nf.format(123.567)); System.out.println(nf.format(123.0)); ``` Will print in English locale (no matter what your locale is): 0.99 123.57 123.00 The example is taken from Farenda - [how to convert double to String correctly](http://farenda.com/java/java-format-double-2-decimal-places/).
153,724
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations. I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes. I know one method of doing this is to use the `String.format` method: ``` String.format("%.5g%n", 0.912385); ``` returns: ``` 0.91239 ``` which is great, however it always displays numbers with 5 decimal places even if they are not significant: ``` String.format("%.5g%n", 0.912300); ``` returns: ``` 0.91230 ``` Another method is to use the `DecimalFormatter`: ``` DecimalFormat df = new DecimalFormat("#.#####"); df.format(0.912385); ``` returns: ``` 0.91238 ``` However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this: ``` 0.912385 -> 0.91239 0.912300 -> 0.9123 ``` What is the best way to achieve this in Java?
2008/09/30
[ "https://Stackoverflow.com/questions/153724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12149/" ]
You can also use the ``` DecimalFormat df = new DecimalFormat("#.00000"); df.format(0.912385); ``` to make sure you have the trailing 0's.
There is a problem with the `Math.round` solution when trying to round to a negative number of decimal places. Consider the code ``` long l = 10; for(int dp = -1; dp > -10; --dp) { double mul = Math.pow(10,dp); double res = Math.round(l * mul) / mul; System.out.println(""+l+" rounded to "+dp+" dp = "+res); l *=10; } ``` this has the results ``` 10 rounded to -1 dp = 10.0 100 rounded to -2 dp = 100.0 1000 rounded to -3 dp = 1000.0 10000 rounded to -4 dp = 10000.0 100000 rounded to -5 dp = 99999.99999999999 1000000 rounded to -6 dp = 1000000.0 10000000 rounded to -7 dp = 1.0E7 100000000 rounded to -8 dp = 1.0E8 1000000000 rounded to -9 dp = 9.999999999999999E8 ``` The problem with -5 decimal places occur when dividing 1 by 1.0E-5 which is inexact. This can be fixed using ``` double mul = Math.pow(10,dp); double res; if(dp < 0 ) { double div = Math.pow(10,-dp); res = Math.round(l * mul) *div; } else { res = Math.round(l * mul) / mul; } ``` But this is another reason to use the BigDecimal methods.
153,724
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations. I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes. I know one method of doing this is to use the `String.format` method: ``` String.format("%.5g%n", 0.912385); ``` returns: ``` 0.91239 ``` which is great, however it always displays numbers with 5 decimal places even if they are not significant: ``` String.format("%.5g%n", 0.912300); ``` returns: ``` 0.91230 ``` Another method is to use the `DecimalFormatter`: ``` DecimalFormat df = new DecimalFormat("#.#####"); df.format(0.912385); ``` returns: ``` 0.91238 ``` However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this: ``` 0.912385 -> 0.91239 0.912300 -> 0.9123 ``` What is the best way to achieve this in Java?
2008/09/30
[ "https://Stackoverflow.com/questions/153724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12149/" ]
You can also use the ``` DecimalFormat df = new DecimalFormat("#.00000"); df.format(0.912385); ``` to make sure you have the trailing 0's.
here is my answer: ``` double num = 4.898979485566356; DecimalFormat df = new DecimalFormat("#.##"); time = Double.valueOf(df.format(num)); System.out.println(num); // 4.89 ```
153,724
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations. I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes. I know one method of doing this is to use the `String.format` method: ``` String.format("%.5g%n", 0.912385); ``` returns: ``` 0.91239 ``` which is great, however it always displays numbers with 5 decimal places even if they are not significant: ``` String.format("%.5g%n", 0.912300); ``` returns: ``` 0.91230 ``` Another method is to use the `DecimalFormatter`: ``` DecimalFormat df = new DecimalFormat("#.#####"); df.format(0.912385); ``` returns: ``` 0.91238 ``` However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this: ``` 0.912385 -> 0.91239 0.912300 -> 0.9123 ``` What is the best way to achieve this in Java?
2008/09/30
[ "https://Stackoverflow.com/questions/153724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12149/" ]
As some others have noted, the correct answer is to use either `DecimalFormat` or `BigDecimal`. Floating-point doesn't *have* decimal places so you cannot possibly round/truncate to a specific number of them in the first place. You have to work in a decimal radix, and that is what those two classes do. I am posting the following code as a counter-example to all the answers in this thread and indeed all over StackOverflow (and elsewhere) that recommend multiplication followed by truncation followed by division. It is incumbent on advocates of this technique to explain why the following code produces the wrong output in over 92% of cases. ``` public class RoundingCounterExample { static float roundOff(float x, int position) { float a = x; double temp = Math.pow(10.0, position); a *= temp; a = Math.round(a); return (a / (float)temp); } public static void main(String[] args) { float a = roundOff(0.0009434f,3); System.out.println("a="+a+" (a % .001)="+(a % 0.001)); int count = 0, errors = 0; for (double x = 0.0; x < 1; x += 0.0001) { count++; double d = x; int scale = 2; double factor = Math.pow(10, scale); d = Math.round(d * factor) / factor; if ((d % 0.01) != 0.0) { System.out.println(d + " " + (d % 0.01)); errors++; } } System.out.println(count + " trials " + errors + " errors"); } } ``` Output of this program: ``` 10001 trials 9251 errors ``` **EDIT:** To address some comments below I redid the modulus part of the test loop using `BigDecimal` and `new MathContext(16)` for the modulus operation as follows: ``` public static void main(String[] args) { int count = 0, errors = 0; int scale = 2; double factor = Math.pow(10, scale); MathContext mc = new MathContext(16, RoundingMode.DOWN); for (double x = 0.0; x < 1; x += 0.0001) { count++; double d = x; d = Math.round(d * factor) / factor; BigDecimal bd = new BigDecimal(d, mc); bd = bd.remainder(new BigDecimal("0.01"), mc); if (bd.multiply(BigDecimal.valueOf(100)).remainder(BigDecimal.ONE, mc).compareTo(BigDecimal.ZERO) != 0) { System.out.println(d + " " + bd); errors++; } } System.out.println(count + " trials " + errors + " errors"); } ``` Result: ``` 10001 trials 4401 errors ```
This was the simplest way I found to display only two decimal places. ``` double x = 123.123; System.out.printf( "%.2f", x ); ```
153,724
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations. I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes. I know one method of doing this is to use the `String.format` method: ``` String.format("%.5g%n", 0.912385); ``` returns: ``` 0.91239 ``` which is great, however it always displays numbers with 5 decimal places even if they are not significant: ``` String.format("%.5g%n", 0.912300); ``` returns: ``` 0.91230 ``` Another method is to use the `DecimalFormatter`: ``` DecimalFormat df = new DecimalFormat("#.#####"); df.format(0.912385); ``` returns: ``` 0.91238 ``` However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this: ``` 0.912385 -> 0.91239 0.912300 -> 0.9123 ``` What is the best way to achieve this in Java?
2008/09/30
[ "https://Stackoverflow.com/questions/153724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12149/" ]
You can also use the ``` DecimalFormat df = new DecimalFormat("#.00000"); df.format(0.912385); ``` to make sure you have the trailing 0's.
Try this: org.apache.commons.math3.util.Precision.round(double x, int scale) See: <http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html> Apache Commons Mathematics Library homepage is: <http://commons.apache.org/proper/commons-math/index.html> The internal implemetation of this method is: ``` public static double round(double x, int scale) { return round(x, scale, BigDecimal.ROUND_HALF_UP); } public static double round(double x, int scale, int roundingMethod) { try { return (new BigDecimal (Double.toString(x)) .setScale(scale, roundingMethod)) .doubleValue(); } catch (NumberFormatException ex) { if (Double.isInfinite(x)) { return x; } else { return Double.NaN; } } } ```
153,724
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations. I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes. I know one method of doing this is to use the `String.format` method: ``` String.format("%.5g%n", 0.912385); ``` returns: ``` 0.91239 ``` which is great, however it always displays numbers with 5 decimal places even if they are not significant: ``` String.format("%.5g%n", 0.912300); ``` returns: ``` 0.91230 ``` Another method is to use the `DecimalFormatter`: ``` DecimalFormat df = new DecimalFormat("#.#####"); df.format(0.912385); ``` returns: ``` 0.91238 ``` However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this: ``` 0.912385 -> 0.91239 0.912300 -> 0.9123 ``` What is the best way to achieve this in Java?
2008/09/30
[ "https://Stackoverflow.com/questions/153724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12149/" ]
Try this: org.apache.commons.math3.util.Precision.round(double x, int scale) See: <http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html> Apache Commons Mathematics Library homepage is: <http://commons.apache.org/proper/commons-math/index.html> The internal implemetation of this method is: ``` public static double round(double x, int scale) { return round(x, scale, BigDecimal.ROUND_HALF_UP); } public static double round(double x, int scale, int roundingMethod) { try { return (new BigDecimal (Double.toString(x)) .setScale(scale, roundingMethod)) .doubleValue(); } catch (NumberFormatException ex) { if (Double.isInfinite(x)) { return x; } else { return Double.NaN; } } } ```
If you're using a technology that has a minimal JDK. Here's a way without any Java libs: ``` double scale = 100000; double myVal = 0.912385; double rounded = (int)((myVal * scale) + 0.5d) / scale; ```
153,724
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations. I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes. I know one method of doing this is to use the `String.format` method: ``` String.format("%.5g%n", 0.912385); ``` returns: ``` 0.91239 ``` which is great, however it always displays numbers with 5 decimal places even if they are not significant: ``` String.format("%.5g%n", 0.912300); ``` returns: ``` 0.91230 ``` Another method is to use the `DecimalFormatter`: ``` DecimalFormat df = new DecimalFormat("#.#####"); df.format(0.912385); ``` returns: ``` 0.91238 ``` However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this: ``` 0.912385 -> 0.91239 0.912300 -> 0.9123 ``` What is the best way to achieve this in Java?
2008/09/30
[ "https://Stackoverflow.com/questions/153724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12149/" ]
Assuming `value` is a `double`, you can do: ``` (double)Math.round(value * 100000d) / 100000d ``` That's for 5 digits precision. The number of zeros indicate the number of decimals.
DecimalFormat is the best ways to output, but I don't prefer it. I always do this all the time, because it return the double value. So I can use it more than just output. ``` Math.round(selfEvaluate*100000d.0)/100000d.0; ``` OR ``` Math.round(selfEvaluate*100000d.0)*0.00000d1; ``` If you need large decimal places value, you can use BigDecimal instead. Anyways `.0` is important. Without it the rounding of 0.33333d5 return 0.33333 and only 9 digits are allows. The second function without `.0` has problems with 0.30000 return 0.30000000000000004.
153,724
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations. I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes. I know one method of doing this is to use the `String.format` method: ``` String.format("%.5g%n", 0.912385); ``` returns: ``` 0.91239 ``` which is great, however it always displays numbers with 5 decimal places even if they are not significant: ``` String.format("%.5g%n", 0.912300); ``` returns: ``` 0.91230 ``` Another method is to use the `DecimalFormatter`: ``` DecimalFormat df = new DecimalFormat("#.#####"); df.format(0.912385); ``` returns: ``` 0.91238 ``` However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this: ``` 0.912385 -> 0.91239 0.912300 -> 0.9123 ``` What is the best way to achieve this in Java?
2008/09/30
[ "https://Stackoverflow.com/questions/153724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12149/" ]
Try this: org.apache.commons.math3.util.Precision.round(double x, int scale) See: <http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html> Apache Commons Mathematics Library homepage is: <http://commons.apache.org/proper/commons-math/index.html> The internal implemetation of this method is: ``` public static double round(double x, int scale) { return round(x, scale, BigDecimal.ROUND_HALF_UP); } public static double round(double x, int scale, int roundingMethod) { try { return (new BigDecimal (Double.toString(x)) .setScale(scale, roundingMethod)) .doubleValue(); } catch (NumberFormatException ex) { if (Double.isInfinite(x)) { return x; } else { return Double.NaN; } } } ```
The code snippet below shows how to display n digits. The trick is to set variable pp to 1 followed by n zeros. In the example below, variable pp value has 5 zeros, so 5 digits will be displayed. ``` double pp = 10000; double myVal = 22.268699999999967; String needVal = "22.2687"; double i = (5.0/pp); String format = "%10.4f"; String getVal = String.format(format,(Math.round((myVal +i)*pp)/pp)-i).trim(); ```
153,724
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations. I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes. I know one method of doing this is to use the `String.format` method: ``` String.format("%.5g%n", 0.912385); ``` returns: ``` 0.91239 ``` which is great, however it always displays numbers with 5 decimal places even if they are not significant: ``` String.format("%.5g%n", 0.912300); ``` returns: ``` 0.91230 ``` Another method is to use the `DecimalFormatter`: ``` DecimalFormat df = new DecimalFormat("#.#####"); df.format(0.912385); ``` returns: ``` 0.91238 ``` However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this: ``` 0.912385 -> 0.91239 0.912300 -> 0.9123 ``` What is the best way to achieve this in Java?
2008/09/30
[ "https://Stackoverflow.com/questions/153724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12149/" ]
A succinct solution: ``` public static double round(double value, int precision) { int scale = (int) Math.pow(10, precision); return (double) (Math.round(value * scale) / scale); } ``` See also, <https://stackoverflow.com/a/22186845/212950> Thanks to [jpdymond](https://stackoverflow.com/users/2984077/jpdymond) for offering this. **Edit**: Added round brackets. Casts the whole result to double, not the first argument only!
Keep in mind that String.format() and DecimalFormat produce string using default Locale. So they may write formatted number with dot or comma as a separator between integer and decimal parts. To make sure that rounded String is in the format you want use java.text.NumberFormat as so: ``` Locale locale = Locale.ENGLISH; NumberFormat nf = NumberFormat.getNumberInstance(locale); // for trailing zeros: nf.setMinimumFractionDigits(2); // round to 2 digits: nf.setMaximumFractionDigits(2); System.out.println(nf.format(.99)); System.out.println(nf.format(123.567)); System.out.println(nf.format(123.0)); ``` Will print in English locale (no matter what your locale is): 0.99 123.57 123.00 The example is taken from Farenda - [how to convert double to String correctly](http://farenda.com/java/java-format-double-2-decimal-places/).
1,478,983
I know that FlexBuiler's refactoring engine can deal with updating variable names… But I can't figure out if it's possible to refactor at the package level. For example, I want to move `foo/a.as` to `foo/bar/a.as`, and I want the `package` path to be updated (ie, from `package foo` to `package foo.bar`) and references to be updated accordingly. Does FlexBuilder support this sort of refactoring? Or am I just doing something wrong?
2009/09/25
[ "https://Stackoverflow.com/questions/1478983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71522/" ]
No, it does not. Sorry. Your only option is to follow that with Ctrl-H, and swap out foo. with foo.bar.
The upcoming [Flash Builder 4](http://labs.adobe.com/technologies/flashbuilder4/) will support Move refactoring to move a class into a different package. A public beta is available on Adobe Labs.
1,904,318
I've got an editor with lots of image thumbnails. I'd like a double-click on an image to display the full resolution image using a modal undecorated dialog. Ideally, this would be animated, to show the image zooming up to full resolution on the center of the screen, then any click would make the image go away, either zooming back out or fading away. I'm not concerned with establishing an exact behavior, I just want something slick. I've found plenty of JavaScript examples for this, but is there anything built for [Swing](http://en.wikipedia.org/wiki/Swing_%28Java%29)?
2009/12/14
[ "https://Stackoverflow.com/questions/1904318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14467/" ]
This piece of code does more or less the trick... There is still a problem in the way I'm setting the dialog's location... Hope it helps. ``` import java.awt.BorderLayout; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.File; import java.lang.reflect.InvocationTargetException; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class OpenImageZooming { private static final int NB_STEPS = 30; private static final long OPENING_TOTAL_DURATION = 3000; public static void main(String[] args) { OpenImageZooming me = new OpenImageZooming(); me.openImage(args[0]); } private JFrame frame; private JDialog dialog; private JPanelZooming panelZooming; private void openImage(final String imagePath) { SwingUtilities.invokeLater(new Runnable() { public void run() { frame = new JFrame(); frame.setTitle("Open image with zoom"); JPanel p = new JPanel(new BorderLayout()); p.add(new JLabel("click on button to display image"), BorderLayout.CENTER); JButton button = new JButton("Display!"); frame.setContentPane(p); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Thread t = new Thread() { @Override public void run() { displayImaggeWithProgressiveZoom(imagePath); } }; t.start(); } }); p.add(button, BorderLayout.SOUTH); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 100); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } protected void displayImaggeWithProgressiveZoom(String imagePath) { try { final BufferedImage image = ImageIO.read(new File(imagePath)); for (int i = 0; i < NB_STEPS; i++) { displayDialog(i, NB_STEPS, image); Thread.sleep(OPENING_TOTAL_DURATION / NB_STEPS); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void displayDialog(final int i, final int nbSteps, final BufferedImage image) { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { if (dialog == null) { dialog = new JDialog(frame); dialog.setUndecorated(true); dialog.setModal(false); panelZooming = new JPanelZooming(image); dialog.setContentPane(panelZooming); dialog.setSize(0, 0); dialog.setLocationRelativeTo(frame); dialog.setVisible(true); } int w = (i + 1) * image.getWidth() / nbSteps; int h = (i + 1) * image.getHeight() / nbSteps; panelZooming.setScale((double) (i + 1) / nbSteps); dialog.setSize(w, h); dialog.setLocationRelativeTo(null); } }); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @SuppressWarnings("serial") public static class JPanelZooming extends JPanel { private BufferedImage image; private double scale = 1.0d; public JPanelZooming(BufferedImage image) { this.image = image; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; AffineTransform at = g2.getTransform(); AffineTransform oldTransform = (AffineTransform) at.clone(); at.scale(scale, scale); g2.setTransform(at); g2.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null); g2.setTransform(oldTransform); } public void setScale(double scale) { this.scale = scale; } } } ```
You can create a custom control that displays the image at the scale you want. 1) Create a BufferedImage from the image file you want using [ImageIO.read(file)](http://java.sun.com/javase/6/docs/api/javax/imageio/ImageIO.html#read%28java.io.File%29) (you can also create it from an InputStream) 2) Extend the JComponent or Canvas class and overload the paint function to draw the animated image using [Graphics.DrawImage()](http://java.sun.com/javase/6/docs/api/java/awt/Graphics.html#drawImage%28java.awt.Image,%20int,%20int,%20int,%20int,%20java.awt.Color,%20java.awt.image.ImageObserver%29) and set the width and height based on how long the window has been open. Set a timer or use another thread to repeatedly have the component redraw itself for however long you want the animation to play. I haven't done much with customized modal dialogs (I mostly find them annoying), but you can use a JDialog and and your component to it.
161,937
I understand there is a HTTP response header directive to disable page caching: ``` Cache-Control:no-cache ``` I can modify the header by "hand": ``` <%response.addHeader("Cache-Control","no-cache");%> ``` But is there a "nice" way to make the JSP interpreter return this header line in the server response? (I checked the <%@page ...%> directive. It seems there is nothing like that.)
2008/10/02
[ "https://Stackoverflow.com/questions/161937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17428/" ]
Also add ``` response.addHeader("Expires","-1"); response.addHeader("Pragma","no-cache"); ``` to your headers and give that a shot.
If you were using a servlet, then I believe what you posted in the question would be the correct approach. I'm not aware of any way to do this in the JSP.
161,937
I understand there is a HTTP response header directive to disable page caching: ``` Cache-Control:no-cache ``` I can modify the header by "hand": ``` <%response.addHeader("Cache-Control","no-cache");%> ``` But is there a "nice" way to make the JSP interpreter return this header line in the server response? (I checked the <%@page ...%> directive. It seems there is nothing like that.)
2008/10/02
[ "https://Stackoverflow.com/questions/161937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17428/" ]
Also add ``` response.addHeader("Expires","-1"); response.addHeader("Pragma","no-cache"); ``` to your headers and give that a shot.
``` <?xml version="1.0"?> <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0"> <jsp:scriptlet><![CDATA[ response.setHeader("Cache-Control", "no-cache"); ]]></jsp:scriptlet> </jsp:root> ``` You must put the response header inside `<jsp:root />`. Also, I would instead recommend it sending this from your servlet instead of JSP page.
161,937
I understand there is a HTTP response header directive to disable page caching: ``` Cache-Control:no-cache ``` I can modify the header by "hand": ``` <%response.addHeader("Cache-Control","no-cache");%> ``` But is there a "nice" way to make the JSP interpreter return this header line in the server response? (I checked the <%@page ...%> directive. It seems there is nothing like that.)
2008/10/02
[ "https://Stackoverflow.com/questions/161937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17428/" ]
Also add ``` response.addHeader("Expires","-1"); response.addHeader("Pragma","no-cache"); ``` to your headers and give that a shot.
IIRC some browsers may ignore the cache control settings in some contexts. The 'safe' workaround for this was to always get a page (even an AJAX chunk) with a new query string variable (like the time.)
1,447,184
Does it actually matter which CDN you use to link to your jquery file or any javascript file for that matter. Is one potentially faster than the other? What other factors could play a role in which cdn you decide to use? I know that Microsoft, Yahoo, and Google all have CDN's now.
2009/09/18
[ "https://Stackoverflow.com/questions/1447184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33690/" ]
**Update based on comments:** **Short version:** It doesn't matter much, but it may depend on what they host. They all host different things: Google doesn't host jQuery.Validate, Microsoft did not host jQuery-UI, since 2016 they do!!, Microsoft offers their scripts that would otherwise be served via `ScriptResource.axd` and an easier integration (e.g. [ScriptManager with ASP.Net 4.0](http://weblogs.asp.net/infinitiesloop/archive/2009/11/23/asp-net-4-0-scriptmanager-improvements.aspx)). **Important Note:** If you're building an intranet application, stay away from the CDN approach. It doesn't matter who's hosting it, unless you're on a **very** overloaded server internally, no CDN will give you more performance than local 100mb/1GB ethernet will. If you use a CDN for a strictly internal application you're **hurting performance**. [Set your cache expiration headers correctly](http://code.google.com/speed/page-speed/docs/caching.html) and ignore CDNs exist in the intranet-only scenario. The chances of either being blocked seems to be about equal, almost zero. I have worked on contracts where this isn't true, but it seems to be an exception. Also, since the original posting of this answer, the context surrounding it has changed greatly, the Microsoft CDN has made a lot of progress. The project I'm currently on uses both CDNs which works best for our solution. Several factors play into this. Users with an **older browser** are still probably making 2 simultaneous requests per domain [as recommended by the HTTP specification](http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html). This isn't an issue for anyone running anything decently new that [supports pipelining](http://en.wikipedia.org/wiki/HTTP_pipelining) (every current browser), but based on another factor we're knocking out this limitation as well, at least as far as the javascript. Google's CDN we're using for: * [jquery.min.js](http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js) * [jquery-ui.min.js](http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js). Microsoft's CDN we're using for: * [MicrosoftAjax.js](http://ajax.microsoft.com/ajax/beta/0911/MicrosoftAjax.js) * [MicrosoftAjaxWebForms.js](http://ajax.microsoft.com/ajax/beta/0911/MicrosoftAjaxWebForms.js) (until 4.0 we're not completely removing all UpdatePanels) * [jQuery.Validate.min.js](http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js) Our server: * Combined.js?v=2.2.0.6190 (Major.Minor.Iteration.Changeset) Since part of our build process is combining and minifying all custom javascript, we do this via a custom script manager that includes the release or debug (non-minified) versions of these scripts depending on the build. Since Google doesn't host the jQuery validation package, this can be a down-side. MVC is including/using this in their 2.0 release, so you could rely completely on Microsoft's CDN for all your needs, [and all of it automatic via the ScriptManager](http://weblogs.asp.net/infinitiesloop/archive/2009/11/23/asp-net-4-0-scriptmanager-improvements.aspx). The only other argument to be made would be DNS times, there is a cost to this in terms of page load speed. **On Average:** Simply because it's used more (it's been around longer) `ajax.googleapis.com` is likely to be returned by DNS sooner than `ajax.microsoft.com`, simply because the local DNS server was more likely to get a request for it (this is a first user in the area penalty). This is a **very** minor thing and should only be considered if performance is extremely important, down to the millisecond. *(Yes: I realize this point is contrary to my using both CDNs, but in our case the DNS time is far overshadowed by the wait time on the javascript/blocking that occurs)* Last, if you haven't looked at it, one of the best tools out there is [Firebug](http://getfirebug.com/), and some plug-ins for it: [Page Speed](http://getfirebug.com/) and [YSlow](http://developer.yahoo.com/yslow/). If you use a CDN but your pages are requesting images every time because of no cache-headers, you're missing the low-hanging fruit. Firebug's Net panel can quickly give you a quick breakdown of your page load-time, and Page Speed/YSlow can offer some good suggestions to help.
You should absolutely use the Google CDN for jQuery (and this is coming from a Microsoft-centric developer). It's simple statistics. Those who would consider using the MS CDN for jQuery will always be a minority. There are too many non-MS developers using jQuery who will use Google's and wouldn't consider using Microsoft's. Since [one of the big wins with a public CDN is improved caching](http://encosia.com/3-reasons-why-you-should-let-google-host-jquery-for-you/), splitting usage among multiple CDNs decreases the potential for that benefit.
1,447,184
Does it actually matter which CDN you use to link to your jquery file or any javascript file for that matter. Is one potentially faster than the other? What other factors could play a role in which cdn you decide to use? I know that Microsoft, Yahoo, and Google all have CDN's now.
2009/09/18
[ "https://Stackoverflow.com/questions/1447184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33690/" ]
> > Is one potentially faster than the other? > > > I was actually curious of this myself so I setup a jsbin test page using each of the following and then ran it through webpagetest.org's visual comparison tool. I tested: 1. ajax.googleapis.com 2. code.jquery.com 3. ajax.aspnetcdn.com 4. cdnjs.cloudflare.com Who was fastest: **code.jquery.com** by 0.1 second in both tests Who was slowest: **ajax.aspnetcdn.com** by 0.7 seconds in first test and **ajax.googleapis.com** by 1 second in second test Here's the **1st test** (each was tested 3 times): **Video:** <http://www.webpagetest.org/video/view.php?id=121019_16c5e25eff2937f63cc1714ed1eac814794e62b3> **Reports:** <http://www.webpagetest.org/video/compare.php?tests=121019_D2_KF0,121019_9Q_KF1,121019_WW_KF2,121019_9K_KF3> Here's the **2nd test** (another 3 each): **Video:** <http://www.webpagetest.org/video/view.php?id=121019_a7b351f706cad2c25664fee7ef349371f17c4e74> **Reports:** <http://www.webpagetest.org/video/compare.php?tests=121019_MP_KJN,121019_S6_KJP,121019_V9_KJQ,121019_VY_KJR>
As stated by [Pingdom](http://royal.pingdom.com/2010/05/11/cdn-performance-downloading-jquery-from-google-microsoft-and-edgecast-cdns/): > > When someone visits your site, if they have already visited another > site that uses the same jQuery file on the same CDN, the file will > have been cached and doesn’t need to be downloaded at all. It can’t > get any faster than that. > > > This means that the most widely used CDN will have the odds on its > side, which can pay off for your site. > > > A few observations on performance: > Google’s CDN is consistently the slowest of the three both in North America and Europe. In Europe, Microsoft’s CDN is the fastest. > > >
1,447,184
Does it actually matter which CDN you use to link to your jquery file or any javascript file for that matter. Is one potentially faster than the other? What other factors could play a role in which cdn you decide to use? I know that Microsoft, Yahoo, and Google all have CDN's now.
2009/09/18
[ "https://Stackoverflow.com/questions/1447184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33690/" ]
One minor thing to consider is that both companies offer slightly different "extra" libraries: * Microsoft is offering the **JQuery validation library** on their CDN, whereas Google is not (<http://www.asp.net/ajaxlibrary/cdn.ashx>) * Google is offering the **JQuery UI library** on their CDN, whereas Microsoft is not (<http://code.google.com/apis/ajaxlibs/documentation/>) Depending on your needs, this may be relevant.
I think it depends on where is your targeted audience. You can use alertra.com to check both CDN speed from many locations around the world.
1,447,184
Does it actually matter which CDN you use to link to your jquery file or any javascript file for that matter. Is one potentially faster than the other? What other factors could play a role in which cdn you decide to use? I know that Microsoft, Yahoo, and Google all have CDN's now.
2009/09/18
[ "https://Stackoverflow.com/questions/1447184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33690/" ]
My answer is bit different than others, I will go with microsoft if you need jquery validator which almost everyone need if you are using jquery. Microsoft CDN http connection is Keep-Alive which is big plus when you are requesting multiple items. So if you need jquery validation then use Microsoft CDN, even if you need jquery ui use microsoft because google not not keeping keep-alive so every request are on it's own. so mixing in that way is plus. if you are using microsoft only for validator then you are doing seperate connection with google server for each request.
Also consider when using Google CDN that some times people make typos such as ajax.googelapis.com. This could potentially create a really nasty xss (cross site scripting) attack. I have actually tested this out by registering a googlapis.com typo and very quickly found myself serving requests for javascript, maps, css etc. I emailed Google and asked them to register similar CDN typo URL's but have not heard back. This could be a real reason not to rely on CDN's because there are potentially dangerous attackers awaiting the typo requests and can easily serve back jquery etc with an xss payload. Thank you
1,447,184
Does it actually matter which CDN you use to link to your jquery file or any javascript file for that matter. Is one potentially faster than the other? What other factors could play a role in which cdn you decide to use? I know that Microsoft, Yahoo, and Google all have CDN's now.
2009/09/18
[ "https://Stackoverflow.com/questions/1447184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33690/" ]
It probably doesn't matter, but you could validate this with some A/B testing. Send half of your traffic to one CDN, and half to the other, and set up some profiling to measure the response. I would think it more important to be able to switch easily in case one or the other had some serious unavailability issues.
As stated by [Pingdom](http://royal.pingdom.com/2010/05/11/cdn-performance-downloading-jquery-from-google-microsoft-and-edgecast-cdns/): > > When someone visits your site, if they have already visited another > site that uses the same jQuery file on the same CDN, the file will > have been cached and doesn’t need to be downloaded at all. It can’t > get any faster than that. > > > This means that the most widely used CDN will have the odds on its > side, which can pay off for your site. > > > A few observations on performance: > Google’s CDN is consistently the slowest of the three both in North America and Europe. In Europe, Microsoft’s CDN is the fastest. > > >
1,447,184
Does it actually matter which CDN you use to link to your jquery file or any javascript file for that matter. Is one potentially faster than the other? What other factors could play a role in which cdn you decide to use? I know that Microsoft, Yahoo, and Google all have CDN's now.
2009/09/18
[ "https://Stackoverflow.com/questions/1447184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33690/" ]
As stated by [Pingdom](http://royal.pingdom.com/2010/05/11/cdn-performance-downloading-jquery-from-google-microsoft-and-edgecast-cdns/): > > When someone visits your site, if they have already visited another > site that uses the same jQuery file on the same CDN, the file will > have been cached and doesn’t need to be downloaded at all. It can’t > get any faster than that. > > > This means that the most widely used CDN will have the odds on its > side, which can pay off for your site. > > > A few observations on performance: > Google’s CDN is consistently the slowest of the three both in North America and Europe. In Europe, Microsoft’s CDN is the fastest. > > >
Depending which industry the application targets, you may not want to use a CDN managed by other organisations. It often raises issues regarding to compliance, privacy and confidentiality. For example, when you include Google Analytics in a secure application, the browser still sends the current URL as the "referer" header. Any identifiers, say a session id or secret token may appear in their logs. For example, if a client IP of 192.0.2.5references <https://healthsystem.example/condition/impotence>, then well, you can infer information which is considered to be rather private. Other cases include information of consequence, such as an account number, social security number or session information in the URL. That sort of data should never be in the URL as it can be used outside of the application. While you may trust Google, Microsoft or Yahoo, your users may not. For industries like Finance, Legal and Health Care, you may want to establish your own CDN with the help of a vendor (e.g. Akamai) with which you can sign a BAA.
1,447,184
Does it actually matter which CDN you use to link to your jquery file or any javascript file for that matter. Is one potentially faster than the other? What other factors could play a role in which cdn you decide to use? I know that Microsoft, Yahoo, and Google all have CDN's now.
2009/09/18
[ "https://Stackoverflow.com/questions/1447184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33690/" ]
One minor thing to consider is that both companies offer slightly different "extra" libraries: * Microsoft is offering the **JQuery validation library** on their CDN, whereas Google is not (<http://www.asp.net/ajaxlibrary/cdn.ashx>) * Google is offering the **JQuery UI library** on their CDN, whereas Microsoft is not (<http://code.google.com/apis/ajaxlibs/documentation/>) Depending on your needs, this may be relevant.
My answer is bit different than others, I will go with microsoft if you need jquery validator which almost everyone need if you are using jquery. Microsoft CDN http connection is Keep-Alive which is big plus when you are requesting multiple items. So if you need jquery validation then use Microsoft CDN, even if you need jquery ui use microsoft because google not not keeping keep-alive so every request are on it's own. so mixing in that way is plus. if you are using microsoft only for validator then you are doing seperate connection with google server for each request.
1,447,184
Does it actually matter which CDN you use to link to your jquery file or any javascript file for that matter. Is one potentially faster than the other? What other factors could play a role in which cdn you decide to use? I know that Microsoft, Yahoo, and Google all have CDN's now.
2009/09/18
[ "https://Stackoverflow.com/questions/1447184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33690/" ]
Google will send you a jQuery version minified with their own software, this version is 6kb lighter than the standard minified version served by MS. Go for Google.
My answer is bit different than others, I will go with microsoft if you need jquery validator which almost everyone need if you are using jquery. Microsoft CDN http connection is Keep-Alive which is big plus when you are requesting multiple items. So if you need jquery validation then use Microsoft CDN, even if you need jquery ui use microsoft because google not not keeping keep-alive so every request are on it's own. so mixing in that way is plus. if you are using microsoft only for validator then you are doing seperate connection with google server for each request.
1,447,184
Does it actually matter which CDN you use to link to your jquery file or any javascript file for that matter. Is one potentially faster than the other? What other factors could play a role in which cdn you decide to use? I know that Microsoft, Yahoo, and Google all have CDN's now.
2009/09/18
[ "https://Stackoverflow.com/questions/1447184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33690/" ]
You should absolutely use the Google CDN for jQuery (and this is coming from a Microsoft-centric developer). It's simple statistics. Those who would consider using the MS CDN for jQuery will always be a minority. There are too many non-MS developers using jQuery who will use Google's and wouldn't consider using Microsoft's. Since [one of the big wins with a public CDN is improved caching](http://encosia.com/3-reasons-why-you-should-let-google-host-jquery-for-you/), splitting usage among multiple CDNs decreases the potential for that benefit.
Google will send you a jQuery version minified with their own software, this version is 6kb lighter than the standard minified version served by MS. Go for Google.
1,447,184
Does it actually matter which CDN you use to link to your jquery file or any javascript file for that matter. Is one potentially faster than the other? What other factors could play a role in which cdn you decide to use? I know that Microsoft, Yahoo, and Google all have CDN's now.
2009/09/18
[ "https://Stackoverflow.com/questions/1447184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33690/" ]
As stated by [Pingdom](http://royal.pingdom.com/2010/05/11/cdn-performance-downloading-jquery-from-google-microsoft-and-edgecast-cdns/): > > When someone visits your site, if they have already visited another > site that uses the same jQuery file on the same CDN, the file will > have been cached and doesn’t need to be downloaded at all. It can’t > get any faster than that. > > > This means that the most widely used CDN will have the odds on its > side, which can pay off for your site. > > > A few observations on performance: > Google’s CDN is consistently the slowest of the three both in North America and Europe. In Europe, Microsoft’s CDN is the fastest. > > >
I would advise that you base your usage on the general location of the users you're targeting. If your site is targeted for general public, then using Google's CDN would be a good choice. If your site is also targeted at China, then using Microsoft's CDN would be a better choice. I know from my experience, as Google's servers kept getting blocked by the Chinese government, rendering websites that uses them un-loadable. \*Note that you can of cos create region specific sites, e.g. cn.mysite.com to cater specifically for China, but if you're low on resources and time, its worth a consideration. Full list of Microsoft CDN here. <http://www.asp.net/ajaxlibrary/cdn.ashx> They have since renamed to **ajax.aspnetcdn.com**, which reduces the likelihood of blockage by firewall rules.
2,148,144
So let's say I have a red square image that turns green when the mouse goes over it, and it turns back to red when the mouse leaves the square. I then made a menu sort of thing with it so that when I hover on the square, it turns green and a rectangle appears below it. What I want to happen is this: After the rectangle appears and I move the mouse out of the square and over the rectangle, I want the square to remain green until I move the mouse out of the rectangle. How do I do this with jquery? The code i use is something like this: ``` $('.square').hover(function() { $(this).addClass('.green'); }, function() { $(this).addClass('.red'); }); $('.square').hover(function() { $(this).children('.rectangle').show(); }, function() { $(this).children('.rectangle').hide(); }); ```
2010/01/27
[ "https://Stackoverflow.com/questions/2148144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260205/" ]
You have just a few errors in your code. 1. You never remove any classes, you only try adding classes. This will only work once, and all subsequent tries won't do anything since jQuery will not add the same class twice to the same element. 2. You shouldn't use the dot syntax when adding classes. Just supply the class name by itself: jQuery: ``` $('.square').hover(function() { $(this).addClass('green'); $(this).children('.rectangle').show(); }, function() { $(this).removeClass('green'); $(this).children('.rectangle').hide(); }); ``` CSS: ``` /* Make sure .green comes after .red */ .red { background: red } .green { background: green } ```
If the menu is inside the square you can try something like this: ``` $('.square').bind("mouseenter",function(){ $(this).addClass('green'); $('.rectangle').show(); }); $('.square').bind("mouseleave",function(){ $(this).addClass('red'); $('.rectangle').hide(); }); ```
2,148,144
So let's say I have a red square image that turns green when the mouse goes over it, and it turns back to red when the mouse leaves the square. I then made a menu sort of thing with it so that when I hover on the square, it turns green and a rectangle appears below it. What I want to happen is this: After the rectangle appears and I move the mouse out of the square and over the rectangle, I want the square to remain green until I move the mouse out of the rectangle. How do I do this with jquery? The code i use is something like this: ``` $('.square').hover(function() { $(this).addClass('.green'); }, function() { $(this).addClass('.red'); }); $('.square').hover(function() { $(this).children('.rectangle').show(); }, function() { $(this).children('.rectangle').hide(); }); ```
2010/01/27
[ "https://Stackoverflow.com/questions/2148144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260205/" ]
I have recently had the same problem. What I did was adding an `mouseenter` event to the "child" element too so while passing from parent to child it's not turned off. Basically I have `mouseenter` and `mouseleave` on both elements (which of course are slightly overlapping for this to work).
If the menu is inside the square you can try something like this: ``` $('.square').bind("mouseenter",function(){ $(this).addClass('green'); $('.rectangle').show(); }); $('.square').bind("mouseleave",function(){ $(this).addClass('red'); $('.rectangle').hide(); }); ```
2,148,144
So let's say I have a red square image that turns green when the mouse goes over it, and it turns back to red when the mouse leaves the square. I then made a menu sort of thing with it so that when I hover on the square, it turns green and a rectangle appears below it. What I want to happen is this: After the rectangle appears and I move the mouse out of the square and over the rectangle, I want the square to remain green until I move the mouse out of the rectangle. How do I do this with jquery? The code i use is something like this: ``` $('.square').hover(function() { $(this).addClass('.green'); }, function() { $(this).addClass('.red'); }); $('.square').hover(function() { $(this).children('.rectangle').show(); }, function() { $(this).children('.rectangle').hide(); }); ```
2010/01/27
[ "https://Stackoverflow.com/questions/2148144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260205/" ]
You have just a few errors in your code. 1. You never remove any classes, you only try adding classes. This will only work once, and all subsequent tries won't do anything since jQuery will not add the same class twice to the same element. 2. You shouldn't use the dot syntax when adding classes. Just supply the class name by itself: jQuery: ``` $('.square').hover(function() { $(this).addClass('green'); $(this).children('.rectangle').show(); }, function() { $(this).removeClass('green'); $(this).children('.rectangle').hide(); }); ``` CSS: ``` /* Make sure .green comes after .red */ .red { background: red } .green { background: green } ```
I have recently had the same problem. What I did was adding an `mouseenter` event to the "child" element too so while passing from parent to child it's not turned off. Basically I have `mouseenter` and `mouseleave` on both elements (which of course are slightly overlapping for this to work).
3,103,982
This Java code lists files in a directory on a Windows shared drive. Will it work correctly on a Unix system? ``` File directory = new File("\\\\server/Shared/stuff/mystuff"); for (File file: directory.listFiles()) { System.out.println(file); } ```
2010/06/23
[ "https://Stackoverflow.com/questions/3103982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/374479/" ]
Short answer: No. Long answer: Do you have samba installed? Even then you need to mount the the share. So it probably won't work. **EDIT** Java delegates the call to the underlying OS eventually. Since Unix doesn't know what the `\\SERVERNAME` path means, Java doesn't know what it means either. What you have to do, to get this to work is mount the drive explicitly using Samba. Your other option, if you are running Ubuntu, is look under `.gvfs` in your `home` directory. Ubuntu creates a mount there for your Samba shares, which you should be able to access using Java. If you don't want to rely on external tools, try [JCIFS](http://jcifs.samba.org/) for a pure-Java solution.
No, as that is a UNC Path, which is a windowsism. Are you trying to access a windows share from unix? Then have a look at [jcifs](http://jcifs.samba.org/).
3,103,982
This Java code lists files in a directory on a Windows shared drive. Will it work correctly on a Unix system? ``` File directory = new File("\\\\server/Shared/stuff/mystuff"); for (File file: directory.listFiles()) { System.out.println(file); } ```
2010/06/23
[ "https://Stackoverflow.com/questions/3103982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/374479/" ]
Short answer: No. Long answer: Do you have samba installed? Even then you need to mount the the share. So it probably won't work. **EDIT** Java delegates the call to the underlying OS eventually. Since Unix doesn't know what the `\\SERVERNAME` path means, Java doesn't know what it means either. What you have to do, to get this to work is mount the drive explicitly using Samba. Your other option, if you are running Ubuntu, is look under `.gvfs` in your `home` directory. Ubuntu creates a mount there for your Samba shares, which you should be able to access using Java. If you don't want to rely on external tools, try [JCIFS](http://jcifs.samba.org/) for a pure-Java solution.
On my system (Debian Sid with Gnome 2.30 Desktop) I have to select "smb:///server/Shared/..." to achieve the same behaviour. I think, that GVFS (Gnome Virtual File System) using smbfs drivers handles the real connection in the background...
3,103,982
This Java code lists files in a directory on a Windows shared drive. Will it work correctly on a Unix system? ``` File directory = new File("\\\\server/Shared/stuff/mystuff"); for (File file: directory.listFiles()) { System.out.println(file); } ```
2010/06/23
[ "https://Stackoverflow.com/questions/3103982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/374479/" ]
Short answer: No. Long answer: Do you have samba installed? Even then you need to mount the the share. So it probably won't work. **EDIT** Java delegates the call to the underlying OS eventually. Since Unix doesn't know what the `\\SERVERNAME` path means, Java doesn't know what it means either. What you have to do, to get this to work is mount the drive explicitly using Samba. Your other option, if you are running Ubuntu, is look under `.gvfs` in your `home` directory. Ubuntu creates a mount there for your Samba shares, which you should be able to access using Java. If you don't want to rely on external tools, try [JCIFS](http://jcifs.samba.org/) for a pure-Java solution.
No... Just let the user select the right path and use an OS dependent file-selection dialog.
3,103,982
This Java code lists files in a directory on a Windows shared drive. Will it work correctly on a Unix system? ``` File directory = new File("\\\\server/Shared/stuff/mystuff"); for (File file: directory.listFiles()) { System.out.println(file); } ```
2010/06/23
[ "https://Stackoverflow.com/questions/3103982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/374479/" ]
Short answer: No. Long answer: Do you have samba installed? Even then you need to mount the the share. So it probably won't work. **EDIT** Java delegates the call to the underlying OS eventually. Since Unix doesn't know what the `\\SERVERNAME` path means, Java doesn't know what it means either. What you have to do, to get this to work is mount the drive explicitly using Samba. Your other option, if you are running Ubuntu, is look under `.gvfs` in your `home` directory. Ubuntu creates a mount there for your Samba shares, which you should be able to access using Java. If you don't want to rely on external tools, try [JCIFS](http://jcifs.samba.org/) for a pure-Java solution.
The counter question I get when seeing this is: "Why would you want to hard-code a path in your application?" Even if it was just for the example and you intend to load the path from a property file or anything, I still think you are on the wrong track here. First of all you will want to avoid absolute paths like the plague. Relative paths are sort of ok. You can use slash ('/') characters in paths hardcoded, it will work on both Windows and Linux/Mac. Basically all platforms. Second of all, why use paths at all? This is the internet age. Use URL's! file: URL's will accomplish the same thing as file paths, but using URL's make your app accept resources from other sources such as web sites and FTP as well. Third of all, avoid the File class. If you invent a good way to do that, you are out of the woodworks completely. Use URL's together with getResource and getResourceAsStream and your app will work platform independent and across network boundaries over the internet.
3,103,982
This Java code lists files in a directory on a Windows shared drive. Will it work correctly on a Unix system? ``` File directory = new File("\\\\server/Shared/stuff/mystuff"); for (File file: directory.listFiles()) { System.out.println(file); } ```
2010/06/23
[ "https://Stackoverflow.com/questions/3103982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/374479/" ]
On my system (Debian Sid with Gnome 2.30 Desktop) I have to select "smb:///server/Shared/..." to achieve the same behaviour. I think, that GVFS (Gnome Virtual File System) using smbfs drivers handles the real connection in the background...
No, as that is a UNC Path, which is a windowsism. Are you trying to access a windows share from unix? Then have a look at [jcifs](http://jcifs.samba.org/).
3,103,982
This Java code lists files in a directory on a Windows shared drive. Will it work correctly on a Unix system? ``` File directory = new File("\\\\server/Shared/stuff/mystuff"); for (File file: directory.listFiles()) { System.out.println(file); } ```
2010/06/23
[ "https://Stackoverflow.com/questions/3103982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/374479/" ]
No... Just let the user select the right path and use an OS dependent file-selection dialog.
No, as that is a UNC Path, which is a windowsism. Are you trying to access a windows share from unix? Then have a look at [jcifs](http://jcifs.samba.org/).
3,103,982
This Java code lists files in a directory on a Windows shared drive. Will it work correctly on a Unix system? ``` File directory = new File("\\\\server/Shared/stuff/mystuff"); for (File file: directory.listFiles()) { System.out.println(file); } ```
2010/06/23
[ "https://Stackoverflow.com/questions/3103982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/374479/" ]
On my system (Debian Sid with Gnome 2.30 Desktop) I have to select "smb:///server/Shared/..." to achieve the same behaviour. I think, that GVFS (Gnome Virtual File System) using smbfs drivers handles the real connection in the background...
The counter question I get when seeing this is: "Why would you want to hard-code a path in your application?" Even if it was just for the example and you intend to load the path from a property file or anything, I still think you are on the wrong track here. First of all you will want to avoid absolute paths like the plague. Relative paths are sort of ok. You can use slash ('/') characters in paths hardcoded, it will work on both Windows and Linux/Mac. Basically all platforms. Second of all, why use paths at all? This is the internet age. Use URL's! file: URL's will accomplish the same thing as file paths, but using URL's make your app accept resources from other sources such as web sites and FTP as well. Third of all, avoid the File class. If you invent a good way to do that, you are out of the woodworks completely. Use URL's together with getResource and getResourceAsStream and your app will work platform independent and across network boundaries over the internet.
3,103,982
This Java code lists files in a directory on a Windows shared drive. Will it work correctly on a Unix system? ``` File directory = new File("\\\\server/Shared/stuff/mystuff"); for (File file: directory.listFiles()) { System.out.println(file); } ```
2010/06/23
[ "https://Stackoverflow.com/questions/3103982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/374479/" ]
No... Just let the user select the right path and use an OS dependent file-selection dialog.
The counter question I get when seeing this is: "Why would you want to hard-code a path in your application?" Even if it was just for the example and you intend to load the path from a property file or anything, I still think you are on the wrong track here. First of all you will want to avoid absolute paths like the plague. Relative paths are sort of ok. You can use slash ('/') characters in paths hardcoded, it will work on both Windows and Linux/Mac. Basically all platforms. Second of all, why use paths at all? This is the internet age. Use URL's! file: URL's will accomplish the same thing as file paths, but using URL's make your app accept resources from other sources such as web sites and FTP as well. Third of all, avoid the File class. If you invent a good way to do that, you are out of the woodworks completely. Use URL's together with getResource and getResourceAsStream and your app will work platform independent and across network boundaries over the internet.
450,464
I'm writing in C# the next generation of an old app originally written in Delphi. I often have to look in the old code and wondered if there's anyway to install Pascal syntax highlighting in the Visual Studio 2008 editor. TIA.
2009/01/16
[ "https://Stackoverflow.com/questions/450464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12379/" ]
Why don't you accept IDbConnection instead of connectionstring to your ctor?
Maybe... ``` class SmartDbConnection<T> where T : IDbConnection, new() { private readonly IDbConnection Connection; public SmartDbConnection(string connectionString) { if (connectionString.Contains("MultipleActiveResultSets=true")) { Connection = new T(); Connection.ConnectionString = connectionString; } } } ``` EDIT: But what [kaanbardak](https://stackoverflow.com/users/53378/kaanbardak) suggests can be even better...
450,464
I'm writing in C# the next generation of an old app originally written in Delphi. I often have to look in the old code and wondered if there's anyway to install Pascal syntax highlighting in the Visual Studio 2008 editor. TIA.
2009/01/16
[ "https://Stackoverflow.com/questions/450464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12379/" ]
Why don't you accept IDbConnection instead of connectionstring to your ctor?
If you don't want to specify SqlConnection there, where would you specify it - and how would you know to use it only if the connection string contains "MultipleActiveResultSets=true"? I suspect at some level you want a connection factory - either a `Func<string, IDbConnection>` you can pass in or set somewhere, or possibly just a class: ``` public static class ConnectionFactory { public static IDbConnection CreateConnection(string connectionString) { // Hard-code stuff here } } ``` Of course, they're just two sides of the same coin - ConnectionFactory is just a static implementation of the `Func<string, IDbConnection>`.
450,464
I'm writing in C# the next generation of an old app originally written in Delphi. I often have to look in the old code and wondered if there's anyway to install Pascal syntax highlighting in the Visual Studio 2008 editor. TIA.
2009/01/16
[ "https://Stackoverflow.com/questions/450464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12379/" ]
First - I've added `IDisposable` to this, as I believe it is important. Second, note that providers are an alternative here: ``` class SmartDbConnection { private DbConnection Connection; public SmartDbConnection(string provider, string connectionString) { Connection = DbProviderFactories.GetFactory(provider) .CreateConnection(); Connection.ConnectionString = connectionString; } public void Dispose() { if (Connection != null) { Connection.Dispose(); Connection = null; } } } ``` If you must go generic, how about: ``` class SmartDbConnection<T> : IDisposable where T : class, IDbConnection, new() { private T Connection; public SmartDbConnection(string connectionString) { T t = new T(); t.ConnectionString = connectionString; // etc } public void Dispose() { if (Connection != null) { Connection.Dispose(); Connection = null; } } } ```
Why don't you accept IDbConnection instead of connectionstring to your ctor?
450,464
I'm writing in C# the next generation of an old app originally written in Delphi. I often have to look in the old code and wondered if there's anyway to install Pascal syntax highlighting in the Visual Studio 2008 editor. TIA.
2009/01/16
[ "https://Stackoverflow.com/questions/450464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12379/" ]
Why don't you accept IDbConnection instead of connectionstring to your ctor?
``` class SmartDbConnection<T> where T: IDbConnection , new() { private readonly T Connection; public SmartDbConnection(string ConnectionString) { if (ConnectionString.Contains("MultipleActiveResultSets=true")) { Connection = new T(); Connection.ConnectionString = ConnectionString; } } } ```
450,464
I'm writing in C# the next generation of an old app originally written in Delphi. I often have to look in the old code and wondered if there's anyway to install Pascal syntax highlighting in the Visual Studio 2008 editor. TIA.
2009/01/16
[ "https://Stackoverflow.com/questions/450464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12379/" ]
Maybe... ``` class SmartDbConnection<T> where T : IDbConnection, new() { private readonly IDbConnection Connection; public SmartDbConnection(string connectionString) { if (connectionString.Contains("MultipleActiveResultSets=true")) { Connection = new T(); Connection.ConnectionString = connectionString; } } } ``` EDIT: But what [kaanbardak](https://stackoverflow.com/users/53378/kaanbardak) suggests can be even better...
If you don't want to specify SqlConnection there, where would you specify it - and how would you know to use it only if the connection string contains "MultipleActiveResultSets=true"? I suspect at some level you want a connection factory - either a `Func<string, IDbConnection>` you can pass in or set somewhere, or possibly just a class: ``` public static class ConnectionFactory { public static IDbConnection CreateConnection(string connectionString) { // Hard-code stuff here } } ``` Of course, they're just two sides of the same coin - ConnectionFactory is just a static implementation of the `Func<string, IDbConnection>`.
450,464
I'm writing in C# the next generation of an old app originally written in Delphi. I often have to look in the old code and wondered if there's anyway to install Pascal syntax highlighting in the Visual Studio 2008 editor. TIA.
2009/01/16
[ "https://Stackoverflow.com/questions/450464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12379/" ]
First - I've added `IDisposable` to this, as I believe it is important. Second, note that providers are an alternative here: ``` class SmartDbConnection { private DbConnection Connection; public SmartDbConnection(string provider, string connectionString) { Connection = DbProviderFactories.GetFactory(provider) .CreateConnection(); Connection.ConnectionString = connectionString; } public void Dispose() { if (Connection != null) { Connection.Dispose(); Connection = null; } } } ``` If you must go generic, how about: ``` class SmartDbConnection<T> : IDisposable where T : class, IDbConnection, new() { private T Connection; public SmartDbConnection(string connectionString) { T t = new T(); t.ConnectionString = connectionString; // etc } public void Dispose() { if (Connection != null) { Connection.Dispose(); Connection = null; } } } ```
Maybe... ``` class SmartDbConnection<T> where T : IDbConnection, new() { private readonly IDbConnection Connection; public SmartDbConnection(string connectionString) { if (connectionString.Contains("MultipleActiveResultSets=true")) { Connection = new T(); Connection.ConnectionString = connectionString; } } } ``` EDIT: But what [kaanbardak](https://stackoverflow.com/users/53378/kaanbardak) suggests can be even better...
450,464
I'm writing in C# the next generation of an old app originally written in Delphi. I often have to look in the old code and wondered if there's anyway to install Pascal syntax highlighting in the Visual Studio 2008 editor. TIA.
2009/01/16
[ "https://Stackoverflow.com/questions/450464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12379/" ]
Maybe... ``` class SmartDbConnection<T> where T : IDbConnection, new() { private readonly IDbConnection Connection; public SmartDbConnection(string connectionString) { if (connectionString.Contains("MultipleActiveResultSets=true")) { Connection = new T(); Connection.ConnectionString = connectionString; } } } ``` EDIT: But what [kaanbardak](https://stackoverflow.com/users/53378/kaanbardak) suggests can be even better...
``` class SmartDbConnection<T> where T: IDbConnection , new() { private readonly T Connection; public SmartDbConnection(string ConnectionString) { if (ConnectionString.Contains("MultipleActiveResultSets=true")) { Connection = new T(); Connection.ConnectionString = ConnectionString; } } } ```
450,464
I'm writing in C# the next generation of an old app originally written in Delphi. I often have to look in the old code and wondered if there's anyway to install Pascal syntax highlighting in the Visual Studio 2008 editor. TIA.
2009/01/16
[ "https://Stackoverflow.com/questions/450464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12379/" ]
First - I've added `IDisposable` to this, as I believe it is important. Second, note that providers are an alternative here: ``` class SmartDbConnection { private DbConnection Connection; public SmartDbConnection(string provider, string connectionString) { Connection = DbProviderFactories.GetFactory(provider) .CreateConnection(); Connection.ConnectionString = connectionString; } public void Dispose() { if (Connection != null) { Connection.Dispose(); Connection = null; } } } ``` If you must go generic, how about: ``` class SmartDbConnection<T> : IDisposable where T : class, IDbConnection, new() { private T Connection; public SmartDbConnection(string connectionString) { T t = new T(); t.ConnectionString = connectionString; // etc } public void Dispose() { if (Connection != null) { Connection.Dispose(); Connection = null; } } } ```
If you don't want to specify SqlConnection there, where would you specify it - and how would you know to use it only if the connection string contains "MultipleActiveResultSets=true"? I suspect at some level you want a connection factory - either a `Func<string, IDbConnection>` you can pass in or set somewhere, or possibly just a class: ``` public static class ConnectionFactory { public static IDbConnection CreateConnection(string connectionString) { // Hard-code stuff here } } ``` Of course, they're just two sides of the same coin - ConnectionFactory is just a static implementation of the `Func<string, IDbConnection>`.
450,464
I'm writing in C# the next generation of an old app originally written in Delphi. I often have to look in the old code and wondered if there's anyway to install Pascal syntax highlighting in the Visual Studio 2008 editor. TIA.
2009/01/16
[ "https://Stackoverflow.com/questions/450464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12379/" ]
If you don't want to specify SqlConnection there, where would you specify it - and how would you know to use it only if the connection string contains "MultipleActiveResultSets=true"? I suspect at some level you want a connection factory - either a `Func<string, IDbConnection>` you can pass in or set somewhere, or possibly just a class: ``` public static class ConnectionFactory { public static IDbConnection CreateConnection(string connectionString) { // Hard-code stuff here } } ``` Of course, they're just two sides of the same coin - ConnectionFactory is just a static implementation of the `Func<string, IDbConnection>`.
``` class SmartDbConnection<T> where T: IDbConnection , new() { private readonly T Connection; public SmartDbConnection(string ConnectionString) { if (ConnectionString.Contains("MultipleActiveResultSets=true")) { Connection = new T(); Connection.ConnectionString = ConnectionString; } } } ```
450,464
I'm writing in C# the next generation of an old app originally written in Delphi. I often have to look in the old code and wondered if there's anyway to install Pascal syntax highlighting in the Visual Studio 2008 editor. TIA.
2009/01/16
[ "https://Stackoverflow.com/questions/450464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12379/" ]
First - I've added `IDisposable` to this, as I believe it is important. Second, note that providers are an alternative here: ``` class SmartDbConnection { private DbConnection Connection; public SmartDbConnection(string provider, string connectionString) { Connection = DbProviderFactories.GetFactory(provider) .CreateConnection(); Connection.ConnectionString = connectionString; } public void Dispose() { if (Connection != null) { Connection.Dispose(); Connection = null; } } } ``` If you must go generic, how about: ``` class SmartDbConnection<T> : IDisposable where T : class, IDbConnection, new() { private T Connection; public SmartDbConnection(string connectionString) { T t = new T(); t.ConnectionString = connectionString; // etc } public void Dispose() { if (Connection != null) { Connection.Dispose(); Connection = null; } } } ```
``` class SmartDbConnection<T> where T: IDbConnection , new() { private readonly T Connection; public SmartDbConnection(string ConnectionString) { if (ConnectionString.Contains("MultipleActiveResultSets=true")) { Connection = new T(); Connection.ConnectionString = ConnectionString; } } } ```
2,943,735
I'm trying to read first row from the `file` ``` > source ./rank file ``` using this script ``` set line = ($<) <- inside rank ``` but when I enter `echo $line` I receive nothing, how can I change it? thanks in advance
2010/05/31
[ "https://Stackoverflow.com/questions/2943735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348275/" ]
Since csh is brain-dead, you'll have to do something like this: ``` set line = `head -n 1 filename` ```
It's built-in in Bash as: ``` read -r line < filename ```
2,943,735
I'm trying to read first row from the `file` ``` > source ./rank file ``` using this script ``` set line = ($<) <- inside rank ``` but when I enter `echo $line` I receive nothing, how can I change it? thanks in advance
2010/05/31
[ "https://Stackoverflow.com/questions/2943735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348275/" ]
Since csh is brain-dead, you'll have to do something like this: ``` set line = `head -n 1 filename` ```
``` set line = `cat file | sed 1q` ```
1,728,477
I though it'll be interesting to look at threads and queues, so I've written 2 scripts, one will break a file up and encrypt each chunk in a thread, the other will do it serially. I'm still very new to python and don't really know why the treading script takes so much longer. Threaded Script: ``` #!/usr/bin/env python from Crypto.Cipher import AES from optparse import OptionParser import os, base64, time, sys, hashlib, pickle, threading, timeit, Queue BLOCK_SIZE = 32 #32 = 256-bit | 16 = 128-bit TFILE = 'mytestfile.bin' CHUNK_SIZE = 2048 * 2048 KEY = os.urandom(32) class DataSplit(): def __init__(self,fileObj, chunkSize): self.fileObj = fileObj self.chunkSize = chunkSize def split(self): while True: data = self.fileObj.read(self.chunkSize) if not data: break yield data class encThread(threading.Thread): def __init__(self, seg_queue,result_queue, cipher): threading.Thread.__init__(self) self.seg_queue = seg_queue self.result_queue = result_queue self.cipher = cipher def run(self): while True: #Grab a data segment from the queue data = self.seg_queue.get() encSegment = [] for lines in data: encSegment.append(self.cipher.encrypt(lines)) self.result_queue.put(encSegment) print "Segment Encrypted" self.seg_queue.task_done() start = time.time() def main(): seg_queue = Queue.Queue() result_queue = Queue.Queue() estSegCount = (os.path.getsize(TFILE)/CHUNK_SIZE)+1 cipher = AES.new(KEY, AES.MODE_CFB) #Spawn threads (one for each segment at the moment) for i in range(estSegCount): eT = encThread(seg_queue, result_queue, cipher) eT.setDaemon(True) eT.start() print ("thread spawned") fileObj = open(TFILE, "rb") splitter = DataSplit(fileObj, CHUNK_SIZE) for data in splitter.split(): seg_queue.put(data) print ("Data sent to thread") seg_queue.join() #result_queue.join() print ("Seg Q: {0}".format(seg_queue.qsize())) print ("Res Q: {0}".format(result_queue.qsize())) main() print ("Elapsed Time: {0}".format(time.time()-start)) ``` Serial Script: ``` #!/usr/bin/env python from Crypto.Cipher import AES from optparse import OptionParser import os, base64, time, sys, hashlib, pickle, threading, timeit, Queue TFILE = 'mytestfile.bin' CHUNK_SIZE = 2048 * 2048 class EncSeries(): def __init(self): pass def loadFile(self,path): openFile = open(path, "rb") #fileData = openFile.readlines() fileData = openFile.read(CHUNK_SIZE) openFile.close() return fileData def encryptData(self,key, data): cipher = AES.new(key, AES.MODE_CFB) newData = [] for lines in data: newData.append(cipher.encrypt(lines)) return newData start = time.time() def main(): print ("Start") key = os.urandom(32) run = EncSeries() fileData = run.loadFile(TFILE) encFileData=run.encryptData(key, fileData) print("Finish") main() print ("Elapsed Time: {0}".format(time.time()-start)) ``` using readlines() instead of read seems to speed things up considerably on the serial version too, but it's already much fast than the threaded version.
2009/11/13
[ "https://Stackoverflow.com/questions/1728477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200822/" ]
1. It seems like your second version only reads one chunk, while the first version reads the whole file - this would explain the big speedup. **Edit**: Another issue: I just noticed that you run `for lines in data` for no reason - this would actually encrypt the characters individually, which is much slower. Instead, just pass the data to `encrypt` directly. 2. There is no point in starting more CPU-heavy threads than you have processor cores. 3. The threads can only work in parallel if they call an extension module which unlocks the GIL while running. I don't think PyCrypto does this, so you won't get any parallel work done here. 4. If the bottleneck was disk performance, you wouldn't see much of an improvement here anyway - in that case it would be better to have one thread that does disk I/O and another to do the encryption. GIL wouldn't be an issue since it is released while doing disk I/O.
Threads are not a magical way to speed up programs - splitting work into threads will usually slow it down unless the program is spending a significant part of its time waiting for I/O. Each new thread adds more overhead to the code in splitting the work up, and more overhead in the OS in switching between threads. In theory if you are running on a multi-processor CPU then the threads could be run on different processors so the work is done in parallel, but even then there is no point in having more threads than processors. In practice it is quite different, at least for the C version of Python. The GIL does not work well at all with multiple processors. See this [presentation](http://blip.tv/file/2232410/) by David Beazley for the reasons why. IronPython and Jython do not have this problem. If you really want to parallelize the work then it is better to spawn multiple processes and farm the work out to them, but there is the possibility that the inter-process communication overhead of passing around large blocks of data will negate any benefit of parallelism.
1,728,477
I though it'll be interesting to look at threads and queues, so I've written 2 scripts, one will break a file up and encrypt each chunk in a thread, the other will do it serially. I'm still very new to python and don't really know why the treading script takes so much longer. Threaded Script: ``` #!/usr/bin/env python from Crypto.Cipher import AES from optparse import OptionParser import os, base64, time, sys, hashlib, pickle, threading, timeit, Queue BLOCK_SIZE = 32 #32 = 256-bit | 16 = 128-bit TFILE = 'mytestfile.bin' CHUNK_SIZE = 2048 * 2048 KEY = os.urandom(32) class DataSplit(): def __init__(self,fileObj, chunkSize): self.fileObj = fileObj self.chunkSize = chunkSize def split(self): while True: data = self.fileObj.read(self.chunkSize) if not data: break yield data class encThread(threading.Thread): def __init__(self, seg_queue,result_queue, cipher): threading.Thread.__init__(self) self.seg_queue = seg_queue self.result_queue = result_queue self.cipher = cipher def run(self): while True: #Grab a data segment from the queue data = self.seg_queue.get() encSegment = [] for lines in data: encSegment.append(self.cipher.encrypt(lines)) self.result_queue.put(encSegment) print "Segment Encrypted" self.seg_queue.task_done() start = time.time() def main(): seg_queue = Queue.Queue() result_queue = Queue.Queue() estSegCount = (os.path.getsize(TFILE)/CHUNK_SIZE)+1 cipher = AES.new(KEY, AES.MODE_CFB) #Spawn threads (one for each segment at the moment) for i in range(estSegCount): eT = encThread(seg_queue, result_queue, cipher) eT.setDaemon(True) eT.start() print ("thread spawned") fileObj = open(TFILE, "rb") splitter = DataSplit(fileObj, CHUNK_SIZE) for data in splitter.split(): seg_queue.put(data) print ("Data sent to thread") seg_queue.join() #result_queue.join() print ("Seg Q: {0}".format(seg_queue.qsize())) print ("Res Q: {0}".format(result_queue.qsize())) main() print ("Elapsed Time: {0}".format(time.time()-start)) ``` Serial Script: ``` #!/usr/bin/env python from Crypto.Cipher import AES from optparse import OptionParser import os, base64, time, sys, hashlib, pickle, threading, timeit, Queue TFILE = 'mytestfile.bin' CHUNK_SIZE = 2048 * 2048 class EncSeries(): def __init(self): pass def loadFile(self,path): openFile = open(path, "rb") #fileData = openFile.readlines() fileData = openFile.read(CHUNK_SIZE) openFile.close() return fileData def encryptData(self,key, data): cipher = AES.new(key, AES.MODE_CFB) newData = [] for lines in data: newData.append(cipher.encrypt(lines)) return newData start = time.time() def main(): print ("Start") key = os.urandom(32) run = EncSeries() fileData = run.loadFile(TFILE) encFileData=run.encryptData(key, fileData) print("Finish") main() print ("Elapsed Time: {0}".format(time.time()-start)) ``` using readlines() instead of read seems to speed things up considerably on the serial version too, but it's already much fast than the threaded version.
2009/11/13
[ "https://Stackoverflow.com/questions/1728477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200822/" ]
Threads are not a magical way to speed up programs - splitting work into threads will usually slow it down unless the program is spending a significant part of its time waiting for I/O. Each new thread adds more overhead to the code in splitting the work up, and more overhead in the OS in switching between threads. In theory if you are running on a multi-processor CPU then the threads could be run on different processors so the work is done in parallel, but even then there is no point in having more threads than processors. In practice it is quite different, at least for the C version of Python. The GIL does not work well at all with multiple processors. See this [presentation](http://blip.tv/file/2232410/) by David Beazley for the reasons why. IronPython and Jython do not have this problem. If you really want to parallelize the work then it is better to spawn multiple processes and farm the work out to them, but there is the possibility that the inter-process communication overhead of passing around large blocks of data will negate any benefit of parallelism.
Threads have a couple different uses: 1. They only provide speedup if they allow you to get multiple pieces of hardware working at the same time on your problem, whether that hardware is CPU cores or disk heads. 2. They allow you to keep track of multiple sequences of I/O events that would be much more complicated without them, such as simultaneous conversations with multiple users. The latter is not done for performance, but for clarity of code.
1,728,477
I though it'll be interesting to look at threads and queues, so I've written 2 scripts, one will break a file up and encrypt each chunk in a thread, the other will do it serially. I'm still very new to python and don't really know why the treading script takes so much longer. Threaded Script: ``` #!/usr/bin/env python from Crypto.Cipher import AES from optparse import OptionParser import os, base64, time, sys, hashlib, pickle, threading, timeit, Queue BLOCK_SIZE = 32 #32 = 256-bit | 16 = 128-bit TFILE = 'mytestfile.bin' CHUNK_SIZE = 2048 * 2048 KEY = os.urandom(32) class DataSplit(): def __init__(self,fileObj, chunkSize): self.fileObj = fileObj self.chunkSize = chunkSize def split(self): while True: data = self.fileObj.read(self.chunkSize) if not data: break yield data class encThread(threading.Thread): def __init__(self, seg_queue,result_queue, cipher): threading.Thread.__init__(self) self.seg_queue = seg_queue self.result_queue = result_queue self.cipher = cipher def run(self): while True: #Grab a data segment from the queue data = self.seg_queue.get() encSegment = [] for lines in data: encSegment.append(self.cipher.encrypt(lines)) self.result_queue.put(encSegment) print "Segment Encrypted" self.seg_queue.task_done() start = time.time() def main(): seg_queue = Queue.Queue() result_queue = Queue.Queue() estSegCount = (os.path.getsize(TFILE)/CHUNK_SIZE)+1 cipher = AES.new(KEY, AES.MODE_CFB) #Spawn threads (one for each segment at the moment) for i in range(estSegCount): eT = encThread(seg_queue, result_queue, cipher) eT.setDaemon(True) eT.start() print ("thread spawned") fileObj = open(TFILE, "rb") splitter = DataSplit(fileObj, CHUNK_SIZE) for data in splitter.split(): seg_queue.put(data) print ("Data sent to thread") seg_queue.join() #result_queue.join() print ("Seg Q: {0}".format(seg_queue.qsize())) print ("Res Q: {0}".format(result_queue.qsize())) main() print ("Elapsed Time: {0}".format(time.time()-start)) ``` Serial Script: ``` #!/usr/bin/env python from Crypto.Cipher import AES from optparse import OptionParser import os, base64, time, sys, hashlib, pickle, threading, timeit, Queue TFILE = 'mytestfile.bin' CHUNK_SIZE = 2048 * 2048 class EncSeries(): def __init(self): pass def loadFile(self,path): openFile = open(path, "rb") #fileData = openFile.readlines() fileData = openFile.read(CHUNK_SIZE) openFile.close() return fileData def encryptData(self,key, data): cipher = AES.new(key, AES.MODE_CFB) newData = [] for lines in data: newData.append(cipher.encrypt(lines)) return newData start = time.time() def main(): print ("Start") key = os.urandom(32) run = EncSeries() fileData = run.loadFile(TFILE) encFileData=run.encryptData(key, fileData) print("Finish") main() print ("Elapsed Time: {0}".format(time.time()-start)) ``` using readlines() instead of read seems to speed things up considerably on the serial version too, but it's already much fast than the threaded version.
2009/11/13
[ "https://Stackoverflow.com/questions/1728477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200822/" ]
Threads are not a magical way to speed up programs - splitting work into threads will usually slow it down unless the program is spending a significant part of its time waiting for I/O. Each new thread adds more overhead to the code in splitting the work up, and more overhead in the OS in switching between threads. In theory if you are running on a multi-processor CPU then the threads could be run on different processors so the work is done in parallel, but even then there is no point in having more threads than processors. In practice it is quite different, at least for the C version of Python. The GIL does not work well at all with multiple processors. See this [presentation](http://blip.tv/file/2232410/) by David Beazley for the reasons why. IronPython and Jython do not have this problem. If you really want to parallelize the work then it is better to spawn multiple processes and farm the work out to them, but there is the possibility that the inter-process communication overhead of passing around large blocks of data will negate any benefit of parallelism.
Just a quick note to update this thread: python 3.2 has a new implementation of the GIL which relieves a lot of the overheads associated with multithreading, but does not eliminate the locking. (i.e. it does not allow you to use more than one core, but it allows you to use multiple threads on that core efficiently).
YAML Metadata Warning: empty or missing yaml metadata in repo card (https://huggingface.co/docs/hub/datasets-cards)

StackExchange Paired 500K is a subset of lvwerra/stack-exchange-paired

which is a processed version of the HuggingFaceH4/stack-exchange-preferences. The following steps were applied: Parse HTML to Markdown with markdownify Create pairs (response_j, response_k) where j was rated better than k Sample at most 10 pairs per question Shuffle the dataset globally

This dataset is designed to be used for preference learning.


license: mit

Downloads last month
3
Edit dataset card