text
stringlengths
64
81.1k
meta
dict
Q: what design pattern for pre-do in class function My class function alway need do something before like this (Python): class X: def f1(): #### if check() == False: return; set_A() #### f1_do_something def f2(): #### if check() == False: return; set_A() #### f2_do_something And I want to : class X: def f1(): # auto check-return-set_A() f1_do_something def f2(): # auto check-return-set_A() f2_do_something I've read about design patterns and I do not know how to apply design patterns in this case. If there is no any suitable design patterns, are there any other solution to this problem? A: You could use a decorator: #!/usr/bin/env python def check(f, *args, **kwargs): def inner(*args, **kwargs): print 'checking...' return f(*args, **kwargs) return inner class Example(object): @check def hello(self): print 'inside hello' @check def hi(self): print 'inside hi' if __name__ == '__main__': example = Example() example.hello() example.hi() This snippet would print: checking... inside hello checking... inside hi If you go this route, please check out functools.wrap, which makes decorators aware of the original function's name and documentation.
{ "pile_set_name": "StackExchange" }
Q: PHP Session Variable Will Not Unset I have a couple of lines of code in a Drupal module as so: if ($arg == 'true' && isset($_SESSION['xyz']['noredirect'])) { unset($_SESSION['xyz']['noredirect']); } When the 2nd line is executed, I get error: Error messageNotice: Undefined variable: _SESSION in blah() (line 122 of /home/xxxxxxx/public_html/sites/all/modules/blah/blah.module). I simply cannot understand why if the session is set, I cannot unset it. Any ideas? Thanks A: It would appear that you are yet to run session_start(). This will create the $_SESSION superglobal.
{ "pile_set_name": "StackExchange" }
Q: How do I add a library to react-native project manually? There is a library react-native-iron-source on GitHub. But this library is not in the npm. How can I add the library to my react-native project manually? So that it works correctly with js code, iOS and Android? A: Try putting this in package.json "dependencies": { ... "react-native-iron-source": "git://github.com/bsy/react-native-iron-source.git" },
{ "pile_set_name": "StackExchange" }
Q: Counting the frequency of a factor in a list() I have a list with 10 different list elements, each containing a sample of 20 breakfast items that can be reproduced here… Diet <- as.factor(rep(c("Eggs","Meat","Eggs","Milk", "Juice"),20)) > head(Diet) [1] Eggs Meat Eggs Milk Juice Eggs Levels: Eggs Juice Meat Milk for() loop creating the 10 list elements. breakfast <- list() for ( i in 1:10) { breakfast[[i]] <- sample(Diet,20) } For each list element 1:10 I am trying to count the number of times “Eggs” occurs. This is a seemingly simple task, but I must be searching the wrong key words on other SO posts as I am getting little help from Goog et al. I think the best option would be to add something like NumEggs <- length(breakfast[[i]]==”Eggs” to the for() loop but this code is incorrect and returns the full length (i.e. 20) rather than only the length of “Eggs.” Any suggestions are appreciated. A: This should work: > sapply(breakfast, function(x)sum(x=="Eggs")) [1] 10 9 11 6 9 8 8 7 7 10
{ "pile_set_name": "StackExchange" }
Q: Rails class comparison - If Class.children include AnotherClass.children do Simple question I hope. I've a couple of classes - User and Recipe - both of which have 'ingredients' as children via has-many-through relationships. I'd like to run a comparison that checks to see if User.ingredients include the ingredients for each Recipe. I thought a simple 'include?' query would work this out, but it's returning nil when implemented. Got a feeling this is because I'm applying it to a class rather than array (although doesn't User.ingredients return an array?!), though not sure how I should adjust this to get it working - I've tried converting items to arrays, plucking ids out, etc. but nothing has working yet. Any help much appreciated! Steve. Here's the controller code: def meals @recipes = Recipe.all @user = current_user #from my user authentication end And the (abridged) view that's returning nil even when both contain the same ingredients: <% @recipes.each do |recipe| %> <% if @user.ingredients.include?(recipe.ingredients) %> <!-- ... --> <td> <%= recipe.name %> </td> <% end %> <% end %> One other point - testing this in the console, I've noticed running .include? on arrays of ingredient ids don't match if they're in the wrong order. Does this also need addressing? A: You can compare two array like so: a = [1,2,3] b = [1,2] c = [4,5] a & b #=> [1, 2] a & c #=> [] (a & c).empty? #=> true In this way, you can do something like: <% @recipes.each do |recipe| %> <% unless (@user.ingredients.pluck(:id) & recipe.ingredients.pluck(:id)).empty? %> <!-- ... --> <td> <%= recipe.name %> </td> <% end %> <% end %> I hope it helps...
{ "pile_set_name": "StackExchange" }
Q: Smart home automated fire response I've got a rather extensive OpenHab smart home installation with tons of lights, thermostats, and more diverse connected devices. One category of connected devices is smoke detectors, one in every zone of the house. Right now, when a smoke detector detects smoke, they all start shrieking like normal. Additionally, I've automated it so that: All the lights in the house turn on at full brightness (to provide a visual queue if someone somehow can't hear the alarms and prevent fumbling with light switches in the dark) The system sends push notifications to phones, alerting them that there might be a fire. If nobody's home, then security cameras can be viewed remotely and fire dept. called if there's actually a fire. Now here is my question: Several rooms have motor-driven windows/skylights. From a fire-safety perspective, would it make sense to automate these to open or close when smoke is detected? I can see both advantages and disadvantages, but I'm not sure what's safer: Automation should close the windows because they provide fresh oxygen for a fire and can make it grow rapidly. Automation should open the windows because this allows smoke and gasses to escape up and outwards. This lets people inside the building breath easier while they escape Some additional information about my house: Old, European construction with modern European doors, windows, and heating All walls are solid stone (cinder blocks mostly) or brick. Structural members are thick lumber or I-beams Automation likely to function for a long time provided fire does not break out in server room. Most devices are battery operated and all networking is powered by UPS in isolated room. A: Whether or not you open or close the windows is going to depend on the specifics of a situation. It's not something I would automate, it's too variable. But if you want too be sure, make an appointment to speak with your local Fire Marshall, that's kind of their job to know these sort of things.
{ "pile_set_name": "StackExchange" }
Q: How would I write a Junit test for parameter-less constructor in Java? Here is the code. I am wondering about how to create a test for the constructor. There are no getters for the last two fields. public class Log implements Reporter { /**The number of passengers processed*/ private int numCompleted; /** The total wait time.*/ private int totalWaitTime; /** The total process time*/ private int totalProcessTime; /** * The log constructor. */ public Log() { this.numCompleted = 0; this.totalWaitTime = 0; this.totalProcessTime = 0; } @Override public int getNumCompleted() { return numCompleted; } A: In the same way you would write a test for a constructor with parameters. Instantiate the object and afterwards verify the state is matching your expectations. Sample entity: public class Log { private int numCompleted; private int totalWaitTime; private int totalProcessTime; public Log(){ this.numCompleted = 0; this.totalWaitTime = 0; this.totalProcessTime = 0; } public Log(int numCompleted, int totalWaitTime, int totalProcessTime) { this.numCompleted = numCompleted; this.totalWaitTime = totalWaitTime; this.totalProcessTime = totalProcessTime; } public int getNumCompleted() { return numCompleted; } public int getTotalWaitTime() { return totalWaitTime; } public int getTotalProcessTime() { return totalProcessTime; } } Sample tests: @Test public void testNoArgConstructor(){ Log log = new Log(); assertEquals(0, log.getNumCompleted()); assertEquals(0, log.getTotalWaitTime()); assertEquals(0, log.getTotalProcessTime()); } @Test public void testArgConstructor(){ Log log = new Log(1,2,3); assertEquals(1, log.getNumCompleted()); assertEquals(2, log.getTotalWaitTime()); assertEquals(3, log.getTotalProcessTime()); }
{ "pile_set_name": "StackExchange" }
Q: Find the solutions of second derivative If $$f(x)=\frac {2x}{x^{2}-3x+2}$$ find the solutions of $$f''(x)=0$$ This problem is from a test. Is it possible to solve this without a calculator and without hard work? Maybe this fraction can be decomposed somehow? I have the same question for this function $$g(x)=\frac{\sqrt{x^2-1}}{x-2}$$ A: Partial fractions give $$f(x) = \frac{-2}{x-1} + \frac{4}{x-2}.$$ Then $$f''(x) = \frac{-4}{(x-1)^3} + \frac{8}{(x-2)^3}.$$ The numerator of that, after you add the fractions is $x^3-6x+6,$ which doesn't have pretty roots. The real root is $-(\sqrt[3]{4}+\sqrt[3]{2}).$
{ "pile_set_name": "StackExchange" }
Q: Add a new row at start of grid collection of custom module grid tab I have a collection ,which has total 30rows,Now,i want add new row at start of grid collection. Current code of prepareCollection() in grid.php protected function _prepareCollection() { $card = Mage::registry('amit_data'); Mage::registry('amit_data')->setData('temp_amount', $card->getCardAmount()); $collection = Mage::getModel('amit/order')->getCollection() ->addFieldToFilter('id_amit', $card->getId()); $collection->getSelect()->joinLeft('sales_flat_order', 'sales_flat_order.entity_id=main_table.id_order', 'sales_flat_order.increment_id as increment_id'); //$this->_prepareInitialRow(); $this->setCollection($collection); return parent::_prepareCollection(); } Current state I want this type work A: Amit Bera's solution is in the right direction. Depending on what type of Collection it is Mage_Eav_Model_Entity_Collection_Abstract or Mage_Core_Model_Resource_Db_Collection_Abstract that might not work though, and you can only add an object of the class you specified when you initialised the collection with ($this->_init('customer/customer'); in the _construct method for example). Try this: $first = Mage::getModel('amit/order') ->setUsedAmount('foo') ->setRemainingAmount('bar'); $collection->addItem($first); $this->setCollection($collection); Varien_Data_Collection::addItem adds an item at the end of the collection, but because the collection hasn't been loaded yet at that point - because of lazy loading - it's index will be at the beginning of the array.
{ "pile_set_name": "StackExchange" }
Q: How do I concatenate a string to all the members inside a comma seperated list in SQL Server 2008? For example my comma separated string looks like Declare @lists nvarchar(max) = N'EmailID , PhoneNumber , Profession' I want to append a string like 'aliasName.' to all the members such that the list should look like @lists = N'aliasName.EmailID , aliasName.PhoneNumber , aliasName.Profession' A: Declare @lists nvarchar(max) = N'EmailID , PhoneNumber , Profession' SET @lists = N'aliasName.' + replace(@lists,' , ', ' , aliasName.') SELECT @lists That should give you the following result: aliasName.EmailID , aliasName.PhoneNumber , aliasName.Profession
{ "pile_set_name": "StackExchange" }
Q: German Umlaute in RMarkdown and rticle I create a new document using the R Markdown Template American Economic Association journals. However, when knitting the whole document, my German Umlaute (such as ä, ü, Ö) are not displayed at all. Reproducible example: --- title: "Der Effekt von Ü auf Ö and ä" short: "ä ü ö" journal: "AER" # AER, AEJ, PP, JEL month: "`r lubridate::month(Sys.time())`" year: "`r lubridate::year(Sys.time())`" vol: 1 issue: 1 jel: - A10 - A11 keywords: - ö author: - name: Öder Ügo firstname: Ö surname: Ügo acknowledgements: | Acknowledgements abstract: | ÖÄÜ output: rticles::aea_article --- A: If you look at the resulting TeX file, you see the umlauts right there. The problem is just that by default LaTeX does not know how to deal with them. I see two possible solutions: Make use of XeLaTeX via output: rticles::aea_article: latex_engine: xelatex Adjust the template.tex file to include \usepackage[utf8]{inputenc} in the preamble. I would use the first approach. Either way you might have to post-process the resulting TeX file before submission: Replace all umlauts by the corresponding TeX commands (\"{U} etc.) and possbily remove the \usepackage. In the future, this will work out of the box, since LaTeX will use UTF-8 by default!
{ "pile_set_name": "StackExchange" }
Q: how to get viewModel by viewModels? (fragment-ktx) I am working with Single viewModel for the Activity and all of it's fragment. So to initialise viewmodel if have to write this setup code in onActivityCreated of all the fragment's override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProviders.of(activity!!).get(NoteViewModel::class.java) } I was going thorough the Android KTX extension page:(refer here) and i found i can initialise view model like this: // Get a reference to the ViewModel scoped to this Fragment val viewModel by viewModels<MyViewModel>() // Get a reference to the ViewModel scoped to its Activity val viewModel by activityViewModels<MyViewModel>() So I added below dependency's to my gradle(app): //ktx android implementation 'androidx.core:core-ktx:1.0.2' implementation 'androidx.fragment:fragment-ktx:1.0.0' implementation "androidx.lifecycle:lifecycle-extensions:2.0.0" But when i try to use viewModels/activityViewModels in my application their reference in not found. I want help in how to use these extension's with some basic example i tried searching for examples haven't found any. A: Atlast we we have got stable version. After moving to implementation 'androidx.fragment:fragment-ktx:1.1.0' i faced another issue. Compiler Error: Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6 build.gradle (Module:app) compileOptions { sourceCompatibility = 1.8 targetCompatibility = 1.8 } kotlinOptions { jvmTarget = "1.8" } reference After applying all the above the issue's is resolved. Thanks everyone. A: try implementation 'androidx.fragment:fragment-ktx:1.1.0-beta02'
{ "pile_set_name": "StackExchange" }
Q: Get phone contacts without the photos in order to save them in a DataOutputStream(vcf format) I have an application that export the phone contacts to the sdcard in a vcf format. I am able to get all the vcards and save them in a vcf format(looping on every ContactsContract.Contacts.LOOKUP_KEY until the cursor count -1 is reached in order to put the vcard concerning each contact in a AssetFileDescriptor and then converted to an FileInputStream using getContentResolver().openAssetFileDescriptor(....) ). The problem is that now I need to save the vcards without the photo. So any idea how to get the contacts without their photo in order to save them on the external storage in a vcf format? Thanks in advance A: API Level 14 + If you check out the source for ContactsContract.java, you can see that they introduced a new way to exclude the contact photo. /** * Boolean parameter that may be used with {@link #CONTENT_VCARD_URI} * and {@link #CONTENT_MULTI_VCARD_URI} to indicate that the returned * vcard should not contain a photo. * * @hide */ public static final String QUERY_PARAMETER_VCARD_NO_PHOTO = "nophoto"; The constant is hidden from the API (@hide), but you can still take advantage of it. After you get your lookup key, you can get the "nophoto" vcard Uri using the following code: String lookupKey = cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); Uri vcardUri = ContactsContract.Contacts.CONTENT_VCARD_URI .buildUpon().appendQueryParameter("nophoto", String.valueOf(true)) .build(); Uri uri = Uri.withAppendedPath(vcardUri, lookupKey); Pre API level 14 Your only solution would be to build your own vcards using the contact information. This library might help.
{ "pile_set_name": "StackExchange" }
Q: Summing a series with a changing power $$\sum_{r=0}^{k-1}4^r$$ Hi, I was wondering whether anyone could explain how to work this out. I know the end result is $\frac{4^k-1}{3}$, but I don't know why or how to get there. Thank you :D A: Multiply it by $(4-1)$. Expand without turning it into $4-1=3$. a lot of powers of $4$ will simplify except $4^k$ and $1$. Afterwards divide by $4-1=3$.
{ "pile_set_name": "StackExchange" }
Q: Phantom Bugs using Queue (STL Library), Windows/MingW/G++ I'm having two unexpected problems using Queue from the STL Library: 1) I'm trying to clear a Queue (Queue does not have a function clear), but the intuitive way is giving me a CORE DUMP: //The queue is defined Globally but the problem happens even //if i define it locally and pass it by reference. queue<pair<int,int> > Q; void yadayada () { //initialize Q while (!Q.empty()) Q.pop(); //CORE DUMP, what the hell? } 2) When i print the element(a pair) from the queue front it is wrongly printed as (0,0). But when i use the element (returning the second element of the pair) it is right! int yadayada2(...) { //code...code...code //the element in front is (4,20) front = Q.front(); Q.pop(); cout << "(" << front.first << "," << front.second << ")" << endl; //prints: (0,0) //what the hell? //correctly returns 20 return front.second; } int main() { //code...code...code //prints 20! cout << yadayada2 << endl; } I though: "Maybe the pop invalidates the element (does not make sense but...) so i moved the Q.pop(); to just before the return. But the same thing still happens... A: The best way to clear a queue is: Q = queue< pair< int, int > >(); // assign value of an empty temporary As for the front bug, I have to agree with Oli and suspect that there is an invalid reference.
{ "pile_set_name": "StackExchange" }
Q: How to check to make sure that blob_service.put_block_blob_from_path() was successful in python? I have to make sure the data was uploaded. Is there a better way then this ? Specially i want to get some meta of the transaction? try: blob_service.put_block_blob_from_path( 'user', fileName+'.'+ext, fileName+'.'+ext) except: print sys.exc_info()[1] A: Azure SDK for python supports progress_callback method. We can monitor the progress using callback function. Callback for progress with signature function(current, total) where current is the number of bytes transfered so far, and total is the size of the blob, or None if the total size is unknown. def progress_callback(current, total): print current print "===============" print total print "===============" if(current<total): print "unfinish" else: print "finish" blob_service = BlobService(account_name=storage_account_name, account_key=storage_account_key) blob_service.put_block_blob_from_path(container, blob_name, 'C:\\Users\\file_path',progress_callback=progress_callback) Also, you can use Storage Explore Tool or list_blob method to check files if you want to know whether is on Azure Storage. Please try it.
{ "pile_set_name": "StackExchange" }
Q: Infragistics XamGrid Column Header I am using the XAMGrid basic features and for some reason the header name is not displayed at all. All I want is the manually decided column name ABC on top of the column: As you see from the pic - there are no binding issues - since the values are coming in properly <ig:XamGrid AutoGenerateColumns="false" ItemsSource="{Binding SalesTradesView}"> <ig:XamGrid.Columns> <ig:TextColumn HeaderText="ABC" Key="ClientName"> <ig:TextColumn.HeaderTemplate> <DataTemplate> <TextBlock Text="{Binding Path=ClientName}"/> </DataTemplate> </ig:TextColumn.HeaderTemplate> </ig:TextColumn> </ig:XamGrid.Columns> </ig:XamGrid> A: Currently you are getting an empty TextBlock because ClientName is either empty or doesn't exist on the DataContext for the header. Note that it doesn't make sense to both set the HeaderText and the HeaderTemplate of the column and if all you want is for "ABC" to be displayed, remove the following XAML: <ig:TextColumn.HeaderTemplate> <DataTemplate> <TextBlock Text="{Binding Path=ClientName}"/> </DataTemplate> </ig:TextColumn.HeaderTemplate>
{ "pile_set_name": "StackExchange" }
Q: Grails table that links to itself I would like to create a grails domain class that links to itself. This related post suggests a solution but I can't get it to work: Grails domain class relationship to itself For one thing I don’t understand what comparable does and would need to add a int compareTo(obj) method. Adding the following to my code without implementing Comparable compiles, but grails crashes at runtime: //NavMenu parent SortedSet subItems static hasMany = [subItems: NavMenu] static belongsTo = [parent: NavMenu] static constraints = { parent(nullable:true) } Thanks in advance A: When you're using SortedSet, a sort algorithm is internally executed, but it needs a sort criteria. You need to implement the Comparable interface because that is the standard way to provide a sort criteria to the internal algorithm. If you don't need a specific order, you can delete the SortedSet subItems line and thus avoid implementing the Comparable interface.
{ "pile_set_name": "StackExchange" }
Q: VBA Copy column name from one sheet to all other sheets I'm stuck on a code with Runtime Error 424, Object required The code is basically copying a column from the first sheet name "Generate" and transpose the copied column to a header row on all other active sheets except "Generate". Could anyone help me to fix the error? Sub Test() Dim ws As Worksheet For Each ws In ActiveWorkbook.Worksheets If ws.Name <> "Generate" Then Worksheets("Generate").Range("B2:B42").Copy ActiveWorksheet.Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial Transpose:=True End If Next ws End Sub A: Try collecting the column header labels into an array first. sub test() dim hdrs as variant, w as long with worksheets(1) hdrs = application.transpose(.range(.cells(2, "B"), .cells(.rows.count, "B").end(xlup)).value2) end with for w=2 to worksheets.count with worksheets(w) .cells(1, "A").resize(1, ubound(hdrs)) = hdrs '.cells(.rows.count, "A").end(xlup).offset(1, 0).resize(1, ubound(hdrs)) = hdrs end with next w end sub 'alternate by worksheet name sub test() dim hdrs as variant, w as long with worksheets("Generate") hdrs = application.transpose(.range(.cells(2, "B"), .cells(.rows.count, "B").end(xlup)).value2) end with for w=1 to worksheets.count if lcase(worksheets(w).name) <> "generate" then with worksheets(w) .cells(1, "A").resize(1, ubound(hdrs)) = hdrs '.cells(.rows.count, "A").end(xlup).offset(1, 0).resize(1, ubound(hdrs)) = hdrs end with end if next w end sub
{ "pile_set_name": "StackExchange" }
Q: Updating a contacts email and phone in Oracles HZ_CONTACT_POINTS through PL/SQL Is it OK to update the EMAIL_ADDRESS or PHONE_NUMBER columns from a PL/SQL procedure for a contact that resides in HZ_CONTACT_POINTS manually using an update query similar to below? UPDATE hz_contact_points SET phone_number = P_PHONE_NUMBER WHERE owner_table_id = p_party_id AND owner_table_name = 'HZ_PARTIES' and primary_flag = 'Y' AND status = 'A' AND UPPER(contact_point_type) = 'PHONE'; OR UPDATE hz_contact_points SET email_address = P_EMAIL_ADDRESS WHERE owner_table_id = p_party_id AND owner_table_name = 'HZ_PARTIES' AND PRIMARY_FLAG = 'Y' AND STATUS = 'A' AND UPPER(CONTACT_POINT_TYPE) = 'EMAIL'; Or does one have to use the API calls: HZ_CONTACT_POINT_V2PUB.update_phone_contact_point OR HZ_CONTACT_POINT_V2PUB.update_email_contact_point A: HZ_CONTACT_POINT_V2PUB is part of the interface for TCA. To quote from the TCA documentation: "Oracle Trading Community Architecture (TCA) is a data model that allows you to manage complex information about the parties, or customers, who belong to your commercial community, including organizations, locations, and the network of hierarchical relationships among them." In particular, that complex information includes a version history. That's what the Oracle Apps APIs do: execute the actual DML and also orchestrates the concomitant changes (dependencies, versioning, audit, etc) to ensure the consistency of that data model. If you use SQL and update an attribute manually you won't do any of that. So, is that "okay"? Maybe you'll get away with it and not break anything. Or perhaps your organization doesn't care about the version history. But they have spent a lot of money licensing Oracle Apps. So my advice would be to use the API, even it it seems like overkill for such a trivial action. Because if you make a habit of bypassing the API eventually you will break the data model, and then Oracle Support will ask some very hard questions.
{ "pile_set_name": "StackExchange" }
Q: ArcPy SearchCursors - Compare rows in attribute table - cursor.next() function I'm new to ArcPy and have a question about ArcPy search cursors. I need to compare the current row of a point shapefile to the previous row for string field "Cat" and IF they are equal then I want to print the FID, ELSE print "NoMatch". Code and data found below. The issue is cursor.next() seems to skip a row perhaps? The output is 1, 3, 5, 7, 9 when it should be 1, 2, 3, 5, 6, 8, 9, 10 (note 4 and 7 should not print because the "Cat" field value does match the previous). Also not sure why 7 was returned in the result. DATA FID Cat POINT_X POINT_Y 0 Sand 619557.6 4843930.0 1 Sand 619515.4 4843900.5 2 Sand 619513.8 4843899.7 3 Sand 619512.6 4843898.6 4 Gravel 619511.3 4843897.5 5 Gravel 619508.8 4843895.5 6 Gravel 619507.5 4843894.5 7 Sand 619495.5 4843883.5 8 Sand 619486.1 4843876.3 9 Sand 619484.1 4843875.3 10 Sand 619476.0 4843870.2 CODE import arcpy shp = "C:\TEST.shp" cursor = arcpy.SearchCursor(shp) for row in cursor: rowCur = row rowPost = cursor.next() if rowPost.getValue("Cat")==rowCur.getValue("Cat"): print (row.getValue("FID")) else: print "NoMatch" A: Try something along these lines (warning: this is untested). import arcpy shp = "C:/TEST.shp" cursor = arcpy.SearchCursor(shp) previousValue = "" for row in cursor: rowCur = row # rowPost = cursor.next() if row.getValue("Cat")== previousValue: print (row.getValue("FID")) else: print "NoMatch" previousValue = row.getValue("Cat")
{ "pile_set_name": "StackExchange" }
Q: Usage of page factory class in magento2 What is the purpose of rendering the custom module page in Magento2 using the result factory \Magento\Framework\View\Result\PageFactory class injected in the constructor and making the page to display $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE); rather than doing these below kind of display which is same like in Magento 1.x approach $this->_view->loadLayout(); $this->_view->renderLayout(); A: Actually is not necessary to return an instance of \Magento\Framework\View\Result\Page. The execute is expected to return an instance of a class that implements the interface \Magento\Framework\Controller\ResultInterface. \Magento\Framework\View\Result\Page is just one possible return. Other possible returns are \Magento\Framework\Controller\Result\Redirect \Magento\Framework\Controller\Result\Raw \Magento\Framework\View\Result\Layout \Magento\Framework\Controller\Result\Forward \Magento\Framework\Controller\Result\Json and there may be others. take a look at the method Magento\Framework\App\Action\Action::dispatch(). This should return an instance of \Magento\Framework\Controller\ResultInterface and based on the result different actions are taken, again by calling methods declared in the ResultInterface. This dispatch method calls $result = $this->execute(); which is the execute method from the controller action. So I guess this is for consistency and to make it easier to introduce a different behavior for a controller action. You just need to add a new class that implements ResultInterface and it will all be handled by the framework. A: I believe that idea was return data/models from controllers, but current implementation looks strange for me too. Personally I expect to that controllers do not return anything, maybe just redirect to other url. To page layout need adds route on with this page will be available. <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-login"> <route url="login"/> <body> </body> </page> JSON will available from rest api
{ "pile_set_name": "StackExchange" }
Q: How can I specify the subsystem in the CodeBlocks additional linker options? One of the things I find nice about CodeBlocks is that it allows me to quickly create, compile and run a file without creating a project. However, this means that all of my programs have console windows, something that isn't normal for most Windows applications. To get rid of it, I've always had to create a project, throw my file in, and navigate to where I could just click GUI Application instead of Console Application. However, it's obviously possible to specify the same thing when building using g++.exe and ld.exe, and CodeBlocks has a section for additional linker options, so I figured I could stick it in there to avoid the hassle of always creating a project, but apparently I was wrong. Firstly, I found this question. I was surprised when I found out who answered it, but that doesn't help me, as the whole point of this is that I can do it with about the same amount of effort without creating a project. Apparently, the -mwindows compiler option will do that, so I tried putting that in Settings\Compiler and Debugger\Compiler settings\Other options, and it compiles and links fine, but still has a console window. Next, I tried Settings\Compiler and Debugger\Linker settings\Other linker options. Fuelled by Google results, I've tried adding the following to there, one option active at a time, and rebuilding. Having -mwindows active makes no difference as far as I can tell. -Wl: Unrecognized command line option --subsystem,windows: Unrecognized command line option --subsystem, windows: windows - No such file or directory. --subsystem windows: windows - No such file or directory. --subsystem=windows: Unregocnized command line option --subsystem, console: console - No such file or directory. This testing was all done on the newest release of CodeBlocks, CodeBlocks 12.11, and GCC 4.7.2, obtained from this MinGW distro (version 9.4). However, I'm fairly certain it works the same way with CodeBlocks 10.05. Am I forced to use a project, use a makefile, or build it from the command line, or is it possible to change this setting right in the CodeBlocks IDE global settings? A: Passing -Wl,--subsystem,windows to the linker is the proper way to do this. If it appears not to work then make sure that you didn't insert a space somewhere; use the argument as it is.
{ "pile_set_name": "StackExchange" }
Q: Spark: How change DataFrame to LibSVM and perform logistic regression I'm using this code to get data from Hive into Spark: val hc = new org.apache.spark.sql.hive.HiveContext(sc) val MyTab = hc.sql("select * from svm_file") and I get DataFrame: scala> MyTab.show() +--------------------+ | line| +--------------------+ |0 2072:1 8594:1 7...| |0 8609:3 101617:1...| | 0 7745:2| |0 6696:2 9568:21 ...| |0 200076:1 200065...| |0 400026:20 6936:...| |0 7793:2 9221:7 1...| |0 4831:1 400026:1...| |0 400011:1 400026...| |0 200072:1 6936:1...| |0 200065:29 4831:...| |1 400026:20 3632:...| |0 400026:19 6936:...| |0 190004:1 9041:2...| |0 190005:1 100120...| |0 400026:21 6936:...| |0 190004:1 3116:3...| |0 1590:12 8594:56...| |0 3632:2 9240:1 4...| |1 400011:1 400026...| +--------------------+ only showing top 20 rows How can I transform this DataFrame to libSVM to perform logistic regression like in this example: https://altiscale.zendesk.com/hc/en-us/articles/202627136-Spark-Shell-Examples ? A: I would say don't load it into DataFrame in the first place and simply use MLUtils.loadLibSVMFile but if for some reason this is not on an option you can convert to RDD[String] and use the same map logic as used by loadLibSVMFile import org.apache.spark.sql.Row import org.apache.spark.mllib.regression.LabeledPoint MyTab .map{ case Row(line: String) => line } .map(_.trim) .filter(line => !(line.isEmpty || line.startsWith("#"))) .map { line => ??? } In place of ??? just copy and paste a relevant part of the loadLibSVMFile method
{ "pile_set_name": "StackExchange" }
Q: Character Frequency in a String Given a string of printable ASCII, output the frequency of each character in that string. The Challenge Input is given as a string of printable ASCII characters (decimal [32-126] inclusive). Output the frequency of each character, in ASCII order. The output must have a format similar to [character][separator][count]. Provided that there is a single, non-newline separating string between the character and its frequency, it is a valid output. Output can be a single string, multiple strings, list of 2-tuples, array of tuples, etc. Input and output can be given using any convenient method. Standard loopholes are forbidden. This is code-golf, so shortest in bytes wins. Sample I/O abcd //outputs a: 1 b: 1 c: 1 d: 1 Over 9001! //outputs [ 1 ! [ 1 0 [ 2 1 [ 1 9 [ 1 O [ 1 e [ 1 r [ 1 v [ 1 --<-<<+[+[<+>--->->->-<<<]>]<<--.<++++++.<<-..<<.<+.>>.>>.<<<.+++.>>.>>-.<<<+. //outputs (as 2-tuples) (+,14),(-,13),(.,13),(<,21),(>,13),([,2),(],2) Su3OH39IguWH //outputs (as 2d array) [[3,2],[9,1],[H,2],[I,1],[O,1],[S,1],[W,1],[g,1],[u,2]] A: Python 3, 50, 43, 41 bytes lambda s:{c:s.count(c)for c in sorted(s)} Try it online! A: Ohm v2, 2 bytes SÖ Try it online! implicit input S sort string Ö run-length encoding implicitly print A: Python 3, 41 bytes lambda s:sorted({*zip(s,map(s.count,s))}) Try it online!
{ "pile_set_name": "StackExchange" }
Q: DashDot/Dash style within Windows Forms drawn incorrectly and Panels vs ShapeContainers I'm creating an UI with a panel(System.Windows.Forms.Panel) which will contain a Rectangle/Ellipse and the size(width/height) of the shape is dependent on the horizontal and vertical sliders. The code below does achieve to some extent the desired behavior. However, A line representing the centre of the panel with no Style works fine whereas a style of DashDot or Dash results in lines drawn across the diagonals and sides of the panels instead of the specified points(startPoint, endPoint). Is there a way to centre the rectangle based on the size of the panel? private void vScroll_Scroll(object sender, ScrollEventArgs e) { this.vScrollValue.Text = vScrollBar.Value.ToString(); panel.Invalidate(/*myRectangle*/); } private void hScrollBar_Scroll(object sender, ScrollEventArgs e) { this.hScrollValue.Text = hScrollBar.Value.ToString(); panel.Invalidate(/*myRectangle*/); } private void panel_Paint(object sender, PaintEventArgs e) { myRectangle = new Rectangle(90, 90, hScrollBar.Value, vScrollBar.Value); System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder(); messageBoxCS.AppendFormat("panel.Location.X = {0} panel.Location.Y = {1} (panel.Size.Height/2) = {2}", panel.Location.X, panel.Location.Y, e.ClipRectangle); //MessageBox.Show(messageBoxCS.ToString(), "Panel Paint"); //Panel's midpoint (location(x,y) = 88,44, Size(x,y) = 182,184) Point startPoint = new Point(e.ClipRectangle.Location.X, e.ClipRectangle.Location.Y + (e.ClipRectangle.Size.Height / 2)); Point endPoint = new Point(e.ClipRectangle.Location.X + e.ClipRectangle.Size.Width, e.ClipRectangle.Location.Y + (e.ClipRectangle.Size.Height / 2)); Pen dashRed = Pens.Red; e.Graphics.DrawRectangle(Pens.Black, myRectangle); //dashRed.DashStyle = System.Drawing.Drawing2D.DashStyle.DashDot; e.Graphics.DrawLine(Pens.Red, startPoint, endPoint); } Within the InitializeComponent() method the paintHandler event is registered as follows: this.panel.Paint += new System.Windows.Forms.PaintEventHandler(this.panel_Paint); Also, being new to C#, Should I be using Micorsoft.VisualBasic.Powerpack - ShapeContainers/RectangleShape/EllipseShape instead of using the WinForms.Panel? A: This should be right: private void panel_Paint(object sender, PaintEventArgs e) { myRectangle = new Rectangle(90, 90, hScrollBar.Value, vScrollBar.Value); System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder(); messageBoxCS.AppendFormat("panel.Location.X = {0} panel.Location.Y = {1} (panel.Size.Height/2) = {2}", panel.Location.X, panel.Location.Y, e.ClipRectangle); //MessageBox.Show(messageBoxCS.ToString(), "Panel Paint"); //Panel's midpoint (location(x,y) = 88,44, Size(x,y) = 182,184) e.Graphics.DrawRectangle(Pens.Black, myRectangle); if(e.ClipRectangle.Location.Y < this.Size.Height / 2 && e.ClipRectangle.Location.Y + e.ClipRectangle.Size.Height > this.Size.Height / 2) { Point startPoint = new Point(e.ClipRectangle.Location.X, this.Size.Height / 2); Point endPoint = new Point(e.ClipRectangle.Location.X + e.ClipRectangle.Size.Width, this.Size.Height / 2); Pen dashRed = Pens.Red; dashRed.DashStyle = System.Drawing.Drawing2D.DashStyle.DashDot; e.Graphics.DrawLine(dashRed, startPoint, endPoint); } } This should be how to make it work with ClipRectangle. Or you could ignore them, as Hans noted, probably in this simple app it wouldn't cause any slowdowns.
{ "pile_set_name": "StackExchange" }
Q: Where do APIs get their information from After some time being working with Restful APIs I would like to know a bit more about their internal functionality. I would like a simple explanation about how the API`s get access to the data that they provide as responses to our requests. There are APIs, for example weather API`s or sports APIs that are capable to provide responses with very recent data (such as sports results), I am wondering where or how they get that updated info almost as soon as it is available. I have seen here on SO questions with answers pointing to API design tutorials, but not to this particular topic. A: An API is usually simply a facade (or an interface if you prefer) to some information resource. The idea behind it is to "hide" any complexity from the user, to unify several services to a single access point or even to keep the details about the implementation of the actual service a secret. This being said you probably understand now that there can't be one definitive answer to the question "where do APIs get their info from?". But some common answers are: other APIs some proprietary/in-house developed service/database etc. For sports APIs - probably they are being provided by some sports media, which has the results as soon as they get out, so they just enter them in their DB and immediately they become available through their API. For weather forecasts - again as with the sports API they are probably provided by a company dealing with weather forecasts. If it's easier for you you can think of the "read-only" APIs as rss feeds in a way. I hope this clears the things a bit for you.
{ "pile_set_name": "StackExchange" }
Q: Trying to make a Dialog on click I'm trying to make an help Dialog which provides some helpful tips to the users of my app. The tips should be in an @string resource to handle language issues. The dialog should pop up on click and the text in it should be scrollable. My current implementation fails to meet such requirements. Here is the code: import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.text.InputType; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import ch.OptiLab.visuscontroll.R; public class MainActivity extends Activity implements OnClickListener { TextView textView; Button buttonende; Button tipps; Button btn1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textView); tipps = (Button) findViewById(R.id.tipps); btn1 = (Button) findViewById(R.id.buttonSTART); buttonende = (Button) findViewById(R.id.buttonende); btn1.setOnClickListener(this); tipps.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { // 1. Instantiate an AlertDialog.Builder with its constructor AlertDialog.Builder builder = new AlertDialog.Builder (MainActivity.this.getActivity()); // 2. Chain together various setter methods to set the dialog characteristics builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title); // 3. Get the AlertDialog from create() AlertDialog dialog = builder.create(); } }); A: Change your code to (...) AlertDialog dialog = builder.create(); dialog.show(); //Do not forget this line Also, make sure to correctly initialize builder: AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
{ "pile_set_name": "StackExchange" }
Q: Equilibrium temperature in a heat equation To find the equilibrium temperature distribution for a heat equation, $$U(x,t)$$ it is critical to note that the second partial derivatives WRT the space variables is zero. Why is this so? A: An equilibrium distribution is stationary, therefore it does not evolve over time $$\frac{\partial U}{\partial t} = 0$$ Substituting this in the heat equation immediately leads us to $$\frac{\partial^2 U}{\partial x^2} = 0 \; .$$
{ "pile_set_name": "StackExchange" }
Q: why property 'a' is not accessible from 'fn' var red = {a: 2}; red.fn = function(b){ console.log("A: "+a ", B : "+b); } red.fn(20); this gives error: a is not defined But i suspect a is already available as a global object to the function fn then why is it not accessible. Any explanation would be helpful. A: Because unlike some other languages, the this. qualifier is not optional in JavaScript (because it works fundamentally differently from most other languages that have this; more here). You need to write it explicitly: red.fn = function(b){ console.log("A: " + this.a + ", B : " + b); // ---------------------^^^^^ } (You were also missing + in there...)
{ "pile_set_name": "StackExchange" }
Q: how can i set radio button checked base after fetching the value I'm making a simple fetch and update. How can I set radio button checked base on the value I fetch on the postgresDB? I already fetch few data's on postgresDB $item['itemtype']; echo "<input type=\"radio\" name=\"radio\" id=\"radio\" value=\"Ingredient\" <?php if(isset($item[itemtype]) && $item[itemtype] == 'Ingredient') echo 'checked=\"checked\"'; ?>>"; echo "<label for=\"radio\">Ingredient</label>"; echo "<input type=\"radio\" name=\"radio\" id=\"radio\" value=\"Miscellaneous\" <?php if(isset($item[itemtype]) && $item[itemtype] == 'Miscellaneous') echo 'checked=\"checked\"'; ?>>"; echo "<label for=\"radio\">Miscellaneous</label>"; echo "</td>"; type's of itemtype Ingredient Miscellaneous and how should I validate it? A: Check this out <?php $item['itemtype'] = "Ingredient"; echo "<input type=\"radio\" name=\"radio\" id=\"radio\" value=\"Ingredient\""; if(isset($item[itemtype]) && $item[itemtype] == 'Ingredient') echo "checked=checked"; echo ">Ingredient"; echo "<input type=\"radio\" name=\"radio\" id=\"radio\" value=\"Miscellaneous\""; if(isset($item[itemtype]) && $item[itemtype] == 'Miscellaneous') echo "checked=checked"; echo ">Miscellaneous"; ?>
{ "pile_set_name": "StackExchange" }
Q: Delphi doesn't have Lambda Expressions and I'm a Delphi programmer, what am I missing out on? I'm nearly clueless as to what a lambda expression is, but I have a hard time believing that I couldn't finagle something to the same effect in Delphi (albeit with 900% more code). What is the big advantage of lambda expressions, what am I missing out on and is there anything with the post Delphi 2009 RTL improvements that comes close to emulating the powers of C# in this regard? A: You're not missing anything, really. Lambdas are just a different form of anonymous methods, which were introduced in Delphi 2009, with a very minimal syntax that makes them cryptic and hard to read. (No function header to speak of, for example, which means that you can't tell the type of the variables you're working with by looking at the code.) A: Let's say in Delphi you have anonymous inline methods like the delegate in this C# code: var squared = Enumerable.Range(0, 100) .Select( delegate(int a) { return a * a; } ); Then the lambdas are simply a shorter way of writing that: var squared = Enumerable.Range(0, 100) .Select( a => a * a ); The code snippets above are identical from the IL point of view. A: I have a hard time believing that I couldn't finagle something to the same effect in Delphi (albeit with 900% more code). Well... That's what you're missing out on then - being able to accomplish certain things without writing a huge amount of plumbing. It's syntactic sugar, in the same sense that things like bounded loops, functions, and user-defined types are sugar - it provides a means of both simplifying and writing code that clearly expresses what you're doing without getting bogged down in the petty details of how you're wrestling the CPU into actually doing it.
{ "pile_set_name": "StackExchange" }
Q: Bit Fields access in C I am trying to access bit fields: Below is the code which works fine and gives expected result but throws compiler warnings which I have mentioned below. #include <stdio.h> #include <stdint.h> struct status_type_one{ unsigned delta_cts : 1;// lsb unsigned delta_dsr : 1; unsigned tr_edge : 1 ; unsigned delta_rec : 1; unsigned cts : 1; unsigned dsr : 1; unsigned ring : 1; unsigned rec_line : 1;// msb } status_one; struct status_type_two { unsigned : 4; // lsb 4 bits unsigned cts : 1; //bit 5 unsigned dsr : 1; // bit 6 } status_two; int main(void) { status_one.delta_cts=1; status_one.delta_dsr=0; status_one.tr_edge=1; status_one.delta_rec=0; status_one.cts=1; status_one.dsr=0; status_one.ring=1; status_one.rec_line=1; printf("The value of status_one is %x\n",status_one); // warning here status_two.cts=1; status_two.dsr=1; printf("The value of status_one is %d\n",status_two); // warning here return 0; } But I am getting below warning: $ gcc -Wall Bit_Fields.c -o Bit_Fields Bit_Fields.c: In function `main': Bit_Fields.c:35: warning: unsigned int format, status_type_one arg (arg 2) Bit_Fields.c:35: warning: unsigned int format, status_type_one arg (arg 2) Bit_Fields.c:40: warning: int format, status_type_two arg (arg 2) Bit_Fields.c:40: warning: int format, status_type_two arg (arg 2) The Output is correct as shown below $ ./Bit_Fields The value of status_one is d5 The value of status_one is 48 Can anyone please tell, What the warning is about and how to resolve it? Thanks A: The typical way to solve this is to have an integer-type union value, e.g: union status_type_one { struct status_type_one{ unsigned delta_cts : 1;// lsb unsigned delta_dsr : 1; unsigned tr_edge : 1 ; unsigned delta_rec : 1; unsigned cts : 1; unsigned dsr : 1; unsigned ring : 1; unsigned rec_line : 1;// msb } bits; unsigned whole[1]; // Size should match the total bits size. } status_one; Now, your other code would have to change: status_one.bits.delta_cts=1; status_one.bits.delta_dsr=0; status_one.bits.tr_edge=1; ... etc ... and the print: printf("The value of status_one is %x\n",status_one.whole[0]); [Obviously, if the struct is more than one item in whole, you need to either loop or pass several values to printf] What you are doing may well appear to work, but you are not really supposed to pass a STRUCT to a printf function, and there's no telling what that does if you use more than one machine word worth of data, or what happens on a 64-bit machine, etc, etc.
{ "pile_set_name": "StackExchange" }
Q: Why do images taken with a Nikon D3100 get cut off? I just received my Nikon D3100 and for the first few photos it worked beautifully, but now when I take photos it only shows approximately the top 3mm. I put on both lenses and removed the caps but still the same thing is happening. I cannot afford to fix it after only one day of use. It looks almost as if a black cover is covering most of the picture. A: It could be a problem with your memory card. Some cameras allow you to take a picture without a memory card and review it for a short time. Try to see if you can do it and see if the image looks ok. Then try it with your memory card on. If your image looks corrupted then the problem is with the memory card. If not you can atleast rule out the memory card as the cause. It would also be helpful to have a sample picture.
{ "pile_set_name": "StackExchange" }
Q: Exporting AD group memberships of users in PowerShell I need to export a list of all groups a user is assigned to. This command works fine for my needs: Get-ADPrincipalGroupMembership username | select name | Export-Csv filepath However I have to review about 100 users in my company, so I would like to to merge those CSVs in an Excel spreadsheet. My problem is that when I merge the CSVs, I just have a random list of AD groups. A solution for this problem would be to export a CSV with two columns while column 1 consists of the AD username and column 2 of the AD groupname, eg. User A | Group A; User A | Group B; User A | Group C I already have figured out that this probably won't be possible with Get -ADPrincipalGroupMembership but unfortunately I haven't found any solution yet. A: The format you're considering is terrible for both viewing and processing. Either build a list mapping the user to each group (one mapping per line) $users = 'userA', 'userB', ... foreach ($user in $users) { $groups = Get-ADPrincipalGroupMembership $user | Select-Object -Expand Name $groups | ForEach-Object { New-Object -Type PSObject -Property @{ 'User' = $user 'Group' = $_ } } } | Export-Csv 'output.csv' -NoType or join the list of groups with a secondary delimiter and map a user to all of its groups like that: $users = 'userA', 'userB', ... foreach ($user in $users) { $groups = Get-ADPrincipalGroupMembership $user | Select-Object -Expand Name New-Object -Type PSObject -Property @{ 'User' = $user 'Group' = $groups -join '|' } } | Export-Csv 'output.csv' -NoType
{ "pile_set_name": "StackExchange" }
Q: Salvando caminho de arquivo no MySQL Estou tendo dificuldade ao salvar endereço de arquivo no banco de dados. Ao salvar o endereço no banco ele esta adicionando a quantidade de vezes que utilizei o OpenFileDialog para salvar um arquivo. Salva o endereço sempre assim C:\Users\phili\Desktop\PDF_SGIM_QUALIDADE_CNH\certificadocalibracao.pdf12 Sempre coloca um numeral depois da extensão. Porque está acontecendo isso? private void tsbtnGravar_Click(object sender, EventArgs e) { try { if (identificacaoTextBox.Text == "") { MessageBox.Show("Informe a Identificação do Instrumento.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); identificacaoTextBox.Focus(); } else if (descricaoTextBox.Text == "") { MessageBox.Show("Informe s Descrição do Instrumento.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); descricaoTextBox.Focus(); } else { if (status == "novo") { cmd.CommandText = "INSERT INTO tb_Intrumento (identificacao,Descricao,Marca, Modelo,Serial,Capacidade,Frequencia,Data_Calibracao,Vencimento_Calibrecao,Certificado) VALUES('" + identificacaoTextBox.Text + "','" + descricaoTextBox.Text + "','" + marcaTextBox.Text + "','" + modeloTextBox.Text + "','" + txb_Numero_Serie.Text + "','" + capacidadeTextBox.Text + "','" + tcb_Frequencia_Calibracao.Text + "','" + txb_Data_Calibracao.Text + "','" + txb_Vencimento_Calibracao.Text + "','" + txb_caminho.Text + "','" + cmd.ExecuteNonQuery(); cmd.Dispose(); MessageBox.Show("Registro salvo com sucesso.", "Salvar", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (status == "editar") { cmd.CommandText = "INSERT INTO tb_Instrumento SET Identificacao='" + identificacaoTextBox.Text + "', Descricao='" + descricaoTextBox.Text + "',Marca='" + marcaTextBox.Text + "', Modelo='" + modeloTextBox.Text + "', Serie='" + txb_Numero_Serie.Text + "', Capacidade='" + capacidadeTextBox.Text + "', Frequencia='" + tcb_Frequencia_Calibracao.Text + "', Data_Calibracao='" + txb_Data_Calibracao.Text + "', Vencimento_Calibracao='" + txb_Vencimento_Calibracao.Text + "', Certificado='" + txb_caminho.Text + lstvInstrumentos.Items[lstvInstrumentos.FocusedItem.Index].Text + "'"; cmd.ExecuteNonQuery(); MessageBox.Show("Registro atualizado com sucesso.", "Atualizar", MessageBoxButtons.OK, MessageBoxIcon.Information); } carregaVariaveis(); btn_Limpar_Dados.PerformClick(); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } Abaixo segue código que insere o caminho no textbox: private void btn_Carregar_Certificado_Click(object sender, EventArgs e) { OpenFileDialog abrir = new OpenFileDialog(); abrir.ShowDialog(); // openFileDialog1.ShowDialog(); txb_caminho.Text = abrir.FileName.Replace(@"\", @"\\"); } A: Faça a query de forma segura e o problema vai se resolver: var cmd = new SqlCommand("INSERT INTO tb_Instrumento SET Identificacao = @Identificao, Descricao = @Descricao, ... aqui vai colocar todos os campos ..., Certificado = @Certificado, ... pode ter outros aqui", connection); cmd.Parameters["@Identificacao"].Value = identificacaoTextBox.Text; cmd.Parameters["@Descricao"].Value = descricaoTextBox.Text; ... todos os parâmetros aqui cmd.Parameters["@Certificado"].Value = txb_caminho.Text; Coloquei no GitHub para referência futura. O código do jeito que está não está só errado, tem sérios problemas de segurança. A: O cmd.CommandText do if (status == "novo") está concatenando a próxima linha junto com a query. Sendo que a próxima linha é o cmd.ExecuteNonQuery();, que retorna o Id do insert que ela acabou de realizar. Portanto basta colocar um ; depois da do txb_caminho.Text ao invés de como está agora: _Calibracao.Text + "','" + txb_caminho.Text + "','" +.
{ "pile_set_name": "StackExchange" }
Q: How to disable welcome message after SSH login? I have changed /etc/issue.net, so I have set a "personal" message after typing a username in an SSH terminal. Now I am trying to change the welcome text after successful login. I have found a lot of posts about the /etc/motd file, but the part "Welcome to Ubuntu blabla versionnumber and so on" + "* Documentation URL " is not there? I just do not want to show OS info in my SSH terminal, I already know what I have installed. :) I only want to see my last login. And also not errors; errors belong in a logfile. Which file do I have to edit? A: The welcome messages are generated by the files residing in /etc/update-motd.d/. From man update-motd: Executable scripts in /etc/update-motd.d/* are executed by pam_motd(8) as the root user at each login, and this information is concatenated in /var/run/motd. So if you don't want the outputs of those scripts upon login via ssh just remove the execute flag on them: sudo chmod -x /etc/update-motd.d/* Now if you want to show something you want upon login, you have two options: Make a script, put it in /etc/update-motd.d/, make it executable, also make sure it outputs on STDOUT. ssh has a Banner option. You can put the text in a file and set it in the Banner option so that the content of the file is shown upon login via ssh. Note that this is applicable to only ssh. Banner /etc/foobar From man 5 sshd_config: Banner The contents of the specified file are sent to the remote user before authentication is allowed. If the argument is “none” then no banner is displayed. This option is only available for protocol version 2. By default, no banner is displayed. A: Another way that does not require administrative rights is to place an empty file called .hushlogin into your $HOME directory (using for example touch ~/.hushlogin). Source that provides further info including a possible downside of this approach. A: You can also nuke pam_motd altogether: sed -i '/^[^#]*\<pam_motd.so\>/s/^/#/' /etc/pam.d/sshd PAM calls pam_motd depending on the settings in /etc/pam.d, and typically the entries are: $ grep pam_motd /etc/pam.d -R /etc/pam.d/login:session optional pam_motd.so motd=/run/motd.dynamic noupdate /etc/pam.d/login:session optional pam_motd.so /etc/pam.d/sshd:session optional pam_motd.so motd=/run/motd.dynamic noupdate /etc/pam.d/sshd:session optional pam_motd.so # [1] Just commenting out the pam_motd lines from these files will disable it.
{ "pile_set_name": "StackExchange" }
Q: Open .NET app from Web Page I just need to be able to open a .NET app (click once) from within an ASP.NET web page, and pass 2 string parameter to the app. How can I do this? Any example please, with any method to do it. Thank you in advance. A: This article explains how to retrieve the parameters from the querystring used to call the ClickOnce app. That should help you to figure out how to compose the URL, along with its querystring containing the parameters you want to send.
{ "pile_set_name": "StackExchange" }
Q: How to find the numerical error when we don't know the exact solution? When some quantity $x$ (e.g., the values of a solution of a PDE, using a finite difference method) is calculated numerically, we get its approximate value $x^*$. The error is $|x-x^*|$. But since we don't know $x$ itself, how is it possible to find the rrror? A: Typically, the accuracy of the numerical approximation hinges on a parameter $h>0$ such as the time step when integration ordinary differential equations or the spacing between grid points when solving the Laplace equation on a square using the standard five point finite difference stencil with a fixed step size. You will frequently have an asymptotic error expansion of the form \begin{equation} T - A_h = \alpha h^p + \beta h^q + O(h^r), \quad p < q < r. \end{equation} Here $T$ is your target, i.e. the number which you which to compute, $A_h$ is the approximation obtained used the parameter $h$, $\alpha$ and $\beta$ are constants which depend on the target, but are independent of $h$ and the numbers $p < q < r$ reflect the properties of you method. You can estimate the principal error term, i.e. $\alpha h^p$ as follows \begin{equation} \alpha h^p \approx \frac{A_h - A_{2h}}{2^p - 1} \end{equation} provided that $h$ is sufficiently small. This can be judged by evaluating the fraction \begin{equation} F_h = \frac{A_{2h}- A_{4h}}{A_h - A_{2h}} \end{equation} which tends to $2^p$ and is close to $2^p$ precisely when the above approximation is good.
{ "pile_set_name": "StackExchange" }
Q: Adding "cacheControlMaxAge" parameter into sddraft I would like adding a new parameter into my sddraft, the value of "cacheControlMaxAge". For this, I have the following code that modifies the value of already existing parameters : import xml.dom.minidom as dom doc = dom.parse(r"Z:\secret_folder\service.sddraft") configProps = doc.getElementsByTagName('ConfigurationProperties')[0] configPropArray = configProps.firstChild configPropSets = configPropArray.childNodes for configPropSet in configPropSets: configPropKeyValues = configPropSet.childNodes for configPropKeyValue in configPropKeyValues: if configPropKeyValue.tagName == 'Key': if configPropKeyValue.firstChild.data == 'cacheControlMaxAge': configPropKeyValue.nextSibling.firstChild.data = 604800 print "OK" else: print "KO" However, it seems that the parameter does not exist : KO If I am wrong with variable name/parameter, how do I add this parameter in the sddraft ? A: Finally, I found a solution to the problem described above. There it is : import xml.dom.minidom as dom doc = dom.parse(r"Z:\secret_folder\service.sddraft") PropertySetProperty_balise = doc.createElement("PropertySetProperty") # creation d une balise PropertySetProperty PropertySetProperty_balise.setAttribute("xsi:type", "typens:PropertySetProperty") # ajout de l attribut xsi:type="typens:PropertySetProperty" a la balise PropertySetProperty key_balise = doc.createElement("Key") # creation d une balise Key key_value = doc.createTextNode("cacheControlMaxAge") # creation d un texte de valeur "cacheControlMaxAge" key_balise.appendChild(key_value) # insertion de la balise texte de valeur "cacheControlMaxAge" dans la balise Key value_balise = doc.createElement("Value") # creation d une balise Value value_balise.setAttribute("xsi:type", "xs:double") # parametrage du type de la balise Value value_value = doc.createTextNode(cacheControlMaxAge) # creation d un texte de valeur numerique cacheControlMaxAge value_balise.appendChild(604800) # insertion de la balise texte de valeur numerique cacheControlMaxAge dans la balise Value PropertySetProperty_balise.appendChild(key_balise) # insertion de la balise Key dans la balise PropertySetProperty PropertySetProperty_balise.appendChild(value_balise) # insertion de la balise Value dans la balise PropertySetProperty configProps = doc.getElementsByTagName('ConfigurationProperties')[0] configPropArray = configProps.firstChild configPropArray.appendChild(PropertySetProperty_balise) # insertion de la balise PropertySetProperty dans la balise PropertyArray configPropSets = configPropArray.childNodes for configPropSet in configPropSets: configPropKeyValues = configPropSet.childNodes for configPropKeyValue in configPropKeyValues: if configPropKeyValue.tagName == 'Key': if configPropKeyValue.firstChild.data == 'cacheControlMaxAge': print configPropKeyValue.nextSibling.firstChild.data else: print "KO" And I get : 604800 In fact I manually created all the necessary tags, without forgetting to configure their type (to keep a valid sddraft) then I inserted the tags in the right place. Thanks for your intervention, Hope this will help you.
{ "pile_set_name": "StackExchange" }
Q: Update Textview right after user change settings value In my app I let the user choose a name to display. It should display as: Hello usertext! I can successfully update settings. I used PreferenceActivity. I can change the value too. But to change the text in the selected textview, I have to restart the app. How can I update my textview right after users update the value in settings? A: Preference.OnPreferenceChangeListener changeListener = new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { // Code goes here return true; } }; EditTextPreference pref = (EditTextPreference)findPreference(getString(R.string.pref1)); pref1.setOnPreferenceChangeListener(changeListener); EditTextPreference pref2 = (EditTextPreference)findPreference(getString(R.string.pref2)); pref2.setOnPreferenceChangeListener(changeListener);
{ "pile_set_name": "StackExchange" }
Q: Lua how to assign default array value to '0' not nil I was getting lately an error in Lua saying cannot assign arithmetic value of '?'. then I realized that I need to define how many storage are in my array and assigning them to a value, this gave me Error : locator = {} this Worked fine : locator = {0,0,0,0,0,0,0,0,0,0} So now I have another array that I need a loop to store 200 values in it, so how to define the storage and values within it without something like this : a = {0,0,0,0,0,...... etc} Any Ideas ? A: this is what worked for me : locator = {} for i = 1, 200 do locator[i] = 0 end just assigning all to 0 inside a loop Before using them Credits : Egor Skriptunoff
{ "pile_set_name": "StackExchange" }
Q: PhoneGap audio issue I am having a small issue on PhoneGap, using the Media plugin to play audio. First of all, I will describe the page and I will include my codes below. I have multiple mp3 files. Each mp3 file will be played once their respective "Play" button is clicked. After implementing the codes, the mp3 files are playing correctly. However, I am having some issues and they are as follows: When I click on the "Play" button of an mp3 file, it does play. But when I click again to play it, it does not play. The mp3 files are only in some seconds. I want that once they complete, I can click again to play. If I play an mp3 file, the others do not play. My codes are as follows: JavaScript <script> // Wait for device API libraries to load document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { } // Audio player var mymedia = null; var audio = false; //Pause event document.addEventListener("pause", onPause, false); function onPause() { mymedia.stop(); audio = false; } // Play audio function playAudio(src) { if (audio === false) { mymedia = new Media(src, onSuccess, onError); mymedia.play(); audio = true; } } // onSuccess Callback function onSuccess() { console.log("playAudio():Audio Success"); } // onError Callback function onError(error) { } </script> HTML <a href="#" class="p" onclick="playAudio('/android_asset/www/one.mp3')"><img src="play.png" alt="play"/></a> <a href="#" class="p" onclick="playAudio('/android_asset/www/two.mp3')"><img src="play.png" alt="play"/></a> NOTE: I do not have Pause and Stop buttons. Again, the audio is playing but if I click again on the "Play" button, it does not play and if I click on another "Play" button of the other audio files, they do not play. I have little experience with this, so forgive me! Thank you! A: Set audio to false in onSuccess function
{ "pile_set_name": "StackExchange" }
Q: Splitting integer so that both sides are prime numbers The problem You're given an n number. Check if that n number can be splitted in half so that both sides of a | are prime numbers. Example: Input Output 223 2|23 123 Not possible to split. My Idea I was given an example of n number that has only three digits, and in that case it would be easy to finish the task, but it wasn't stated that n number is going to be three digits so that makes the problem much more complex, in my opinion. So if n could have m number of digits I'd do the next. Convert an integer n to array and then implement some sort of a divide and conquer algorithm. However, I'm not sure how am I going to compare each element to the rest of the element(s). Does anyone have any ideas how can I complete the algorithm? Also nothing is set in stone so any other suggestions would be more than welcome. Update Thanks to everyone I finished the algorithm. I will post my code below. #include <iostream> #include <cmath> using namespace std; int numberOfDigits(int n) { int digits = 0; if(n < 0) digits = 1; while(n) { n /= 10; digits++; } return digits; } bool isPrime(int n) { int isPrime = true; for(int i = 2; i <= sqrt(n); i++) { if(n % i == 0) { isPrime = false; break; } } if(isPrime && n > 1) return true; else return false; } int removeLastDigits(int n, int count) { return n / pow(10, count); } int getLastDigits(int n, int count) { return n % (int)pow(10, count); } void findPair(int n, int m) { int a = n; int b = m; int counter = 1; int digits = numberOfDigits(n); int arePrimes = 0; while(digits >= 1) { if(isPrime(a) && isPrime(b)) { cout << a <<"|" << b << endl; arePrimes = 1; break; } else { a = removeLastDigits(n, counter); b = getLastDigits(n, counter); counter++; digits--; } } if(arePrimes == 0) cout << "Not possible to split." << endl; } int main() { int n; cout << "Enter the number: "; cin >> n; findPair(n, 0); } A: First create the list of numbers to check based on the initial number. Example: 253 Assume split only once. The Numbers From the initial number: [2,53], [25,3] Note, one could do some de-duping here as well to avoid double processing the same number (Example: 111 only has two numbers 1, 11). Each of these "split pair" can be checked if each number is prime. If (IsPrime(2) and IsPrime(53)) => then true If (IsPrime(25) and IsPrime(3)) => then false (25 is not prime) So, just send each number to your IsPrime() number sieve. (Eratosthenes, etc.) In this case the numbers to check for prime are 2,53,25,3. Then "And Logic Gate" each split pair for the final answer. One could parallelize IsPrime() for multiple number processing at the same time. There are some shortcuts. If the original number ends in 4,6,8, or zero, any "split pair" will always evaluate to false since one of the numbers in the pair is even and never prime. (@Andres F., @user949300) So, one could do that check first rather than running all the numbers through the sieve as a short circuit to save CPU. I'm sure there are some other tricks as well.
{ "pile_set_name": "StackExchange" }
Q: Dynamic column name in function How do I create dynamic column names, that can be used in a trigger? I have a trigger function, that should update a value in a table. The columnname is created dynamicially. But when I run it, the error does not grasp the column name but instead the name of the variable. What the code should do was to create a column name example: p123 ERROR: column "column_name" of relation "col_extra_val_lookup" does not exist LINE 2: SET column_name = NEW.value The code I use is this: DECLARE column_name TEXT ; BEGIN column_name :='p'|| NEW.customer_column_id; UPDATE col_extra_val_lookup SET column_name = NEW.value WHERE col_extra_val_lookup.customer_id=NEW.customer_id; END A: You get values because that is the only thing referencing a data point is able to give. To get what your looking for you need dynamic SQL. What you are attempting is take a data value and create a column with that value (prefixed with 'p'). This is really a very bad plan. Since you have no way of knowing the value of customer_column_name before your trigger must also alter the table. But unless you have very strict control over that value you can wind up with very strange column names. The following shows one way of accomplishing what you requested. But before you do this I suggest you look here to see just what can happen, and if you are prepared to handle the possible consequences, at least with its current limitations (code). create or replace function really_bad_idea() returns trigger language plpgsql as $$ declare k_add_column constant text = 'alter table col_extra_val_lookup add column if not exists %I text'; k_update_lookup constant text = 'update col_extra_val_lookup set %I = $1 where customer_id = $2'; column_name character varying(63); -- normal Postgres max length for column name begin column_name = 'p'|| NEW.customer_column_id; execute format(k_add_column, column_name); execute format(k_update_lookup, column_name) using new.value, new.customer_id; return new; end; $$; Enjoy your side effects.
{ "pile_set_name": "StackExchange" }
Q: Making Loop in xPath() : Call to a member function xpath() on a non-object I want to making loop with xpath() with this function: function rs(){ $rs = array(); $cities = array("city1", "city2", "city3", "city4", "city5", "city6", "city7", "city8"); foreach ($cities as $value) { $rs[] = $xmls->xpath("area[city= '$value']"); } return $rs; } $rs = rs(); Edit: function meteor(){ $request_url = "http://meteoroloji.gov.tr/FTPDATA/analiz/sonSOA.xml"; $xml = simplexml_load_file($request_url) or die("feed not loading"); return $xml;} $xmls = meteor(); with print_r($rs); I have Fatal error: Call to a member function xpath() on a non-object. Is my function wrong? (Im not familliar with OOP) Thanks in advance A: $xmls is not in scope, as simple as that. Pass it as an argument (rs($xmls)), or set it as an attribute if this is a method from a class rather then a standalone function (and it if that would be more logical).
{ "pile_set_name": "StackExchange" }
Q: Trouble with Last Method in Rails Let me get started by saying I am a Rails newbie so I'm going to try and explain this the best that I can. As a reference, please see this thread which describes exactly what is happening to me, except the fix doesn't seem to be working. Problems with limit method in Rails 3.2 and hash ordering I have a database with events that I am trying to sort by the primary key "id". I tried following the Railscast on sortable table columns here: http://railscasts.com/episodes/228-sortable-table-columns The sorting works properly but the sort happens on the entire column instead of just the "last 50". Controller Code: def index @events = Event.order(sort_column + " " + sort_direction).page(params[:page]).last(50) @events = @events.sort_by(&:id) @events = Kaminari.paginate_array(@events).page(params[:page]).per(10) end def sort_column Event.column_names.include?(params[:sort]) ? params[:sort] : "event_id" end def sort_direction %w[asc desc].include?(params[:direction]) ? params[:direction] : "desc" end Application_helper: def sortable(column, title = nil) title ||= column.titleize direction = column == sort_column && sort_direction == "desc" ? "asc" : "desc" link_to title, :sort => sort_column, :direction => direction end Finally, in the index view, I call it like this: <th><%= sortable "event_id" %></th> I'm sorry if this question has already been answered, any help on this subject would be greatly appreciated. EDIT Thanks for the quick reply. I understand what you did there, but now I get an exception for some reason in my index view. undefined method `id' for #<Array:0x00000004170c10> Extracted source (around line #25): 22: <tbody> 23: <% @events.each do |event| %> 24: <tr> 25: <td><%= link_to event.id, event_path(event) %></td> 26: <td><%= event.event_date_time_local %></td> 27: <td><%= EventType.find(id = event.event_type_id).event_type %></td> 28: <td> A: You said "instead of the last 50" but that is all you are returning. The last 50 found items after sorting based on sort_column and direction. @events = Event.order(sort_column + " " + sort_direction).page(params[:page]).last(50) #Sorted the last 50 by sort_column and direction @events = @events.sort_by(&:id) #sorted again by id and lost the first sort To get all events and then sort the last fifty you can do @events = Event.order(sort_column + " " + sort_direction).page(params[:page]) last_fifty = @events.pop(50) # remove last 50 and return it @events << last_fifty.sort_by(&:id) # insert last fifty back sorted by id Edit: Sorry, instead of @events << last_fifty.sort_by(&:id) try @events.concat last_fifty.sort_by(&:id)
{ "pile_set_name": "StackExchange" }
Q: PIC measuring PWM pulse length I'm just getting started with PIC processors, driven mainly by a shortage of the simpler PICAXE from my local retailer. My question is, how do I read the length of a PWM pulse on a certain input pin (analogous to the PULSIN command on PICAXEs). I'm using the MPLab IDE, and the specific PIC in question is the 12F683. Secondly, (sorry to combine two questions into one), are there libraries out there that contain 'common' functions (PWM output, i2c support and the like)? Google's turning up dry-ish, but it seems to me that such libraries have to be out there, somewhere.... Thanks for any help! EDIT: the language is C, and the PWM signal is the output from a RC reciever intended for a servo, so, it is a 1-2 ms high pulse every 20 ms (if I understand that correctly) A: There are various ways to measure the width of incoming pulses. Which is most appropriate depends on the width of the pulses, what accuracy you need, and which peripherals your PIC has. Some possibilities are: Use two CCP modules in capture mode. This is not possible for your particular PIC since it has only one CCP module, I'll mention it anyway for others or in case you change the PIC. A CCP module in capture mode grabs a snapshot of the free running 16 bit timer 1 on the edge of a I/O pin. With two of these captures, one for each edge, you subtract them to get the pulse duration. This method allows for the shortest duration pulses and has the most accuracy, but takes two CCP modules. Use a single CCP module and flip the edge it captures on in a interrupt triggered by the first capture. This has the same accuracy and resolution as #1 and uses only a single CCP module, but requires the pulse to be some minimum width so that the interrupt routine has time to grab the captured value switch the capture edge polarity. Capture the free running timer 1 in firmware every edge, then do the subtraction as in #1 and #2. This requires no CCP module at all, but there must be some minimum time between edges for the interrupt routine to do its job. It also has a bit more error due to some uncertainty in the interrupt response, and possibly in variable number of instructions from the interrupt routine if not coded carefully. Gate timer 1 from the pulse. Have the trailing edge cause a interrupt, which then reads the timer 1 value and possibly resets it ready for the next pulse. This has good accuracy and resolution, but requires some minimum time between pulses for the interrupt to grab the timer 1 value and set up for the next pulse. There are other methods too, but without knowing more about the characteristics of your pulses it's not worth spending time on them. Given that your PIC has a single CCP module and timer 1 with gating option, methods 2 and 4 are worth considering. Again, it would help to know more about the pulse characteristics. One thing I didn't metion is overflow handling for long pulses, but if your pulses are known to be short enough this is not a issue.
{ "pile_set_name": "StackExchange" }
Q: Image Gallery in Fragment Error I'm trying to make an app with an image gallery in it inside a fragment, but not getting errors in the code but getting this error below. Any help would be awesome, only a beginner. If you wish any more details just ask. Think its something to do with the 34th line which is: GridView gridview = (GridView) getView().findViewById(R.id.gridview); Code: public class Fragment_3 extends Fragment{ private static View view; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (view != null) { ViewGroup parent = (ViewGroup) view.getParent(); if (parent != null) parent.removeView(view); } try { view = inflater.inflate(R.layout.fragment_3, container, false); } catch (InflateException e) { } GridView gridview = (GridView) getView().findViewById(R.id.gridview); gridview.setAdapter(new ImageAdapter(this.getActivity())); gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Toast.makeText(Fragment_3.this.getActivity(), "" + position, Toast.LENGTH_SHORT).show(); } }); return view; } public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); } else { imageView = (ImageView) convertView; } imageView.setImageResource(mThumbIds[position]); return imageView; } // references to our images private Integer[] mThumbIds = { R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7, R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7, R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7 }; } } Error 06-24 14:02:27.385: E/AndroidRuntime(3959): FATAL EXCEPTION: main 06-24 14:02:27.385: E/AndroidRuntime(3959): java.lang.NullPointerException 06-24 14:02:27.385: E/AndroidRuntime(3959): at com.bottlecapp.ahmetmikko.Fragment_3.onCreateView(Fragment_3.java:34) 06-24 14:02:27.385: E/AndroidRuntime(3959): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460) 06-24 14:02:27.385: E/AndroidRuntime(3959): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911) 06-24 14:02:27.385: E/AndroidRuntime(3959): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088) 06-24 14:02:27.385: E/AndroidRuntime(3959): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682) 06-24 14:02:27.385: E/AndroidRuntime(3959): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444) 06-24 14:02:27.385: E/AndroidRuntime(3959): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429) 06-24 14:02:27.385: E/AndroidRuntime(3959): at android.os.Handler.handleCallback(Handler.java:725) 06-24 14:02:27.385: E/AndroidRuntime(3959): at android.os.Handler.dispatchMessage(Handler.java:92) 06-24 14:02:27.385: E/AndroidRuntime(3959): at android.os.Looper.loop(Looper.java:137) 06-24 14:02:27.385: E/AndroidRuntime(3959): at android.app.ActivityThread.main(ActivityThread.java:5041) 06-24 14:02:27.385: E/AndroidRuntime(3959): at java.lang.reflect.Method.invokeNative(Native Method) 06-24 14:02:27.385: E/AndroidRuntime(3959): at java.lang.reflect.Method.invoke(Method.java:511) 06-24 14:02:27.385: E/AndroidRuntime(3959): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 06-24 14:02:27.385: E/AndroidRuntime(3959): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 06-24 14:02:27.385: E/AndroidRuntime(3959): at dalvik.system.NativeStart.main(Native Method) A: Is there a reason why you have a try catch block on your onCreate resulting in returning a View? Syntax wise you don't need getView() on your GridView, you can just do GridView gridview = (GridView) findViewById(R.id.gridview); But it looks like you are getting a NullPointerException. Can you let us know what line 34 is?
{ "pile_set_name": "StackExchange" }
Q: Use output as an input on the next loop I need to have an outcome like this: example the user input are principal = 2000, term=6, rate=2% Period Interest Total Interest Total Balanced<br> 1 6.66 6.66 2006.60 2 6.69 13.35 2013.35 3 6.71 20.06 2020.06 4 6.74 26.80 2026.80 5 6.75 33.55 2033.55 6 6.78 40.33 2040.33 My code is: import java.io.*; public class interest { public static void main(String[] args)throws Exception { BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in)); float p, t, r, total; int a = 1; System.out.println("Enter the amount deposited: "); p = Integer.parseInt(bufferedreader.readLine()); System.out.println("Enter the number of term: "); t = Integer.parseInt(bufferedreader.readLine()); System.out.println("Enter the interest rate(%): "); r = Integer.parseInt(bufferedreader.readLine()); System.out.println("Period \t Interest Total Interest Total Balance"); while ( a &lt;= t) { System.out.print(" " + a + "\t "); a++; { float R = (float) (r/100)/t; float interest = (float) p * R; float totalInt = (float) interest ; total = p + totalInt; System.out.println(interest + "\t\t" + totalInt + "\t " + total); } } } } but the outcome turns up like this: Period Interest Total Interest Total Balance 1 6.6666665 6.6666665 2006.6666 2 6.6666665 6.6666665 2006.6666 3 6.6666665 6.6666665 2006.6666 4 6.6666665 6.6666665 2006.6666 5 6.6666665 6.6666665 2006.6666 6 6.6666665 6.6666665 2006.6666 A: Move your totalInt declaration outside of your while declaration. You're currently resetting it in every loop, thus it's not actually your total interest but your current interest. You need to do: totalInt += interest; in the loop. And you don't need to cast interest to a float again for the increment, as it's already declared as a float. Also it might be cleaner to do total += interest rather than starting out from your base deposit and incrementing it with your totalInt every time. And as to your last issue, the formatting, just do something along the lines of: System.out.printf("%.2f \t\t %.2f \t\t %.2f\n", interest, totalInt, total); Or take a look at DecimalFormat
{ "pile_set_name": "StackExchange" }
Q: Wildcard Text Index and inherited schemas I have 1 root schema and 4 inherited schemas using a discriminatorKey http://mongoosejs.com/docs/discriminators.html In this scenario I'm not clear if I can use a wild card text index. The purpose is to index all the string fields of each inherited schema independently. https://docs.mongodb.org/manual/core/index-text/ EDIT Adding this myRootSchema.index({ "_type": 1, "$**": "text" }); on my mongoose root schema I get this error when I try to query. Should I repeat this on the inherited schemas too? { "name": "MongoError", "message": "error processing query: ns=MYDB.caseNotesTree: TEXT : query=title, language=english, caseSensitive=0, diacriticSensitive=0, tag=NULL\nSort: {}\nProj: {}\n planner returned error: failed to use text index to satisfy $text query (if text index is compound, are equality predicates given for all prefix fields?)", "waitedMS": 0, "ok": 0, "errmsg": "error processing query: ns=MYDB.caseNotesTree: TEXT : query=title, language=english, caseSensitive=0, diacriticSensitive=0, tag=NULL\nSort: {}\nProj: {}\n planner returned error: failed to use text index to satisfy $text query (if text index is compound, are equality predicates given for all prefix fields?)", "code": 2 } the query: Model .find( { $text : { $search :req.query.q } } ) .exec(function(err, data) { if(err)res.json(err) res.json(data) }); A: To efficiently utilize a wildcard index with inherited schemas, you'd want to use a compound text index using the kind discriminator field as the leading field in the index: { kind: 1, "$**": "text" }
{ "pile_set_name": "StackExchange" }
Q: finally { if (inputStream != null) { inputStream.close(); I don't know how to understand this: { if (inputStream **!= null**) { inputStream.close(); from that example: public class CopyLines { public static void main(String[] args) throws IOException { BufferedReader inputStream = null; PrintWriter outputStream = null; try { inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream = new PrintWriter(new FileWriter("characteroutput.txt")); String l; while ((l = inputStream.readLine()) != null) { outputStream.println(l); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } }} inputStream is beeing closed when there is any data provided??? A: It means that whenever the try block is completed (successfully or not) it will try to close the streams (inputStream and outputStream) in the finally block but as the try block could fail while creating the instance of BufferedReader or PrintWriter, you need to check first if it is not null otherwise you will get a NPE. You can consider using try-with-resouces statement to avoid having to check if null and calling close() explicitly such that it would simplify your code a lot. try (BufferedReader inputStream = new BufferedReader(new FileReader("xanadu.txt")); PrintWriter outputStream = new PrintWriter(new FileWriter("characteroutput.txt")) { // your code here }
{ "pile_set_name": "StackExchange" }
Q: Debugging and understanding code with possible dynamic function creation I am trying to run the following python package, python-searchengine. However running the shell command python -m searchengine.main '"Python Search Engine" GitHub -bitbucket' throws the error AttributeError: 'SearchEngine' object has no attribute 'search' which I think is correct as the class SearchEngine class SearchEngine(object): """ """ def __init__(self, *args, **kwargs): pass has no property called search I would have called that code buggy, but the project seems to have some forks and watches, which makes me rethink about my understanding of python. I am quite new to python, so it could be that I am missing out some vital clue, something like the function is getting created dynamically ! Can someone explain, how this function searchengine def searchengine(query, *args, **kwargs): search_engine = SearchEngine(*args, **kwargs) search_engine.search(query) supposed to work! A: If you look at the readme there is header: NB: UNDER DEVELOPMENT Also this repository is 9 years old. The code is incomplete and there are only two commits to this file. That would suggest project is just unfinished and this portion of code doesn't yet work (and won't ever work). So you should try looking for an alternative.
{ "pile_set_name": "StackExchange" }
Q: static side menu scroll in bootstrap I am using admin template from http://startbootstrap.com/templates/sb-admin-v2/ but I found that if side menu items get more than page hight there is no scroll, how can I add scroll to static side menu when menu items or page height is changed? like http://responsiweb.com/themes/preview/ace/1.3/ You may change your browser height to see the problem. A: Just use a scroll plugin like niceScroll and use this code: var sideMenuCheck = function () { var ss = $("#side-menu"); ss.css({ 'height': ss.height() + 'px' }); document.body.style.overflow = "hidden"; var viewportHeight = $(window).height(); document.body.style.overflow = ""; var menuParent = ss.parent(); menuParent.css({ 'height': (viewportHeight - 50) + 'px', 'overflow': 'hidden' }); menuParent.niceScroll(); }; $(document).ready(function () { sideMenuCheck(); }); $(window).resize(function () { sideMenuCheck(); }); Note: This answer was posted on behalf of the OP.
{ "pile_set_name": "StackExchange" }
Q: For which number of pairs is it an advantage to start in memory Players A and B play memory starting with $n$ pairs of cards. We assume that they can remember all cards which have been turned. At his turn a player will first recall if two cards already turned match. If so he will choose such a pair, turn them and get a pair. If not he will turn uniformly at random a card which has not yet been turned. Then if the corresponding match has turned already he will turn that card and get a pair. If not he will again turn uniformly at random a card which has not yet been turned. As usual if a player gets a pair he can continue. Player A will start. For which $n$ does Player A have an advantage by being able to start and for which $n$ is it actually a disadvantage? Here is what I considered so far: If $E_{k,l}$ denotes the expected number of pairs the starting player will get when $k$ cards are known and $l\geq k$ cards are unknown one can derive the following recursion formula $$ E_{k,l}=\frac{k}{l} \left( E_{k-1,l-1}+1 \right)\\ +\frac{(l-k)}{l} \frac{1}{(l-1)} \left( E_{k,l-2}+1 \right)\\ +\frac{(l-k)}{l} \frac{k}{(l-1)} \left( \frac{k+l}{2}-1-E_{k,l-2} \right)\\ +\frac{(l-k)}{l} \frac{(l-k-1)}{(l-1)} \left( \frac{k+l}{2}-E_{k+2,l-2}\right). $$ Furthermore we have $E_{k,k}=k$. The expected number of pairs players $A$ resp. $B$ will get are $E_{0,2n}$ resp. $n-E_{0,2n}$. The following list show the expected number of pairs for A and B for $n\leq 24$. It seems that for larger $n$ the expected number of pairs for $A$ and $B$ are closer together. Can this be proven rigorously? For $n=18$ the expected number of pairs of $A$ and $B$ are equal and the game is fair in some sense. Do there exist other numbers $n$ with that property? Is it possible to give a characterization of the numbers for which $A$ has an advantage? A has an advantage for $n\in \{ 1,4,7,8,10,11,14,17,18,20,21,23,24,\dots\}$. B has an advantage for $n\in \{ 2,3,5,6,12,13,15,16,19,22,\dots\}$ Octave code: n=50; A=diag(0:n-1);A(1,3)=1; for s=4:2:n-1 for l=s/2+1:s k=s-l; if k>0 A(k+1,l+1)=k/l*(1+A(k,l)); end if l>k A(k+1,l+1)=A(k+1,l+1)-(l-k)/l*k/(l-1)A(k+2,l); end if l>k+1 A(k+1,l+1)=A(k+1,l+1)-(l-k)/l(l-k-2)/(l-1)A(k+3,l-1); end if l>k && l>2 A(k+1,l+1)=A(k+1,l+1)+(l-k)/l/(l-1)(1+A(k+1,l-1)); end end end B=zeros(n/2-1,3); for i=1:n/2-1 B(i,:)=[i (i+A(1,2*i+1))/2 (i-A(1,2*i+1))/2]; disp([num2str(i) ':' num2str(A(1,2*i+1)) ' ' num2str((i+A(1,2*i+1))/2)]); end B(:,1) rats(B(:,2)) rats(B(:,3)) Awins=''; Bwins=''; for i=1:n/2-1 if A(1,2*i+1)>0 Awins=[Awins ',' num2str(i)]; else Bwins=[Bwins ',' num2str(i)]; end end Awins Bwins A: This problem has been studied (and solved for many values) in this MSc thesis: Erik Alfthan: Optimal strategy in the childrens game Memory. He defines four strategies: Bad: open a known card, then an unknown that may match, Safe: open an unknown card, then a known card, matching if possible, Risky: open an unknown card, then match if possible, i.e. an known matching card if possible, otherwise an unknown card that may match, Passive: open two, known, unmatching cards. He proves that you should never play 'Bad' and there are situation when 'Passive' would be needed (easy example: 100 pairs and 99 unmatched cards are known, i.e., there's only 1 unknown pair), so the game would never terminate, so he disallows this strategy, i.e., players need to open with an unknown card. I copy here my favorite table, followed by open problems. n = number of pairs on board j = number of unknown pairs Chosen strategy, 1 : risky, 0 : safe, # : no choice   j:0 1 2 3 4 5 6 7 8 9 ... n 2 # 1 # 3 # 1 0 # 4 # 1 0 1 # 5 # 1 0 1 0 # 6 # 1 0 1 0 0 # 7 # 1 0 1 0 0 1 # 8 # 1 0 1 0 0 1 0 # 9 # 1 0 1 0 0 0 0 0 # 10 # 1 0 1 0 1 0 1 0 1 # 11 # 1 0 1 0 1 0 1 0 1 0 # 12 # 1 0 1 0 1 0 0 0 1 0 1 # 13 # 1 0 1 0 1 0 0 0 1 0 1 0 # 14 # 1 0 1 0 1 0 0 0 1 0 1 0 1 # 15 # 1 0 1 0 1 0 0 0 1 0 1 0 1 0 # 16 # 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 # 17 # 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 # 18 # 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 # 19 # 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 # 20 # 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 # The pattern of the table continues, computation with as many as 200 pairs, renders that, except for very small boards, the strategy should be Safe when $j$ is even and Risky when $j$ is odd. Conjecture 1. [Alfthan] Except for smaller boards, $n < 16$, the optimal strategy is to use the risky strategy when $j$ is odd and safe strategy when $j$ is even. Conjecture 2. [Alfthan] Except for smaller $j$, $j < 18$, the expected number of gained cards is monotone in $n$ for fixed $j$, growing if $j$ is even and declining if $j$ is odd. Update: I've just discovered this nice blogpost about the same game: https://possiblywrong.wordpress.com/2011/10/25/analysis-of-the-memory-game/ This has a 5. possible strategy that Alfthan seems to have missed: NON: pick up a face-down card and, if its match is known, a non-matching face-up card (leaving a known pair on the table!), otherwise another face-down card. This might be advantageous in some cases, so if we allow this move, the above table gets changed! See the blogpost for details.
{ "pile_set_name": "StackExchange" }
Q: passing variables as arguments from excel VBA I use the following code for passing arguments to my script from VBA. Successful case: (argument value without space) FilePath = "c:\Users\dimension_export.exe" AppName = "Area_Sales" Call Shell(FilePath & " " & AppName, 1) Error case: (argument value with space ('')) FilePath = "c:\Users\dimension_export.exe" AppName = "Total Sales" Call Shell(FilePath & " " & AppName, 1) when I do this, only the Total part in the AppName variable is passed as a argument to my exe file. Is there any specific keyword or symbols I should pad up? A: Call Shell(FilePath & " " & AppName, 1) should be Call Shell(FilePath & " """ & AppName & """", 1) Any items with spaces (including the file path) should be enclosed in quotes
{ "pile_set_name": "StackExchange" }
Q: What's the best way to implement AdWords in Android app? What is the best way to handle Google AdWords in an Android app? I want to implement it like it's done in the New York Times Magazine app. A small banner that shows up in the top and show for a while then disappears. Once the banner has been displayed it needs to be registered with my AdWords account. Any feedback is welcome! A: It seems like there is a project for this in Google Labs.
{ "pile_set_name": "StackExchange" }
Q: Nine Patch Image in Android Game I am trying to use a nine patch image as a background in an android game. The image expands well in multiple resolutions but, my game has slowed down by 10 fps. I used to get a consistent 45 to 50 fps now I get 35 fps. The question is when we use a nine patch as a drawable and set it as a background in a view does it have any performance implications as opposed to a plain bitmap drawing. Thanks in advance. A: The question is when we use a nine patch as a drawable and set it as a background in a view does it have any performance implications as opposed to a plain bitmap drawing. If you are causing it to be stretched, then yes.
{ "pile_set_name": "StackExchange" }
Q: How can I see "rowcount" (?) of a textlabel in xamarin forms? I have a label in my XAML that I bind to my data and sometimes the text is longer than others and if the text is long enough to get into 2 rows, i want to adjust my code a little bit to make the UI look better. Is there a way to solve that in xamarin forms? XAML <Label x:Name = "title" /> CODE title.Text = Title; //title is a string cointaining the text. So do something with: if(title.text > 2 (rows?)) { //change the ui. } Or if there is a solution that sees if a label doesnt fit on a the row. so if i have a absolutelayout that only allows 1 row and the label recieves the "..." because it all cannot fit. can you do something with that? if (title.Text.Contains == "...") { // change size of label } A: No you can't do that like that, as xamarin forms uses "plaftorm renderers", specific to each platform, to render your string. In fact you have no way to know if your label will split on more than one line. What you can do is count the number of chars that can fit on one line on most devices, and customize your rendering based on this value. If you still want to compute the number of lines, you can do it using specific platform code that needs the width in point of your label. For example on iOS you will use NSString GetSizeUsingAttributes like described here: https://forums.xamarin.com/discussion/10016/measuring-string-width-getsizeusingattributes
{ "pile_set_name": "StackExchange" }
Q: Aws S3 InvalidAccessKeyId when adding more images months later I am attempting to add more assets to my production site, but first I began by attempting to add the image to my development site and when I attempted to save, I got this error: Aws::S3::Errors::InvalidAccessKeyId in PortfoliosController#update The AWS Access Key Id you provided does not exist in our records. Extracted source (around line #46): respond_to do |format| if @portfolio_item.update(portfolio_params) format.html { redirect_to portfolios_path, notice: 'The record was successfully updated.' } else format.html { render :edit } I have two other images that I successfully uploaded months ago and are still in my production site, so I do not know why its telling me the AWS Access Key Id I provided does not exist. A: can you confirm if the access key id is present in your production site? and whether the IAM role exists or not. And whether the access key in the IAM role exist or not. If you confirmed that, check that if your application really use that access key id and not other profiles. The assets is different from your access permission. The assets are the object and your .update method requires access permission. In this case, the assets exist and your access permission does not exist. That's why you cannot update the asset in your s3 bucket. Based on your comment, it seems that recreating the access key in the IAM role is the solution. Although, if you're using AWS product as the production server, try using roles instead of IAM credentials as it doesn't require any access key. Thus, one can say that it's more secure.
{ "pile_set_name": "StackExchange" }
Q: Swift optionals and their instantiation I'm new to Swift. I'll explain what I'm trying to do in Java terms and hopefully someone can help me understand. I want a class scoped array that is instantiated/set in viewDidLoad of a view controller. It sounds simple enough, but this is what I had to do to get it to work. Could someone explain to me why the _dictionary must be instantiated as an empty array and why I need to use as? when unpacking dictionary even though the componentsSeparatedByString function returns an array? Thanks. class ViewController: UIViewController, UITextFieldDelegate { var _dictionary : [String] = [] override func viewDidLoad() { super.viewDidLoad() let bundle = NSBundle.mainBundle() let path = bundle.pathForResource(“TextFile”, ofType: "txt") var err: NSError? let dico = NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: &err) if let dictionary = dico?.componentsSeparatedByString("\n") as? [String] { _dictionary = dictionary } else { println("Error reading dictionary") } } } A: _dictionary must be given an initial value because all instance properties must be given an initial value. That is a Swift safety feature to make sure that all instances are well-formed at birth. You could have done this by initializing _dictionary in an actual initializer, but you didn't. You chose to give it its first "real" value in viewDidLoad which is much later. Therefore you have forced yourself to supply a "fake" initial value until such time as viewDidLoad comes along and gives you a "real" initial value. I don't understand your other question because I don't know what "unpacking dictionary" means. But perhaps you are referring to the rest of the stuff in this code. I'll talk you through it. dico is an Optional wrapping a String. It is an Optional because the contentsOfFile: initializer of String returns an Optional - it is a failable initializer. That is because there might be no such file, or that file might not have that encoding, in which case the initializer needs to return nil. So now dico is an Optional wrapping a String that must be unwrapped - or nil. So you do unwrap it as dico? in the next line. dico? is a String at that point, assuming that dico was not nil. Then you call componentsSeparatedByString. It returns an array of AnyObject. So you have chosen to cast it down to an array of String using as?. I don't know why you chose to use as? since you know it will be an array of String if we get to this point - personally, I would have used as. But in any case, as? always returns an Optional! So you unwrap that, optionally, by using an if let conditional binding. The irony throughout is that _dictionary is not and never was or will be a dictionary - it is an array. Your name for this (and for dictionary) is very poorly chosen! dico is a String, and dictionary and _dictionary are arrays. There is not a dictionary in sight. Assuming we keep your rather odd names, though, you could have done all this much more briefly and clearly, like this: var err : NSError? if let dico = NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil) { _dictionary = dico.componentsSeparatedByString("\n") as [String] } else { println(err) } Moreover, if you start with the String class instead of the NSString class, then componentsSeparatedByString will be an array of String instead of an untyped NSArray (i.e. an array of AnyObject), and you can skip the cast: var err : NSError? if let dico = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil) { _dictionary = dico.componentsSeparatedByString("\n") } else { println(err) }
{ "pile_set_name": "StackExchange" }
Q: Difference between double auction and continuous double auction? What is the difference between double auction and continuous double auction? Sometimes I feel that they were types of two-sided auction but sometimes I feel as if they were two separate concepts. A: So, if a distinction is made, as continuous double auctions are usually just called double auctions, then the difference has to do with frequency. It is easier to have an example. The New York Stock Exchange is an example of a continuous double auction. Within its trading hours, you can bid in either direction as much or as often as you want and so can everyone else. The best example of an ordinary double auction was the Arizona Stock Exchange which closed in 2001. It only permitted two bids per day, at the open of US trading and at the close. It sought to solve an institutional liquidity problem. Certain types of institutions are at risk if they cannot clear their orders at or as near to as possible a particular moment in time. Mutual funds, for example, usually only have one valuation per day and if there need to be a lot of transactions from redemption or purchase activity, then the least risk is to have the trade near that time. Most are at the open or close. The Arizona exchange found the single price that cleared the largest number of trades. You paid a fee to participate. There was no bid-ask spread. So possibly hundreds of customers would place their limit orders at the same time as buyers or sellers. What they did in practice was create single supply curve and a single demand curve and the price paid/received was the intersection of the two curves.
{ "pile_set_name": "StackExchange" }
Q: How to delete a line from a file after it has been used I'm trying to create a script which makes requests to random urls from a txt file e.g.: import urllib2 with open('urls.txt') as urls: for url in urls: try: r = urllib2.urlopen(url) except urllib2.URLError as e: r = e if r.code in (200, 401): print '[{}]: '.format(url), "Up!" But I want that when some url indicates 404 not found, the line containing the URL is erased from the file. There is one unique URL per line, so basically the goal is to erase every URL (and its corresponding line) that returns 404 not found. How can I accomplish this? A: The easiest way is to read all the lines, loop over the saved lines and try to open them, and then when you are done, if any URLs failed you rewrite the file. The way to rewrite the file is to write a new file, and then when the new file is successfully written and closed, then you use os.rename() to change the name of the new file to the name of the old file, overwriting the old file. This is the safe way to do it; you never overwrite the good file until you know you have the new file correctly written. I think the simplest way to do this is just to create a list where you collect the good URLs, plus have a count of failed URLs. If the count is not zero, you need to rewrite the text file. Or, you can collect the bad URLs in another list. I did that in this example code. (I haven't tested this code but I think it should work.) import os import urllib2 input_file = "urls.txt" debug = True good_urls = [] bad_urls = [] bad, good = range(2) def track(url, good_flag, code): if good_flag == good: good_str = "good" elif good_flag == bad: good_str = "bad" else: good_str = "ERROR! (" + repr(good) + ")" if debug: print("DEBUG: %s: '%s' code %s" % (good_str, url, repr(code))) if good_flag == good: good_urls.append(url) else: bad_urls.append(url) with open(input_file) as f: for line in f: url = line.strip() try: r = urllib2.urlopen(url) if r.code in (200, 401): print '[{0}]: '.format(url), "Up!" if r.code == 404: # URL is bad if it is missing (code 404) track(url, bad, r.code) else: # any code other than 404, assume URL is good track(url, good, r.code) except urllib2.URLError as e: track(url, bad, "exception!") # if any URLs were bad, rewrite the input file to remove them. if bad_urls: # simple way to get a filename for temp file: append ".tmp" to filename temp_file = input_file + ".tmp" with open(temp_file, "w") as f: for url in good_urls: f.write(url + '\n') # if we reach this point, temp file is good. Remove old input file os.remove(input_file) # only needed for Windows os.rename(temp_file, input_file) # replace original input file with temp file EDIT: In comments, @abarnert suggests that there might be a problem with using os.rename() on Windows (at least I think that is what he/she means). If os.rename() doesn't work, you should be able to use shutil.move() instead. EDIT: Rewrite code to handle errors. EDIT: Rewrite to add verbose messages as URLs are tracked. This should help with debugging. Also, I actually tested this version and it works for me.
{ "pile_set_name": "StackExchange" }
Q: PHP include functions and AJAX div loading I have a php generated web page, which has several divs that are initially created using php includes. <div id ="siteLeft" class ="site"> <div id="divGauges"><?php include('gauges.php');?></div> <div id="divHistory"><?php include('history.php');?></div> </div> <div id="siteRight" class ="site"> <div id="divLymGauges"><?php include('gaugesLym.php');?></div> <div id="divLymHistory"><?php include('historyLym.php');?></div> </div> These divs are then reloaded every 10 seconds, using an AJAX call, which is in a seperate scripts.js file: function updateHistory(){ $('#divHistory').load('history.php'+"?ms=" + new Date().getTime()); $('#divLymHistory').load('historyLym.php'+"?ms=" + new Date().getTime()); } setInterval( "updateHistory()", 10000 ); Within the history.php and historyLym.php, I have a function call, and the function is in another file called functions.php. If I do: include ('functions/functions.php'); within the index.php page, then the div's display nicely on initial load, but I get Fatal error: Call to undefined function displaying on the webpage after the AJAX call refreshes the div with the history.php and historyLym.php (obviously, as the include for the function file isn't in the div, which is the only bit that gets called). So I tried putting the functions.php include into the divs that are loaded. If I do that, then on initial page load I get: Fatal error: Cannot redeclare getForce() which also makes sense, as on initial load the two divs both contain the include for functions.php. Putting the include in only one of the divs results in the page loading fine (as it should do), but on the AJAX refresh of the divs, I get this error: Fatal error: Call to undefined function getForce() which again makes sense as the two divs are being refreshed independently by AJAX, and so only the div with the include for functions.php will be able to use the function. So my questions is: Where on earth can I put the include for functions.php so that the divs can use the functions.php functions on initial page load AND on individual seperate AJAX refreshes?? A: First include the function file in your index.php, Then add this at the top of your include files (ie: gauges.php, history.php, etc..) <?php if ( !function_exists( "getForce" ) ) { // include the function file } ?> You can replace getForce with any other function names which is defined in your function file
{ "pile_set_name": "StackExchange" }
Q: java servlet information I am new to java servlets. I studied some code about servlet but I really want to know more basic things and how it works. I just wonder what type of material/content can be sent from java servlet to a browser. Like http request or something? And how does brower know how to deal with this material? In addtion, for java bean. I know it is a java class. But, what is the purpose behind the development of the java bean concept. A: You need to do some background reading, start with something such as this tutorial We can answer specific questions when you get stuck, but conceptual material is not best addressed by a Q&A site such as this. We usually use servlets that understand the HTTP protocol, so a browser sends an HTTP request, the servlet sends a response. Often the response is in the form of HTML which browsers know how to render into a nice human-readable page. Java Beans: don't worry about them yet, just think of them as yet another Java Class. A: What type of material/content can be sent from java servlet to a browser? A servlet can return any kind of data to the browser (or whatever else made the request). The data is wrapped in a ServletResponse object, usually a HttpServletResponse. The response contains both the actual data and also meta data in the form of response headers, although we are now moving into the realm of HTTP, rather than servlets. You know how HTTP works, right? Yo How does brower know how to deal with this material? The response headers typically hint to the browser what type of data the response is, whether it is text, html, XML, etc. This is given by the response header called Content-Type. Again this is standard HTTP stuff, not really specific to servlets. What is the purpose behind the development of the java bean concept? The java bean standard is a convention used for writing POJOs. There are many tools that are specifically designed to work with classes written to the java bean standard. In relation to servlets and HTTP, the best example is probably JSTL, which allows you to access objects in a JSP so long as they follow the bean standard.
{ "pile_set_name": "StackExchange" }
Q: SWIG for JavaScript: "Module did not self-register." on load With SWIG 3.0.12 and node 8.12.0 I want to create a native module from some minimal code base: api.h: #pragma once #include <string> std::string foo(); api.cpp: #include "api.h" std::string foo() { return "hello world"; } api.i: %module(directors="1") api %{ #include <api.h> %} %include "api.h" to build the node-module I run: swig -c++ -javascript -node api.i g++ -c -fPIC api_wrap.cxx api.cpp -I /usr/include/node -I . g++ -shared *.o -o api.node .. and try to import it: node -e "api = require('./api.node');" But now I get module.js:682 return process.dlopen(module, path._makeLong(filename)); ^ Error: Module did not self-register. at Object.Module._extensions..node (module.js:682:18) at Module.load (module.js:566:32) at tryModuleLoad (module.js:506:12) at Function.Module._load (module.js:498:3) at Module.require (module.js:597:17) at require (internal/module.js:11:18) at [eval]:1:7 at ContextifyScript.Script.runInThisContext (vm.js:50:33) at Object.runInThisContext (vm.js:139:38) at Object.<anonymous> ([eval]-wrapper:6:22) I found lot's of questions and answers regarding similar errors but they all seem to be related to npm and incorrect versions of node modules and the node runtime. What do I do wrong? A: Unfortunately, the current release of swig (3.0.12) does not support Node.js versions 7 or later. Instead, you get compile-time errors like error: no template named 'WeakCallbackData' in namespace 'v8' To use swig with Node 8, either use the master branch, a later version of swig (it looks like this will be fixed in the next release, which will likely be 3.0.13), or download the 4 files changed in PR 968 and install them in place of the ones that came with swig 3.0.12. On my Mac, those files are in /usr/local/Cellar/swig/3.0.12/share/swig/3.0.12/javascript/v8/ After that, though, @frans still has some work to do. According to the SWIG documentation, "it is crucial to compile your module using the same compiler flags as used for building v8", for which they recommend building your module with node-gyp. You need to create a binding.gyp like this: { "targets": [ { "target_name": "api", "sources": [ "api.cpp", "api_wrap.cxx" ] } ] } and then, after creating the wrapper with swig, build the module with node-gyp configure build (If necessary, install node-gyp with npm install -g node-gyp) You probably also do not want %module(directors="1") for JavaScript, and you should not use the bracket style include <file.h> for your own header files. Also, if you want to use std::string, you need to include std_string.i in your interface file. I suggest your api.i would be better as %module api %{ #include "api.h" %} %include "std_string.i" %include "api.h" Finally, when you are done, the module will be in ./build/Release, so test with node -e "api = require('./build/Release/api.node'); console.log(api.foo());"
{ "pile_set_name": "StackExchange" }
Q: VB.NET QueryString I am using datagrid and I have a <asp:TemplateField> I have passed some parameters in it the code is as follow: <asp:TemplateField HeaderText="Download"> <ItemTemplate> <asp:LinkButton ID="lnkname" runat="server" Text="Download" PostBackUrl='<%#"~/logout.aspx?ID="+Eval("ID")+"&category=mobile"%>'></asp:LinkButton> </ItemTemplate> </asp:TemplateField> I have numeric field (ID) which i need to send through URL I have tried to send the String type data and its working fine but while I am sending numeric type (ID) I am facing this error Conversion from string "~/logout.aspx?ID=" to type 'Double' is not valid I know something I need to change in the syntax near Eval("ID"). How should I send numeric data in query string? Thanks A: <asp:TemplateField HeaderText="Download"> <ItemTemplate> <asp:LinkButton ID="lnkname" runat="server" Text="Download" PostBackUrl='<%# String.Format("~/logout.aspx?ID={0}&category=mobile", Eval("ID")) %>'></asp:LinkButton> </ItemTemplate> </asp:TemplateField>
{ "pile_set_name": "StackExchange" }
Q: If all directional derivatives of $f$ in point $p$ exist, is $f$ differentiable? I am a little bit confused by the various theorems concerning the differentiability of a multivariable function. Let $f : D \subseteq R^n \to R$ have all directional derivatives in point $p$. Does it directly imply that $f$ is differentiable in $p$? I know that the opposite is true: If $f$ were differentiable, it would imply that it has directional derivatives. A: No, this is not true. Take, for instance$$\begin{array}{rccc}f\colon&\mathbb{R}^2&\longrightarrow&\mathbb{R}\\&(x,y)&\mapsto&\begin{cases}\frac{x^2y}{x^4+y^2}&\text{ if }(x,y)\neq(0,0)\\0&\text{ otherwise.}\end{cases}\end{array}$$You can check that, at $(0,0)$, every directional derivative is $0$. However, $f$ is not differentiable there.
{ "pile_set_name": "StackExchange" }
Q: C program to call pam_passwdqc.so and report password strength, pass/fail Is it possible (and where would I find the interface documentation) to write a simple C program to use pam_passwdqc.so to determine if a potential password will be strong enough to pass muster under passwd? A: I think what you actually want is libpasswdqc, which is the stand alone version of the PAM module. The source / download links are at the middle of the page(note, if you just want the checking functionality, you probably just want the library). The file INTERNALS points you to the header, which is brief and self explanatory. The file pwqcheck.c illustrates pretty much what you want to accomplish. At least on my Ubuntu workstation, I could not find a package that didn't also install all of the PAM bits. The stand alone library is small enough to drop into almost any tree, if the dependency would be problematic for you. Then again, you could try linking to the DSO, The interface might be the same. The way my OS packages it, it's kind of hard to tell. The library uses the most permissive version of the BSD license that I've ever seen, so dropping it in place is a non-issue: Redistribution and use in source and binary forms, with or without modification, are permitted. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
{ "pile_set_name": "StackExchange" }
Q: Array of floats throws "incomplete type is not allowed" I'm still fairly new to C++, so maybe its a very simple error I made here. I wanted to initialize a private float array in one of my classes, like this. float firstVect[] = {0.0f,0.0f,0.0f}; but firstVect is underlined with the explanation of incomplete type. On the other hand two lines below the float array i have an int array looking like this: int normalNumberOfDigits[]= {0,0,0}; The compile does not complain about the int array but only about the float array. Why? Full code of my class: class DataFilter { public: int filterMovement(float vect3[3]) { //TBD } private: float firstVect[] = {0.0f,0.0f,0.0f}; int initialized = 0; int normalNumberOfDigits[]= {0,0,0}; int determinNumberOfDigits(float testValue) { //TBD } }; A: Compiling with a modern version of clang++ makes your mistake obvious: error: array bound cannot be deduced from an in-class initializer You need to explicitly specify the size of the arrays (if you want to use a C-style array) in your class initialization: class DataFilter { // ... float firstVect[3] = {0.0f,0.0f,0.0f}; int initialized = 0; int normalNumberOfDigits[3]= {0,0,0}; // ... }; "The compile does not complain about the int array but only about the float array. Why?" Compiling with a modern version of g++ makes this obvious as well: error: flexible array member DataFilter::normalNumberOfDigits not at end of class DataFilter When you declare an array without an explicit size, the compiler thinks that it is a flexible array, which is a C-only feature. It seems to be allowed in C++ as a non-standard g++ extension.
{ "pile_set_name": "StackExchange" }
Q: Is an array of length 1 the same size as a single variable of the same type? Fairly basic question, imagine int a = 5; int[] b = new int[1]; b[0] = 5; Do both a and b take up the same space in memory? I assume b is larger than a as it has to store the length of itself somewhere, so I thought it would be IntPtr.Size larger, but I am not sure. I am trying to write code where the length of the array is determined at runtime, and can be 1 or larger (<10). I didn't know if I should just make an array if the length is set to one, or to have a special case in the code and just use the underlying type for length == 1. I know that a is a value type while b is a reference type. A: No, a and b will not occupy the same amount of memory. The array container is an object in its own right. It will, somewhere, have to store data pertaining to the number of elements it contains. So it will have a non-zero size.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to edit Home Assistant's configuration.yaml remotely? I just set up Home Assistant using HASSbian and am being told that I need to edit the configuration.yalm file, stored under ~/.homeassistant, to do a bunch of things. Is it possible to do that from the Chrome browser, or do I have to hook up to my Raspberry Pi manually? A: Turns out Terminal (on OSX) is the app to use. There, I start by typing: $ ssh pi@ip-address-of-pi (Excluding the "$" sign.) Then these three commands: $ sudo su -s /bin/bash homeassistant $ cd /home/homeassistant/.homeassistant $ nano configuration.yaml After doing my changes I press CTRL-X (written as "^X" in the Terminal window) and then in the Home Assistant page in Chrome, navigate to configuration and press restart, wait, and press restart again.
{ "pile_set_name": "StackExchange" }
Q: What is the correct way to center a text in a DIV button I've always wondered what the 'best' way to position text inside a div is 1) Put padding on the element surrounding the text and minus the padding from the height/width of the element. <div class="button"> Activate </div><!-- button --> .button { height: 20px; /* -10px from padding for text */ width: 90px; /* -10px from padding for text */ padding-left:10px; padding-right:10px; } 2) Put a span around the text, and position it as its own element. <div class="button2"> <span class="button2-text"> Activate </span> </div><!-- button2 --> .button2 { height: 30px width: 100px } .button2-text { padding-left:10px; padding-top:10px; } I always go with 1) because its less code, but I feel 2) is more proper or something Wondering if I'm in the wrong for using method 1) in any way. A: Your second option doesn't mix the height / width with the padding. Nowadays browsers all follow the same box model (which is how you position in option 1). This is equivalent to having box-sizing: content-box. Internet Explorer versions up to 6 and Quirks mode didn't and used the alternative one which included padding as part of the width, equivalent to box-sizing: border-box. In order to correctly position for both models, using option 2 is the safest. If you check http://jsfiddle.net/stb5a/ , box-sizing is set to content-box. Changing it to border-box doesn't change the positioning of the text; So basically, option 2 would be used for compatibility with older versions of Internet Explorer (now pretty much gone) and by developers who use to code for these versions, using the same pattern as they've always done.
{ "pile_set_name": "StackExchange" }
Q: BluetoothLeScanner null object reference I have a problem regarding my Bluetooth app. When I enable Bluetooth before starting up the app everything works alright. But when I don't, my app will ask permission to enable Bluetooth via the turnOn method. But when I press my onScan button I get a error stating: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.le.BluetoothLeScanner.startScan(android.bluetooth.le.ScanCallback)' on a null object reference here is my onCreate method: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Set layout setContentView(R.layout.activity_main); //Bluetooth // BluetoothManager final BluetoothManager BTManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); BTAdapter = BTManager.getAdapter(); // BluetoothLescanner BTScanner = BTAdapter.getBluetoothLeScanner(); //Turn on BT turnOn(); //Ask permission for location. requestPermission(); } My ques is that, BTScanner is made before the turnOn method is called, making the BTScanner a null object. Any help regarding this problem would be greatly. Kind regards, Binsento A: Try this (taken from one of my projects): Class variable: private BluetoothAdapter mBtAdapter = null; Inside onCreate: final BluetoothManager btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBtAdapter = btManager.getAdapter(); checkBt(); // called at the end of onCreate The checkBt() method: private void checkBt() { if (mBtAdapter == null || !mBtAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } } Then from there when the "Scan" button is clicked: public void onScanButton(){ if (mBtAdapter.isEnabled()){ scanLeDevice(true); } } Then scanLeDevice calls mBtAdapter.startLeScan(mLeScanCallback); NOTE: Some of this is now deprecated but can be updated to comply with the new API. I have not taken the time to do that.
{ "pile_set_name": "StackExchange" }
Q: как построить график двух функций по таблице Есть некоторая таблица экспериментальных данных в формате csv. Я её импортирую следующим образом: >>> import pandas as pd >>> df = pd.read_csv('data.csv', sep=',') >>> df 'Set' 'Rx' 'Traffic' 'Modulation' 0 -67.0 -64.35 15.00 '64-QAM 2/3' 1 -68.0 -65.35 15.00 '16-QAM 3/4' 2 -69.0 -66.85 14.78 '64-QAM 2/3' 3 -70.0 -67.60 15.42 '64-QAM 2/3' 4 -71.0 -68.85 15.04 '64-QAM 2/3' 5 -72.0 -70.35 15.04 '16-QAM 3/4' 6 -73.0 -70.85 15.04 '16-QAM 3/4' 7 -74.0 -71.35 15.28 '16-QAM 3/4' 8 -75.0 -72.60 12.35 '64-QAM 2/3' 9 -76.0 -73.10 11.38 '16-QAM 3/4' 10 -77.0 -74.60 11.64 '16-QAM 3/4' 11 -78.0 -75.60 7.76 '16-QAM 1/2' 12 -79.0 -76.85 7.76 '16-QAM 1/2' 13 -80.0 -77.85 7.52 '16-QAM 1/2' 14 -81.0 -79.35 5.85 'QPSK 3/4' Теперь я хочу построить график, в котором в качестве значений Х используется колонка 'Set'. На этом графике я хочу увидеть две(!) кривые: Y1: 'Rx' Y2: 'Traffic' Как такое можно сделать с помощью matplotlib.pyplot? Нашёл руководство (Pandas), где первым шагом рекомендуют выделить колонку из таблицы, как-то так: df = pd.read_csv('apple.csv', index_col='Date', parse_dates=True) new_sample_df = df.loc['2012-Feb':'2017-Feb', ['Close']] Но у меня первый индекс датафрейма числовой и я никак не могу выбрать интересующую меня колонку: new_sample_df = df.iloc[0:14, ['Rx']] TypeError: cannot perform reduce with flexible type Но даже, если я сумею это как-то сделать, то как передать в функцию рисования два (!) значения Y для каждой точки по Х? Попробовал оба предложенных варианта. Не получается :-( Что бы исключить неясности, привожу сам CSV файл: 'Set,Rx','Traffic','Modulation' -67.00, -64.35, 15.00, '64-QAM 2/3' -68.00, -65.35, 15.00, '16-QAM 3/4' -69.00, -66.85, 14.78, '64-QAM 2/3' -70.00, -67.60, 15.42, '64-QAM 2/3' -71.00, -68.85, 15.04, '64-QAM 2/3' -72.00, -70.35, 15.04, '16-QAM 3/4' -73.00, -70.85, 15.04, '16-QAM 3/4' -74.00, -71.35, 15.28, '16-QAM 3/4' -75.00, -72.60, 12.35, '64-QAM 2/3' -76.00, -73.10, 11.38, '16-QAM 3/4' -77.00, -74.60, 11.64, '16-QAM 3/4' -78.00, -75.60, 7.76, '16-QAM 1/2' -79.00, -76.85, 7.76, '16-QAM 1/2' -80.00, -77.85, 7.52, '16-QAM 1/2' -81.00, -79.35, 5.85, 'QPSK 3/4' И текст программулины, которую пытаюсь выполнить, с двумя закомментированными вариантами: #!/usr/bin/env python import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv(r'data.csv', quotechar="'") #1 df.set_index('Set')[['Rx','Traffic']].plot(legend=True, grid=True) #2 df.set_index("'Set'")[["'Rx'","'Traffic'"]].plot(legend=True, grid=True) Если раскомментировать #1, то выдаётся сообщение: KeyError: 'Set' Если раскомментировать #2, то сообщение соответственно меняется: KeyError: "'Set'" Может быть всё дело в том, что меня третий питон, а примеры - для второго? A: Чтобы правильно прочитать CSV, где значения и имена столбцов обрамлены кавычками следует использовать параметр quotechar=...: In [26]: df = pd.read_csv(r'C:\Temp\data.csv', quotechar="'") In [27]: df Out[27]: Set Rx Traffic Modulation 0 -67.0 -64.35 15.00 64-QAM 2/3 1 -68.0 -65.35 15.00 16-QAM 3/4 2 -69.0 -66.85 14.78 64-QAM 2/3 3 -70.0 -67.60 15.42 64-QAM 2/3 4 -71.0 -68.85 15.04 64-QAM 2/3 5 -72.0 -70.35 15.04 16-QAM 3/4 6 -73.0 -70.85 15.04 16-QAM 3/4 7 -74.0 -71.35 15.28 16-QAM 3/4 8 -75.0 -72.60 12.35 64-QAM 2/3 9 -76.0 -73.10 11.38 16-QAM 3/4 10 -77.0 -74.60 11.64 16-QAM 3/4 11 -78.0 -75.60 7.76 16-QAM 1/2 12 -79.0 -76.85 7.76 16-QAM 1/2 13 -80.0 -77.85 7.52 16-QAM 1/2 14 -81.0 -79.35 5.85 QPSK 3/4 In [28]: df.columns Out[28]: Index(['Set', 'Rx', 'Traffic', 'Modulation'], dtype='object') после этого построить график можно так: df.set_index('Set')[['Rx','Traffic']].plot(legend=True, grid=True) пример CSV файла: 'Set','Rx','Traffic','Modulation' -67.0,-64.35,15.0,'64-QAM 2/3' -68.0,-65.35,15.0,'16-QAM 3/4' -69.0,-66.85,14.78,'64-QAM 2/3' -70.0,-67.6,15.42,'64-QAM 2/3' -71.0,-68.85,15.04,'64-QAM 2/3' -72.0,-70.35,15.04,'16-QAM 3/4' -73.0,-70.85,15.04,'16-QAM 3/4' -74.0,-71.35,15.28,'16-QAM 3/4' -75.0,-72.6,12.35,'64-QAM 2/3' -76.0,-73.1,11.38,'16-QAM 3/4' -77.0,-74.6,11.64,'16-QAM 3/4' -78.0,-75.6,7.76,'16-QAM 1/2' -79.0,-76.85,7.76,'16-QAM 1/2' -80.0,-77.85,7.52,'16-QAM 1/2' -81.0,-79.35,5.85,'QPSK 3/4'
{ "pile_set_name": "StackExchange" }
Q: Java variable aliasing workaround I've recently moved to Java, but I've had some problems with variable aliasing. I've searched everywhere, but I can't seem to find the proper way to copy the contents of one object to another object without just referencing to the same object. Does anyone have any suggestions? Edit: What if it is an int that I am having aliasing problems with? Should I be avoiding situations like this in the first place? If so, how? A: If your class implements the Clonable interface, then you can use the Object.clone() method to create a hard copy. The Wikipedia entry has some good details. An alternative is to use copy constructors, which according to this page are safer. A: It depends on the "content". For example, you cannot just copy a FileInputStream and then assume that both will continue loading from the same file. Basically, there are two ways: If the class supports "Cloneable" interface, you can clone it by calling clone(). If not, it often has a copy constructor, that copies in data from another object. Usually, you will end up with a shallow copy (i. e. all fields of the class are copied, but they point to the same object). On the other hand, a lot of objects are designed to be immutable (like the String class), and there is no need to copy such an object as it cannot be changed anyway.
{ "pile_set_name": "StackExchange" }
Q: Multiple memcached with one infinispan? Infinispan understands the memcached protocol. is it possible to expose multiple infinispan caches as memcached servers on different ports without actually starting multiple infinispan instances? A: it does not seem to be possible at the moment and as I'm not that experienced with scala i can't make it work with code.
{ "pile_set_name": "StackExchange" }
Q: generating a dll of a web usercontrol How can I make a dll of my web application usercontrol? I have usercontrol222.ascx, but I want to make a dll out of this usercontrol. A: Create a project containing only your user control ("usercontrol222.ascx") and grab the control's dll from the deployment of your new project. Here's the source of this method with a more complete explanation: Turning an .ascx User Control into a Redistributable Custom Control (Notable excerpts below, see the link for the full run-down). Step 3: Use the Publish Command to Precompile the Site The next step is to use the new Publish command to precompile your site and turn your user control into a potential custom control. You'll find the command under Build / Publish Web Site. In the Publish dialog, do the following: Pick a Target Location. This is the location on your hard drive that your site will be precompiled to. Deselect "Allow this precompiled site to be updatable". In updatable mode, only the code behind file (if any) would get compiled, and the ascx would be left unprocessed. This is useful in some scenarios, but is not what you want here since you want the resulting DLL to be self-contained. Select "Use fixed naming and single page assemblies". This will guarantee that your user control will be compiled into a single assembly that will have a name based on the ascx file. If you don't check this option, your user control could be compiled together with other pages and user controls (if you had some), and the assembly would receive a random name that would be more difficult to work with. Step 4: Finding the Resulting Custom Control Now, using the Windows Explorer or a command-line window, let's go to the directory you specified as the target so we can see what was generated. You will see a number of files there, but let's focus on the one that is relevant to our goal of turning the user control into a custom control. In the "bin" directory, you will find a file named something like App_Web_MyTestUC.ascx.cdcab7d2.dll. You are basically done, as this file is your user control transformed into a custom control! The only thing that's left to do is to actually use it.
{ "pile_set_name": "StackExchange" }
Q: Не работает функция permutations Ошибка:RuntimeError: maximum recursion depth exceeded in compariso Почему не работает? from itertools import permutations def permutations(string): if len(string)<2: return [string] else: return [''.join(x) for x in permutations(string)] print(permutations("ab")) A: Ну вы вызываете рекурсивно функцию без изменения аргумента. Лучше не используйте идентификаторы, являющиеся названиями модулей/стандартных функций/ключевых слов. import itertools def permutations(string): if len(string)<2: return [string] else: return [''.join(x) for x in itertools.permutations(string)] print(permutations("ab"))
{ "pile_set_name": "StackExchange" }
Q: Центрировать текст относительно ромба Подскажите, как его отцентрировать, чтобы как на фото было? .zaslugi_icons { width: 140px; float: left; padding-top: 48px; padding-left: 39px; padding-right: 18px; } .zaslugi_icons p { font-family: 'Open Sans', sans-serif; font-weight: 300; color: #000; } .zaslugi_icons span { display: block; } <div class="zaslugi_icons"> <img src="img/icons_1.png" alt=""> <p>Реализованных <span>проектов</span></p> </div> <div class="zaslugi_icons"> <img src="img/icons_2.png" alt=""> <p>Положительных <span>отзыва</span></p> </div> <div class="zaslugi_icons"> <img src="img/icons_3.png" alt=""> <p>Лет <span>опыта</span></p> </div> A: Самый простой вариант с псевдо-элементами: body { display: flex; justify-content: space-around; align-items: center; flex-wrap: wrap; counter-reset: div; } div { position: relative; text-transform: capitalize; font-size: 25px; text-align: center; } div::before { content: ''; display: block; width: 5rem; height: 5rem; margin: 1rem; border: 2px solid gray; box-shadow: inset 0 0 0 4px white, inset 0 0 0 5px gray; transform: rotate(45deg); } div::after { counter-increment: div; content: counter(div); position: absolute; bottom: 50%; left: 50%; transform: translateX(-50%); } <div>lorem</div> <div>ipsum</div> <div>dolor</div> A: Без псевдо элементов * { margin: 0; padding: 0; } .unit { background: #fff; width: 150px; height: 150px; border: 1px solid red; position: relative; transform: rotate(45deg); overflow: hidden; margin: 0 40px; } .border { position: absolute; top: 15px; left: 15px; width: 120px; height: 120px; border: 1px solid blue; } .wrapper { display: flex; margin: 10px; } .over { width: 100px; height: 100px; transform: rotate(-45deg); position: absolute; top: 25px; left: 25px; text-align: center; line-height: 100px; border-radius: 50%; } .unites { height: 200px; padding: 30px; position: relative; } .unites .vois { color: red; position: absolute; bottom: 0; left: 0; width: 100%; text-align: center; font-size: 1.2em; } <div class="wrapper"> <div class="unites"> <div class="unit"> <div class="border"></div> <div class="over"> <p>75</p> </div> </div> <p class="vois">Наши отзывы</p> </div> <div class="unites"> <div class="unit"> <div class="border"></div> <div class="over"> <p>115</p> </div> </div> <p class="vois">Выполненые работы</p> </div> <div class="unites"> <div class="unit"> <div class="border"></div> <div class="over"> <p>180</p> </div> </div> <p class="vois">Количество благодарных клентов</p> </div> </div> <div class="wrapper"> <div class="unites"> <div class="unit"> <div class="border"></div> <div class="over"> <p>75</p> </div> </div> <p class="vois">Наши отзывы</p> </div> <div class="unites"> <div class="unit"> <div class="border"></div> <div class="over"> <p>115</p> </div> </div> <p class="vois">Выполненые работы</p> </div> <div class="unites"> <div class="unit"> <div class="border"></div> <div class="over"> <p>180</p> </div> </div> <p class="vois">Количество благодарных клентов</p> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: CAS AD LDAP 32 error I am seeing this when I try to login with CAS which is authenticating against AD over LDAP. SEVERE: Servlet.service() for servlet cas threw exception javax.naming.NameNotFoundException: [LDAP: error code 32 - 0000208D: NameErr: DSID-031001E5, problem 2001 (NO_OBJECT), data 0, best match of: '' ]; remaining name '/' at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3092) at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:3013) at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2820) at com.sun.jndi.ldap.LdapCtx.searchAux(LdapCtx.java:1829) at com.sun.jndi.ldap.LdapCtx.c_search(LdapCtx.java:1752) at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(ComponentDirContext.java:368) at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContext.java:338) at javax.naming.directory.InitialDirContext.search(InitialDirContext.java:257) at org.springframework.ldap.core.LdapTemplate$3.executeSearch(LdapTemplate.java:231) at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:293) at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:237) at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:588) at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:546) at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:401) at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:421) at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:441) Up to that point I was authenticated by the BindLdapAuthenticationHandler, resolved, it generated a query builder and then threw this. I think it is failing when it is trying to get attributes back. Why is the remaining name '/'? A: Remaining name is a part of a DN that wasn't actually found at a certain level of a DIT. For example when you search cn=johns,ou=marketing,dc=example,dc=com and ou=marketing,dc=example,dc=com exists but cn=johns does not exists inside of ou=marketing then the remaning name would be cn=johns. '/' does not look like a valid RDN. I would recommend to verify what you pass as a search base. Most likely it's an invalid DN string. A: LDAP error code 32 means "no such object", in this case, perhaps the base object of the search did not exist.
{ "pile_set_name": "StackExchange" }
Q: How to get content from a paragraph tag inside div via DOMDocument? How can I get paragraph tag inside a specific ID via DOMDocument()? For example, the HTML is this: <div id='content'> xxx yyyy zzzz fffuuu uuuueee xxx yyyy pppppp zzzz <p>i need only this line</p> </div> I just want to take P tag in content id DIV... Note 1: I get whole content of the DIV with: $doc = new DOMDocument(); @$doc->loadHTML($html); $xpath = new DOMXPath($doc); $newcontent = $xpath->query("//*[@id='content']"); Note 2: Don’t say getElementsByTagName; the HTML contains too many P tags. A: I dare a getElementsByTagName :) - you dont need xpath at all : $doc = new DOMDocument(); @$doc->loadHTML($html); $p=$doc->getElementById('content')->getElementsByTagName('p')->item(0); echo $p->nodeValue; outputs i need only this line
{ "pile_set_name": "StackExchange" }
Q: How to ensure that changes of the test object properties do not propagate to other test cases? This is foo.js: var Foo; Foo = function () { var foo = {}; foo.get = function (url) { // [..] return Foo.get(url); }; return foo; }; Foo.get = function (url) {}; module.exports = Foo; This is a test case for foo.js: var expect = require('chai').expect, sinon = require('sinon'); describe('foo', function () { var Foo, foo; beforeEach(function () { Foo = require('foo.js'); foo = Foo(); }); describe('.get(url)', function () { it('passes the call to Foo.get(url)', function () { var spy = sinon.spy(); // We are going to spy on Foo.get: Foo.get = spy; foo.get('http://'); // [..] }); it('does something else', function () { foo.get('http://'); // Here Foo.get persists to refer to an instance of sinon.spy. // How to make sure that the tests are indepeondent? }); }); }); I have overwritten the Foo.get property to spy on it. I expect that using beforeEach to require('foo.js') will overwrite the Foo object and make the next test unaware of the previous changes to the object. The obvious solution is to store reference to the previous property state and restore it after test, e.g. it('passes the call to Foo.get(url)', function () { var spy = sinon.spy(), Fooget = Foo.get; // We are going to spy on Foo.get: Foo.get = spy; foo.get('http://'); // [..] Foo.get = Fooget; }); However, this approach is error-prone. One way of doing it is to rewrite the module & turn it into a constructor: module.exports = function () { var Foo; Foo = function () { var foo = {}; foo.get = function (url) { // [..] return Foo.get(url); }; return foo; }; Foo.get = function (url) {}; }; And then construct a new instance before each test: describe('foo', function () { var Foo, foo; beforeEach(function () { Foo = require('foo.js')(); foo = Foo(); }); describe('.get(url)', function () { // [..] }); }); Not ideal though, because this affects the API of the library. A: So sinon has restoration of spies/stubs/mocks built in. It is best to let sinon cleanup after itself instead of trying to manually implement your own cleanup code. With mocha, there is even mocha-sinon which will do the cleanup for you. The mocha-sinon docs also explain how to use a sinon sandbox to keep track of what needs cleaning up and clean it up, but if you use mocha-sinon and do this.sinon in your mocha test code, the sandbox creation and cleanup happen automatically for you. var sinon = require('sinon'); beforeEach(function() { this.sinon = sinon.sandbox.create(); }); afterEach(function(){ this.sinon.restore(); });
{ "pile_set_name": "StackExchange" }
Q: XSLT for-each loop I have a very tricky XSLT question. Imagine I have the following input: <OtherCharges> <LineId> <Id>P</Id> </LineId> <Items> <Item1>1</Item1> <Item2>2</Item2> <Item3>3</Item3> </Items> <LineId> <Id>P</Id> </LineId> <Items> <Item1>4</Item1> </Items> <LineId> <Id>P</Id> </LineId> <Items> <Item1>5</Item1> <Item2>6</Item2> </Items> </OtherCharges> and as an output I would like to have this: <OtherCharges> <LineId>P</LineId> <OtherChargesValues> <value>1</value> <value>2</value> <value>3</value> </OtherChargesValues> </OtherCharges> <OtherCharges> <LineId>P</LineId> <OtherChargesValues> <value>4</value> </OtherChargesValues> </OtherCharges> <OtherCharges> <LineId>P</LineId> <OtherChargesValues> <value>5</value> <value>6</value> </OtherChargesValues> </OtherCharges> Where I can have an unlimited number of lines but each line has maximum of 3 items. I've tried the following code: <xsl:for-each select="/OtherCharges/LineId"> <Id> <xsl:value-of select="Id"/> <Id> <xsl:variable name="ChargeLine" select="."/> <xsl:for-each select="following-sibling::Items[preceding-sibling::LineId[1] = $ChargeLine]"> <xsl:if test="name(.)='Items'"> <xsl:if test="Item1"> <value> <xsl:value-of select="Item1"/> </value> </xsl:if> <xsl:if test="Item2"> <value> <xsl:value-of select="Item2"/> </value> </xsl:if> <xsl:if test="Item3"> <value> <xsl:value-of select="Item3"/> </value> </xsl:if> </xsl:if> </xsl:for-each> If the ID's are different it works well but the problem is when I have the same ID values (as is in the example). Anyone can help me with this? Thanks. A: This transformation: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:key name="kFollowing" match="*[not(self::LineId)]" use="generate-id(preceding-sibling::LineId[1])"/> <xsl:template match="LineId"> <OtherCharges> <LineId><xsl:value-of select="."/></LineId> <OtherChargesValues> <xsl:apply-templates mode="inGroup" select="key('kFollowing', generate-id())"/> </OtherChargesValues> </OtherCharges> </xsl:template> <xsl:template match="Items/*" mode="inGroup"> <value><xsl:value-of select="."/></value> </xsl:template> <xsl:template match="text()"/> </xsl:stylesheet> when applied on the provided XML document: <OtherCharges> <LineId> <Id>P</Id> </LineId> <Items> <Item1>1</Item1> <Item2>2</Item2> <Item3>3</Item3> </Items> <LineId> <Id>P</Id> </LineId> <Items> <Item1>4</Item1> </Items> <LineId> <Id>P</Id> </LineId> <Items> <Item1>5</Item1> <Item2>6</Item2> </Items> </OtherCharges> produces the wanted, correct result: <OtherCharges> <LineId>P</LineId> <OtherChargesValues> <value>1</value> <value>2</value> <value>3</value> </OtherChargesValues> </OtherCharges> <OtherCharges> <LineId>P</LineId> <OtherChargesValues> <value>4</value> </OtherChargesValues> </OtherCharges> <OtherCharges> <LineId>P</LineId> <OtherChargesValues> <value>5</value> <value>6</value> </OtherChargesValues> </OtherCharges>
{ "pile_set_name": "StackExchange" }
Q: Using JRuby Warbler, is it possible to generate a WAR that can learn its RAILS_ENV from an environment variable? Warbler wants you to specify a RAILS_ENV when creating the WAR. This is then put inside the web.xml of the generated WAR. However, if you could create a wAR that learned its RAILS_ENV from the environment, you could create one WAR that could be used for staging or production - in other words, a superior management regime where a WAR can be tested and then deployed without being changed. A: JRuby-Rack is already set up to read from RAILS_ENV before what gets put in web.xml, so that part is golden. The only thing you need to defeat is this rails.erb template that gets merged into a META-INF/init.rb inside the war file: ENV['RAILS_ENV'] = '<%= config.webxml.rails.env %>' There isn't a real good way to do this at the moment, but you can override the Warbler::Jar#add_init_file as follows at the top of your config/warble.rb to remove the Rails template: class Warbler::Jar alias_method :orig_add_init_file, :add_init_file def add_init_file(config) config.init_contents.delete("#{config.warbler_templates}/rails.erb") if config.init_contents orig_add_init_file(config) end end
{ "pile_set_name": "StackExchange" }
Q: Drawing a tile based Ellipse inside a Rectangle I'm trying to generate randomly sized ellipses and draw them to a map(just a 2D array of tiles). For the most part, it works, however it seems that when the room is wider than it is taller, it cuts off corners of the walls. Below is my code for drawing the ellipse. Basically takes in a rectangle and draws the Ellipse inside of it. private void AddCellEllipse(int xStart, int yStart, int xEnd, int yEnd, Tile tile) { // Draw an ellipse centered in the passed-in coordinates float xCenter = (xEnd + xStart) / 2.0f; float yCenter = (yEnd + yStart) / 2.0f; float xAxis = (xEnd - xStart) / 2.0f; float yAxis = (yEnd - yStart) / 2.0f; for (int y = yStart; y <= yEnd; y++) for (int x = xStart; x <= xEnd; x++) { // Only draw if (x,y) is within the ellipse if (Math.sqrt(Math.pow((x - xCenter) / xAxis, 2.0) + Math.pow((y - yCenter) / yAxis, 2.0)) <= 1.0f) tiles[x][y] = tile; } } I call that method like so. Generates a randomly sized rectangle in a random position, then creates an ellipse of wall tiles, then covers the inside wall tiles with floor tiles. AddCellEllipse(xRoomStart, yRoomStart, xRoomStart + roomWidth, yRoomStart + roomHeight, Tile.WALL); AddCellEllipse(xRoomStart + 1, yRoomStart + 1, xRoomStart + roomWidth - 1, yRoomStart + roomHeight - 1, Tile.FLOOR); Also bonus question, anyone have any idea how I can make it not put the 1 tile sticking out at the top/bottom of the ellipse? A: You can use Bresenham ellipse algorithm or midpoint algorithm to draw ellipses. And when you draw two symmetric points (tiles) with mentioned algo like these: DrawPixel (xc + x, yc + y); DrawPixel (xc - x, yc + y); just fill line segment between them with interior tiles.
{ "pile_set_name": "StackExchange" }
Q: Submodules of a module with a given property I am curious about the submodules of a module with a given property. Let $M$ be an $R$-module. If $M$ is a finitely generated are the submodules of $M$ finitely generated? If $R=\mathbb Z$, $M$ is a abelian group. The subgroup of $M$ is finitely generated by Proving that a subgroup of a finitely generated abelian group is finitely generated If $R$ is Noetherian, we also have positive answer. I'd like to know is there any generalization that contains the situation $R=\mathbb Z$ or Noetherian. Any advice is helpful. Thank you. A: For #1: no. For example, every ring $R$ is a finitely generated module over itself (namely, it is generated by $1$). However, the submodules of $R$ correspond with ideals of $R$, so if $R$ is not noetherian, then there is some ideal which is not finitely generated. In the case $R = \mathbb{Z}$, this is true; I refer you to this post. For #2: once again, no. Consider $R$ as a free $R$-module. Then again, the submodules of $R$ are ideals. If $I$ is a free $R$-module, then it has a $R$-basis; but you can see that any two elements of an ideal $I$ are linearly dependent, so any ideal which is a free $R$-module has to be principal. Now just take $R$ to be a ring which is not a PID, e.g. $R = \mathbb{Z}[x]$. However, if $R$ is a PID, then this is true (in particular, this resolves the case $R = \mathbb{Z}$). This is a good exercise, so you should try it yourself. If you can't figure it out, feel free to comment, and I will post a proof or refer you to one on the web. A: For any non-noetherian ring, there is a finitely generated $R$-module, which has a non-finitely generated submodule, namely $R$ itself. So there is no generalization.
{ "pile_set_name": "StackExchange" }
Q: Webview Add Menu Item to TextSelection Menu I am having an issue with android webview default text selection. what i want to do is add an item to the default menu which appears on text selection in webview The functionality i want to acieve is add a button to left side of select all. how can this be done A: you need to override the WebView class for this you need to use this code i am giving you demo code for changing defaut CAB after selection you can use your own contextual menu public class MyWebView extends WebView{ CustomizedSelectActionModeCallback actionModeCallback; public Context context; public MyWebView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub this.context=context; } @Override public ActionMode startActionMode(ActionMode.Callback callback) { // TODO Auto-generated method stub // ViewParent parent = getParent(); // if (parent == null) { // return null; // } actionModeCallback = new CustomizedSelectActionModeCallback(); return startActionModeForChild(this,actionModeCallback); } public class CustomizedSelectActionModeCallback implements ActionMode.Callback{ @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { // TODO Auto-generated method stub mode.getMenuInflater().inflate(R.menu.contextual_menu, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // TODO Auto-generated method stub mode.setTitle("CheckBox is Checked"); return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case R.id.item_delete: clearFocus(); Toast.makeText(getContext(), "This is my test click", Toast.LENGTH_LONG).show(); break; default: break; } return false; } @Override public void onDestroyActionMode(ActionMode mode) { // TODO Auto-generated method stub clearFocus(); // this is not clearing the text in my device having version 4.1.2 actionModeCallback=null; } } } MainActivity.java is public class MainActivity extends Activity { MyWebView web_view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); web_view= (MyWebView)findViewById(R.id.webView1); web_view.loadUrl("file:///android_asset/menu_pages/Chemchapter1/OEBPS/Text/07_Chapter01.html");// you can load your html here } } activity_main.xml <RelativeLayout 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" tools:context="${packageName}.${activityClass}" > <com.rstm.webviewcheck.MyWebView android:id="@+id/webView1" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> contextual_menu.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/item_delete" android:icon="@android:drawable/ic_menu_delete" android:showAsAction="ifRoom|withText" android:title="Delete" android:titleCondensed="Delete">
{ "pile_set_name": "StackExchange" }
Q: given a URL in python, how can i check if URL has RSS feed? am trying to find a way to detect if a given URL has an RSS feed or not. Any suggestions? A: Each RSS have some format. See what Content-Type the server returns for the given URL. However, this may not be specific and a server may not necessarily return the correct header. Try to parse the content of the URL as RSS and see if it is successful - this is likely the only definitive proof that a given URL is a RSS feed.
{ "pile_set_name": "StackExchange" }
Q: How to delete first line of a file from powershell ise? I have a file with the content of 09-JAN-2018 12-FEB-2018 13-MAR-2018 Could you help me on, How could I delete the first line of the file from PowerShell. Thank you in advance A: This takes the data from file1.txt without the first line, then prints it into file2.txt Get-Content file1.txt | Select-Object -Skip 1 | Out-File file2.txt But it will be usefull to know if you are working with a .txt file, a .csv, .xml or other type of file.
{ "pile_set_name": "StackExchange" }
Q: Wich's significant that code at right of variable declaration in cobol? I was studying a cobol code and I find and I did not understand a number at right of code line, like that's below: 007900 03 EXAMPLE-NAME PIC S9(17) COMP-3. EB813597 the first number is about position of that line in code, the second is about column's position (like how many 'tabs' you are using), the third is type of variable, but the fourth (COMP-3) and mainly the last (EB813597) I did not understand. Can anyone help me ? A: Columns >= 72 are ignored. So EB813597 is ignored. It could be a change id from the last time it was changed or have some site specific meaning e.g. EB could be the initials of the person who last changed it. Comp-3 - is the type of numeric. It is bit like using int or double in C/java. In Comp-3 (packed-decimal) 123 is stored as x'123c'. Alternatives to comp-3 include comp - normally big endian binary integer, comp-5 (like int / long in C) 007900 03 EXAMPLE-NAME PIC S9(17) COMP-3. EB813597 (a) (b) Field-Name (c) (d) Usage (numeric type) a - line-number ignored by the compiler b - level-number it provides a method of grouping fields together 01 Group. 03 Field-1 ... 03 Field-2 ... field-1 and field-2 belong to group. it is a bit like struct in c struct { int field_1; int field-2; ... } c) PIC (picture) tells us the field picture follows. d) fields picture in this case it is a signed field with 17 decimal digits Comp-3 - usage - how the field stored So in summary EXAMPLE-NAME is a Signed numeric field with 17 decimal digits and it is stored as Comp-3 (packed decimal).
{ "pile_set_name": "StackExchange" }
Q: AppStore submission: ERROR ITMS-9000: "Invalid Bundle Structure - The binary file 'MyApp.app/BuildAgent' is not permitted I'm stuck with the following error which I simply don't even understand. ERROR ITMS-9000: "Invalid Bundle Structure - The binary file 'MyApp.app/BuildAgent' is not permitted. Your app may contain only one executable file. When I export from the Archive with Xcode to IPA, I see that BuildAgent as 0 entitlement. Is that related to my error? What's a BuildAgent? How should I fix this? A: Please remove any reference to BuildAgent executable file that was accompanied with the HockeySDK-iOS
{ "pile_set_name": "StackExchange" }
Q: VLC instalation problem (Installing through Terminal) I wanted to install VLC on Ubuntu, it wasn't working, updated system, than upgraded it, but still it isn't working. I used both the Ubuntu Software center and the Terminal for that. In the terminal I typed the command sudo apt-get install vlc The error message terminal gives me is as follows. arif@arifpc:~$ sudo apt-get install vlc [sudo] password for arif: Reading package lists... Done Building dependency tree Reading state information... Done Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: vlc : Depends: vlc-nox (= 2.2.0~rc1-1ppa2~trusty) but it is not going to be installed Depends: libavcodec56 (>= 7:2.4~) but it is not going to be installed Depends: libgles1-mesa (>= 7.8.1) but it is not installable or libgles1 but it is not installable Depends: libsdl-image1.2 (>= 1.2.10) but it is not installable Depends: libsdl1.2debian (>= 1.2.11) but it is not installable Depends: libva-drm1 but it is not installable Depends: libva-x11-1 (> 1.3.0~) but it is not installable Depends: libva1 (> 1.3.0~) but it is not installable Depends: libvlccore8 (>= 2.2.0~pre1) but it is not going to be installed Depends: libxcb-composite0 but it is not installable Depends: libxcb-xv0 (>= 1.2) but it is not installable Recommends: vlc-plugin-notify (= 2.2.0~rc1-1ppa2~trusty) but it is not going to be installed Recommends: vlc-plugin-samba (= 2.2.0~rc1-1ppa2~trusty) but it is not going to be installed E: Unable to correct problems, you have held broken packages. Note:I'm using Ubuntu 14.04 LTS A: This happened to me after the upgrade from Ubuntu 14.04 to 14.10. I found this Solution that helped me. You need to add the xorg-edgers fresh X crack Repository with this Code in Terminal: sudo add-apt-repository ppa:xorg-edgers/ppa apt-cache policy libgl1-mesa-glx libglapi-mesa Then Reboot your PC. Then update the repositories with the following commands and install VLC: sudo apt-get update sudo apt-get install vlc A: Actually I solved this problem the same day, the problem was with the nearest archive.ubuntu.com (Ubuntu Archive Server) I changed all of its instances (13 occurrences in my case) to us.archive.ubuntu.com and it worked. The configuration file where I changed this setting was /etc/apt/sources.list. Edit: Recently I found another question on askubuntu, the accepted answer to this question is also a nice solution to this problem if you don't want to change the archive.ubuntu address. Here is that question.
{ "pile_set_name": "StackExchange" }
Q: Comparing arrays not working correctly? Ok this is my code. Now I have it set up so far to display the correct pattern for 3 seconds, go to an input screen for the user to input, when the user clicks the screen 6 times it takes the pattern the user inputs and stores it into the array input, then checks if the input array and pattern array are the same. Now the problem is that when it checks for the arrays to be the same that it works correctly for the percent pattern but it doesn't work correctly for any other pattern. How can I compare the two 2D arrays? package game; import java.awt.Dimension; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; public class InputGame implements Properties,Listeners{ public static JFrame gf = new JFrame(); public static JButton a1,a2,a3,a4; public static JButton b1,b2,b3,b4; public static JButton c1,c2,c3,c4; public static JButton d1,d2,d3,d4; public static int height = 800; public static int width = 600; public static int gsize = 4; public static int order =1; public static Dimension size = new Dimension(height,width); public static menu Menu = new menu(); public static GridLayout Ggrid = new GridLayout(gsize,gsize); public static int numOfClicks =0; public static int numCorrect=0; public static int[][] input = new int[][]{ {0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0} }; //public static Thread d; public static void clear() { gf.dispose(); } public static void setup() { gf.dispose(); gf = new JFrame(); gf.setLocation(300,100); gf.setSize(size); gf.setResizable(false); gf.setLayout(Ggrid); gf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); PatternGame.clear(); blank(); gf.setVisible(true); System.out.print(numOfClicks); } public static void blank() { { a1 = new JButton(""); a2 = new JButton(""); a3 = new JButton(""); a4 = new JButton(""); a1.addActionListener(new input()); a2.addActionListener(new input()); a3.addActionListener(new input()); a4.addActionListener(new input()); gf.add(a1); gf.add(a2); gf.add(a3); gf.add(a4); } { b1 = new JButton(""); b2 = new JButton(""); b3 = new JButton(""); b4 = new JButton(""); b1.addActionListener(new input()); b2.addActionListener(new input()); b3.addActionListener(new input()); b4.addActionListener(new input()); gf.add(b1); gf.add(b2); gf.add(b3); gf.add(b4); } { c1 = new JButton(""); c2 = new JButton(""); c3 = new JButton(""); c4 = new JButton(""); c1.addActionListener(new input()); c2.addActionListener(new input()); c3.addActionListener(new input()); c4.addActionListener(new input()); gf.add(c1); gf.add(c2); gf.add(c3); gf.add(c4); } { d1 = new JButton(""); d2 = new JButton(""); d3 = new JButton(""); d4 = new JButton(""); d1.addActionListener(new input()); d2.addActionListener(new input()); d3.addActionListener(new input()); d4.addActionListener(new input()); gf.add(d1); gf.add(d2); gf.add(d3); gf.add(d4); } } public static void input() { { String x = a1.getText(); if (x.equals("X")) { input[0][0] = 1; } x = a2.getText(); if (x.equals("X")) { input[0][1] = 1; } x = a3.getText(); if (x.equals("X")) { input[0][2] = 1; } x = a4.getText(); if (x.equals("X")) { input[0][3] = 1; } } { String x = b1.getText(); if (x.equals("X")) { input[1][0] = 1; } x = b2.getText(); if (x.equals("X")) { input[1][1] = 1; } x = b3.getText(); if (x.equals("X")) { input[1][2] = 1; } x = b4.getText(); if (x.equals("X")) { input[1][3] = 1; } } { String x = c1.getText(); if (x.equals("X")) { input[2][0] = 1; } x = c2.getText(); if (x.equals("X")) { input[2][1] = 1; } x = c3.getText(); if (x.equals("X")) { input[2][2] = 1; } x = c4.getText(); if (x.equals("X")) { input[2][3] = 1; } } { String x = d1.getText(); if (x.equals("X")) { input[3][0] = 1; } x = d2.getText(); if (x.equals("X")) { input[3][1] = 1; } x = d3.getText(); if (x.equals("X")) { input[3][2] = 1; } x = d4.getText(); if (x.equals("X")) { input[3][3] = 1; } } } public static boolean checkCorrect() { input(); for (int a=0;a<4;a++) { for(int b=0;b<4;b++) { if (order == 1) { if (handlebars[a][b] == input[a][b]) { InputGame.numCorrect++; } } if (order == 2) { if (ys[a][b] == input[a][b]) { InputGame.numCorrect++; } } if (order == 3) { if (spaceShip[a][b] == input[a][b]) { InputGame.numCorrect++; } } if (order == 4) { if (flock[a][b] == input[a][b]) { InputGame.numCorrect++; } } if (order == 5) { if (percent[a][b] == input[a][b]) { InputGame.numCorrect++; } } if (order == 6) { if (square[a][b] == input[a][b]) { InputGame.numCorrect++; } } } } System.out.println(numCorrect); for (int a =0;a<4;a++) { System.out.println(); for(int b=0;b<4;b++) { System.out.print(input[a][b]); } } for (int a =0;a<4;a++) { System.out.println(); for(int b=0;b<4;b++) { System.out.print(ys[a][b]); } } if (numCorrect == 16) { return true; } else { return false; } } } package game; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JOptionPane; public interface Listeners { static PatternGame game = new PatternGame(); InputGame game2 = new InputGame(); static class inst implements ActionListener { public void actionPerformed(ActionEvent e) { if ("inst".equals(e.getActionCommand())) { } } } static class play implements ActionListener { public void actionPerformed(ActionEvent e) { if ("play".equals(e.getActionCommand())) { menu.mf.dispose(); PatternGame.gameStart(); } } } static class exit implements ActionListener { public void actionPerformed(ActionEvent e) { if ("exit".equals(e.getActionCommand())) { System.exit(0); } } } static class input implements ActionListener { public void actionPerformed(ActionEvent e) { if (InputGame.numOfClicks !=1) { JButton x = (JButton) e.getSource(); x.setText("X"); InputGame.numOfClicks--; } else if (InputGame.numOfClicks ==1) { JButton x = (JButton) e.getSource(); x.setText("X"); InputGame.numOfClicks--; if (InputGame.checkCorrect()) { int yesno = JOptionPane.showConfirmDialog(null, "<html> Correct!" +"<br>Would you like another pattern?"); if (yesno == JOptionPane.YES_OPTION) { PatternGame.order++; InputGame.clear(); PatternGame.gameStart(); } else { InputGame.clear(); menu.start(); } } else { JOptionPane.showMessageDialog(null, "Incorrect!"); InputGame.clear(); menu.start(); } } } } } package game; import java.awt.Dimension; import java.awt.GridLayout; import java.util.Timer; import java.util.TimerTask; import javax.swing.JButton; import javax.swing.JFrame; public class PatternGame implements Properties { public static JFrame df = new JFrame(); public static int height = 800; public static int width = 600; public static int gsize = 4; public static int order =1; public static Dimension size = new Dimension(height,width); public static menu Menu = new menu(); public static GridLayout Ggrid = new GridLayout(gsize,gsize); public static void DisplayPat() { df.dispose(); df = new JFrame(); df.setLocation(300,100); df.setSize(size); df.setResizable(false); df.setLayout(Ggrid); df.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); df.setVisible(true); } public static boolean StayIn = true; public static InputGame game = new InputGame(); public static int flag =0; public static void clear() { df.dispose(); } public static void gameStart() { DisplayPat(); getpattern(); schedule(3); //notifyAll(); } public static void blank() { for (int a=0;a<4;a++) { for(int b=0;b<4;b++) { JButton button = new JButton(" "); df.add(button); } } } public static void getpattern() { InputGame.numOfClicks=0; if (order == 1) { for (int a=0;a<4;a++) { for(int b=0;b<4;b++) { if (handlebars[a][b] == 1) { JButton button = new JButton("X"); df.add(button); InputGame.numOfClicks++; } else { JButton button = new JButton(""); df.add(button); } flag =1; } } } if (order == 2) { for (int a=0;a<4;a++) { for(int b=0;b<4;b++) { if (ys[a][b] == 1) { JButton button = new JButton("X"); df.add(button); InputGame.numOfClicks++; } else { JButton button = new JButton(""); df.add(button); } } } } if (order == 3) { for (int a=0;a<4;a++) { for(int b=0;b<4;b++) { if (spaceShip[a][b] == 1) { JButton button = new JButton("X"); df.add(button); InputGame.numOfClicks++; } else { JButton button = new JButton(""); df.add(button); } } } } if (order == 4) { for (int a=0;a<4;a++) { for(int b=0;b<4;b++) { if (flock[a][b] == 1) { JButton button = new JButton("X"); df.add(button); InputGame.numOfClicks++; } else { JButton button = new JButton(""); df.add(button); } } } } if (order == 5) { for (int a=0;a<4;a++) { for(int b=0;b<4;b++) { if (percent[a][b] == 1) { JButton button = new JButton("X"); df.add(button); InputGame.numOfClicks++; } else { JButton button = new JButton(""); df.add(button); } } } } if (order == 6) { for (int a=0;a<4;a++) { for(int b=0;b<4;b++) { if (square[a][b] == 1) { JButton button = new JButton("X"); df.add(button); InputGame.numOfClicks++; } else { JButton button = new JButton(""); df.add(button); } } } } df.setVisible(true); } public static Timer timer = new Timer(); //timer object public static void schedule(int seconds) { timer.schedule(new ScheduleTask(), seconds*1000); } static class ScheduleTask extends TimerTask { public void run() { InputGame.setup(); // timer.cancel(); //Terminate Timer thread } } } package game; public interface Properties { int[][] percent = new int[][]{ {1,0,0,1}, {0,0,1,0}, {0,1,0,0}, {1,0,0,1} }; int[][] spaceShip = new int[][]{ {0,1,1,0}, {0,0,0,0}, {0,1,1,0}, {1,0,0,1} }; int[][] flock = new int[][]{ {0,0,0,0}, {1,0,1,0}, {0,1,0,1}, {1,0,1,0} }; int[][] ys = new int[][]{ {0,0,1,0}, {1,0,1,0}, {0,1,0,1}, {0,1,0,0} }; int[][] handlebars = new int[][]{ {1,0,0,0}, {0,1,1,0}, {0,1,1,0}, {0,0,0,1} }; int[][] square = new int[][]{ {0,1,0,1}, {1,0,0,0}, {0,0,0,1}, {1,0,1,0} }; } A: Try using: Arrays.equals(); // <---- One Dimensional Arrays or ArrayUtils.isEquals(); // <---- Multi Dimensional Arrays These methods will compare the actual contents of the two arrays (not if they are the same reference or same object) and you wont have to step through each element individually. Hope it helps!
{ "pile_set_name": "StackExchange" }
Q: could not be able to work with the SplitViewNavigator container I want to make an App using SplitViewNavigator container which contains List of cities in left view and Detail about the city in right view, In right view there is a text input through I get Name of city and store in a SQLite Database, and that name should be added to list in left view from SQLite Database I got started with flowing code in Main.mxml: <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" applicationDPI="160" initialize="application1_initializeHandler(event)"> <fx:Script> <![CDATA[ import model.DataModel; import mx.events.FlexEvent; import valueobject.CityValueObject; import utillities.CityUtils; public var sqlConnection:SQLConnection; protected var statement:SQLStatement; protected function application1_initializeHandler(event:FlexEvent):void { sqlConnection = new SQLConnection(); sqlConnection.open(File.applicationStorageDirectory.resolvePath("cityDB.db"), SQLMode.CREATE); statement.sqlConnection = sqlConnection; // Here error occurs saying that Error #1009: Cannot access a property or method of a null object reference. statement.text = "CREATE TABLE IF NOT EXISTS CITYNAME (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "nameofcity TEXT)"; statement.execute(); DataModel.getInstance().connection = sqlConnection; CityUtils.getAllCities(); } ]]> </fx:Script> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <s:SplitViewNavigator id="svn" width="100%" height="100%"> <s:ViewNavigator width="30%" height="100%" id="list_of_cities" firstView="views.ListOfCities"/> <s:ViewNavigator width="70%" height="100%" id="display_contents" firstView="views.DisplayContents"/> </s:SplitViewNavigator> My model.DataModel is an action script class: package model { import flash.data.SQLConnection; import mx.collections.ArrayCollection; [Bindable] public class DataModel { public var connection:SQLConnection; public var cityList:ArrayCollection = new ArrayCollection(); public var logs:String="Application Logs........\n"; public static var _instance:DataModel; public function DataModel() { } public static function getInstance():DataModel { if(_instance == null) { _instance = new DataModel(); } return _instance; } } } My valueobject.CityValueObject class is: package valueobject { [Bindable] public class CityValueObject { public var id:uint; public var nameofcity:String; }} And My uttillities.CityUtils class is :: package utillities { import flash.data.SQLResult; import flash.data.SQLStatement; import flash.display.Loader; import flash.display.LoaderInfo; import flash.events.Event; import flash.net.URLRequest; import flash.utils.ByteArray; import model.DataModel; import mx.collections.Sort; import mx.collections.SortField; import valueobject.CityValueObject; public class CityUtils { public static function getAllCities():void { var contactListStatement:SQLStatement = new SQLStatement(); contactListStatement.sqlConnection = DataModel.getInstance().connection; contactListStatement.text = "SELECT * FROM CITYNAME"; contactListStatement.execute(); var result:SQLResult = contactListStatement.getResult(); if( result.data!=null) { DataModel.getInstance().cityList.removeAll(); for(var count:uint=0;count<result.data.length;count++) { var cityVO:CityValueObject = new CityValueObject(); cityVO.id = result.data[count].id; cityVO.nameofcity = result.data[count].city; DataModel.getInstance().cityList.addItem(cityVO); } } sortData(); } public static function sortData():void { var dataSortField:SortField = new SortField(); dataSortField.name = "cityName"; dataSortField.numeric = false; /* Create the Sort object and add the SortField object created earlier to the array of fields to sort on. */ var numericDataSort:Sort = new Sort(); numericDataSort.fields = [dataSortField]; /* Set the ArrayCollection object's sort property to our custom sort, and refresh the ArrayCollection. */ DataModel.getInstance().cityList.sort = numericDataSort; DataModel.getInstance().cityList.refresh(); } public static function updateLog(newLog:String):void { DataModel.getInstance().logs += new Date().time+" :-> "+newLog+"\n"; } } } My left containing list of cities is : <?xml version="1.0" encoding="utf-8"?> <s:View xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" title="Cities" > <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <fx:Script> <![CDATA[ import model.DataModel; import mx.collections.ArrayCollection; import mx.events.FlexEvent; import mx.events.IndexChangedEvent; import spark.components.SplitViewNavigator; import spark.components.ViewNavigator; import spark.transitions.ViewTransitionBase; protected function myList_changeHandler():void { // Create a reference to the SplitViewNavigator. var splitNavigator:SplitViewNavigator = navigator.parentNavigator as SplitViewNavigator; // Create a reference to the ViewNavigator for the Detail frame. var detailNavigator:ViewNavigator = splitNavigator.getViewNavigatorAt(1) as ViewNavigator; detailNavigator.transitionsEnabled = false; // Change the view of the Detail frame based on the selected List item. detailNavigator.pushView(DisplayContents, list_of_cities.selectedItem); } ]]> </fx:Script> <s:VGroup width="100%" height="100%"> <s:List id="list_of_cities" height="100%" width="100%" change="myList_changeHandler();" dataProvider="{DataModel.getInstance().cityList}" labelField="nameofcity"> </s:List> </s:VGroup> and in last my Display Detail about city is simply like this : <?xml version="1.0" encoding="utf-8"?> <s:View xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" title="Detail About City" > <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <s:actionContent> <s:CalloutButton id="add_call_out_button" label="Add City" verticalPosition="after" icon="@Embed('assets/add.png')" calloutDestructionPolicy="never"> <!-- layout the callout content here --> <s:calloutLayout> <s:VerticalLayout paddingTop="10" paddingBottom="10" paddingLeft="10" paddingRight="10" horizontalAlign="center" gap="5"/> </s:calloutLayout> <s:calloutContent> <s:TextInput id="city_name_input" prompt="Enter City Name" text="Sydney"/> <s:HGroup gap="40"> <s:Button id="add_city_name" label="Add City" width="150" height="40" click="add_city_name_clickHandler()"/> <s:CheckBox id="preferred_cbox" label="Preferred" height="40" /> </s:HGroup> </s:calloutContent> </s:CalloutButton> <s:Button id="remove_city_name" label="Remove" width="120" height="40" click="remove_city_name_clickHandler()" icon="@Embed('assets/delete.png')"/> </s:actionContent> <s:Label id="nameSomeThing" text="{data.Description}"/> <fx:Script> <![CDATA[ import model.DataModel; import spark.components.SplitViewNavigator; import spark.components.ViewNavigator; protected function add_city_name_clickHandler():void { var sqlStatement:SQLStatement = new SQLStatement(); sqlStatement.sqlConnection = DataModel.getInstance().connection; sqlStatement.text = "INSERT INTO CITYNAME (nameofcity)" + "VALUES(:nameofcity)"; sqlStatement.parameters[":nameofcity"] = city_name_input.text; sqlStatement.execute(); var splitNavigator:SplitViewNavigator = navigator.parentNavigator as SplitViewNavigator; // Create a reference to the ViewNavigator for the Detail frame. var detailNavigator:ViewNavigator = splitNavigator.getViewNavigatorAt(1) as ViewNavigator; detailNavigator.transitionsEnabled = false; // Change the view of the Detail frame based on the selected List item. detailNavigator.popToFirstView(); } protected function remove_city_name_clickHandler():void { // TODO Auto-generated method stub } ]]> </fx:Script> the above view(Display Detail) is still in development but at this stage I was Trying to add City Name to list of cities by getting name from city name input text input but at: statement.sqlConnection = sqlConnection; // Here error occurs saying that Error #1009: Cannot access a property or method of a null object reference. Iget that error and not be able to go ahead. Can any one please give me the way to solve my this problem by my code givien above or suggest me an other way to meet my needs by this App Thanks in Advance... A: As the error message says, statement is null. I don't see any code that would initialize it. You need: statement = new SQLStament(); (And I don't see any reason why this variable would need to be outside the application1_initializeHandler function.)
{ "pile_set_name": "StackExchange" }
Q: Parse JSON array output by PHP I have a JSON array which PHP returns, example output from PHP: [ { "uid": "1", "username": "mike", "time_created": "2014-12-27 15:30:03", "time_updated": "2014-12-27 15:30:03", "time_expires": "2014-12-27 15:30:03" }, { "uid": "2", "username": "jason", "time_created": "2014-12-27 15:31:41", "time_updated": "2014-12-27 15:31:41", "time_expires": "2014-12-27 15:31:41" }, { "uid": "3", "username": "david", "time_created": "2014-12-27 18:10:53", "time_updated": "2014-12-27 18:10:53", "time_expires": "2014-12-27 18:10:53" } ] I tried several methods, I tried Iterator, I tried toArray from JSonObject, but nothing seems to work! So far I have this sample code: QJsonDocument jsonResponse = QJsonDocument::fromJson(JData.toUtf8()); QJsonObject jsonObject = jsonResponse.object(); for (QJsonObject:: Iterator it = jsonObject.begin(); it != jsonObject.end(); ++it) { QJsonArray array= (*it).toArray(); foreach (const QJsonValue & v, array) qDebug() << v.toString(); I tried several other ways, no luck. I need to iterate through this JSON data. Please advice. I'm using QT 5.4, C++. A: Just verified your code with putting the data to QString first (not implying it needs to be done, only for my debug). A couple of problems found: An array is on upper level of the document. QJsonValue::toString() could not traverse the nested structure but QJsonValue (variable v) still can be printed via qDebug() stream. QString JsonStr = "[" "{" "\"uid\": \"1\"," "\"username\": \"mike\"," "\"time_created\": \"2014-12-27 15:30:03\"," "\"time_updated\": \"2014-12-27 15:30:03\"," "\"time_expires\": \"2014-12-27 15:30:03\"" "}," "{" "\"uid\": \"2\"," "\"username\": \"jason\"," "\"time_created\": \"2014-12-27 15:31:41\"," "\"time_updated\": \"2014-12-27 15:31:41\"," "\"time_expires\": \"2014-12-27 15:31:41\"" "}," "{" "\"uid\": \"3\"," "\"username\": \"david\"," "\"time_created\": \"2014-12-27 18:10:53\"," "\"time_updated\": \"2014-12-27 18:10:53\"," "\"time_expires\": \"2014-12-27 18:10:53\"" "}" "]"; QJsonDocument jsonResponse = QJsonDocument::fromJson(JsonStr.toUtf8()); QJsonArray array = jsonResponse.array(); // print foreach (const QJsonValue & v, array) { qDebug() << v; } // or parse foreach (const QJsonValue& v, array) { QJsonObject o = v.toObject(); qDebug() << o["username"]; qDebug() << o["time_expires"]; }
{ "pile_set_name": "StackExchange" }
Q: Cell of UICollectionViewController doesn't show Xcode 9.2, Swift 4 I have a CollectionViewController scene in my Main.storyboard that I linked to CollectionVewController class. In this scene there is a cell, whose the identifier is TextCell. I changed the background color of this one directly in the Main.storyboard. Here is the code of my CollectionViewControllerClass import UIKit private let reuseIdentifier = "TextCell" class CollectionViewController: UICollectionViewController { override func viewDidLoad() { super.viewDidLoad() // Register cell classes self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) self.collectionView?.backgroundColor = UIColor(red: 52.0 / 250.0, green: 63.0 / 250.0, blue: 77.0 / 250.0, alpha: 1) } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 12 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) // Configure the cell return cell } } I don't see any cell when I run the app, does someone know why ? Thanks ! A: Delete this line: self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) That line tells the runtime not get the cell from the storyboard. But you do want to get the cell from the storyboard, because that is where you changed the background color of the cell.
{ "pile_set_name": "StackExchange" }
Q: AS3 Key Down event listener doesn't work? I'm new to OOP programming with AS3, I'm trying to create a listener that will respond when keys are pressed.. It worked fine when I just typed it in the timeline, but now when it's on it's own package it doesn't respond at all, what am I doing wrong? package{ import flash.events.KeyboardEvent; import flash.display.Sprite; public class PlayerController extends Sprite{ public function PlayerController(){ addEventListener(KeyboardEvent.KEY_DOWN,onButDown); } function onButDown(event:KeyboardEvent):void{ trace("Key Down"); } } } And in the main class I have this: var pc:PlayerController = new PlayerController(); Thanks A: Your issue here may be that the instance of PlayerController has not received focus (and never will since it doesn't look like you're adding it to the display list). If an object does not have focus, it cannot receive keyboard events. One solution would be to pass a reference to stage in your constructor and then add the event listener to that instead: package { import flash.events.KeyboardEvent; import flash.display.Sprite; public class PlayerController extends Sprite{ public function PlayerController($stageRef:Stage){ $stageRef.addEventListener(KeyboardEvent.KEY_DOWN,onButDown); } function onButDown(event:KeyboardEvent):void{ trace("Key Down"); } } } Then, in your main app: var pc:PlayerController = new PlayerController(stage); Edit to add: this is assuming stage is not null. You would need to make sure of that before you instantiate PlayerController in this manner.
{ "pile_set_name": "StackExchange" }
Q: i want to make custom json from multiple json object heres my first json [ { "future_sell": "2300.00", "to_currency": "DKK", "creation_datetime": "2016-10-20 12:23:29", "title": "Total selling currency", "title_two": "Date : 2016-10-20", "description": "DKK = 2300.00", "start": "2016-10-20", "end": "2016-10-20" }, { "future_sell": "536.66", "to_currency": "USD", "creation_datetime": "2016-10-20 15:27:36", "title": "Total selling currency", "title_two": "Date : 2016-10-20", "description": "USD = 536.66", "start": "2016-10-20", "end": "2016-10-20" }, { "future_sell": "600.00", "to_currency": "USD", "creation_datetime": "2016-10-21 13:51:28", "title": "Total selling currency", "title_two": "Date : 2016-10-21", "description": "USD = 600.00", "start": "2016-10-21", "end": "2016-10-21" } ] and I want to make below json from above [ { "creation_datetime": "2016-10-20 12:23:29", "title": "Total selling currency", "title_two": "Date : 2016-10-20", "description": "DKK = 2300.00,USD = 536.66", "start": "2016-10-20", "end": "2016-10-20" }, { "creation_datetime": "2016-10-21 13:51:28", "title": "Total selling currency", "title_two": "Date : 2016-10-21", "description": "USD = 600.00", "start": "2016-10-21", "end": "2016-10-21" } ] means want to combine if same date in creation_datetime field and its to_currency in Description field my array is below for first array json object foreach ($future_sell_data as $key => $value) { $future_sell_data[$key]['title'] = "Total selling currency"; $future_sell_data[$key]['title_two'] = "Date : " .date("Y-m-d",strtotime($value['creation_datetime'])); $future_sell_data[$key]['description'] = $value['to_currency']." = ".$value['future_sell']; $future_sell_data[$key]['start'] = date("Y-m-d",strtotime($value['creation_datetime'])); $future_sell_data[$key]['end'] = date("Y-m-d", strtotime($value['creation_datetime'])); } can anyone help me how do i make second json object ? A: Assuming that you are not considering time Assuming that you have first creation_datetime to be considered foreach ($arr as $value) { $timestamp = $value["title_two"]; // Store the timestamp to combine similar values if(isset($customArr[$timestamp])) { $customArr[$timestamp]['description'] .= ",".$value['description']; } else { $customArr[$timestamp]['creation_datetime'] = $value['creation_datetime']; $customArr[$timestamp]['description'] = $value['description']; } $customArr[$timestamp]['title'] = $value['title']; $customArr[$timestamp]['title_two'] = $value['title_two']; $customArr[$timestamp]['start'] = $value['start']; $customArr[$timestamp]['end'] = $value['end']; } echo json_encode(array_values($customArr)); // timestamp is not needed for your JSON, so resetting the index Output: Check here [ { "creation_datetime": "2016-10-20 12:23:29", "description": "DKK = 2300.00,USD = 536.66", "title": "Total selling currency", "title_two": "Date : 2016-10-20", "start": "2016-10-20", "end": "2016-10-20" }, { "creation_datetime": "2016-10-21 13:51:28", "description": "USD = 600.00", "title": "Total selling currency", "title_two": "Date : 2016-10-21", "start": "2016-10-21", "end": "2016-10-21" } ]
{ "pile_set_name": "StackExchange" }
Q: Laravel 5.3 - insert data to multiple rows i am new for laravel.this is my view form <div class="row"> <div class="col-md-6"> <form class="" action="{{route('production.update', $rm->id)}}" method="post"> <input name="_method" type="hidden" value="PATCH"> {{csrf_field()}} <input type="hidden" name="id" id="id" class="form-control" value="{{$rm->id}}"> <div class="form-group{{ ($errors->has('batch_id')) ? $errors->first('title') : '' }}"> <lable>Batch ID</lable> <input type="text" name="batch_id" id="batch_id" class="form-control" value="{{$rm->product_id}}" readonly=""> {!! $errors->first('wastage','<p class="help-block">:message</p>') !!} </div> <div class="form-group{{ ($errors->has('')) ? $errors->first('title') : '' }}"> <lable>Packing</lable> @foreach($subitem as $sub) <div class="row"> <div class="col-md-4"> <input type="checkbox" name="subitem[i]" value="{{$sub->id}}"> {{$sub->subitem_name}} <div class="col-md-4"> <input type="text" name="qty[i]" id="qty" class="form-control" placeholder="Entire Qty"> {!! $errors->first('qty','<p class="help-block">:message</p>') !!} </div> </div> @endforeach </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Add"> </div> </form> </div> </div> </div> i need to do, when i click the add button, insert batch_id, sub_id and quantity to multiples rows.batch_id is same and quantity, sub_id are difference.please can anyone help me to do it ? i need to change my controller also, public function update(Request $request, $id) { $items = new Itempacking; $items->batch_id = $request->batch_id; $items->sub_id = $request->sub_id $items->quantity = $request->quantity; $items->save(); } anyone can help for this ? A: Change you form element like this @foreach($subitem as $sub) <div class="row"> <div class="col-md-4"> <input type="checkbox" name="subitem[{{$sub->id}}][id]" value="{{$sub->id}}"> {{$sub->subitem_name}} <div class="col-md-4"> <input type="text" name="subitem[{{$sub->id}}][qty]" value="{{$sub->qty}}}" class="form-control" placeholder="Entire Qty"> {!! $errors->first('qty','<p class="help-block">:message</p>') !!} </div> </div> @endforeach Loop the $request->subitem like this ` public function update(Request $request, $id) { foreach($request->subitem as $key=>$row) { $items = new Itempacking; $items->batch_id = $request->batch_id; $items->sub_id = $row['id'] $items->quantity = $row['qty']; $items->save(); $items=''; }`
{ "pile_set_name": "StackExchange" }