text
stringlengths
64
89.7k
meta
dict
Q: Ignore empty string when mapping CSV to JSON using Dataweave I am mapping from CSV to JSON and some of the CSV fields are showing as "" in the JSON mapping. How can I get Dataweave to ignore "" and only populate when there is a value? I have tried skipNullOn but this doesn't work. Is there another way to do it or do I have to add an when condition around each field? Seeing this error with the recursive solution: Thanks A: Try this solution, adapted from this answer. We recursively decide if we want to remove a field from the model, using match in the acceptable function to remove empty strings, nulls, and empty objects. %dw 1.0 %output application/json %function acceptable(value) ( value match { :null -> false, o is :object -> o != {}, s is :string -> s != "", default -> true } ) %function filterKeyValue(key, value) ( {(key): value} when acceptable(value) otherwise {} ) %function removeFields(x) x match { a is :array -> a map removeFields($), o is :object -> o mapObject (filterKeyValue($$, removeFields($))), default -> $ } --- removeFields(payload)
{ "pile_set_name": "StackExchange" }
Q: template metaprogramming problem template <int p> bool FComapare (Node *lId, Node* rId) { if(lId->getDiff(p) < rId->getDiff(p)) return true; else if(lId->getDiff(p) == rId->getDiff(p)) { if(lId->getLT() < rId->getLT()) return true; else if(lId->getLT() == rId->getLT()) return (lId->getTFG() < rId->getTFG()); } return false; } vector<set<Node*, bool (*)(Node*,Node*) > > m_F; for (int i = 0;i < partNum; ++i) { //This doesn`t workbecause of const problem... set<Node *, bool (*)(Node*,Node*) > f(&FComapare<i>); m_F.push_back(f); } I am getting following error error C2664: 'std::set<_Kty,_Pr>::set(bool (__cdecl *const &)(Node *,Node *))' : cannot convert parameter 1 from 'bool (__cdecl *)(Node *,Node *)' to 'bool (__cdecl *const &)(Node *,Node *)' 1> with 1> [ 1> _Kty=Node *, 1> _Pr=bool (__cdecl *)(Node *,Node *) 1> ] Reason: cannot convert from 'overloaded-function' to 'bool (__cdecl *const )(Node *,Node *)' 1> None of the functions with this name in scope match the target type How can I solve the problem and get the same functionality? How do I define correctly vector<set<Node*, bool (*)(Node*,Node*) > > m_F; Thanks A: You can't use a variable for the non-type argument. Instead of a template function, try a function object that stores the value of i. class FCompare { int p; public: FCompare(int p): p(p) {} bool operator()(const Node *lId, const Node* rId) const {...} }; set<Node *, FCompare > f((FCompare(i)));
{ "pile_set_name": "StackExchange" }
Q: How to update document in Azure CosmosDB in C# I have a method that loads a document from Cosmos DB. The document is not strongly type and it cannot be strongly typed. I want to update various properties on the document and then push that document back to CosmosDB. The problem that I'm having is that the property that I want to update is nested underneath another object and I cannot find documentation on how to navigate down to this sub property and update that. Here is what I'm currently trying to do. var project = await Service.GetById(projectId) as Microsoft.Azure.Documents.Document; var gate = project.GetPropertyValue<dynamic>("IdeaInitiatedGate"); project.SetPropertyValue("IdeaInitiatedGate.VpApprovalStatus", status); project.SetPropertyValue("IdeaInitiatedGate.VpApprovalComments", comments); project.SetPropertyValue("IdeaInitiatedGate.VpApprovalOn", DateTime.Now); project.SetPropertyValue("IdeaInitiatedGate.Status", status == "Approved" ? "Completed" : "Rejected"); if (status == "Approved") { project.SetPropertyValue("CharterReview.Status", "Active"); } var document = await Service.Replace(project); Service is just wrapper around the actual CosmosDB calls. What is happening with the above code is that new property is being created in the document called "IdeaInitiatedGate.VpApprovalStatus" right at the root of the document. What I want to happen is to update the VpApprovalStatus property of the IdeaInitiatedGate to the new value. want to update this { "IdeaInitiatedGate": { "VpApprovalStatus": "Approved" } } not create this { "IdeaInitiatedGate.VpApprovalStatus": "Approved" } The final working solution that I ended up with is below. Basically I use the GetPropertyValue to pull out the root object that I want, which is dynamic and then I change this object and the SetProperty value of the entire dynamic object. if (!(await Service.GetById(projectId) is Document project)) return null; var gate = project.GetPropertyValue<dynamic>("IdeaInitiatedGate"); gate.VpApprovalStatus = status; gate.VpApprovalComments = comments; gate.VpApprovalOn = DateTime.Now; gate.Status = status == "Approved" ? "Completed" : "Rejected"; project.SetPropertyValue("IdeaInitiatedGate", gate); if (status == "Approved") { var charterGate = project.GetPropertyValue<dynamic>("CharterReview"); charterGate.Status = "Active"; project.SetPropertyValue("CharterReview", charterGate); } var result = await Service.Replace(project); A: We could set IdeaInitiatedGate Property with a JObject project?.SetPropertyValue("IdeaInitiatedGate", new JObject { { "VpApprovalStatus", status }}); If you want to add the mutilple property for IdeaInitiatedGate. We could do with following way. project?.SetPropertyValue("IdeaInitiatedGate", new JObject { { "VpApprovalStatus", "Approved" },{ "VpApprovalComments", comments},{ "VpApprovalOn", DateTime.Now }}); The following is the demo code. It works correctly on my side. var project = (Document)client.CreateDocumentQuery<dynamic>(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName)) .AsEnumerable() .First(); var gate = project?.GetPropertyValue<dynamic>("IdeaInitiatedGate"); project?.SetPropertyValue("IdeaInitiatedGate", new JObject { { "VpApprovalStatus", "Approved" }}); var document = client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, project?.Id), project).Result.Resource; Check from the Azure Portal:
{ "pile_set_name": "StackExchange" }
Q: OUTPUT a DATE and Time from database TIMESTAMP PHP How can i convert the timestamp in database table row to 9:00AM or PM say i have a row value from database 2016-10-14 15:08:06 the Output must be 2016-10-14 03:08 AM or PM using php 2016-10-14 03:08 AM A: for example we have time stamp at below variable $t="1512314221"; use Date function to convert it to date time format : echo Date("Y-m-d H:i:s",$t); //output 2017-03-13 15:17:01 also you can append these strings to date format : F A full textual representation of a month, such as January or March m Numeric representation of a month, with leading zeros 01 through 12 M A short textual representation of a month, three letters Jan through Dec l (lowercase 'L') A full textual representation of the day of the week Sunday through Saturday D A textual representation of a day, three letters Mon through Sun g 12-hour format of an hour without leading zeros 1 through 12 G 24-hour format of an hour without leading zeros 0 through 23 h 12-hour format of an hour with leading zeros 01 through 12
{ "pile_set_name": "StackExchange" }
Q: Hyper-V virtualization with google compute engine image I am trying to download an image from my Google Compute Engine VM Instances in Google Cloud Platform and I'm following this article to export the image to a GCS Bucket and download it locally. I need to restore/import this image in an on-premises Hyper-V VM for testing purposes. How can I virtualize a Hyper-V VM from a GCE image? A: If the file you downloaded is a raw image of the virtual hard drive, then you will need to convert it to a VHD or VHDX first. The tools available in VirtualBox are a good fit for this situation. VBoxManage.exe clonehd "diskimage.img" "diskimage.vhd" -format vhd or VBoxManage.exe clonehd "diskimage.img" "diskimage.vhdx" -format vhdx
{ "pile_set_name": "StackExchange" }
Q: Condition number of a polynomial root problem I dont't understand how the condition number is defined for a problem such as: $x^2-2xp+1=0,\ p\geq1$ Here there are two roots $x_-=p-\sqrt{p^2-1}$ and $x_+=p+\sqrt{p^2-1}$ I understand that the sum is not well conditionned because the relative error can become very high if the numbers sum up to something close to zero, so when $p$ is close to $1$ both roots $x_-$ and $x_+$ are unstable and when $p$ is big $x_-$ is unstable (that is why we take advantage of the fact that $x_-=\frac{1}{x_+}$ and the division is a stable operation). But I don't understand why the condition number $K(p)\simeq \frac{p}{\sqrt{p^2-1}}$ for $p>1$ I would appreciate it if someone could explain to me how I should understand the condition number. A: By definition, the (relative) condition number of $x_+(p)$ is $$ K(p)=\frac{p}{x_+}\frac{dx_+}{dp} = \frac{p}{p+\sqrt{p^2-1}} \left( 1+\frac{p}{\sqrt{p^2-1}} \right) = \frac{p}{\sqrt{p^2-1}}. $$ The root $x_+$ is sensitive for $p$ close to one with $K$ growing to infinity and insensitive for large $p$ with $K\approx 1$.
{ "pile_set_name": "StackExchange" }
Q: What HTTP status code should I use for processing status update? I am building an application that sends a set of images to a custom server for processing. The processing can take up to several minutes, so I am implementing a progress bar in the app. The progress bar is updated via an http get request that returns a JSON object containing either an error message, the status of the processing, or the results of the processing. Upon a successful upload (via put request) the server responds with a status of 202 Accepted. The HTTP request responds with a status of 500 Internal Server Error if an error has occurred, 102 Processing if the processing has not completed, and 200 Ok if the processing is done and the results are available. When I am testing in postman the content of the message when a 102 Processing status is returned is hidden, leading me to believe I am misunderstanding something about which codes I should be using. Do the HTTP codes I am using in these scenarios make sense or should I be using other codes? Thank you A: 102 Processing is not a "normal" status code. Like the others in the 100 series, they act more like an 'intermediate' status code. When a server sends 102 or 10x, it means that the client will continue to wait for a 'real' status code. So an actual single HTTP request might result in all of the following HTTP status codes: 100 102 102 (might appear more than once) 103 103 200 (finally got the real 'OK'). Your use-case is not an appropiate usage of 102, unless you keep the connection open and send more status-codes. Many HTTP clients don't have a built-in way to notify you of these 'intermediate statuses', but some do. Given that you're doing a sort of polling and you have a resource that represents 'the status of the image' (I'm imagining something like /image/{upload-id}/status it's fine for that resource to return 200 OK both when the image has and has not been processed. Think about it this way, regardless of the image itself, the 'status of the image'-resource is always available and can return 200. Plug: I wrote a blog post about this code.
{ "pile_set_name": "StackExchange" }
Q: Breakpoint a multi thread application What happens if I breakpoint a multi thread application. does it stop all the threads, just the one that is break pointed or does the whole program just crash ? If it is possible would I want to stop just one thread or would this mess up my application ? If I cannot break point a multi tread application what are the debug techniques available to me ? A: JAVA: As far as personal experience goes, you can debug multi-threaded applications by stopping all threads or individual threads. It would most likely depend on what IDE you are using, and what application you are connecting to, but for me its: Eclipse connecting in debug mode to a Tomcat server running in jpda Place a breakpoint in the code, go to Eclipse's debug perspective (sometimes it pauses but doesn't switch perspective) In the breakpoints window, you will see a list of breakpoints. Each one you can right-click and set properties on... if you want to stop all threads on one breakpoint, hit the Suspend VM radio button. If you only want to stop a single thread, click suspend thread. I'm not sure you're able at this point to select which thread you want to pause if using the single thread stop option. In Suspend VM, you can look at the Debug pane and see your thread... scroll down and you can jump between the threads (Daemon thread 10 vs Daemon thread 9, something like that) A: It stops all threads. It is not normally possible to just stop one thread. For more information on debugging threads with GDB see this part of the manual.
{ "pile_set_name": "StackExchange" }
Q: NSPredicate for NSNumber property of NSManagedObject I have NSNumber * year property of NSManagedObject, it's type in data model is Integer 16. I try to check with NSPredicate for this year, but can't find the right one. What I tried: NSPredicate *p = nil; NSNumberFormatter *nf = [[NSNumberFormatter alloc] init]; NSNumber *yearNo = [nf numberFromString:term]; if (yearNo) { p = [NSPredicate predicateWithFormat:@"(cars.year == %i)", yearNo.intValue]; } I also tried: NSPredicate *p = nil; NSNumberFormatter *nf = [[NSNumberFormatter alloc] init]; NSNumber *yearNo = [nf numberFromString:term]; if (yearNo) { p = [NSPredicate predicateWithFormat:@"(cars.year == %@)", yearNo]; } In both cases app crashes. A: If you provide more details for your model, we could help you. But I think the problem is due to cars. If cars is to-many you need a modifier for this [NSPredicate predicateWithFormat:@"ANY cars.year == %@", yearNo]; A: As @flexaddicted already said, you have not supplied sufficient information, e.g. for which entity the fetch request is made. If you want to fetch Car objects with a given year, the predicate is just [NSPredicate predicateWithFormat:@"year == %@", yearNo]
{ "pile_set_name": "StackExchange" }
Q: Struct and Pointers C++ I am experimenting with Struct, pointers and typedef in the code below. I want to create a pointer to a struct that I made up. Then I want to manipulate the struct's members using the -> operator. The below code compiles fine, however, when I run the program it produces a segmentation fault. Can someone please help explain where my logic went wrong? Thank you. struct Structure1 { char c; int i; float f; double d; }; typedef Structure1* structp; int main(){ structp s1, s2; s1->c = 'a'; s1->i = 1; s1->f = 3.14; s1->d = 0.00093; s2->c = 'a'; s2->i = 1; s2->f = 3.14; s2->d = 0.00093; } A: structp s1, s2; You've declared two pointers, s1 and s2 but they don't point anywhere yet! You need to allocate memory for these pointers using new. s1 = new Structure1(); s1->c = 'a'; s1->i = 1; // ... Don't forget to delete the memory afterwards: delete s1; See this answer why the parentheses in new Structure1() make a difference. Also, note that there are other ways to obtain a pointer to an object, such as using the & operator, but in this particular case, I think you want to allocate memory.
{ "pile_set_name": "StackExchange" }
Q: Can I see what search terms are most often used to get to stackoverflow? I saw this page http://www.101appsblog.com/alternativa-pc-game/ and it has footer saying Incoming search terms: alternativa walkthrough alternativa game walkthrough Does stackoverflow has statistics like this? A: You can get some sort of non-authoritative analytics on alexa (click "Search analytics"). They are estimated, but should at least be somewhat accurate. For Stack Overflow they would be: stack overflow 0.18% jquery redirect 0.04% stackoverflow 0.04% jquery this 0.03% php self 0.03% jquery create element 0.03% jquery timeout 0.02% jquery settimeout 0.02% call javascript in jquery 0.02% nib file with two view 0.02%
{ "pile_set_name": "StackExchange" }
Q: Hide sub div on second time click I've following script to show & hide subdiv on subsequent clicks but somehow it doesn't hide subdiv on second click. Here's the code: <script> $.ajax({ $('#floatcategory').append("<div class='floatbutton' id='float_"+categories[k][0]+"'>" +categories[k][1]+"</div>"); $('#floatcategory').append("<div id='"+categories[k][0]+"_"+products[l][0]+"'>" +products[l][1]+"</div>"); }); $('.floatbutton').live('click',function() { var floatidl=$(this).attr('id'); var floatid=floatidl.substr(6); if ($('#'+floatidl'').hasClass("clicked-once")){ $('[id^="'+floatid+'_"]').hide(); $('#'+floatidl'').removeClass("clicked-once"); } else { $('[id^="'+floatid+'_"]').show(); $('#'+floatidl'').addClass("clicked-once"); } }); </script> I'm using jQuery version 1.6. It doesn't hide the div. Can anyone help? A: Use .live() (for older jquery versions - < v1.7): $('.floatbutton').live('click',function() { var floatidl=$(this).attr('id'); var floatid=floatidl.substr(6); if ($('#'+floatid).hasClass("clicked-once")){ $('[id^='+floatid+']').hide(); $('#'+floatid).removeClass("clicked-once"); } else { $('[id^='+floatid+']').show(); $('#'+floatid).addClass("clicked-once"); } }); or $(document).delegate('.floatbutton','click',function() { var floatidl=$(this).attr('id'); var floatid=floatidl.substr(6); if ($('#'+floatid).hasClass("clicked-once")){ $('[id^='+floatid+']').hide(); $('#'+floatid).removeClass("clicked-once"); } else { $('[id^='+floatid+']').show(); $('#'+floatid).addClass("clicked-once"); } }); Use .on() (for new jquery versions - >= 1.7): $(document).on('click','.floatbutton',function() { var floatidl=$(this).attr('id'); var floatid=floatidl.substr(6); if ($('#'+floatid).hasClass("clicked-once")){ $('[id^='+floatid+']').hide(); $('#'+floatid).removeClass("clicked-once"); } else { $('[id^='+floatid+']').show(); $('#'+floatid).addClass("clicked-once"); } }); Hope this helps you :)
{ "pile_set_name": "StackExchange" }
Q: Spoiler Display Code I have a question about your spoiler in this page: http://jdownloader.org/download/index When i click on Windows it appears a table but when i click on Linux the content of Windows disappears. I want create a spoiler like this but that the content of one spoiler doesn't disappear when i press another spoiler. What exactly should I change in this code (html source)? <div class="dokuwiki"> <div class="right_page"> <div class="entry-content"> <script type="text/javascript" src="./JDownloader.org - Official Homepage_files/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".nonjs").removeAttr( "href"); //href is needed for users without JS $('.OS').click(function(){ if($(this).find(".details").is(":visible")) { $(this).find(".details").not(":hidden").hide("slow"); return true; } else { $(".OS").not(this).each(function(i) { $(this).find(".details").hide("slow"); }); $(this).find(".details").show("slow"); return false; } }); }); </script> <style type="text/css"> <!-- .details { display: none; clear: both; padding: 2px; } .nonjs{ cursor:pointer; } img { border: 0px; } --> </style> A: $(".OS").not(this).each(function(i) { $(this).find(".details").hide("slow"); }); That part finds all the ones that are NOT the current (clicked) one and hides them.
{ "pile_set_name": "StackExchange" }
Q: sublime text 3 plugin host crash recovery I develop a plugin for Sublime Text 3 and my python code uses c type bindings to clang. Sometimes calling libclang would segfault with libclang: crash detected during reparsing (I don't understand the reason yet, but it is irrelevant to this question). This then leads to crashing plugin host. So the question is: is there any way in python to recover from a failure in the underlying c binding? I would gladly just skip this action on this particular file where I experience the crash. Thanks! UPD: There was a short discussion in comments and it makes sense to elaborate further on the lack of a proper small reproducible example. It is not vecause of my laziness, I do try to make it as easy as possible to understand the issue for the people I expect help from. But in this case it is really hard. The original issue is caused by libclang segfaulting in some strange situation which I haven't nailed down yet. It probably has something to do with one library being compiled with no c++11 support and the other one using it while being compiled with c++11 support, but I want to emphasize - this is irrelevant to the question. The issue here is that there is a segfault in something that python is calling and this segfault causes Sublime Text plugin_host to exit. So there is simple example here, but not for the lack of trying. I am also open to suggestions if you have ideas how to construct one. And sorry for the poor quality of this question, this is currently my best. A: Working with the detail that I have, I'm reasonably sure your question boils down to "can Python handle errors that occurred when using the foreign function interface." I'm pretty sure that the answer is "no", and I put together the following test scenario to explain why: Here's our test C++ module (with a bit of C for name-mangling purposes) that will blow up in our face, test.cc : #include <iostream> #include <signal.h> class Test{ public: void test(){ std::cout << "stackoverflow" << std::endl; // this will crash us. shouldn't really matter what SIG as long as it crashes Python raise (SIGABRT); } }; extern "C" { Test* Test_new(){ return new Test(); } void Test_example(Test* test){ test->test(); } } clang -shared -undefined dynamic_lookup -o test.so test.cc And our calling script, test.py: from ctypes import cdll test_so = cdll.LoadLibrary("test.so") class PyTest: def __init__(self): self.obj = test_so.Test_new() def output(self): test_so.Test_example(self.obj) if __name__ == "__main__": p = PyTest() p.output() Call it: Ξ /tmp/29_may → python test.py stackoverflow [1] 55992 abort python test.py This crashes Python as expected and generates a nice "report error" detail on OS X: Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 libsystem_kernel.dylib 0x00007fff95bf48ea __kill + 10 1 test.so 0x0000000110285006 Test::test() + 70 2 test.so 0x0000000110284fb5 Test_example + 21 3 _ctypes.so 0x000000011026d7c7 ffi_call_unix64 + 79 4 _ctypes.so 0x000000011026dfe6 ffi_call + 818 5 _ctypes.so 0x000000011026970b _ctypes_callproc + 867 6 _ctypes.so 0x0000000110263b91 PyCFuncPtr_call + 1100 7 org.python.python 0x000000010fd18ad7 PyObject_Call + 99 8 org.python.python 0x000000010fd94e7f PyEval_EvalFrameEx + 11417 9 org.python.python 0x000000010fd986d1 fast_function + 262 10 org.python.python 0x000000010fd95553 PyEval_EvalFrameEx + 13165 11 org.python.python 0x000000010fd91fb4 PyEval_EvalCodeEx + 1387 12 org.python.python 0x000000010fd91a43 PyEval_EvalCode + 54 13 org.python.python 0x000000010fdb1816 run_mod + 53 14 org.python.python 0x000000010fdb18b9 PyRun_FileExFlags + 133 15 org.python.python 0x000000010fdb13f9 PyRun_SimpleFileExFlags + 711 16 org.python.python 0x000000010fdc2e09 Py_Main + 3057 17 libdyld.dylib 0x00007fff926d15ad start + 1 I copy and pasted this because it's cleaner/easier to parse than an strace (also, I'm lazy ;). The call to __kill is where we crashed; we never see a return to Python, which means it's out of our control. To prove this, modify our test.py into test_handle_exception.py to try to catch the exception: from ctypes import cdll test_so = cdll.LoadLibrary("test.so") class PyTest: def __init__(self): self.obj = test_so.Test_new() def output(self): test_so.Test_example(self.obj) if __name__ == "__main__": p = PyTest() try: p.output() except: print("If you're reading this, we survived somehow.") And running it again: Ξ /tmp/29_may → python test_handle_exception.py stackoverflow [1] 56297 abort python test_handle_exception.py Unfortunately, and as far as I know, we cannot catch the exception/crash at the Python layer because it happened "beneath" the control of bytecode. A non-specific Exception clause will try to catch any exception that occurs, where the following statement is the action taken when an exception gets caught. If you're reading this, we survived somehow. was never sent to stdout, and we crashed, which means Python doesn't get a chance to react. If you can, handle this exception in your C++ code. You may be able to get creative and use multiprocessing to fork into a process that can crash without taking down your main process, but I doubt it.
{ "pile_set_name": "StackExchange" }
Q: jQuery event on select change except one select I have a page with several select buttons. I would like for a function to be called in jQuery any select function except for say one with id="Select1" is changed. I know that I can link the function to each select that I want liked to the event, but it would be much more convenient to specify those that should be excluded than list all that should be included. Would it be possible for one specific class of selects to cause a change? A: $('select:not(#Select1)'); or if you're specifying several to exclude: $('select:not(.excludeClass)'); the same can be achieved with method chaining: $('select').not('#Select1');
{ "pile_set_name": "StackExchange" }
Q: NSDate processing very CPU intensive I have a method in my code for processing a string that needs to be transformed in a NSDate. This method is called hundreds on times a second, and apparently is very inefficient. How can it be improved as much as possible? - (NSDate *)getDateFromString:(NSString *)dateString { NSDateFormatter* formatter = [NSDateFormatter new]; [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"]; [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; NSDate* date = [formatter dateFromString:dateString]; if (date == nil) { [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"]; date = [formatter dateFromString:dateString]; } return date; } A: The number one thing you can do is don't create that formatter instance each call! Creating formatters are very expensive. From Apple's "Data Formatting Guide": Creating a date formatter is not a cheap operation. If you are likely to use a formatter frequently, it is typically more efficient to cache a single instance than to create and dispose of multiple instances. You can do this with a static var or with properties and the lazy load pattern. For example, using static: -(NSDate *)getDateFromString:(NSString *)dateString{ static NSDateFormatter *formatterWithZone = nil; static NSDateFormatter *formatterWithoutZone = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ formatterWithZone = [NSDateFormatter new]; [formatterWithZone setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"]; [formatterWithZone setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; formatterWithoutZone setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"]; }); NSDate *date = [formatterWithZone dateFromString:dateString]; //... date = [formatterWithoutZone dateFromString:dateString]; } Or, if you're going to use the formatter elsewhere, put it in a property: @property (nonatomic) NSDateFormatter *formatterWithZone; @property (nonatomic) NSDateFormatter *formatterWithoutZone; //... -(NSDateFormatter *)formatterWithZone{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _formatterWithZone = [NSDateFormatter new]; [_formatterWithZone setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"]; [_formatterWithZone setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; }); return _formatterWithZone; } -(NSDateFormatter *)formatterWithoutZone{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _formatterWithoutZone = [NSDateFormatter new]; [_formatterWithoutZone setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"]; }); return _formatterWithoutZone; } -(NSDate *)getDateFromString:(NSString *)dateString{ NSDate* date = [[self formatterWithZone] dateFromString:dateString]; //... date = [[self formatterWithoutZone] dateFromString:dateString]; } UPDATE: Also check out (and upvote) mrueg's comment below about NSCalendar -currentCalendar being expensive. Both the above techniques would work to cache an NSCalendar instance as well. A: Date formatters are very expensive to create (and to change the format of). Make two static date formatter variables, one for each format, and use them instead of creating new formatters each time. Create the formatters inside a dispatch_once block.
{ "pile_set_name": "StackExchange" }
Q: Switch from file contents to STDIN in piped command? (Linux Shell) I have a program (that I did not write) which is not designed to read in commands from a file. Entering commands on STDIN is pretty tedious, so I'd like to be able to automate it by writing the commands in a file for re-use. Trouble is, if the program hits EOF, it loops infinitely trying to read in the next command dropping an endless torrent of menu options on the screen. What I'd like to be able to do is cat a file containing the commands into the program via a pipe, then use some sort of shell magic to have it switch from the file to STDIN when it hits the file's EOF. Note: I've already considered using cat with the '-' for STDIN. Unfortunately (I didn't know this before), piped commands wait for the first program's output to terminate before starting the second program -- they do not run in parallel. If there's some way to get the programs to run in parallel with that kind of piping action, that would work! Any thoughts? Thanks for any assistance! EDIT: I should note that my goal is not only to prevent the system from hitting the end of the commands file. I would like to be able to continue typing in commands from the keyboard when the file hits EOF. A: I would do something like (cat your_file_with_commands; cat) | sh your_script That way, when the file with commands is done, the second cat will feed your script with whatever you type on stdin afterwards.
{ "pile_set_name": "StackExchange" }
Q: SQL Count certain elements in a group showing each element and total count Imagine I have a table like this : +----+--------+--------+------+ | ID | NAME | DEPTNO | MGR | +----+--------+--------+------+ | 1 | AYEW | 10 | 4 | | 2 | JORDAN | 20 | 4 | | 3 | JAMES | 20 | 4 | | 4 | MESSI | 30 | NULL | +----+--------+--------+------+ I need to display a result like this : +----+---------+-------------+--------+-------+ | ID | MANAGER | SUBORDINATE | DEPTNO | COUNT | +----+---------+-------------+--------+-------+ | 4 | MESSI | AYEW | 10 | 1 | | 4 | MESSI | JORDAN | 20 | 2 | | 4 | MESSI | JAMES | 20 | 2 | +----+---------+-------------+--------+-------+ In other words, I have to count how many subordinates by department got each manager and also show the name and deptno of the subordinates. I know how to easily associate the managers and subordinates with a JOIN but the problem is in the column of count. How can i count the total subordinates by department showing subordinates names at the same time ? I assume I can't use GROUP BY to count the number of subordinates in each department so I have no idea how to do this. Figured out thanks to mathguy's answer it is also possible to do a second join like : join original_table c on (e.deptno=c.deptno and e.mgr=c.mgr) so the count column will also show the intended result. A: Not sure how the analytic functions are implemented internally - it is possible Gordon's solution is EXACTLY the same as below. (Ordering of rows will probably be different - add an explicit ORDER BY if needed.) NOTE: I took your lead and named a column "count" - in general that is best avoided, as "count" is a reserved word (use "cnt" or something like it instead). select m.id, m.name, e.name, e.deptno, c.count from emps e join emps m on e.mgr = m.id join (select mgr,deptno, count(*) count from emps where mgr is not null group by mgr, deptno) c on e.mgr = c.mgr and e.deptno = c.deptno SQL> / ID NAME NAME DEPTNO COUNT ---------- ------ ------ ---------- ---------- 4 MESSI JORDAN 20 2 4 MESSI JAMES 20 2 4 MESSI AYEW 10 1 3 rows selected. Elapsed: 00:00:00.01
{ "pile_set_name": "StackExchange" }
Q: Effect of the Tenth Doctor’s regeneration on the TARDIS Why was the TARDIS heavily damaged when the Tenth Doctor regenerated, but when the Ninth Doctor regenerated, there was no visible effect? Is it a writing error, or just done for plot-based reasons? A: The Tenth Doctor's regeneration was an unusually violent one. It's established that Time Lords have some control over their regenerations. For example, in the classic episode Destiny of the Daleks, Romana (a Time Lady and the Doctor’s companions) regenerated about half a dozen times until she found an appearance that she liked. In this instance, the Tenth Doctor was reluctant to regenerate. When describing regeneration, he said: Even if I change, it feels like dying. Everything I am dies. Some new man goes sauntering away… and I'm dead. He spent a long time putting it off, both before and after his lethal dose of radiation. Once he gets the dose, he makes a final trip to visit many of his companions, trying to keep regeneration at bay. All that time, regeneration energy is building up. When he finally concedes, it bursts out of him in a particularly explosive way. Normally the Doctor regenerates shortly after his “death”, so there's less of a buildup.
{ "pile_set_name": "StackExchange" }
Q: In voice recognition programs, what methods are generally used to separate voice from noise? I think voice recognition is cool, and I might start studying it soon, but one big question that I've always wondered about is "How do the programmers separate the noise from the voice?" I mean, if you've watched "Her", you'll notice the main character uses voice commands commonly in quiet places, but today, voice recognition is mostly used in the car, amid a LOT of background noise, and even possibly background voices. I've used Siri in these loud situations, and I'm always impressed that the program still understands me over the noise. So, without going into detailed specifics, I'd like to know what methods or concepts are generally used by programmers to do this. A: This is a big question, but the algorithms fall broadly under the category of signal processing. In short, there are a couple of things that make a voice stand out (or any other sound, for that matter, though I will call every sound a voice for simplicity's sake). They are pitch, timbre, and loudness. Pitch is probably the most familiar, but specifically it refers to the frequencies occupied by a voice. Most people voices have a uniform pitch, which is to say I've never heard of a single person singing a chord. Timbre is what makes the difference between a saxaphone and a violin playing the same note. It's like the flavor of the sound, and can be affected by the acoustics of the room, the noise (is it breathy or raspy), resonance, etc. Loudness is like the average pressure of the air's movement. It's surprisingly complicated, but for my explanation a volume knob works. Okay? Now, to isolate a sound, we can try and trace these three factors. It's pretty rare for a voice to change pitch, timbre, and loudness simultaneously. So we'll call a dramatic change in two of these a different voice. A fourier transform of your audio signal can give you a "frequency-loudness over time" view of it. So, if you look at a fourier transform (the graph at the bottom of the following image) you can begin to get an idea of how this can be carried out. Once you know where a voice lies along the spectrum in time, you can apply a moving band pass filter to it to isolate that signal. Still, this is something that has taken a long time for people to get right. Siri is just the latest in a long line of voice recognition applications of varying ability.
{ "pile_set_name": "StackExchange" }
Q: Google sign in not working android webview app I've created Android App with webview. When trying to sign in with Google, it first asks for username & password, then the screen with the message 'Please close this window' shows up & nothing happens. Also user is not logged in. P.S. This works absolutely fine with my mobile website which itself is ported to Android Webview App. Can anyone tell why that doesn't work? I'm completely new to Android. A: Here is the working code: public class MainActivity extends Activity { protected WebView mainWebView; // private ProgressBar mProgress; private Context mContext; private WebView mWebviewPop; private FrameLayout mContainer; private ProgressBar progress; private String url = "http://m.example.com"; private String target_url_prefix = "m.example.com"; public void onBackPressed() { if (mainWebView.isFocused() && mainWebView.canGoBack()) { mainWebView.goBack(); } else { super.onBackPressed(); finish(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = this.getApplicationContext(); // Get main webview mainWebView = (WebView) findViewById(R.id.webView); progress = (ProgressBar) findViewById(R.id.progressBar); progress.setMax(100); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { mainWebView.setWebContentsDebuggingEnabled(true); } mainWebView.getSettings().setUserAgentString("example_android_app"); // Cookie manager for the webview CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setAcceptCookie(true); // Get outer container mContainer = (FrameLayout) findViewById(R.id.webview_frame); if (!InternetConnection.checkNetworkConnection(this)) { showAlert(this, "No network found", "Please check your internet settings."); } else { // Settings WebSettings webSettings = mainWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setAppCacheEnabled(true); webSettings.setJavaScriptCanOpenWindowsAutomatically(true); webSettings.setSupportMultipleWindows(true); mainWebView.setWebViewClient(new MyCustomWebViewClient()); mainWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); mainWebView.setWebChromeClient(new MyCustomChromeClient()); mainWebView.loadUrl(url); } } // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.example_main, menu); // return true; // } private class MyCustomWebViewClient extends WebViewClient { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { progress.setProgress(0); progress.setVisibility(View.VISIBLE); super.onPageStarted(view, url, favicon); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { String host = Uri.parse(url).getHost(); Log.d("shouldOverrideUrlLoading", host); //Toast.makeText(MainActivity.this, host, //Toast.LENGTH_SHORT).show(); if (host.equals(target_url_prefix)) { // This is my web site, so do not override; let my WebView load // the page if (mWebviewPop != null) { mWebviewPop.setVisibility(View.GONE); mContainer.removeView(mWebviewPop); mWebviewPop = null; } return false; } if (host.contains("m.facebook.com") || host.contains("facebook.co") || host.contains("google.co") || host.contains("www.facebook.com") || host.contains(".google.com") || host.contains(".google.co") || host.contains("accounts.google.com") || host.contains("accounts.google.co.in") || host.contains("www.accounts.google.com") || host.contains("www.twitter.com") || host.contains("secure.payu.in") || host.contains("https://secure.payu.in") || host.contains("oauth.googleusercontent.com") || host.contains("content.googleapis.com") || host.contains("ssl.gstatic.com")) { return false; } // Otherwise, the link is not for a page on my site, so launch // another Activity that handles URLs //Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); //startActivity(intent); //return true; return false; } @Override public void onPageFinished(WebView view, String url) { progress.setVisibility(View.GONE); super.onPageFinished(view, url); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { Log.d("onReceivedSslError", "onReceivedSslError"); // super.onReceivedSslError(view, handler, error); } } public void setValue(int progress) { this.progress.setProgress(progress); } public void showAlert(Context context, String title, String text) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( context); // set title alertDialogBuilder.setTitle(title); // set dialog message alertDialogBuilder.setMessage(text).setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // if this button is clicked, close // current activity finish(); } }).create().show(); } private class MyCustomChromeClient extends WebChromeClient { @Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { mWebviewPop = new WebView(mContext); mWebviewPop.setVerticalScrollBarEnabled(false); mWebviewPop.setHorizontalScrollBarEnabled(false); mWebviewPop.setWebViewClient(new MyCustomWebViewClient()); mWebviewPop.getSettings().setJavaScriptEnabled(true); mWebviewPop.getSettings().setSavePassword(false); mWebviewPop.setLayoutParams(new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); mContainer.addView(mWebviewPop); WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj; transport.setWebView(mWebviewPop); resultMsg.sendToTarget(); return true; } @Override public void onProgressChanged(WebView view, int newProgress) { // TODO Auto-generated method stub super.onProgressChanged(view, newProgress); MainActivity.this.setValue(newProgress); } @Override public void onCloseWindow(WebView window) { Log.d("onCloseWindow", "called"); } } }
{ "pile_set_name": "StackExchange" }
Q: Cracking the Coding Interview, 6th Edition- Q: 2.2 The question is return the kth to last element of a singly linked list. All the proposed solutions are pretty complex, and I don't know why my solution is invalid. Could someone please let me know why? public class CrackTheInterview { /** * @param args the command line arguments */ public static Node kthToLast(Node n, int k) //pass in LinkedList's head node { int counter = 1; while (n.next != null) { n = n.next; } //at the end of the while loop, n equals the last node in the LinkedList while (counter != k) { n = n.previous; counter++; } //now node n is the kth node from the end return n; } } class Node { Node next = null; Node previous = null; int data; public Node (int d) { this.data = d; } } A: A singly linked list would not have both next and previous. You have a doubly linked list, which clearly makes this problem easier. A: I don't have a copy of that book, so I don't know what complicated solutions might be found in it, but the following two-finger solution seems pretty simple to me, and is not that different from yours aside from using a singly-linked list: /* Returns the kth last node in the list starting at n. * If the list is empty (n == null) returns null. * If k is <= 1, returns the last node. * If k is >= the number of nodes in the list, returns the first node. */ public static Node kthToLast(Node n, int k) { Node advance = n; while (--k > 0 && advance != null) { advance = advance.next; } /* Now advance is k nodes forward of n. Step both in parallel. */ while (advance != null) { advance = advance.next; n = n.next; } return n; }
{ "pile_set_name": "StackExchange" }
Q: В чем принципиальная разница DirectX и DirectX SDK? Здравствуйте. Недавно начал изучать DirectX, и у меня возник вопрос. Для написания программ использующих прямой доступ к видеоустройству необходим DirectX SDK. В этом пакете находятся библиотеки с описанием функций, структур, типов данных, а так же заголовочные файлы, включаемые в создаваемую программу. Далее написанный код преобразуется компилятором в объектный и пакуется в исполняемый файл или динамическую библиотеку. Так вот, сам вопрос: Почему для запуска исполняемого файла(те же игры) нужен именно DirecX, хотя для его создания был необходим DirectX SDK? И чем именно DirectX отличается от DirectX SDK? Заранее извиняюсь если что-то не правильно написал. A: sdk - это набор для программиста, что бы он мог создавать приложения. А вот конечному пользователю нужен небольшой набор файлов с sdk (обычно это называют run time или подобное) для того, что бы оно работало. Например. Программисту, что бы написать, нужна dll, заголовочный файл к ней и документация. А ещё и какие-нибудь воспомогательные утилиты. Это и будет sdk, а пользователю обычно нужна только dll.
{ "pile_set_name": "StackExchange" }
Q: Continuity of linear maps $l^\infty\rightarrow l^\infty$ Let $C=(c_1,c_2,...)\in l^1$ and $A:l^\infty\rightarrow l^\infty$ a linear map with $A(x)=(c_1x_1,c_1x_1+c_2x_2,c_1x_1+c_2x_2+c_3x_3,...)$ for $x=(x_1,x_2,...)\in l^\infty$. How do I prove that $A$ is continuous? Let $c=(c_1,c_2,...)$ be a sequence in a field $k$ such that $(c_1x_1,c_1x_1+c_2x_2,c_1x_1+c_2x_2+c_3x_3,...)\in l^\infty$ for $x\in l^\infty$. How do I prove that $c\in l^1$? What I know: I know that $l^p$ is the vector space of bounded sequences $\{x_i\}$ in $k$ such that $\sum |x_i|^p<\infty$. On $l^1$ the norm is $||x||_1=\sum|x_i|$ and on $l^\infty$ the norm is $||x||=\sup\{|x_i|\}$. Furthermore I know that one of the definitions of continuity (and probably the one I should use here) is that there exists a constant $\alpha$ such that $||A(x)||\leq \alpha||x||$ for all $x\in l^\infty$. Thus what I'm looking to prove is that $\sup\{|A(x)_i|\}\leq \alpha\sup\{|x_i|\}$. How do I do this? A: $\|A(x)\|_\infty=\sup|\sum_{i=1}^n c_i x_i|\leq\sup\sum_{i=1}^n|c_i||x_i|\leq\sup\sum_{i=1}^n|c_i|\cdot\|x\|_\infty=\|C\|_1\cdot\|x\|_\infty$. Edit. Answer to Question 2. I assume the field $k$ is restricted to $\mathbb{R}$ and $\mathbb{C}$, otherwise it's not easy to define norms. In both cases, for any number $t$ in the field $k$ there exists a number $f(t)$ such that $|f(t)|=1,tf(t)=|t|$. More precisely, one may choose $f(t)=\operatorname{sgn}(t)$ if $k=\mathbb{R}$, and $f(t)=e^{-i\arg t}$ if $k=\mathbb{C}$. Now take $x=(f(c_1),f(c_2),\cdots)$. It's easy to see $\|x\|_\infty=1$, hence $x\in l^\infty$. But due to the condition we have $\sup|\sum_{i=1}^n c_i x_i|=\sup\sum_{i=1}^n|c_i|=\sum_{i=1}^\infty|c_i|<\infty$, which shows $c\in l^1$.
{ "pile_set_name": "StackExchange" }
Q: Using 'DATE_SUB(now(), INTERVAL 2 MONTH)' properly with Codeigniter I'm trying to run this query with Codeigniter: SELECT * FROM `bf_bs_history` WHERE date > DATE_SUB(now(), INTERVAL 2 MONTH) If I enter it directly in phpMyAdmin, I get the result I want. However, running if from the code, it will not take any effect. It's not filtering at all. The PHP line looks like this: $this->history_model->where(array('date > ' => 'DATE_SUB(now(), INTERVAL 2 MONTH)'))->find_all(); Any idea where I go wrong? A: CodeIgniter Active Record is adding backticks to your statement, which renders your clause as a string, not an executable function. You can set a second parameter to false to stop that. Also, for a function predicate like this you can simply pass in the string: $this->history_model->where("date > DATE_SUB(now(), INTERVAL 2 MONTH)", false)->find_all();
{ "pile_set_name": "StackExchange" }
Q: Link from a html to directly a block element on other website Please help me, I have a html that contain a link <a href="LoginandRegistration/Login_register.html#signup">Sign Up</a> When I was click it I want to move it right into other html <div class="containerlogin"> <div class="avatarcontainer avatar"> <img src="avatar.jpg"> </div> <div class="Loginbox"> <div class="form"> <form class="login-form" name="login"> <p>User Name</p> <input type="text" placeholder="Enter Your Name"/><br> <p>Password</p> <input type="text" placeholder="Enter Your Password"/><br> <input type="submit" value="Login"><br> <p class="message">Create an account? <a href="#">Register</a></p> </form> <form class="register-form" name="signup"> <p>User Name</p> <input type="text" placeholder="Enter Your Name"/><br> <p>Password</p> <input type="text" placeholder="Enter Your Password"/><br> <p>Email</p> <input type="email" placeholder="Enter Your Email"/><br> <p>Phone number</p> <input type="tel" placeholder="Enter Yo Telephone Number"/><br> <p>Address</p> <input type="text" placeholder="Enter Your Address"/><br> <button>Create Account</button> <p class="message">Alreday Have an account? <a href="#">Login</a></p> </form> </div> </div> </div> Javascript <script src='https://code.jquery.com/jquery-3.3.1.js'></script> <script> $('.message a').click(function(){ $('form').animate({height:"toggle",opacity: "toggle"},"slow"); } ) </script> Here is the form https://i.imgur.com/vg27sQo.jpg https://i.imgur.com/ogEdgSY.jpg I use the javascript to change to login form to the sign up form but when I put a link like LoginandRegistration/Login_register.html#signup to the link on first html that can't link directly to sign up form, it still link to login form Please help me, thanks. A: The url hash is a link to an id related anchor in the page - You need to add the id to the form - such as: <form class="register-form" name="signup" id="signup"> That said - I would do it differently - I would display only the form identified by the url hash - rather than showing both and scrolling to the indicated one.
{ "pile_set_name": "StackExchange" }
Q: Load the solution in which the Stand-Alone code Analyser is being written I was trying to write an analyser to get information about some methods using the roslyn syntax tree. The problem is: The analyser that I am writing, needs to be in the same solution as the solution that I want to analyse. So, this is my code: using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; public static class Main { public static Solution solution { get; set; } = null; public static string GetMethodInfo(string methodToFind) { Task<Solution> GetSolutionTask = null; string namespaceToFind, classToFind, methodToFind, invocationToFind; if (solution == null) { var workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(); GetSolutionTask = workspace.OpenSolutionAsync(Config.SolutionPath); } if (GetSolutionTask != null) solution = GetSolutionTask.Result; foreach (Project proj in solution.Projects) { Compilation compilation = proj.GetCompilationAsync().Result; foreach (var tree in compilation.SyntaxTrees) { findMethodAndProcessIt()... } } return String.Empty; } } The problem I get is that no compilation has any syntax tree. I tried this same code by opening other solutions and it works. So clearly the problem here is to be trying to open the solution that the visual studio is using. I have already tried to run this code with visual studio closed, only running the .exe , but the problem persists. Do you have any idea on how to solve this? A: You are using MSBuildWorkspace to open a solution. Typically, when use of MSBuildWorkspace leads to projects not being loaded correctly, no source files, etc, there has been a failure during msbuild processing. This usually happens when your application does not have the same binding redirects in its app.config file that msbuild uses (in msbuild.exe.config), which causes some custom tasks/extensions to fail to load due to versioning mismatch. You'll want to copy the <assemblyBinding> section into your app.config.
{ "pile_set_name": "StackExchange" }
Q: multiple input field jquery.autocomplete i want to make autocomplete for many text input field... but with this autocomplete <html><head><script type="text/javascript" src="jquery-1.4.js"></script> <script type='text/javascript' src='jquery.autocomplete.js'></script> <link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" /> <link rel="stylesheet" href="main.css" type="text/css" /> <script type="text/javascript"> $().ready(function() { $("#perkiraan").autocomplete("proses_akun.php", { width:350, max:28, scroll:false }); }); </script> </head> <body> <div class="demo" style="width: 250px;"> <div> <p>Nama Akun : <input type="text" id="perkiraan" name="perkiraan" size="65"></p> </div> </div> <div id="pilihan"> </div> <div class="demo" style="width: 250px;"><div> <p>Nama Akun : <input type="text" id="perkiraan" name="perkiraan" size="65"></p> </div> </div> <div id="pilihan"> </div> </body> </html> i know it because only one same name permit for this jquery... but i want to add more input text (second, third, etc) below the first that using javascript too without copy paste the scriot and change its name... help please,,,, A: Working demo http://jsfiddle.net/nckYT/ Please note DOM should never have the same id attributes for elements which is the case in the sample above. i.e. id="perkiraan" solution use class attribute instead. I think the official doc says that if there are multiple same id then it takes the last id-ied element as the identified element. further for mutiple element you can use class element for autocomplete like this $( ".perkiraan" ).autocomplete({ that will attach autocomplete with all the elements with class perkiraan. or you can chain the different ids like $( "#perkiraan, #foo" ).autocomplete({ but addaing class will do the trick Hope this helps, lemme know if I missed anything, :) cose <body><div class="demo" style="width: 250px;"> <div><p>Nama Akun : <input type="text" class="perkiraan" name="perkiraan" size="65"></p></div></div><div id="pilihan"></div> <div class="demo" style="width: 250px;"> <div><p>Nama Akun : <input type="text" class="perkiraan" name="perkiraan" size="65"></p></div></div> <div id="pilihan"></div></body> Image 1 input 1 Image 2 input 2
{ "pile_set_name": "StackExchange" }
Q: AWS DynamoDB insert values in a LIST or NUMBER SET I'm using AWS DynamoDB for iOS. I created a table with a column of NumberSet. Now I'm trying to add values on it using the app but wondering why it saves differently. For example: I added values on NumberSet manually on the browser and its values will look like {123, 456, 789} While on using the app, it saves but it saves as [{"N": 123}, {"N": 456}, {"N": 789}] Any idea on how to save a NumberSet? I'm using swift on this. A: Okay. I just found out that I need to use a NSSet/NSMutableset to store NumberSet.
{ "pile_set_name": "StackExchange" }
Q: java.lang.verifyerror in android I have one android project.I have one class file of about 6000 lines when i tried to add more code it shows the java.lang.verifyerror please help me out A: I have used about 500 lines of switch case with atleast 25 case in it ,i put all the cases in if else condition and My problem solved
{ "pile_set_name": "StackExchange" }
Q: Why my Storyboard can't initiate on simulator? I built a storyboard like this: I didn't write a single line of code, and my settings seem to be correct. So why do I always get a blank screen on simulator? Please help me. A: Is your app delegate explicitly creating *window? If so, delete that line of code. // self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; But keep the property definition: @property (strong, nonatomic) UIWindow *window; // keep this
{ "pile_set_name": "StackExchange" }
Q: Trouble extracting First and LastName from Full Name column I am having FullName column and I am extracting the First Name and last name using the following query select SUBSTRING(FULL_NAME, 1, CHARINDEX(' ', FULL_NAME) - 1) AS FirstName, SUBSTRING(FULL_NAME, CHARINDEX(' ', FULL_NAME) + 1, 500) AS LastName from [dbo].[TABLE] But in the Full Name column there are just First names, some 10 digit phone numbers, 4 digit extensions and some text like 'this is a special case'. How should I modify my query to accommodate these exceptions? And also when there are only single words in the Full Name column I am getting this following error message: "Invalid length parameter passed to the LEFT or SUBSTRING function." A: Parsing good names from free form fields is not an easy task... I would suggest a dual approach. Identify common patterns, i.e. you might find phone number with something like this Where IsNumeric( Replace(Field,'-','')=1 and you might identify single names with Where charindex(' ',trim(field))=0 etc. Once you've identified them, the write code to attempt to split them... So you might use the code you have above with the following WHERE clause select SUBSTRING(FULL_NAME, 1, CHARINDEX(' ', FULL_NAME) - 1) AS FirstName, SUBSTRING(PRQ_BP_CONTACT_NAME, CHARINDEX(' ', FULL_NAME) + 1, 500) AS LastN from [dbo].[TABLE] where charindex(' ',trim(field))>0 and Where IsNumeric( Replace(Field,'-','')=0 Use the WHERE clauses to (a) make sure you only get records you can parse and (b) help identify the oddball cases you'll like need to do by hand... Good luck
{ "pile_set_name": "StackExchange" }
Q: measure length of edittext string dynamically in android How can i measure length of string entered in the edittext while typing.Because i want to show a warning when the entered text length cross 100 character. Thanks in advance. A: You can use TextWatcher to your EditText to do that in Android. Something like this EditText test = new EditText(this); test.addTextChangedListener(new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { try { //write your code here } catch (NumberFormatException e) { } } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } });
{ "pile_set_name": "StackExchange" }
Q: Get Application File Path in Windows Forms Application I have a simple windows form app that I need to get the file path for. I am placing a config file in the same directory and I need to be able to get the path to that file. I have used Application.CommonAppDataPath but that returns the path with 1.0.0.0 at the end. and Applicaiton.StartupPath but that returns the path with \bin\debug at the end Is there anyway to get the path to just the main file directory without anything appended to the end? A: Application.StartupPath is returning the path with \bin\debug on the end because that is where your code is running, at least on your development machine. If you are going to deploy this away from your development machine then Application.StartupPath will give you what you're asking for - the file path for your application. And yes, if you have deployed the config file to that same location, your code is going to find it. How to get the application also working on your development machine and get round the bin\debug issue? Well, a dirty hack would be just to chop the bin\debug string off the end of Application.StartupPath. In that case, if you need to check for whether you're running inside the debugger, see this question
{ "pile_set_name": "StackExchange" }
Q: sufficient condition for being an integral factor Let $ f: \mathbb {R}^m \rightarrow \mathbb {R}-\{0\} $ function $C^{\infty}$ class and $w$ a one-form $C^{\infty}$ class in $\mathbb {R}^m $. If $\alpha=w-\dfrac{1}{f}dx_{m+1} $ satisfies $\alpha \wedge d\alpha= w \wedge dw$ then $d(fw)=0$ Note: $\mathbb {R}^m \subseteq \mathbb {R}^{m+1}$ with $x_{m+1}=0$. Thanks for any suggestions. A: Well, by a straightforward computation, $$ \alpha \wedge d\alpha = (\omega - f^{-1}dx^{m+1}) \wedge d (\omega - f^{-1}dx^{m+1})\\ = (\omega - f^{-1}dx^{m+1}) \wedge (d\omega + f^{-2} df \wedge dx^{m+1})\\ = \omega \wedge d \omega + \omega \wedge f^{-2}df \wedge dx^{m+1} - f^{-1}dx^{m+1} \wedge d\omega\\ = \omega \wedge d\omega - f^{-2} (df \wedge \omega \wedge dx^{m+1} + f d\omega \wedge dx^{m+1})\\ = \omega \wedge d\omega - f^{-2} d(f \omega ) \wedge dx^{m+1}. $$ Now, given what you know, what can you conclude about $d(f\omega)$?
{ "pile_set_name": "StackExchange" }
Q: Java Regular Expression; need to map \' to '' I'm trying to map the \' to ''. That is, a string consisting of a backslash followed immediately by a single quote should be mapped to two single quotes. I've tried using string = string.replace("\'", "''") but this also maps a single quote to two single quotes (i.e., "'" to "''"), which is incorrect for what I need. What am I doing wrong? A: Backslash here is a escape character and it just will match ' if you want to match \' you need \\': string = string.replace("\\'", "''")
{ "pile_set_name": "StackExchange" }
Q: Gerar cor unica para cada resultado entao.. eu tenho um sistema de comentarios de forma anonima em um projeto meu que no lugar do avatar ele coloca a abreviação do nome da pessoa, por exemplo: Vinicius Eduardo -> VE e eu quero criar um sistema ou uma funcao que gere uma COR unica para cada abreviacao, para assim o usuario ser identificado com mais facilidade. Resumindo tudo, eu tenho uma array contendo 24 cores em formato "#VLVLVL" e para cada abreviacao ele vai dar uma cor unica, por exemplo VE -> #cccccc ED -> #000000 e se o VE comentar novamente a cor dele se repete como #cccccc A: Considerando uma array de cores assim: $cores = array('#000', '#333', '#666', '#999'); // do tamanho que você precisar Eu criaria uma segunda array, associativa, onde você guarda as cores para cada usuário. Ela começa vazia: $coresPorUsuario = array(); E a ideia é que ela passe a conter as cores dos usuários conforme eles vão surgindo. Por exemplo, array('VE' => '#000', 'ED' => '#333'). Para controlar tudo, use uma função. Ela recebe as iniciais do usuário e devolve a cor correspondente. Se o usuário já existe em $coresPorUsuario, pega a cor que está lá. Se não existe, pega a próxima cor disponível, associa ao usuário, e devolve essa cor. Também será necessária uma variável para controlar qual é a próxima cor disponível. $proxima = 0; function corUsuario($usuario) { global $cores; global $coresPorUsuario; global $proxima; // Usuário ainda não existe na array if(empty($coresPorUsuario[$usuario])) { // Guarda a cor do usuário e avança para a próxima cor disponível $coresPorUsuario[$usuario] = $cores[$proxima++]; // Se passou da quantidade de cores disponíveis, começa novamente da primeira $proxima = $proxima == count($cores) ? 0 : $proxima; } // Retorna a cor do usuário return $coresPorUsuario[$usuario]; } AVISO: O exemplo acima usa variáveis globais por ser um caminho curto como exemplo. É provável que você queira implementar essa função como um método de uma classe. Nesse caso, use propriedades de instância em vez das variáveis globais. Testando: echo corUsuario('AA') . "\n"; // #000 echo corUsuario('AB') . "\n"; // #333 echo corUsuario('AC') . "\n"; // #666 echo corUsuario('AA') . "\n"; // #000 echo corUsuario('AD') . "\n"; // #999 echo corUsuario('AE') . "\n"; // #000 Demonstração A: Você pode criar uma array para as cores ja usadas e outra para as cores de cada usuário. Eu poderia usar uma solução mais curta e prática, (e que alias usasse menos CPU..) mas queria que as cores fossem aleatorias.. mas como os usuários (ordenados por ID) já são aleatório o suficiente, acho a solução do bfavaretto melhor. Embora eu ache a solução dele mais prática e leve, vou manter a minha caso ainda tenho algum uso... fiz uma simples "ilustração". <?php // Array para as cores de cada usuário. # "NomeDeUsuario" => "COR HEX"; $usersColors = array(); // Array para as cores disponiveis [usei cores aleatorias] $avaliableColors = array( 0 => "#ececea", 1 => "#efefef", 2 => "#abcdef" ); // Primeiro pegamos os usuários, eles são a parte importantes $users = array( 'banana123', 'SouEUmesmo', 'kitKat159', ); // Se tiver mais usuários do que cores, abortar execução if ( count($users) > count($avaliableColors) ) { die("ERRO: existem mais usuários do que cores."); } // Vamos criar uma array que guarda as cores ja usadas, pra não repeti-las $alreadyUsed = array(); $userCount = count($users); $colorCount = count($avaliableColors); // Definindo uma cor aleatoria para cada um for ($i=0;$i<$userCount;++$i) { // Numero aleatorio representando uma das cores. $max = $colorCount-1; $numeroAleatorio = rand(0, $max); if (in_array($numeroAleatorio, $alreadyUsed)) { // Se o numero ja tiver sido usado, ficar até encontrar um não utilizado $numeroNaoUsadoEncontrado = false; while ($numeroNaoUsadoEncontrado != true) { $numeroAleatorio = rand(0, $max); // Se o numero não tiver sido utilziado aidna if (!in_array($numeroAleatorio, $alreadyUsed)) { // Sair do loop de tentativas $numeroNaoUsadoEncontrado = true; // Colocar esse numero como já usado. $alreadyUsed[] = $numeroAleatorio; } } } else { // Colocar esse numero como já usado. $alreadyUsed[] = $numeroAleatorio; } // Agora que a cor ja foi escolhida, atribuir ela ao usuário $userName = $users[$i]; $usersColors[$userName] = $avaliableColors[$numeroAleatorio]; } # DEBUG echo "<br>"; foreach ($usersColors as $user => $color) { echo $user . " -> " . $color . "<br/>\n"; }
{ "pile_set_name": "StackExchange" }
Q: how to use a javascript variable inside html tag I have a form in this There are two field One is Search and other is Option When i select any value from Search field the value of Option field will change.Value of Second field are different datalist defines as datalist1,datalist2,datalist3.....I want the value given in List attribute of Second filed to be same as the variable value in java script.i Tried the following code this code is not giving any output. function random() { var a = document.getElementById('search').value; if (a === "sampleid") { var datalist = datalist1; } else if (a === "facility") { var datalist = datalist1; } else if (a === "user") { var datalist = datalist3; } else if (a === "affiliation") { var datalist = datalist4; } else if (a === "status") { var datalist = datalist5; } else if (a === "btr") { var datalist = datalist6; } else if (a === "type") { var datalist = datalist7; } document.getElementById('option').innerHTML = datalist; } <form class="form-inline" method="post" action="search-sample.php"> <div class="col-md-5" align="center"> <label class="search">SEARCH BY-</label> <select type="text" name="SEARCH" id="search" class="form-control" onchange="random()"> <option value="SELECT TYPE">SELECT TYPE</option> <option value="sampleid">SAMPLE-ID</option> <option value="facility">FACILITY</option> <option value="user">USER NAME</option> <option value="affiliation">AFFILIATION</option> <option value="status">STATUS</option> <option value="btr">BTR</option> <option value="type">SAMPLE TYPE</option> <option value="date">DATE</option> </select> </div> <div class="col-md-5" align="center"> <label class="search">OPTION</label> <input type="text" class="form-control" id="option" name="facility" list=< ?php echo "datalist" ?> /> </div> <datalist id="datalist1"> <option value=""> </option> <?php $sql = "SELECT * from tblfacility order by sampleid asc"; $query = $dbh -> prepare($sql); $query->execute(); $results=$query->fetchAll(PDO::FETCH_OBJ); $cnt=1; if($query->rowCount() > 0) { foreach($results as $result) { ?> <option value="<?php echo htmlentities($result->sampleid);?>"><?php echo htmlentities($result->sampleid);?></option> <?php }} ?> </datalist> A: Here is what you need to do. Use quotes around the IDs of the datalists Use setAttribute of the list attribute of the input function random() { var a = document.getElementById('search').value, datalist = "datalist1"; if (a === "sampleid") { datalist = "datalist1"; } else if (a === "facility") { datalist = "datalist1"; } else if (a === "user") { datalist = "datalist2"; } else if (a === "affiliation") { datalist = "datalist3"; } else if (a === "status") { datalist = "datalist1"; } else if (a === "btr") { datalist = "datalist2"; } else if (a === "type") { datalist = "datalist3"; } const inp = document.getElementById('option'); inp.value=""; inp.setAttribute("list", datalist) } <form class="form-inline" method="post" action="search-sample.php"> <div class="col-md-5" align="center"> <label class="search">SEARCH BY-</label> <select type="text" name="SEARCH" id="search" class="form-control" onchange="random()"> <option value="SELECT TYPE">SELECT TYPE</option> <option value="sampleid">SAMPLE-ID</option> <option value="facility">FACILITY</option> <option value="user">USER NAME</option> <option value="affiliation">AFFILIATION</option> <option value="status">STATUS</option> <option value="btr">BTR</option> <option value="type">SAMPLE TYPE</option> <option value="date">DATE</option> </select> </div> <div class="col-md-5" align="center"> <label class="search">OPTION</label> <input type="text" class="form-control" id="option" name="facility" list="" /> </div> <datalist id="datalist1"> <option value="A"> </option> <option value="B"> </option> <option value="C"> </option> <option value="D"> </option> </datalist> <datalist id="datalist2"> <option value="AA"> </option> <option value="BB"> </option> <option value="CC"> </option> <option value="DD"> </option> </datalist> <datalist id="datalist3"> <option value="AAA"> </option> <option value="BBB"> </option> <option value="CCC"> </option> <option value="DDD"> </option> </datalist> </form>
{ "pile_set_name": "StackExchange" }
Q: How to get current Spring profile in jsp file. I'm developing Spring MVC application. In my application I have two profiles, test and production. Test is enable when I deploy my app to test envirionemnt, Production on production environment. I need to get current profile in jsp file. Is it possible ? I don't want to send additional variable to get this information because file is included to lot of others files. Thanks A: Since you are using MVC, a more straightforward approach is to autowire the environment in your controller and pass the profiles in the model. @Autowired private Environment environment; @RequestMapping("/needsProfile") public String needsProfile(Model model) { model.addAttribute("profiles", environment.getActiveProfiles()); return "needsProfile"; } And in your needsProfile.jsp: <jsp:useBean id="profiles" type="java.lang.String[]" scope="request"/> <%-- ... --%> <div>First Profile: ${profiles[0]}</div> A: You can use something like the following: ServletContext sc = request.getSession().getServletContext(); WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc); String[] profiles = applicationContext.getEnvironment().getActiveProfiles();
{ "pile_set_name": "StackExchange" }
Q: MySQL Select Group of Records Based on latest timestamp I have a routine that runs every few hours that creates several entries in a table used for logging. What I need to do is select all the records with the most recent timestamp that have a common account id. Something like this: SELECT * FROM TABLE_logs WHERE ACCOUNT_ID='12345' ORDER BY TIMESTAMP DESC Where I'm stuck is that I can't say LIMIT 5 or something like that because the number of records created at each routine interval could be different. So, for example, when the routine runs at 10AM, it may create 6 table entries and only 4 table entries at 2PM. Is there a way to select the grouping of the latest records without knowing how many there are? A: Assuming you mean multiple entries in your Table_Logs table could have the same timestamp and you want to return each of those that were entered most recently, you need to use GROUP BY: SELECT Field1, Field2, Max(TimeStamp) maxTime FROM Table_Logs WHERE Account_Id = '12345' GROUP BY Field1, Field2 Field1, etc. are the fields you want to return in Table_Logs. Here is some sample SQL Fiddle to try out. Good luck.
{ "pile_set_name": "StackExchange" }
Q: I need just the count of unique phone numbers in my mySql table. How do I do that? I have a mySQL table with list of people and phone numbers. There are some repeats in these phone numbers. I don't want to remove the duplicates based on the phone numbers as a same phone number is related to more that one entity. I just want the count of unique phone numbers in the phone number column. How do I do this? A: SELECT COUNT(DISTINCT COLUMN_NAME) FROM TABLE_NAME I think this is what you are looking for??
{ "pile_set_name": "StackExchange" }
Q: itemmouseleave event is not getting called if we move cursor quickly I have treepanel. On some specific condition I want to show image on mouse enter and remove that image on mouseleave in treenode. but when i hover the mouse quickly image get added but not getting removed as itemmouseleave event is not getting fired. I have prepared jsfiidle to understand my problem in which I am trying to change text of node on mouseenter and mouseleave. on slow motion it is working fine but if hover quickly it shows mouseenter even if we are away from node. Link to jsfiddle : http://jsfiddle.net/79ZkX/238/ Ext.create("Ext.tree.Panel", { title: "Car Simple Tree", width: 400, height: 600, store: store, rootVisible: false, lines: true, // will show lines to display hierarchy. useArrows: true, //this is a cool feature - converts the + signs into Windows-7 like arrows. "lines" will not be displayed renderTo: Ext.getBody(), listeners: { itemmouseenter: function(_this, _item) { var name = _item.get("name"); _item.set("name", "mouseenter"); }, itemmouseleave: function(_this, _item) { //var name = _item.get('name'); _item.set("name", "leave"); } }, columns: [ { xtype: "treecolumn", dataIndex: "name", // value field which will be displayed on screen flex: 1 } ] }); I want to remove the image on mouseleave. Thanks A: Added manual workaround for this. On Fast Mouse Hover itemmouseleave event will not get triggered. so i am maintaining array of hovered node and on mouseenter of node, checking if array contain element then set text of that node. added code to this jsfiddle: http://jsfiddle.net/79ZkX/250/ Ext.create('Ext.tree.Panel', { title: 'Car Simple Tree', width: 400, height: 600, store: store, rootVisible: false, visibleNodes: [], lines: true, // will show lines to display hierarchy. useArrows: true, //this is a cool feature - converts the + signs into Windows-7 like arrows. "lines" will not be displayed renderTo: Ext.getBody(), listeners : { itemmouseenter: function(_this, _item) { for (var i = 0; i < this.visibleNodes.length; i++) { var node = this.visibleNodes[i]; node.set('name', "leave"); this.visibleNodes.splice(i, 1); } var name = _item.get('name'); _item.set('name', "mouseenter"); this.visibleNodes.push(_item); }, itemmouseleave: function(_this, _item) { //var name = _item.get('name'); _item.set('name', "leave"); var index = this.visibleNodes.indexOf(_node); if (index != -1){ this.visibleNodes.splice(index, 1); } }, }, columns: [{ xtype: 'treecolumn', dataIndex: 'name', // value field which will be displayed on screen flex: 1 }] });
{ "pile_set_name": "StackExchange" }
Q: How to check if a function parameter is a Normalizr schema class? Is there any way to check, at runtime, if a function parameter is (or not) a Normalizr schema class? Could be any type: entity, array, object, etc. For example: function processTMDBRespose(response, schema) { // if 'schema' param is not a normalizr schema, throw! // some code } A: You can and can't do what you're looking for. If you write yourself a lint rule that only allows creating schema from normalizr classes, like new schema.Array() and prohibits the use of shorthand [], then you can check using instanceof: if ( mySchema instanceof schema.Array || mySchema instanceof schema.Entity || mySchema instanceof schema.Object || mySchema instanceof schema.Union || mySchema instanceof schema.Values ) { // your code } else { throw new Error('mySchema is not a schema'); } However, if you use shorthand, any array [] or plain object {} is also a valid schema for schema.Array and schema.Object, respectively. This is much more difficult to validate, because almost everything is typeof Object in JavaScript (like null)
{ "pile_set_name": "StackExchange" }
Q: VisualStateManager in Windows Phone 8 I'm trying to change the appearance of the button when the mouse pointer over it using VisualStateManager. But it does not work. Help, please! XAML <Button x:Name="button" Background="AntiqueWhite" Grid.Row="2" Grid.Column="0" MouseEnter="button_MouseEnter" MouseLeave="button_MouseLeave"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="ColorState"> <VisualState x:Name="MouseEnter"> <Storyboard Storyboard.TargetProperty="Background"> <ColorAnimation To="Aquamarine" Duration="0:1:30"/> </Storyboard> </VisualState> <VisualState x:Name="MouseLeave"/> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Button> С# private void button_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e) { bool bol = VisualStateManager.GoToState(this, MouseEnter.Name, true); } private void button_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e) { bool bol = VisualStateManager.GoToState(this, MouseLeave.Name, true); } A: Your VistualStateManager is not correct. As far as I know there is no "MouseEnter" but there is a MouseOver Here's the complete ControlTemplate for a <Button>. I comment out the default behavior for the MouseOver State and coded in your Color Change Animation. All you have to do is set any Button's Style to this "Chubs_ButtonStyle" and it will highlight to Aquamarine. Hopes this helps. <phone:PhoneApplicationPage.Resources> <Style x:Key="Chubs_ButtonStyle" TargetType="Button"> <Setter Property="Background" Value="Transparent"/> <Setter Property="BorderBrush" Value="{StaticResource PhoneForegroundBrush}"/> <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/> <Setter Property="BorderThickness" Value="{StaticResource PhoneBorderThickness}"/> <Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilySemiBold}"/> <Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMedium}"/> <Setter Property="Padding" Value="10,5,10,6"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid Background="Transparent"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"> <Storyboard> <!-- restore it back to original color --> <ColorAnimation To="AntiqueWhite" Storyboard.TargetProperty="(ContentContainer.Background).(SolidColorBrush.Color)" Storyboard.TargetName="ButtonBackground" Duration="0"/> </Storyboard> </VisualState> <VisualState x:Name="MouseOver"> <Storyboard> <!-- <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneAccentBrush}"/> </ObjectAnimationUsingKeyFrames> --> <ColorAnimation To="Aquamarine" Storyboard.TargetProperty="(ContentContainer.Background).(SolidColorBrush.Color)" Storyboard.TargetName="ButtonBackground" Duration="0"/> </Storyboard> </VisualState> <VisualState x:Name="Pressed"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneButtonBasePressedForegroundBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneAccentBrush}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Disabled"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground"> <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="0" Margin="{StaticResource PhoneTouchTargetOverhang}"> <ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/> </Border> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </phone:PhoneApplicationPage.Resources> Apply the style to a button like so <Button x:Name="button" Background="AntiqueWhite" Grid.Column="0" Width="100" Height="100" Style="{StaticResource Chubs_ButtonStyle}"/> Screenshots in action
{ "pile_set_name": "StackExchange" }
Q: Twitter API: count followers, count total retweet, and retrieve RSS feed of someone's twitter page I am new to Twitter API and only know that we can pull someone's Twitter feed from Twitter through RSS feed on that person's Twitter page/ profile. But, how can I pull more information of that person's Twitter page? For instance, His/ Her followers. Total of his/ her retweet items. http://www.qapture.net/ There are a couple of interesting things I still cannot figure them out how they did this website, If you compare the particular person's twitter feed on this website with that person's twitter page, some of the items are pull in qapture website, but some are not, so I think they must have select certain items of feed only - how do they do that?? If you mouse over an item of feed on qapture website, you can see other information of that feed item, such as '9 hours ago', '6 tweet(s)', etc - how do you get that information from? Which area of Twitter API that I should look into to achieve these...? I'm using PHP and Jquery for my web development by the way... Many thanks! Lau A: Take a look at the actual Twitter API, not just RSS feeds: http://dev.twitter.com/
{ "pile_set_name": "StackExchange" }
Q: What library does docker use to render the pulling/downloading/extracting information on terminal I really like how when I run docker build/compose in terminal it shows the status as it downloads/extracts layers. Does anyone know what library is used to render this? Is it something open-source or part of docker source code? A: Docker is written in GO language and the STDOUT manipulation you see must be written using the termbox package. The manipulation is none other than moving the cursor to the desired position before writing to STDOUT. func SetCursor(x, y int) The effect is updating text- rather than appending text.
{ "pile_set_name": "StackExchange" }
Q: Form partial in RefineryCMS I need to make a form that I can show on every page of my Refinery site. I know about rails g refinery:form and in fact, have already used that. I'm just wondering how to turn the generated view (located in /vendor/extensions) into a partial that I can use across the whole site. Thanks in advance. A: @IGNIS, it should just work! Using RefineryCMS -- I have an extension at vendor/extensions/notices. In there is a partial app/views/custom/_displayLatestNotices.html.erb like: <ul id="notices"> <% Refinery::Notices::Notice.each do |notice| %> <li><h3><%= notice.title %></h3> <p><%= notice.body %></p> </li> <% end %> </ul> And I can show that from the main site code like: <% content_for :body do %> <%= render( :partial => "custom/displayLatestNotices" ) %> <% end %> So, in your generated form extension for "widget" you will probably have something like: app/views/refinery/widgets/widgets/new.html.erb. I would refactor that into two files, with the form itself in: app/views/refinery/widgets/widgets/_new_widget_form.html.erb. In your new.html.erb you probably want to include this form partial -- and you should be able to include it elsewhere via: <%= render( :partial => "refinery/widgets/widgets/_new_widget_form" ) %> or possibly even just: <%= render( :partial => "_new_widget_form" ) %>
{ "pile_set_name": "StackExchange" }
Q: Using PowerShell's New-WebServiceProxy to access a net.tcp endpoint I am trying to access a net.tcp endpoint from powershell. I would like to use New-WebServiceProxy for that purpose, however I am not sure if it can be done. Right now I get a + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShell.Commands.NewWebServiceProxy when pointing it at the wsdl (which I have heavly hand written, so it could be that...) A: You simply cannot do this. New-WebServiceProxy is not a WCF proxy, its a http soap proxy. You could probably use a combination of svcutil.exe and Add-Type to generate the proxy on the fly on machines that have svcutil.exe installed. A more complex example in C# that you might be able to translate to powershell is available here. A: Apparently you have been able to do this since December 22nd 2008. Christian Glessner wrote a WCF Proxy generator. The original blog post in which he described it is here. He also posted the script in this PoshCode.org post. I updated the code to Powershell v2. I'd suggest using that version. I talk about my version on this blog post. If you use that code, dotsource it from another script, don't include it inline. Here is an example using my version of the code: # My example WCF service: # https://github.com/justaprogrammer/EchoService . .\wcf.ps1 $wsdlImporter = Get-WsdlImporter 'http://localhost.fiddler:14232/EchoService.svc/mex' Get-WsdlImporter 'http://localhost.fiddler:14232/EchoService.svc' -HttpGet Get-WsdlImporter 'http://localhost.fiddler:14232/EchoService.svc?wsdl' -HttpGet $proxyType = Get-WcfProxyType $wsdlImporter $endpoints = $wsdlImporter.ImportAllEndpoints(); $proxy = New-Object $proxyType($endpoints[0].Binding, $endpoints[0].Address); $proxy = Get-WcfProxy 'http://localhost.fiddler:14232/EchoService.svc/mex' $proxy.Echo("Justin Dearing"); Get-Help Get-WsdlImporter Get-Help Get-WcfProxyType Get-Help Get-WcfProxy
{ "pile_set_name": "StackExchange" }
Q: Draggable jquery function inside div positions I am using a Jquery a script to drag images (currently only one image) around inside a div. I am currently using this code: var offset = 0, xPos = 0, yPos = 0; $(document).ready(function(){ $(".item").draggable({ containment: '#house_wall1', drag: function(){ offset = $(this).position(); xPos = offset.left; yPos = offset.top; $('#posX').text('x: ' + xPos); $('#posY').text('y: ' + yPos); }, // Find original position of dragged image. start: function(event, ui) { // Show start dragged position of image. var Startpos = $(this).position(); $("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top); }, // Find position where image is dropped. stop: function(event, ui) { // Show dropped position. var Stoppos = $(this).position(); $("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top); } }); }); My problem is not that the draggable images is not inside the div, my problem is that the positions x and y is calculated from the screen sizes and not the div. That means if you resize the screen or have a lower screen resolution, the images will in fact hold a different x and y position than a person with another resolution. How can I change the image positions to track x and y from the div margins instead of the screens size. Thanks in advance. A: Use position() instead of offset(). position() gives you the top/left w.r.t. to the element's parent element instead of the document top/left. offset = $(this).position();
{ "pile_set_name": "StackExchange" }
Q: Correct way to target and style specific child elements in Material-ui wrapper components? What is the correct/suggested way to target and style specific child elements in Material-ui wrapper components using makeStyles()? Do we use the class selectors? e.g. Targeting the input element of a TextField component I use & .MuiInput-input import { makeStyles} from '@material-ui/core/styles'; const useStyles = makeStyles(theme => ({ foo: { '& .MuiInput-input': { backgroundColor: 'red' } } }); export default function () { const classes = usePageStyles(); return (<div> <TextField id="search" label="Search" placeholder="Search" className={classes.x} /> </div>); }; I know that there are a lot of methods to style components in Material-UI, which is why I am a bit confused which is which. So, I just want to know the standard way to target the child elements. I saw examples in the docs using '& p' - does that mean that there is no Material-UI specific way? We just use basic css selectors? A: I'd suggest passing in InputProps with an object to the TextField. Something like: const InputProps = { className: classes.input, color: 'primary' } Then pass it into TextField: <TextField InputProps={InputProps} >
{ "pile_set_name": "StackExchange" }
Q: Download image by Python CGI I have a Python cgi that converts a svg to a png file, I'd like then to download the converted output to the user's disk. #the conversion stuff print "Content-Type: image/png" print "Content-Disposition: attachment; filename='pythonchart.png'" print print open("http:\\localhost\myproj\pythonchart.png").read() This results in a png file containing ‰PNG. Any help please? A: You are reading binary data from the text-mode stream returned by open(), and writing binary data to the text-mode stdout stream. You must open the file in binary mode, and convert the stdout to binary mode. import sys print "Content-Type: image/png" print "Content-Disposition: attachment; filename='pythonchart.png'" print if sys.platform == "win32": import os, msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) print open("C:\\wamp\\www\\myproj\\pythonchart.png", "rb").read() Ref: Python 2.x - Write binary output to stdout?
{ "pile_set_name": "StackExchange" }
Q: Why do no browsers apart from Firefox support animated PNGs? When I look into the list (http://caniuse.com/apng) of supported browser on animated PNG, I found that basically only Firefox support it. All the other major browsers don't support. Even the Opera which they once support it and they drop it on newer release. I always thinking animated PNG is nice. But why is most browsers don't support it? What is the reason they not support? A: Google developers discussed it here: https://groups.google.com/a/chromium.org/forum/#!msg/chromium-dev/2xvXNJMsgxc/2CJ9jl-jItcJ
{ "pile_set_name": "StackExchange" }
Q: subquery Count() - Column must appear in the GROUP BY clause I just wanted to know, why a subquery returned more than one value, so I made this query: SELECT id, (SELECT Count(tags[i]) FROM generate_subscripts(tags, 1) AS i WHERE tags[i]='oneway') as oneway_string FROM planet_osm_ways WHERE 'oneway' = ANY(tags) HAVING (SELECT Count(tags[i]) FROM generate_subscripts(tags, 1) AS i WHERE tags[i]='oneway') > 1 which should find all occurences of 'oneway' in tags array and count them. [42803] ERROR: column "planet_osm_ways.id" must appear in the GROUP BY clause or be used in an aggregate function Position: 8 A: You should change HAVING to WHERE as there are no groups on which you could apply HAVING filter, instead you want to use WHERE filter which applies to each row. SELECT id, (SELECT Count(tags[i]) FROM generate_subscripts(tags, 1) AS i WHERE tags[i]='oneway') as oneway_string FROM planet_osm_ways WHERE 'oneway' = ANY(tags) AND (SELECT Count(tags[i]) FROM generate_subscripts(tags, 1) AS i WHERE tags[i]='oneway') > 1
{ "pile_set_name": "StackExchange" }
Q: XText programmatically parse a DSL script into an Ecore model I need to programmatically turn a text conform to an XText grammar into an AST conform to an Ecore meta-model generated by XText from the same grammar. I know XText also generate the Java classes implementing such parser but I don't know either where they are and how to use it. A: A complete answer to this question can be found on the Xtext page of the Eclipse wiki. new org.eclipse.emf.mwe.utils.StandaloneSetup().setPlatformUri("../"); Injector injector = new MyDslStandaloneSetup().createInjectorAndDoEMFRegistration(); XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class); resourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE); Resource resource = resourceSet.createResource(URI.createURI("dummy:/example.mydsl")); InputStream in = new ByteArrayInputStream("type foo type bar".getBytes()); resource.load(in, resourceSet.getLoadOptions()); Model model = (Model) resource.getContents().get(0); Change the file extension (mydsl) to your own language extension. A: Here's the code: @Inject ParseHelper<Domainmodel> parser def void parseDomainmodel() { // When in a vanilla Java application (i.e. not within Eclipse), // you need to run a global setup: val injector = new MyDslStandaloneSetup().createInjectorAndDoEMFRegistration injector.injectMembers(this) // sets the field 'parser' // this is how you can use it: val model = parser.parse( "entity MyEntity { parent: MyEntity }") val entity = model.elements.head as Entity assertSame(entity, entity.features.head.type) } See also http://www.eclipse.org/Xtext/documentation.html#TutorialUnitTests.
{ "pile_set_name": "StackExchange" }
Q: Add trend lines to some plots I am new to ggplot2 but decided to learn it because I like its simplicity and visuals. I have a time-series (zoo) with rainfall for several cities. Looking at other questions I found out how to reshape it and plot it: df <- data.frame(time = time(rain.yr), city = rep(colnames(rain.yr), each = nrow(rain.yr)), value = as.vector(rain.yr)) ggplot(df, aes(x=time, y=value)) + geom_line() + facet_wrap( ~ city, ncol=4) I really like the end result in terms of visuals, as it gives one plot per city but with global axes. And I found out how to add trends: stat_smooth(method="lm") The problem is that I want to add trend lines to some of the plots, not all of them; just the ones where a trend is significant (I have a vector with zeros and ones for sig/non-sig). I know how to do it with base graphics (using par and a loop to plot and only adding a line if the trend is significant) but is there a way of doing it in ggplot2? A: As as been suggested, just create a dataframe of the subset you want for smoothing and use that as the data for stat_smooth(). subdf<-diamonds[which(diamonds$clarity %in% c('SI2','SI1')),] ggplot(diamonds,aes(x=carat,y=depth))+geom_point() + facet_wrap(~clarity) + geom_smooth(data=subdf)
{ "pile_set_name": "StackExchange" }
Q: operator<< overload in C++ for a class in class i have the following classes: class mypipe { class node { public: char ch; node* next; node(){...} node(char c){..} } ; public: unsigned int size; node* head; and i need to overload the operator<<, to print the mypipe as it is now. then, i'm trying to write the following: friend ostream& operator<< (ostream& stream, mypipe p) { node* curr = p.head -> next; ... immediately after the variables definition. the problem is that i get an error "identifier node is undefined". i've tried to declare the operator and implement it outside of the class, that didn't help. does anyone have any ideas about it? thanks in advance for anyone who can help :) A: node is an inner class, which means you have to qualify its type: mypipe::node* curr = p.head -> next;
{ "pile_set_name": "StackExchange" }
Q: Problems with subtraction of a float number This program have to count minimum number of coins, but it has some kind of bug because results are weird. It`s probably obvious mistake but I cant find it. int main(int argc,char* argv[]){ float x; printf("How much cash in float number:"); scanf("%f", &x); int quaters; while(x>=0.25){ x-=0.25; quaters++; } printf("%f\n",x); int fives; while (x>=0.05){ x-=0.05; fives++; } printf("%f\n",x); int one; while (x>=0.01){ x-=0.01; one++; } printf("%f\n",x); printf("quaters %d\t fives %d\t ones %d\n", quaters, fives, one); return 0; } And the output is this How much cash in float number:0.41 0.160000 0.010000 0.010000 quaters 1 fives 3 ones 32764 What`s wrong? A: You need to initialize quaters, fives and one to 0 before using it: int quaters=0; .... int fives=0; .... int one=0; .... Regarding the last 0.01 result, google for "comparing float variables C++". Even here in SO you will find plenty of related posts. For immediate solution, since you use up to 2 digits after the decimal point, change float compare from x>=0.25 to x>0.249 And all the others accordingly: x>0.049 x>0.009
{ "pile_set_name": "StackExchange" }
Q: How to find the rows from a table which has exactly two 'n' s in the employee name? I want to find all the employees whose names have exactly two n's in their name. How can this be done? A: something like this should be enough: select * from employee_table where Length(lastname) - length(replace(lastname, 'n','')) = 2 be aware that may cause a full table scan :-)
{ "pile_set_name": "StackExchange" }
Q: MVC - Ajax - Inconsistency between Chrome and IE 9 I have an MVC view where I am doing some paging of data, using the PagedList component. My JavaScript to support this looks as follows: $(function () { var getPage = function () { var $a = $(this); var options = { url: $a.attr("href"), type: "get" }; $.ajax(options).done(function (data) { var target = $a.parents("div.pagedList").attr("data-ExchangeSite-target"); data: $("form").serialize(), $(target).replaceWith(data); }); return false; }; $(".main-content").on("click", ".pagedList a", getPage); }); My .cshtml file looks, in part, like this: @model ExchangeSite.Entities.BicycleSearchSeller <div id="itemList"> <div class="pagedList" data-ExchangeSite-target="#itemList"> @Html.PagedListPager(Model.BicycleSellerListingList, pageNumber => Url.Action("Index", new {pageNumber}), PagedListRenderOptions.ClassicPlusFirstAndLast) </div> ... ... In IE9, this works perfectly. When I click on a specific page number, or the next/previous page, an asynch call is made to my controller to refresh the list of data ("itemList"). However, in Chrome, two calls are made to my controller. One is an Ajax call, the other is not. Can anyone tell me why, in Chrome, two calls are made to my controller? If you need to see more code, please let me know. A: There seems to be some buggy line in your success callback: data: $("form").serialize(), It is terminated with a comma instead of semicolon. It also contains a colon after data. IE might be a little more tolerant towards broken javascript compared with Google Chrome.
{ "pile_set_name": "StackExchange" }
Q: How to arrange image divs in rows of 3? Hi all i got many divs that has class names such as ItemLeft,ItemMiddle and ItemRight. I wonder how i can display these image divs 3 in a row using css or any easy method(currently all the images display one below each other) ? i get the image divs from getjson call as follows: $.getJSON('http://www.awebsite.com/get?url=http://www.bwebsite.com/moreclips.php&callback=?', function(data){ //$('#output').html(data.contents); var siteContents = data.contents; document.getElementById("myDiv").innerHTML=siteContents Note: each time i call the getjson i get 6 image divs back that shows all below each other instead of 3 in a row! and this the div images retrieved by making getjson call, but all these image divs below each other not 3 in rows: <div class="ItemLeft"> <div class="Clipping"> <a class="ImageLink" href="/videos/id1234" title="galaxy"> <img class="ItemImage" src="/Images/galaxyimg.jpg" alt="galaxy" /> <img class="OverlayIcon" src="/Images/1.png" alt="" /> </a> <a class="DurationInfo" onmouseover="showDuration2(this);" onmouseout="hideDuration2(this);" href="/videos/id1234"><span class="Text">51:57</span></a> </div> <div class="Title"><a href="/videos/id1234" title="galaxy">galaxy</a></div> <div class="VideoAge">1 daybefore</div> <div class="PlaysInfo"> broadcast 265</div> </div> A: Based on your question i have duplicated your leftItem to create multiple items and added a fiddle here http://jsfiddle.net/tVMet/ Provide float for your divs and end of the third just give a div clearing the float. <div class="clear" /> .ItemLeft, .ItemMiddle, .ItemRight { float:left; } .clear { clear:both; }
{ "pile_set_name": "StackExchange" }
Q: Cómo colocar y configurar BottomNavigationView en un Fragment estoy colocando un Menu Bottom en un fragment, antes lo tenía configurado en un CordinatorLayout y generaba todo el código desde el MainActivity, pero ahora lo quiero colocar en un fragment y que desde ahi escuche los eventos, lo que necesito es saber como declararlo en el Fragment. A continuación muestro el código xml y el Fragment, tambien les muestro el código que usaba antes en el MainActivity para que me ayuden a pasarlo al Fragmento, muchas gracias. XML <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#eddd76" xmlns:app="http://schemas.android.com/apk/res-auto" tools:context="com.tecnologias.uniagustapp.fragmentos.Fragment_Home"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginBottom="58dp" android:background="#eddd76"> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" app:srcCompat="@drawable/main03" tools:ignore="ContentDescription" /> </LinearLayout> <android.support.design.widget.BottomNavigationView android:id="@+id/navigation" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_gravity="bottom" android:background="#202240" app:menu="@menu/navigation" /> Fragment public class Fragment_Home extends Fragment { public Fragment_Home() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment__home, container, false); return v; } } A continuación el código que antes usaba en el MainActivity private BottomNavigationView bottomNavigationView; //BOTTON NAVIGATION VIEW final Fragment home = new Home(); final Fragment noticias = new Noticias(); final Fragment calendario = new Calendario(); final Fragment ubicacion = new Map_Fragment(); final Fragment pqrs = new PQRS(); final Fragment preinscrip = new PreInscripcion(); bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation); bottomNavigationView.setItemIconTintList(null);//Los iconos del menu Bottom toman su color original bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { FragmentManager fragmentManager = getFragmentManager(); if (item.getItemId() == R.id.noticias) { //FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); //fragmentTransaction.replace(R.id.content_main, noticias).commit(); } else if (item.getItemId() == R.id.rutas) { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.content_main, ubicacion).commit(); } else if (item.getItemId() == R.id.cal_aca) { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.content_main, calendario).commit(); } else if (item.getItemId() == R.id.pqrs) { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.content_main, pqrs).commit(); } else if (item.getItemId() == R.id.preinscripcion) { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.content_main, preinscrip).commit(); } return true; } });//* A: Puedes hacerlo en el onViewCreated, si declaras en el onCreateView el view como global. Ejemplo: private View root; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment root = inflater.inflate(R.layout.fragment__home, container, false); return root; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ... bottomNavigationView = (BottomNavigationViewEx) root.findViewById(R.id.navigation); ... // El resto de tu implementación. } Si ya lo has intentado y tienes errores, ¿cuales son?
{ "pile_set_name": "StackExchange" }
Q: Handling checkbox event in option menu : Android I have a menu that has checkbox menu item type and whenever i check it. It doesn't trigger anything. Here is my menu.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/delete" android:actionViewClass="android.widget.CheckBox" android:checkableBehavior="single" android:title="All" android:titleCondensed="All" app:showAsAction="ifRoom"></item> </menu> Here is my onOptionsItemSelected @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.delete: Toast.makeText(this,"Hello",Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } } Any idea? A: You can handle CheckBox click inside onCreateOptionsMenu by listen setOnCheckedChangeListener like this @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); CheckBox checkBox = (CheckBox) menu.findItem(R.id.delete).getActionView(); checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { // perform logic } } }); return true; } And remember change android:actionViewClass="android.widget.CheckBox" to app:actionViewClass="android.widget.CheckBox"
{ "pile_set_name": "StackExchange" }
Q: How to return an object variable from a function? The value in some variables are being overlapped. When I loop the first time on a node everything works fine but when I loop again, the values from the last variable created are printed and sometimes the program stops working. #include "pugixml.hpp" #include "pugixml.cpp" pugi::xml_node varnodes = getNodesXML(varsFilepath); for (pugi::xml_node node = varnodes.first_child(); node; node = node.next_sibling()){ printf("%s: %s\n", node.name(), node.attribute("id").value()); } pugi::xml_node blocknodes = getNodesXML(blocksFile); for (pugi::xml_node node = blocknodes.first_child(); node; node = node.next_sibling()){ printf("%s: %s\n", node.name(), node.attribute("id").value()); //varnodes.append_copy(node); } pugi::xml_node funcnodes = getNodesXML(functionsFile); for (pugi::xml_node node = funcnodes.first_child(); node; node = node.next_sibling()){ printf("%s: %s\n", node.name(), node.attribute("id").value()); //varnodes.append_copy(node); } //looping on varnodes after other nodes have been created (the program crash and this is not displayed) for (pugi::xml_node node = varnodes.first_child(); node; node = node.next_sibling()) printf("%s: %s\n", node.name(), node.attribute("id").value()); for (pugi::xml_node node = blocknodes.first_child(); node; node = node.next_sibling()) printf("%s: %s\n", node.name(), node.attribute("id").value()); for (pugi::xml_node node = funcnodes.first_child(); node; node = node.next_sibling()) printf("%s: %s\n", node.name(), node.attribute("id").value()); This is how I get the nodes from different files: pugi::xml_node getNodesXML(char *filepath){ printf("%s\n",filepath); pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(filepath); if(!result) printf("Error reading file: %s\n%s\n", filepath, result.description()); pugi::xml_node nodes = doc.child("nodes"); if(!nodes) printf("Error finding root <nodes> in: \n%s\n", filepath); return nodes; } The xml is something like this: varnodes.xml <nodes><node id="firstvar"></node></nodes> blocknodes.xml <nodes><node id="firstblock"></node></nodes> funcnodes.xml <nodes><node id="firstfunc"></node></nodes> //Expected output: node: firstvar node: firstblock node: firstfunc node: firstvar node: firstblock node: firstfunc //Wrong output Im getting (sometimes the program just stops working): node: firstvar node: firstblock node: firstfunc node: firstfunc node: firstfunc node: firstfunc Error: Unhandled exception at 0x00eb0cdd in practice.exe: 0xC0000005: Access violation reading location 0xfeeeff0a. main.exe has stopped working and points me to this function: PUGI__FN xml_attribute xml_node::attribute(const char_t* name_) const { if (!_root) return xml_attribute(); > for (xml_attribute_struct* i = _root->first_attribute; i; i = i->next_attribute) if (i->name && impl::strequal(name_, i->name)) return xml_attribute(i); return xml_attribute(); } When I add the code from the function to main.cpp the variables values print perfectly (I think there is something wrong in the way I return a value from getNodesXML() ) A: I think I solved it: In the function I create an object of type pugi::xml_document which is local, if I create the doc object as a pointer everything works correctly but I guess I'll have a memory leak so probably I need another function that returns that object to delete later or create a global variable to store it.
{ "pile_set_name": "StackExchange" }
Q: Does mremap work with malloc? Is void * mremap(void *old_address, size_t old_size , size_t new_size, unsigned long flags); compatible with malloc()? GCC (C++) and using Linux. Thanks. A: No, it is not. Apart from the fact that malloc doesn't need to give you an address at a page border (which is what mremap expects), it would be dangerous to mess with memory mappings from malloc without malloc knowing you did it. Use realloc instead.
{ "pile_set_name": "StackExchange" }
Q: How to disable caching using XrmDataContext in Dynamics CRM 4.0? We are using the Advanced Developer Extension against Dynamics CRM 4.0. We have generated the entities and the Xrm context using CrmSvcUtil. What we need to do is disable the built in caching that the context uses as it is returning incorrect results, but I've been unable to find out how to do this - any ideas ? Thanks Matt A: Take a look at these links http://arens.ws/wordpress/?p=54 http://community.adxstudio.com/Default.aspx?DN=d589dc6c-b2bf-4ae1-a8ca-06ac55f2a177&topic=40f3987f-9600-4a75-84f8-1dcffcfbd875&page=1 http://msdn.microsoft.com/en-us/library/gg398020.aspx
{ "pile_set_name": "StackExchange" }
Q: Handle — while import csv file using C# I had written code (in C#) about to import csv file using filehelper. I am facing one issue that if file contain any &mdash (—) than it would replace by ? character (not exact ? instead some special character as per shown in below image) How can i handle this by code? Thanks. A: How your stream reader object is created ? Have you provided any specific encoding to it ? I think you should try if not yet, as default encoding can not be detected while there is no BOM defined. From MSDN The character encoding is set by the encoding parameter, and the buffer size is set to 1024 bytes. The StreamReader object attempts to detect the encoding by looking at the first three bytes of the stream. It automatically recognizes UTF-8, little-endian Unicode, and big-endian Unicode text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the Encoding.GetPreamble method for more information.
{ "pile_set_name": "StackExchange" }
Q: How do I find the Recaptcha ID? I've been stuck on something for the past day. I'm building a RoR bot, and part of it involves signing up for an email account with mail.com. I've automated all the filling out of the form, apart from the captcha (Recaptcha). I'll be using the deathbycaptcha Ruby gem. However, in order to have the captcha solved, I'll need to get either its ID or its URL. While this shows up when I "enable form details" with the Firefox Web Developer toolbar, it doesn't seem to be in the source. How can I find it out? I'm using Watir. Thanks! Joe http://service.mail.com/registration.html A: The recaptcha challenge id is the code that comes after the k in the recaptcha URL. They just ran it through a function rather than just displaying it in the source. Their site key is 6LdKsrwSAAAAAHjmh-jQNZ7zskPDs1gsY-WNXAKK
{ "pile_set_name": "StackExchange" }
Q: Get all Woocommerce products from current product category term Id in a WP_Query I have a simple taxonomy-product_cat.php page, where I am trying to display only the products in the current category. Right now, it's displaying all products, not just the ones in the current category. Here is my code: <ul class="products"> <?php $current_cat_id = $wp_query->get_queried_object()->term_id; $args = array( 'taxonomy' => 'product_cat', 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => -1, 'tax_query' => array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $current_cat_id, 'operator' => 'IN' ) ); $products = new WP_Query( $args ); while ( $products->have_posts() ) : $products->the_post(); echo '<li><a href="'. get_permalink() .'"><div class="product__preview"><img src="' . get_the_post_thumbnail_url() . '"></div><span>' . get_the_title() . '</span></a></li>'; endwhile; wp_reset_query(); ?> </ul> My client keeps changing the names/slugs of the category, so I need to get the products by category ID. Any idea why this is generating all products, instead of just the ones in the current category? A: Update 2 The tax query need to have 2 arrays embedded in each other: 'tax_query' => array( array( Removed the first unneeded 'taxonomy' => 'product_cat', Replaced 'terms' => $current_cat_id, by 'terms' => array( get_queried_object()->term_id ), Replaced wp_reset_query(); by wp_reset_postdata(); Your code will be: $query = new WP_Query( array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => array( get_queried_object()->term_id ), ) ) ) ); while ( $query->have_posts() ) : $query->the_post(); echo '<li><a href="'. get_permalink() .'"><div class="product__preview"><img src="' . get_the_post_thumbnail_url() . '"></div><span>' . get_the_title() . '</span></a></li>'; endwhile; wp_reset_postdata(); Tested and works
{ "pile_set_name": "StackExchange" }
Q: How to schedule a task at fixed rate with a duration longer than the rate? I'm trying to schedule a task that requires ~2.25 sec to be run every second.Thus I know 3 threads should be enough to handle the load. My code looks like this: private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(4); scheduler.scheduleAtFixedRate(new Streamer(), 0, 1000, TimeUnit.MILLISECONDS); interestingly this behaves like scheduledAtFixedDelay with a delay of 0 (threads finish every ~2.25 sec). I know, that scheduleAtFixedRate can be late if a thread runs late. But shouldn't giving the executor a larger threadpool solve this problem? I could easily circumnvent the problem by coding 3 executors to start every 3 seconds, but that would make administration unnecessarily difficult. Is there an easier solution to this problem? A: You can use threadPool and scheduler to achieve this effect: Create a fixedThreadPool (or other that will fullfill your needs), let say with 4 threads - the number of threads should be based on the time single task consumes to execute and the rate at which the tasks are scheduled, basically numberOfThreads = avgExecTimeOfSingleTaks * frequency + someMargin; then create scheduler thread, that every second (or other desired period) will add a job to the fixedThreadPool queue, then the tasks can overlap. This way of solving the problem has additional adventage: If your tasks start to take longer than 2.25 sec, or you would like to execute them with greater frequency, then all you have to do is to add some threads to the threadPool, whereas using the other answer, you need to recalculate and reschedule everything. So this approch gives you clearer and easier to maintenance approach.
{ "pile_set_name": "StackExchange" }
Q: Discord.py Give role when reacting to a message I can't get this code to work, posting the reacted message is no problem. But giving the user who reacts the "Beta" role doesn't work. Discord.py version: 0.16.12 @bot.command(pass_context=True) async def test(ctx): if ctx.message.author.server_permissions.administrator: testEmbed = discord.Embed(color = discord.Color.red()) testEmbed.set_author(name='Test') testEmbed.add_field(name='Test', value='Test') msg = await bot.send_message(ctx.message.channel, embed=testEmbed) await bot.add_reaction(msg, emoji='✅') @bot.event async def on_reaction_add(reaction, user): Channel = bot.get_channel('714282896780951563') if reaction.message.channel.id != Channel: return if reaction.emoji == "✅": Role = discord.utils.get(user.server.roles, name="Beta") await bot.add_roles(user, Role) A: reaction.message.channel.id != Channel will never be True because Channel is a discord.Channel object and reaction.message.channel.id is an string. Instead, you should just compare the id to the expected id directly: if reaction.message.channel.id != '714282896780951563':
{ "pile_set_name": "StackExchange" }
Q: CSS animation in reverse I have the following CSS: @keyframes divFadeIn { 0%{opacity:0; transform: scale(0.5)} 100%{opacity:1; transform: scale(1)} } .overlay { position: relative; top: -$headerHeight; z-index: 1000; height: 100%; animation: divFadeIn 0.3s 1 ease-out; } This affects the DIV when I click a button it animates from the center to 100% width. However, how do I get it so that it animates backwards when I click another button?? So I click first button - animates to 100% I click another button - animates the opposite way to 0% A: For your problem, you can create another keyframes divFadeOut with opposite values with divFadeIn (animates the opposite way to 0%) and create a class fadeOut with content: .fadeOut { animation: divFadeOut 0.3s 1 ease-out; } Remove animation from class overlay and add to class fadeIn: .fadeIn { animation: divFadeIn 0.3s 1 ease-out; } When you click button, you can remove or add one of above animations to DIV with following code. In case, i use jQuery implement: $('#button1').click(function() { $('.overlay').addClass('fadeIn'); }); $('#button2').click(function() { $('.overlay').removeClass('fadeIn'); $('.overlay').addClass('fadeOut'); });
{ "pile_set_name": "StackExchange" }
Q: I need help understanding Identity in sql IDENTITY [ (seed , increment) ] What does seed do? I can't seem to find the answer on google. A: The seed param is the value that is used for the very first row loaded into the table.Think of seed as the starting value, and increment as the amount to go up by.The default val for seed an increment is (1,1) resulting in identities of 1,2,3,... If you specified (5,1) you would get identities 5,6,7,... Source: https://msdn.microsoft.com/en-us/library/ms186775.aspx
{ "pile_set_name": "StackExchange" }
Q: Javascript: Split a string into array matching parameters I have a string that has numbers and math operators (+,x,-, /) mixed in it '12+345x6/789' I need to convert it into an array seperated by those math operators. [12, +, 345, x, 6, /, 789] What is a simple way of doing this? A: Splitting on consecutive non-digit chars \D+ you get console.log ('12+345x6/789'.split (/\D+/)) // [ '12', '345', '6', '789' ] If you add a capture group, (\D+) you get the separator too console.log ('12+345x6/789'.split (/(\D+)/)) // [ "12", "+", "345", "x", "6", "/", "789" ] If you want to support parsing decimals, change the regexp to /([^0-9.]+)/ - Note, \D used above is equivalent to [^0-9], so all we're doing here is adding . to the character class console.log ('12+3.4x5'.split (/([^0-9.]+)/)) // [ "12", "+", "3.4", "x", "5" ] And a possible way to write the rest of your program const cont = x => k => k (x) const infix = f => x => cont (f (x)) const apply = x => f => cont (f (x)) const identity = x => x const empty = Symbol () const evaluate = ([ token = empty, ...rest], then = cont (identity)) => { if (token === empty) { return then } else { switch (token) { case "+": return evaluate (rest, then (infix (x => y => x + y))) case "x": return evaluate (rest, then (infix (x => y => x * y))) case "/": return evaluate (rest, then (infix (x => y => x / y >> 0))) default: return evaluate (rest, then (apply (Number (token)))) } } } const parse = program => program.split (/(\D+)/) const exec = program => evaluate (parse (program)) (console.log) exec ('') // 0 exec ('1') // 1 exec ('1+2') // 3 exec ('1+2+3') // 6 exec ('1+2+3x4') // 24 exec ('1+2+3x4/2') // 12 exec ('12+345x6/789') // 2
{ "pile_set_name": "StackExchange" }
Q: JSOM Script Returning serverRelativeUrlOrFullUrl Error from SP.ClientContext.get_current() I'm attempting to build a script for a Sharepoint 2013 project management hub that eases the process of spinning up and archiving project subsites as they are needed. I'm having trouble getting my archival script to work and very frustrated with the error I'm receiving. I'm storing the javascript file in a library on the top level site so that I can reference the file in the template that the project subsites will be created from. The idea is that a user on a project subsite will be able to execute the script and do a couple of housekeeping actions. The script file is referenced via a Script Editor web part on a page in the subsite. The first step is to retrieve the current subsite context for things like the subsite title and the subsite url. To make the script usable for all subsites I'm doing this via: var subsiteCtx = new SP.ClientContext.get_current(); var subWeb = subsiteCtx.get_web(); subsiteCtx.load(subWeb); subsiteCtx.executeQueryAsync( *callbackfunction*,*callbackfunction*) When I execute this code I'm receiving: Error: Sys.ArgumentException: Value does not fall within the expected range. Parameter name: serverRelativeUrlOrFullUrl I originally thought this was because I'm executing a script from a file hosted on the top level site but the error persists whether I host the script file on the subsite or paste the code directly in to the script editor web part. When I run the exact same code manually in the browser console I get the desired behavior. What the heck is going on? A: Turns out I was misreading my debugger and should have been troubleshooting a nested function that had a typo in it. Such a dumb problem. Thank you for the suggestions regardless.
{ "pile_set_name": "StackExchange" }
Q: Cant find Pygame Module I just started game developing in python with pygame and I have the following code: bif="main_background.jpg" mif="player_head.png" import pygame, sys from pygame.locals import * pygame.init() screen=pygame.display.set_mode((640,360),0,64) background=pygame.image.load(bif).convert() mouse_c=pygame.image.load(mif).convert_alpha() while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() screen.blit(background, (0,0)) x,y = pygame.mouse.get_pos() x -= mouse_c.get_width()/2 y -= mouse_c.get_height()/2 screen.blir(mouse_c,(x,y)) pygame.display.update() I get the following error in Python: Traceback (most recent call last): File "C:/Users/Eier/Documents/Code Developments/pygame.py", line 4, in <module> import pygame, sys File "C:/Users/Eier/Documents/Code Developments\pygame.py", line 5, in <module> from pygame.locals import * ImportError: No module named locals >>> If someone knows how to make python find pygame please reply. Thank you :) A: I'm about 83.4% sure that you named your script pygame.py (or possibly created another file with the same name in the same directory as your script). If you do that, Python has no way of knowing what you want to load when you import pygame. It could be your script, it could be the installed package—they both have the same name. What ends up happening is that import pygame imports your script, then from pygame.locals import * looks for a module called locals inside your script. Since your script is a script, and not a package, Python just gets confused and prints a confusing ImportError. Python 3.x gives you some ways around this, but 2.x does not, and I'm guessing you're using 2.x. So, the solution is: Rename your script to mygame.py. Delete any other files in the same directory as your script named pygame.py.
{ "pile_set_name": "StackExchange" }
Q: Oracle identity column and insert into select Oracle 12 introduced nice feature (which should have been there long ago btw!) - identity columns. So here's a script: CREATE TABLE test ( a INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, b VARCHAR2(10) ); -- Ok INSERT INTO test (b) VALUES ('x'); -- Ok INSERT INTO test (b) SELECT 'y' FROM dual; -- Fails INSERT INTO test (b) SELECT 'z' FROM dual UNION ALL SELECT 'zz' FROM DUAL; First two inserts run without issues providing values for 'a' of 1 and 2. But the third one fails with ORA-01400: cannot insert NULL into ("DEV"."TEST"."A"). Why did this happen? A bug? Nothing like this is mentioned in the documentation part about identity column restrictions. Or am I just doing something wrong? A: I believe the below query works, i havent tested! INSERT INTO Test (b) SELECT * FROM ( SELECT 'z' FROM dual UNION ALL SELECT 'zz' FROM dual ); Not sure, if it helps you any way. For, GENERATED ALWAYS AS IDENTITY Oracle internally uses a Sequence only. And the options on general Sequence applies on this as well. NEXTVAL is used to fetch the next available sequence, and obviously it is a pseudocolumn. The below is from Oracle You cannot use CURRVAL and NEXTVAL in the following constructs: A subquery in a DELETE, SELECT, or UPDATE statement A query of a view or of a materialized view A SELECT statement with the DISTINCT operator A SELECT statement with a GROUP BY clause or ORDER BY clause A SELECT statement that is combined with another SELECT statement with the UNION, INTERSECT, or MINUS set operator The WHERE clause of a SELECT statement DEFAULT value of a column in a CREATE TABLE or ALTER TABLE statement The condition of a CHECK constraint The subquery and SET operations rule above should answer your Question. And for the reason for NULL, when pseudocolumn(eg. NEXTVAL) is used with a SET operation or any other rules mentioned above, the output is NULL, as Oracle couldnt extract them in effect with combining multiple selects. Let us see the below query, select rownum from dual union all select rownum from dual the result is ROWNUM 1 1
{ "pile_set_name": "StackExchange" }
Q: How to change a digit in string to integer rather than its ASCII code? Question : Write a program in a C++ to display the sum of digits present in a text file. --> #include<iostream.h> #include<fstream.h> int main() { ifstream f1("Fees.txt"); int sum=0; char n; while(f1.eof()==0) { f1>>n; if(isdigit(n)) { sum=sum+n; } } cout<<sum; } I know the program's not working because string is changed to digit,( 1 changes to its ASCII code 49 instead of 1) Please guide me And is there a better way to approach the question? UPDATE Ok so I changed the line sum+=n to sum+=n-'0'. Still the program only seems to be working when there is a special character in addition to numbers in the text file Fees.txt. Example: 1 2 9 This does not work 1 2 9ok This does work, any idea what's going on here? A: As you point out, the ASCII codes for digits do not start at zero, which is your problem. Luckily though, they do lie in a continuous range, so all you need to do is change the line: sum=sum+n; to sum += (n - '0');
{ "pile_set_name": "StackExchange" }
Q: Where do my iPod's notes go when they're synchronized with my Gmail account? Where do my iPod's notes go when they're synchronized with my Gmail account? Where can I find them in my browser? A: When you go to Gmail, you should now see a 'notes' label in gmail. This will hold your notes, but you can not edit them in gmail.
{ "pile_set_name": "StackExchange" }
Q: Implicit coercion for objects I am having troubles with implicit coercion with the + operator in JavaScript. Namely the priority order of valueOf and toString. var obj = {}; obj.toString(); => "[object Object]" obj.valueOf(); => Object {} 'Hello ' + obj; => "Hello [object Object]" So obj is implicitly coerced to a string using the toString() method over valueOf(); var obj2 = { toString: function() { return "[object MyObject]"; }, valueOf: function() { return 17; } }; obj2.toString(); => "[object MyObject]" obj2.valueOf(); => 17 'Hello ' + obj2; => "Hello 17" So when I override the toString and valueOf methods, the + operator will coerce with valueOf. What am I missing? Thanks. A: The answer can be found in a similar thread: valueOf() vs. toString() in Javascript If the object can be transformed into a "primitive" JavaScript will try to treat it as a number. Otherwise string concatenation via the toString method is used. Without the valueOf method, JavaScript cannot tell how to convert the data, hence the object will be concatenated as a string. If you're interested the precise specifications are available in the following pdf at around page 58: http://www.webreference.com/javascript/reference/ECMA-262/E262-3.pdf Hope that helped :-)
{ "pile_set_name": "StackExchange" }
Q: Sorting an Array of int using BubbleSort Why is my printed out Array not sorted in the below code? public class BubbleSort { public void sortArray(int[] x) {//go through the array and sort from smallest to highest for(int i=1; i<x.length; i++) { int temp=0; if(x[i-1] > x[i]) { temp = x[i-1]; x[i-1] = x[i]; x[i] = temp; } } } public void printArray(int[] x) { for(int i=0; i<x.length; i++) System.out.print(x[i] + " "); } public static void main(String[] args) { // TestBubbleSort BubbleSort b = new BubbleSort(); int[] num = {5,4,3,2,1}; b.sortArray(num); b.printArray(num); } } A: You need two loops to implement the Bubble Sort . Sample code : public static void bubbleSort(int[] numArray) { int n = numArray.length; int temp = 0; for (int i = 0; i < n; i++) { for (int j = 1; j < (n - i); j++) { if (numArray[j - 1] > numArray[j]) { temp = numArray[j - 1]; numArray[j - 1] = numArray[j]; numArray[j] = temp; } } } } A: You're only making one pass through your array! Bubble sort requires you to keep looping until you find that you are no longer doing any swapping; hence the running time of O(n^2). Try this: public void sortArray(int[] x) { boolean swapped = true; while (swapped) { swapped = false; for(int i=1; i<x.length; i++) { int temp=0; if(x[i-1] > x[i]) { temp = x[i-1]; x[i-1] = x[i]; x[i] = temp; swapped = true; } } } } Once swapped == false at the end of a loop, you have made a whole pass without finding any instances where x[i-1] > x[i] and, hence, you know the array is sorted. Only then can you terminate the algorithm. You can also replace the outer while loop with a for loop of n+1 iterations, which will guarantee that the array is in order; however, the while loop has the advantage of early termination in a better-than-worst-case scenario.
{ "pile_set_name": "StackExchange" }
Q: Using layout_weight for ImageView in RelativeLayout I'm using a RelativeLayout with an ImageView on the left. Here I hardcoded the layout_width for it with 150dp but this doesn't look good on other screens. On bigger screens the 150dp is fairly little. So I thought about using layout_weight but I can't use this on RelativeLayout. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res /android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/layout_quiz" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:fitsSystemWindows="true" android:minHeight="?attr/actionBarSize" android:padding="2dp" app:titleMarginStart="20dp" app:titleTextAppearance="@style/MyMaterialTheme.Base.TitleTextStyle" app:titleTextColor="@color/textColorPrimary"> <TextView android:id="@+id/toolbar_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:textColor="@android:color/white" android:textStyle="bold|italic"/> </android.support.v7.widget.Toolbar> <TextView android:id="@+id/tv_topic" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_below="@+id/toolbar" android:background="@android:color/holo_green_light" android:gravity="center" android:padding="5dp" android:textColor="@android:color/white"/> <RelativeLayout android:id="@+id/layout_question" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/toolbar" android:layout_toEndOf="@+id/tv_topic" android:layout_toRightOf="@+id/tv_topic" android:gravity="top" android:orientation="horizontal"> <TextView android:id="@+id/tv_question" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_toLeftOf="@+id/bt_favorite" android:padding="5dp" android:text="Schritte der Trainingssteuerung. Was ist hier richtige Reihenfolge?" android:textAppearance="?android:attr/textAppearanceMedium" android:textStyle="bold"/> <ImageButton android:id="@+id/bt_favorite" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:background="#00ffffff" android:src="@drawable/star"/> </RelativeLayout> <View android:layout_width="fill_parent" android:layout_height="1dp" android:layout_alignBottom="@+id/layout_question" android:layout_toEndOf="@+id/tv_topic" android:layout_toRightOf="@+id/tv_topic" android:background="?android:attr/listDivider"/> <View android:id="@+id/view" android:layout_width="1dp" android:layout_height="fill_parent" android:layout_below="@+id/toolbar" android:layout_toEndOf="@+id/iv_image" android:layout_toRightOf="@+id/iv_image" android:background="?android:attr/listDivider"/> <LinearLayout android:id="@+id/layout_multiplechoice" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/layout_question" android:layout_margin="5dp" android:layout_toEndOf="@+id/iv_image" android:layout_toRightOf="@+id/iv_image" android:orientation="horizontal"> <LinearLayout android:id="@+id/layout_multiplechoice_solutions" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center_vertical" android:orientation="vertical" android:visibility="invisible"> <CheckBox android:id="@+id/cb_solution1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:enabled="false"/> <CheckBox android:id="@+id/cb_solution2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:enabled="false"/> <CheckBox android:id="@+id/cb_solution3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:enabled="false"/> <CheckBox android:id="@+id/cb_solution4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:enabled="false"/> <CheckBox android:id="@+id/cb_solution5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:enabled="false"/> </LinearLayout> <LinearLayout android:id="@+id/layout_multiplechoice_answers" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center_vertical" android:orientation="vertical"> <CheckBox android:id="@+id/cb_answer1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:buttonTint="@android:color/holo_green_light"/> <CheckBox android:id="@+id/cb_answer2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:buttonTint="@android:color/holo_green_light"/> <CheckBox android:id="@+id/cb_answer3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:buttonTint="@android:color/holo_green_light"/> <CheckBox android:id="@+id/cb_answer4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:buttonTint="@android:color/holo_green_light"/> <CheckBox android:id="@+id/cb_answer5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:buttonTint="@android:color/holo_green_light"/> </LinearLayout> </LinearLayout> <LinearLayout android:id="@+id/layout_singlechoice" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/layout_question" android:layout_margin="5dp" android:layout_toEndOf="@+id/iv_image" android:layout_toRightOf="@+id/iv_image" android:orientation="horizontal" android:visibility="gone"> <LinearLayout android:id="@+id/layout_singlechoice_solutions" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center_vertical" android:orientation="vertical" android:visibility="invisible"> <RadioGroup android:id="@+id/rg_solution_group" android:layout_width="wrap_content" android:layout_height="wrap_content"> <RadioButton android:id="@+id/rb_solution1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:enabled="false"/> <RadioButton android:id="@+id/rb_solution2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:enabled="false"/> <RadioButton android:id="@+id/rb_solution3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:enabled="false"/> <RadioButton android:id="@+id/rb_solution4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:enabled="false"/> <RadioButton android:id="@+id/rb_solution5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:enabled="false"/> </RadioGroup> </LinearLayout> <LinearLayout android:id="@+id/layout_singlechoice_answers" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center_vertical" android:orientation="vertical"> <RadioGroup android:id="@+id/rg_answer_group" android:layout_width="wrap_content" android:layout_height="wrap_content"> <RadioButton android:id="@+id/rb_answer1" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <RadioButton android:id="@+id/rb_answer2" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <RadioButton android:id="@+id/rb_answer3" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <RadioButton android:id="@+id/rb_answer4" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <RadioButton android:id="@+id/rb_answer5" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </RadioGroup> </LinearLayout> </LinearLayout> <LinearLayout android:id="@+id/layout_info" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/layout_progressbar" android:layout_below="@+id/layout_question" android:layout_toEndOf="@+id/iv_image" android:layout_toRightOf="@+id/iv_image" android:orientation="vertical"> <TextView android:id="@+id/tv_infotitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="7dp" android:textStyle="bold"/> <ScrollView android:id="@+id/sv_infoscroller" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/tv_infotext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tv_infotitle" android:layout_margin="7dp" android:scrollbars="vertical"/> <ImageView android:id="@+id/iv_infopicture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tv_infotext" android:layout_margin="7dp"/> </LinearLayout> </ScrollView> </LinearLayout> <View android:layout_width="fill_parent" android:layout_height="1dp" android:layout_alignTop="@+id/layout_progressbar" android:layout_marginTop="5dp" android:layout_toEndOf="@+id/iv_image" android:layout_toRightOf="@+id/iv_image" android:background="?android:attr/listDivider"/> <RelativeLayout android:id="@+id/layout_progressbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_toEndOf="@+id/view" android:layout_toRightOf="@+id/view" android:gravity="bottom" android:orientation="horizontal"> <ImageButton android:id="@+id/bt_next" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_marginTop="5dp" android:enabled="false" android:src="@drawable/ic_arrow_right" android:text="@string/next"/> <ImageButton android:id="@+id/bt_info" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="16dp" android:layout_marginTop="15dp" android:layout_toLeftOf="@+id/bt_next" android:layout_toStartOf="@+id/bt_next" android:background="@null" android:src="@drawable/ic_info" android:visibility="invisible"/> <TextView android:id="@+id/tv_resultmessage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_margin="15dp"/> <ImageButton android:id="@+id/bt_back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="5dp" android:src="@drawable/ic_arrow_left" android:text="@string/back"/> <ProgressBar android:id="@+id/pb_quiz" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/bt_back" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:progress="1"/> </RelativeLayout> <ImageView android:id="@+id/iv_image" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_below="@id/toolbar" android:src="@drawable/schmuck"/> Do you know a solution for this? A: you can use PercentRelativeLayout <android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView app:layout_widthPercent="50%" app:layout_heightPercent="50%" app:layout_marginTopPercent="25%" app:layout_marginLeftPercent="25%"/> </android.support.percent.PercentRelativeLayout> Add this to your gradle dependencies: compile 'com.android.support:percent:22.2.0' see the official docs
{ "pile_set_name": "StackExchange" }
Q: Push view controller without stacking Is there any way to push a view controller to the navigation controller without stacking it? Wanted behavior (stack representation): [VC1[VC2]] -> Push VC3 from VC2 -> [VC1[VC3]] A: Yeah, just pop the other one before (without animating this one) like this: [navController popViewControllerAnimated:NO] [navController pushViewController:VC3 animated:YES] Or go for option 2, which is more general: Replace the viewControllers property: NSArray *newControllers = @[VC1, VC3]; [navController setViewControllers:newControllers animated:YES]; or... NSArray *newControllers = @[navController.viewControllers[0], VC3]; [navController setViewControllers:newControllers animated:YES];
{ "pile_set_name": "StackExchange" }
Q: Execute a Python script inside Python and pass arguments to it and get the value returned I want to execute a piece of Python code [B] from my existing Python code [A]. In B I would like to access methods defined in A. From A I would like to pass arguments to B. If I try this way: B.py def Main(args): print(args) method_a() # this doesn't work A.py def method_a(): return 5 mod = importlib.import_module('B') mod.Main(123) Using import_module I do not have access to methods in A.py If I use eval then I cannot pass any arguments to it and I'm not able to execute an entire file: eval('print(123)') works but eval(open('B.py').read()) does not. If I use exec I can access methods from A.py but I cannot return any value or pass any arguments. I'm Using python 3.6 A: Wrong design - two modules (or a module and a script - the only difference is how it's used) should not depend on each other. The correct way to structure your code is to have your "library" code (method_a etc) in one (or more) modules / packages that are totally independant of your application's entry point (your "main" script), and a main script that depends on your library code. IOW, you'd want something like this: # lib.py def method_a(args): print(args) return 42 def method_b(): # do something # etc And # main.py import sys import lib def main(args): print(lib.method_a(args)) if __name__ == "__main__": main(sys.argv)
{ "pile_set_name": "StackExchange" }
Q: Attempting to dynamcially append innerText to label elements from array I am working on my second ever Javascript project. As you can imagine, since I am still finding my feet with building projects, there are quite a few errors which I am running into (and learning from). Let me just quickly explain what stage I am at in building the family quiz and what the problem is. I have created an array of objects which stores questions, choices and answers within each index of the array. When the quiz starts up, there is an intro screen displaying the rules etc. The user then clicks on a "start quiz" button which transitions the screen to the first question. The user then selects the correct answer and clicks next question. This is the stage I am at currently. What I am trying to simply do is append the next 'choices' into the label elements. But when I click it nothing happens. Obviously I am doing something wrong. Please can someone assist? Many thanks! EDIT I have been informed by a response that there was a syntax error in my forEach loop which appends the next 'choices' to the label elements. I have corrected that. However, what I am finding now is that it is only appending the first index value of every 'choices' array to every label button. $(document).ready(function(){ var azeem = [ { question: "What is Azeem's favourte color?", choices: ["blue", "yellow", "red", "green"], answer: 0 }, { question: "What is Azeem's favourte movie?", choices: ["Scarface", "The Terminator", "Shawshank Redemption", "The Dark Knight"], answer: 3 }, { question: "What was Azeem's first ever job role?", choices: ["Cleaner", "Store Assistant", "Sales", "Admin"], answer: 1 }, { question: "What is Azeem's favourite dish?", choices: ["Pasta", "Pizza", "Chips", "Curry"], answer: 0 }, { question: "What subject did Azeem enjoy the most in school?", choices: ["Drama", "Science", "P.E", "History"], answer: 0 }, { question: "What subject did Azeem least enjoy in school?", choices: ["Geography", "Maths", "History", "I.T"], answer: 1 }, { question: "Which one of these cities has Azeem travelled to?", choices: ["Madrid", "Lisbon", "Istanbul", "Dublin"], answer: 1 }, { question: "Which college did Azeem study in?", choices: ["NewVic", "Redbridge", "East Ham", "Barking"], answer: 3 }, { question: "Who is Azeem's favourite sports icon?", choices: ["Eric Cantona", "Muhammad Ali", "Cristiano Ronaldo", "Prince Naseem"], answer: 1 }, { question: "Who is Azeem's favourite music artist?", choices: ["Michael Jackson", "Eminem", "Drake", "Linkin Park"], answer: 1 }, ]; var currentQuestion = 0; var questionNumberCounter = 1; var questionNumber = document.getElementById("questionCount"); var choices = document.getElementById("choicesSection"); var questions = document.getElementById("ques"); questions.innerText = azeem[currentQuestion].question; // The following event listener will transition from the instructions to the first question of the quiz document.getElementById("startquiz").addEventListener("click",function(){ $(".quiz-intro").fadeOut(600); $(".quiz-section").delay(600).slideDown("slow"); questionNumber.innerText = questionNumberCounter; azeem[currentQuestion].choices.forEach(function(value){ var radio = document.createElement("input"); var label = document.createElement("label"); var div = document.createElement("div"); $(div).addClass("choice"); radio.setAttribute("type", "radio"); radio.setAttribute("name", "answer"); radio.setAttribute("value", value); var radioID = 'question-'+currentQuestion; radio.setAttribute('id', radioID) ; label.setAttribute("for", radioID); label.innerHTML = value +"<br>"; choices.appendChild(div); div.appendChild(radio); div.appendChild(label); }) }) document.getElementById("submitanswer").addEventListener("click",function(){ questionNumberCounter++; questionNumber.innerText = questionNumberCounter; currentQuestion++ questions.innerText = azeem[currentQuestion].question; azeem[currentQuestion].choices.forEach(function(value){ var labels = document.getElementsByTagName("label"); var labelCounter = 0; while (labelCounter < 5){ labels[labelCounter].innerText = value; labelCounter++; } } }) }); HTML: <div class="container"> <h1 class="text-center">FAMILY QUIZ</h1> <h4 class="text-center">YOU HAVE CHOSEN AZEEM!</h4> <div class="row text-center quizSection"> <div class="col-md-4 image-section"> <img src="images/3.jpg" id="azeem" class="img-responsive img-thumbnail"> </div> <div class="col-md-8 quiz-intro"> <h2>INSTRUCTIONS</h2> <ul id="instructions"> <li>This is a multiple choice quiz</li> <li>There is only one correct answer per question</li> <li>At the end of the quiz you will be shown your total score which will reflect the amount of questions answered correctly</li> <li>There are no hints available during the process of the quiz</li> <li>Click the 'Start Quiz' button to begin</li> </ul> <button id="startquiz" class="btn-small btn-success">START QUIZ</button> </div> <div class="col-md-8 quiz-section"> <h5>Question <span id="questionCount">1</span> of 15</h5> <p class="text-center" id="ques"></p> <div id="choicesSection"> </div> <input type="submit" id="submitanswer" value="Submit Answer" class="btn-small btn-success"> </div> </div> A: Okay so first things first, you were missing a closing parens ) The bigger issue with your code lay within two things. First, this for loop is causing an issue where every choice you iterate over you are renaming every label that name. Why? The code below goes through each choice, sure, but it then loops over every label and redefines the label's text as that choice. Take a look: azeem[currentQuestion].choices.forEach(function(value) { var labels = document.getElementsByTagName("label"); var labelCounter = 0; while (labelCounter < 5) { labels[labelCounter].innerText = value; labelCounter++; } }); Another thing you'll notice above is that you are specifically saying 5 when really the operand should be checking for an amount that's less than labels.length (this will throw an error, so once we change it we can carry on) azeem[currentQuestion].choices.forEach(function(value) { var labels = document.getElementsByTagName("label"); var labelCounter = 0; while (labelCounter < labels.length) { labels[labelCounter].innerText = value; labelCounter++; } }); Now you'll see the questions populate with the same possible answer over and over. How do we fix this? Well, first it would pay to get our labels ahead of the loop since the elements themselves aren't being moved or deleted(we're just changing their text property) otherwise we're wasting resources grabbing the same elements over and over again. Secondly forEach comes with a handy parameter called index that is automatically supplied to the callback function. a.e. forEach(item, indexOFItem) - this means that we can eliminate your while loop entirely and just change the label corresponding to the index of the choice. var labels = document.getElementsByTagName("label"); azeem[currentQuestion].choices.forEach(function(value, ind) { labels[ind].innerText = value; }); Edit As pointed out in the comments, you're also going to want to check if the current question exists before loading it. A quick and dirty test for this with your current code is to simply check if the question exists in your object. There are better ways to make sure. You want to avoid static values when it comes to dynamic objects/arrays. As an example the labels issue above where you had set it to check if it was < 5 (less than 5). We changed this to labels.length to dynamically check the length instead of assuming it would always be 5. In the case of the question number, you have 15 questions stated, but that's not dynamic. A better way would be to check against azeem.length if you know that every object within azeem is a question. However, as I'm not sure, a quick fix is the following: if (azeem[currentQuestion]) { questions.innerText = azeem[currentQuestion].question; var labels = document.getElementsByTagName("label"); azeem[currentQuestion].choices.forEach(function(value, ind) { labels[ind].innerText = value; }); } else { alert("no more questions"); } If you change these things the code will run as follows: $(document).ready(function() { var azeem = [{ question: "What is Azeem's favourte color?", choices: ["blue", "yellow", "red", "green"], answer: 0 }, { question: "What is Azeem's favourte movie?", choices: ["Scarface", "The Terminator", "Shawshank Redemption", "The Dark Knight"], answer: 3 }, { question: "What was Azeem's first ever job role?", choices: ["Cleaner", "Store Assistant", "Sales", "Admin"], answer: 1 }, { question: "What is Azeem's favourite dish?", choices: ["Pasta", "Pizza", "Chips", "Curry"], answer: 0 }, { question: "What subject did Azeem enjoy the most in school?", choices: ["Drama", "Science", "P.E", "History"], answer: 0 }, { question: "What subject did Azeem least enjoy in school?", choices: ["Geography", "Maths", "History", "I.T"], answer: 1 }, { question: "Which one of these cities has Azeem travelled to?", choices: ["Madrid", "Lisbon", "Istanbul", "Dublin"], answer: 1 }, { question: "Which college did Azeem study in?", choices: ["NewVic", "Redbridge", "East Ham", "Barking"], answer: 3 }, { question: "Who is Azeem's favourite sports icon?", choices: ["Eric Cantona", "Muhammad Ali", "Cristiano Ronaldo", "Prince Naseem"], answer: 1 }, { question: "Who is Azeem's favourite music artist?", choices: ["Michael Jackson", "Eminem", "Drake", "Linkin Park"], answer: 1 }, ]; var currentQuestion = 0; var questionNumberCounter = 1; var questionNumber = document.getElementById("questionCount"); var choices = document.getElementById("choicesSection"); var questions = document.getElementById("ques"); questions.innerText = azeem[currentQuestion].question; // The following event listener will transition from the instructions to the first question of the quiz document.getElementById("startquiz").addEventListener("click", function() { $(".quiz-intro").fadeOut(600); $(".quiz-section").delay(600).slideDown("slow"); questionNumber.innerText = questionNumberCounter; azeem[currentQuestion].choices.forEach(function(value) { var radio = document.createElement("input"); var label = document.createElement("label"); var div = document.createElement("div"); $(div).addClass("choice"); radio.setAttribute("type", "radio"); radio.setAttribute("name", "answer"); radio.setAttribute("value", value); var radioID = 'question-' + currentQuestion; radio.setAttribute('id', radioID); label.setAttribute("for", radioID); label.innerHTML = value + "<br>"; choices.appendChild(div); div.appendChild(radio); div.appendChild(label); }) }) document.getElementById("submitanswer").addEventListener("click", function() { questionNumberCounter++; questionNumber.innerText = questionNumberCounter; currentQuestion++; if (azeem[currentQuestion]) { questions.innerText = azeem[currentQuestion].question; var labels = document.getElementsByTagName("label"); azeem[currentQuestion].choices.forEach(function(value, ind) { labels[ind].innerText = value; }); } else { alert("no more questions"); } }) }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <h1 class="text-center">FAMILY QUIZ</h1> <h4 class="text-center">YOU HAVE CHOSEN AZEEM!</h4> <div class="row text-center quizSection"> <div class="col-md-4 image-section"> <img src="images/3.jpg" id="azeem" class="img-responsive img-thumbnail"> </div> <div class="col-md-8 quiz-intro"> <h2>INSTRUCTIONS</h2> <ul id="instructions"> <li>This is a multiple choice quiz</li> <li>There is only one correct answer per question</li> <li>At the end of the quiz you will be shown your total score which will reflect the amount of questions answered correctly</li> <li>There are no hints available during the process of the quiz</li> <li>Click the 'Start Quiz' button to begin</li> </ul> <button id="startquiz" class="btn-small btn-success">START QUIZ</button> </div> <div class="col-md-8 quiz-section"> <h5>Question <span id="questionCount">1</span> of 15</h5> <p class="text-center" id="ques"></p> <div id="choicesSection"> </div> <input type="submit" id="submitanswer" value="Submit Answer" class="btn-small btn-success"> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: Parse error: syntax error, unexpected '=' I'm just starting out in programming i'm hitting my head at the moment against the wall cos i don't understand what is wrong with the following code mysql_query=("UPDATE tech_kunena_messages SET tech_kunena_messages.parent=tech_kunena_topics.first_post_id FROM tech_kunena_messages INNER JOIN tech_kunena_topics ON tech_kunena_messages.thread = tech_kunena_topics.id"); I'm getting a Parse error: syntax error, unexpected '=' i'm trying to update the _kunena_messages.parent with the first_post_id from kunena_topics as long as the .thread and .id are the same... I don't understand why i've got an unexpected =. Any help would be much appreciated A: mysql_query=(" ... ) should be mysql_query(" Edit: you should be using mysqli_( ... ) as mysql_() is deprecated.
{ "pile_set_name": "StackExchange" }
Q: Laravel 5 RESTful resource route not working I have Laravel 5 resource route: Route::group(['middleware' => 'auth'], function() { Route::resource('api/room', 'RoomsController'); // ... }); The RoomsController is generated with php artisan make:controller command. <?php namespace App\Http\Controllers; use Auth; use App\Room; use App\RoomUsers; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class RoomsController extends Controller { // ... } The index route working. When I GET the api/room, It returns expected result. There is the RoomsController@index method: public function index() { $user = Auth::user(); $currentUserRooms = RoomUsers::where('user_id', '=', $user->id)->get(); return response($currentUserRooms); } The problem: When I try to POST to the same URI (/api/room), I get 500 Internal Server Error. There is the RoomsController@store method (which should be called when POST request coming). public function store() { return response('is Working') // But isn't working } I setted these options in the php.ini file, but I still can't see the error information. It shows only "500 Internal server error" error_reporting = E_ALL display_errors = On display_startup_errors = On I have enabled the Laravel 5 debug mode too. A: The problem was caused by Laravel's CSRF Protection. I used PostMan to send the requests. It accepts GET requests, but not POST or PUT. I used the fix from this page to disable CSRF to these routes : // app/Http/Middleware/VerifyCsrfToken.php // ... class VerifyCsrfToken extends BaseVerifier { private $openRoutes = ['api/room', 'api/message']; public function handle($request, Closure $next) { foreach ($this->openRoutes as $route) { if ($request->is($route)) { return $next($request); } } return parent::handle($request, $next); } } About the error reporting: Yesterday I enabled all error reporting options and restarted many times the apache2 service. But no error description or stack trace was showed in PostMan. Today I wake up and tested it. It just worked. Now I have laravel error reporting with stack trace. I didn't turned off or restart the machine. (Lubuntu 14.04 32bit). I have no idea why this was happen yesterday. Maybe it was some stupid bug.
{ "pile_set_name": "StackExchange" }
Q: Best way to construct a read-only, empty List? I'm creating an immutable representation of an "event" in my system, and thus for lists of owners passed in the constructor, I'd like to take a read only view of them. Further, if they pass in null for the list, I'd like to make a read-only empty list in that case. Now, since Collections.unmodifiableList balks at null, I currently have this: userOwners_ = Collections.unmodifiableList(userOwners != null ? userOwners : new ArrayList<String>(0)); But that seems a bit ugly and inefficient. Is there a more elegant way to do this in Java? A: Collections.emptyList(). But seriously, null should NPE. A: An equally ugly, but marginally more efficient answer would be userOwners_ = userOwners != null ? Collections.unmodifiableList(userOwners) : Collections.emptyList(); However there are a couple of other things to observe. It appears that at some point, someone has decided to use null to represent an empty list. That is poor design ... and results in the need for special handling. Better to set it to either a new list, or emptyList() if you know the list is always empty. If you haven't consciously decided that null is the way to represent an empty list, then that null is "unexpected" and you should juts let it throw an NPE so you can track down and fix the cause. (It could be a variable that you have assumed is initialized elsewhere ... but isn't. That's a bug.) There is some confusion about whether you want a "read-only" list or an "immutable" list: The unmodifiableList() method gives you a list that you cannot modify; i.e. it is "read only". But the original list can still be modified, and those changes will be visible via the "read only" wrapper. If you want an "immutable" list (i.e. one that cannot be changed at all), you need to clone() the original list, and then wrap the clone using unmodifiableList(). Neither of these will make the elements of the list (the "owner" objects) immutable (if they are not already immutable). The identifier userOwners_ is a code style violation in the most widely accepted / used Java style guide.
{ "pile_set_name": "StackExchange" }
Q: Rename tooltip in altair I am trying to plot a chart in Altair using the below code. tot_matches_played = alt.Chart(mpt).mark_bar().encode( alt.X('Team',axis=alt.Axis(title='Teams Played in IPL'), sort=alt.EncodingSortField(field='Number_of_matches_played:Q', op='count', order='ascending')), alt.Y('Number_of_matches_played:Q' ), tooltip=['sum(Number_of_matches_played)'] ) But since the tooltip name is weird, I would like to rename it on the chart using "as", something like below. tot_matches_played = alt.Chart(mpt).mark_bar().encode( alt.X('Team',axis=alt.Axis(title='Teams Played in IPL'), sort=alt.EncodingSortField(field='Number_of_matches_played:Q', op='count', order='ascending')), alt.Y('Number_of_matches_played:Q' ), tooltip=['sum(Number_of_matches_played)' as total_matches] ) How to rename a tooltip so that it would appear in a more readable way to users looking at the chart. A: You can adjust the title output via alt.Tooltip: tot_matches_played = alt.Chart(mpt).mark_bar().encode( alt.X('Team',axis=alt.Axis(title='Teams Played in IPL'), sort=alt.EncodingSortField(field='Number_of_matches_played:Q', op='count', order='ascending')), alt.Y('Number_of_matches_played:Q' ), tooltip=[alt.Tooltip('sum(Number_of_matches_played)', title='matches played')] )
{ "pile_set_name": "StackExchange" }
Q: Birt with restful APIs I am developing BIRT reports for a PHP project. I can easily develop reports by connecting directly to the database using JDBC Datasource. However certain data come from restful api and I am unable to create a datasource from those api endpoints. Birt has option to create datasource from web services, however this seems to only accept SOAP APIs. I was wondering if someone can show me how to create birt datasources from REST APIs. I read through all the search results provided by google. Some recommend using POJO Datasource, while some recommend using scripted Datasource which requires knowledge in Java and which is little difficult for a PHP programmer to crack through. Most links redirect to devshare which now points to open text and the content doesnot exist anymore. I tried all the recommendations which are as follows. Using Webservices Datasource: It requires the location of wsdl file which is not there for a REST API. It comes only with SOAP API. Would be great if there is an alternative to this. Tried POJO Datasource and Scripted Datasource: But as a PHP developer couldn't get a good result as there is no step by step guide out there to do this. Because REST is pretty popular today, I was wondering if there is any straight forward way to do this, or if there is anyone who can help with Java or Javascript program for scripted datasource for a PHP head. I have been trying this for the last 15 days and is desperate for some help. A: Ended up with scripted datasource. Create a scripted datasource with open() method as follows: logger = java.util.logging.Logger.getLogger("birt.report.logger"); importPackage(Packages.java.io); importPackage(Packages.java.net); //if you have a parameter var param= params["industryname"].value; var inStream = new URL("http://yourapi/endpoint/" + param).openStream(); var inStreamReader = new InputStreamReader(inStream); var bufferedReader = new BufferedReader(inStreamReader); var line; var result = ""; while ((line = bufferedReader.readLine()) != null) result += line; inStream.close(); var json = JSON.parse(result); vars["HTMLJSON"] = json; logger.warning (result); //logger.warning (json); Then create a dataset with the following methods: open() recNum=0; fetch() len = vars["HTMLJSON"].length; if (recNum >= len) return false; row["name"] = vars["HTMLJSON"][recNum].name; row["id"] = vars["HTMLJSON"][recNum].id; row["active"] = vars["HTMLJSON"][recNum].active; recNum++; return true; You may need Apache Commons IO included in your scriptlib folder.
{ "pile_set_name": "StackExchange" }
Q: Controlling versions with Maven I have 3 poms in my projects, 1 for parent and 2 for each of the modules in use. Each pom currently contains <version>2.1.9.0-SNAPSHOT</version> tag Is it possible for each of the modules to pull this information form the parent automatically? A: Use the versions-maven plugin as described here : https://stackoverflow.com/a/5726599/320180
{ "pile_set_name": "StackExchange" }
Q: Quantum Lorentz Transformations Now I am reading a Weinberg's book "Quantum theory of field". Vol.1 page: 55 Сould you explain me the following things? Einstein's principle of relativity states the equivalence of certain 'inertial' frames of reference. It is distinguished from the Galilean principle of relativity, obeyed by Newtonian mechanics, by the transformation connecting coordinate systems in different inertial frames. If $x^\mu $ are the coordinates in one inertial frame (with $x^1$,$x^2$,$x^3$ Cartesian space coordinates, and $x ^ 0 = t$ a time coordinate, the speed of light being set equal to unity) then in any other inertial frame, the coordinates $x^\mu$ must satisfy: $$\eta_{\mu\nu}dx^{'\mu}dx^{'\nu} = \eta_{\mu\nu}dx^{\mu}dx^{\nu} \tag{2.3.1}$$ or equivalently: $$\eta_{\mu\nu}\frac{dx^{'\mu}}{dx^{\rho}}\frac{dx^{'\nu}}{dx^{\sigma}} = \eta_{\rho\sigma}. \tag{2.3.2}$$ How can it be equivalent? What are $\rho$ , $\sigma$, $\nu$? Why do we have $\eta_{\mu\nu}$ at both sides in the first equation? A: In the first equation you have $\eta_{\mu\nu}$ at both sides because you define the Lorentz transformations as those leaving the metric $\eta_{\mu\nu}$ invariant. So $\eta'_{\mu\nu}=\eta_{\mu\nu}$. You can obtain the first equation from the second by multiplying times $dx^{\rho}dx^{\sigma}$:$$\eta_{\mu\nu}\frac{dx^{'\mu}}{dx^{\rho}}dx^{\rho}\frac{dx^{'\nu}}{dx^{\sigma}}dx^{\sigma} \equiv \eta_{\mu\nu}dx'^{\mu}dx'^{\nu}=\eta_{\rho\sigma}dx^{\rho}dx^{\sigma}$$ where the last step is just multiplying the right hand side of the start point equation times $dx^{\rho}dx^{\sigma}$
{ "pile_set_name": "StackExchange" }
Q: Mobile Site Footer Location I am developing a full on RWD with a very small footer. Footer contains only couple links which are orphan pages (FAQs, etc). Our main target users will be accessing the site using iPhones (mostly), and we are optimizing for them. All pages are longer than iPhone 4/4S, but one of the sub-pages on the website has a very little content, which is less than 380 x 480 (iphone). See attached image. My question is, for this unique case, should I show the footer so the users know that it's consistently there? or place the footer below the viewport so it's not interfering with the main content/info? My instinct says B. A: Option B is a good choice if you have no important information. Copyright, trademark, etc. are needed things, but not necessary. I have seen quite a few websites follow the B pattern. They get some additional space for the main content. The disadvantage/advantage of this design is, the first time the user will end up scrolling (for regular people it's a habit to scroll on mobile pages) and once their mental model is fixed that there is no additional content below the fold they can use the site more effectively. Just make sure your design is consistent across pages.
{ "pile_set_name": "StackExchange" }
Q: .SMS file GSM 6 bit decoding I have to decode a file .SMS witch is encoded in GSM 6 bit(the SMS is not set from a cell phone but from some sensors to a base station, an then I get the .sms files). Can you help me with this any idea or tip? Thanks! There is a lot about 7 bit and 8 bit but nothing about 6 bit. Is is possible that is an user-defined alphabet? A: 3GPP TS 27.007 Section 5.5 gives the allowed coding schemes supported by the AT+CSCS command. As far as I am aware, none of them are 6 bit. But it does say that (conversion schemes not listed here can be defined by manufacturers) So it seems that as you suspected, you may have a user-defined alphabet. How to deal with this? If you can't get any information from the sender, then I would try fitting your messages to the first 6 bits of all of the officially supported conversion alphabets, to see if you can match all the characters. Consider the contents of the messages - are they a limited character set, e.g. all numbers (0-9)? It is possible that the sender may have used an official alphabet, maybe one that contains all the characters that they need in the first 6 bits, so they did not need to use the 7th and 8th bit.
{ "pile_set_name": "StackExchange" }
Q: Use Rails or Sinatra to bulid an Restful API? I have a question, I need to create an API for an iOS app. This API will be private, only usable with the iOS App and I don't know what framework I must to use. Rais? Sinatra? rails-api? What is your recommendation? Thanks! A: If you are already familiar with Rails, I'd use the Rails API gem. It customizes Rails to behave as an API, and includes several useful functionalities like versioning and serialization. Sinatra can be good for a very simple API, but usually, you'll end up adding most of Rails back into it. A: In addition to rails-api, I would take a look to Grape gem You can use it on top of Rack, Sinatra and Rails.
{ "pile_set_name": "StackExchange" }
Q: SAPUI5 Deep Insert from Kapsel Offline App on OData V2 Model Question: How can a "Deep Insert" performed from a SAPUI5 Client application on an OData V2 Model? Situation: I want to Deep Insert an "Operation" together with some "Components" into my OData V2 Model in my SAPUI5 Client application. // the request data "OperationSet" : { "Orderid" : "13700090", "OperationComponentSet" : [ { "Orderid" : "13700090", "Activity" : "0010", "SubActivity" : "", "ComponentItem" : "000010" } ] } this.getView().getModel().create("/OperationSet", requestData); I cannot use the function create(sPath, oData, mParameters?) on the OData V2 Model the documentation says: "Please note that deep creates are not supported and may not work." see https://sapui5.netweaver.ondemand.com/sdk/docs/api/symbols/sap.ui.model.odata.v2.ODataModel.html#create Is there any other possibility to perform a Deep Insert on an OData V2 Model? Links: https://sapui5.netweaver.ondemand.com/sdk/docs/api/symbols/sap.ui.model.odata.v2.ODataModel.html http://scn.sap.com/docs/DOC-58063#deepinsert A: The answer is, "Deep Insert" doesn't support 0..n assoziations with the Offline Kapsel Plugin at the moment. see http://help.sap.com/saphelp_smp308sdk/helpdata/en/d3/0ded03756247f1a136c84be7901879/content.htm Limitations of Deep Inserts A deep insert is an OData POST request to create an entity that also contains the inlined definitions of related entities. When a deep insert is processed, the top-level entity and all of its related entities are created and linked together as a single operation. In SDK SP07, the Offline Store supports deep inserts through the OData API on Android, iOS and WinPhone 8 platforms with one important restriction: The navigation property used for the deep insert must refer to at most one entity. Any inlined related entities must be added using a navigation property whose ToRole refers to an association end with cardinality 0..1 or 1. They cannot be added using a navigation property whose ToRole refers to an association end with cardinality *. Navigation properties that refer to a set of entities cannot be used for deep inserts. So "Deep Insert" will only work if the request is executed online against the gateway at the moment.
{ "pile_set_name": "StackExchange" }
Q: Mapping a new column to a DataFrame by rows from another DataFrame I have a Pandas DataFrame stations with index as id: id station lat lng 1 Boston 45.343 -45.333 2 New York 56.444 -35.690 I have another DataFrame df1 that has the following: duration date station gender NaN 20181118 NaN M 9 20181009 2.0 F 8 20170605 1.0 F I want to add to df1 so that it looks like the following DataFrame: duration date station gender lat lng NaN 20181118 NaN M nan nan 9 20181009 New York F 56.444 -35.690 8 20170605 Boston F 45.343 -45.333 I tried doing this iteratively by referring to the station.iloc[] as shown in the following example but I have about 2 mil rows and it ended up taking a lot of time. stat_list = [] lng_list [] lat_list = [] for stat in df1: if not np.isnan(stat): ref = station.iloc[stat] stat_list.append(ref.station) lng_list.append(ref.lng) lat_list.append(ref.lat) else: stat_list.append(np.nan) lng_list.append(np.nan) lat_list.append(np.nan) Is there a faster way to do this? A: Looks like this would be best solved with a merge which should significantly boost performance: df1.merge(stations, left_on="station", right_index=True, how="left") This will leave you with two columns station_x and station_y if you only want the station column with the string names in you can do: df_merged = df1.merge(stations, left_on="station", right_index=True, how="left", suffixes=("_x", "")) df_final = df_merged[df_merged.columns.difference(["station_x"])] (or just rename one of them before you merge)
{ "pile_set_name": "StackExchange" }
Q: Make one of two fields required in GraphQL schema? Im using Graphcool but this may be a general GraphQL question. Is there a way to make one of two fields required? For instance say I have a Post type. Posts must be attached to either a Group or to an Event. Can this be specified in the schema? type Post { body: String! author: User! event: Event // This or group is required group: Group // This or event is required } My actual requirements are a bit more complicated. Posts can either be attached to an event, or must be attached to a group and a location. type Post { body: String! author: User! event: Event // Either this is required, group: Group // Or both Group AND Location are required location: Location } So this is valid: mutation { createPost( body: "Here is a comment", authorId: "<UserID>", eventId: "<EventID>" ){ id } } As is this: mutation { createPost( body: "Here is a comment", authorId: "<UserID>", groupID: "<GroupID>", locationID: "<LocationID>" ){ id } } But this is not: As is this: mutation { createPost( body: "Here is a comment", authorId: "<UserID>", groupID: "<GroupID>", ){ id } } A: There's no way you can define your schema to define groups of inputs as required -- each input is individually either nullable (optional) or non-null (required). The only way to handle this type of scenario is within the resolver for that specific query or mutation. For example: (obj, {eventId, groupID, locationID}) => { if ( (eventID && !groupID && !locationID) || (groupID && locationID && !eventID) ) { // resolve normally } throw new Error('Invalid inputs') } It looks like in order to do that with Graphcool, you would have to utilize a custom resolver. See the documentation for more details.
{ "pile_set_name": "StackExchange" }
Q: How do spell-casting monsters prepare and recover their spells? For example. a Spirit Naga is a "10th level spellcaster", and "has the following wizard spells prepared". The text explains that the DM may substitute other spells for the ones given, but it is not clear whether such substitutions are permanent for that individual or simply represent the creature's selections from a spellbook (like a wizard) or other mechanic. And it is not stated whether slots are regained after a short or long rest - if ever! So, if the PCs engage a Spirit Naga and force it to retreat to a safe haven, what will the Naga's spell repertoire look like in two hours? In a day? A: Preparing spells From Monster Manual, page 10. The monster has a list of spells known or prepared from a particular class. This part basicallly means that there are two options: - monster has spells prepared (he knows even more) which resembles clerics, wizards - monster has spells known, which looks a little similar classes of bard or sorcerer Continueing. You can change the spells that a monster knows or has prepared, replacing any spell on a monster's spell list with a different spell of the same level and from the same class list. If you do so, you might cause the monster to be a greater or lesser threat than suggested by its challenge rating. From Monster Manual Errata: The monster is considered a member of that class when attuning to or using a magic item that requires membership in the class or access to its spell list. Player Handbook page 201 Before a spellcaster can use a spell, he or she must have the spell firmly fixed in mind, or must have access to the spell in a magic item. Members of a few classes, including bards and sorcerers, have a limited list of spells they know that are always fixed in mind. The same thing is true of many magic-using monsters. Other spellcasters, such as clerics and wizards, undergo a process of preparing spells. Notice, that the word "many" is used, not "all". If you read Monster Manual, you will notice that there are 2 types of casting for monster: innate or one that has spells from one of the spellcasting classes. Since word "many" applies only to a part, it is clearly means, that only one part of the magic using monster does not need to prepare them. That part are monsters with innate spellcasting. The other part goes with the rule: Other spellcasters, such as clerics and wizards, undergo a process of preparing spells. Morefurther, to prove my point: Drow Mage, and Drow Priestess of Lolth are basically Drows who took some classes of wizard or cleric, since their innate magic is not so powerful(you can easily create such a character like it was a PC). Notice that both of them are not called "wizard" or "cleric" but spellcasters with prepared spells from wizard/cleric list. If someone is still uncertain, there is a reply from wizards: Basically this means, that you should treat the monster depending what kind of spellcasting they have. Example: Spirit Naga must prepare it's spells like a wizard does. Derro Savant (Out of the Abyss, page 60) doesn't have to prepare it's spells, as he is treated like sorcerer. Recovering spells From Player's Handbook, page 201: Finishing a long rest restores any expended spell slots (see chapter 8 for the rules on resting). Some characters and monsters have special abilities that let them cast spells without using spell slots. This means, unless the monster has a special ability to regain spell slots, it needs a rest. Such an example would be Lich: On initiative count 20 (losing initiative ties), the lich can take a lair action to cause one of the following magical effects; the lich can't use the same effect two rounds in a row: The lich rolls a d8 and regains a spell slot of that level or lower. If it has no spent spell slots of that level or lower, nothing happens.
{ "pile_set_name": "StackExchange" }
Q: How can we extract the complete Facebook friend list using Graph API in java script? I am trying to extract friends list of a profile. I tried looking for the help and only thing I got is, "/me/friends" but this call has a limitation. This will only return any friends who have used (via Facebook Login) the app making the request. I wanted to have the list of all the friends in my profile. A: That´s how it works, you can´t get the full friendlist anymore. See the changelog for more information: https://developers.facebook.com/docs/apps/changelog You can only get the friends who authorized your App too, for privacy reasons. There are also plenty of other threads about that question already, for example: Facebook Graph Api v2.0+ - /me/friends returns empty, or only friends who also use my app Get ALL User Friends Using Facebook Graph API - Android
{ "pile_set_name": "StackExchange" }
Q: Using Namespaces I have a "Web Project" in VS. File structure - AdminCms - Sections - CmsAuthors - App_Code - Business Logics - Common - BuilderStrings.cs - DataAccess -CmsModel.edmx When I Build the Project VS in BIN Create a Cms.dll file. In file "BuilderStrings.cs" I use: namespace Cms.App_Code.BusinessLogics.Common Using this code from folder "CmsAuthors" using Cms.App_Code.BusinessLogics.Common; As so far all is working fine. Now for my understanding I should be able to name the namespace as I want ex: namescape Wdg.Cms.Common so if I use: using Wdg.Cms.Common; Script should be work just fine. Instead I get an error "Missing Assembly Reference". What is wrong? It is namespae a sort of path how to retrieve the Class? Why I cannot use a different name? Thanks guys for you help! A: It is perfectly fine. Have you saved and rebuild your project? ** I did get the error for the first time as I didn't save my changes in app_code. Nothing wrong here. The main purpose of having namespace is to avoid class name collision. For example, you have StringBuilder.cs in App_Code/Admin and App_Code/Common, you can differentiate them by using name space: Wdg.Cms.Common.StringBuilder and Wdg.Cms.Admin.StringBuilder You can use a different name.
{ "pile_set_name": "StackExchange" }