text
stringlengths
8
267k
meta
dict
Q: Haskell Graphics Programming in Linux/Unix I am interested in making a game in Haskell and I am looking for a graphics library. I found one called the HUGS Graphics Library but much to my dismay it only runs on Win32. I was wondering if there was a graphics library for Linux/Unix Haskell programming or am I out of luck. Thank you for reading. A: Do you know about hackage? Hosted on hackage are lots of graphics-related libraries. Low level OpenGL bindings (openglraw, glut, hgl, glfw), higher level special-purpose GL libraries (ex: gloss), 2D libraries (cairo, gtk, gd), and more. For 2D I suggest you see this related question. A: Raincat is a simple puzzle game written in Haskell that demonstrates graphics library usage and some strait forward techniques. Try looking up some Haskell SDL and OpenGL tutorials to help you in understanding the code. I am looking forward to playing your game. Regards, http://hackage.haskell.org/package/Raincat
{ "language": "en", "url": "https://stackoverflow.com/questions/7629774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why Am I Getting NaN (and not an answer)? I have this equation: val2 = ((((((((((Math.Pow(((previous_val) + (val5*100)), 1.001)) / 24) / 60) / 60) * 100) / 3600)*h)/m)*s)); previous_val and val5 are local variables that equal other values. The variables h, m, and s represent hours, minutes, and seconds. My problem: When both, m and s, are equivalent to 0, I get a NaN Instead of my answer. NaN was also achieved when h and m were equivalent to 0. What should I add into my code that will throw an exception? I'm sure that the reason for this 'not a number' "error" is that I am dividing by zero. A: A NaN is easy to produce: float f = 0.0f / 0; // NaN (note use of fp operand to promote / to fp) float g = f + 42; // NaN How do/can the zeros in h, m, and s cause that? Remember, once a NaN has been introduced, it will silently propagate through in most cases. (As others have suggested, breaking the problem up into smaller bite-size portions will aide in debugging -- and likely future maintainability ;-) While a final (or intermediate) IsNaN check will work to detect the scenario, consider checking/reacting to illegal inputs as well. (I am not sure if there is a way to get [the rare] signaling NaN in C#, which is different than the quiet NaN observed, but quick google searches say: not possible.) Happy coding. Although [standard] floating point operations will not throw an exception (as NaN is encoded as a floating point value), integer math operations may throw an exception (as NaN is not encoded). If the operations are such that integer math is sufficient then it can be used to "throw" an exception: int zero = 0; // to trick compiler int k = 42 / zero; // KABOOM! (DivideByZeroException) A: Floating point operations do not throw exceptions. Divide by zero will obviously not result in a valid answer and so you should check for this scenario before making the calculation. A: * *Simplify this expression into multiple sub-expressions, if possible. *Wrap in a "try/catch (DivideByZeroException ex)" block, if possible. *Most important, do your aritmetic in "double" (or "float") space, if possible (e.g. "24.0" instead of "24").
{ "language": "en", "url": "https://stackoverflow.com/questions/7629778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: ManyToManyField widget in a django admin change list? In the change list of the django admin, I want to use list_editable to display a django-autocomplete widget for a ManyToManyField. I found something similar here: list_editable and widgets Normally including a ManyToManyField in list_display raises an ImproperlyConfigured exception, eg: ""'BookAdmin.list_display[2]', 'author' is a ManyToManyField which is not supported." I (perhaps unwisely) removed 3 lines from contrib/admin/validate.py to bypass the exception. :) I now have it spitting out the following, which is close(?) but no cigar. <django.db.models.fields.related.ManyRelatedManager object at 0x1032a85d0> Any thoughts on how to proceed? Is there a better way of doing this? Here's what I have at the moment: (AuthorAutocomplete is working fine in the regular admin form) class AuthorAutocomplete(AutocompleteSettings): search_fields = ('first_name', 'last_name') class BookAdmin(AutocompleteAdmin, admin.ModelAdmin): def get_changelist_form(self, request, **kwargs): kwargs.setdefault('form', AuthorAutocompleteForm) return super(BookAdmin, self).get_changelist_form(request, **kwargs) list_display = ['isbn', 'title', 'author', 'publisher'] #... class AuthorAutocompleteForm(forms.ModelForm): class Meta: model = Book author = AuthorAutocomplete Thanks! A: To get the values for a ManyToMany field in your own code so you can display their values you can do the following. I'm using list_display as an example. class TestAdmin(admin.ModelAdmin): def get_some_value(self): return ", " . join([x.__str__() for x in self.manytomany_field.all()]) get_some_value.short_description = 'Title' # sets column header title list_display = ('get_some_value',) # define Model's fields to be presented on admin changelist where manytomany_field is the name you gave your manytomany_field and get_some_value is a method within the class which is assigned a short_description. A: Silly me. I thought that William's manytomany_field was a built-in ModelAdmin object. So I ran his code as is (after putting in the missing parenthesis after join). Strange to say, it ran without producing an error message. But (None) appeared when I was supposed to get values. And I thought it was strange that I couldn't find anything when I Googled "django model.Admin.manytomany_field". Hah! So eventually I realized that I was to put the NAME of the many-to-many field in place of manytomany_field. It works!
{ "language": "en", "url": "https://stackoverflow.com/questions/7629786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Msg 547, Level 16, State 0, Line 1 The INSERT statement conflicted with the FOREIGN KEY constraint Hey everyone I have been having a problem with my SQL database, specifically the foreign key. Here is the table I am trying to enter into. CREATE TABLE Employee ( EmployeeID int NOT NULL Primary Key, LastName varchar(30) NOT NULL, FirstName varchar(30) NOT NULL, Address varchar(30) NOT NULL, City varchar(20) NOT NULL, State char(2) NOT NULL, TelephoneAreacode char(5) NOT NULL, TelephoneNumber char(8) NOT NULL, JobTitle varchar(30) NOT NULL Foreign Key References Job_Title(JobTitle), EEO1Classification varchar(30) NOT NULL, HireDate char (10) NOT NULL, Salary money NOT NULL, Gender varchar(7) NOT NULL, Age int NOT NULL ) And the data INSERT INTO Employee VALUES ('95687', 'Edelman', 'Glenn', '175 Bishops Lane', 'LA Jolla', 'CA', '619', '5550199','Cashier', 'Sales Workers', '10/7/2003', '$21,500', 'Male', '64'), ('95688', 'McMullen', 'Eric', '763 Church ST', 'Lemm Grove', 'CA', '619', '5550135','Bagger', 'Sales Workers', '11/1/2002', '$12,500', 'Male', '20'), ('95995', 'Slentz', 'Raj', '123 Torrey DR', 'North Clairmont', 'CA', '619', '5550123','Assistant Manager', 'Officials & Managers', '6/1/2000', '$48,000', 'Male', '34'), ('55978', 'Broun', 'Erin', '2045 Parkway - Apt2B', 'Encinitas', 'CA', '760', '5550100', 'Bagger','Sales Workers', '3/12/2003', '$10,530', 'Female', '24'), ('55928', 'Carpenter', 'Donald', '927 Second St', 'Encinitas', 'CA', '760','5550154', 'Stocker','Office/Clerical', '11/1/2003', '$15,000', 'Male', '18'), ('59852', 'Esquivez', 'David', '10983 N. Coast Hwy Apt 902', 'Encinitas', 'CA', '760', '5550108','Butchers & Seafood Specialists', 'Operatives (Semi skilled)', '8/1/2003', '$19,000', 'Male', '22'), ('52362', 'Sharp', 'Nancy', '10793 Montecino RD', 'Ramona', 'CA', '858', '5550135', 'Cashier','Sales Workers', '7/12/2003', '$21,000', 'Female', '24'); The table with the foreign key is this one, CREATE TABLE Job_Title ( JobTitle varchar(30) NOT NULL Primary key, EEO1Classification varchar(30) NOT NULL, JobDescription varchar(100) NOT NULL, ExemptNonExempt varchar(30) NOT NULL, ) And the data already entered there is INSERT INTO Job_Title VALUES ('Accounting Clerk','Office/Clerical', 'Records Data', 'Non-Exempt'), ('Assistant Manager','Officials & Managers', 'Supervises and coordinates activities', 'Exempt'), ('Bagger','Sales Workers', 'Places customer orders in bags', 'Non-Exempt'), ('Cashier','Sales Workers', 'Operates cash register to itemize and total customer’s purchases', 'Non-Exempt'), ('Computer Support Specialist','Technician', 'Installs, modifies, and makes minor repairs to personal computers', 'Non-Exempt'), ('Dir. of Fin. & Acct.','Officials & Managers', 'Plans and directs the finance and accounting activities', 'Exempt'), ('Asst. - Bakery & Pastry','Craft Workers (Skilled)', 'Bakes Cakes and Pastries', 'Non-Exempt'), ('Butchers & Seafood Specialists','Operatives (Semi skilled)', 'Cuts Meat and seafood', 'Non-Exempt'), ('Stocker','Office/Clerical', 'Stocks Shelves', 'Non-Exempt'); Please help. A: Make sure that the values you are inserting in the table that contains the foreign key ( child table ) has a corresponding value in the table that contains the primary key (parent Table ) i,e you can not insert something into the child table that has no corresponding value in the parent table due to the pk -Fk relation ship A: Sometimes the error occurs due to the reason that the Child table does not have the corresponding values already present in the Parent table's column which is being referenced as the foreign key. To do: * *Truncating both the tables (make sure to backup the data if its bulky) could simply fix the problem. *Try entering values in the Child table that are existing already in the Parent table's column. Hope this would help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need to combine values from multiselect option to form a url with javascript I am using an application that allows real estate searching on my site. The app came with a very limited search functionality form, so I've taken it and tried to enhance it by way of URL parameters that the IDX solution provider provides. One of these parameters is to make a URL and combine multiple city names in order to search for listings in more than one city at a time. I've added a multi select field to the form, but the problem is that each city has to have a sequential number in between < > symbols. So the search would end up looking like this and the first city has to be number <0>: www.yourblog.com/idx/?idx-q-Cities<0>=Irvine&idx-q-Cities<1>=Laguna%20Beach I need a way tfor the options selected in the multiple select field to be combined to achieve the above result. Here is what the part of the form with the multi select looks like. <form action="http://www.mmysite.com/idx/" method="get" onsubmit="prepareSearchForm(this)"> <table> <tr> <th><label for="idx-q-Cities">Select Your Cities</label></th> <td> <select multiple name="idx-q-Cities" title="Type or select your cities"> <option id="idx-q-Cities" class="idx-q-Cities" value="Abbeville">Abbeville</option><br> <option id="idx-q-Cities" class="idx-q-Cities" value="Abilene">Abilene</option> </select> </tr> </table> </form> I had someone helping me try to get this to work, but it was unsuccessful. Here is what they came up with. Maybe it will help. <script> function prepareSearchForm(form){ var count = 0; $(form).children('.idx-q-Cities').each(function(i,o){ var cityDOM = document.createElement('select'); cityDOM.name = "idx-q-Cities<" + count++ + ">"; cityDOM.value = o.value; form.appendChild(cityDOM); }); return true; } </script> Any ideas on how to correct the above JS or another way to take the multi select options and combine them in order to end up with the URL above? A: Well, I'll offer you this: function prepareURL() { var vals = $('select option:selected').map( function(i){ return $(this).attr('class') + '<' + i + '>=' + $(this).val(); }).get().join(';'); var URL = 'www.yourblog.com/idx/' + vals; $('#urloutput').text(URL); } $('select').click( function() { prepareURL(); }); JS Fiddle demo. But I'm not sure if you want the first selected 'get' option to be 0 (whether that's Abeline or Abbeville), or if you want the Abbeville to always be the 0 option and Abeline to always be the 1 option. So I offer you an option based on that possibility too: function prepareURL() { var vals = $('select option:selected').map( function(){ return $(this).attr('class') + '<' + $(this).index('select option') + '>=' + $(this).val(); }).get().join(';'); var URL = 'www.yourblog.com/idx/' + vals; $('#urloutput').text(URL); } $('select').click( function() { prepareURL(); }); JS FIddle demo. Also, given that this appears to be a GET string, I can't help but feel you should have a ? in the URL somewhere. But I leave that to you to implement, in case you don't want it there, for some reason. And, as a (final?) addenda, I'd strongly suggest URL-encoding the vals variable before submitting it as a URL: var URL = 'www.yourblog.com/idx/' + encodeURIComponent(vals); $('#urloutput').text(URL); JS Fiddle demo. A: If you are using PHP then change: <select multiple name="idx-q-Cities" title="Type or select your cities"> To: <select multiple name="idx-q-Cities[]" title="Type or select your cities"> Your javascript is for sure wrong. Do this on the server end.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to serialize/deserialize an assembly object to and from a byte array Let's say a create an (executable) assembly in memory by compiling a code string. Then I want to serialize this assembly object into a byte array and then store it in a database. Then later on I want to retrieve the byte array from the database and deserialize the byte array back into an assembly object, then invoke the entry point of the assembly. At first I just tried to do this serialization like I would any other simple object in .net, however apparently that won't work with an assembly object. The assembly object contains a method called GetObjectData which gets serialization data necessary to reinstantiate the assembly. So I'm somewhat confused as to how I piece all this together for my scenario. The answer only needs to show how to take an assembly object, convert it into a byte array, convert that back into an assembly, then execute the entry method on the deserialized assembly. A: A dirty trick to get the assembly bytes using reflection: MethodInfo methodGetRawBytes = assembly.GetType().GetMethod("GetRawBytes", BindingFlags.Instance | BindingFlags.NonPublic); object o = methodGetRawBytes.Invoke(assembly, null); byte[] assemblyBytes = (byte[])o; Explanation: at least in my sample (assembly was loaded from byte array) the assembly instance was of type "System.Reflection.RuntimeAssembly". This is an internal class, so it can be accessed only using reflection. "RuntimeAssembly" has a method "GetRawBytes", which return the assembly bytes. A: An assembly is more conveniently represented simply as a binary dll file. If you think of it like that, the rest of the problems evaporate. In particlar, look at Assembly.Load(byte[]) for loading an Assembly from binary. To write it as binary, use CompileAssemblyFromSource and look at the result's PathToAssembly - then File.ReadAllBytes(path) to obtain the binary from the file. A: System.Reflection.Assembly is ISerializable and can simply be serialized like so: Assembly asm = Assembly.GetExecutingAssembly(); BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, asm); and deserialization is just as simple but call BinaryFormatter.Deserialize instead. A: Here is my example: public static byte[] SerializeAssembly() { var compilerOptions = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } }; CSharpCodeProvider provider = new CSharpCodeProvider(compilerOptions); CompilerParameters parameters = new CompilerParameters() { GenerateExecutable = false, GenerateInMemory = false, OutputAssembly = "Examples.dll", IncludeDebugInformation = false, }; parameters.ReferencedAssemblies.Add("System.dll"); ICodeCompiler compiler = provider.CreateCompiler(); CompilerResults results = compiler.CompileAssemblyFromSource(parameters, StringClassFile()); return File.ReadAllBytes(results.CompiledAssembly.Location); } private static Assembly DeserializeAssembyl(object fromDataReader) { byte[] arr = (byte[])fromDataReader; return Assembly.Load(arr); } private string StringClassFile() { return "using System;" + "using System.IO;" + "using System.Threading;" + "namespace Examples" + "{" + " public class FileCreator" + " {" + " private string FolderPath { get; set; }" + " public FileCreator(string folderPath)" + " {" + " this.FolderPath = folderPath;" + " }" + " public void CreateFile(Guid name)" + " {" + " string fileName = string.Format(\"{0}.txt\", name.ToString());" + " string path = Path.Combine(this.FolderPath, fileName);" + " if (!File.Exists(path))" + " {" + " using (StreamWriter sw = File.CreateText(path))" + " {" + " sw.WriteLine(\"file: {0}\", fileName);" + " sw.WriteLine(\"Created from thread id: {0}\", Thread.CurrentThread.ManagedThreadId);" + " }" + " }" + " else" + " {" + " throw new Exception(string.Format(\"duplicated file found {0}\", fileName));" + " }" + " }" + " }" + "}"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7629799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Forgot SA password and user in Administrators account can't change it? I have a local install of SQLExpress that I haven't touched in months. Now I need to use it, and I've forgotten the SA password. That would be fine, except that my local user which IS a member of the local Administrators Group apparently doesn't have permission to change the SA password or permissions to change my own User Rights. I have tried using SQL Server Management Studio, I have done Single User Mode with SQL Server and used sqlcmd, they all tell me I don't have permissions for it. I'm afraid that even reinstalling SQL Express isn't going to fix this for me. Does anyone know of any other route I could take here? A: As long as you have physical access to the machine, there's a way to start SQL Server in maintenance mode, which will allow you to connect and reset the password, assign new permissions, etc. Instructions. Short version: * *From the Start menu, open SQL Configuration Manager. *Go to the "SQL Server Services" node. *Right-click on the SQL Server instance and select Properties. *Under "Advanced", find the "Startup Parameters" setting, and prepend -m; (that is, add a hyphen, m, and semicolon to the beginning of the existing string). *OK out. *Stop and restart SQL Server. You're now in maintenance mode, and can connect locally and change whatever settings you need to, including permissions. (The link says you can only connect with sqlcmd, but I know that, with SQL 2008, you can connect with SQL Server Management Studio.) Make sure to take the server back out of maintenance mode (remove the -m;) when you're done, so that apps can connect normally. A: I would just uninstall and then reinstall -- it's not a very lengthy process. I believe you will be presented with the option to setup your sa account on the new installation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: showing text when text get mousefocus I need to show a couple of names when a especific text get focus. the code I have is: $forum=mysql_query("SELECT * FROM forum ORDER BY cod_forum DESC") or die (mysql_error()); while($de=mysql_fetch_array($forum)){ $nomesfoto=mysql_fetch_array(mysql_query("SELECT nome,foto FROM logins WHERE cod_login='$de[1]'")) or die (mysql_error()); echo"<h3 id='pipi'><img src='$nomesfoto[1]' width='50' height='70'> Postado por:<b> $nomesfoto[0] </b>em $de[3] </h3>"; echo"<p id='maior'> $de[2] </p>"; echo "<span class='like'>".$de[5]."</span>"; echo"<input class='porreiro' type='button' name='like' value=''><br>"; echo"<hr></hr>"; } the $de[5] show the number os likes of a comment. What I want is, when that number get focus of the mouse, to be showed the names os the persons who did the like. I just need the onfocus code... getting the names it's already done in another part of my code. thank you A: You can try setting a title on the <span>, most browsers will show a tooltip for such an element on mouse over echo "<span class='like' title='" . $names . "'>".$de[5]."</span>"; Otherwise pick a jQuery tooltip plugin and implement it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Is there Windows analog to supervisord? I need to run python script and be sure that it will restart after it terminates. I know that there is UNIX solution called supervisord. But unfortunately server where my script has to be run is on Windows. Do you know what tool can be useful? Thanks A: If you want a supervisord-like process manager that runs on most posix OS and is Python-based like supervisord, then you should look at honcho which is a Python port of foreman (Ruby-based): http://pypi.python.org/pypi/honcho/ It works great on mac, linux but (actually) not yet windows... (editing my initial answer where I had said optimistically it was already working on Windows based on a pull request that has been discarded since) There is a fork that provides Windows support here https://github.com/redpie/honcho and some work in progress to support Windows here https://github.com/nickstenning/honcho/issues/28 ... at least it could become a possible solution in a near future. There is also a foreman fork to support Windows here: https://github.com/ddollar/foreman-windows that may be working for you, though I never tried it. So for now, a Windows service might be your best short term option. A: Despite the big fat disclaimer here, you can run Supervisor with Cygwin in Windows; it turns out that Cygwin goes a long way to simulate a Posix environment, so well that in fact supervisord runs unchanged. There is no need to learn a new tool, and you will even save quite a bit of work if you need to deploy a complicated project across multiple platforms. Here's my recipe: * *If you have not done it yet, install Cygwin. During the installation process, select Python. *From the Cygwin terminal, install virtualenv as usual. *Create a virtualenv for supervisord, and then install as usual: pip install supervisord *Configure supervisord in the usual way. Keep in mind that supervisord will be running with Cygwin, so you better use paths the Cygwin way (C:\myservers\project1 translates to /cygdrive/c/myservers/project1 in Cygwin). *Now you probably want to install supervisord as a service. Here's how I do it: cygrunsrv --install supervisord --path /home/Administrator/supervisor/venv/bin/python --args "/home/Administrator/supervisor/venv/bin/supervisord -n -c /home/Administrator/supervisor/supervisord.conf" *Go to the Windows service manager and start the service supervisord that you just installed. Point 5 installs supervisord as a Windows service, so that you can control it (start/stop/restart) from the Windows service manager. But the things that you can do with supervisorctl work as usual, meaning that you can simply deploy your old configuration file. A: supervisor for windows worked for us on python27 - 32 bit. I had to install pypiwin32 and pywin32==223. A: You likely want to run your script as a Windows Service. To do so you'll need the python-win32 library. This question has a good description of how you go about doing this, as well as a bunch of links to other related resources. This question may also be of use. A Windows Service is how you want to wrap up any script that needs to run continuously on Windows. They can be configured to automatically start on boot, and handle failures. Nothing is going to stop anyone from killing the process itself, but to handle that potential situation, you can just create a bat file and use the sc command to poll the service to see if it is running and if not restart the service. Just schedule the bat file to run every 60 seconds (or whatever is reasonable for your script to potentially be down). A: As it is an old question with old answers I will update it with latest news: There is a supervisor-win project that claims to support supervisor on Windows. A: No, supervisord is not supported under Windows. BUT what you can do is, to restart it automatically from a wrapper script: #!/usr/bin/python from subprocess import Popen file_path = " script_to_be_restarted.py" args_as_str = " --arg1=woop --arg2=woop" while True: print("(Re-)Start script %s %s" % (file_path, args_as_str)) p = Popen("python " + file_path + args_as_str, shell=True) p.wait()
{ "language": "en", "url": "https://stackoverflow.com/questions/7629813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: gcc: error: request for member ‘rlen’ in something not a structure or union I have a unsigned char pointer which contains a structure.Now I want to do the following unsigned char *buffer ; //code to fill the buffer with the relavent information. int len = ntohs((record_t*)buffer->len); where record_t structure contains a field called len.I am not able to do so and am getting the error. error: request for member ‘len’ in something not a structure or union. what am I doing wrong here? A: in C you can't just take buffer->len, because it's being parsed as if the final result buffer->len is being cast to a record_t *. Try ((record_t *)buffer)->len A: Try ((record_t*)buffer)->len You're casting buffer->len to a record_t*, when what you want to do is cast buffer to a record_t and then get the len value of that. A: If you're confident that you're doing the right thing (though this looks very hackish), you just have to get the operator precedence right: ntohs( ((record_t*)buffer)->len ); A: Precedence of -> is higher than the cast. Add some parentheses appropriately.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: radio button to enable form fields I have a form containing two radio buttons, I want to enable corresponding fields when a radio button is checked. My code just isn't working, here it is: <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function() { var $type = $('select'), $field1 = $("#fieldID1"), $field2 = $("#fieldID2"); $type.change(function() { var isDisabled = ($type.filter(":checked").val() === "1"); $field1.prop("disabled", !isDisabled); $field2.prop("disabled", isDisabled); }).change(); }); </script> </head> My html body is like: <body> <form action="" method="post"> <input type="radio" name="select" value="1" /> <input type="text" name="fieldID1" id="fieldID1"/> <input type="radio" name="select" value="2" /> <table id="fieldID2"> <tr>...</tr> <tr>...</tr> ... </table> <input type="submit" value="Add"> </form> </body> I referenced the code from this post. Can anyone point me out what the problem is, I am not quite familiar with jQuery, thanks! Still cannot be fixed... A: $fieldID1.prop("disabled", !isDisabled); $fieldID2.prop("disabled", isDisabled); Should probably be: $field1.prop("disabled", !isDisabled); $field2.prop("disabled", isDisabled); A: $(document).ready(function() { var $type = $(':radio[name="select"]'), $field1 = $("#fieldID1"), $field2 = $("#fieldID2"); $type.change(function() { var isDisabled = ($type.filter(":checked").val() === "1"); $field1.prop("disabled", !isDisabled); $field2.prop("disabled", isDisabled); }).change(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7629817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Style TreeView but keep it Virtualized The Virtualization on my TreeView works when I have only styled the TreeViewItem with this bit of xaml in the style: <Style.Triggers> <Trigger Property="VirtualizingStackPanel.IsVirtualizing" Value="true"> <Setter Property="ItemsPanel"> <Setter.Value> <ItemsPanelTemplate> <VirtualizingStackPanel/> </ItemsPanelTemplate> </Setter.Value> </Setter> </Trigger> </Style.Triggers> But then if I try and give the TreeView itself a style with Style={Resource} the virtualization breaks, i.e: <Style x:Key="FontTreeViewStyle" TargetType="{x:Type TreeView}"> <Setter Property="OverridesDefaultStyle" Value="True" /> <Setter Property="SnapsToDevicePixels" Value="True" /> <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto" /> <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="TreeView"> <Border Name="Border" CornerRadius="1" BorderThickness="1" BorderBrush="{DynamicResource BorderMediumColor}" Background="{DynamicResource ControlLightColor}"> <ScrollViewer Focusable="False" CanContentScroll="False" Padding="4"><!-- Style="{StaticResource MyScrollViewer}"--> <ItemsPresenter /> </ScrollViewer> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> Thanks in advance! A: By specifying CanContentScroll="False" on the ScrollViewer you will always stop it virtualizing Take a look at why setting ScrollViewer.CanContentScroll to false disable virtualization If you still have problems double check the visual tree that's created in something like Snoop or WPF Inspector. For virtualization to work the IScrollInfo object (ie the panel) must be the direct child of the ScrollViewer. http://msdn.microsoft.com/en-us/library/ms750665.aspx Hope that helps, Mark A: MarkDaniel alredy answered (thanks!) but here is a full example style: <Style x:Key="ScrollViewerStyle" TargetType="{x:Type ScrollViewer}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ScrollViewer}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <ScrollContentPresenter CanContentScroll="True" VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.IsContainerVirtualizable="True" VirtualizingPanel.VirtualizationMode="Recycling"/> <ScrollBar Name="PART_VerticalScrollBar" Grid.Column="1" Value="{TemplateBinding VerticalOffset}" Maximum="{TemplateBinding ScrollableHeight}" ViewportSize="{TemplateBinding ViewportHeight}" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" Style="{DynamicResource ScrollBarStyle}"/> <ScrollBar Name="PART_HorizontalScrollBar" Orientation="Horizontal" Grid.Row="1" Value="{TemplateBinding HorizontalOffset}" Maximum="{TemplateBinding ScrollableWidth}" ViewportSize="{TemplateBinding ViewportWidth}" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" Style="{DynamicResource ScrollBarStyle}"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>
{ "language": "en", "url": "https://stackoverflow.com/questions/7629818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to make Git aware of an existing .gitmodules file? I added a submodule: git submodule add git://github.com/chneukirchen/rack.git rack A file .gitmodules was created like: [submodule "rack"] path = rack url = git://github.com/chneukirchen/rack.git And of course Git knows about it: git submodule status 30fb044db6ba5ea874ebc44a43bbd80a42676405 rack (1.3.0-64-g30fb044) I added a submodule by hand, for example, adding to that file: [submodule "redcloth"] path = plugins/redcloth url = git://github.com/jgarber/redcloth.git And I repeated the previous command: git submodule init Submodule 'rack' () registered for path 'rack' git submodule update (no output) git submodule status 30fb044db6ba5ea874ebc44a43bbd80a42676405 rack (1.3.0-64-g30fb044) So, as far I can see, what I added by hand is ignored. Is there some way to make Git aware of the lines added by hand in the .gitmodules file? Note: I've also tried to add the lines by hand to the .git/config file and that didn't work either. A: You need to run git submodule update --init --recursive UPDATE: the submodule add command actually clones the entire repo and adds the sha1 to the index. This may be new behaviour as compared to previous versions of git, the clone was not done immediately. If you don't have an entry in the index pointing the module to a particular commit, git submodule update refuses to do anything. This seems to be new behaviour. Hope this helps. A: Ok, so thanks to Adam I found the answer, was kind of obvious but nevertheless, here it is: If you check what git submodule add does, you'd notice that it does three things: * *Adds the lines to the .gitmodules file, *Clones the repo in the 'path' you determined in the command, and *Adds the module to the .git/config file. So, basically the only difference between a repo with a submodule added by hand and the one added via the git submodule command is the contents of the repo itself. Answering with the same example, you should: $ git clone git://github.com/jgarber/redcloth.git plugins/redcloth Add the following to the .git/config file*: [submodule "redcloth"] url = git://github.com/jgarber/redcloth.git Make sure at least you add them to the git repo: $ git add plugins/redcloth And then check if git actually is "aware": $ git submodule status 0766810ab46f1ed12817c48746e867775609bde8 plugins/redcloth (v4.2.8) 30fb044db6ba5ea874ebc44a43bbd80a42676405 rack (1.3.0-64-g30fb044) *note that the "path" variable you use in the .gitmodules file isn't needed in that file
{ "language": "en", "url": "https://stackoverflow.com/questions/7629822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Why is CRM 2011 Entity Relationship null in this plugin code? this is a working example of a plugin that I have written for CRM 2011. I have created a 'Create' step in the plugin registration tool for this plugin. This executes fine. I also have an 'Update' step registered for the plugin. This fails to execute because the primary contact returned is null. These steps are both registered as asynchronous. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xrm.Sdk; using System.ServiceModel; using System.IO; using System.Net; namespace CRMNewsletterPlugin { public class NewsletterSignup : IPlugin { public void Execute(IServiceProvider serviceProvider) { ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); // Obtain the execution context from the service provider. IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); tracingService.Trace("Begin load"); // The InputParameters collection contains all the data passed in the message request. if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { tracingService.Trace("We have a target."); // Obtain the target entity from the input parmameters. Entity entity = (Entity)context.InputParameters["Target"]; IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); if (!entity.GetAttributeValue<bool>("new_receivesnewsletter")) { try { //check if the account number exist string emailAddress = entity.GetAttributeValue<string>("emailaddress1"); EntityReference primaryContact = entity.GetAttributeValue<EntityReference>("primarycontactid"); // UPDATE STEP FAILS HERE if (primaryContact == null) { tracingService.Trace("Primary Contact is null"); } Entity contact = service.Retrieve("contact", primaryContact.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "fullname" })); string fullname = contact.GetAttributeValue<string>("fullname"); string name = entity.GetAttributeValue<string>("name"); WebRequest req = WebRequest.Create("http://localhost"); string postData = "cm-name=" + fullname + "&cm-ddurhy-ddurhy=" + emailAddress + "&cm-f-jddkju=" + name; tracingService.Trace(postData); byte[] send = Encoding.Default.GetBytes(postData); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = send.Length; tracingService.Trace("Sending info"); Stream sout = req.GetRequestStream(); sout.Write(send, 0, send.Length); sout.Flush(); sout.Close(); tracingService.Trace("Info sent"); WebResponse res = req.GetResponse(); StreamReader sr = new StreamReader(res.GetResponseStream()); string returnvalue = sr.ReadToEnd(); tracingService.Trace(returnvalue); entity.Attributes["new_receivesnewsletter"] = true; service.Update(entity); tracingService.Trace("Newsletter field set"); } catch (FaultException ex) { throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex); } } } } }//end class } A: The entity contained in the InputParameters["Target"] only includes the changed fields that were submitted in the update, not all fields. Your plugin works for Create because InputParameters["Target"] always contains all fields during a Create obviously. To fix this, you need to add a PreImage to your step in PluginRegistrationTool that includes the primarycontactid field. A PreImage will always include the values for the fields you specify as they were before the update. The trick is to check for primarycontactid on InputParameters["Target"] first, because that would contain the latest value (if the user updated both new_receivesnewsletter and primarycontactid during the same save, for example). If InputParameters["Target"] doesn't contain primarycontactid, then fall back on your PreImage, accessed something like this (assuming you set your PreImage's alias to "preimage"): context.PreEntityImages["preimage"].GetAttributeValue<EntityReference>("primarycontactid") Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7629825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Setting up mvc application on IIS7? I've created a MVC website using Visual Studio 2010 and would like to deploy it to my newly installed local IIS7. The website works perfectly running from Visual Studio on the development server that it comes with. Here are the steps I've done: 1) Opened IIS7 Manager. 2) Under Sites created a new site called Foo. -- I used the DefaultAppPool which is set to .net4 integrated -- I created a empty directory and used it as the default path -- I set the port to 54321 3) I then in Visual Studio used the publish button with local IIS and the site set as Foo. IIS Manager now shows the following under sites: Foo bin content scripts views When I go to localhost:54321 I am given a message saying it can't list the directory. If I put a index.html file in this directory it will launch the file as expected. I guess I'm missing something big here. I published my site to this directory. When I go to localhost:54321 I expected it to launch the index view of the home controller, but it just tries to list the directory. Found the answer here: ASP.NET MVC on IIS 7.5 Can't answer my own question cause I have less than 100 points :) A: The new server is missing the ASP.NET MVC 3.0. Install it using standalone ASP.NET MVC 3 installer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android, Proguard 'Unknown option 'and' in argument number 9' I'm getting the following error every time I try to export my application from Eclipse. Proguard returned with error code 1. See console proguard.ParseException: Unknown option 'and' in argument number 9 at proguard.ConfigurationParser.parse(ConfigurationParser.java:170) at proguard.ProGuard.main(ProGuard.java:491) I'm using the defualt proguard.cfg file that Eclipse generated. My android sdk is in C:\Android\SDK(here) My default.properties file is like this: target=android-7 proguard.config=proguard.cfg I have also done a clean and build. I also made sure Eclipse and my SDK tools were up to date. A: The 'spaces in the pathnames' problem is well documented here - note that you can use Junctions/Links to get around this without moving or renaming files... The Dalvik error is usually just Eclipse 'having a moment' - a 'Clean Project' and Rebuild usually cures it. A: So, in my workspace for the name of the project I had C:\workspace\Name Android Name for the name, so I changed that to C:\workspace\NameName, then I changed my sdk to C:\sdk, then I exported to C:\NameAndroidName.apk, and I got the failure to convert to dalvik format error. And then I went to this question and that solved the dalvik format error, and it exported successfully.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IOS - how to write file to network share? i'm trying to create and write a file to a network share (smb). i have some data stored in an NSData object and need to write the content to a network share at \\media\file.xml any help or advise would be greatly appreciated! thanks! A: Search your favorite search engine on "samba iOS" or similar terms. You want an API for connecting to an SMB service, which is what an iOS port of Samba can help provide.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can i get geocoding information from Google Geocoding API passing only the city? I just need to fetch some geo data for a given city, i'm not interested (and i don't know) the address. Sending a request like this: http://maps.googleapis.com/maps/api/geocode/xml?address=fake,%20USA&sensor=false will match a street with whe word fake in it, somewhere in USA. How can i match only cities and get ZERO_RESULTS response if there is no city with that name? A: You can't do this with the Geocoding API unfortunately, from the docs page: Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739) The API will always look for a specific address and if it can't find an exact match from the string you provide it will always make a 'best effort' guess as to what you meant to try and find one. Only if it can't make this reasonable guess wil it return ZERO_RESULTS. A: I also just explore the API.how about using link like below http://maps.googleapis.com/maps/api/geocode/xml?components=locality:fake|country:US locality equal to City and stated the country as US.It will return zero result.But if using this http://maps.googleapis.com/maps/api/geocode/xml?components=locality:fake|country:Nigeria This will return the result.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I properly queue and execute tasks with variable start times in c#? I'm still new to C#. Currently using .NET 3.5. I'm writing an online game, and my game engine needs to handle player requested unit movement. The units will move at different speeds and can have different destinations, so the actual time that the unit arrives (and the command completes) will differ widely. My strategy is that the model will calculate the next move along a given path, and then queue a worker to execute around the same time the unit would be arriving at the location. The worker will update the unit, notify players, queue the next step, etc. One of my biggest stumbling blocks was writing a worker thread that would conditionally execute a task. In the past my worker threads have just tried to run each task, in order, as quickly as possible. The other challenge is that unit moves might get queued that have earlier start times than any other task in the queue, so obviously, they would need to get moved to the front of the line. This is what I have figured out so far, it works but it has some limitations, namely its 100ms sleep limits my command response time. Is there a pattern for what i'm trying to do, or am I missing something obvious? Thank you! public class ScheduledTaskWorker { List<ScheduledTask> Tasks = new List<ScheduledTask>(); public void AddTask(ScheduledTask task) { lock (Tasks) { Tasks.Add(task); Tasks.Sort(); } } private void RemoveTask(ScheduledTask task) { lock (Tasks) { Tasks.Remove(task); } } private ScheduledTask[] CopyTasks() { lock (Tasks) { return Tasks.ToArray(); } } public void DoWork() { while (!StopWorking) { ScheduledTask[] safeCopy = CopyTasks(); foreach (ScheduledTask task in safeCopy) { if (task.ExecutionTime > DateTime.Now) break; if (ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCallBack), task)) RemoveTask(task); else { // if work item couldn't be queued, stop queuing and sleep for a bit break; } } // sleep for 100 msec so we don't hog the CPU. System.Threading.Thread.Sleep(100); } } static void ThreadPoolCallBack(Object stateInfo) { ScheduledTask task = stateInfo as ScheduledTask; task.Execute(); } public void RequestStop() { StopWorking = true; } private volatile bool StopWorking; } And the task itself... public class ScheduledTask : IComparable { Action<Item> Work; public DateTime ExecutionTime; Item TheItem; public ScheduledTask(Item item, Action<Item> work, DateTime executionTime) { Work = work; TheItem = item; ExecutionTime = executionTime; } public void Execute() { Work(TheItem); } public int CompareTo(object obj) { ScheduledTask p2 = obj as ScheduledTask; return ExecutionTime.CompareTo(p2.ExecutionTime); } public override bool Equals(object obj) { ScheduledTask p2 = obj as ScheduledTask; return ExecutionTime.Equals(p2.ExecutionTime); } public override int GetHashCode() { return ExecutionTime.GetHashCode(); } } A: I'm not disagreeing with Chris, his answer is probably more appropriate to your underlying problem. However, to answer your specific question, you could use something equivalent to Java's DelayQueue, which looks to have been ported to C# here: http://code.google.com/p/netconcurrent/source/browse/trunk/src/Spring/Spring.Threading/Threading/Collections/Generic/DelayQueue.cs?spec=svn16&r=16 Your Task class would implement IDelayed then you could either have a single thread calling Take (which blocks while there are no items ready) and executing task, or pass them off to ThreadPool.QueueUserWorkItem. A: That sounds dangerously brittle. Without knowing more about your game and its circumstances, it sounds like you could potentially drown the computer in new threads just by moving a lot of units around and having them do long-running tasks. If this is server-side code and any number of players could be using this at once, that almost guarantees issues with too many threads. Additionally, there are timing problems. Complex code, bad estimating, delays in starting a given thread (which will happen with the ThreadPool) or a slowdown from a lot of threads executing simultaneously will all potentially delay the time when your task is actually executed. As far as I know, the majority of games are single-threaded. This is to cut down on these issues, as well as get everything more in sync. If actions happen on separate threads, they may receive unfair prioritization and run unpredictably, thereby making the game unfair. Generally, a single game loop goes through all of the actions and performs them in a time-based fashion (i.e. Unit Bob can move 1 square per second and his sprite animates at 15 frames per second). For example, drawing images/animating, moving units, performing collision detection and running tasks would all potentially happen each time through the loop. This eliminates timing issues as well, because everything will get the same priority (regardless of what they're doing or how fast they move). This also means that the unit will know the instant that it arrives at its destination and can execute whatever task it's supposed to do, a little bit at a time each iteration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to support different languages with dynamic web data on Android? I have an application that pulls information from a web server and displays it. I know that Android has some nice language features where you can put multiple strings.xml files inside the project for specific languages. Is there a way to convert the text from the server (which is in english) to whatever local the user has set on their device? Thanks A: Yes, but that's usually done at the server-side with some kind of translation api. Even on Android, when an app needs content that hasn't already been pre-translated, it goes through a server for the translation. For instance, you could use Google Translate's api (which is not free) http://code.google.com/apis/language/translate/overview.html Or you could install some open source solution on your own server and use that remotely as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Back bar doesn't show up in navigation controller Here is the code: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { DrinkDetailViewController *detailViewController = [[DrinkDetailViewController alloc] initWithNibName:@"DrinkDetailViewController" bundle:nil]; [self.navigationController pushViewController:detailViewController animated:YES]; [self.navigationController popToRootViewControllerAnimated:YES]; [DrinkDetailViewController release]; } I want to have a back bar to go to my root view from the detail view. How do I do it? A: There's 2 things that look a little weird here... hopefully fixing em will make the back btn show up: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { DrinkDetailViewController *detailViewController = [[DrinkDetailViewController alloc] initWithNibName:@"DrinkDetailViewController" bundle:nil]; [self.navigationController pushViewController:detailViewController animated:YES]; //[self.navigationController popToRootViewControllerAnimated:YES]; <-- you just pushed a viewController onto the stack, and you're immediately removing it here and going to the root [detailViewController release]; //<-- you want to release the *instance* that you created... not the Class } The UINavigationController should take care of the back button for you as far as I know. If not, I would check to see that everything is wired up correctly in your xib (if you have one). Good Luck! A: With your code, it will still push to the DrinkDetailViewController but the' popToRootViewController is totally unnecessary. You should delete the line like follows.. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { DrinkDetailViewController *detailViewController = [[DrinkDetailViewController alloc] initWithNibName:@"DrinkDetailViewController" bundle:nil]; [self.navigationController pushViewController:detailViewController animated:YES]; [detailViewController release]; } And I believe, the reason your back button does not show up on the nav bar is because you didn't put any title in your root view. You can put this code on you viewdidload method on the root view. self.title = @"Your Title";
{ "language": "en", "url": "https://stackoverflow.com/questions/7629854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Transloadit: Sending 0 byte file while request.body.read is not empty I'm using transloadit and sending files with xhr using valumns file uploader. Files are sent to the server without errors (i checked size and content of request.body.read) but once I do: response = assembly.submit! (request.body) An empty file is sent (I checked many times in the assemblies history page). Thanks for you help. A: Call request.body.rewind before using request.body.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to make a collection of type objects in Scala Basically, I want to have a Map indexed by type objects. In this case, I'm trying to use Class as the "type type". the following code: class SuperClass {} val typemap = new HashMap[Class[_ <: SuperClass], SuperClass] def insertItem1[T <: SuperClass] (item : T) = typemap += classOf[T] -> item def insertItem2[T <: SuperClass] (item : T) = typemap += item.getClass -> item does not compile, because (1) classOf[T] is apparently invalid: error: class type required but T found and (2) item.getClass is of the wrong type: Type mismatch, expected: Class[_ <: SuperClass], actual: Class[_] I see two ways to accomplish this: either drop the type requirement and use Class[_] only or use Manifest instead of Class (not sure how to do that yet, any examples are welcome) But more generally, why is classOf[T] invalid, and how do I obtain a class object for a parametrized type? update: I found out that I can use item.getClass.asInstanceOf[Class[T]] to get to the class object. For one, this is ugly. For two, it doesn't help much, because later in the code i have functions such as this one: def isPresent[T <: SuperClass] = typemap contains classOf[T] Obviously, I could use the asInstanceOf method in insertItem and pass the class as a parameter to isPresent. Is there a better way? A: You can use manifests to achieve this: class TypeMap extends HashMap[Class[_], Any] { def putThing[T](t: T)(implicit m: Manifest[T]) = put(m.erasure, t) } val map = new TypeMap map.putThing(4) map.get(classOf[Int]) // returns Option[Any] = Some(4) You are losing the types through erasure, so you need to add the implicit argument to the putThing which contains the name of the class, using a Manifest. A: The problem is once again that generics aren't available at run time. The compiler does the task of figuring out what T is, but it can't because it is only know at run time. You could use a manifest to obtain that information: What is a Manifest in Scala and when do you need it?.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Which Android device has all possible orientation sensors Looking for a device that give maximum possible combination of: Accelerometer Gyroscope Rotation matrix Linear acceleration Magnetic field Rotation vector Or any other sensor which gives any data about 3D orientation. OR: Are there devices that embed InvenSense MotionFusion chips? I'm looking for a device which is already available for sale on market, however any confirmed information about any upcoming devices will help as well. Thanks. A: A couple of Market apps, AndroSensor and Sensor List show actual phone sensors with running data. Good old Nexus One has Accelerometer and Magnetic compass. I assume you want a gyroscope. My year-old AT&T Galaxy S has a couple of orientation sensors that may add-up to 6 axis but not a true gyro. A wealth of gyroscople links are documented on SO and more details on Galaxy S sensors here. Max, let us know which device you settle on, please, and how it works out. Apparently, Galaxy S2 has LOTS of sensors Orientation type of the sensor A: My HTC Desire (aka the Nexus One) is an oldish device now and it has all the sensors needed to detect it's orientation in 3 dimensions (gyro) and movement therein (acceleration). I suspect most phones have these sensors - they're commonly used in Apps and people tend not to use stuff which isn't widely available (like proper multitouch for example). It must have some sort of light sensor as it has an automatic backlight adjustment too - tho I've never tried to access that for any development purpose. In fact, those apps which demonstrate sensor values only show a blank against things like temperature sensors which I suspect few devices have!? If you'd like me to check it for any other sensor value - let me know - but I've developed a few Apps which use those sensors widely so I know they do work...
{ "language": "en", "url": "https://stackoverflow.com/questions/7629865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to setup prepared statements for mysql queries in C? I'm trying to set up a prepared statement based on this example I found on the web. I just want to protect against sql injections in the grade= and username=, but the statement isn't executing. MYSQL_STMT *stmt; MYSQL_BIND bind[2]; char* usrname = &uname[0]; //uname supplied by user char* choi = choice; //choice supplied by user stmt = mysql_stmt_init(connect); char* statement = "UPDATE grades SET grade='?' WHERE username='?'"; mysql_stmt_prepare(stmt, statement, strlen(statement)); memset(bind,0,sizeof(bind)); bind[0].buffer_type=MYSQL_TYPE_STRING; bind[0].buffer=usrname; bind[0].buffer_length=50; bind[0].is_null=0; bind[0].length= strlen(usrname); bind[1].buffer_type=MYSQL_TYPE_STRING; bind[1].buffer=choi; bind[1].buffer_length=50; bind[1].is_null=0; bind[1].length= 2; mysql_stmt_bind_param(stmt, bind); mysql_stmt_execute(stmt); A: bind[0].length= strlen(usrname); bind[1].length= 2; bind[x].length is a pointer. It should be pointing to an address that contains the value of the length, or be NULL (zero) to be "ignored" When set to NULL (or zero), I think length_value is then used... but I don't know if the user should set it, or if it's for mysql to use it internally. However, from what I understood (I didn't try it) this is for getting the length of a string read from the database, so it's not useful in this case because you are not reading. For input, which is your case, buffer_length is the length of the string you want to send. For output, it is the size of the buffer that can be filled with the value read from the db, which is truncated if longer than that value. You should have: bind[0].buffer_type=MYSQL_TYPE_STRING; bind[0].buffer=usrname; bind[0].buffer_length=strlen(usrname); bind[0].is_null=0; bind[0].length=0; bind[1].buffer_type=MYSQL_TYPE_STRING; bind[1].buffer=choi; bind[1].buffer_length=strlen(choi); bind[1].is_null=0; bind[1].length=0; but I haven't tested that and you must have actual strings in your buffers. The buffers in the sample you provided are not initialized. I also strongly suggest that you use memset(bind, 0, sizeof(bind)); to zero the whole structure. It will avoid having garbage values where you didn't set anything. This may be useful: https://www.assembla.com/code/DelphiMS/subversion/nodes/Required%20Units/Zeos%207/plain/mysql_bind.txt?rev=32
{ "language": "en", "url": "https://stackoverflow.com/questions/7629866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Network communication options in Java (Client/Server) There is RMI, which I understand to be relatively fragile, direct Socket connections, which is rather low level, and Strings, which while about as solid as it gets seems to be the metaphorical PHP. What less basic options do I have for internet based Client/Server communication ? What are the advantages/disadvantages ? What are some concerns I should take into consideration ? Third party library suggestions are fine, as long as they stay platform independent (i.e. no restrictive native code). Looking for options, not a definite answer, so I'm leaving the details of my own requirements blank. A: As you specified "internet based", there's a lot to be said for an HTTP-based, RESTful approach (I've highlighted some concerns you should consider): Pros: * *You can use/abuse one of the myriad web-tier frameworks for the server side (e.g. Spring MVC, Play!) *The low-level work has been done on client-side (Apache HTTPClient) *Plain-text protocol is easy to debug on the wire *Tons of tools available to help you debug the interactions (e.g. SoapUI) - you can pretend to be client OR server and so develop in isolation until the other end is ready *Using a well-known port (80/443) makes punching through corporate firewalls a whole lot easier Cons: * *There's a fairly major assumption that the server will be doing the lion's share of the work - if your model is "inverted" then it might not make much sense to be RESTful *Raw performance will be lower than a bits-on-the-wire socket-based approach *Plain-text protocol is easy to sniff on the wire (SSL can remedy this) A: What does 'relatively fragile' mean? The issues with RMI have to do with it being a large superstructure on a narrow foundation, and specifically that it has a large reliance on DNS and Object Serialization. The closer you are to the silicon, the less 'fragile' any program becomes, but the more code you have to write. It's a tradeoff. I'm not a one-eyed RMI supporter, despite having written a book about it, but 'fragility' is too strong a word. It does what it does, and it does that reasonably well. RMI/IIOP does it even better in many respects if you need large-scale scalability. If your view of the world is an at-most-once remote method call without too much security, RMI/JRMP will give it to you. The further you get from that model the harder it becomes to apply.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Windows Azure - Persistence of OS Settings when using WebRoles I've been watching some videos from the build conference re: Inside Windows Azure etc. My take away from one of them was that unless I loaded in a preconfigured VHD into a virtual machine role, I would lose any system settings that I might have made should the instance be brought down or recycled. So for instance, I have a single account with 2 Web Roles running multiple (small) websites. To make that happen I had to adjust the settings in the Hosts file. I know my websites will be carried over in the event of failure because they are defined in the ServiceConfiguration.csfg but will my hosts file settings also carry over to a fresh instance in the event of a failure? i.e. how deep/comprehensive is my "template" with a web role? A: The hosts file will be reconstructed on any full redeployment or reimage. In general, you should avoid relying on changes to any file that is created by the operating system. If your application is migrated to another server it will be running on a new virtual machine with its own new copy of Windows, and so the changes will suddenly appear to have vanished. The same will happen if you perform a deployment to the Azure "staging" environment and then perform a "swap VIP": the "staging" environment will not have the changes made to the operating system file. Microsoft intentionally don't publish inner details of what Azure images look like as they will most likely change in future, but currently * *drive C: holds the boot partition, logs, temporary data and is small *drive D: holds a Windows image *drive E: or F: holds your application On a full deployment, or a re-image, you receive a new virtual machine so all three drives are re-created. On an upgrade, the virtual machine continues to run but the load balancer migrates traffic away while the new version of the application is deployed to drive F:. Drive E: is then removed. So, answering your question directly, the "template" is for drive E: -- anything else is subject to change without your knowledge, and can't be relied on. A: Azure provides Startup Scripts so that you can make configuration changes on instance startup. Often these are used to install additional OS components or make IIS-configuration changes (like disabling idle timeouts). See http://blogs.msdn.com/b/lucascan/archive/2011/09/30/using-a-windows-azure-startup-script-to-prevent-your-site-from-being-shutdown.aspx for an example. A: The existing answers are technically correct and answer the question, but hosting multiple web sites in a single web role doesn't require editing the hosts file at all. Just define multiple web sites (with different host headers) in your ServiceDefinition.csdef. See http://msdn.microsoft.com/en-us/library/gg433110.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7629871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NLTK "generate" function: How to get back returned text? I'm a Python noob, so bear with me. I'm trying to work with the NLTK library, and in particular the 'generate' function. It looks like from the documentation this function simply prints its result (http://nltk.googlecode.com/svn/trunk/doc/api/nltk.text-pysrc.html). I would like to manipulate the resulting text prior to printing it to the screen, but I can't seem to figure out how to get this function to return its text. How would I go about getting the output of this function? Do I have to change the function to return the result instead of printing it? UPDATE: I found this link which kinda does it, but it feels pretty darn hacky. http://northernplanets.blogspot.com/2006/07/capturing-output-of-print-in-python.html Is this the best I can hope for? A: All generate is doing is generating a trigram model if none exists, then calling text = self._trigram_model.generate(length) and wrapping and printing it. Just take the parts you want -- possibly just the above line (with self replaced by the instance name), or possibly the whole thing, as below, with the final print replaced with return. def generate(self, length=100): if '_trigram_model' not in self.__dict__: estimator = lambda fdist, bins: LidstoneProbDist(fdist, 0.2) self._trigram_model = NgramModel(3, self, estimator) text = self._trigram_model.generate(length) return tokenwrap(text) # or just text if you don't want to wrap And then you can just call it with a manually passed instance as the first argument. A: Go into Python26/site-packages/nltk/text.py and change the "generate" function: def generate(self, length=100): if '_trigram_model' not in self.__dict__: print "Building ngram index..." estimator = lambda fdist, bins: LidstoneProbDist(fdist, 0.2) self._trigram_model = NgramModel(3, self, estimator) text = self._trigram_model.generate(length) text_gen = tokenwrap(text) print text_gen return text_gen`
{ "language": "en", "url": "https://stackoverflow.com/questions/7629872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I mix audio files using python? I would like to do basic audio mixing in python. To give an example: I would like to take two mp3 files and add them together and return one mp3 file. Another example: I would like to take the first ten seconds of one mp3 file and add it to the beginning of another mp3 file. What is the best way to accomplish these tasks? I would like to use built in python functions like audioop but can not find any good tutorials or sample code out there for using the built in functions. I am going through the docs but I am pretty confused and cannot figure out how to do things like this. I am not even sure that the python libraries like mp3's. Most of the stuff I have looked at seem to refer to WAV files. So, if this is the case, I guess a follow up question would be is there an easy way to convert an mp3 to a WAV for manipulation and back again? A: You can do this pretty easily using pydub: from pydub import AudioSegment sound1 = AudioSegment.from_mp3("/path/to/file1.mp3") sound2 = AudioSegment.from_mp3("/path/to/file1.mp3") # mix sound2 with sound1, starting at 5000ms into sound1) output = sound1.overlay(sound2, position=5000) # save the result output.export("mixed_sounds.mp3", format="mp3") A: You could check out some of the code in the python audiotools project. It is a collection of command-line utilities which make use of a common python package. There is a utility included with audiotools (trackcat) which can con*cat*enate two or more audio tracks; another (tracksplit) can split an audio track (using a .cue file). These, as well as the numerous other included utilities, can work with audio files of various encodings, including mp3. A: The way I've done this in the past is just use subprocess. and call sox. E.g. subprocess.call(["sox", "in.1.mp3", "in.2.mp3", "out.mp3"])
{ "language": "en", "url": "https://stackoverflow.com/questions/7629873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Proper syntax for executing a function only if another function is successful I have the following code that is part of my email class that I use in my programs. Currently I am running the quit function whether or not a connection to the SMTP server was made in the connect function. I know I could put the quit function inside of the try statement after the email is sent, but I would like to figure out how to write the code to say the equivalent of "if a connection to the server is open, close it." What is the best way to write that in Python? Thanks! def connect(self, headers, msg): try: self.server.starttls() try: self.server.login(self.usrname,self.pswd) try: self.server.sendmail(self.sendfrom, self.sendto, headers + "\r\n\r\n" + msg) except Exception as sendmailfail: print(sendmailfail) except Exception as emailfail: print (emailfail) except Exception as error: print(error) def quit(self): self.server.quit() print("The SMTP connection is closed") first = GmailSmpt('x','y','z','zz') x , y = first.message() first.connect(x,y) first.quit() A: You need to finish the "Errors and Exceptions" section of the tutorial. try: possibly_fail() except ...: handle_exception() else: no_exceptions() finally: always_run_this()
{ "language": "en", "url": "https://stackoverflow.com/questions/7629883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Filling out an inherited mongoid document using nested attributes Given the following models: class Company include Mongoid::Document has_many :workers, autosave: true accepts_nested_attributes_for :workers attr_accessible :workers_attributes end class Worker include Mongoid::Document field :hours attr_accessible :hours belongs_to :company end class Manager < Worker field :order has_many :contributors, :class_name => "Worker" attr_accessible :order, :contributors end class Contributor < Worker field :task belongs_to :manager, :class_name => "Worker" attr_accessible :task end How does one create a manager in a company in the controller and view using nested attributes? Here's my guess: def new @company = Company.new @company.workers = [Manager.new] end def create @company = Company.new params[:user] if @company.save redirect_to root_url, :notice => "Company with manager created." else render :new end end = semantic_form_for @company do |f| = f.semantic_fields_for :workers do |worker_fields| = worker_fields.inputs do = worker_fields.input :hours = worker_fields.input :order problem is the order field which specifically belongs to the manager is not persisting after the create. Also when the data is improperly filled there is an error: undefined method `order' for #<Worker:0x0000000646f018> (ActionView::Template::Error) So is there a way for nested attributes to handle inheritance in the models from mongoid? The question is related to Can nested attributes be used in combination with inheritance? except instead of active record using mongoid. Honestly, this is a paraphrasing of my code... the real code is more complex situation although i believe these are all of the relevant parts. If you have more questions ask. UPDATE: I changed the view to the following: = semantic_form_for @company do |f| - @company.workers.each do |worker| - if worker._type == "Manager" = f.semantic_fields_for :workers, worker do |worker_fields| = worker_fields.inputs do = worker_fields.input :hours = worker_fields.input :order I do not get the error anymore, however the nested attributes do not update the company object properly. The params are the following: {"company"=> {"workers_attributes"=>{"0"=>{"hours"=>"30", "order" => "fish", "id"=>"4e8aa6851d41c87a63000060"}}}} Again edited for brevity. So the key part is that there is a hash between "0" => {data for manager}. The workers data seems to be held in a hash. I would expect the data to look more like the following: params = { company => { workers_attributes => [ { hours => "30", "order" => "fish" } ]}} This is different because the workers data is held in an array instead of a hash. Is there another step to get the nested attributes to save properly? Thanks A: what version of Mongoid are you using? Because I don't think the use of refereneces_many is encouraged -- Not that that's related to your problem here, just wanted to probe what version you're using. In the doc on the gorgeous Mongoid.org, get this, I had to learn it the hard way, they say for Updating your records, you need to the autossave set to true. That's NOT accurate. You need it for even creating so: class Company include Mongoid::Document has_many :workers, :autossave => true # your money shot accepts_nested_attributes_for :workers attr_accessible :workers_attributes end ADDED: I was re-reading your code, I spotted the following that might be the problem: Your Company model is set to has_many :workers and is set to accept nested attribbutes for Worker when changes come in, correct? And there is a field named Order in your Manager model which is subclassed from Worker. Yet you're having a form whose nested fields part is pointed at Worker not at Manager, the model that actually has the Order field. And that's obviously not enough, because Company isn't having_many :managers yet, you may need to set it to has_many :managers in the Company model as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you configure Jenkins to use git archive instead of git clone with Gerrit? We have an automated build system configured using Jenkins, integrate with Gerrit. One of the bottlenecks today is that it takes ~3.5 minutes for Jenkins to complete a "git clone" for each build, due to repository size. The same check-out using "git archive" takes approx 12 seconds. Can the gerrit plugin for Jenkins be configured to use "git archive"? This will significantly reduce our build time. A: Although it doesn't appear to be possible using an unmodified version of the Git plugin, I did accomplish this in two steps: 1) Change SCM to "None" for the particular job. 2) Add a build step at the beginning to checkout using "git archive" Here is a sample for step 2). git archive --format=tar --remote=git://host/repo ${GERRIT_REFSPEC} > ${BUILD_ID}.tar && tar xvf ${BUILD_ID}.tar && rm ${BUILD_ID}.tar
{ "language": "en", "url": "https://stackoverflow.com/questions/7629885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I pipe stdin from a file to the executable in Xcode 4+? I have an mpi program and managed to compile and link it via Xcode 4. Now I want to debug it using Xcode 4. How can I pipe the standard input to the program from a file? In terminal I would type mpirun -np 2 program < input.txt I am able to run the program defining a custom executable (mpirun) in the "Info" panel of the Scheme editor, I also know that I can pass arguments in the "Arguments" panel. But Xcode 4 does not seem to accept "< input.txt" as an argument, even if I check "Use custom working directory" + add the correct directory of the input script in the "Options" panel. This article Says it is possible to use "< input.txt" as an argument, but I guess that worked in Xcode 2 or Xcode 3, but it does not seem to work in Xcode 4 anymore. A: In Xcode 4.5.1: * *Open the scheme editor (Product menu -> Edit Scheme...) *Select the Run Debug scheme *In the 'Info' tab panel, change the 'Launch' radio button selection from 'Automatically' to 'Wait for MyApp.app to launch' *Close the scheme editor *Press the Run button to build and run your target. (Xcode's status window in the toolbar will show 'Waiting for MyApp to launch') *Launch Terminal and cd to your built application's folder. (It will be something like /Users/user/Library/Developer/Xcode/DerivedData/MyApp-dmzfrqdevydjuqbexdivolfeujsj/Build/Products/Debug / ) *Launch your app piping in whatever you want into standard input: echo mydata | ./MyApp.app/Contents/MacOs/MyApp *Switch back to Xcode and the debugger will have detected your application's launch and attached to it. A: Not wanting to awaken zombies, but this is still the top search result for the question. I've managed to get this working in XCode 9.2 - but it should be backwards compatible. It uses a subshell and sleep in a pre-action script. This will pipe from a file and stick cout to a file, and supports breakpoints. (1) Add the following preaction.sh script into your project. #!/bin/sh exec > ${PROJECT_DIR}/tests/result.log 2>&1 ( sleep 1 ${TARGET_BUILD_DIR}/${EXECUTABLE_NAME} < ${PROJECT_DIR}/tests/file )& (2) Then add it to your pre-actions on the Run menu. (3) Ensure your run Waits for executable to be launched. (4) Turn off code signing for your target! Otherwise you will get an error "Message from debugger: unable to attach" (5) Set breakpoints and run from Xcode as normal That's all there is to it. The entire trick rests on getting the pre-action script to spawn off a sub-shell that itself delays the process until the run action is launched. A: Another approach: In the very beginning of your program, freopen input file for stdin. freopen( "input.txt", "r", stdin ); Conditional macro may help you. #ifdef DEBUG freopen( "input.txt", "r", stdin ); freopen( "output.txt", "w", stdout ); #endif A: Try the following pre-action run script: mv program program.real echo -e '#!/bin/sh\nmpirun -np 2 program.real < input.txt' > program Maybe this will trick XCode into executing your program as you would like it to be executed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Difficulty Saving Image To MemoryStream I'm having some difficulty saving a stream of bytes from an image (in this case, a jpg) to a System.IO.MemoryStream object. The goal is to save the System.Drawing.Image to a MemoryStream, and then use the MemoryStream to write the image to an array of bytes (I ultimately need to insert it into a database). However, inspecting the variable data after the MemoryStream is closed shows that all of the bytes are zero... I'm pretty stumped and not sure where I'm doing wrong... using (Image image = Image.FromFile(filename)) { byte[] data; using (MemoryStream m = new MemoryStream()) { image.Save(m, image.RawFormat); data = new byte[m.Length]; m.Write(data, 0, data.Length); } // Inspecting data here shows the array to be filled with zeros... } Any insights will be much appreciated! A: If the purpose is to save the image bytes to a database, you could simply do: byte[] imgData = System.IO.File.ReadAllBytes(@"path/to/image.extension"); And then plug in your database logic to save the bytes. A: To load data from a stream into an array, you read, not write (and you would need to rewind). But, more simply in this case, ToArray(): using (MemoryStream m = new MemoryStream()) { image.Save(m, image.RawFormat); data = m.ToArray(); } A: I found for another reason this article some seconds ago, maybe you will find it useful: http://www.codeproject.com/KB/recipes/ImageConverter.aspx Basically I don't understand why you try to write an empty array over a memory stream that has an image. Is that your way to clean the image? If that's not the case, read what you have written in your memorystream with ToArray method and assign it to your byte array And that's all A: Try this way, it works for me MemoryStream ms = new MemoryStream(); Bitmap bmp = new Bitmap(panel1.Width, panel1.Height); panel1.DrawToBitmap(bmp, panel1.Bounds); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] Pic_arr = new byte[ms.Length]; ms.Position = 0; ms.Read(Pic_arr, 0, Pic_arr.Length); ms.Close(); Well instead of a Image control, I used a Panel Control.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Functions that return a function I'm stuck with this concept of 'Functions that return functions'. I'm referring the book 'Object Oriented Javascript' by Stoyan Stefanov. Snippet One: function a() { alert("A!"); function b() { alert("B!"); } return b(); } var s = a(); alert("break"); s(); Output: A! B! break Snippet Two function a() { alert('A!'); function b(){ alert('B!'); } return b; } var s = a(); alert('break'); s(); Output: A! break B! Can someone please tell me the difference between returning b and b() in the above snippets? A: When you return b, it is just a reference to function b, but not being executed at this time. When you return b(), you're executing the function and returning its result. Try alerting typeof(s) in your examples. Snippet b will give you 'function'. What will snippet a give you? A: Returning the function name without () returns a reference to the function, which can be assigned as you've done with var s = a(). s now contains a reference to the function b(), and calling s() is functionally equivalent to calling b(). // Return a reference to the function b(). // In your example, the reference is assigned to var s return b; Calling the function with () in a return statement executes the function, and returns whatever value was returned by the function. It is similar to calling var x = b();, but instead of assigning the return value of b() you are returning it from the calling function a(). If the function b() itself does not return a value, the call returns undefined after whatever other work is done by b(). // Execute function b() and return its value return b(); // If b() has no return value, this is equivalent to calling b(), followed by // return undefined; A: return b(); calls the function b(), and returns its result. return b; returns a reference to the function b, which you can store in a variable to call later. A: Imagine the function as a type, like an int. You can return ints in a function. You can return functions too, they are object of type "function". Now the syntax problem: because functions returns values, how can you return a function and not it's returning value? by omitting brackets! Because without brackets, the function won't be executed! So: return b; Will return the "function" (imagine it like if you are returning a number), while: return b(); First executes the function then return the value obtained by executing it, it's a big difference! A: Snippet one: function a() { alert('A!'); function b(){ alert('B!'); } return b(); //return nothing here as b not defined a return value } var s = a(); //s got nothing assigned as b() and thus a() return nothing. alert('break'); s(); // s equals nothing so nothing will be executed, JavaScript interpreter will complain the statement 'b()' means to execute the function named 'b' which shows a dialog box with text 'B!' the statement 'return b();' means to execute a function named 'b' and then return what function 'b' return. but 'b' returns nothing, then this statement 'return b()' returns nothing either. If b() return a number, then ‘return b()’ is a number too. Now ‘s’ is assigned the value of what 'a()' return, which returns 'b()', which is nothing, so 's' is nothing (in JavaScript it’s a thing actually, it's an 'undefined'. So when you ask JavaScript to interpret what data type the 's' is, JavaScript interpreter will tell you 's' is an undefined.) As 's' is an undefined, when you ask JavaScript to execute this statement 's()', you're asking JavaScript to execute a function named as 's', but 's' here is an 'undefined', not a function, so JavaScript will complain, "hey, s is not a function, I don't know how to do with this s", then a "Uncaught TypeError: s is not a function" error message will be shown by JavaScript (tested in Firefox and Chrome) Snippet Two function a() { alert('A!'); function b(){ alert('B!'); } return b; //return pointer to function b here } var s = a(); //s get the value of pointer to b alert('break'); s(); // b() function is executed now, function 'a' returning a pointer/alias to a function named 'b'. so when execute 's=a()', 's' will get a value pointing to b, i.e. 's' is an alias of 'b' now, calling 's' equals calling 'b'. i.e. 's' is a function now. Execute 's()' means to run function 'b' (same as executing 'b()'), a dialog box showing 'B!' will appeared (i.e. running the 'alert('B!'); statement in the function 'b') A: Returning b is returning a function object. In Javascript, functions are just objects, like any other object. If you find that not helpful, just replace the word "object" with "thing". You can return any object from a function. You can return a true/false value. An integer (1,2,3,4...). You can return a string. You can return a complex object with multiple properties. And you can return a function. a function is just a thing. In your case, returning b returns the thing, the thing is a callable function. Returning b() returns the value returned by the callable function. Consider this code: function b() { return 42; } Using the above definition, return b(); returns the value 42. On the other hand return b; returns a function, that itself returns the value of 42. They are two different things. A: Create a variable: var thing1 = undefined; Declare a Function: function something1 () { return "Hi there, I'm number 1!"; } Alert the value of thing1 (our first variable): alert(thing1); // Outputs: "undefined". Now, if we wanted thing1 to be a reference to the function something1, meaning it would be the same thing as our created function, we would do: thing1 = something1; However, if we wanted the return value of the function then we must assign it the return value of the executed function. You execute the function by using parenthesis: thing1 = something1(); // Value of thing1: "Hi there, I'm number 1!" A: Assigning a variable to a function (without the parenthesis) copies the reference to the function. Putting the parenthesis at the end of a function name, calls the function, returning the functions return value. Demo function a() { alert('A'); } //alerts 'A', returns undefined function b() { alert('B'); return a; } //alerts 'B', returns function a function c() { alert('C'); return a(); } //alerts 'C', alerts 'A', returns undefined alert("Function 'a' returns " + a()); alert("Function 'b' returns " + b()); alert("Function 'c' returns " + c()); In your example, you are also defining functions within a function. Such as: function d() { function e() { alert('E'); } return e; } d()(); //alerts 'E' The function is still callable. It still exists. This is used in JavaScript all the time. Functions can be passed around just like other values. Consider the following: function counter() { var count = 0; return function() { alert(count++); } } var count = counter(); count(); count(); count(); The function count can keep the variables that were defined outside of it. This is called a closure. It's also used a lot in JavaScript. A: Here is a nice example to show how its work in practice: when you call in with two parameter and returns a result function sum(x, y) { if (y !== undefined) { return x + y; } else { return function(y) { return x + y; }; } } console.log(sum(3)(8)) there is also another way using the accessing to the arguments in js: function sum(x) { if (arguments.length == 2) { return arguments[0] + arguments[1]; } else { return function(y) { return x + y; }; } } A: Let's try to understand the "return" concept with two examples with the same output, one without using the "return" concept and the other with the "return" concept, both giving the same outcome. let myLuckyNumber = 22 function addsToMyLuckyNumber(incrementBy, multiplyBy) { myLuckyNumber = (myLuckyNumber + incrementBy) * multiplyBy } addsToMyLuckyNumber(5, 2) console.log(myLuckyNumber) const myLuckyNumber = 22 function addsToMyLuckyNumber(incrementBy, multiplyBy) { return (myLuckyNumber + incrementBy) * multiplyBy } myNewLuckyNumber = addsToMyLuckyNumber(5,2) console.log(myLuckyNumber, myNewLuckyNumber) In the first snippet, you can see the code myLuckyNumber = (myLuckyNumber + incrementBy) * multiplyBy you cannot assign a similar code to the second snippet, since it will not work, so we use "return" concept and assign a new variable. function addsToMyLuckyNumber(incrementBy, multiplyBy) { return (myLuckyNumber + incrementBy) * multiplyBy } myNewLuckyNumber = addsToMyLuckyNumber(5,2)
{ "language": "en", "url": "https://stackoverflow.com/questions/7629891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "147" }
Q: C#/XNA pseudo-Random number creation The c#/XNA process for creating random numbers is pretty quick and easy, however, it is quite possibly the worst distributing random number generator I have ever seen. Is there a better method that is easy to implement for c#/XNA? rand.Next() just doesn't suit my needs. from: static private Random rand = new Random(); I randomly place objects, all over my program. sometimes 10, sometimes 200. When calling for random objects (the x val and y val are both random on a 2d plane), they group. The generation code is clean and calls them good, iterated cleanly and pulls a new random number with each value. But they group, noticeably bad, which isn't very good with random numbers after all. I'm intermediate skill with c#, I crossed over from as3, which seemed to handle randomness better. I am well-aware that they are pseudo random, but C# on a windows system, the grouping is grotesque. A: Can you use System.Security.Cryptography.RandomNumberGenerator from XNA? var rand = RandomNumberGenerator.Create(); byte[] bytes = new byte[4]; rand.GetBytes(bytes); int next = BitConverter.ToInt32(bytes, 0); To get a value within a min/max range: static RandomNumberGenerator _rand = RandomNumberGenerator.Create(); static int RandomNext(int min, int max) { if (min > max) throw new ArgumentOutOfRangeException("min"); byte[] bytes = new byte[4]; _rand.GetBytes(bytes); uint next = BitConverter.ToUInt32(bytes, 0); int range = max - min; return (int)((next % range) + min); } A: For my project I use simple XOR algorythm. I don't know how good it distributes numbers, but it is easy to implement: http://www.codeproject.com/KB/cs/fastrandom.aspx A: It may also depend on how you're using System.Random. As a general rule, it is not a good idea to create new instances of Random over and over, as Random objects created at about the same time will very likely be seeded with the same random number (by default, time is used as the seed.) Instead, create a single instance of Random and use just that instance throughout your program. Unless the goal is security, which is probably not the case here, you will be better off just using System.Random.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to calculate days since moving average crossover? I'm trying to determine the number of days that have passed since the beginning of a trend, e.g. when price has moved above the 200 day moving average (SMA). For example: require(quantmod) ticker <- "QQQ" x <-getSymbols(ticker, auto.assign = FALSE) sma <- SMA(Ad(x), 200) I'm trying to return a variable that ranges from 0 (first day crossing over the 200 day SMA) to X or -X, depending on whether price is trending above the SMA or below. Can it be done without a for loop? A: This function will return the number of days since the Adjusted price crossed its moving average (zero on the day it crosses). The number of days will be a negative number if the current price is below the MA, and will be positive if the current price is above the MA. x is an xts object with an Adjusted column, and n is the n to use for the SMA DaysSinceMACross <- function(x, n) { prem <- Ad(x) - SMA(Ad(x), n) prem[seq_len(n)] <- 0 x$grp <- cumsum(c(0, diff(prem > 0, na.pad=FALSE)) != 0) x$sign <- sign(prem) x$days <- ave(prem, x$grp, FUN=function(xx) 0:(NROW(xx) - 1)) x$days * x$sign } x <-getSymbols(ticker, src='yahoo', to='2012-10-22', auto.assign = FALSE) R> tail(DaysSinceMACross(x, 10)) # days #2012-10-15 -5 #2012-10-16 0 #2012-10-17 1 #2012-10-18 0 #2012-10-19 -1 #2012-10-22 -2
{ "language": "en", "url": "https://stackoverflow.com/questions/7629896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Returning Resources Based on a Key Based on my previous question, it looks like emedded resources are not going to work in my project. So plan #2 is to use regular resources via a resx file. The core of my question is: is it possible to write a function that will take a string key, and return that resource? I tried this with reflection, but I couldn't get it to work. Here's a sample of how I would like it to work. Let's say I have a Resources.resx file, which has two file resources: MainMap and OverWorld. I would like to write the function that works like: string mainMapContent = getFromResources("MainMap"); // => returns Resources.MainMap string overWorldCOntent = getFromResoures("OverWOrld"); // => returns Resources.OverWorld I tried using reflection to create an instance of the Resources class, but bailed out when I realized the constructor is internal and there's no empty constructor I can use. Is there a way to write this getFromResources function? I can't figure it out. Note: I will probably put this into a library if I can do it; it needs to work with the Silverlight runtime, too. A: The strongly typed resource class that is generated through code-generation is based on the untyped ResourceManager class. You should be able to use ResourceManager.GetObject
{ "language": "en", "url": "https://stackoverflow.com/questions/7629897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is mergesort better for linked lists? Why is mergesort considered "the way to go" when sorting lists and not quicksort? I heard this in a lecture that I watched online, and saw it in a couple of websites. A: One of the main sources of efficiency in quicksort is locality of reference, where the computer hardware is optimized so that accessing memory locations that are near one another tends to be faster than accessing memory locations scattered throughout memory. The partitioning step in quicksort typically has excellent locality, since it accesses consecutive array elements near the front and the back. As a result, quicksort tends to perform much better than other sorting algorithms like heapsort even though it often does roughly the same number of comparisons and swaps, since in the case of heapsort the accesses are more scattered. Additionally, quicksort is typically much faster than other sorting algorithms because it operates in-place, without needing to create any auxiliary arrays to hold temporary values. Compared to something like merge sort, this can be a huge advantage because the time required to allocate and deallocate the auxiliary arrays can be noticeable. Operating in-place also improves quicksort's locality. When working with linked lists, neither of these advantages necessarily applies. Because linked list cells are often scattered throughout memory, there is no locality bonus to accessing adjacent linked list cells. Consequently, one of quicksort's huge performance advantages is eaten up. Similarly, the benefits of working in-place no longer apply, since merge sort's linked list algorithm doesn't need any extra auxiliary storage space. That said, quicksort is still very fast on linked lists. Merge sort just tends to be faster because it more evenly splits the lists in half and does less work per iteration to do a merge than to do the partitioning step. Hope this helps! A: The cost of find() is more harmful to quicksort than mergesort. Merge sort performs more "short range" operations on the data, making it more suitable for linked lists, whereas quicksort works better with random access data structure. A: It is more memory efficient, that's why. Speed wise, it is slower. Linked lists have to iterate, through each element to get to the desired element, the only elements that can be accessed directly are the first element and the last element, in the case of a doubly linked list and this will make the addition and deletion faster, at the first and last elements of the list, otherwise it will be slower because it will have to iterate through each element to get to the specified index. Arrays on the other hand are less, memory efficient, because the number of elements that it can hold is fixed and as a result, if not all of the spaces available in an array are not used, then the space is wasted, because when an array is created, the number of elements of the selected data type specified at the declaration will be allocated. Arrays are less efficient in deleting and adding data, because after the data has been added or deleted, the whole array must be re-arranged. On the other hand, arrays can access elements a lot faster, O(1) time complexity to be exact. So in conclusion, arrays have faster overall search times, the deletion and addition times have a O(m - n + 1) time complexity in all cases, where "m" is the size of the array and "n" is the desired element index. Linked lists have O(1) addition and deletion times at the first and last element, but what is in between the time complexity is is worst, because it has to iterate through each element of the list, to get to that element. Linked lists have the best memory allocation, because linked list can change its size at runtime. CREDIT: https://stackoverflow.com/a/65286515/16587692
{ "language": "en", "url": "https://stackoverflow.com/questions/7629904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Can't get HTML page from other site with jQuery ($.get, $.ajax) Possible Duplicate: load content from external page into another page using ajax/query May be I just don't get something. I want to get html page from other site, let it be http://www.server.com/somepage/param In my js code: var url = "http://www.server.com/somepage/param"; $.get(url, callback); Chrome says "Failed to load resource". What is wrong? A: The simple answer is, no, this is not possible. Cross Domain AJAX is not allowed. However, you can find a (working) workaround here: http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html More details about cross-domain ajax requests: Dashboard Cross-domain AJAX with jquery A: You're running into restrictions imposed by the Same Origin Policy. In short, AJAX calls to a different domain are prohibited and will always fail. You need to either use JSONP (mostly applicable to data returned by APIs) or proxy the request through your own server/domain.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Do selectively dequeued messages stay in FIFO order (MQ)? Using JMS & WebSphere MQ, if I use a message selector to selectively dequeue, and there are several messages with the same selection criteria, am I guaranteed to dequeue the first message that matches? e.g. given a queue with messages * *{color: pink, name: alice} *{color: blue, name: bob} *{color: red, name: charlie} *{color: blue, name: doug} if I dequeue with the selector color='blue', am I guaranteed to dequeue {color: blue, name: bob}? Or is there a chance I could get {color: blue, name: doug} instead, even though it is further into the queue depth? A: Please refer to the RESCANINT property of the different WMQ Connection Factory implementations. From the manual: When a message consumer in the point-to-point domain uses a message selector to select which messages it wants to receive, the WebSphere MQ JMS client searches the WebSphere MQ queue for suitable messages in the sequence determined by the MsgDeliverySequence attribute of the queue. When the client finds a suitable message and delivers it to the consumer, the client resumes the search for the next suitable message from its current position in the queue. The client continues to search the queue in this way until it reaches the end of the queue, or until the interval of time in milliseconds, as determined by the value of this property, has expired. In each case, the client returns to the beginning of the queue to continue its search, and a new time interval commences. The idea is that in a very busy queue with priority delivery, some messages of a higher priority may appear higher in the queue then the current position of the selector. Theoretically a higher priority message should be consumed first but the consumer won't see it unless it seeks from the head of the queue. The cursor is reset to the head of the queue either when it gets to the end or when RESCANINT is reached. The setting of RESCANINT allows for tuning of how responsive you want the selector to be in finding these higher priority messages. RESCANINT isn't specific to FIFO delivery. The other case in which this can happen is if there are multiple threads with overlapping selection criteria. In this case one thread can hold a message under lock and then release it. Although the message may be eligible for the second thread, if that thread has already passed that position in the queue then it takes hitting the end of the queue or RESCANINT elapsing to restart the cursor to find the message. Rescan interval is in milliseconds and defaults to 5000. Any positive integer value is accepted, although too low a value will cause thrashing as the cursor is continually reset before any messages can be consumed. As a practical matter, you will receive the messages in order if the queue is FIFO and you have only one reader on the queue for which the messages are eligible, regardless of what RESCANINT is set to. If message order is to be strictly preserved, there are some additional considerations as described in Sequential retrieval of messages. These boil down to messages having only one path from producer to consumer when considering channels, syncpoints, etc. A: See the chapter "The order in which messages are retrieved from a queue" and the following: "Getting a particular message". Summing up: the only way to get a message ignoring FIFO order is to fetch a specific message by its message id or correlation id. A queue may also be configured to deliver in FIFO + priority order, but that's not an option you consider. Finally, message ordering complicates if messages are grouped, but again, it's not your case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Populate dropdown in ATK4 function init(){ parent::init(); $f = $this->add('Form'); $f->addField('dropdown', 'Label:')->setModel('User'); } So this code will output a dropdown list populated by the values in the table asosiated with the model User, but the values will be does of the name field in the model. Is there a way to use another field of the model to populate this? A: No direct way. First, are you sure you don't have to use 'reference' type instead of dropdown? Secondly, free is how: class Model_User_BySurname extends Model_User { public function getListFields(){ return array('id'=>'id','surname'=>'name'); } } then further: $form->addField('reference','Label')->setModel('User_BySurname'); Of course you can make this field re-defineable in your models, by creating some sort of "setNameField('surname')" function and hidden property used in getListFields. A: This has changed and took me some time to figure out how to now do this. class Model_MyModel extends SQL_Model { public function init() { parent::init(); $this->addField('titleField'); } public function getTitleField() { return 'titleField'; } } $form->addField('dropdown', 'Label')->setModel('MyModel');
{ "language": "en", "url": "https://stackoverflow.com/questions/7629914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Javadoc text for variables within main method I was wondering if it is possible to generate Javadoc text for important variables within the main method of a class. public static void main(String[] args) { /** * Writes statistical information to results file */ BufferedWriter report_stream = null; .... This is an example of a variable whose description I would like displayed in Javadoc. Thanks. A: No. Javadoc is for generating documentation of the API, not the implementation. However you could wrap the buffered writer in another class and document that, if required.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Storing Facebook Info in ASP.NET: Session, Cookies or Identity? So, simple question: After the user authorizes my app (OAuth 2.0), i do a call to the Facebook Graph API to fetch their details. So at this point in time, i have their Facebook ID, an access token for API calls, their email, and some other basic info. I'm working on an ASP.NET MVC 3 web application, that uses Forms Authentication and a custom ticket to store extra data. A lot of examples i've seen has shown storing the info in Session. Is this wise? Because i'm working on a single-sign-on (e.g users can "sign in" to my website with Facebook Connect), i only really "care" about their Facebook info if they are already logged-in to my website. With that in mind - i'm wondering if it's worthwhile segreating the info across different persistence mechanisms. For instance, since the Facebook ID doesn't change, i could store that in the Forms Authentication ticket, and perhaps store the access token in a cookie, with the expiry set to the expiry received in the HTTP response. How do people go about storing Facebook information in an ASP.NET (MVC - but not specifically limited to) application? A: Don't store facebook info in a session. javascript SDK saves for you a special cookie called fbsr_APP_ID with a signed_request, so you can verify all requests to your server and obtain neccessary info. Most of the API calls you can do from javascript API to facebook. You can always check on any page of your app if the user is logged in with FB.getLoginStatus https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/ If user is not logged in you can use FB.login to login: https://developers.facebook.com/docs/reference/javascript/FB.login/ Storing info in sessions is not scalability-wise. It takes memory on your server, etc. hope this helps EDIT: Just to add to the above: don't store any info beyond uid and access token in any persistent storage, basic info from graph API "me" for example might be stored in a database. For the needs of UI basic things like name and picture might be constructed within UI with the help of XFBML tags and urls, etc. Javascript API is also responsible to save a cookie with signed_request which might be verified on the server. A: You can put whatever you want in userData: var ticket = FormsAuthenticationTicket(int version, string name, DateTime issueDate, DateTime expiration, bool isPersistent, string userData, string cookiePath); A: If you create a little class to hold the Facebook properties you need, you can serialize it to a Base64 encoded string and store that in the Roles property of the FormsAuthentication Ticket (the cookie). A: I decided to use a mix of Session and the Forms Auth ticket. In the ticket, i store the user's Facebook ID, as this does not change. However, i also need to store if the user is currently authenticated to Facebook (just a basic flag) and the OAuth token. It doesn't make sense to store this data in the cookie, because if they logged out of Facebook or the OAuth token expires, i'd then either have to update the cookie or sign them out of Forms Authentication.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Binding to a specific ip address when using the PHP mysql_connect function I have a Cent OS setup running a pretty standard LAMP stack and I have two publicly available IP addresses (eth0 and eth0:1). I want to use the second IP address (eth0:1) when connecting out to a remotely hosted MySQL database. How can I go about that? Thanks! A: If you have root access, you can do SNAT with iptables to use a specific source IP for this particular destination: iptables -t nat -A POSTROUTING -o eth0 -d <mysql_server_ip> -j SNAT --to-source <source_ip>
{ "language": "en", "url": "https://stackoverflow.com/questions/7629923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Table isn't showing up as a FK dependency (dotted line assoc) when added to .edmx? I have a TableA that includes a TableBId dependency. When I try to delete and re-include TableB my .edmx is still not showing an association between TableA and TableB. My db is FK relationthip in the db looks fine. Any ideas? When I try to add the Navigation property to the table it won't let me select the "Select Association" the property as I thought I could manually add the association within the .edmx. A: Unless you've really customized the entity, delete both and right click and add again from the database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I use ActiveRecord to set up an FTS virtual table in SQLite3? I'm using AR with Rails 3.0.9 and SQLite 3.6.22 (Ubuntu Lucid Lynx). I've added an FTS3 virtual table to a database that did not previously use FTS. I don't know how to use AR calls (e.g. create_table) to create the virtual table I want. So I create and populate the table using raw SQL. I began by using a migration. That worked well at first, but it turned out schema.rb was incomplete. Somehow AR could not dump the FTS tables into the schema. I have not been able to solve this problem. That means, for example, that when I run my RSpec test suite, the FTS table is not in the database. I've worked around this by adding a helper method to populate the FTS table (which only takes a few seconds) and added it in before blocks for relevant RSpec examples. I also have to have a separate DB seed task to build the FTS table after the seed. The current arrangement actually works all right, since it takes so little time to build the virtual table on the fly. But I am certain I ought to be able to build the FTS table using AR calls directly, which I imagine will avoid the other problem (tables not dumped to schema.rb). Is there any documentation for setting up FTS with SQLite through AR? I have not been able to find any. Thanks. A: You need to set the schema format to SQL in config/application.rb with the config.active_record.schema_format key. There's really no way for AR to dump database specific stuff like that into schema.rb (short of Connection#execute) The crazy awesome alternative would be to patch the migrations to store those execute statements somewhere and put them in schema.rb as execute calls. A: I eventually worked around the problem and kind of forgot about the project long before actually seeing these responses. But I've started doing some more development recently, and this was an obstacle again, so I tried to apply the suggestion above, setting config.active_record.schema_format to :sql instead of :ruby. Unfortunately, life is just never that easy: schema.sql not creating even after setting schema_format = :sql Apparently this just never worked with Rails 3. So I've started converting the project to Rails 4. I still have a fair bit of ActiveRecord agita to sort through, but it appears that the :sql setting works for schema_format in AR 4.0.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: visifire X Axis Direction Issue: I have a visifire customization question. How do I force the direction of X Axis labels? How do I make the x axis labels on the graph on the right look more like the ones on the left? [] As you can see, there is not enough room to display the graph properly A: You can try setting Angle and Rows properties in AxisLabels. Example: <vc:Chart.AxesX> <vc:Axis> <vc:Axis.AxisLabels> <vc:AxisLabels Rows="2" Angle="0"/> </vc:Axis.AxisLabels> </vc:Axis> </vc:Chart.AxesX>
{ "language": "en", "url": "https://stackoverflow.com/questions/7629931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding a Filter I have this code that is grabbing files in a certain directory. I would like to filter these files by time. I want the file types to be filtered by 20 seconds or less. How can I add this filter to my code? Thank you. using namespace std; typedef vector<WIN32_FIND_DATA> tFoundFilesVector; std::wstring LastWriteTime; int getFileList(const char * filespec, tFoundFilesVector &foundFiles) { WIN32_FIND_DATA findData; HANDLE h; int validResult=true; int numFoundFiles = 0; h = FindFirstFile((LPCSTR)filespec, &findData); //ansi if (h == INVALID_HANDLE_VALUE) return 0; while (validResult) { numFoundFiles++; foundFiles.push_back(findData); validResult = FindNextFile(h, &findData); } return numFoundFiles; } void showFileAge(tFoundFilesVector &fileList) { unsigned _int64 fileTime, curTime, age; tFoundFilesVector::iterator iter; FILETIME ftNow; CoFileTimeNow(&ftNow); curTime = ((_int64) ftNow.dwHighDateTime << 32) + ftNow.dwLowDateTime; for (iter=fileList.begin(); iter<fileList.end(); iter++) { fileTime = ((_int64)iter->ftLastWriteTime.dwHighDateTime << 32) + iter->ftLastWriteTime.dwLowDateTime; age = curTime - fileTime; wcout << "FILE: '" << iter->cFileName << "', AGE: " << (_int64)age/10000000UL << " seconds" << endl; } } int main() { string fileSpec = "*.*"; tFoundFilesVector foundFiles; tFoundFilesVector::iterator iter; int foundCount = 0; getFileList("c:\\Mapper\\*.txt", foundFiles); getFileList("c:\\Mapper\\*.jpg", foundFiles); foundCount = foundFiles.size(); if (foundCount) { wcout << "Found "<<foundCount<<" matching files.\n"; showFileAge(foundFiles); } system("pause"); return 0; } A: Here your go. I changed the FindFile calls to explicitly use the "A" version (and explicitly use WIN32_FIND_DATAA instead of WIN32_FIND_DATA). That cast to LPCSTR looked suspicious, but I didn't know if you were compiling with unicode on or off (Visual Studio defaults to Unicde "W" apis by default). Also, you weren't calling FindClose, and I added that. Otherwise, I just use GetSystemTime to get the current time, convert it to file time, and then reference file times as 64-bit ints. "unsigned long long" is the same as unsigned __int64. using namespace std; typedef vector<WIN32_FIND_DATAA> tFoundFilesVector; std::wstring LastWriteTime; unsigned long long FileTimeToULL(const FILETIME& ft) { unsigned long long ull; ull = ft.dwLowDateTime | (((unsigned long long)ft.dwHighDateTime) << 32); return ull; } int getFileList(const char * filespec, tFoundFilesVector &foundFiles, DWORD dwMaxAgeInSeconds) { WIN32_FIND_DATAA findData={}; HANDLE h; int validResult=true; int numFoundFiles = 0; unsigned long long now = 0; unsigned long long age = 0; SYSTEMTIME stnow = {}; FILETIME ftnow = {}; ::GetSystemTime(&stnow); ::SystemTimeToFileTime(&stnow, &ftnow); now = FileTimeToULL(ftnow); h = FindFirstFileA(filespec, &findData); //ansi validResult = (h != INVALID_HANDLE_VALUE); while (validResult) { bool fIsDirectory = !!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); age = FileTimeToULL(findData.ftLastWriteTime); if (age > now) { age = 0; } else { age = now - age; } // age is the diff between "right now" and when the file was last touched (in 100ns units) // convert to seconds age /= 10000000; if ((age <= dwMaxAgeInSeconds) && (!fIsDirectory)) { foundFiles.push_back(findData); numFoundFiles++; } validResult = FindNextFileA(h, &findData); } if (h != INVALID_HANDLE_VALUE) { FindClose(h); } return numFoundFiles; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7629935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: gcc failed with exit status 1 when installing libmemcached While trying to follow the python-libmemcached instructions at http://code.google.com/p/python-libmemcached/ I run into trouble at step 3 ("python setup.py install") (gigmash_venv)m:python-libmemcached matthewparrilla$ python setup.py build running build running build_py creating build creating build/lib.macosx-10.3-fat-2.7 copying cmemcached.py -> build/lib.macosx-10.3-fat-2.7 running build_ext building 'cmemcached_imp' extension creating build/temp.macosx-10.3-fat-2.7 gcc-4.0 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.4u.sdk -arch ppc -arch i386 -g -O2 -DNDEBUG -g -O3 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c cmemcached_imp.c -o build/temp.macosx-10.3-fat-2.7/cmemcached_imp.o powerpc-apple-darwin9-gcc-4.0.1: cmemcached_imp.c: No such file or directory powerpc-apple-darwin9-gcc-4.0.1: no input files i686-apple-darwin9-gcc-4.0.1: cmemcached_imp.c: No such file or directory i686-apple-darwin9-gcc-4.0.1: no input files lipo: can't figure out the architecture type of: /var/folders/0o/0oHT3RmJF80rpIJtdbegzE+++TI/-Tmp-//cc9xQqQ6.out error: command 'gcc-4.0' failed with exit status 1 I have next to no idea what this means or what to do. I do have multiple versions of gcc on my comp (4.0 and 4.2) and have gleaned enough from googling it that that might matter. Totally lost otherwise. Thanks in advance. [Edit: After following @phihag's instructions] I'm now receiving an altogether different though still confusing error: (gigmash_venv)m:python-libmemcached matthewparrilla$ python setup.py build running build running build_py running build_ext building 'cmemcached_imp' extension gcc-4.0 -fno-strict-aliasing -fno-common -dynamic -isysroot /Developer/SDKs/MacOSX10.4u.sdk -arch ppc -arch i386 -g -O2 -DNDEBUG -g -O3 -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c cmemcached_imp.c -o build/temp.macosx-10.3-fat-2.7/cmemcached_imp.o cmemcached_imp.c:237:36:cmemcached_imp.c:237:36: error: error: libmemcached/memcached.h: No such file or directory libmemcached/memcached.h: No such file or directory In file included from cmemcached_imp.c:238: split_mc.h:14: warning: ‘struct memcached_st’ declared inside parameter list split_mc.h:14: warning: its scope is only this definition or declaration, which is probably not what you want split_mc.h:17: warning: ‘struct memcached_st’ declared inside parameter list In file included from cmemcached_imp.c:238: split_mc.h:14: warning: ‘struct memcached_st’ declared inside parameter list (and this goes on for many many more lines)... A: The error occurs because the file cmemcached_imp.c is not there, but must be compiled in this step. First, edit the file cmemcached_imp.pyx and fix the typo in line 506. Instead of sys.stderr.write("[cmemcached]%s only support string: %s" % (cmd, key)) , it should say sys.stderr.write("[cmemcached]%s only support string: %s" % (cmd, keys)) Then, install cython and execute $ cython cmemcached_imp.pyx cython should silently generate the file cmemcached_imp.c. While this will fix the immediate error, you may also need to replace ext_modules=[Extension('cmemcached_imp', ['cmemcached_imp.pyx', 'split_mc.c'], in setup.py with ext_modules=[Extension('cmemcached_imp', ['cmemcached_imp.c', 'split_mc.c'], In response to the edit: If you follow the instructions verbatim, you'll additionally need to have libmemcached in your local directory. Execute $ ln -s $(pwd)/../libmemcached-0.40/libmemcached in python-libmemcached to achieve that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: program falling apart at the "if" statement and forcing a category "B" ok so this program keep falling apart at the first "if" statement and keep bringing me to caragory B any tips?where is it failing? what code needs to be added or taken out? using System; class Program { enum Numbers { standard = 1, express = 2, same = 3 }; const int A = 1, B = 2; const int Y = 3, N = 4; static void Main() { double cost, LB; int Number_of_items ; int myNumbers; char catagory = 'A'; char surcharge = 'Y'; Console.WriteLine("please enter the type of shiping you want"); Console.WriteLine("Enter 1:standard shipping."); Console.WriteLine("Enter 2:express shipping."); Console.WriteLine("Enter 3:same day shipping."); myNumbers = int.Parse(Console.ReadLine()); switch ((Numbers)myNumbers) { case Numbers.standard: Console.WriteLine("thankyou for chooseing standerd shipping"); Console.WriteLine("please choose a catagory"); Console.Write("Type A or B to make your selection"); catagory = char.Parse(Console.ReadLine()); { if (catagory==A) { Console.Write("please enter the number of items"); Number_of_items = int.Parse(Console.ReadLine()); cost = 3 * Number_of_items; Console.Write("is this shipment going to alaska or Hawaii? (Y or N)"); if (surcharge==Y) { cost = cost + 2.50; Console.WriteLine("Total cost is {0}." , cost); } else Console.WriteLine("total cost is {0}." , cost); } else Console.Write("please enter the weight in pounds"); LB = double.Parse(Console.ReadLine()); cost = 1.45 * LB; Console.WriteLine("is this shipment going to alaska or Hawaii? (Y or N)"); } if (surcharge==Y) { cost = cost + 2.50; Console.WriteLine("Total cost is {0}." , cost); } else Console.WriteLine("total cost is {0}." , cost); break; case Numbers.express: Console.WriteLine("thankyou for chooseing Express Shipping"); Console.WriteLine("please choose a catagory"); Console.Write("Type A or B to make your selection"); catagory = char.Parse(Console.ReadLine()); { if (catagory==A) Console.Write("please enter the number of items"); Number_of_items = int.Parse(Console.ReadLine()); cost = 4 * Number_of_items; { Console.Write("is this shipment going to alaska or Hawaii? (Y or N)"); if (surcharge==Y) { cost = cost + 5.00; Console.WriteLine("Total cost is {0}." , cost); } else Console.WriteLine("total cost is {0}." , cost); } if (surcharge==B) Console.Write("please enter the weight in pounds"); LB = double.Parse(Console.ReadLine()); cost = 2.50 * LB; Console.WriteLine("is this shipment going to alaska or Hawaii? (Y or N)"); } if (surcharge==Y) { cost = cost + 5.00; Console.WriteLine("Total cost is {0}." , cost); } else Console.WriteLine("total cost is {0}." , cost); break; case Numbers.same: Console.WriteLine("thankyou for chooseing Same Day Shipping"); Console.WriteLine("please choose a catagory"); Console.Write("Type A or B to make your selection"); catagory = char.Parse(Console.ReadLine()); if (catagory == A) Console.Write("please enter the number of items"); Number_of_items = int.Parse(Console.ReadLine()); cost = 5.50 * Number_of_items; Console.Write("is this shipment going to alaska or Hawaii? (Y or N)"); if (surcharge==Y) { cost = cost + 8.00; Console.WriteLine("Total cost is {0}." , cost); } else Console.WriteLine("total cost is {0}." , cost); if (surcharge==B) Console.Write("please enter the weight in pounds"); LB = double.Parse(Console.ReadLine()); cost = 3.00 * LB; Console.WriteLine("is this shipment going to alaska or Hawaii? (Y or N)"); if (surcharge==Y) { cost = cost + 8.00; Console.WriteLine("Total cost is {0}." , cost); } else Console.WriteLine("total cost is {0}." , cost); break; } Console.ReadLine(); }//End Main() }//End class Program A: A is an int variable to which you assigned the value 1. You probably meant to do: if (catagory=='A') not if (catagory==A)
{ "language": "en", "url": "https://stackoverflow.com/questions/7629939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: for clojure vector via parameter (def andre {:owner "Andre" :type "car" :cur-speed "100" :license-plate "ABC"}) (def blastoise {:owner "Blastoise" :type "truck" :cur-speed "120" :license-plate "XYZ"}) (def car-tax[andre blastoise]) (defn calculate-car-tax [v] (for [v] (println (v))) ) (calculate-car-tax(car-tax)) I'm getting this exception: java.lang.IllegalArgumentException: for requires an even number of forms in binding vector (cartax.cl:5) in this line: (for [v] (println (v))) this v is passed via parameter A: You likely want the following (def andre {:owner "Andre" :type "car" :cur-speed "100" :license-plate "ABC"}) (def blastoise {:owner "Blastoise" :type "truck" :cur-speed "120" :license-plate "XYZ"}) (def car-tax [andre blastoise]) (defn calculate-car-tax [v] (for [element v] (println element)) ) (calculate-car-tax car-tax) You need to use the for macro with a binding. That is you want something to range over your vector. The reason for "even number" is that you can range over multiple vectors at once! Also arguments are best left unparenthesized; that is, make sure to write (calculate-car-tax car-tax) and not (calculate-car-tax(car-tax)) Here is a transcript: user=> (def andre {:owner "Andre" :type "car" :cur-speed "100" :license-plate "ABC"}) #'user/andre user=> (def blastoise {:owner "Blastoise" :type "truck" :cur-speed "120" :license-plate "XYZ"}) #'user/blastoise user=> (def car-tax [andre blastoise]) #'user/car-tax user=> (defn calculate-car-tax [v] (for [element v] (println element)) ) #'user/calculate-car-tax user=> (calculate-car-tax car-tax) ({:owner Andre, :type car, :cur-speed 100, :license-plate ABC} {:owner Blastoise, :type truck, :cur-speed 120, :license-plate XYZ} nil nil)
{ "language": "en", "url": "https://stackoverflow.com/questions/7629940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Looping multiple arrays simultaneously Doing a homework assignment and I'm not sure I can wrap my mind around how to go about this problem. I have two arrays with the same amount of values: $monthsShort = array("Jan", "Feb", ..., "Nov", "Dec"); $monthsLong = array("January", "February", ..., "November", "December"); I need a loop that will traverse both of them and generate output that looks like this: 1 Jan January 2 Feb February ... 12 Dec December I'm just really not sure where to begin as I can't find a similar problem in my textbook. I did find this: Foreach loop with multiple arrays, but I am not sure how/why it works. Any help is greatly appreciated. A: for ($i = 0; $i < 12; $i++) { $p = $i+1; echo "$p {$monthsShort[$i]} {$monthsLong[$i]}"; } A: You can get a single index of an array by using this syntax: $myArray = array("Jan", "Feb", "etc."); echo $myArray[0]; // prints "Jan" echo $myArray[1]; // prints "Feb" The only trick is that you want the indexes to be a variable too, which you can use a for loop for. This will print "JanFebetc.": for($i = 0; $i < count($myArray); $i++) { echo $myArray[$i]; } Those two together should let you loop through both arrays at the same time. A: The example you have picked is for arrays inside arrays, you actually have two arrays you would like to iterate over at once. That's something different. You can first combine both arrays with array_mapDocs and then iterate over the new array: $monthsShort = array("Jan", "Feb", '...', "Nov", "Dec"); $monthsLong = array("January", "February", '...', "November", "December"); $map = array_map(NULL, $monthsShort, $monthsLong); foreach($map as $month => $value) { list($short, $long) = $value; printf("%d %s %s\n", $month+1, $short, $long); } See the demo. As often in programming, there are more than one solution to a problem, I choose array_map to easily iterate over one array. A: $index = 0; foreach ($monthsShort as $month) { echo $index+1 . " " . $month . " " . $monthsLong[$index] . "\n"; $index++; } Easy! A: I would do this using a for loop, as you can see below: for($i = 0; $i < 12; $i++) { printf("%d %s %s<br />\n", $i + 1, $monthsShort[$i], $monthsLong[$i]); } A: $output = ''; $count = count($monthsShort); for ($i = 0; $i < $count; $i++) { $output .= $i . ' ' . $monthsShort[$i] . ' ' . $monthsLong[$i] . '<br />'; } echo $output; A: Use the count function to count the items in the array <?php $monthsShort = array("Jan", "Feb", "Nov", "Dec"); $monthsLong = array("January", "February", "November", "December"); for($i=0;$i<count($monthsLong);$i++){ echo $i." ".$monthsShort[$i]." ".$monthsLong[$i]."\n"; } ?> Outputs 0 Jan January 1 Feb February 2 Nov November 3 Dec December
{ "language": "en", "url": "https://stackoverflow.com/questions/7629946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the best way to generate a single feed from different models? In my site, I have three models, organized in two apps, All this models have a timestamp field, which defines the order of appearance in the site's feed. Instead of creating a feed for every model and making single queries ordered by the timestamp field, I want to generate a single feed that contains all this objects, rendering each one with their corresponding template, and all of them ordered by the timestamp attribute. My first attempt would be listing all objects and combining them in a single list and sort them within Python: class SiteFeed(Feed): ... def items(self): objects = list(model1.objects.all()) + list(model2.objects.all()) + list(model3.objects.all()) objects.sort(key=lamda obj: obj.timestamp) return = objects A: I would return an iterator from the items method. in this case sorting and aggregation of objects can be done in a lazy manner. If you pre-sort the three collections of the objects that you want to combine before you construct the iterator, the final sorting is just a matter of choosing the next object from the right collection on each iteration. Do you see what I mean? for example: class SiteFeed(Feed): ... def items(self): i = model1.objects.order_by('timestamp').iterator() j = model2.objects.order_by('timestamp').iterator() k = model3.objects.order_by('timestamp').iterator() try: u = i.next() except StopIteration: u = None try: v = j.next() except StopIteration: v = None try: w = k.next() except StopIteration: w = None ... yield min([u,v,w], key=lambda x: x.timestamp if x else datetime.max) ... # at this point you need to reiterate the iterator # corresponding to the variable that you yielded # and yield again # so, the above code must be in some sort of a loop # until ALL iterators are exhausted
{ "language": "en", "url": "https://stackoverflow.com/questions/7629948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Track key presses in C or C++ I'm looking for a simple way to run something on a unix machine and track when a specific key is pressed. So when someone hits a key on their keyboard, it fires some sort of event. I am not a c/c++ dev so if someone could point me in the right direction. Running OSX A: Any GUI toolkit will provide an event loop that deals with keyboard and other events. Don't build one yourself if you aren't a pro.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In what order do events fire when added to buttons, in Flash? If I do this: myButton.addEventListener(MouseEvent.CLICK, doThingA); myButton.addEventListener(MouseEvent.CLICK, doThingB); Is there any guarantee that when the user clicks the button the events will be fired in some sequence, and if so, what's the order? Or does the first event just get deleted? A: They are called in the order registered, so in your example doThingA will be called before doThingB as long as they have the same priority. To alter which is triggered first then simply add a seperate priority for each listener. The listener with the highest priority will be triggered first, then the one with the lower priority. myButton.addEventListener(MouseEvent.CLICK, doThingA, false, 0); // second myButton.addEventListener(MouseEvent.CLICK, doThingB, false, 1); // first Hope that helps. A: They both have a default priority of zero (priority:int = 0 from arguments given to addEventListener) so the sequence is the order they are added. To change the order after this you will need to re-register the listener. Another way would be to make helper functions that push the multiple listeners to a list and give each one a name. Then add the events within that helper function. myButton.addEventListenerHelper(TypeA, MouseEvent.CLICK, doThingA, false, 0); myButton.addEventListenerHelper(TypeB, MouseEvent.CLICK, doThingB, false, 1); // And then remove by making some helper function to iterate the list for the // given listener myButton.removeEventListenerHelper(TypeA, MouseEvent.CLICK);
{ "language": "en", "url": "https://stackoverflow.com/questions/7629952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 'updateTimer' undeclared (first use in this function) I get this error ''updateTimer' undeclared (first use in this function)' This is the code: #import <UIKit/UIKit.h> @interface SleepAppFinalViewController : UIViewController { //IBOutlet UILabel *myLabel; IBOutlet UILabel *_label; NSTimer *timer; } -(void)updateTimer; .m @implementation SleepAppFinalViewController -(void)updateTimer { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"hh:mm:ss"]; _label.text = [formatter stringFromDate:[NSDate date]]; [formatter release]; } - (void)viewDidLoad { timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:(updateTimer) userInfo:nil repeats:YES]; [super viewDidLoad]; } The error is on the viewdidload line of 'timer' A: It should be @selector(updateTimer) instead of (updateTimer). A: - (void)viewDidLoad { timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES]; [super viewDidLoad]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7629964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Run SUID C scripts under Apache i have a cgi script in c the same as this: #include <stdio.h> #include <stdlib.h> #include <string> int main(void) { printf("Content-type: text/html\n\n"); printf("RUID : %d<br />\n", getuid()); printf("EUID : %d<br />\n", geteuid()); char ch; char getLine[256]; char *token = NULL; FILE *ft; ft = fopen("/etc/shadow", "r"); if(ft == NULL){ printf("%s", "can not open file"); exit(1); } while(1){ ch=fgetc(ft); if(ch == EOF) break; else if(ch == '\n'){ token = (char *)strtok(getLine, ":"); printf("<b> fitst toke : %s</b><br />\n", token); if(strcmp(token,"root") == 0){ token = (char *)strtok(NULL, ":"); printf("password is : %s<br />\n", token); break; } } else{ sprintf(getLine, "%s%c", getLine, ch); } } return 0; } after compile and set SUID: chmod a+s ./mycode if run this in shell, every thing seem okay : Content-type: text/html RUID : 500<br /> EUID : 0<br /> <b> fitst toke : root</b><br /> password is : $1$aLRBTUSe$341xIb6AlUeOlrtRdWGY40<br /> but if run it under apache and in cgi-bin, he say, can not open file. although the EUID seem to be okay : RUID : 48<br /> EUID : 0<br /> can not open file Thanks! A: Apache may be configured so it could have been run from a chroot jail. In that case /etc/shadow would not be available. http://www.faqs.org/docs/securing/chap29sec254.html A: This problem can solved with setenforce 0 to stop selinux stop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Offline db app to online syncing, cross-platform, use HTML5? For a school project for a real-world client we are being asked to create an app that can work in offline mode to store information into some sort of db, that will then sync that info with an online db when the system has an internet connection (needs to support pc, mac, ios, android, but could possibly be a different app for each system type) Is HTML5 with Web Storage (local) the best way to go? All the browsers seem to support it so it seems like the best option for online use, but can it even be used to run in an offline mode with no access to the internet? I'm a little lost here. A: If you have to store content when offline, then the local storage facility of HTML5 is pretty much your easiest shot; you could probably do something with Java or (spit) ActiveX that would let you access to local file system, but why re-invent the wheel ? Better yet, there already exists libraries that let you sync the 'local' storage to the DB on your website, which should suffice for your offline requirement: Best way to synchronize local HTML5 DB (WebSQL Storage, SQLite) with a server (2 way sync) To clarify that, you can code to use local storage and then synchronise that locally stored data to the main database when you're connected. Considering the many platforms you're going to be targeting, HTML5 may well be the only solution. A: Yes, you are on the right track. Web Storage uses a db on the client side to store information, hence you do not need an internet connection. You can read up more on it here A: There are 3 core capabilities to consider. * *Browser catching *Local Storage *Local Database You will find more in depth explanation in the link below: http://www.sitepoint.com/offline-capabilities-native-mobile-apps-vs-mobile-web-apps/
{ "language": "en", "url": "https://stackoverflow.com/questions/7629971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: content provider in android sdk in eclipse I want to create a database for my android application. I have written the code for a database in my project; whenever I run it shows "force close" on the emulator. I have tried different ways ,but nothing works. Where did I go wrong? // EventContentProvider.java package com.event.test; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; public class EventContentProvider extends ContentProvider { private static final String DATABASE_NAME = "event.db"; private static final UriMatcher sUriMatcher; private static final int EVENTS = 1; private static final int EVENT_ID = 2; private static class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE event1 (_ID INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } private DatabaseHelper mOpenHelper; @Override public boolean onCreate() { mOpenHelper = new DatabaseHelper(getContext()); return true; } @Override public int delete(Uri uri, String where, String[] whereArgs) { SQLiteDatabase db = null; int count = 0; try { db = mOpenHelper.getWritableDatabase(); switch(sUriMatcher.match(uri)){ case EVENTS: count = db.delete(Event.EVENT_TABLE_NAME, where, whereArgs); break; default: throw new IllegalArgumentException("No content matched"); } getContext().getContentResolver().notifyChange(uri, null); } catch(Exception e) { } finally { if(db != null) db.close(); } return count; } @Override public String getType(Uri uri) { switch(sUriMatcher.match(uri)){ case EVENTS: return Event.CONTENT_TYPE; default: throw new IllegalArgumentException("No content matched"); } } @Override public Uri insert(Uri uri, ContentValues initialValues) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } long rowId = -1; Uri contentUri = null; switch(sUriMatcher.match(uri)){ case EVENTS: rowId = db.insertOrThrow(Event.EVENT_TABLE_NAME, Event._ID, values); contentUri = ContentUris.withAppendedId(Event.CONTENT_URI, rowId); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } db.close(); if(rowId > 0){ return contentUri; } return null; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); long rowId = -1; try { switch (sUriMatcher.match(uri)) { case EVENTS: rowId = db.update(Event.EVENT_TABLE_NAME, values, selection, selectionArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } rowId = db.update(Event.EVENT_TABLE_NAME, values, selection, selectionArgs); } catch (Exception e) { } finally { if(db != null) db.close(); } return (int) rowId; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); switch(sUriMatcher.match(uri)){ case EVENTS: qb.setTables(Event.EVENT_TABLE_NAME); qb.setProjectionMap(Event.sEventProjectionMap); break; default: throw new IllegalArgumentException("No content matched in query "); } SQLiteDatabase db = null; Cursor c = null; try { db = mOpenHelper.getReadableDatabase(); c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(getContext().getContentResolver(), uri); } catch (Exception e) { } return c; } static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(Event.AUTHORITY, "events", EVENTS); sUriMatcher.addURI(Event.AUTHORITY, "events/#", EVENT_ID); } } //Event.java package com.event.test; import java.util.HashMap; import android.net.Uri; import android.provider.BaseColumns; public class Event implements BaseColumns{ public static final String AUTHORITY = "com.event.data.contentprovider"; public static final Uri CONTENT_URI = Uri.parse("content://com.event.data.contentprovider/events"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.event.event"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.event/vnd.event.event"; public static final String EVENT_TABLE_NAME = "event1"; public static final String FIRSTNAME = "first_name"; public static final String LASTNAME = "last_name"; public static String _ID; public static HashMap<String,String> sEventProjectionMap; static { Event.sEventProjectionMap = new HashMap<String,String>(); Event.sEventProjectionMap.put(Event._ID, Event._ID); Event.sEventProjectionMap.put(Event.FIRSTNAME, Event.FIRSTNAME); Event.sEventProjectionMap.put(Event.LASTNAME, Event.LASTNAME); } } //manifestfile.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.event.test" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="10" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".EventManagementActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <provider android:name="com.event.test.EventContentProvider" android:authorities="com.event.data.contentprovider" /> </application> </manifest> //EventManagementActivity.java package com.event.test; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class EventManagementActivity extends Activity implements OnClickListener{ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btn = (Button) findViewById(R.id.btn01); btn.setText("Press Me"); btn.setOnClickListener(this); } @Override public void onClick(View arg0) { switch(arg0.getId()){ case R.id.btn01: ContentValues cv = new ContentValues(); cv.put(Event.FIRSTNAME, "DATTA"); cv.put(Event.LASTNAME, "Prabhu"); getContentResolver().insert(Event.CONTENT_URI, cv); String[] str = {Event.FIRSTNAME, Event.LASTNAME}; String where = Event.FIRSTNAME + " = ? AND " + Event.LASTNAME + " = ?"; String [] whereArgs = {"Datta", "Prabhu"}; Cursor c = getContentResolver().query(Event.CONTENT_URI, str, where, whereArgs, null); if (c.moveToFirst() ) { int id = c.getInt(0); String firstName = c.getString(0); String lastName = c.getString(1); EditText edit = (EditText) findViewById(R.id.edit01); edit.setText( id + firstName + " " + lastName); TextView tv = (TextView) findViewById(R.id.text01); tv.setText(id + firstName + " " + lastName); } c.close(); break; } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" android:id="@+id/text01" /> <EditText android:id="@+id/edit01" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn01" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> //R.java package com.event.test; public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; } public static final class id { public static final int btn01=0x7f050002; public static final int edit01=0x7f050001; public static final int text01=0x7f050000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040001; public static final int hello=0x7f040000; } } //logcat 10-04 01:12:06.904: DEBUG/MediaScanner(285): total time: 981ms 10-04 01:12:06.984: DEBUG/MediaScannerService(285): done scanning volume internal 10-04 01:12:07.344: DEBUG/dalvikvm(216): GC_CONCURRENT freed 243K, 51% free 2798K/5703K, external 410K/517K, paused 4ms+3ms 10-04 01:12:07.854: DEBUG/dalvikvm(178): GC_EXPLICIT freed 331K, 50% free 2952K/5895K, external 1313K/1400K, paused 64ms 10-04 01:12:12.318: WARN/ActivityManager(73): Activity destroy timeout for HistoryRecord{4072bb18 com.event.test/.EventManagementActivity} 10-04 01:12:15.079: INFO/InputReader(73): Device reconfigured: id=0x0, name=qwerty2, display size is now 240x432 10-04 01:12:15.079: INFO/InputManager-Callbacks(73): No virtual keys found for device qwerty2. 10-04 01:12:15.653: INFO/ARMAssembler(73): generated scanline__00000177:03515104_00001001_00000000 [ 91 ipp] (114 ins) at [0x44325520:0x443256e8] in 1138243 ns 10-04 01:12:16.543: INFO/dalvikvm(73): Jit: resizing JitTable from 512 to 1024 10-04 01:12:18.393: INFO/Process(239): Sending signal. PID: 239 SIG: 9 10-04 01:12:18.403: INFO/ActivityManager(73): Process com.event.test (pid 239) has died. 10-04 01:12:21.153: DEBUG/dalvikvm(178): GC_EXTERNAL_ALLOC freed 61K, 51% free 2947K/5895K, external 1202K/1400K, paused 48ms 10-04 01:12:24.723: INFO/ActivityManager(73): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.event.test/.EventManagementActivity } from pid 178 10-04 01:12:24.773: INFO/ActivityManager(73): Start proc com.event.test for activity com.event.test/.EventManagementActivity: pid=335 uid=10034 gids={} 10-04 01:12:25.253: INFO/ARMAssembler(73): generated scanline__00000177:03515104_00001002_00000000 [ 87 ipp] (110 ins) at [0x443256f0:0x443258a8] in 551089 ns 10-04 01:12:25.303: INFO/ActivityThread(335): Pub com.event.data.contentprovider: com.event.test.EventContentProvider 10-04 01:12:25.583: DEBUG/AndroidRuntime(335): Shutting down VM 10-04 01:12:25.583: WARN/dalvikvm(335): threadid=1: thread exiting with uncaught exception (group=0x40015560) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): FATAL EXCEPTION: main 10-04 01:12:25.594: ERROR/AndroidRuntime(335): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.event.test/com.event.test.EventManagementActivity}: java.lang.NullPointerException 10-04 01:12:25.594: ERROR/AndroidRuntime(335): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): at android.os.Handler.dispatchMessage(Handler.java:99) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): at android.os.Looper.loop(Looper.java:123) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): at android.app.ActivityThread.main(ActivityThread.java:3683) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): at java.lang.reflect.Method.invokeNative(Native Method) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): at java.lang.reflect.Method.invoke(Method.java:507) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): at dalvik.system.NativeStart.main(Native Method) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): Caused by: java.lang.NullPointerException 10-04 01:12:25.594: ERROR/AndroidRuntime(335): at com.event.test.EventManagementActivity.onCreate(EventManagementActivity.java:21) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 10-04 01:12:25.594: ERROR/AndroidRuntime(335): ... 11 more 10-04 01:12:25.603: WARN/ActivityManager(73): Force finishing activity com.event.test/.EventManagementActivity 10-04 01:12:26.123: WARN/ActivityManager(73): Activity pause timeout for HistoryRecord{4070aaa0 com.event.test/.EventManagementActivity} 10-04 01:12:27.503: INFO/Process(335): Sending signal. PID: 335 SIG: 9 10-04 01:12:27.543: WARN/InputManagerService(73): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@4073ba40 10-04 01:12:27.874: INFO/ActivityManager(73): Process com.event.test (pid 335) has died. 10-04 01:12:36.575: WARN/ActivityManager(73): Activity destroy timeout for HistoryRecord{4070aaa0 com.event.test/.EventManagementActivity} A: The stack trace points you to the exact line of code that is causing the problem: at com.event.test.EventManagementActivity.onCreate(EventManagementActivity.java:21) While the stack trace can look confusing, it's very useful. The key is to look past all of the Android classes, and trace it down to your class: com.event.test.EventManagementActivity.onCreate(EventManagementActivity.java:21) ... the 21 means line 21. The null pointer exception usually means something is not instantiated. Debug, and step through to check your variables up to this line. You are referencing something null.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: inroads into sql database encryption I followed article http://msdn.microsoft.com/en-us/library/ms179331.aspx with success, but can't translate this into security value added. I have too little context to completely understand the article -- if someone gains access to the mdf files, why not assume they have access to the keys and certificates? Getting up and running with SQL has been very easy from a VS C# perspective, but beginning to understand the security risks and safeguards is not proving the same. I allow for the windows authentication magic (which I will hopefully someday demystify) that the server does to prevent random people from querying the database. Is that even an issue if shared memory is the only protocol? My other defenses are equally high-level (e.g. SQL injection is a non-issue with LINQ). I'm looking for a point of entry into understanding the categories of risks -- any book title or link. A: In the example you linked the data is encrypted with the symmetric key (SSN_Key_01) which in turn is encrypted with the a certificate (HumanResources037) that in turn is encrypted by the database master key that in turn is encrypted with the service master key that is stored in DPAPI and therefore encrypted with a key that can is encrypted with a key derived from the service account password. This is a fairly typical encryption key hierarchy. It protects primarily against accidental media loss: if someone gets hold of the MDF/LDF files or a backup file (eg. from an old HDD improperly disposed or from a lost/stolen laptop), these files cannot be used to retrieve the encrypted information because the 'founder' cannot decrypt the database master key. As a side note, accidental media loss is the major reason for sensitive data leaks, so its well worth protecting against. This scheme though it does not protect against compromised access to the SQL Server itself: if an attacker can run queries on the server (eg. SQL injection) it can retrieve the encrypted data even though it does not know the encryption key (of course, data is still subject to access protection, ie. read/write privileges on the data and on the keys). While it may sound bad that any user can decrypt the data (given enough privileges, even if it doesn't know the password), it is a given for any scheme in which the server has to serve the data w/o asking the user for the decryption password. In general though, if you can afford it (Enterprise Edition license required) Transparent Data Encryption is a better alternative that this scheme. Another common scheme is when the data is encrypted with a symmetric key that in turn is encrypted with a certificate that in turn is encrypted with a password. In this scheme the server cannot decrypt the data unless the certificate is open in the session using the password. This scheme is common in multi-tenant applications, where each tenant wants to make sure that other tenants and/or the system administrators/owners cannot access the data (since they do not know the password). The application has to request the data access password on each session, since the server cannot decrypt the data (it doesn't know the keys).
{ "language": "en", "url": "https://stackoverflow.com/questions/7629980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why am I getting "Thread was being aborted" in ASP.NET? I am not sure why this happens and I never explicitly abort threads, so it's a bit of a surprise. But I log Exceptions and I am seeing: System.Threading.ThreadAbortException - Thread was being aborted. It appears to happen in a call to System.Threading.WaitHandle.WaitOne. I am not sure how far this Exception goes. I don't think my threads ever terminate, because I catch log and swallow the error. Why am I getting these errors? Perhaps it's when I am forcefully terminating my server or asking it to reboot? If it isn't then what might be causing them? A: This error can be caused by trying to end a response more than once. As other answers already mentioned, there are various methods that will end a response (like Response.End, or Response.Redirect). If you call more than one in a row, you'll get this error. I came across this error when I tried to use Response.End after using Response.TransmitFile which seems to end the response too. A: Nope, ThreadAbortException is thrown by a simple Response.Redirect A: ASP.NET spawns and kills worker processes all the time as needed. Your thread may just be getting shut down by ASP.NET. Old Answer: Known issue: PRB: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer Response.Redirect ("bla.aspx", false); or try { Response.Redirect("bla.aspx"); } catch (ThreadAbortException ex) { } A: If you spawn threads in Application_Start, they will still be executing in the application pool's AppDomain. If an application is idle for some time (meaning that no requests are coming in), or certain other conditions are met, ASP.NET will recycle the entire AppDomain. When that happens, any threads that you started from that AppDomain, including those from Application_Start, will be aborted. Lots more on application pools and recycling in this question: What exactly is Appdomain recycling If you are trying to run a long-running process within IIS/ASP.NET, the short answer is usually "Don't". That's what Windows Services are for. A: For a web service hosted in ASP.NET, the configuration property is executionTimeout: <configuration> <system.web> <httpRuntime executionTimeout="360" /> </system.web> </configuration> Set this and the thread abort exception will go away :) A: This problem occurs in the Response.Redirect and Server.Transfer methods, because both methods call Response.End internally. The solution for this problem is as follows. For Server.Transfer, use the Server.Execute method instead. Visit this link for download an example. A: I got this error when I did a Response.Redirect after a successful login of the user. I fixed it by doing a FormsAuthentication.RedirectFromLoginPage instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "85" }
Q: NSURL from File -> Editing text of data then turn back into URL = NULL I have an html file that I want to dynamically edit before displaying to change some of the values. I get the file fine, then replace the text I want, still fine. But when I convert it back to a NSURL it shows NULL and WebKitErrorDomain error 101. Here is the code: NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"]; NSURL *theURL = [NSURL fileURLWithPath:filePath isDirectory:NO]; NSError *error; NSString* text = [NSString stringWithContentsOfURL:theURL encoding:NSASCIIStringEncoding error:&error]; NSString *newURL = @"SRC=\"http://75.25.157.90/nphMotionJpeg?Resolution=640x480&Quality=Standard\""; text = [text stringByReplacingOccurrencesOfString:@"__SRC__" withString:newURL] ; NSURLRequest *newRequest = [ [NSURLRequest alloc] initWithURL: [NSURL URLWithString:text] ]; [web loadRequest:newRequest]; I have "__SRC__" in the html file and I want to replace it with the newURL string above... Any pointers would be great. I've tried everything I can think of... ---- Added HTML code ---- <HEAD> <META HTTP-EQUIV="expires" CONTENT="0"> <META HTTP-EQUIV="Pragma" CONTENT="no-cache"> <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache"> <TITLE>ImageViewer</TITLE> <META http-equiv="Content-Script-Type" content="text/javascript"> <META http-equiv="Content-Style-Type" content="text/css"> </HEAD> <BODY onLoad="setParam();play();" BGCOLOR="#EFEFEF" TEXT="#ffffff" LINK="#ffffff" VLINK="#ffffff" ALINK="#ffffff" TOPMARGIN="0" LEFTMARGIN="0" MARGINHEIGHT="0" MARGINWIDTH="0"> <INPUT TYPE=hidden NAME="Width" VALUE="640"> <INPUT TYPE=hidden NAME="Height" VALUE="480"> <INPUT TYPE=hidden NAME="Language" VALUE="0"> <INPUT TYPE=hidden NAME="Direction" VALUE="Direct"> <INPUT TYPE=hidden NAME="PermitNo" VALUE="514861200"> <TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0> <TR> <TD><INPUT TYPE=image NAME="NewPosition" __SRC__ WIDTH=320 HEIGHT=240 BORDER=0></TD> </TR> </TABLE> </BODY> </HTML> A: You can't turn html source back into a URL. You can sent the updated html to a UIWebView to display. - (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL Or you could server it with a web server. But perhaps there is a terminology breakdown and I don't understand what the html is, please post it or at least a sample.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error with "this" in IE with jQuery plugin I'm coding a plugin for jQuery which now works fine on every browser but IE. This is part of the code: (function( $ ){ $.fn.myPlugin = function(options) { var methods = { getFirstList: function(el){ return $("ul:first", el); } }; return this.each(function(){ ... var list = methods.getFirstList(this); // "this" here refers to window or document in IE. ... }); }; })( jQuery ); When I call the plugin ($("#myObject").myPlugin();), the keyword "this" is not refered to the DOM object, but to the window or document. How do I fix this? A: Try replacing this with $(this)
{ "language": "en", "url": "https://stackoverflow.com/questions/7629991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to retrieve images from a remote server in Android The code below is what I use to retrieve images from a remote server, but the problem is the image doesn't show always. The image will only appear 5/7. Is there anything I am doing wrong? And also I am using LazyList (Lazy load of images in ListView) created by Fedor and I noticed that this never happens to it ImageView mainImageView = (ImageView) findViewById(R.id.picture); ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar); String imageurl = "http://www.yoururl/cutecats.png"; ImageDownloadMessageHandler imageDownloadMessageHandler1= new ImageDownloadMessageHandler(progressBar, mainImageView); ImageDownlaodThread imageDownlaodThread = new ImageDownlaodThread(imageDownloadMessageHandler1,imageurl); imageDownlaodThread.start(); } class ImageDownlaodThread extends Thread { ImageDownloadMessageHandler imageDownloadMessageHandler; String imageUrl; public ImageDownlaodThread(ImageDownloadMessageHandler imageDownloadMessageHandler, String imageUrl) { this.imageDownloadMessageHandler = imageDownloadMessageHandler; this.imageUrl = imageUrl; } @Override public void run() { Drawable drawable = LoadImageFromWebOperations(imageUrl); Message message = imageDownloadMessageHandler.obtainMessage(1, drawable); imageDownloadMessageHandler.sendMessage(message); System.out.println("Message sent"); } } class ImageDownloadMessageHandler extends Handler { ProgressBar progressBar; View imageTextView; public ImageDownloadMessageHandler(ProgressBar progressBar, View imageTextView) { this.progressBar = progressBar; this.imageTextView = imageTextView; } @Override public void handleMessage(Message message) { progressBar.setVisibility(View.GONE); imageTextView.setBackgroundDrawable(((Drawable) message.obj)); imageTextView.setVisibility(View.VISIBLE); } } Drawable LoadImageFromWebOperations(String url) { Drawable d = null; InputStream is = null; try { is = (InputStream) new URL(url).getContent(); d = Drawable.createFromStream(is, "src name"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return d; } public void onBackPressed(){ captains1.this.finish(); overridePendingTransition(R.anim.hold, R.anim.fadeout); return; } A: I made an Android open source class to manage pictures, maybe you can solve your problem with it: http://code.google.com/p/imagemanager/
{ "language": "en", "url": "https://stackoverflow.com/questions/7629998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: play an mp3 with MediaPlayer class on Android issues What is wrong with my code? I have a toggle button and i would like to play/stop an mp3. I guess that the code should be as follows: package com.android.iFocus; import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ToggleButton; public class iFocusActivity extends Activity implements OnClickListener { public int count; MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.rain); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ToggleButton toggleRain = (ToggleButton)findViewById(R.id.toggleRain); //Define Listeners toggleRain.setOnClickListener(this); count = 0; } @Override public void onClick(View toggleRain) { if(count==0){ mediaPlayer.start(); count=1; } else { //MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.rain); mediaPlayer.pause(); mediaPlayer.stop(); mediaPlayer.release(); count=0; } } } the problem is: Eclipse doesn't give any error, but on emulator/phone it gives me an exception and die immediately after started. here goes: 10-02 20:28:24.312: INFO/ActivityManager(59): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.android.iFocus/.iFocusActivity } 10-02 20:28:24.392: DEBUG/AndroidRuntime(960): Shutting down VM 10-02 20:28:24.402: DEBUG/dalvikvm(960): Debugger has detached; object registry had 1 entries 10-02 20:28:24.462: INFO/ActivityManager(59): Start proc com.android.iFocus for activity com.android.iFocus/.iFocusActivity: pid=967 uid=10036 gids={} 10-02 20:28:24.502: INFO/AndroidRuntime(960): NOTE: attach of thread 'Binder Thread #3' failed 10-02 20:28:25.822: DEBUG/AndroidRuntime(967): Shutting down VM 10-02 20:28:25.822: WARN/dalvikvm(967): threadid=1: thread exiting with uncaught exception (group=0x4001d800) 10-02 20:28:25.932: ERROR/AndroidRuntime(967): FATAL EXCEPTION: main 10-02 20:28:25.932: ERROR/AndroidRuntime(967): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.android.iFocus/com.android.iFocus.iFocusActivity}: java.lang.NullPointerException Well, when i initialize mediaPlayer inside onClick inner class, it doesn't give me any error and the aplication doesn't give me any error for to start the song. but it does not stop as should. So, when i click on toggleButton, it starts, when i click again, it doesn't do anything but give me an error on log cat: Error when first press toggle button and the song starts ok (but give this error): 10-02 20:39:02.712: INFO/ActivityManager(59): Start proc com.android.iFocus for activity com.android.iFocus/.iFocusActivity: pid=996 uid=10036 gids={} 10-02 20:39:02.782: INFO/AndroidRuntime(989): NOTE: attach of thread 'Binder Thread #3' failed 10-02 20:39:04.432: INFO/ActivityManager(59): Displayed activity com.android.iFocus/.iFocusActivity: 1804 ms (total 640049 ms) 10-02 20:39:08.672: DEBUG/AudioSink(34): bufferCount (4) is too small and increased to 12 10-02 20:39:08.982: WARN/AudioFlinger(34): write blocked for 73 msecs, 2105 delayed writes, thread 0xb3b8 10-02 20:39:09.682: DEBUG/dalvikvm(437): GC_EXPLICIT freed 686 objects / 38192 bytes in 216ms 10-02 20:39:14.502: WARN/AudioFlinger(34): write blocked for 86 msecs, 2110 delayed writes, thread 0xb3b8 10-02 20:39:14.642: DEBUG/dalvikvm(188): GC_EXPLICIT freed 164 objects / 11408 bytes in 176ms 10-02 20:39:19.622: DEBUG/dalvikvm(261): GC_EXPLICIT freed 43 objects / 1912 bytes in 154ms 10-02 20:39:20.352: WARN/AudioFlinger(34): write blocked for 78 msecs, 2119 delayed writes, thread 0xb3b8 Error when i again press the toggleButton and the song should stop: 10-02 20:43:22.412: ERROR/MediaPlayer(1032): pause called in state 8 10-02 20:43:22.412: ERROR/MediaPlayer(1032): error (-38, 0) 10-02 20:43:22.412: ERROR/MediaPlayer(1032): stop called in state 0 10-02 20:43:22.412: ERROR/MediaPlayer(1032): error (-38, 0) 10-02 20:43:22.612: WARN/MediaPlayer(1032): mediaplayer went away with unhandled events 10-02 20:43:22.612: WARN/MediaPlayer(1032): mediaplayer went away with unhandled events 10-02 20:43:22.622: WARN/MediaPlayer(1032): mediaplayer went away with unhandled events 10-02 20:43:22.622: WARN/MediaPlayer(1032): mediaplayer went away with unhandled events A: First thing first, my analysis: 1. You didn't init the MediaPlayer inside onCreate(): MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.rain); 'this' <--- this thing is NULL, so you've got a NullPointerException at Runtime, first loading app timing. 2. On second click to button, you've called mediaPlayer.release(); And next time you click, exception at MediaPlayer State Well, the fix is pretty much simple, you need to consider best practice on Android programming: package pete.android.study; import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ToggleButton; public class Main extends Activity implements OnClickListener { // declare controls public int count = 0; MediaPlayer mediaPlayer = null; ToggleButton toggleRain = null; /* * (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { // load layout super.onCreate(savedInstanceState); setContentView(R.layout.main); // load controls toggleRain = (ToggleButton)findViewById(R.id.toggleRain); // init player mediaPlayer = MediaPlayer.create(this, R.raw.rain); // set click event handler toggleRain.setOnClickListener(this); // init state for playing count = 0; } /* * (non-Javadoc) * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View toggleRain) { if(count == 0){ mediaPlayer.start(); count = 1; } else { mediaPlayer.pause(); count = 0; } } /* * (non-Javadoc) * @see android.app.Activity#onDestroy() */ @Override protected void onDestroy() { if(mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer = null; } } } Certainly it works like charm ^^! There are many ways to improve this simple app, however, I guess you can find out by looking over Android Developers' References Documentation :) A: Have you tried moving the initialization inside of onCreate instead of just inside the class body? This would be the best place to do it. If you initialize inside of onClick, the error you show is expected. This is because a new MediaPlayer instance is being created every time you click. A: Your problem is with the release() statement here: if(count==0){ mediaPlayer.start(); count = 1; } else { //MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.rain); mediaPlayer.pause(); mediaPlayer.stop(); mediaPlayer.release(); count = 0; } There are a few different ways you can change this, depending on your desired result. If you just want to play/pause, as you've said, then you only need to remove the stop() and release() calls. ESPECIALLY release(). That call releases the audio resources back to the system, meaning you'll need to get it back into a prepared state before you can use it again. I highly recommend reading this reference document VERY thoroughly. The MediaPlayer class is fairly complex, and it's easy and common for mistakes like this to appear when the states aren't managed properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get CSS properties/rules out of String jQuery So I am looking for a jQuery Plugin or a method using javascript in general where I can obtain CSS properties from a string without using a lot of If else statements I have to write. The string comes from a user input like a Text area. Example: var string = "#hello{border:1px #000 solid;background-color:#FFF;}"; So basically I want to be able to identify ID's and Classes from a string and their properties. So in this case that there is an ID called Hello and that it has a 1px border and a background color of #FFF (white). The info will be then be added to an object asnd pushed into an array. Is there a plugin or a way I can do this? There will also be multiple in each string. I know this might seem a little confusing. Thanks! A: It seems that you want to parse CSS style rules and extract the components. That isn't too hard since the general syntax is a selector followed by a list of zero or more semi-colon separated sets of colon separated name:value pairs (i.e. selector { property : value; property : value; …}). A regular expression should do the trick, however it might get complex if you want the selector to be fully compliant with the current standard, CSS 2.1. If all you want is single id and class selectors, then life is much simpler. A start on such a function is: function parseCSSRule(s) { var a = s.indexOf('{'); var b = s.indexOf('}'); var selector = s.substring(0, a); var rules = s.substring(++a, b).split(';'); // Do something with the selector and the rules alert(selector + '\n' + rules); } that will split the selector from the rules, then separate the rules into an array. You will need to deal with a bit of whitespace here and there, but otherwise if all you want to do is apply the (possibly empty set of) style rules to an element selected by the selector, that's about it. You just need to split each rule on the colon ":" and apply the CSS text to the appropriate style property, changing hyphenated names to camelCase in the processs. Edit Oh, and if you want a really simple solution, just add the rule to the bottom of the last style sheet in the document. That way you don't have to parse it at all, just drop it in and let the browser do the work. A: This can be quite trivial if you run javascript on the rendered page. First, get a list of all CSS properties (the list can be quite large). Then you do: (pseudocode) var properties = [] foreach(property in css_properies) { var value = $('#hello').css(property) if( value != "" ) properites.push(property + ':' + value) } Then the string you want would become: '#hello{' + properties.join(';') + '}' Now, the list contains all computed styles, so it can be quite large. See the css method for more details. A: JSCSSP is a CSS parser that I believe should be able to do exactly what you are looking for. Please look at the following link: http://glazman.org/JSCSSP/ Please tell me if it looks like an appropriate solution to you. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP require file from top directory I have several subdomains contained in their own directory above my root site, and an assets folder in my root directory. For example: / /assets/ /forums/ /blog/ I'm trying to require() files on php pages in both the root directory, and the subdirectories, for example, assets/include/form.php is required() in both index.php in the root directory and index.php in the forums directory. However, inside form.php, is another require, trying to get another file contained in the include directory. I can't seem to find a way to require a file inside this form.php where it will work on both the root directory's index.php and the forum directory's index.php. Is there any way I can explicitly require a file starting from the root directory? A: There are several ways to achieve this. Use relative path from form.php require_once __DIR__ . '/otherfile.php'; If you're using PHP 5.2 or older, you can use dirname(__FILE__) instead of __DIR__. Read more about magic constants here. Use the $_SERVER['DOCUMENT_ROOT'] variable This is the absolute path to your document root: /var/www/example.org/ or C:\wamp\www\ on Windows. The document root is the folder where your root level files are: http://example.org/index.php would be in $_SERVER['DOCUMENT_ROOT'] . '/index.php' Usage: require_once $_SERVER['DOCUMENT_ROOT'] . '/include/otherfile.php'; Use an autoloader This will probably be a bit overkill for your application if it's very simple. Set up PHP's include paths You can also set the directories where PHP will look for the files when you use require() or include(). Check out set_include_path() here. Usage: require_once 'otherfile.php'; Note: I see some answers suggest using the URL inside a require(). I would not suggest this as the PHP file would be parsed before it's included. This is okay for HTML files or PHP scripts which output HTML, but if you only have a class definition there, you would get a blank result. A: If one level higher use: include('../header.php'); if two levels higher: include('../../header.php'); Fore more, visit: http://forums.htmlhelp.com/index.php?showtopic=2922 A: You have 2 solutions. You can either use the full URL to the file, for instance if your file is in the 'lib' directory you can use: require_once ('http://www.example.com/lib/myfile.php') or You can try the $_SERVER['DOCUMENT_ROOT'] function in PHP but this isnt always fool proof. A: * *suppose you have pgm1.php in www.domain.com/dir1/dir2/dir3/pgm1.php, which include or require 'dirA/inc/Xpto.php'. *and another pgm2.php in www.domain.com/dirZ1/dirZ2/pgm2.php, which include or require same 'dirA/inc/Xpto.php'. *and your Host configuration not authorize require/include 'http://www.domain.com/......' *So...you can use this, in both pgm1.php & pgm1.php, and REQUIRE or INCLUDE works ! function rURI($p){ for($w='',$i=1;$i<(count(explode('/',$_SERVER['PHP_SELF']))-1);$i++,$w.='../');return $w.$p; } require rURI('dirA/inc/Xpto.php'); // path from root A: Maybe this isn't correct topic and maybe not correct use, but maybe it will help someone. When I wanted to make links in menu from absolute path, as I was jumping from directory to directory and paths were nonstop changing, I wanted to fix to base dir. So instead of using '../' to go sub-folder (as I didn't know many I needed to go down ../../../), I wrote link as <a href='/first_dir/second_dir/third_dir//..'>, similar it works also with <img src='/first_dir/second_dir//../logo.svg'>. Unfortunately this doesn't work with require_once(). PHP 7 A: why don't you use (../) require('../folder/file.php');
{ "language": "en", "url": "https://stackoverflow.com/questions/7630002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: CLLocationManager delegate not called I am using CLLocationManager on device and the delegate methods aren't getting called. Here's my code (I can see that the class isn't getting deallocated either): #import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> @interface CurrentLocation : NSObject <CLLocationManagerDelegate> { CLLocationManager *locationManager; } @property (nonatomic, retain) CLLocationManager *locationManager; @end #import "CurrentLocation.h" #import "SBJson.h" @implementation CurrentLocation @synthesize locationManager; - (id)init { self = [super init]; if (self) { NSLog(@"Initialized"); locationManager = [[[CLLocationManager alloc] init] autorelease]; locationManager.delegate = self; [locationManager startUpdatingLocation]; BOOL enable = [CLLocationManager locationServicesEnabled]; NSLog(@"%@", enable? @"Enabled" : @"Not Enabled"); } return self; } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSLog(@"A"); NSString *stringURL = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=true", newLocation.coordinate.latitude, newLocation.coordinate.longitude]; NSLog(@"%@", stringURL); NSURL *url = [NSURL URLWithString:stringURL]; NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:url] returningResponse:nil error:nil]; SBJsonParser *parser = [[SBJsonParser alloc] init]; NSDictionary *dict = [parser objectWithData:data]; NSLog(@"%@", dict); } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { NSLog(@"B"); } - (void)dealloc { NSLog(@"Dealloc called"); [super dealloc]; [locationManager release]; } @end In log, I see: 2011-10-02 19:49:04.095 DixieMatTracker[1404:707] Initialized 2011-10-02 19:49:04.109 DixieMatTracker[1404:707] Enabled What am I doing wrong? Thanks A: You're using the locationManager ivar, not the property; this means that the CLLocationManager isn't being retained and will be deallocated as you're autoreleasing it. Use self.locationManager: self.locationManager = [[[CLLocationManager alloc] init] autorelease]; A: I would suggest that you check your memory management on your CLLocationManager instance. Write it so: #import "CurrentLocation.h" #import "SBJson.h" @implementation CurrentLocation @synthesize locationManager; - (id)init { self = [super init]; if (self) { NSLog(@"Initialized"); locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; [locationManager startUpdatingLocation]; BOOL enable = [CLLocationManager locationServicesEnabled]; NSLog(@"%@", enable? @"Enabled" : @"Not Enabled"); } return self; } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSLog(@"A"); NSString *stringURL = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=true", newLocation.coordinate.latitude, newLocation.coordinate.longitude]; NSLog(@"%@", stringURL); NSURL *url = [NSURL URLWithString:stringURL]; NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:url] returningResponse:nil error:nil]; SBJsonParser *parser = [[SBJsonParser alloc] init]; NSDictionary *dict = [parser objectWithData:data]; NSLog(@"%@", dict); } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { NSLog(@"B"); } - (void)dealloc { NSLog(@"Dealloc called"); [super dealloc]; [locationManager release]; } @end The delegate does not get called because the CLLocationManager object is deallocated before it can provide a response to the location request. This is caused by the autorelease in your code. Besides that - iff autorelease is used it would be a mistake to manually release it in dealloc. This could lead to unexpected crashes. The solution above does it 'by-hand' allocating a CLLocationManager in init and releasing it in dealloc. A: In my case it was because of my device was unable to determine location - while staying indoors GPS signal was unavailable and wi-fi was also disconnected so location manager just wasn't able to receive any location data and delegate was never called. Once I've connected wi-fi it worked (I guess moving outdoors should also do the trick in that case, but sometimes it is not very convenient way :) )
{ "language": "en", "url": "https://stackoverflow.com/questions/7630003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jquery dropdown, content in neighbour Usually, when you enter the menu, you are allowed to browse menu items. In this code it is not working: http://jsfiddle.net/petrm/xwtS5/ Is it because the items are not inside menu element? If so, could it be solved in jQuery, instead of moving the code? Thanks. A: works well with Superfish plugin
{ "language": "en", "url": "https://stackoverflow.com/questions/7630005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Chrome not loading Stylesheet Seems like Google Chrome is not displaying my site according to the stylesheet. When the page first load, it loads fine...but then it changes to raw html format towards the end of the page load. It ends up looking like this (you can see web address at the top bar): [click for full size] I have 2 style sheets, one is an "alternative" that a user can switch between by clicking the Light/Dark buttons at top right of the site. Why is this happening? I never had a problem before. My specs: Mac OS X with Google Chrome 14.0.835.186 A: Maybe a caching problem on your side. Can you try "Shift+Ctrl+R"? A: I tried this on OS X with the same Chrome version as you and everything is rendered correctly for the dark and light versions. It could be a caching problem for you. Hold down the shift key while you reload the page. This will force the browser to get all of the resources and ignore the cached versions. A: Had this same issue, spent hours going around in circles wondering "What the hell have I done!", I tried many of the suggestions from this site and many others but the thing that worked for me and I felt kind of stupid afterwards for not trying it was to disable ad-blocker for chrome, followed by a shift+f5 and problem solved. A: Do you have HTTPS everywhere + Adblock installed? If so, I've found that clicking through google search results will often produce this behavior when the main site has no, or limited https support. I notice the same behavior, with those extensions, when I search for and click through an XKCD comic, for example. Temporarily disabling https everywhere, or re-entering the URL without https seems to fix it for me. A: On my friend's laptop it was caused by some DNS problems. After changing DNS to 8.8.8.8 everything is fine. A: Change css charset to UTF8. It fixed my issue. A: I had this issue. It started when I added a Chrome extension 'Akamai Debug Headers'. This caused random sites' CSS not to load and displayed CORS errors. I turned off the extension and it all worked again. So maybe disable all extensions and then test Chrome
{ "language": "en", "url": "https://stackoverflow.com/questions/7630010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Difficulty throwing NoSuchElementException in Java this is my first attempt to a code doubly linked program in java: This is my implementation of getting an iterator to getall items in the doubly linkedlist public Object next() { if(list.getSize()==0){ throw new NoSuchElementException(); }else{ current=current.getNext(); return current.getItem(); } } Please dont laugh at me but whatever I try I am getting Cannot find symbol : symbol class: NoSuchElementException I tried creating a class NoSuchElementException.java which extends Exception Then I get unreported exception NoSuchElementException; must be caught or declared to be thrown throw new NoSuchElementException(); I tried changing code to : public Object next() throws NoSuchElementException { Then I get next() in ElementsIterator cannot implement next() in java.util.Iterator; overridden method does not throw NoSuchElementException Can anybody point to where I got wrong. If this is not sufficient info to resolve this issue, please do tell me. A: The compiler is giving you a pretty good explanation. You are providing an implementation of the next() method declared in Iterator, which has a signature of: public Object next() However, you have introduced your own checked exception called NoSuchElementException, which required that you change the method signature to: public Object next() throws NoSuchElementException Now you are no longer implementing the method declared in the interface. You've changed the signature. Anyways, there are a couple ways you can fix this: * *Change your NoSuchElementException class so that it inherits from RuntimeException instead of just Exception. Then you don't need to add a throws declaration to the method signature. *Get rid of your custom exception type and instead use Java's built-in NoSuchElementException, which already inherits from RuntimeException. This is almost certainly the better option. A: The next() method of Iterator does not declare an exception to be thrown, so you can't decalre an exception if you are implementing it. You can however throw an unchecked exception. The simple fix is to define your custom exception as extends RuntimeException, which will make it an unchecked exception. I'm a little confused, because NoSuchElementException is an unchecked exception already, unless you have defined your own NoSuchElementException class. A: You need to import java.util.NoSuchElementException instead of creating your own. A: Check the javadocs for java.util.Iterator and java.util.NoSuchElementException. If you implement the Iterator interface, you have to play by its rules. Import that exception; don't create it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: c++ no suitable user-defined conversion from "myClass1" to "myClass1" exists I'm very new to c++ and was really confused when this syntax error was highlighted by visual studio 2010. Definitions class myClass1 { public: myClass1(); } class myClass2 { public: myClass2(); void doSomething(myClass1 thing) {}; } int main(int argc, char* argv[]) { vector<myClass1> arr; arr.resize(1); arr[0] = myClass1(); myClass2 c2 = myClass2(); c2.doSomething(arr[0]); //this line is being highlighted as giving the error in the title }; I'm just really confused as to what this means. The syntax error is at the line that i commented and it gives the error "no suitable user-defined conversion from "myClass1" to "myClass1". Edit: sorry about not making the question clear A: The myClass* classes contain nothing/do nothing so it's kind of hard to understand your purpose. Your code won't compile because the constructors are not defined. You should always provide a minimum of relevant information (and not much more) in your code pastes. To declare an instance of a myClass2 object on the stack, simply do: myClass2 c2; The doSomething method uses a copy of myClass1, which is probably not what you want. The copy constructor is not defined (but there is nothing to copy). Plus the function does nothing...
{ "language": "en", "url": "https://stackoverflow.com/questions/7630015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you get browsers to recognize a password change? As I'm sure you are aware, a feature on most browsers is that they save passwords. Now, I have a site where a user can change their password on one of the pages. Is there a way to get the browser to recognize the change? In other words, the I want the browsers to bring up their "save new password" dialog when a user enters their new password in a certain field. Is there a way to do this? Obviously, a pure html solution is preferred, but I'd be happy to hear of ways to do this in Javascript. FYI, the site I am working does not require very strong security. A: It should be as simple as <INPUT TYPE="password" AUTOCOMPLETE="on" ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7630018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I know a DataInput size? public void readFields(DataInput in) throws IOException{ //How can I set up the byteArray size here? //DataInput does not have available() or length() method. byte[] videoByteArray = new byte[size]; in.readFully(videoByteArray); } How can I know the DataInput size? Before I read all data into a byte array, I need set up the size first. A: If you are sending a portion of data, the simplest approach to know the size is to send it first in the DataOutput stream. Otherwise you have to assume you want to read all the data until the end of the stream (and you can't send anything else) A: DataInput is an interface for reading stream data, i.e. when length may be not known upfront. The idea is to read data chunks into byte array in a loop until you hit the end, indicated by EOFException.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Type was not found or was not a compile-time constant 1046 I want to pulish SWF file from .fla file. I have some scripts there, but when I pulished them - they don't work. I get error from compiler: 1046: Type was not found or was not a compile-time constant **Warning** The linkage identifier 'scrollableContent' was already assigned to the symbol 'pop_ups/__pop_up_other_elements/scrollableContent', and cannot be assigned to the symbol 'pop_ups/__pop_up_other_elements/scrollable_game_content', since linkage identifiers must be unique. I google that error, but don't find any appropriate answer. I saw some information here, but it didn't help me. http://curtismorley.com/20​07/06/20/flash-cs3-flex-2-​as3-error-1046/ Please, tell anybody what problem produce this error and how can I fix it? Thanx! A: The official compiler errors list on Adobe's site. In this case Error 1046 The class used as a type declaration is either unknown or is an expression that could have different values at run time. Check that you are importing the correct class and that its package location has not changed. Also, check that the package that contains the code (not the imported class) is defined correctly (for example, make sure to use proper ActionScript 3.0 package syntax, and not ActionScript 2.0 syntax). The error can also occur if the class being referenced is not defined in a namespace that is in use or is not defined as public: public class Foo{} Check your .fla file to make sure you have all the links for assets properly. One simple case is that you have something on the stage with a name and one of your scripts has the same name. You cannot define it twice. Fix one of them. A: So, I finded out reason, why that error was. Here is solution: If, for example, you have 2 MovieClips: movie1_mc, class linkage: "movie1" movie2_mc, class linkage: "movie2" And if movie1_mc is a child of movie2_mc, and also have its instance name same that its class linkage - error 1046 occurs. So, the rule is: If one file with class linkage is child of some other class, than its instance name must be different than its class linkage.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to convert IplImage(OpenCV) to ALLEGRO_BITMAP (A5) fast? Is there a fastest way to convert a IplImage type from OpenCV to ALLEGRO_BITMAP type from Allegro 5.0.x than just putting every pixel from one to another? Like 2 for loops like this: void iplImageToBitmap(IplImage *source, ALLEGRO_BITMAP* dest) { if(source!= NULL && dest!= NULL) { al_set_target_bitmap(dest); int height = source->height; int width = source->width; int x,y; for( y=0; y < height ; y++ ) { uchar* ptr = (uchar*) ( source->imageData + y * source->widthStep ); for( x=0; x < width; x++ ) { al_put_pixel(x,y,al_map_rgb(ptr[3*x+2],ptr[3*x+1],ptr[3*x])); } } } } A: Use al_lock_bitmap to get an ALLEGRO_LOCKED_REGION, then set the pixel data as described. Then unlock it with al_unlock_bitmap.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Implementation differences between MVP Passive View and Supervising Controller for collections I've started to wrap my head around the whole MVP pattern and despite I'm doing fine with single objects it starts getting difficult when it comes to collections. So let's say we're architecting a simple WinForms application that consists of a DataGrid within a Form, with the data Model being a simple collection of stuff, where such stuff has a bunch of properties and the View is going to actually display them: Model public class Person { public string Name { get; set; } public DateTime Birth { get; set; } public bool IsCool { get; set; } } public class People { public List<Person> Persons { get; set; } } View public interface IPeopleView { List<People> ListOfPeople { get; set; } } public partial class PeopleViewImpl : Form, IPeopleView { private DataGridView _grid = new DataGridView(); public PeopleViewImpl() { InitializeComponent(); } // Implementation of IPeopleView public List<People> ListOfPeople { get { return /* TODO */; } set { _grid.DataSource = value; } } } Presenter public class PeoplePresenter { private People _model; private IPeopleView _view; public PeoplePresenter(People model, IPeopleView view) { _model = model; _view = view; } void UpdateView() { _view.ListOfPeople = _model.Peoples; } } So what should I implement at View's List<People> ListOfPeople getter as well as how should I invoke Presenter's UpdateView()? And generally, which extra Presenter methods would be interesting to have in order to achieve MVP Passive View and Supervising Controller respectively? Any advice, code style review or opinion will be sincerely appreciated. Thanks much in advance. A: First of all, you should decide for one pattern: * *Supervising Controller is appropriate if you want to leverage data binding and if a tool for automated view tests is available *Passive View is indicated if your view data becomes more complex or if you have to rely on pure unit tests for the complete view *Presentation Model (also known as Model View ViewModel) is ideal if you need easy access to the complete view state and if you have code generation available I have collected all aspects as well as links to useful considerations and examples. In either case, you should define a PeopleModel and let PeopleViewImplementation reference PeopleModel. This clearly separates the model from the view. When it comes to collections, Supervising Controller can rely on the data binding of a list to the DataGridView. See winForms + DataGridView binding to a List. Only Passive View and Presentation Model require additional code for mapping the list to the view fields respectively to the Presentation Model. Secondly, the data mapping should be clarified: Should PeopleView show a list of persons or a list of several peoples? The DataGridView can either display one person per row or one people per row. If one person is displayed per row, the treatment of the people could be achieved in one of the following ways, for example: * *Show all persons of one people on one page and add a pager element to navigate between different peoples *Show all persons of one people in the data grid and add a selection widget for the people, e.g. a tree with all peoples *Mix persons of different peoples in the data grid and add a column to display the people of each person A: My suggestion is to have a ViewModel for that collection. The view implementation will have the responsibility of create new instances and update old, but it won't touch anything of your actual model. In order to retrieve them, just iterate the rows an create new. Finally, the presenter will iterate that collection and create/update each member of your model. (I also suggest using IEnumerable<> and using yield return so the collection is iterated only once). For showing the data, you can also use this ViewModel (so it will be consistent) or just use the actual model (in a readonly fashion) if they are different for some reason (maybe yo show more information than what you can edit). Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how to set user defaults with folder name I hope to set the user defaults to ~/Library/Preference under the folder name 'MyFolder', plist name is com.mycompany.myapp.plist Do I need to create the plist file and the folder by myself or the system create automatically? Is there any tutorial? A: You need to use the User Defaults System. The User Defaults classes (particularly NSUserDefaults) manage the creation and location of the preferences file and allow you to easily read and write preferences data. By default, the User Defaults system creates a preferences file with your app's bundle ID and the plist extension under the ~/Library/Preferences folder, however you should not rely on this behaviour. If you use the API you don't need to know the location of the file as it's not important. You should never create or manage the preferences file directly, you should always use the API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mongoid Associations not working In my problem I need posts to each belong to Category but I also want every post to be in a second category. Such that one post could be in "News" and another in "Sports" but they would both be in "Everything". Currently my associations are like this: class Article include Mongoid::Document belongs_to :category belongs_to :home_category, :class_name => 'Category' end class Category include Mongoid::Category has_many :articles end Currently the normal article.category works fine. However article.home_category sets on the Article object but does not reciprocate to Category object. So if I set article.home_category=category it works but if I do category.articles I get []. Any ideas why? A: the way you set up your relation, it's a 1:n relation between Article and Category ... that means that you can't have many categories for an article. You should change it to a n:m relationship, see: http://mongoid.org/docs/relations/referenced/n-n.html class Article include Mongoid::Document has_and_belongs_to_many :categories end class Category include Mongoid::Category has_and_belongs_to_many :articles end Or you could try acts_as_taggable for Mongoid : http://abhishiv.tumblr.com/post/3623498128/introducing-acts-as-taggable-for-mongoid Having two relations to Categories as you have in your example code is probably not a good idea. A: So it turns out that my problem was that I was setting the category using a before_save, which incidentally turns out to not work out well when it is called on an unpersisted article. I fixed the problem by switching the before_save to an after_create filter and it then worked fine! In the end there was no problem with the Mongoid Associations, the problem was me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I save scores in my game using cookies? I am currently making an Jeopardy game on the topic of HTML using jQuery. Right now it works well, but I want to add a recent saved scores tag using cookies. I don't know how to achieve this. I know cookies but I don't know how I will get the name and score and then save it. I want to do something like this: Recent Saved Scores {NAME HERE}....{Score HERE} {NAME HERE}....{Score HERE} {NAME HERE}....{Score HERE} And it's supposed to save. Here's a link to my game: http://redirectme.yolasite.com/resources/jeopardy.html A: I would suggest to use something like jstorage It uses localStorage or cookies if localStorage is not available. A: Assuming that you know how to get/set cookie with javascript, just use json to encode the array of recent scores. NOTE. cookies will register only results for the particular computer. if you need highscore chart, then you need some kind of backend e.g. php for storing and retrieving results. let me know if you need any further guidance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tab index not work on image, panel and Group tags in flash I am writing code to order the tab on multiple tags like "img","Panel","LinkButton",... and pie charts. when I run my flash program, the tab indexing does not work at all. it just works on pie chart and "link button" tags, not on "img","Panel","Group" tags. I also have tried to "enable tab" on those fields , but no help.on the other hand when I disable tab on the pie chart, and link button, still the tab is enabled. I have searched a lot and could not find a solution yet. appreciate a lot if someone could help me I am working on Flash 10.0.0.0 , sdk 4.1 A: My guess is that you are looking for tabEnabled and tabIndex, both properties of flash.display.InteractiveObject http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/InteractiveObject.html?filter_flash=cs5&filter_flashplayer=10.2&filter_air=2.6 You might also want to take a look at Stage.focus http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/Stage.html#focus If you can give more details about your issue I'll try to help you with a more direct answer. A: I was finally able to implement the IFocusMangerComponent in order to get the focus for image. although the "tab index" is available in the class, if you want to get the tab to work on image, you have to simply implement IFocusMangerComponent as following in .as file. (no need to implement the functions in the new class) import mx.controls.Image; import mx.managers.IFocusManagerComponent; public class FocusableImage extends Image implements IFocusManagerComponent { public function FocusableImage() { super(); } } then in the code instead of using var image = new Image() , you have to use var image = new FocusableImage() image.tabEnabled = true; image.tabFocusEnabled = true; image.tabIndex = 1;
{ "language": "en", "url": "https://stackoverflow.com/questions/7630042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Remove white spaces in character strings I have a data frame imported from a text file : dateTime contract bidPrice askPrice bidSize askSize 1 Tue Dec 14 05:12:20 PST 2010 CLF1 0 0 0 0 2 Tue Dec 14 05:12:20 PST 2010 CLG1 0 0 0 0 3 Tue Dec 14 05:12:20 PST 2010 CLH1 0 0 0 0 4 Tue Dec 14 05:12:20 PST 2010 CLJ1 0 0 0 0 5 Tue Dec 14 05:12:20 PST 2010 NGF1 0 0 0 0 6 Tue Dec 14 05:12:20 PST 2010 NGG1 0 0 0 0 lastPrice lastSize volume 1 0 0 0 2 0 0 0 3 0 0 0 4 0 0 0 5 0 0 0 6 0 0 0 I try to create a subset for all rows where contract = CLF1 but get the following error: > clf1 <- data.frame(subset(train2, as.character(contract="CLF1"))) Error in as.character(contract = "CLF1") : supplied argument name 'contract' does not match 'x' I try to find how many characters are in the cell: > f <-as.character(train2[1,2]) > nchar(f) [1] 5 I assumed this is due to a leading or trailing space so I try the following: > clf1 <- data.frame(subset(train2, as.character(contract=" CLF1"))) Error in as.character(contract = " CLF1") : supplied argument name 'contract' does not match 'x' > clf1 <- data.frame(subset(train2, as.character(contract="CLF1 "))) Error in as.character(contract = "CLF1 ") : supplied argument name 'contract' does not match 'x' Again no luck, so here I am. Any suggestions would be great. Thank you. EDIT: > clf1 <- subset(train2, contract == "CLF1") > head(clf1) [1] dateTime contract bidPrice askPrice bidSize askSize lastPrice lastSize [9] volume <0 rows> (or 0-length row.names) A: I believe your problem is that you are using the incorrect syntax in subset. Try this instead: subset(train2, contract == "CLF1") So you shouldn't be coercing the subset expression to a character, and you also need to use the == equality operator, not =. You should read ?subset and look at the difference between the examples there and your code. Although your field may indeed contain leading spaces, in which case it would be good to try: subset(train2, contract == " CLF1") or when you read the file in using read.table you can use the strip.white argument to strip whitespace.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Root certificate automatically removed from the "Trusted Root Certification Authorities" I've a development environment with a test public key infrastructure. This infrastructure has one root CA, one intermediate CA and multiple end-entities (clients and servers). On the dev. machines, the root CA is installed into the "Trusted Root Certification Authorities", simulating a "commercial trusted CA" I've successfully used this environment several times in the past, however I'm currently observing the following behavior: the root CA is automatically removed from the "Trusted Root Certification Authorities" the first time a chain using it is built (e.g. SSL connection establishment). I know that windows automatically adds certificates to the "Trusted Root Certification Authorities". However, I didn't knew that they could be automatically removed. What are the circumstances on which this removal can happen? The root certificate doesn't point to a CRL nor to a OCSP endpoint. Thanks Pedro
{ "language": "en", "url": "https://stackoverflow.com/questions/7630050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: class design improvement - tweet - decoupling super global variables? Question: Should I decouple the SESSION variables, i.e. move them outside of the class...this was a suggestion from another POST. I would like to extend this library to more general cases than just for my purposes..and I believe this is the next step here? Summary: This class sends "tweet" data to the client in the form of a custom markup language. It is used in Ajax call and in previous post people have suggested not to echo the result..but this is my primary means of communicating with the server via Ajax responseText. Also <tw_p> is used to denote a pass and is read by the client. The markup looks like this. field 1 | field 2 | field 3 | field 4 || field 1 | field 2 | field 3 | field 4 || It is called like this - new tweet(); The client knows how render this into xhtml once it receives it. /*tweet*/ class tweet extends post { function __construct() { parent::__construct(); $email=$_SESSION['email']; $flname=$_SESSION['name']; $message=$this->_protected_arr['f4b']; $time=time(); database::query("INSERT INTO tw VALUES ('$time','$flname','$message','$email')"); $query_return = database::query("SELECT * FROM tw ORDER BY time DESC LIMIT 7"); $b=0; $c='<tw_p>'; while($a=mysqli_fetch_assoc($query_return)) { if($b==0) { $c = $c . $a['email'] . "|" . $a['fname'] . "|" . $a['time'] . "|" . $time . "|" . $a['message']; } else { $c = $c . "||" . $a['email'] . "|" . $a['fname'] . "|" . $a['time'] . "|" . $time . "|" . $a['message']; } $b++; } echo $c; } } A: What I would do if it was my code: * *Remove logic from constructor, it is for initialization only. Thus remove all the business logic into separate method doTheWork (choose the meaningful name that explains what happens in the code) *Parametrize constructor with: * *email *name *database instance (yes, I'd avoid static database::query() method) *Remove echo $c; in the end and replace it with return $c; *Remove the presentation logic from this class outside (the lines with || stuff) *Sanitize the data used in the query (thanks to vzwick)
{ "language": "en", "url": "https://stackoverflow.com/questions/7630057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to override default styles in GWT 2.3? This question has been asked before, but for older versions of GWT. I'm using the "clean" theme that's provided, but I'd like to override some styles (fonts and such). Linking a stylesheet in the HTML file with link tags is deprecated, as is using a stylesheet tag in the gwt xml file (http://code.google.com/webtoolkit/doc/latest/DevGuideUiCss.html#cssfiles). How do you associate a css file with your project, then? I'm not using UIBinder. A: It seems like google wants us to use ClientBundle & CssResource from now on. A: From the same page you're refering to: If you do not care about sharing or re-using your module then you can just use the standard HTML link rel stuff in the host page. But what I do is create a specific CSSResource for the 'old' styles. This resource is not used in code, but is specific to place all 'old' styles in and have them in one css file during development. Typically this should only contain 'old' GWT styles and not you're own set via a string as class name. Those should preferable go via the CssResource technique. A difference with plain style inclusion via link rel is that the styles in the resource are injected and not included via a separate stylesheet. Code example: interface Resources { @Source("notstrict.css") @CssResource.NotStrict CssResource notStrictCss(); } (also don't forget to inject this css resource). See more on strict scoping here: http://code.google.com/webtoolkit/doc/latest/DevGuideClientBundle.html#Strict_scoping A: I think the best way to go about this is to copy the "clean" theme's CSS file from the GWT jar file. Disable the theme in your application and just customise your own version of that CSS file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jquery title selector error in ie why is it giving error in ie, when i try to change the title. $('title').text('new title'); or $('title').html('new title'); works fine in other browsers. btw i just want to mention, when i try to get the value of title using following code, it works fine. alert($('title')); anyone has any idea on why its doing this? its soo annoying to fix bugs for ie. A: You should set the document.title property to an ordinary string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: switching images using jquery i can't get the following code to work: $('#clicked_package').css({"background-image" : "url(img/head_2.png)"}).fadeOut("slow"); $('#clicked_package').css({"background-image" : "url(img/head_2_normal.png)"}).fadeIn("slow"); Regardless of what image I put in the first line, It always seems to replace it with the second line. So my first image is the same as the second image. What i want is to fade out the first image, and then fade in a second image. suggestions? thanks A: You probably want the version of fadeOut that accepts a callback function: $('#clicked_package') .css({"background-image" : "url(img/head_2.png)"}) .fadeOut("slow", function () { $(this).css({"background-image" : "url(img/head_2_normal.png)"}) .fadeIn("slow"); }); Example: http://jsfiddle.net/andrewwhitaker/VLRKy/
{ "language": "en", "url": "https://stackoverflow.com/questions/7630063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I am able to compile the java program but not able to run a java program When I run the java program it gives following error: Exception in thread "main" java.lang.NoClassDefFoundError: check Caused by: java.lang.ClassNotFoundException: check at java.net.URLClassLoader$1.run(URLClassLoader.java:217) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:205) at java.lang.ClassLoader.loadClass(ClassLoader.java:321) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) Could not find the main class: check. Program will exit. The source code is: import java.io.*; class check { public static void main (String [] args) { System.out.println("Hello"); } } ~ ~ A: You've got the CLASSPATH environment variable set, and it doesn't include . (dot), the current directory. Try this java -cp . check (That's java space dash cp space dot space check). A: Please try by set the class path first then compile and execute the class Then your problem will be resolved. For example at command prompt: C:\> setclasspath=%classpath%;.; C:\> javac check.java C:\> java check Now, you will get the output as Hello.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does previously saved data not appear in opened document of Core Data app? I have created the Core Data app that is outlined in this tutorial by Apple using XCode 4. All works fine however when I save the document and reopen it the document window is empty and no data is shown. When I check the data file, I can actually see the saved data in the file (only for XML format as other formats are unreadable). This problem rises for all of the supported save formats (XML, binary and SQLLITE). There are no stacktraces in the debugger. All looks fine... A: Found it. You need to check the "Prepares content" checkbox on the controller (attributes inspector pane of the Array Controller) otherwise data is not shown.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why isnt Rectangle2D.createUnion() working for me? im trying to implement a getBounds() method, but i cant get union to work; i must not understand how union works. my code is the following: public Rectangle2D getBounds2D() { Rectangle2D rec= new Rectangle2D.Double(); Rectangle2D temp; for(int i=0; i<shapes.size(); i++){ temp = new Rectangle2D.Double(shapes.get(i).getBounds2D().getX(),shapes.get(i).getBounds2D().getY(),shapes.get(i).getBounds2D().getWidth(), shapes.get(i).getBounds2D().getHeight()); rec.createUnion(temp); } return rec; } the shapes variable is an arraylist of Shapes. i use temp to create a rectangle using the bounds from each shape in the arraylist Ive used getbounds().getWidth/Height on temp to see if it were returning wierd numbers but the numbers look fine. When i call rec.getBounds.getWidth/Height i get 0.0 for both. From this, im assuming that im not using union() correctly. does anyone have any insight as to what i can to? thanks! A: If you are not sure how to use the method then why is your code so complex to test the method? Why are you looping through and array? How will you verify the results? Start with something simple. Try to use the method with just two rectangles and with hardcoded values for each Rectangle. Then you can easily verify the results. If it doesn't work then you have a complete program to post. Something like: public class Test { public static void main(String args[]) throws Exception { Rectangle a = new Rectangle(5, 5, 30, 30); Rectangle b = new Rectangle(10, 10, 50, 50); a = a.union(b); System.out.println(a); System.out.println(b); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7630073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the best practices in Android, create new string object (static final) or only use the string.xml file (and call many getters)? In Android there is an conflict about how to get the best performance (like less Garbage Collector). First, In Android best practices it recommends avoid getters and setters and also avoid creating short lived objects (like: private static final String name = "my name"). Then, what should i do with all strings that I have in my code? Should I set all of them them in the string.xml file and then get it using "this.getString(R.string.myString)" or its still good for permformance keep using "static final String name = "my name" ??? Due to the big amount of strings in my app, if I use only strings from string.xml it would be too many of "getString"s in all code, isn't that bad? A: There is a slight performance overhead in calling getString() but no extra memory overhead. And using string.xml will make managing your strings a lot easier. It also makes it much easier to localize these values if you ever choose to do so in the future. In addition, the values in your resource files will be compiled into final static Strings so it works out similar in the end.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: DOM exception 11 I'm running this code via the console on http://TheScoutApp.com on line 3 I'm getting a DOM exception 11!!! var xhr2 = new XMLHttpRequest(); xhr2.onreadystatechange = function() { console.error(xhr2.statusText); //DOM exception 11!!! if (xhr2.readyState === 4 && xhr2.status === 200) { console.error('xhr2'); } } xhr2.open("GET","http://thescoutapp.com/extension/update.xml",true); xhr2.send(); A: The property xhr.statusText may only be accessed after the request is finished. But the onreadystatechange-callback gets called erlier - the earlier calls have xhr.readyState==1 (=server connection established). You have to put the assess of xhr.statusText inside a condition: if(xhr.readyState == 4) { console.error(xhr.statusText); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7630082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need guidance with template class and understanding line errors and I am trying to now do a Breadth First Order for files but, when I implement this template class to use a Queue I get this errors?, any idea where this might be?, also I do not understand the way the line number where the error is, is specified (i.e myprogram.c:23:10) no idea where that is program.c:11:10: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘<’ token program.c:22:10: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘<’ token program.c:33:10: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘<’ token program.c: In function ‘display_info’: program.c:49:3: error: ‘q_type’ undeclared (first use in this function) program.c:49:3: note: each undeclared identifier is reported only once for each function it appears in program.c:49:10: error: ‘string’ undeclared (first use in this function) program.c:49:18: error: ‘bfFilesQueue’ undeclared (first use in this function) program.c:50:18: error: ‘bfDirsQueue’ undeclared (first use in this function) Now the Queue class was taken from here, and I want to use it with strings , basically a file path http://www.java2s.com/Code/Cpp/Generic/Createagenericqueue.htm So my questions are, because i don't expect you to debug this for me.. but want to know the following: * *I tried to declare the queue at the top after the #include's so that i have have access to them globally. It seems like it does not like it because i am trying to use it from the display_info function. How can I declare this so that I have access to those Queues from anywhere? *I dont understand how to check in which line it is telling about the error (i.e. :12:10), i took that Template class from the link i posted.. not sure why would it throw an error.. How can I know the line number based on those weird numbers? So the code and errors are just informational so that you may answer those two questions with enough information.. any help will be much appreciated. Thank you #define _XOPEN_SOURCE 500 #include <ftw.h> #include <stdio.h> #define SIZE 100 template <class Qtype> class q_type { Qtype queue[SIZE]; int head, tail; public: q_type() { head = tail = 0; } void q(Qtype num); Qtype deq(); }; template <class Qtype> void q_type<Qtype>::q(Qtype num) { if(tail+1==head || (tail+1==SIZE && !head)) { cout << "Queue is full.\n"; return; } tail++; if(tail==SIZE) tail = 0; // cycle around queue[tail] = num; } template <class Qtype> Qtype q_type<Qtype>::deq() { if(head == tail) { cout << "Queue is empty.\n"; return 0; } head++; if(head==SIZE) head = 0; return queue[head]; } q_type<string> bfFilesQueue; q_type<string> bfDirsQueue; static int display_info(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf) { //Check the type of Flag (i.e File or Directory) switch(tflag) { case FTW_D: case FTW_F: bfFilesQueue.q(fpath); break; case FTW_DP: bfDirsQueue.q(fpath); break; } return 0; /* Continue */ } A: program.c:11:10: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘attribute’ before ‘<’ token That sounds like you're compiling the C++ source code as C. A simple fix can then be to rename the file as program.cpp. Cheers & hth., A: You declare q_type<string> bfFilesQueue; q_type<string> bfDirsQueue; before you actually declare q_type. Try putting these lines after the class
{ "language": "en", "url": "https://stackoverflow.com/questions/7630083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to stop a background thread in Sinatra once the connection is closed I'm trying to consume the twitter streaming API with Sinatra and give users real-time updates when they search for a keyword. require 'sinatra' require 'eventmachine' require 'em-http' require 'json' STREAMING_URL = 'https://stream.twitter.com/1/statuses/sample.json' get '/' do stream(:keep_open) do |out| http = EM::HttpRequest.new(STREAMING_URL).get :head => { 'Authorization' => [ 'USERNAME', 'PASS' ] } buffer = "" http.stream do |chunk| puts "still chugging" buffer += chunk while line = buffer.slice!(/.+\r?\n/) tweet = JSON.parse(line) unless tweet.length == 0 or tweet['user'].nil? out << "<p><b>#{tweet['user']['screen_name']}</b>: #{tweet['text']}</p>" end end end end end I want the processing of the em-http-request stream to stop if the user closes the connection. Does anyone know how to do this? A: Eric's answer was close, but what it does is closing the response body (not the client connection, btw) once your twitter stream closes, which normally never happens. This should work: require 'sinatra/streaming' # gem install sinatra-contrib # ... get '/' do stream(:keep_open) do |out| # ... out.callback { http.conn.close_connection } out.errback { http.conn.close_connection } end end A: I'm not quite familiar with the Sinatra stream API yet, but did you try this? http.callback { out.close }
{ "language": "en", "url": "https://stackoverflow.com/questions/7630084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: exec family with a file input Hey guys I am trying to write a shell with C++ and I am having trouble with the function of using input file with the exec commands. For example, the bc shell in Linux is able to do “bc < text.txt” which calculate the lines in the text in a batch like fashion. I am trying to do likewise with my shell. Something along the lines of: char* input = “input.txt”; execlp(input, bc, …..) // I don’t really know how to call the execlp command and all the doc and search have been kind of cryptic for someone just starting out. Is this even possible with the exec commands? Or will I have to read in line by line and run the exec commands in a for loop?? A: You can open the file and then dup2() the file descriptor to standard input, or you can close standard input and then open the file (which works because standard input is descriptor 0 and open() returns the lowest numbered available descriptor). const char *input = "input.txt"; int fd = open(input, O_RDONLY); if (fd < 0) throw "could not open file"; if (dup2(fd, 0) != 0) // Testing that the file descriptor is 0 throw "could not dup2"; close(fd); // You don't want two copies of the file descriptor execvp(command[0], &command[0]); fprintf(stderr, "failed to execvp %s\n", command[0]); exit(1); You would probably want cleverer error handling than the throw, not least because this is the child process and it is the parent that needs to know. But the throw sites mark points where errors are handled. Note the close(). A: the redirect is being performed by the shell -- it's not an argument to bc. You can invoke bash (the equivalent of bash -c "bc < text.txt") For example, you can use execvp with a file argument of "bash" and argument list "bash" "-c" "bc < text.txt"
{ "language": "en", "url": "https://stackoverflow.com/questions/7630085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Boolean vs. Enum vs. Flag I am working on a website that allows users to login. All users have 1 account, an account can have many orders. A user may be a client, worker, or manager. A client is never a worker nor a manager. a manager is also a worker. I would like to present additional sections of pages/ navigation options depending on the type of user logged in. Currently I am using a set of boolean values to mark the user as a specific type, test for that value, and run through some if/elsif blocks to generate the page that the user sees. class User include DataMapper::Resource # ... # various properties # ... property :client, Boolean property :worker, Boolean property :manager, Boolean end And then I am using a before filter to test for the user type and set the result as variable. before do @user = session[:user] if @user.client? @ura = 'client' elsif @user.worker? @ura = 'worker' elseif @user.manager? @ura = 'manager' end end Then in my views I have @ura to play around with. It seems to me that this is already going to cause me problems for managers because @ura will have to be both worker & manager. I could use some or's in my views but I think a better solution would to have the user type set as an Enum or Flag. But I don't really understand how to use that in my process. I would like to know what the advantages/disadvantages of each are & a basic example of how I can end up with an appropriate value in @ura. A: I'm not sure, but may be an Array will be better solution: class User .... def getRoles roles = Array.new roles << "client" if self.client? roles << "manager" if self.manager? roles << "worker" if self.worker? roles end end before do @user = session[:user] if(@user.getRoles.index("manager") != nil) ... A: I don't remember how I solved this exact issue ( I think it was for a bicycle delivery app ), but today just noticed that it is still unanswered. So, just shy of a decade later, even though I no longer use DataMapper regularly, he is how I would solve this now; At the time I did not understand fully the difference between authentication & authorization with respect to a users's Role in a system. class User include DataMapper::Resource ... properties ... property :role, Enum[ :client, :worker, :manager ] end class Employee < User include DataMapper::Resource ... more properties end This way all users can have the things they need, employees could be further split into Worker & Manager. then you can put the appropriate validations on the corresponding model. More code upfront but more maintainable & more easy to scale, just add a new role to the User Enum & a corresponding class. If the class doesn't do anything beyond namespace/logical separation you might even be able to get away with some meta programing/reflection infer the classes from the enum & include appropriate modules at initialization.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting unique string to a unique integer I'm wanting to change our c# asp.net mvc application to work with windows authentication as well as forms authentication (as is currently implemented). Currently we have a number of tables referencing a user id integer in the user table used by the forms authentication. Is there an appropriate way of converting the unique string username returned by windows authentication to a unique integer that can be used as the id for the other tables? An example might be using .GetHashCode() on the username, however I'm not sure if that will definitely create an appropriate integer (ie. unique, always the same integer returned given the same username, etc.) A: Do not use GetHashCode()! Instead, you should create a database table mapping Windows user accounts to integral user IDs (a Users table). You can also store additional information about each user in this table. A: GetHashCode() changes between framework versions, OS platform, etc., so you cannot rely on it for use as a DB PK. If you are working with Windows authentication then maintaining the identify is useful for debugging, troubleshooting and possibly impersonation. Why not store it in a table with a Windows Username -> UserID mappings so that you can lookup a User ID given a user name?
{ "language": "en", "url": "https://stackoverflow.com/questions/7630088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: make-node in zipper library I am trying to create a zipper from a map of my own. According to zipper definition, Usage: (zipper branch? children make-node root) the parameters branch? and children are clear and i am able to define it. But the make-node function is confusing. I gave an implementation to it which i dont think is being used. I have a map of {:question "Question 1" :yes "Answer1" :no {:question "Question 2" :yes "Answer2" :no "Answer3"}} I want build a zipper from this map. So i used the following zipper function call, (zip/zipper map? (fn [node] [(:yes node) (:no node)]) (fn [node children] (:question node)) question-bank) This works fine. It works even if give the make-node parameter nil. I dont understand when and where is this parameter will be used. A: Zippers allow you to modify the tree as well as just walking over it. The make-node function will be called if you try to add a new node to the tree, or modify an existing node. It's a little weird because your zipper doesn't expose the :question element at all, but I might write your zipper as: (zip/zipper map? (juxt :yes :no) (fn [_ [yes no]] {:yes yes :no no}) root) I don't use zippers much personally, so this is probably not a correct implementation; I'm just hoping to illustrate that the make-node function is supposed to be used to create new nodes to attach to the zipper.
{ "language": "en", "url": "https://stackoverflow.com/questions/7630089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a property/method for determining if a TcpListener is currently listening? Currently I'm doing something like this: public void StartListening() { if (!isListening) { Task.Factory.StartNew(ListenForClients); isListening = true; } } public void StopListening() { if (isListening) { tcpListener.Stop(); isListening = false; } } Is there not a method or property within TcpListener to determine if a TcpListener has started listening (ie TcpListener.Start() was called)? Can't really access TcpListener.Server because if it hasn't started, it has not been instantiated yet either. Even if I could access it I'm not sure even that contains a Listening property. Is this really the best way? A: The TcpListener actually has a property called Active which does exactly what you want. However, the property is marked protected for some reason so you cannot access it unless you inherit from the TcpListener class. You can get around this limitation by adding a simple wrapper to your project. /// <summary> /// Wrapper around TcpListener that exposes the Active property /// </summary> public class TcpListenerEx : TcpListener { /// <summary> /// Initializes a new instance of the <see cref="T:System.Net.Sockets.TcpListener"/> class with the specified local endpoint. /// </summary> /// <param name="localEP">An <see cref="T:System.Net.IPEndPoint"/> that represents the local endpoint to which to bind the listener <see cref="T:System.Net.Sockets.Socket"/>. </param><exception cref="T:System.ArgumentNullException"><paramref name="localEP"/> is null. </exception> public TcpListenerEx(IPEndPoint localEP) : base(localEP) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Net.Sockets.TcpListener"/> class that listens for incoming connection attempts on the specified local IP address and port number. /// </summary> /// <param name="localaddr">An <see cref="T:System.Net.IPAddress"/> that represents the local IP address. </param><param name="port">The port on which to listen for incoming connection attempts. </param><exception cref="T:System.ArgumentNullException"><paramref name="localaddr"/> is null. </exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="port"/> is not between <see cref="F:System.Net.IPEndPoint.MinPort"/> and <see cref="F:System.Net.IPEndPoint.MaxPort"/>. </exception> public TcpListenerEx(IPAddress localaddr, int port) : base(localaddr, port) { } public new bool Active { get { return base.Active; } } } Which you can use in place of any TcpListener object. TcpListenerEx tcpListener = new TcpListenerEx(localaddr, port); A: You can get this directly from the Socket. A Socket is always created when a TcpListener is instantiated. if(tcpListener.Server.IsBound) // The TcpListener has been bound to a port // and is listening for new TCP connections
{ "language": "en", "url": "https://stackoverflow.com/questions/7630094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }