text
stringlengths
64
89.7k
meta
dict
Q: i want to create a counter with a text view i want to create a counter with a text view and want for every 15 click , to change the text in the text view and that is what i have wrote to create the counter ........ i have two text views .... one for the no. of clicks and the another for the text i want to show ,,,,,,,,,,, so i want to use "if" to set the counter to 0 (the counter is tvx) and to change the text (tvx2) to "click 15 more" @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tips_2); btn = (Button) findViewById(R.id.bt); txv = (TextView) findViewById(R.id.tx); txv2 = (TextView) findViewById(R.id.tx2); btn.setOnClickListener(new View.OnClickListener() { public int mCounter; public Integer tx; @Override public void onClick(View v) { mCounter++; txv.setText(Integer.toString(mCounter)); } }); } A: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tips_2); btn = (Button) findViewById(R.id.bt); txv = (TextView) findViewById(R.id.tx); txv2 = (TextView) findViewById(R.id.tx2); public int mCounter=0; public Integer tx =15; btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCounter++; if(mCounter==tx){ txv.setText(Integer.toString(mCounter)); //reset the counter after 15 click mCounter=0 } } } ); } }
{ "pile_set_name": "StackExchange" }
Q: XQuery – passing a list of parameters I can’t figure out a bit trivial thing! I need to automatize packing of ePubs from TEI XML. I know how to use compression but can’t pass list of arguments programmatically. The problem is I want to take a list made from a set of divs and pass it to the function as arguments. Instead of let $entries := (<entry>x</entry>, <entry>y</entry>) compression:zip($entries, true()) I need to do something like let $header := (<header>xyz</header>) let $divs := ( for $book in doc('./file.xml') return $book//tei:div[@n='1'] ) let $entries := ( for $div in $divs return <entry>{$div}</entry> ) compression:zip($entries, $header, true()) I simply can’t pass extracted divs as a comma-separated list of arguments (as the compressing needs). If I could use something like array iteration or path joining, it would be fine! I am very close with for $chapter at $count in doc('./bukwor.xml')//tei:div[@n='1'] return <entry name="chapter-{$count}"> type="xml">{$chapter}</entry> but still can’t do the magic. A: Got it (thanks to https://en.wikibooks.org/wiki/XQuery/DocBook_to_ePub). The compression:zip function takes comma-separated argument lists as well as lists unseparated. It is legal to do let $chaps := ( for $chapter at $count in doc('./file.xml')//tei:div[@n='1'] return <entry name="OEBPS/chapter-{$count}.xhtml" type="xml">{$chapter}</entry> ) let $entries := ( <entry name="mimetype" type="text" method="store">application/epub+zip</entry>, <entry>XYZ</entry>, $chaps ) The last $chaps entry gathers right files and adds them to the archive.
{ "pile_set_name": "StackExchange" }
Q: Virtualenv wont work on I have build my virtual env with this command: virtualenv env --distribute --no-site-packages And then I have installed several modules (django etc) into env with pip, the problem is that when I wanted to run the code on the second machine it would not work, here is what I have done: visgean@rewitaqia:~/scripty/project_name$ source ./env/bin/activate (env)visgean@rewitaqia:~/scripty/project_name$ python Python 2.7.1+ (r271:86832, Sep 27 2012, 21:12:17) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.__file__ '/home/visgean/scripty/project_name/env/lib/python2.7/site-packages/django/__init__.pyc' but when I want to run it on the second machine: (env)user@debian:~/project_name$ python Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named django >>> I wild error appears! The first machine is ubuntu, the second one is ubuntu. There seems to be some broken links in /home/user/project_name/env/lib/python2.7 , is that the problem? and if so, how should I prevent it/repair it? A: I have just noticed that I did have a wrong version of python on the second machine - debian does not have python2.7, installing 2.7 and pip for is the solution
{ "pile_set_name": "StackExchange" }
Q: Eclipse associating .war with Tomcat I've taken a checkout of a project on github from below... https://github.com/wakaleo/game-of-life/ I can build it and create a war file. The only problem I have is that when I make the war in /gameoflife/target/gameoflife.war when I right click on it, I don't get the option to "run on server". I've created a tomcat server, how do I actually configure the project to allow me to run this war on a tomcat server or even associate the war file with tomcat? I can get the project to work by just copying this war into a webapps folder on tomcat, but surely there's a solution that can be done within my IDE so I just have to click "run". Thanks, David A: You have to create a server runtime in eclipse. You just go to Window->Preferences->Servers and add a new Runtime Environment. Choose the button create local server Set it up to point to your Tomcat. Then you should see a servers tab and a server view for tomcat configuration. By clicking on the tomcat inside the server view you can select all dynamic web projects to be imported. Or you can click on the project and add it to server Update: If it not a dynamic web project then you should add the relative facets. Right-click on project and click Properties. Click on Project Facets and modify your project to include Dynamic Web Module and all the dependencies. This should be done using J2EE perspective
{ "pile_set_name": "StackExchange" }
Q: What happens if the load factor of a HashMap is greater than 1? Default value of hashmap's load factor os 0.75f i.e it will re-hash the hash map once the 75% of capacity of hasmap is filled. What if I set the value of load factor greater than 1 for example lets say 2 (super(capacity+1, 2.0f, true);) How it will work in sch case and how the hashing will work here? A: What if I set the value of load factor greater than 1 for example lets say 2 (super(capacity+1, 2.0f, true);) You already have the answer; ... it will re-hash the hash map once the 200% of capacity of hashmap is filled. The hashing works the same, it just uses a smaller capacity which impacts performance. If you make the initial capacity large enough the load factor never comes into play. The load factor only applies when the map is resized. Note: the actual capacity is always a power of 2. I suggest you try it. BTW Changing the load factor can change the order the elements appear as there is less buckets. Trying printing out the Set or Map and comparing.
{ "pile_set_name": "StackExchange" }
Q: Azure blob storage - controlling name when resource is downloaded We have thousands of files to store in Azure blob storage. These files could be of any type, but PDF files, images, and Excel are the most common. With the URI of the blob in an anchor tag, a user of our system can download a file directly from Azure to the user's computer. All is good. We would like to have the blob name be the name of the file itself, so when the user downloads the file, the original filename is intact. However, we must account for inevitable filename collisions in the Container. Using GUIDs for the blob name is a workable solution, but when the user clicks to download the file, they will get a filename as the GUID blob name (vs. the original filename). Is there a way to use a GUID for the blob name, but when the user clicks to download the file, the returned file has the original filename? I realize we can download the file to our server and stream a properly named file to the user, but we are trying to keep the load off our web server for file downloads. So is there a configuration setting with a blob that would enable the file to be returned with the proper filename? We can set a MIME type for a blob, and we were looking for a similar setting for the filename part. A: Is there a way to use a GUID for the blob name, but when the user clicks to download the file, the returned file has the original filename? I realize we can download the file to our server and stream a properly named file to the user, but we are trying to keep the load off our web server for file downloads. You can use Content-Disposition property of the blob to achieve this. What you can do is set the name of the blob as GUID however set the content-disposition property of the blob as attachment; filename="original-file-name". If you want the file to be always downloaded, you can permanently set this property. However if you want to only set this name when the file is downloaded, you can create a Shared Access Signature on the blob with Read permission and overwrite this header. I wrote about this in my blog sometime ago. From my blog post: Assume a scenario where you want your users to download the files from your storage account but you wanted to give those files a user friendly name. Furthermore, you want your users to get prompted for saving the file instead of displaying the file in browser itself (say a PDF file opening up automatically in the browser only). To accomplish this, earlier you would need to first fetch the file from your blob storage on to your server and then write the data of that file in the response stream by setting “Content-Disposition” header. In fact, I spent a good part of last week implementing the same solution. Only if I had known that this feature is coming in storage itself:). Now you don’t need to do that. What you could do is specify a content-disposition property on the blob and set that as “attachment; filename=yourdesiredfilename” and when your user tries to access that through a browser, they will be presented with file download option. Now you may ask, what if I have an image file which I want to show inline also and also as a downloadable item also. Very valid requirement. Well, the smart guys in the storage team has already thought about that :). Not only you can set content-disposition as a blob property but you can override this property in a SAS URL (more on it in a bit).
{ "pile_set_name": "StackExchange" }
Q: Pass JSON Data from PHP to Python Script I'd like to be able to pass a PHP array to a Python script, which will utilize the data to perform some tasks. I wanted to try to execute my the Python script from PHP using shell_exec() and pass the JSON data to it (which I'm completely new to). $foods = array("pizza", "french fries"); $result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods))); echo $result; The "escapeshellarg(json_encode($foods)))" function seems to hand off my array as the following to the Python script (I get this value if I 'echo' the function: '["pizza","french fries"]' Then inside the Python script: import sys, json data = json.loads(sys.argv[1]) foods = json.dumps(data) print(foods) This prints out the following to the browser: ["pizza", "french fries"] This is a plain old string, not a list. My question is, how can I best treat this data like a list, or some kind of data structure which I can iterate through with the "," as a delimiter? I don't really want to output the text to the browser, I just want to be able to break down the list into pieces and insert them into a text file on the filesystem. A: Had the same problem Let me show you what I did PHP : base64_encode(json_encode($bodyData)) then json_decode(shell_exec('python ' . base64_encode(json_encode($bodyData)) ); and in Python I have import base64 and content = json.loads(base64.b64decode(sys.argv[1])) as Em L already mentioned :) It works for me Cheers!
{ "pile_set_name": "StackExchange" }
Q: Set a new property of model and not mark it dirty I have a store (with proxy 'memory') and I have an array of models, when I create one model I setted his propety using set(field,newValue) but this methode marks it as derty, I want to know I can set a value of field and not mark it as dirty, here is my example: for(var i=0;i<questions.length;++i){ var question=Ext.create('DCM.model.TCL'); question.set('scope',questions[i].scope); question.set('topic',questions[i].topic); question.set('area',questions[i].area); question.set('target',questions[i].target); var responses=questions[i].responses; var sumJan=0,nbResponsesJan=0; var sumFeb=0,nbResponsesFeb=0; var sumMar=0,nbResponsesMar=0; var sumApr=0,nbResponsesApr=0; var sumMay=0,nbResponsesMay=0; var sumJun=0,nbResponsesJun=0; var sumJul=0,nbResponsesJul=0; var sumAout=0,nbResponsesAout=0; var sumSep=0,nbResponsesSep=0; var sumOct=0,nbResponsesOct=0; var sumNov=0,nbResponsesNov=0; var sumDec=0,nbResponsesDec=0; for(var j=0;j<responses.length;++j){ switch(responses[j].month){ case 0:sumJan+=responses[j].score;++nbResponsesJan;break; case 1:sumFeb+=responses[j].score;++nbResponsesFeb;break; case 2:sumMar+=responses[j].score;++nbResponsesMar;break; case 3:sumApr+=responses[j].score;++nbResponsesApr;break; case 4:sumMay+=responses[j].score;++nbResponsesMay;break; case 5:sumJun+=responses[j].score;++nbResponsesJun;break; case 6:sumJul+=responses[j].score;++nbResponsesJul;break; case 7:sumAout+=responses[j].score;++nbResponsesAout;break; case 8:sumSep+=responses[j].score;++nbResponsesSep;break; case 9:sumOct+=responses[j].score;++nbResponsesOct;break; case 10:sumNov+=responses[j].score;++nbResponsesNov;break; case 11:sumDec+=responses[j].score;++nbResponsesDec;break; } } if(nbResponsesJan>0){ question.set('jan',sumJan/nbResponsesJan); } if(nbResponsesFeb>0){ question.set('feb',sumFeb/nbResponsesFeb); } if(nbResponsesMar>0){ question.set('mar',sumMar/nbResponsesMar); } if(nbResponsesApr>0){ question.set('apr',sumApr/nbResponsesApr); } if(nbResponsesMay>0){ question.set('may',sumMay/nbResponsesMay); } if(nbResponsesJun>0){ question.set('jun',sumJun/nbResponsesJun); } if(nbResponsesJul>0){ question.set('jul',sumJul/nbResponsesJul); } if(nbResponsesAout>0){ question.set('aout',sumAout/nbResponsesAout); } if(nbResponsesSep>0){ question.set('sep',sumSep/nbResponsesSep); } if(nbResponsesOct>0){ question.set('oct',sumOct/nbResponsesOct); } if(nbResponsesNov>0){ question.set('nov',sumNov/nbResponsesNov); } if(nbResponsesDec>0){ question.set('dec',sumDec/nbResponsesDec); } questionsModel[i]=question; } tclController.getStore('TCL').loadRawData(questionsModel); } the rows of my grid look like dirty records, How to resolve it. Thanx. A: With Ext JS 5 and 6 you can pass false to a dirty option. When set to false, then the set field values are to be understood as non-dirty (fresh from the server). The dirty option defaults to true. record.set({ name: 'value', age: 42}, { dirty: false }) Or record.set('age', 42, { dirty: false }) The options parameter of the set method was introduced with Ext JS 5. A: call question.commit() this will do: me.phantom = me.dirty = me.editing = false;
{ "pile_set_name": "StackExchange" }
Q: Resolution for different densities in Android OpenGL ES app I am developing a game for Android using OpenGL ES, and until now I've using only the folder drawable-hdpi for the textures. My biggest textures are 1024x512. Which resolutions should I use for folders mdpi and ldpi? Or should I leave just 1 folder? A: Android's built-in density bitmap scaling solution isn't really helpful for GLES applications, and sometimes can even break things (such as the non-power-of-two bitmap scaling). For this reason (and others), libraries like libgdx have their own asset loading infrastructure. If you want to really keep using bitmap loading from R.drawable, you should put the images in a drawable-nodpi folder instead, so that no pre-scaling is performed. Otherwise it is a good idea to put it under an assets folder. If you want to do scaling for different screen densities (or more likely screen resolutions), you should do this in your code.
{ "pile_set_name": "StackExchange" }
Q: Woocommerce изменение переменной Написал плагин, рассчитывающий цену на доставку товара. Не смог понять как добавлять цену доставки к основной цене товара Woocommerce. Т.е. я сделал товар "Книга" с ценой 100р. На сайте я добавляю товар в корзину. В корзине: интерфейс плагина доставки и ниже Woocommerce c ценой товара 100р. Как мне добавить к этой сумме сумму доставки? add_action('woocommerce_checkout_before_customer_details', 'My_func'); add_action('woocommerce_checkout_update_order_meta', 'my_func',10,2); add_action('woocommerce_shipping_init', 'my_func'); add_action('woocommerce_after_shipping_rate', 'action_woocommerce_after_shipping_rate', 10, 2); add_action('woocommerce_review_order_after_shipping', 'my_func'); A: Надо использовать $woocommerce->cart->add_fee(): function woocommerce_custom_surcharge() { global $woocommerce; if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; $shipping_fee = 10; $woocommerce->cart->add_fee( 'Доставка', $shipping_fee, true, '' ); } add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
{ "pile_set_name": "StackExchange" }
Q: Unity 4.6: Position jumps when switching Canvas render mode from Overlay to camera in code In the project I am currently working on I have two sets of main UI: one set that is on the screen at all times for the players use, and the second set which the player can open and look at to gauge their progress and see things about the game world(think pokedex) . The second set also has 3d models in front of the UI in places. To achieve this, I have a script that changes the canvas render mode to Screen Space - Camera when the 2nd UI opens, and I instantiate a 3d model in front of it. My problem is when I switch the canvas back to Screen Space - Overlay, it jumps down in the corner. My to switch the canvas mode to Camera is as follows: /*--Adjust canvas--*/ canvas.renderMode = RenderMode.OverlayCamera; canvas.planeDistance = canvasPlaneDistance; //1 in this case My code to switch the canvas back to overlay looks like this: /*--Adjust canvas render mode and position--*/ canvas.renderMode = RenderMode.Overlay; I discovered that it seems the problem is because the z pos of the Canvas's Rect Transform changes value when I initially change the render mode and this displaces it when I switch it back. I can adjust it back into position in the code by doing this: canvas.GetComponent<RectTransform>().localPosition = new Vector3(canvas.GetComponent<RectTransform>().localPosition.x, canvas.GetComponent<RectTransform>().localPosition.y, 0); But this causes a disorienting flicker which I would rather avoid. Is there any workaround or fix for this? A: Instead of changing the render mode of the canvas you could instantiate the 3d model and a Camera that points at it in an unused part of the scene (or set the Camera culling settings to only render the 3d model). That camera then renders to a texture that is used by an Image element in the alternate GUI. You'll need Unity Pro though.
{ "pile_set_name": "StackExchange" }
Q: What are these white spots in my bread dough? I'm making hot cross buns following this recipe: https://domesticgothess.com/blog/2020/03/09/vegan-hot-cross-buns/ About an hour into the first rise, I'm seeing these alarmingly mold-like dots in the dough. I didn't see these when I was kneading it. The only things I might've done abnormally for this recipe were: My soy milk might've been a touch too hot when I added the yeast. I was afraid it would kill the yeast, but it looks like the dough has risen normally. Not sure if that has something to do with the appearance of these spots. For the soy milk, I made it using cooked soybeans blended up with water. It was done in a high speed blender and the soy milk appeared quite smooth, but could these be unblended soybean chunks? I used kosher salt. Perhaps the salt was not fully dissolved by the time I let it rise. Are there any other possibilities for what these spots could be? A: It's impossible to say what it is - but I am quite sure what it isn't. I have never seen or heard of a pathogen (mold or otherwise) which is able to build visible colonies during such a short time at room temperature, especially in the presence of yeast. And your yeast was not dead - the dough rising proves it. This is almost sure some ingredient not being mixed well. There are a few alternative explanations such as you covering the bowl with a nonpermeable lid and having enough condensation to drop onto the dough surface, or maybe (and we are getting into really weird/rare territory here) the vegan substitutes acting in unusual ways and managing to clump somehow. I would bake and eat - it is one of the exceptions where I can't connect this unusual photo to the "when in doubt, throw it out" rule.
{ "pile_set_name": "StackExchange" }
Q: Automatic model cache expiry in Rails I was reading a few guides on caching in Rails but I am missing something important that I cannot reconcile. I understand the concept of auto expiring cache keys, and how they are built off a derivative of the model's updated_at attribute, but I cannot figure out how it knows what the updated_at is without first doing a database look-up (which is exactly what the cache is partly designed to avoid)? For example: cache @post Will store the result in a cache key something like: posts/2-20110501232725 As I understand auto expiring cache keys in Rails, if the @post is updated (and the updated_at attribute is changed, then the key will change. But What I cannot figure out, is how will subsequent look-ups to @post know how to get the key without doing a database look-up to GET the new updated_at value? Doesn't Rails have to KNOW what @post.updated_at is before it can access the cached version? In other words, if the key contains the updated_at time stamp, how can you look-up the cache without first knowing what it is? A: In your example, you can't avoid hitting the database. However, the intent of this kind of caching is to avoid doing additional work that is only necessary to do once every time the post changes. Looking up a single row from the database should be extremely quick, and then based on the results of that lookup, you can avoid doing extra work that is more expensive than that single lookup. You haven't specified exactly, but I suspect you're doing this in a view. In that case, the goal would be to avoid fragment building that won't change until the post does. Iteration of various attributes associated with the post and emission of markup to render those attributes can be expensive, depending on the work being done, so given that you have a post already, being able to avoid that work is the gain achieved in this case.
{ "pile_set_name": "StackExchange" }
Q: How to calculate the size of a folder. (This size must agree with Finder.) I need to calculate the size of a folder in MacOS. This size value must agree with Finder. I've tried several ways to do this. but the results are always different from Finder. the following methods are what I tried. typedef struct{ //getResourceValue in NSURL unsigned long long fileSize; unsigned long long fileAllocSize; unsigned long long totalFileSize; unsigned long long totalFileAllocSize; //lstat in posix unsigned long long statSize; unsigned long long blockSize; //NSFileManager unsigned long long cocoaSizeNo; unsigned long long cocoaSizeYes }sizePack; - (sizePack)foldSize:(NSString *)direString{ sizePack sizeP; memset(&sizeP, 0, sizeof(sizeP)); NSFileManager *fileManager = [NSFileManager defaultManager]; NSArray *tempArray = [fileManager contentsOfDirectoryAtPath:direString error:nil]; for (NSString *fileName in tempArray) { BOOL flag = YES; NSString *fullPath = [direString stringByAppendingPathComponent:fileName]; if ([fileManager fileExistsAtPath:fullPath isDirectory:&flag]) { if (!flag) { NSNumber* FileSize; NSNumber* FileAllocatedSize; NSNumber* TotalFileSize; NSNumber* TotalAllocatedSize; NSURL* url = [NSURL fileURLWithPath:fullPath]; [url getResourceValue:&FileSize forKey:NSURLFileSizeKey error:nil]; [url getResourceValue:&FileAllocatedSize forKey:NSURLFileAllocatedSizeKey error:nil]; [url getResourceValue:&TotalFileSize forKey:NSURLTotalFileSizeKey error:nil]; [url getResourceValue:&TotalAllocatedSize forKey:NSURLTotalFileAllocatedSizeKey error:nil]; struct stat statbuf; stat([fullPath UTF8String], &statbuf); unsigned long long fileSize = [FileSize unsignedLongLongValue]; unsigned long long fileAllocSize = [FileAllocatedSize unsignedLongLongValue]; unsigned long long totalFileSize = [TotalFileSize unsignedLongLongValue]; unsigned long long totalFileAllocSize = [TotalAllocatedSize unsignedLongLongValue]; unsigned long long cocoaSizeNO = [[[NSFileManager defaultManager] fileAttributesAtPath:fullPath traverseLink:NO] fileSize]; unsigned long long cocoaSizeYES = [[[NSFileManager defaultManager] fileAttributesAtPath:fullPath traverseLink:YES] fileSize]; sizeP.fileSize += fileSize; sizeP.fileAllocSize += fileAllocSize; sizeP.totalFileSize += totalFileSize; sizeP.totalFileAllocSize += totalFileAllocSize; sizeP.statSize += statbuf.st_size; sizeP.blockSize += statbuf.st_blksize; sizeP.cocoaSizeNo += cocoaSizeNO; sizeP.cocoaSizeYes += cocoaSizeYES; } else { sizePack tmp = [self foldSize:fullPath]; sizeP.fileSize += tmp.fileSize; sizeP.fileAllocSize += tmp.fileAllocSize; sizeP.totalFileSize += tmp.totalFileSize; sizeP.totalFileAllocSize += tmp.totalFileAllocSize; sizeP.statSize += tmp.statSize; sizeP.blockSize += tmp.blockSize*4096; sizeP.cocoaSizeNo += tmp.cocoaSizeNo; sizeP.cocoaSizeYes += tmp.cocoaSizeYes; } } } return sizeP; } A: - (unsigned long long) folderSizeWithFSRef:(FSRef*)theFileRef { FSIterator thisDirEnum = NULL; unsigned long long totalSize = 0; // Iterate the directory contents, recursing as necessary if (FSOpenIterator(theFileRef, kFSIterateFlat, &thisDirEnum) == noErr) { const ItemCount kMaxEntriesPerFetch = 256; ItemCount actualFetched; FSRef fetchedRefs[kMaxEntriesPerFetch]; FSCatalogInfo fetchedInfos[kMaxEntriesPerFetch]; OSErr fsErr = FSGetCatalogInfoBulk(thisDirEnum, kMaxEntriesPerFetch, &actualFetched, NULL, kFSCatInfoDataSizes | kFSCatInfoRsrcSizes | kFSCatInfoNodeFlags, fetchedInfos, fetchedRefs, NULL, NULL); while ((fsErr == noErr) || (fsErr == errFSNoMoreItems)) { ItemCount thisIndex; for (thisIndex = 0; thisIndex < actualFetched; thisIndex++) { // Recurse if it's a folder if (fetchedInfos[thisIndex].nodeFlags & kFSNodeIsDirectoryMask) { totalSize += [self folderSizeWithFSRef:&fetchedRefs[thisIndex]]; } else { // add the size for this item totalSize += fetchedInfos[thisIndex].dataLogicalSize; totalSize += fetchedInfos[thisIndex].rsrcLogicalSize; } } if (fsErr == errFSNoMoreItems) { break; } else { // get more items fsErr = FSGetCatalogInfoBulk(thisDirEnum, kMaxEntriesPerFetch, &actualFetched, NULL, kFSCatInfoDataSizes | kFSCatInfoRsrcSizes | kFSCatInfoNodeFlags, fetchedInfos, fetchedRefs, NULL, NULL); } } FSCloseIterator(thisDirEnum); } return totalSize; } - (unsigned long long) sizeOfFileWithURL:(NSURL *)aURL { NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:aURL.path error:nil]; if ([attr objectForKey:NSFileType] == NSFileTypeDirectory) { FSRef theFileRef; CFURLGetFSRef((__bridge CFURLRef)aURL, &theFileRef); return [self folderSizeWithFSRef:&theFileRef]; } else { return [[attr objectForKey:NSFileSize] longValue]; } } I also noticed that finder does not divide by 1024, but by 1000 when calculating size. Strange
{ "pile_set_name": "StackExchange" }
Q: C# reactive extension - Join() overloads Reactive Extensions has the extension method: Join(this IObservable<TLeft> left, IObservable<TRight> right, Func<TLeft, IObservable<TLeftDuration>> leftDurationSelector, Func<TRight, IObservable<TRightDuration>> rightDurationSelector, Func<TLeft, TRight, TResult> resultSelector) However, there is no overload that also takes a Func<TLeft, TRight, bool> as a join condition. As a result this method returns a full Cartesian product of the left and right. I have implemented this as public static IObservable<TResult> Join<TLeft, TRight, TResult>( this IObservable<TLeft> left, IObservable<TRight> right, Func<TLeft, TRight, bool> joinCondition, Func<TLeft, TRight, TResult> resultSelector) { return left.Join(right, l => Observable.Never<TLeft>(), r => Observable.Never<TRight>(), (l, r) => new Tuple<TLeft, TRight>(l, r)) .Where(CurryTuple(joinCondition)) .Select(CurryTuple(resultSelector)); } private static Func<Tuple<TLeft, TRight>, TResult> CurryTuple<TLeft, TRight, TResult>(Func<TLeft, TRight, TResult> func) { return tuple => func(tuple.Item1, tuple.Item2); } As I am using this more I am wondering if I might require more similar methods (perhaps outer joins - whatever that means for Observables). Rather than trying to implement them all (and bring in the potential for bugs and sub-optimal code) I was wondering if someone else has had the same problem and if there are libraries that have already been written. Any ideas? A: I think you have misunderstood how reactive joins work. The join condition is event coincidence, not a binary operation you supply. Basically each event gets a duration attached to it, and events from left and right sources that exist at the same time are joined. Have a look at this video for more explanation. The result of a reactive join is the Cartesian product if the durations are non-terminating - as you have made them in your sample. What you are doing is going to give some very poor performance characteristics. Can you provide marble diagrams, unit tests and/or example scenarios of what you are trying to achieve? I suspect there will be a better way without using a Join.
{ "pile_set_name": "StackExchange" }
Q: How to place marker on google maps, given input (latitude, longitude) I want to insert the latitude and longitude and I want to place a marker on the map with the latitude and longitude specified when clicking the biutton. I also want the marker placed to have the characteristics that the code shows, meaning, 3 buttons and some information that was given when the marker was placed ("data" and "fotografia") I don't know how to fix this error because when I click F12, it doesn't recognize any errors. <div class="row"> <div id="map"></div> <script> var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 7, center: { lat: 39.397, lng: -8 } }); // setMarkers(map); } /*ignições var locations = [ ["Recusado", "13/02/2019", 38.776816, -9.441833, 335, "foto.jpg",], ["Aceite", "15/08/2019", 38.817562, -8.941728, 36, "foto.jpg"], ["Em avaliação", "20/07/2019", 38.487978, -9.004425, 90, "foto.jpg"], ["Concluído", "01/07/2019", 37.045804, -8.898041, 12, "foto.jpg"] ];*/ function setMarkers(map,lat, long, data, fotografia) { var latlong = lat + "," + long; //var bounds = new google.maps.LatLngBounds(); var marker; var contentString = '<div id="content">' + '<div id="siteNotice">' + '</div>' + '<div id="bodyContent">' + '<p><b>Avaliação da Ocorrência:</b></p>' + '<p>Fotografias:' + fotografia + '</p>' + '<p>Avaliação:</p>' + '<p>Data:' + data + '</p></br>' + '<button id="aceite" >Aceitar</button>' + '<button id="recusado">Recusar</button>' + //'<button> Em avaliação</button>' + '<button id="concluido"> Concluído</button>' + '</div>'; var infoWindow = new google.maps.InfoWindow({ content: contentString }); var myLatLgn = new google.maps.LatLng(lat, long); marker = new google.maps.Marker({ position: myLatLgn, map: map, info: contentString, icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png' }); //bounds.extend(marker.getPosition()); google.maps.event.addListener(marker, 'click', function () { marker = this; infoWindow.setContent(this.info); google.maps.event.addListener(infoWindow, 'domready', function () { google.maps.event.addDomListener(document.getElementById("recusado"), 'click', function (e) { marker.setMap(null); }) google.maps.event.addDomListener(document.getElementById("aceite"), 'click', function (e) { marker.setIcon('https://maps.google.com/mapfiles/marker_green.png'); }) google.maps.event.addDomListener(document.getElementById("concluido"), 'click', function (e) { marker.setIcon('https://maps.google.com/mapfiles/marker_grey.png'); }) }); infoWindow.open(map, this); }); } // map.fitBounds(bounds); </script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyABFYXhqed9HKYt20cFIqQ6nmmPDZTr09c&callback=initMap" async defer></script> </div> latitude: <input id="latitude" type="text" /> <br /> longitude: <input id="longitude" type="text" /> <br /> data: <input id="data" type="text" /> <br /> fotografia: <input id="fotografia" type="text" /> <br /> <input id="marcar" type="button" value="Marcar" onclick="setMarkers(map.value,latitude.value, longitude.value, data.value, fotografia.value)" /> I just want to input some informations like "latitude", "longitude", "data" and "fotografia", and based on that information, mainly latitude and longitude, it's placed a marker on the map with its infowindow. A: You have a typo in your click listener function's arguments: <input id="marcar" type="button" value="Marcar" onclick="setMarkers(map.value,latitude.value, longitude.value, data.value, fotografia.value)" /> Should be (you want to pass in the map variable, not map.value): <input id="marcar" type="button" value="Marcar" onclick="setMarkers(map, latitude.value, longitude.value, data.value, fotografia.value)" /> proof of concept fiddle code snippet: html, body, #map { height: 100%; width: 100%; margin: 0; padding: 0; } .row { height: 60%; } <div class="row"> <div id="map"></div> <script> var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 7, center: { lat: 39.397, lng: -8 } }); } function setMarkers(map, lat, long, data, fotografia) { console.log("lat=" + lat + " long=" + long + " data=" + data + " fotografia=" + fotografia); var latlong = lat + "," + long; //var bounds = new google.maps.LatLngBounds(); var marker; var contentString = '<div id="content">' + '<div id="siteNotice">' + '</div>' + '<div id="bodyContent">' + '<p><b>Avaliação da Ocorrência:</b></p>' + '<p>Fotografias:' + fotografia + '</p>' + '<p>Avaliação:</p>' + '<p>Data:' + data + '</p></br>' + '<button id="aceite" >Aceitar</button>' + '<button id="recusado">Recusar</button>' + //'<button> Em avaliação</button>' + '<button id="concluido"> Concluído</button>' + '</div>'; var infoWindow = new google.maps.InfoWindow({ content: contentString }); var myLatLgn = new google.maps.LatLng(lat, long); marker = new google.maps.Marker({ position: myLatLgn, map: map, info: contentString, icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png' }); //bounds.extend(marker.getPosition()); google.maps.event.addListener(marker, 'click', function() { marker = this; infoWindow.setContent(this.info); google.maps.event.addListener(infoWindow, 'domready', function() { google.maps.event.addDomListener(document.getElementById("recusado"), 'click', function(e) { marker.setMap(null); }) google.maps.event.addDomListener(document.getElementById("aceite"), 'click', function(e) { marker.setIcon('https://maps.google.com/mapfiles/marker_green.png'); }) google.maps.event.addDomListener(document.getElementById("concluido"), 'click', function(e) { marker.setIcon('https://maps.google.com/mapfiles/marker_grey.png'); }) }); infoWindow.open(map, this); }); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script> </div> latitude: <input id="latitude" type="text" value="39.397" /> <br /> longitude: <input id="longitude" type="text" value="-8.001" /> <br /> data: <input id="data" type="text" value="data" /> <br /> fotografia: <input id="fotografia" type="text" value="fotografia" /> <br /> <input id="marcar" type="button" value="Marcar" onclick="setMarkers(map, latitude.value, longitude.value, data.value, fotografia.value)" />
{ "pile_set_name": "StackExchange" }
Q: CodeIgniter 3.0.2 does not login with old code User_log.php (This is controller File) <?php class User_log extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('user_data'); } public function index($msg = NULL) { $data['msg'] = $msg; $data['title'] = "My Real Title"; $data['heading'] = "My Real Heading"; $data['attribute'] = array('name' => 'process'); $data['data'] = array( 'name' => 'username', 'id' => 'username', ); $data['pass'] = array( 'name' => 'password', 'id' => 'password', ); $this->load->view('login', $data); } public function process() { // Load the model $this->load->model('user_data'); // Validate the user can login $result = $this->user_data->validate(); // Now we verify the result if(! $result){ // If user did not validate, then show them login page again $msg = '<font color=red>Invalid username and/or password.</font><br />'; $this->index($msg); }else{ // If user did validate, // Send them to members area redirect('success'); } } } User_data.php (This is model file) <?php class User_data extends CI_Model { public function __construct() { parent::__construct(); } public function validate() { $username = $this->security->xss_clean($this->input- >post('username')); $password = $this->security->xss_clean($this->input- >post('password')); $this->db->where('username', $username); $this->db->where('password', $password); $query = $this->db->get('user'); if($query->num_rows == 1) { // If there is a user, then create session data $row = $query->row(); $data = array( 'id' => $row->id, 'username' => $row->username, 'validated' => true ); $this->session->set_userdata($data); return true; } return false; } } login.php (This is view file) <head> <title>Jotorres Login Screen | Welcome </title> </head> <body> <div id='login_form'> <form action='<?php echo base_url();?>index.php/blog/process' method='post' name='process'> <h2>User Login</h2> <br /> <label for='username'>Username</label> <input type='text' name='username' id='username' size='25' /><br /> <label for='password'>Password</label> <input type='password' name='password' id='password' size='25' /><br /> <input type='Submit' value='Login' /> </form> </div> </body> </html> Where is the problem of this code? Is not working properly in CodeIgniter version 3.0. A: According to the code provided, your form action is wrong. <form action='<?php echo base_url();?>index.php/blog/process' method='post' name='process'> ^ ^ This should be <form action='<?php echo base_url();?>index.php/user_log/process' method='post' name='process'> ^ ^ Instead of blog, it should be user_log. Also you are not echoing the error message in login page. Add this some where in your login.php may be after your <form> tag. <?= $msg ?>
{ "pile_set_name": "StackExchange" }
Q: creating fixed number for id in sql programming I am trying to have 10 numbers for my id column in sql and number only. I want to check the input is only from 0000000000 to 9999999999. I wrote the following codes but I am not sure where goes wrong as it lets A000000000 pass the checking. Please help me! Thanks a lot! create table member ( member_id char(10) primary key, check (member_id not like '%^[0-9]%' and char_length(member_id) = 10) ); insert into member values ('A000000000') A: change member_id not like '%^[0-9]%' to member_id not ~ '^[0-9]{10}' for regular expression ~ operator is used instead of like your example like '%^[0-9]%' checks for exact match of ^[0-9] string in any place
{ "pile_set_name": "StackExchange" }
Q: Remotely check CPU, memory and disk space IBM Bluemix PHP instance Remotely check CPU, memory and disk space IBM Bluemix PHP instance. I have a php instance running in IBM Bluemix. Now I want to check the CPU, Memory and Disk Space from an external program by calling a php web page. For CPU I tried the following function: function get_server_cpu_usage(){ $load = sys_getloadavg(); $cores = shell_exec("grep 'model name' /proc/cpuinfo | wc -l"); $load[2] = ($load[2] / $cores) * 100; return $load[2]; } For Memory I use the following function: memory_get_usage(true) For Disk Space I use the following function: disk_free_space("/") But when I compare these results with the results provided by the IBM Bluemix Console, they are different. Is there a correct way to externally monitor these values? A: You can retrieve that information using CF API REST call. You can find the CF APIs documentation here: Application summary: https://apidocs.cloudfoundry.org/234/apps/get_app_summary.html Detailed application stats: https://apidocs.cloudfoundry.org/234/apps/get_detailed_stats_for_a_started_app.html In this specific case you could do a curl call from your php application and parse the JSON response for CPU, Memory and Disk Space information. curl "https://api.ng.bluemix.net/v2/apps/YOURAPP_GUID/summary" -X GET -H "Authorization: bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoidWFhLWlkLTQyNCIsImVtYWlsIjoiZW1haWwtMjkzQHNvbWVkb21haW4uY29tIiwic2NvcGUiOlsiY2xvdWRfY29udHJvbGxlci5hZG1pbiJdLCJhdWQiOlsiY2xvdWRfY29udHJvbGxlciJdLCJleHAiOjE0NjA1MDY2NjF9.iUpeFnPKDWf3sxvDB0RF2_nSLAkqLZP7iN6Nx0bWE-Q" You can retrieve the Authorization header with: cf oauth-token after login to IBM Bluemix (cf login) If you want retrieve the auth-token from your application you should use another REST API before running the first curl get. curl -s -X POST -H "Accept-Encoding: application/json" -d "grant_type=password&password=YOURPASSWORD&scope=&username=YOURUSERNAME" -u "cf:" https://login.ng.bluemix.net/UAALoginServerWAR/oauth/token
{ "pile_set_name": "StackExchange" }
Q: PyOpenGL Polygon See Through Colors I have a problem with PyOpenGL. this is my code: import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from math import * a=[[cos(0.5*pi/180),sin(0.5*pi/180),0], [-sin(0.5*pi/180),cos(0.5*pi/180),0], [0,0,1]] def zarb_matris(p,b): c=[b[0][0]*p[0][0]+b[0][1]*p[1][0]+b[0][2]*p[2][0], b[1][0]*p[0][0]+b[1][1]*p[1][0]+b[1][2]*p[2][0], b[2][0]*p[0][0]+b[2][1]*p[1][0]+b[2][2]*p[2][0]] return c verticies= [ [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1], [1, -1, 1], [1, 1, 1], [-1, -1, 1], [-1, 1, 1] ] edges = ( (0,1), (0,3), (0,4), (2,1), (2,3), (2,7), (6,3), (6,4), (6,7), (5,1), (5,4), (5,7), ) surfaces= ( (0,1,2,3), (3,2,7,6), (6,7,5,4), (4,5,1,0), (1,5,7,2), (4,0,3,6) ) ## (0,3,2,1), ## (6,7,2,3), ## (4,5,7,6), ## (4,0,1,5), ## (5,1,2,7), ## (4,0,3,6) ## ) colors = ( (0.9,0,0),#red (0,1,0),#green (0.75,0.38,0),#orange (0,0,1),#blue (1,1,0),#yellow (1,1,1), (1,0,0), (0,1,0), (0.75,0.38,0), (0,0,1), (1,1,0), (0.9,1,1) ) def Cube(): global verticies glBegin(GL_QUADS) x = 0 for surface in surfaces: x+=1 for vertex in surface: glColor3fv(colors[x]) glVertex3fv(verticies[vertex]) glEnd() glBegin(GL_LINES) glColor3fv((1,1,1)) for edge in edges: for vertex in edge: glVertex3fv(verticies[vertex]) glEnd() def main(): global s pygame.init() display = (800,600) pygame.display.set_mode(display, DOUBLEBUF|OPENGL) gluPerspective(45, (display[0]/display[1]), 0.1, 50.0) glTranslatef(1,1, -10) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() glRotatef(1, 12, 1, 1) for i in range(8): s=[] for j in verticies[i]: s.append([j]) k=zarb_matris(s,a) verticies[i]=k glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) Cube() pygame.display.flip() pygame.time.wait(10) main() It just shows a simple cube with colored faces. The colors are not solid and you can see through them. What should I do to fix this problem? Any help would be greatly appreciated. A: I can see from your commented out part that you may have suspected the winding order of your quads as the culprit, but that's not the actual problem here. However, it's still a good practice to use the winding order together with back face culling to reduce the unnecessary work the graphics card has to perform. (With all values at their defaults, your second commented set of surfaces is the correct one, apart from the last surface which you still need to turn around.) The real problem here is that you need to enable features - even very basic ones that you intuitively assume to be there - before they will be used. After set_mode() put this: glEnable(GL_DEPTH_TEST) Without that, the primitives are simply drawn in the order they come in without looking at the depth buffer (it's just ignored). Thus some faces and some lines that actually lie behind others will unexpectedly be drawn on top of them due to be rendered later. Note that you should also enable back face culling (after commenting the first set and uncommenting the second set of surfaces), as it won't be used either by default: glEnable(GL_CULL_FACE) Note also that if you didn't have lines (you can try by commenting out that part of your code), the depth test wouldn't strictly be required, as a cube is a convex shape and back face culling alone would do the trick (this won't work for concave shapes or complex scenes, obviously).
{ "pile_set_name": "StackExchange" }
Q: Max() with different label array This is my code for function, each variable has different label with array: I want to find max value from this code. $user_id = Auth::user()->id; $first_hour = DB::table('finaltrade') ->select(DB::raw('count(*) as first')) ->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id') ->where('finaltrade.user_id', $user_id) ->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '>=', DB::raw('exchanges.start_time')) ->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '<=', DB::raw("ADDTIME(exchanges.start_time, '01:00:00')")) ->first(); $last_hour = DB::table('finaltrade') ->select(DB::raw('count(*) as last')) ->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id') ->where('finaltrade.user_id', $user_id) ->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '<=', DB::raw('exchanges.close_time')) ->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '>=', DB::raw("SUBTIME(exchanges.close_time, '01:00:00')")) ->first(); $other_hours = DB::table('finaltrade') ->select(DB::raw('count(*) as other')) ->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id') ->where('finaltrade.user_id', $user_id) ->whereRaw('finaltrade.created_at NOT BETWEEN exchanges.start_time AND DATE_ADD(exchanges.start_time, INTERVAL 1 HOUR)') ->whereRaw('finaltrade.created_at NOT BETWEEN exchanges.close_time AND DATE_SUB(exchanges.close_time, INTERVAL 1 HOUR)') ->first(); $allTrades = array($first_hour, $last_hour,$other_hours ); $max =0; Foreach($allTrades as $key => $val){ $temp = max($val); If($temp > $max){ $max = $temp; $place = $key . " => " . Key($val); } } Echo $max; Echo "\n" . $place; How to get max value from this type of array in arrays? Every array has different name : first, last and other this is result of variable: A: Use corected code $allTrades = array($first_hour, $last_hour,$other_hours ); $max = 0; $property = ''; foreach ($allTrades as $stdObject) { $propertyValues = get_object_vars($stdObject); foreach ($propertyValues as $prop => $value) { if ($value > $max) { $max = $value; $property = $prop; } } } echo $max; echo $property; or one step less if know $first_hour object structure $allTrades = array($last_hour,$other_hours ); $max = $first_hour->first; $property = 'first'; foreach ($allTrades as $stdObject) { $propertyValues = get_object_vars($stdObject); foreach ($propertyValues as $prop => $value) { if ($value > $max) { $max = $value; $property = $prop; } } } echo $max; echo $property;
{ "pile_set_name": "StackExchange" }
Q: How to remove duplicate objects from json array using hashset? Any one help me out from this issue, How to remove duplicate objects from JSON using JAVA hash set? Here I want to remove duplicates from below JSON { "others":[ { "id":"1", "caption":"test" }, { "id":"2", "caption":"self" }, { "id":"2", "caption":"Self" }, { "id":"1", "caption":"test" } ], "quantity":[ { "id":"1", "caption":"self1" }, { "id":"1", "caption":"self1" } ]} A: Below code parses your json and puts it in the HashMap to get unique elements HashMap<String,String> hashOut = new HashMap<String,String>(); String input = "{\"others\":[ { \"id\":\"1\", \"caption\":\"test\" }, { \"id\":\"2\", \"caption\":\"self\" }, { \"id\":\"2\", \"caption\":\"self\" }, { \"id\":\"1\", \"caption\":\"test\" }],\"quantity\":[ { \"id\":\"1\", \"caption\":\"self1\" }, { \"id\":\"1\", \"caption\":\"self1\" }]}"; JSONObject jsonObj = new JSONObject(input); Iterator it = jsonObj.keys(); while (it.hasNext()) { hashOut.clear(); JSONArray jsInner = (JSONArray) jsonObj.getJSONArray((String) it.next()); for (int i=0;i<jsInner.length();i++) { JSONObject jo = new JSONObject(jsInner.get(i).toString()); hashOut.put((String)jo.get("id"), (String)jo.get("caption")); } System.out.println(hashOut); } To get the output as below {2=self, 1=test} {1=self1}
{ "pile_set_name": "StackExchange" }
Q: declared name in.h but reports undeclare in .cpp in Xcode Below is my code: MathCore.h #ifndef __CC_MATHCORE_H__ #define __CC_MATHCORE_H__ #include "math.h" class MathCore { public: MathCore(); virtual ~MathCore( ); int x (int n ); }; #endif MathCore.cpp #ifndef __CC_MATHCORE_H__ #define __CC_MATHCORE_H__ #include "MathCore.h" MathCore::MathCore()//a { } MathCore::~ MathCore()//b { } int MathCore::x (int n )//c { float v=0; return v; } #endif but it erports error at a:C++ requires a type specifier for all declarations Use of undeclared identifier 'MathCore' b:Expected a class or namespace c:Expected a class or namespace Your comment welcome A: You shouldn't have that #define in both the .cpp and .h files, as it will prevent the contents of the .h file from actually being included. When you #include a file, for all practical purposes it behaves the same way as copying and pasting that file into wherever you have the #include. So, the first few lines of your MathCore.cpp are effectively this: #ifndef __CC_MATHCORE_H__ #define __CC_MATHCORE_H__ #ifndef __CC_MATHCORE_H__ #define __CC_MATHCORE_H__ /* the rest of your .h file here */ When restructured that way, it becomes a little more obvious, that second #ifndef can never match since the symbol it's checking is defined immediately above. A: Because, in your C++ file, you're using the same header guards as your header. The second line defines __CC_MATHCORE_H__. After this, you include the header, which does nothing if __CC_MATHCORE_H__ is defined. Remove the guard from the cpp file, and you'll be fine. Guards are rarely, if ever, needed in actual implementation files.
{ "pile_set_name": "StackExchange" }
Q: "distinguishability" of 1D identical particles Recently when I deal with 1D electron system, it occurred to my mind that since these electrons are not able to bypass each other during the scattering processes, we can actually label them as the 1st, 2nd,..., Nth electron. As a result, it seems that these electrons now become distinguishable. so my questions is: does this kind of distinguishability have any deep physical consequences? For instance, for 3D identical particles the wave function has to be either symmetric or anti-symmetric, whereas in 2D case we have the interesting anyons that obey a different statistics. Then what about the 1D case? Further more, what kind of distribution functions should we use (i.e. Fermi-Dirac or Bose-Einstein)? I do remember that in undergraduate condensed matter modules people deal with 1D electron gas using Fermi-Dirac distribution, but now it seems not so natural to me. A: Your intuition is exactly correct. In 1D, fermions and "hard-core" bosons (i.e. bosons with strong on-site repulsion that prohibits putting two bosons on the same site) are exactly dual to each other and produce the same energy spectrum for any given Hamiltonian. This (nonlocal) duality is easy to construct: a system of fermions is dual to a spin-1/2 chain by the (nonlocal) Jordan-Wigner transformation, and a system of hard-core bosons is dual to a spin-1/2 chain by the (local) Holstein-Primakoff transformation. By composing the two dualities together and "passing through" the intermediate spin-1/2 chain, you get get a duality between fermions and hard-core bosons. A: One can also label the electrons in an atom by the energy in its Hartree-Fock approximation, and thus makes them distinguishable. This has physical consequences, for example one can speak unambiguously about the outer electron of a Lithium atom. For a 1D quantum system one may have nonstandard statistics related to the braid group. Instead of Bose or Fermi statistics one has exchange relations satisfying Yang-Baxter equations. There is a nearly endless literature about this and the related quantum groups. In 1D there is also no spin-statistic theorem, and one can describe bosons by fermionic fields and conversely.
{ "pile_set_name": "StackExchange" }
Q: Is my answer a duplicate? I recently answered a word request question without having read any other answers. In the question, the OP suggested the best word that came to their mind, and my answer agreed with their suggestion. It was later brought to my attention that another user's answer had also agreed with the OP's suggested word, and they are now demanding I remove my answer, claiming it is a duplicate of theirs. I am unsure if this is a just course of action. The post I am being accused of duplicating did not define the suggested word as I did, and additionally suggested many, many other words, which I did not. We both agreed with the OP, but I do not think this is grounds for being a duplicate. It's not even as though I took the other answer's idea, it was the OP's. If the community at large seems to think I should delete my answer, however, I will do it. A: Duplicate answers, in the sense that the same answer is given but the post is not literally the same, are permitted by Stack Exchange policy. This allows users to provide different explanations, or provide their own take on the matter. However, for obvious reasons, we do not accept copy-and-pasted answers. As your answer is of the former kind, there is no issue with it. I have removed the comments on the answer accordingly.
{ "pile_set_name": "StackExchange" }
Q: Highcharts yAxis labels inside plot area and left padding I have a column chart that has yAxis labels inside the plot area. DEMO: http://jsfiddle.net/o4abatfo/ This is how I have set up the labels: yAxis: { labels: { align: 'left', x: 5, y: -3 } } The problem is that the leftmost column is so near the plot area edge that labels are overlapping it. Is there a way to adjust the plot area padding so that the columns would start a bit further on the right? A: I asked the same thing in the Highcharts forum and got this solution as a reply from @paweł-fus: var chartExtraMargin = 30; Highcharts.wrap(Highcharts.Axis.prototype, 'setAxisSize', function (p) { p.call(this); if (this.isXAxis) { this.left += chartExtraMargin; this.width -= chartExtraMargin; this.len = Math.max(this.horiz ? this.width : this.height, 0); this.pos = this.horiz ? this.left : this.top; } }); However, adding this made the tooltips appear in the wrong position. This was fixed by overriding the Tooltip.prototype.getAnchor() method and adding the extra margin in the x coordinate: Highcharts.wrap(Highcharts.Tooltip.prototype, 'getAnchor', function(p, points, mouseEvent) { var anchor = p.call(this, points, mouseEvent); anchor[0] += chartExtraMargin; return anchor; });
{ "pile_set_name": "StackExchange" }
Q: Should users be able to migrate their own questions to another Stack Exchange site? It might be an idea to allow users to migrate their own questions between sites. This can for example be allowed when all the following condition match: The question has a maximum of X up-votes (for example 5)1, The user had a minimal reputation of X on both the source and the target site (for example 1.000) The question is not older than X amount of time (for example a week). Sometimes I see questions that will fit way better on another site in the Stack Exchange family. Any thoughts on such a feature? Also a badge can be created for the first move and maybe others related to moving. Note: The threshold will be high, because a certain number of reputation points on both sites and the amount of votes and question age will limit the range of questions that can be self-migrated. Therefore it will prevent users from massively starting to migrate questions. The reputation makes self-migration a privilege to be earned. 1. Upvotes only because a question is likely to be downvoted when asked on the wrong site. And unlikely to be upvoted on the wrong site. A: To a degree, the question asker already has this control... if a user requests that their question be moved using the "In need of moderator attention" flag and the mods determine that the question is a good fit on the other site, the question is quite likely to be moved... Or, if the question meets the deletion requirements, they can simply delete it and re-ask it on the other site, no migration necessary. I don't know why self-migration is needed. The badges are outright horrid ideas because then people will start intentionally asking questions on the wrong site just so they can migrate them.
{ "pile_set_name": "StackExchange" }
Q: C++ compiling error template-related I'm a newbie in c++ and I have this piece of code: #include "passenger.h" #include "plane_list.h" int main(){ plane_list<T>::plane_list(); plane_list<T>::add(); } and I don't understand nor can I seem to find an answer online why I get these errors: error: ‘T’ was not declared in this scope plane_list::plane_list(); error: template argument 1 is invalid plane_list::plane_list(); error: invalid type in declaration before ‘;’ token plane_list::plane_list(); error: ‘::add’ has not been declared plane_list::add(); This is the header file: template <class T> class plane_list{ friend class planes; public: plane_list(); ~plane_list(); int search(const std::string &flight_code); plane_list<T> del(const std::string &flight_code); plane_list<T> add(); private: T *element; int length; }; template <class T> plane_list<T>::plane_list(){ element = new T[100]; length=0; } template <class T> int plane_list<T>::search(const std::string &flight_code){ for(int i=0;i<length;i++)if(element[i]._flight_code==flight_code)return i; return 0; } template <class T> plane_list<T> plane_list<T>::del(const std::string &flight_code){ if(search(flight_code)!=0){ for(int i=search(flight_code); i<length; i++)element[i-1]=element[i]; length--; return *this; } else std::cerr<<"Did not find flight"<<std::endl; } template <class T> plane_list<T> plane_list<T>::add(){ element[length]=planes::planes(); length++; return *this; } Any help would be appreciated. A: The issue is that there is no type T. I am assuming that plane_list is some template class like this: template<typename T> class plane_list{ //... } Here the typename T is a placeholder for some type that will be provided when you instantiate the class. You are getting an error because you are trying to instantiate the plane_list with a type that does not exists. To use your class correctly you need to change T to some other type: //for example you could use an int int main(){ plane_list<int>::plane_list(); plane_list<int>::add(); } Without knowing the contents of plane_list.h I cannot infer what you are actually trying to do. EDIT: As suggested in the comments. You are using the incorrect syntax for instantiating and using your variable. The correct usage would be: int main(int argc, char** argv){ //create a variable of type plane_list<int> names "list: plane_list<int> list; //default constructor is called automatically list.add(); ///call the member function "add" } Additionally your code has a memory leak, you allocate the array 'element' with dynamic storage by calling new in your constructor, but never call delete element anywhere which causes the leak. There are several ways to fix this: Add a destructor and call delete element in it. Use std::vector<T> if you need to resize the array. Use std::unique_ptr<T> if you need a fixed length array of runtime determined length. Don't use dynamic memory since you are allocating an array with compile time size. I will not provide an example of each of these, but I would recommend reading up on memory management in C++. Go through your header and be sure to correct the your function call syntax. There are a few places where you are using the same incorrect syntax within your class. For example: template <class T> plane_list<T> plane_list<T>::add(){ //element[length]=planes::planes(); element[length]=planes{}; //default initialize a "planes" object length++; return *this; }
{ "pile_set_name": "StackExchange" }
Q: A correct word for 'learnful' I’m looking for a word that would fit in the sentence it was a very learnful experience: i.e., I learned a lot during that experience. Learnful feels correct to me, but the dictionary disagrees. It’s possible I’'m incorrectly assuming there is an English equivalent to the Dutch word leerzaam, but I can’t imagine there is no word to convey such a meaning. Google Translate suggests instructive or informative, but those seem to either mean providing ways of doing things or factual information. What I want it to mean is more abstract, including things like skills and insights and overall growth in competency. Interestingly, I do now think that the Dutch word leerzaam might not be translatable to English after all; so if someone (Dutch) has some thoughts on this, it might be of interest, since the languages are so similar. I’m trying to think of a nice counterexample, but the best I can come up with now is this: Although it was a setback that my roof collapsed, it was an educational experience, and I would never start a home improvement project without proper preparation again. That does sound pretty awkward in English, right? A: The term instructive can be used in the sentence: Conveying knowledge or information; enlightening.(AHD) or educational: Serving to educate; instructive: an educational film.(AHD) A: It was a very edifying experience. Edifying: adjective Providing moral or intellectual instruction ODO A: Your original sentence "It was a very learnful experience" would normally be phrased "The experience was very educational" or "It was a very instructive/informative experience" Educate, inform, instruct, teach, have similar meanings and can be substituted for leerzaam when translating to English. Instructive is likely the one that best fits your intention. The context of the sentence would clarify what was learned. Leerzaam in English would be educational, informative, instructive. Instructief and informatief in fact are given as Dutch synonyms for leerzaam As so often happens, the word does not have an exact counterpart in English, but rather a short list of words with similar meanings that cover various specific uses of the word being translated.
{ "pile_set_name": "StackExchange" }
Q: mvc3 dapper parameter issue I have dapper working correctly, but it is unsecure as in I haven't been using parameters, how can I best turn my dapper variables into parameters for instance this is the unparameterized code that I had that worked.. var getinfo = sqlConnection.Query<test>("Select name,location from tests where location="+ myplace).FirstOrDefault(); myplace is a textbox that users put information on, now when I tried to parameterized that code like var getinfo = sqlConnection.Query<test>("Select name,location from tests where location='@location'", new {location = myplace}).FirstOrDefault(); I get absolutely no returns back, yet no error messages. What can I be missing here or whats the best way to parameterized variables. A: You do not need to place the single quotes around the parameter. Hope this helps. var getinfo = sqlConnection.Query<test>("Select name,location from tests where location=@location", new {location = myplace}).FirstOrDefault();
{ "pile_set_name": "StackExchange" }
Q: Magento 2 How to add all country regions in database? I checked directory_country_region in the database there is no region of the United Kingdom, I need all region of United Kingdom. Is Magento provide the sheet of all country regions or from where I can add them? Please help me. A: Magento 1: You can use the direct SQL files to add regions into database. For this you can refer this post. Another way is You can use the Magento custom code to add regions into database. For this you can refer this post. Also I have found one extension "Regions Manager" that provide facility to add/update regions from backend. UPDATE The solution which I did to add United Kingdom Regions is: I found a CSV for united Kingdom states here: Here is the CSV Just import it in Database and its save my time and effort.
{ "pile_set_name": "StackExchange" }
Q: Forge Autodesk model's transform matrix I would like to know what are the two matrix below and what they are used for : placementTransform (1 x 12) refPointTransform (1 x 16) Does anyone know what they are used ? I think it has to do with translation(Tx, Ty, Tz)/rotation (Rx, Ry, Rz) of 3D objects but there are too many parameters in each vector... A: The placementTransform sets the position-offset and scale of a model during loading. refPointTransform is similar (but contains rotation), but is applied (multiplied) after the placementTransform. Here is an example and source code, of how to use 'placementTransform': https://github.com/wallabyway/viewer-multimodel-search/blob/1c2e71397a78ab807644f96dfb34b8e578825987/docs/index.html#L61 Take a look at line 61. When I load in the second model, I set the offset and scale of the 3D-building, so that it's positioned above the 3D-hand-saw.
{ "pile_set_name": "StackExchange" }
Q: How to print first 10 natural numbers who's square is divisible by 5? I am looking at this slideshow at the moment: http://www.slideshare.net/GeisonFlores/ruby-functional-programming Slide 24 shows that I can find the first 10 natural numbers who's square is divisible by 5 by doing this: Integer::natural.select{ |x| x**2 % 5 == 0}.take(10).inject(:+) I get the error: cannot find type 'natural' for Integer. I have tried to using ruby 1.9.3 and 2.2 and can't seem to run this LOC. Can anyone point me to how I can correct this? I am new to FP. A: Integer::natural is defined on other slide. Run this code before executing the select: class Integer def self.natural Enumerator.new do |yielder| (1..1.0/0).each do |number| yielder.yield number end end end end
{ "pile_set_name": "StackExchange" }
Q: ExecuteExcel4Macro, path containing an apostrophe This will be my first question on this site, so bear with me. So, I am trying to utilize the ExecuteExcel4Macro function, to reference a value in a different workbook, without having to open the workbook, as it will have to loop through a lot of workbooks in a directory, and reference the same cell on each workbook. The problem arisen on this line: wbRef = "'" & folderName & "[" & myDir & "]" & thatSheet & "'!" which leads to the run-time error 1004 on this line: month = CStr(ExecuteExcel4Macro(wbRef & Range("D4").Address(, , xlR1C1))) If, let's say, folderName = "C:\test\Accounts\O'Malley\Summary\" , the error occurs. Since folderName contains an apostrophe, ExecuteExcel4Macro is not recogninzing wbRef as what it is, a path to a folder, but closing that path too early in the path string, therefore resulting the error. So my question is: Is there a way to get around this apostrophe, without having to change the folder names, without having to open each individual workbook in the subfolder? I've tried with double quotations, but didn't seem to do the trick. Below is a draft of my code, or at least the context. Sub refMonth() Dim thisWb as Workbook, folderName as String, myDir as String, wbRef as String, thatSheet as String, month as String Set thisWb = ActiveWorkbook folderName = SelectFolder(thisWb) If folderName = vbNullString Then GoTo Done myDir = Dir(folderName & "*.xls") thatSheet = "Sheet1" wbRef = "'" & folderName & "[" & myDir & "]" & thatSheet & "'!" Do Until myDir = vbNullString month = CStr(ExecuteExcel4Macro(wbRef & Range("D4").Address(, , xlR1C1))) 'Do a lot of stuff, which works when in a folder without an apostrophe myDir = Dir() wbRef = "'" & folderName & "[" & myDir & "]" & thatSheet & "'!" Loop Done: End Sub Function SelectFolder(thisWb As Workbook) Dim diaFolder As FileDialog, DirName As Variant ' Open the file dialog Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker) diaFolder.AllowMultiSelect = False diaFolder.InitialFileName = strFolder(thisWb.Path) If diaFolder.Show = True Then 'diaFolder.Show DirName = diaFolder.SelectedItems(1) If Right(DirName, 1) <> "\" Then DirName = DirName & "\" End If Else Set diaFolder = Nothing Exit Function End If Set diaFolder = Nothing SelectFolder = DirName End Function Function strFolder(ByVal strFolder0) As String strFolder = Left(strFolder0, InStrRev(strFolder0, "\") - 1) & "\" End Function Any help is appreciated, even if it's just to tell me it's impossible to get around the apostrophe. I couldn't find an answer on here, but if there is one, please point me in the right direction. A: You need to double the apostrophe to escape it: wbRef = "'" & Replace$(folderName & "[" & myDir & "]" & thatSheet, "'", "''") & "'!"
{ "pile_set_name": "StackExchange" }
Q: Reduce the use of $this pseudo-variable in php? Any time I want to use an instance variable, I need to use the pseudovariable $this, am I correct? And if those are objects with methods, I'm still having to use them. So when I have an example like so: class myClass{ private $thingOne; private $thingTwo; public function __construct($thingOne,$thingTwo){ $this->thingOne = $thingOne; $this->thingTwo = $thingTwo; } } And then I start adding methods to myClass I have to start typing things like: $this->thingOne->doSomething($this->thingTwo->doSomethingElse()); But I would much rather type: $thingOne->doSomething($thingTwo->doSomethingElse()); I just find writing this-> all the time to be annoying. Can't it just be assumed that I'm using the instance variables that I have given it? My code ends up having this this this this this this this everywhere. Could I rename it to something shorter? $t or something? A: $this is a reference to the current class object and cannot be renamed. You could make your own reference variable, but you would have to declare it in every method, thus making it inefficient. Instead you should just regularly use $this.
{ "pile_set_name": "StackExchange" }
Q: How do I get x and y coords of the mouse individually? I want to print the x position of my mouse without the y position. import pygame pygame.init() mouse = pygame.mouse.get_pos() print(mouse) This prints the x and y of the mouse as a tuple but I want to just print the x. How do I do this? A: You can simply unpack your tuples: x, y = pygame.mouse.get_pos()
{ "pile_set_name": "StackExchange" }
Q: Clickable image with discord embed? So is it possible to set a link to the big image you can see below What do I need to change in this code? embed.set_image(url="https://images-na.ssl-images-amazon.com/images/I/41j-vKWKFfL._SL250_.jpg") A: Unfortunately there's no way to url-link an image.
{ "pile_set_name": "StackExchange" }
Q: Codeigniter - multiple input with loop I wanted to make the multiple inputs with loop and the different value for each data I fill, it seems this code is working but it was only for getting 1 data to 3 data with the same value, what I wanted is that I can make different value for each data in the form. Or maybe do I need a model for this one or something? been struggle for few days here please help this is what i expect for the result in the form loop image 1 but what i get is image 2 controller.php public function aksi_soal3(){ $ps5 = $this->input->post('soal'); $ps6 = $this->input->post('opsi_a'); $ps7 = $this->input->post('opsi_b'); $ps11 = $this->input->post('kunci_jawaban'); $data = array( array( 'soal' => $ps5, 'opsi_a' => $ps6, 'opsi_b' => $ps7, 'kunci_jawaban' => $ps11 ), array( 'soal' => $ps5, 'opsi_a' => $ps6, 'opsi_b' => $ps7, 'kunci_jawaban' => $ps11 ), array( 'soal' => $ps5, 'opsi_a' => $ps6, 'opsi_b' => $ps7, 'kunci_jawaban' => $ps11 ) ); $this->db->insert_batch('soal',$data); redirect('guru/index'); } view.php <!DOCTYPE html> <html lang="en" > <head> <title></title> </head> <body> <?php $i=1; while ($i<=3){ foreach($tampilan as $soal){ ?> <form action="<?php echo base_url()?>guru/aksi_soal3" method="post"> <?php echo " <input type='hidden' name='kode_soal' value='$soal->kode_soal''> <textarea placeholder='soal' name='soal'></textarea> <input type='text' name='opsi_a' placeholder='jawaban a'> <input type='text' name='opsi_b' placeholder='jawaban b'> <input type='text' name='kunci_jawaban' placeholder='Kunci jawaban' > </div> </div> "; ?> <?php $i=$i+1; }} ?> <button type="submit" class="btn">Selesai</button> </form> </html> A: You need to do something like below, Controller public function aksi_soal3(){ $ps5 = $this->input->post('soal'); $ps6 = $this->input->post('opsi_a'); $ps7 = $this->input->post('opsi_b'); $ps11 = $this->input->post('kunci_jawaban'); $data = array(); foreach($ps5 as $key=>$value) { $data[] = array( 'soal' => $value, 'opsi_a' => $ps6[$key], 'opsi_b' => $ps7[$key], 'kunci_jawaban' => $ps11[$key] ); } $this->db->insert_batch('soal',$data); redirect('guru/index'); } View <input type='hidden' name='kode_soal[]' value='$soal->kode_soal''> <textarea placeholder='soal[]' name='soal'></textarea> <input type='text' name='opsi_a[]' placeholder='jawaban a'> <input type='text' name='opsi_b[]' placeholder='jawaban b'> <input type='text' name='kunci_jawaban[]' placeholder='Kunci jawaban' >
{ "pile_set_name": "StackExchange" }
Q: Why is type inference useful? I read code way more often than I write code, and I'm assuming that most of the programmers working on industrial software do this. The advantage of type inference I assume is less verbosity and less written code. But on the other hand if you read code more often, you'll probably want readable code. The compiler infers the type; there are old algorithms for this. But the real question is why would I, the programmer, want to infer the type of my variables when I read the code? Isn't it more faster for anyone just to read the type than to think what type is there? Edit: As a conclusion I understand why it is useful. But in the category of language features I see it in a bucket with operator overloading - useful in some cases but affecting readability if abused. A: Let's take a look at Java. Java can't have variables with inferred types. This means I frequently have to spell out the type, even if it is perfectly obvious to a human reader what the type is: int x = 42; // yes I see it's an int, because it's a bloody integer literal! // Why the hell do I have to spell the name twice? SomeObjectFactory<OtherObject> obj = new SomeObjectFactory<>(); And sometimes it's just plain annoying to spell out the whole type. // this code walks through all entries in an "(int, int) -> SomeObject" table // represented as two nested maps // Why are there more types than actual code? for (Map.Entry<Integer, Map<Integer, SomeObject<SomeObject, T>>> row : table.entrySet()) { Integer rowKey = entry.getKey(); Map<Integer, SomeObject<SomeObject, T>> rowValue = entry.getValue(); for (Map.Entry<Integer, SomeObject<SomeObject, T>> col : rowValue.entrySet()) { Integer colKey = col.getKey(); SomeObject<SomeObject, T> colValue = col.getValue(); doSomethingWith<SomeObject<SomeObject, T>>(rowKey, colKey, colValue); } } This verbose static typing gets in the way of me, the programmer. Most type annotations are repetitive line-filler, content-free regurgiations of what we already know. However, I do like static typing, as it can really help with discovering bugs, so using dynamic typing isn't always a good answer. Type inference is the best of both worlds: I can omit the irrelevant types, but still be sure that my program (type-)checks out. While type inference is really useful for local variables, it should not be used for public APIs which have to be unambiguously documented. And sometimes the types really are critical for understanding what's going on in the code. In such cases, it would be foolish to rely on type inference alone. There are many languages that support type inference. For example: C++. The auto keyword triggers type inference. Without it, spelling out the types for lambdas or for entries in containers would be hell. C#. You can declare variables with var, which triggers a limited form of type inference. It still manages most cases where you want type inference. In certain places you can leave out the type completely (e.g. in lambdas). Haskell, and any language in the ML family. While the specific flavour of type inference used here is quite powerful, you still often see type annotations for functions, and for two reasons: The first is documentation, and the second is a check that type inference actually found the types you expected. If there is a discrepancy, there's likely some kind of bug. A: It's true that code is read far more often than it is written. However, reading also takes time, and two screens of code are harder to navigate and read than one screen of code, so we need to prioritize to pack the best useful-information/reading-effort ratio. This is a general UX principle: Too much information at once overwhelms and actually degrades the effectiveness of the interface. And it is my experience that often, the exact type isn't (that) important. Surely you sometimes nest expressions: x + y * z, monkey.eat(bananas.get(i)), factory.makeCar().drive(). Each of these contains sub-expressions that evaluate to a value whose type is not written out. Yet they are perfectly clear. We're okay with leaving the type unstated because it's easy enough to figure out from the context, and writing it out would do more harm than good (clutter the understanding of the data flow, take valuable screen and short-term memory space). One reason to not nest expressions like there's no tomorrow is that lines get long and the flow of values becomes unclear. Introducing a temporary variable helps with this, it imposes an order and gives a name to a partial result. However, not everything that benefits from these aspects also benefits from having its type spelled out: user = db.get_poster(request.post['answer']) name = db.get_display_name(user) Does it matter whether user is an entity object, an integer, a string, or something else? For most purposes, it does not, it's enough to know that it represents a user, comes from the HTTP request, and is used to fetch the name to display in the lower right corner of the answer. And when it does matter, the author is free to write out the type. This is a freedom that must be used responsibly, but the same is true for everything else that can enhance readability (variable and function names, formatting, API design, white space). And indeed, the convention in Haskell and ML (where everything can be inferred without extra effort) is to write out the types of non-local functions functions, and also of local variables and functions whenever appropriate. Only novices let every type be inferred. A: I think type inference is quite important and should be supported in any modern language. We all develop in IDEs and they could help a lot in case you want to know the inferred type, just few of us hack in vi. Think of verbosity and ceremony code in Java for instance. Map<String,HashMap<String,String>> map = getMap(); But you can say it's fine my IDE will help me, it could be a valid point. However, some features wouldn't be there without the help of type inference, C# anonymous types for instance. var person = new {Name="John Smith", Age = 105}; Linq wouldn't be as nice as it is now without the help of type inference, Select for instance var result = list.Select(c=> new {Name = c.Name.ToUpper(), Age = c.DOB - CurrentDate}); This anonymous type will be inferred neatly to the variable. I dislike type inference on return types in Scala because I think your point applies here, it should be clear for us what a function returns so we can use the API more fluently
{ "pile_set_name": "StackExchange" }
Q: call method every so often vue js I need to call a function every so often, what I want is to update the data every so often for this reason I need to call that method, I'm using vue js. in the same way I want to know in which property of vue js locate it, thanks, I will investigate all the comments I need to call the 'listar()' method every 30 seconds <script> export default { methods: { listar(){ let me=this; me.mesas=[]; axios.get('api/mesas/ListarTodos').then(function(response){ //console.log(response); me.mesas=response.data; me.loading=false; }).catch(function(error){ console.log(error); }); }, } </script> This did not work for me setTimeout(() => { // }, 300) Upgrade 1 this code actually works for me,but the problem is — it will keep running after you switch to another page, because it’s a single page application. I'm using clearInterval () but it does not work, the method keeps running even though I change the page (component). Clear the clear only the first time I enter another page, then no longer Ref-->https://renatello.com/vue-js-polling-using-setinterval/ <script> import axios from 'axios' export default { data () { return { polling: null, }, methods: { listar(){ let me=this; me.mesas=[]; axios.get('api/mesas/ListarTodos').then(function(response){ //console.log(response); me.mesas=response.data; me.loading=false; }).catch(function(error){ console.log(error); }); pollData () { this.polling = setInterval(() => { this.listar(); }, 3000) }, }, created () { this.pollData() }, beforeDestroy () { clearInterval(this.polling) }, } </script> A: Like ittus said, you should use setInterval: setInterval(() => { // call listen() }, 30 * 1000); setInterval returns an object you can pass to clearInterval in order to stop calling listen. However, if you want to take into account the time of the request, you could also use setTimeout in a .finally block at the end of your (promise) request: axios.get('api/mesas/ListarTodos').then(function(response){ //console.log(response); me.mesas=response.data; me.loading=false; }).catch(function(error){ console.log(error); }).finally(function(){ setTimeout(/*call listen in a function*/, 30 * 1000); }); Anyway, it doesn't have much to do with vuejs
{ "pile_set_name": "StackExchange" }
Q: Cosmos DB: How to reference a document in a separate collection using DocumentDB API I am new to Azure Cosmos DB using the DocumentDB API. I plan to model my data so that one document references another document. This is pretty straight forward, as described in Modeling document data. However, I also would like to separate the related documents into different collections (this decision is related to how the data are partitioned). Edit 7/24/2017: In response to a comment wondering why I chose to use separate collections: The reasoning for a separate collections mainly comes down to partition keys and read/write priorities. Since a certain partition key is required to be present in ALL documents in the collection, it then makes sense to separate documents that the chosen partition key doesn't belong. After much weighing of options, the partition key that I settled on was one that would optimize write speeds and evenly distribute my data across shards - but unfortunately it did not logically belong in my "Metadata" documents. Since there is a one to gazillion relationship between metadata and measurements, I chose to use a reference to the metadata in the measurements instead of embedding. And because metadata would rarely (or never) be appended to each measurement, I considered the expense of an additional round-trip to the DB a very low concern. Since the reference is a "weak link" that is not verified by the database, is it possible and wise to store additional information, such as the collection name? That is, instead of having just a string id, we may use a kind of path? Metadata document in collection "Metadata": { "id": "metadata1", ... } Measurement document in collection "Measurements": { "id": "measurement1", "metadata-id" : "../Metadata/metadata1", ... } Then, when I parse the data in my application/script I know what collection and document to query. Finally, I assume there are other/better ways to go about this and I welcome your suggests (e.g. underscores, not slashes; use a symbol to represent a collection, like $Metadata; etc). Or, is my use of relations spanning collections a code smell? Thank you! Edit: To the downvoter, can you please explain your reasoning? Is my question uninformed, unclear, or not useful? Why? A: You're thinking about this the wrong way and incurring significantly more cost for an "optimization" that isn't necessary since you're billed at the per collection level. What you should be doing is picking a more generic partition key. Something like key or partitionKey. The tradeoff here is that you'll need to ensure in your client application that you populate this property on all of your documents (it may lead to a duplicated value, but ultimately that's okay). They you can continue to use the value of whatever you chose originally for your Measurements document and set something different for your Metadata documents. I've written about this extensively in some other answers here and I believe it's one of the biggest misunderstandings about using Cosmos effectively and at scale. It doesn't help that in many Cosmos examples they talk about picking a partitionKey like deviceId or postal code which implies that you're dealing with homogeneous documents. Please refer to this question that I answered regarding homogeneous vs heterogeneous in documentdb. The biggest argument for this pattern is the new addition of Graph APIs in Cosmos which necessitate having many different types of entities in a single collection and supports exactly the use case you're describing minus the extra collections. Obviously when dealing with heterogeneous types there isn't going to be a single property present on all documents that is appropriate for a partition key which is why you need to go generic.
{ "pile_set_name": "StackExchange" }
Q: delete/add button not showing in UITableViewCellStyleDelete/UITableViewCellStyleInsert I have a plain ol UITableView, and I want its cells to have the delete button on the left. I know this is done using UITableViewCellStyleDelete. I set up my tableview like so: adjustmentTable.rowHeight = 35.0; [adjustmentTable setEditing:YES animated:YES]; adjustmentTable.allowsSelectionDuringEditing = YES; adjustmentTable.userInteractionEnabled = YES; With breakpoints, i know that this function is getting called: - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row < tmpNumOfRows) { return UITableViewCellEditingStyleDelete; } return UITableViewCellEditingStyleInsert; } and in my cellForRowAtIndexPath method, i set the cells editing mode to YES. When my tableview shows up, it has the indentations for the buttons on the left, but no buttons show up, its just a white indentation. Am I missing more steps to get the red/green buttons to show? A: Writing that question me consider my last comment, setting the cells editing property to yes. For some reason, if you do this, the left add/delete buttons do not show up! I removed the code that did that and I see it now. Perhaps someone can clarify why this is so with a comment.
{ "pile_set_name": "StackExchange" }
Q: PHP - How to insert new element in array avoiding duplicates? I want to create a function that takes as input parameters an array $arr_previsioni, a value $previsione, and a number $pos indicating the position. The function should: 1 - add the value $previsione if it does not already exist. 2 - If the value $previsione given in input is already present in the array, it must modify the value of $previsione so that it is not different from all the others and in the end add it to the array. Essentially given an input x number I have to create an array of unique numbers with this priority: if the x number I gave at the input is already present in the array then we need to change the x number (adding or subtracting something) to make it unique. function aggiungiPrevisione($previsione,$pos,$arr_previsioni){ echo '<br>'; // if it is the first element of the array if($pos == 1){ $arr_previsioni['PREVISIONE1'] = $previsione; return $arr_previsioni; } $numero_elementi = count($arr_previsioni); foreach($arr_previsioni as $key=>$value){ for($i=0; $i <= $numero_elementi+2; $i++){ // Verifica se esiste if (in_array($previsione, $arr_previsioni)){ // The same number was found in array if($previsione > 45){ $previsione = $previsione - 13; } else { $previsione = $previsione + 13; } $previsione = getNumeroGiocabile($previsione); // returns a number from 0 to 90 } // end checking } // end for } // end foreach // Add $previsione in array $arr_previsioni['PREVISIONE'.$pos] = $previsione; // by Vincent Decaux return $arr_previsioni; } $previsione = makePrevisione(); // return number from 1 to 90 $arr_previsioni = array(); // initially empty for($pos=1; $pos<=24; $pos++){ $arr_previsioni = aggiungiPrevisione($previsione,$pos,$arr_previsioni); } var_dump($arr_previsioni); The function I created returns an array of 24 elements but some are the same as the others. Here are the values ​​of the array: array(24) { ["PREVISIONE1"]=> int(30) ["PREVISIONE2"]=> int(71) ["PREVISIONE3"]=> int(22) ["PREVISIONE4"]=> int(1) ["PREVISIONE5"]=> int(67) ["PREVISIONE6"]=> int(51) ["PREVISIONE7"]=> int(35) ["PREVISIONE8"]=> int(14) ["PREVISIONE9"]=> int(72) ["PREVISIONE10"]=> int(57) ["PREVISIONE11"]=> int(11) ["PREVISIONE12"]=> int(76) ["PREVISIONE13"]=> int(41) ["PREVISIONE14"]=> int(40) ["PREVISIONE15"]=> int(39) ["PREVISIONE16"]=> int(37) ["PREVISIONE17"]=> int(34) ["PREVISIONE18"]=> int(29) ["PREVISIONE19"]=> int(42) ["PREVISIONE20"]=> int(55) ["PREVISIONE21"]=> int(55) ["PREVISIONE22"]=> int(55) ["PREVISIONE23"]=> int(55) ["PREVISIONE24"]=> int(55) } as you can see there are repeated values ​​(55). I would like the function to insert the number of the $previsione as provided in case it did not already exist in the array, otherwise it would have to modify the value of $previsione (in order to obtain a number that is not already present) and add it to the array. Let's see if I can make it easier to understand the problem. By giving these input parameters: $arr_previsione = ( "PREVISIONE1"=> 30, "PREVISIONE2"=> 71, "PREVISIONE3"=> 22, "PREVISIONE4"=> 1, "PREVISIONE5"=> 67, "PREVISIONE6"=> 51, "PREVISIONE7"=> 35); $pos = 8; $previsione = 22; $arr_previsioni = aggiungiPrevisione($previsione8,8,$arr_previsioni); The result that I can currently get with the function shown above could be this: $arr_previsione = ( "PREVISIONE1"=> 30, "PREVISIONE2"=> 71, "PREVISIONE3"=> 22, "PREVISIONE4"=> 1, "PREVISIONE5"=> 67, "PREVISIONE6"=> 51, "PREVISIONE7"=> 35, "PREVISIONE8"=> 22); // error What I would rather get is: $arr_previsione = ( "PREVISIONE1"=> 30, "PREVISIONE2"=> 71, "PREVISIONE3"=> 22, "PREVISIONE4"=> 1, "PREVISIONE5"=> 67, "PREVISIONE6"=> 51, "PREVISIONE7"=> 35, "PREVISIONE8"=> 48); // after the change the new value entered should be 48 or any other number, it is enough that it is not already present in the array itself I hope I explained myself A: It seems you're looking for something like this: function aggiungiPrevisione($previsione,$pos,$arr_previsioni) { echo '<br>'; // if it is the first element of the array if ($pos == 1) { $arr_previsioni['PREVISIONE1'] = $previsione; return $arr_previsioni; } // Make sure $previsione does not yet exist while (in_array($previsione, $arr_previsioni)) { $previsione = rand(0, 90); } // Add $previsione in array $arr_previsioni['PREVISIONE'.$pos] = $previsione; return $arr_previsioni; } Note that I only changed the middle part of this function. I have a simple while loop checking if the value $previsione is in the array $arr_previsioni. If it is a new random value between 0 and 90 is generated for $previsione, and the loop condition is checked again, until the value is not present in the array anymore. Note that this routine will fail as soon as all values between 0 and 90 have been used. I also cannot correct all the other problems, like: Having an echo '<br>'; in a function that's meant to manipulate an array. Having unneeded string keys in the array. The default numeric keys would probably do. Bad initialization routine for the array. I like to program in English since the programming language is English. Mixing two languages doesn't help other people reading your code, unless they happen to be Italian. I'm Dutch, by the way. You wouldn't like to read Dutch code, I'm sure. Contrary to that your comments are in English. Were they added for the question only?
{ "pile_set_name": "StackExchange" }
Q: How far can a knight travel without visiting the same square twice? How many Knight moves is it possible to execute on an empty chess board before the Knight lands on a square it has already landed on in its previous moves? The most I've ever been able to land on was 54 squares, usually 50-52. A: There is a famous puzzle called the Knight's Tour in which the aim is to visit every square exactly once. Since this has several solutions, the answer to your question is that it can visit all 64 squares.
{ "pile_set_name": "StackExchange" }
Q: Regex for MongoDB ObjectID With reference to this SO question, I have a scenario where I only need to match a hex string with a-f included. All else should not match. Example: checkForHexRegExp.test("112345679065574883030833"); // => false checkForHexRegExp.test("FFFFFFFFFFFFFFFFFFFFFFFF"); // => false checkForHexRegExp.test("45cbc4a0e4123f6920000002"); // => true My use case is that I am working with a set of hex strings and would like to only validate as true those that are mongodb objectIDs. A: You can use following regular expression but it will not quite work checkForHexRegExp = /^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i Example: > checkForHexRegExp.test("112345679065574883030833") false > checkForHexRegExp.test("FFFFFFFFFFFFFFFFFFFFFFFF") false > checkForHexRegExp.test("45cbc4a0e4123f6920000002") true But, as I commented, 112345679065574883030833, FFFFFFFFFFFFFFFFFFFFFFFF are also valid hexadecimal representations. You should use /^[a-f\d]{24}$/i because it passes all the above tests A: I need a regex that will only match mongodb ObjectIDs If you need that, you will have to specify exactly what makes up a mongodb ObjectID, so that we can create the appropriate regex string for it. This should technically work in js: var myregexp = /^[0-9a-fA-F]{24}$/; subject = "112345679065574883030833"; if (subject.match(myregexp)) { // Successful match } else { // Match attempt failed } A: Technically, all examples in the question potentially could be valid ObjectIds. If you have to add some additional verification and that regexp is not enough, then my suggestion is to check if the first 4 bytes are a valid timestamp. You can even verify that ObjectId has been generated during a certain period of time (e.g. since your project has been started or so). See ObjectId documentation for details. If there's another timestamp field in an object, then it's also possible to make sure that both times are really close. Just for the reference, in MongoDB shell ObjectId::getTimestamp() method can be used to extract a timestamp from ObjectId.
{ "pile_set_name": "StackExchange" }
Q: UIDatePicker setting minimum and maximum hour How to set minimum and maximum hour to UIDatePicker ? At all is it possible ? I know how to set minimum and maximum date: [datePicker setMinimumDate: today]; [datePicker setMaximumDate: nextMonthDay]; What i want to achieve is that in picker user could select from 8 am to 10 pm every day. Thanks. A: Hope the following code help you. - (IBAction)dataPickerValueChanged:(UIDatePicker *)sender { NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:[testDatePicker date]]; if ([dateComponents hour] > 8 && [dateComponents hour] < 22) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error!" message:@"This time cant be selected" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles: nil]; [alert show]; return; } lblDate.text = [sender date]; }
{ "pile_set_name": "StackExchange" }
Q: llc - expected value token error I'm getting this message when I try to llc my example.ll file: llc: example.ll:12:29: error: expected value token %1 = icmp slt i1 %cmptmp, i16 0 ^ The example.ll file: ; ModuleID = 'modulle' define i16 @main() { entry: %x = alloca i16 store i16 2, i16* %x br label %loop_condition loop_condition: ; preds = %loop, %entry %0 = load i16, i16* %x %cmptmp = icmp sgt i16 %0, 1 %1 = icmp slt i1 %cmptmp, i16 0 br i1 %1, label %loop, label %while_continue loop: ; preds = %loop_condition br label %loop_condition while_continue: ; preds = %loop_condition ret i16 0 } When I remove i16 everything works fine, but I don't know why LLVM insert that in my code. Does anybody know what's the problem? --- UPDATE --- The .ll output is from my toy compiler. This is the code for lines 11 and 12: Value *cond = llvm::CmpInst::Create(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_SLT, binRelOpCond, llvm::ConstantInt::get(llvm::getGlobalContext(), llvm::APInt(16, 0, true)), "", codeGenContext.getBlock()); where binRelOpCond variable is: CmpInst *compareRes = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SGT, left, right, "cmptmp", codeGenContext.getBlock()); Thanks. A: That ll file is malformed. icmp's syntax doesn't have a type for each operand, just a single type for both: <result> = icmp <cond> <ty> <op1>, <op2> Looking at the code you added in the comment which generated the ll, the bug is with llvm::APInt(16, 0, true) - you're explicitly creating a constant of type i16, but you may only compare with a constant of type i1 since that's %cmptmp's type. I don't know why no assertion caught that, though.
{ "pile_set_name": "StackExchange" }
Q: Softlayer location conflict for port speeds This question is related to this one But now I got a new message: 10 Gbps Private Network Uplink cannot be ordered with location Amsterdam 1 on this package. I tried 253 package and looked at location conflicts. What I got for this item(3957 id) is: [ { "itemId"=>3957, "message"=>"10G connections cannot be ordered in dal01", "packageId"=>"", "resourceTableId"=>3 }, { "itemId"=>3957, "message"=>"10G connections cannot be ordered in hou02", "packageId"=>"", "resourceTableId"=>142775 } ] I've seen that 10gps uplinks are conflicts for many datacenter, but I don't see that this particular item is one for Amsterdam 1. I wonder if there is one more place for conflicts to look at?... A: I'm really sure that you are using an ObjectFilter to get the result. Currently there is an issue for itemLocationConflicts with the ObjectFilter, that's the reason why your are not able to see all the conflicts for itemId: 3957 (The fix of this issue could take some time), so I recommend not use the objectFilter https://api.softlayer.com/rest/v3/SoftLayer_Product_Package/253/getItemLocationConflicts There is a location conflict for item: 3957 with Amsterdan 1 { "itemId": 3957, "packageId": 253, "resourceTableId": 168642 } My apologies for the inconveniences, I will update this forum when the issue has been solved
{ "pile_set_name": "StackExchange" }
Q: templated function with an argument that is a templated class I realise there are a lot of similar questions, but I couldn't find any that solves my problem (read: I did not truly understood the answers so that I could apply it to my case) I have the following function: void printVariable(map<string, bool*>::iterator it) { cout << it->first << " " << *(it->second) << endl; } Now If i have a map<string, bool*> mapping I can do the following: printVariable(mapping.begin()); This works, now I also have a a map<string, int*> and want to be able to do the same, so I figured I change the printVariable function: template <typename T> void printVariable(map<string, T*>::iterator it) { cout << it->first << " " << *(it->second) << endl; } However this gives compile errors (gcc): error: variable or field 'printVariable' declared void error: expected ')' before 'it' I guess I can work around this pretty easy by overloading the function. But I'd like to know why the above is not working. Edit2: removed text claiming a right solution was wrong A: You have to say typename to disambiguate the dependent name: template <typename T> void printVariable(typename map<string, T*>::iterator it) // ^^^^^^^^ However, note that this is not a deducible context, so this form isn't terribly convenient. Better yet, just make the entire iterator a template parameter: template <typename Iter> void printVariable(Iter it) { /* ... */ } That way, you also capture maps with non-standard comparators or allocators, and unordered maps, etc. etc. Here's a simple thought experiment for why you don't have a deducible context in the first situation: How should T be deduced in the following call of foo? template <typename T> void foo(typename Bar<T>::type); template <typename T> struct Bar { typedef char type; }; template <> struct Bar<int> { typedef int type; }; template <> struct Bar<double> { typedef int type; }; foo(10); // What is T?
{ "pile_set_name": "StackExchange" }
Q: Why is NumPy subtraction slower on one large matrix $M$ than when dividing $M$ into smaller matrices and then subtracting? I'm working on some code where I have several matrices and want to subtract a vector $v$ from each row of each matrix (and then do some other stuff with the result). As I'm using NumPy and want to 'vectorise' as much as possible, I thought I'd speed up my running time by storing all the matrices as one large ('concatenated') matrix and subtracting $v$ from that. The issue is that my code runs slower after this supposed optimisation. In fact, in some scenarios breaking up the matrices and subtracting separately is significantly faster (see code example below). Can you tell me what is causing this? Naively, I would assume that both approaches require the same number of elementary subtraction operations and the large matrix approach is faster as we avoid looping through all matrices separately with a pure Python loop. Initially, I thought the slow-down may be due to initialising a larger matrix to store the result of subtracting. To test this, I initialised a large matrix outside my test function and passed it to the np.subtract command. Then I thought that broadcasting may be causing the slow performance, so I manually broadcast the vector into the same shape as large matrix and then subtracted the resulting broadcasted matrix. Both attempts have failed to make the large matrix approach competitive. I've made the following MWE to showcase the issue. Import NumPy and a timer: import numpy as np from timeit import default_timer as timer Then I have some parameters that control the size and number of matrices. n = 100 # width of matrix m = 500 # height of matrix k = 100 # number of matrices M = 100 # upper bound on entries reps = 100 # repetitions for timings We can generate a list of test matrices as follows. The large matrix is just the concatenation of all matrices in the list. The vector we subtract from the matrices is randomly generated. list_of_matrices = [np.random.randint(0, M+1, size=(m,n)) for _ in range(k)] large_matrix = np.row_stack(list_of_matrices) vector = np.random.randint(0, M+1, size=n) Here are the three functions I use to evaluate the speed of subtraction. The first subtracts the vector from each matrix in the list, the second subtracts the vector from the (concatenated) large matrix and the last function is an attempt to speed up the latter approach by pre_initialising an output matrix and broadcasting the vector. def list_compute(list_of_matrices, vector): for j in range(k): np.subtract(list_of_matrices[j], vector) def array_compute(bidlists, vector): np.subtract(large_matrix, vector_matrix, out=pre_allocated) pre_allocated = np.empty(shape=large_matrix.shape) vector_matrix = np.broadcast_to(vector, shape=large_matrix.shape) def faster_array_compute(large_matrix, vector_matrix, out_matrix): np.subtract(large_matrix, vector_matrix, out=out_matrix) I benchmark the three functions by running start = timer() for _ in range(reps): list_compute(list_of_matrices, vector) print timer() - start start = timer() for _ in range(reps): array_compute(large_matrix, vector) print timer() - start start = timer() for _ in range(reps): faster_array_compute(large_matrix, vector_matrix, pre_allocated) print timer() - start For the above parameters, I get timings of 0.539432048798 1.12959504128 1.10976290703 Naively, I would expect the large matrix approach to be faster or at least competitive compared to the several matrices approach. I hope someone can give me some insights into why this is not the case and how I can speed up my code! A: The type of the variable pre_allocated is float8. The input matrices are int. You have an implicit conversion. Try to modify the pre-allocation to: pre_allocated = np.empty_like(large_matrix) Before the change, the execution times on my machine were: 0.6756095182868318 1.2262537249271794 1.250292605883855 After the change: 0.6776479894965846 0.6468182835551346 0.6538956945388001 The performance is similar in all cases. There is a large variance in those measurements. One may even observe that the first one is the fastest. It seams that there is no gain due to pre-allocation. Note that the allocation is very fast because it reserves only address space. The RAM is consumed only on access event actually. The buffer is 20MiB thus it is larger that L3 caches on the CPU. The execution time will be dominated by page faults and refilling of the caches. Moreover, for the first case the memory is re-allocated just after being freed. The resource is likely to be "hot" for the memory allocator. Therefore you cannot directly compare solution A with others. Modify the "action" line in the first case to keep the actual result: np.subtract(list_of_matrices[j], vector, out=pre_allocated[m*j:m*(j+1)]) Then the gain from vectorized operations becomes more observable: 0.8738251849091547 0.678185239557866 0.6830777283598941
{ "pile_set_name": "StackExchange" }
Q: Most efficient way of transferring large amounts of data from one column to another? I currently have two tables, and one has a dependency on the other that I want to remove. Let's say the tables are Product and Employee, and there are about 800,000 rows in each table. The Employee table has a ProductID, in which there is a ProductRefID, which I need to reference in my application. The way this is done is to join in the Product table, and reference the ProductRefID that way. However, I now want to change this so that ProductRefID is a column on the Employee table, and then transfer every Product row's "ProductRefID" to the Employee row's "ProductRefID". What would be the most efficient way of writing this query? (I know it sounds stupid, but it's just an example, it's not actually what I'm trying to do specifically). A: Something like this ? alter table Employee add ProductRefID INT update e set ProductRefID = p.ProductRefID from Employee e join Product p on e.ProductID = p.id
{ "pile_set_name": "StackExchange" }
Q: Frequency : Decibel plot using FFT in MATLAB I am trying to use MATLAB to import a WAV file and create the type of diagram shown below. I am basically trying to pull frequency information and plot it according to decibels. Here is the code I am working with, but it doesn't seem to pull the frequency information correctly: [x fs]=wavread('filename.wav'); dt=1/fs;%% time interval X=fft(x); df=1/(length(x)*dt); %% frequency interval f=(1:length(X))*df;%% frequency vector %% frequency domain plot, freq in hertz figure plot(f,abs(X)) Please help! Thank you! A: In your code "X" contains the waveform information, not the frequency information. To get the frequency information of the soundfile you could use the FFT function. I use this (more elaborate, but still simple) code for what you want to do: [FileName,PathName]=uigetfile('*.wav'); [y, Fs, nbits] = wavread(fullfile(PathName,FileName)); length_y=length(y); NFFT = 2^nextpow2(length_y); % Next power of 2 from length of y fft_y=fft(y,NFFT)/length_y; f = Fs/2*linspace(0,1,NFFT/2+1); semilogy(f,abs(fft_y(1:length(f)))); title('Single-Sided Amplitude Spectrum of y(t)') xlabel('Frequency (Hz)') ylabel('|Y(f)|') I hope this is useful to you. The plot will not be in steps like the one you have shown, but that can also be achieved - using the "stairs" plot function.
{ "pile_set_name": "StackExchange" }
Q: Regarding same Runnable reference on Multiple Treads When we call start() on a Thread by passing a Runnable object as argument, can we pass the same Runnable reference to start multiple threads? public class MyMain { public static void main(String[] args) { MyRunnableImpl impl = new MyRunnableImpl(); new Thread(impl).start(); new Thread(impl).start(); } } A: Yes, you can do this when your Runnable is implemented accordingly. But you have to be careful your Runnable implementation does not contain a mutable state. You can control this in your own implementations, but the Runnable contract does not specify. // can be used for multiple Threads class StatelessRunnable { public void run() { doSomething(); } } // may go bang on the second execution -> use two instances class StatefulRunnable { volatile boolean canRun = true; public void run() { if(!canRun) throw new IllegalStateException(); canRun = false; } } In the above sample you see that you can use StatelessRunnable for as many threads as you like. In fact you could even make it a singleton. StatefulRunnable in contrast can be run only once per instance. Shared State Reading Jon's answer I realised there may be scenarios where you actually want to share a state of two Runnable instances. Of course a stateful Runnable instance is not always bound to fail with multiple threads, but this is much more trickier to get right than a stateless one. // willingly share state over threads class WillinglyStatefulRunnable { final BlockingQueue<Object> sharedObjects = new BlockingQueue<Object>(); public void run() { sharedObjects.offer(new Object()); } } The above example shows how you could work on a single collection sharedObjects with multiple threads. Literature Sidenote: Item 15 in Joshau Bloch's Effective Java says Minimize Mutabilty. This chapter - in case you have access to the book - addresses similar points in a much more general context. Shortly summarised he states that immutable objects make it easier to reuse instances and reduce the potential of illegal states.
{ "pile_set_name": "StackExchange" }
Q: How to make a custom relational operator in Swift I am working with Doubles that have a range of 0..<360. I want to create a switch statement that will have 8 cases. A case for 0, 90, 180 and 270, and a case for the values in between. It seems that the half-open operator will not satisfy what I'm trying to do here. I'm thinking the solution may be to create a custom relational operator. Let's call it <..< case 0: case 0<..<90: case 90: case 90<..<180: case 180: case 180<..<270: case 270: case 270<..<360: I've looked into creating a custom infix operator that returns a Boolbut that won't work because the arguments would only include the lhs and rhs. How can I accomplish this? A: Your switch is unnecessarily complicated. See if this works for you: let value: Double = 180 switch value { case 0: print("exactly 0") case 0..<90: print("less than 90") case 90: print("exactly 90") case 90..<180: print("less than 180") case 180: print("exactly 180") case 180..<270: print("less than 270") case 270: print("exactly 270") default: print("less than 360") }
{ "pile_set_name": "StackExchange" }
Q: Make a PHP GET request from a PHP script and exit Is there something simpler than the following. I am trying to make a GET request to a PHP script and then exit the current script. I think this is a job for CURL but is there something simpler as I don't want to really worry about enabling the CURL php extension? In addition, will the below start the PHP script and then just come back and not wait for it to finish? //set GET variables $url = 'http://domain.com/get-post.php'; $fields = array( 'lname'=>urlencode($last_name), 'fname'=>urlencode($first_name) ); //url-ify the data for the GET foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; } rtrim($fields_string,'&'); //open connection $ch = curl_init(); //set the url, number of POST vars, POST data curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_GET,count($fields)); curl_setopt($ch,CURLOPT_GETFIELDS,$fields_string); //execute GET $result = curl_exec($ch); //close connection curl_close($ch); I want to run the other script which contains functions when a condition is met so a simple include won't work as the if condition wraps around the functions, right? Please note, I am on windows machine and the code I am writing will only be used on a Windows OS. Thanks all for any help and advice A: $url = 'http://domain.com/get-post.php?lname=' . urlencode($last_name) . '&fname=' . urlencode($first_name); $html = file_get_contents($url); If you want to use the query string assembly method (from the code you posted): //set GET variables $url = 'http://domain.com/get-post.php'; $fields = array( 'lname'=>urlencode($last_name), 'fname'=>urlencode($first_name) ); //url-ify the data for the GET foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; } rtrim($fields_string,'&'); $html = file_get_contents($url . '?' . $fields_string); See: http://php.net/manual/en/function.file-get-contents.php
{ "pile_set_name": "StackExchange" }
Q: Using one Partial View Multiple times on the same Parent View I am using MVC3 razor. I have a scenario where I have to use a partial view multiple times on the same parent view. The problem I am having is that when the Parent View gets rendered, it generates same names and ids of the input controls within those partial views. Since my partial views are binded to different models, when the view is posted back on "Save" it crashes. Any idea how can i make the control id/names unique, probably some how prefix them ? Awaiting Nabeel A: Personally I prefer using editor templates, as they take care of this. For example you could have the following view model: public class MyViewModel { public ChildViewModel Child1 { get; set; } public ChildViewModel Child2 { get; set; } } public class ChildViewModel { public string Foo { get; set; } } and the following controller: public class HomeController : Controller { public ActionResult Index() { var model = new MyViewModel { Child1 = new ChildViewModel(), Child2 = new ChildViewModel(), }; return View(model); } [HttpPost] public ActionResult Index(MyViewModel model) { return View(model); } } and inside the Index.cshtml view: @model MyViewModel @using (Html.BeginForm()) { <h3>Child1</h3> @Html.EditorFor(x => x.Child1) <h3>Child2</h3> @Html.EditorFor(x => x.Child2) <input type="submit" value="OK" /> } and the last part is the editor template (~/Views/Home/EditorTemplates/ChildViewModel.cshtml): @model ChildViewModel @Html.LabelFor(x => x.Foo) @Html.EditorFor(x => x.Foo) Using the EditorFor you can include the template for different properties of your main view model and correct names/ids will be generated. In addition to this you will get your view model properly populated in the POST action.
{ "pile_set_name": "StackExchange" }
Q: Using Lucene.Net with the Repository pattern? Anybody doing this? I am curious to know if anyone has implemented this in their own projects. A: Basically, I have found that there is not a lot of good information out there about this. I am implementing my own LuceneContext that can be used like a Unit Of Work for a repository.
{ "pile_set_name": "StackExchange" }
Q: Why this question was downvoted and closed? Drivers for recent (64-bit) version of Windows must be signed before they'll load. Which certificate issuers can supply a certificate suitable for this? http://www.stackoverflow.com/questions/6689758/what-certificate-do-i-need-for-windows-driver-signing What it misses to be "well written"? A: Currently that question is open and positively scored. But take a look at the question's revision history. That question used to be Where to buy certificate for driver signing? What are possible choices, which ones are cheaper? And that is simply off-topic. That caused it to be closed and more than likely explains at least some of the downvotes it received.
{ "pile_set_name": "StackExchange" }
Q: Embedd SU(n) into an enlarged twisted Spin(2n) in terms of Lie groups precisely It is standard practice to show $$ SU(n) \subset SO(2n). $$ However, some post Is $SU(n) \subset \text{Spin}(2n)$? suggests that $\DeclareMathOperator\Spin{Spin}$ $$ SU(n) \subset \Spin(2n) (?). $$ I am very puzzled, because $1 \to \mathbb{Z}/2 \to \Spin(2n)\to SO(2n) \to 1$, so $SO(2n) \not \subset \Spin(2n) $. The $ SO(2n) $ is only a quotient group not a normal subgroup. Is this answer $SU(n) \subset \Spin(2n)$ true of false, Is $SU(n) \subset \text{Spin}(2n)$?? I thought $SU(n) \not\subset \Spin(2n)$ However, is it possible to show that $$ SU(n) \times U(1) \subset \frac{\Spin(2n) \times \Spin(2)}{\mathbb{Z}/2}= \frac{\Spin(2n) \times U(1)}{\mathbb{Z}/2}? $$ $$ SU(n) \times SU(2) \subset \frac{\Spin(2n) \times \Spin(3)}{\mathbb{Z}/2}=\frac{\Spin(2n) \times SU(2)}{\mathbb{Z}/2}? $$ precisely? A: Since $SU(n)$ is simply connected, any map $SU(n)\rightarrow SO(k)$ lifts to a map $SU(n)\rightarrow Spin(k)$. Further, there is a unique lift mapping the identity in $SU(n)$ to the identity in $Spin(k)$. Apply this to the inclusion map $i:SU(n)\rightarrow SO(2n)$. Note that $i$ is injective, so any lift must also be injective, so there are always copies of $SU(n)$ in $Spin(2n)$
{ "pile_set_name": "StackExchange" }
Q: How do I change the user agent in my WebView using Swift 4.2? I'm struggling with changing the user agent on my project using the latest Xcode version with swift 4.2 . I want to pretend that I'm a Mac visiting a specific website. Please edit this code and post it in the comments Here's my code so far. class ViewController: UIViewController { @IBOutlet weak var webview: WKWebView! override func viewDidLoad() { super.viewDidLoad() let userAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36 Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10" let myURL = NSURL(string: "http://website.com") let myURLRequest:NSURLRequest = URLRequest(url: myURL! as URL) as NSURLRequest webview.load(myURLRequest as URLRequest) myURLRequest.setValue(userAgent, forKey: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36") webview.load(URLRequest(url: myURL! as URL)) } } If I build it I receive this error: ![Error][2]. A: The problem i seeing here, first time loading without the user-agent set and then setting it wrongly and put another request Please check the appledoc, for setting up the HTTPHeaderField. Based on your given code, the solution would be class ViewController: UIViewController { @IBOutlet weak var webview: WKWebView! override func viewDidLoad() { super.viewDidLoad() let userAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36 Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10" if let myURL = URL(string: "http://website.com") { var myURLRequest= URLRequest(url: myURL) myURLRequest.setValue(userAgent, forHTTPHeaderField:"user-agent") webview.load(myURLRequest) } } }
{ "pile_set_name": "StackExchange" }
Q: wpf use elements declared in style i'm in trouble joining styles and code in my form: here is my situation: my TabItem style: <Style TargetType="TabItem" x:Key="testStyle"> <Setter Property="FocusVisualStyle" Value="{x:Null}" /> <Setter Property="IsTabStop" Value="False" /> <Setter Property="BorderThickness" Value="1" /> <Setter Property="Padding" Value="6,2,6,2" /> <Setter Property="HorizontalContentAlignment" Value="Stretch" /> <Setter Property="VerticalContentAlignment" Value="Stretch" /> <Setter Property="MinWidth" Value="5" /> <Setter Property="MinHeight" Value="5" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="TabItem"> <DockPanel Width="120" x:Name="rootPanel"> <ContentPresenter ContentSource="Header" RecognizesAccessKey="True" /> <Image x:Name="rootImage"/> <Label x:Name="rootLabel" FontSize="18" /> </DockPanel> <ControlTemplate.Triggers> and here is where I apply my style <TabItem Style="{StaticResource testStyle}"> <TabItem.Header> </TabItem.Header> but: how can I set the values to my Image and label called rootImage and rootLabel? A: I assume you have a class named SomeClass public class SomeClass { public string SomeLabel; public string SomeImage; } Now change your style <DockPanel Width="120" x:Name="rootPanel"> <ContentPresenter ContentSource="Header" RecognizesAccessKey="True" /> <Image x:Name="rootImage" Source={Binding SomeImage}/> <Label x:Name="rootLabel" Content={Binding SomeLabel} FontSize="18" /> </DockPanel> Finally: <TabItem Style="{StaticResource testStyle}" Name="myTabItem"> <TabItem.Header> </TabItem.Header> </TabItem> And in the code behind: myTabItem.DataContext = new SomeClass(); //create a SomeClass with proper label and image
{ "pile_set_name": "StackExchange" }
Q: Local wordpress install only shows home page, all other pages Not Found I am working on a local install of a live wordpress site, all links from the main page show Not Found errors. all .htaccess files are all present. The problem is that every page except for the home page is showing a Not Found error, I can't find any problems with permissions or anything else that would cause it to not work. Is there anything that I can try that I might be overlooking? I apologize for the vauge questions but I am having trouble figuring out where to start. A: Log in to the admin panel (localhost/sitedirectory/wp-admin) and go to Settings->Permalinks and click Save Changes. Permalinks often need to be rebuilt after mirroring a site and updating the site url. You don't need to change any settings, just hit save and it will rebuild the permalinks with the selected options. Also make sure the Apache module mod_rewrite is enabled on your local stack. IIRC WAMP (and possible XAMPP) do not enable this by default. Doing so in WAMP is as simple as clicking the WAMP icon in the taskbar, then going to Apache -> Apache Modules -> mod_rewrite (click to toggle) and then restart all services. Also I am assuming you already updated the site and home urls (either in the wp_options database table or in wp-config.php). For reference there is a Codex page about this: Moving Wordpress A: You can do it in a really simple way. Just go to Settings >> Permalinks >> and click "save changes" without changing anything. If it gives you .htaccess file permission issue, you need to set privilege of your ROOT folder (where your wp-content folder lies) to read and write. And again go to Settings >> Permalinks >> and click "save changes" without changing anything. That's all. Hope it resolves the issue. A: Please enable rewrite_module. To enable it on windows wamp follow these click on wamp -> Apache ->Apache Module -> check rewrite_module
{ "pile_set_name": "StackExchange" }
Q: Setting up devise+omniauth in rails, keep getting a routing error after 'login' So I've been working on a fairly simple rails 4 app and I've reached the point where I need to add user authentication. In particular, I want to use Google Apps (and only google apps) authentication via a combination of devise and omniauth. Now, devise has a tutorial that supposedly tells you how to set something like that up. After installing devise and making the suggested changes in the tutorial, everything seemed great. I clicked my sign-in link and was properly sent off to google for authentication. However, after I supply my credentials I'm immediately greeted with a routing error: uninitialized constant Users Which is confusing. From what I understand, that means that the controller is missing... but I definitely have users_controller.rb and it's where it should be. Barring that, I have no clue. Here's my route.rb for reference: resources :instances, :users devise_for :users, :controllers => { :omniauth_callbacks => 'users/omniauth_callbacks' } # authentication routes devise_scope :user do get 'sign_in', :to => 'devise/sessions#new', :as => :new_user_session get 'sign_out', :to => 'devise/sessions#destroy', :as => :destroy_user_session end root to: 'instances#index' And here's the result of rake routes: Prefix Verb URI Pattern Controller#Action instances GET /instances(.:format) instances#index POST /instances(.:format) instances#create new_instance GET /instances/new(.:format) instances#new edit_instance GET /instances/:id/edit(.:format) instances#edit instance GET /instances/:id(.:format) instances#show PATCH /instances/:id(.:format) instances#update PUT /instances/:id(.:format) instances#update DELETE /instances/:id(.:format) instances#destroy users GET /users(.:format) users#index POST /users(.:format) users#create new_user GET /users/new(.:format) users#new edit_user GET /users/:id/edit(.:format) users#edit user GET /users/:id(.:format) users#show PATCH /users/:id(.:format) users#update PUT /users/:id(.:format) users#update DELETE /users/:id(.:format) users#destroy user_omniauth_authorize GET|POST /users/auth/:provider(.:format) users/omniauth_callbacks#passthru {:provider=>/google_apps/} user_omniauth_callback GET|POST /users/auth/:action/callback(.:format) users/omniauth_callbacks#(?-mix:google_apps) new_user_session GET /sign_in(.:format) devise/sessions#new destroy_user_session GET /sign_out(.:format) devise/sessions#destroy root GET / instances#index Also of note is that I'm running rails 4 and devise 3.0.0.rc (because it's rails 4 compatible) Let me know if there's anything else you need, pretty much everything else that is relevant is in the tutorial thing though. A: You're problem lies here: :omniauth_callbacks => 'users/omniauth_callbacks' 'users/omniauth_callbacks' translates to Users::OmniauthCallbacksController. While your application does have a User model and a UserController, you haven't declared a constant which defines a Users namespace. You'll need to add a controller in that namespace to handle the callback: # app/controllers/users/omniauth_callbacks_controller.rb class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController # action names should match the names of the providers def facebook; end def twitter; end def github; end ... end
{ "pile_set_name": "StackExchange" }
Q: $.each is iterating through each character in array I'm creating an array by pulling data from a json ajax request. But using that array in another $.each statement is resulting in iteration over each character rather than each value. var setInfo = []; $.ajax({ url: blah, async: false, dataType: 'json', success: function{ $.each(data.photosets.photoset, function(i,photoinfo) { setInfo.push(photoinfo.id); }) // completed set values look like 1234,5678,etc.. holler(); }) function holler() { $.each(setInfo, function(index, value) { // using each array value in here splits into each // character rather than each value. So rather than // iterating through each whole value 1234,5678,etc.. // It is iterating as 1,2,3,4,5,6,7,8,and so on. var url1 = "http://www.test.com/" + value; // Rather than http://www.test.com/1234, value is being evaluated as just 1 // so the result is http://www.test.com/1 }); Here's a sample of the json response in which I am getting the id: ({"photosets":{"photoset": [{"id":"123456789", "primary":"102932423", "secret":"19ca84349a", "server":"5143", "farm":6, "photos":"52", "videos":0, "title":{"_content":"Thanksgiving 2010"}, "description":{"_content":""}}, {"id":"012345678", "primary":"1294872352", "secret":"983a9c58d1", "server":"5184", "farm":6, "photos":"12", "videos":0, "title":{"_content":"24th Birthday Dinner at McCormick and Schmitts"}, "description":{"_content":""}}]}, "stat":"ok"}) Edit: It appears that I has a piece of code which I'm assuming was turning the array into a string: setInfo += ''; running my code in console on firebug while on stackoverflow, I'm able to see that an array is now showing up as [1234,5678] BUT running locally, I'm getting a weird jQuery error: uncaught exception: [Exception... "Could not convert JavaScript argument arg 0 [nsIDOMDocumentFragment.appendChild]" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://code.jquery.com/jquery-1.5.js :: <TOP_LEVEL> :: line 5579" data: no] Line 0 A: I tried the code and it works as expected with the data you provided. I would suggest to use console.log inside your function to see what's happening in your arrays. > x= ({"photosets":{"photo set":[{"id":"123456789", "primary":"102932423",... > xx=[] > $.each(x.photosets.photoset,function(i,photoinfo){ xx.push(photoinfo.id); }); > xx ["123456789", "012345678"] > $.each(xx,function(index,value){ console.log(value); }); 123456789 012345678
{ "pile_set_name": "StackExchange" }
Q: jQuery - hover IE issue I have a custom menu in jQuery that apparently doesn't work with IE 8 & 9. It's supposed to open multilevel menus with the hover() method, but it's only working o IE untill the first level from the root. Code : $('ul#leftmenu li').hover(function() { if ($(this).hasClass('top')) return false; var p = $(this).parent().get(0); var o = $(this).offset(); var t; var l; if (leftmenu_level >= 1) { t = 0; l = 210; } else { leftmenu.top = o.top; leftmenu.left = o.left; t = o.top; l = o.left + 210; } $(this).find('ul:first').css({ position : 'absolute', top : t, left : l }).show(); $(this).find('a:first').css('color', '#5a3512'); leftmenu_level++; return true; }, function() { if ($(this).hasClass('top')) return false; $(this).find('a:first').css('color', '#777777'); leftmenu_level--; $(this).find('ul:first').hide(); return true; } ); Live example (left menu) : http://lrp-workwear.com/ Any tips? A: Try applying position:relative to your anchor tags, this seems to force the width & height of the anchor tags correctly and triggers a hover over the entire element and not just the text as it currently seems to be doing. Hope this helps
{ "pile_set_name": "StackExchange" }
Q: Pathfinder from image file I've created a simple pathfinder programme that receives its input from a very small .png file. Example file here: Here's a link to the file (note that the green pixel represents the start, the red pixel represents the end and black pixels represent walls). Also, the file needs to be saved as map.png, in the same folder that the programme is running, for it to be recognised as the input. Although the programme generally works, it often fails to find a path to the exit in more complicated mazes. I'm certain there are many improvements that could be made to make it work in a more efficient way. from PIL import Image import sys, numpy class Node(object): distance = 0 end = False start = False pathItem = False def __init__(self, color, position): self.color = color; self.position = position if color == "0, 0, 0": self.passable = False else: self.passable = True def updateDistance(self, end): diffX = abs(end[0]-self.position[0]) diffY = abs(end[1]-self.position[1]) self.distance = diffX+diffY if self.distance < 10: self.distance = "0"+str(self.distance) else: self.distance = str(self.distance) def checkAround(self): #returns how many available nodes are passable around self. Excluding diagonal counter = [] x = self.position[0] y = self.position[1] if x < width-1: if map[y][x+1].passable: counter.append("r") if x > 0: if map[y][x-1].passable: counter.append("l") if y < height-1: if map[y+1][x].passable: counter.append("d") if y > 0: if map[y-1][x].passable: counter.append("u") return counter def printMap(show="all"):#just a pretty for loop, used for debugging offset=" "*2 # print("\n" + offset, end="") for i in range(width): print(str(i) + " ", end="") print("\n" + offset, end="") print("_"*width*3) for y in range(height): print(str(y) + "|", end="") for x in range(width): if show == "start": if map[y][x].start: print("S ", end="") else: print(" ", end="") elif show == "end": if map[y][x].end: print("E ", end="") else: print(" ", end="") elif show == "passable": if not map[y][x].passable: print("■ ", end="") else: print(" ", end="") else: if map[y][x].color == "255, 255, 255": if show == "distance": print(map[y][x].distance + " ", end="") else: print(" ", end="") elif map[y][x].color == "0, 0, 0": print("■ ", end="") elif map[y][x].color == "0, 255, 0": print("S ", end="") elif map[y][x].color == "255, 0, 0": print("E ", end="") elif map[y][x].color == "0, 0, 255": print("* ", end="") print("") image = Image.open("map1.png") width, height = image.size image_data = list(image.getdata()) for i in range(len(image_data)):#make data easier to handle image_data[i] = Node(str(image_data[i]).replace("(", "").replace(")", ""), [0, 0])#create Node objects map = [] for i in range(width):#change image_data into matrix of Nodes with correct width map.append(image_data[i*width:width*(i+1)])#object can be accessed by map[y][x] start = end = [] for y in range(height): for x in range(width): if map[y][x].color == '0, 255, 0':#set start position if start == []: start = [x, y] map[y][x].start = True else: print("Error: Cannot have more than one start") sys.exit() elif map[y][x].color == '255, 0, 0':#set end position if end == []: end = [x, y] map[y][x].end = True else: print("Error: Cannot have more than one end") sys.exit() if start == []: print("Error: Could not find start") sys.exit() elif end == []: print("Error: Could not find end") sys.exit() #now start and end are found, update Node for y in range(height): for x in range(width): map[y][x].position = [x, y] map[y][x].x = x map[y][x].y = y map[y][x].updateDistance(end) ################################# #FIND PATH foundFinish = False lowestDistance = width+height path = [] currentNode = map[start[1]][start[0]] nextNode = "unknown" while not foundFinish: path.append(currentNode) if currentNode.checkAround() == []: currentNode = map[start[1]][start[0]] for i in path: map[i.y][i.x].passable = True map[path[len(path)-1].y][path[len(path)-1].x].passable = False path = [] for i in currentNode.checkAround(): if currentNode.x < width-1: if i == 'r': if int( map[currentNode.y][currentNode.x+1].distance ) < lowestDistance: lowestDistance = int(map[currentNode.y][currentNode.x+1].distance) nextNode = map[currentNode.y][currentNode.x+1] if currentNode.x > 0: if i == 'l': if int( map[currentNode.y][currentNode.x-1].distance ) < lowestDistance: lowestDistance = int(map[currentNode.y][currentNode.x-1].distance) nextNode = map[currentNode.y][currentNode.x-1] if currentNode.y < height-1: if i == 'd': if int( map[currentNode.y+1][currentNode.x].distance ) < lowestDistance: lowestDistance = int(map[currentNode.y+1][currentNode.x].distance) nextNode = map[currentNode.y+1][currentNode.x] if currentNode.y > 0: if i == 'u': if int( map[currentNode.y-1][currentNode.x].distance ) < lowestDistance: lowestDistance = int(map[currentNode.y-1][currentNode.x].distance) nextNode = map[currentNode.y-1][currentNode.x] if currentNode.checkAround() == [] and path == []: print("Could not find path!") break currentNode.passable = False currentNode = nextNode lowestDistance = width+height if currentNode.distance == "00": foundFinish = True #output found path for i in path: map[i.y][i.x].color = "0, 0, 255" printMap() The way the algorithm works is by assigning each pixel on the map a distance from the exit, regardless if walls are blocking the way or not. Then, starting from the start point, the programme evaluates which pixels are available to move the current position to, and it then moves to the pixel that has the smallest distance from the exit. If the current position has nowhere else to go, i.e. it is blocked off on all 4 sides, the current position is set to: Node.passable = False The current position is then set back to the start and the programme runs again. If the start position is blocked off on all 4 sides, the programme exits. Any hints or tips to make the code better or to help me become a better programmer would be massively appreciated (I'm still a newbie). A: My first annoyance with this is that your printMap function doesn't display it nearly as nicely as I would like it to - I get something like this 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ________________________________________________________________________ 0|S * * * * * * * * * ■ ■ ■ ■ ■ ■ 1|■ ■ ■ ■ ■ ■ ■ ■ * ■ ■ ■ ■ ■ ■ ■ 2| ■ * * * * ■ ■ ■ ■ ■ ■ ■ 3| ■ ■ ■ ■ * ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ 4| ■ ■ * * * ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ 5| ■ ■ ■ ■ ■ ■ ■ * ■ ■ ■ ■ ■ * * * * * * 6| ■ * * ■ ■ ■ ■ ■ * ■ ■ ■ ■ * 7|■ ■ ■ ■ ■ ■ ■ * ■ ■ ■ ■ ■ ■ * ■ ■ * 8|* * * * * * * * ■ ■ ■ ■ * * * ■ ■ * 9|* ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ * ■ ■ ■ ■ ■ * 10|* * * * * * * * * * * * * * * * * ■ E * Without appropriate spacing it makes it much harder to understand what's going on. If you just add some padding it should be manageable (as long as we don't get massive images). Ideally it would end up like this 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 _____________________________________________________________________________________________ 0|S * * * * * * * * * ■ ■ ■ ■ ■ ■ 1|■ ■ ■ ■ ■ ■ ■ ■ * ■ ■ ■ ■ ■ ■ ■ 2| ■ * * * * ■ ■ ■ ■ ■ ■ ■ 3| ■ ■ ■ ■ * ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ 4| ■ ■ * * * ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ 5| ■ ■ ■ ■ ■ ■ ■ * ■ ■ ■ ■ ■ * * * * * * 6| ■ * * ■ ■ ■ ■ ■ * ■ ■ ■ ■ * 7|■ ■ ■ ■ ■ ■ ■ * ■ ■ ■ ■ ■ ■ * ■ ■ * 8|* * * * * * * * ■ ■ ■ ■ * * * ■ ■ * 9|* ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ * ■ ■ ■ ■ ■ * 10|* * * * * * * * * * * * * * * * * ■ E * My second annoyance is how much stuff you have going on in the body of your module. Typically you would do if __name__ == '__main__': # stuff This makes your module import-safe, i.e. if you (or someone else) tries to import your module it won't execute a bunch of code that would be surprising. Generally all you want to do in the body of your module is declare important constants and globals, functions, classes, etc. We can address this by doing two things: Move a lot of that code into functions to make it more generic Move the remaining code into such a block. Lets start with this code image = Image.open("map1.png") width, height = image.size image_data = list(image.getdata()) for i in range(len(image_data)):#make data easier to handle image_data[i] = Node(str(image_data[i]).replace("(", "").replace(")", ""), [0, 0])#create Node objects map = [] for i in range(width):#change image_data into matrix of Nodes with correct width map.append(image_data[i*width:width*(i+1)])#object can be accessed by map[y][x] There are two primary things I'm going to suggest here: Use list comprehensions. Don't override the builtin function map. We can greatly simplify this code and put it into a function like so: def create_image_graph(image_name): image = Image.open(image_name) width, height = image.size image_data = [Node(str(datum).replace("(", "").replace(")", ""), [0, 0]) for datum in image.getdata()] image_graph = [image_data[i*width:(i+1)*width] for i in range(width)] return image_graph, width, height image_map, width, height = create_image_graph("map1.png") Next we can look at this chunk start = end = [] for y in range(height): for x in range(width): if map[y][x].color == '0, 255, 0':#set start position if start == []: start = [x, y] map[y][x].start = True else: print("Error: Cannot have more than one start") sys.exit() elif map[y][x].color == '255, 0, 0':#set end position if end == []: end = [x, y] map[y][x].end = True else: print("Error: Cannot have more than one end") sys.exit() if start == []: print("Error: Could not find start") sys.exit() elif end == []: print("Error: Could not find end") sys.exit() for y in range(height): for x in range(width): map[y][x].position = [x, y] map[y][x].x = x map[y][x].y = y map[y][x].updateDistance(end) First of all, it's kind of weird to do start = end = []. This is a red flag to most experienced Python programmers as that would lead to bugs due to mutability. If someone were to do start.append(1), then both start and end would be equal to [1], which is not desirable. You also use sys.exit() - this is really weird. Instead you should raise an exception. Then whatever is using your function can handle it (if they know how) or let it continue, which will eventually end the program anyway. It's also a bit weird how you have to keep track of the start and the end separately, when really those belong on your map. I'd use a different data structure to hold your map (more on this later) where those are data members. I'd also give a Node a cell_type attribute that can have one of a few enum values - START, END, WALL, EMPTY, PATH for example. Also, all of this information should be available as soon at time of construction. These values should either be set when you initialize the Node (with the exception of updateDistance) or made into properties of the Node (or both). I'd do something like this from enum import Enum CellType = Enum("CellType", "START END PATH WALL EMPTY") class Node(object): _cell_types = { (0, 0, 0): CellType.WALL, (255, 255, 255): CellType.EMPTY, (0, 255, 0): CellType.START, (255, 0, 0): CellType.END, (0, 0, 255): CellType.PATH, CellType.WALL: (0, 0, 0), CellType.EMPTY: (255, 255, 255), CellType.START: (0, 255, 0), CellType.END: (255, 0, 0), CellType.PATH: (0, 0, 255) } @property def passable(self): return self.color != CellType.WALL @property def cell_type(self): return Node._cell_types[self.color] @cell_type.setter def cell_type(self, value): self.color = Node._cell_types[value] @property def x(self): return self.position[0] @property def y(self): return self.position[1] def __init__(self, color, position): self.color = color; self.position = position self.neighbors = [] def distance_to_node(self, node): return sum(map(lambda x, y: abs(x - y), zip(node.position, self.position))) You'll notice that I've put a bidirectional mapping into Node._cell_types - that was more out of convenience than anything, and if I were writing this myself I probably would, but for the sake of this review I just jammed them all in there. I've also stopped treating the color as strings - they work just fine as tuples, and converting them back and forth is silly. This means that we can change create_image_graph to skip all of the str() and .replace() calls. Lastly, I've removed the updateDistance and the checkAround functions - those are really functions that should live on whatever is managing all of your nodes (coming soon, I promise). They both require knowledge that the node itself shouldn't have about the topography of the system as a whole. I did make a distance_to_node function that essentially replaces the updateDistance function - it should accomplish the same thing, although I got a little fancier to make it a one-liner. I'm not sure how I feel about how you calculate your distance, however. You should really be doing something like this (assuming you mean distance in the traditional sense) def distance_to_node(self, node): return sum(map(lambda x, y: pow(x - y, 2), zip(node.position, self.position))) With this we've gotten rid of looping over all of your nodes to set values and do calculations after they've been created. This gets rid of two loops that could take quite a long time for larger images. We'll still need to do error handling for an invalid number of start/end points, but that'll all be handled by the container class, which I'll talk about now. This problem is a graph problem, specifically one about path finding. There are libraries that can handle a lot of this for you (I'll talk about that at the end) but first let's understand what we need in a graph: Nodes, or the actual points in the graph Edges, or connections between nodes There are a bunch of other things you may want for a specific domain or application of a graph (such as start/end points, color, etc) but those two things are all you really need. I started with this structure from collections import defaultdict class InvalidGraphException(Exception): pass class Graph: @classmethod def from_file(cls, image_name): return Graph(Image.open(image_name)) @property def width(self): return self.image.width @property def height(self): return self.image.height _start = None @property def start(self): return self._start @start.setter def start(self, value): if self._start: raise InvalidGraphException("Graph can only have one start point") self._start = value _end = None @property def end(self): return self._end @end.setter def end(self, value): if self._end: raise InvalidGraphException("Graph can only have one end point") self._end = value def _calculate_position(self, index): return index // self.width, index % self.width def __init__(self, image): self.image = image self.nodes = {} self.edges = defaultdict(set) for i, datum in enumerate(image.getdata()): position = self._calculate_position(i) self.add_node(datum, position) if not self.start: raise InvalidGraphException("Graph must have a start point") if not self.end: raise InvalidGraphException("Graph must have an end point") def add_node(self, datum, position): self.nodes[position] = Node(datum, position) if self.nodes[position].cell_type is CellType.START: self.start = position elif self.nodes[position].cell_type is CellType.END: self.end = position This takes a lot of your existing code, but again uses properties to make things cleaner and makes sure that everything is owned by the right thing - the topography of our image owns the collection as a whole, while our nodes own themselves. The next thing we want to do is make our edges - edges should go between adjacent nodes that are passable. We can do that like so def __init__(self, image): # same as before up until this point for position, node in filter(lambda node: node[1].passable, self.nodes.items()): for neighbor in self._neighbors_of_node(node): self.add_edge(node, neighbor) def _neighbors_of_node(self, node): if not node.neighbors: x, y = node.position neighbor_coords = (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) for coordinates in neighbor_coords: neighbor = self.nodes.get(coordinates, None) if neighbor is not None and neighbor.passable: node.neighbors.append(neighbor) return node.neighbors def add_edge(self, start, end): if start.position not in self.nodes: raise ValueError("{} not in the graph".format(start)) if end.position not in self.nodes: raise ValueError("{} not in the graph".format(end)) self.edges[start.position].add(end) self.edges[end.position].add(start) Next we want to actually figure out the distance between them. I've modified your algorithm a bit (I'm not actually sure if it works or not, as it times out for me). I've gotten rid of a lot of the weird string transformations you did as they are no longer necessary, and I've also removed a bunch of code that was unnecessary with the improvements we've made elsewhere. def find_path(self): min_distance = self.width + self.height path = [] current_node = self.nodes[self.start] next_node = None while True: path.append(current_node) if not current_node.neighbors: current_node = start path = [] else: for neighbor in current_node.neighbors: if neighbor not in path: new_distance = current_node.distance_to_node(neighbor) if new_distance < min_distance: min_distance = new_distance next_node = neighbor if not (current_node.neighbors or path): print("Could not find path!") break current_node = next_node min_distance = self.width + self.height if current_node == self.nodes[self.end]: break for node in path: node.color = (0, 0, 255) return path Then to wrap up your module, you'd just do this if __name__ == '__main__': g = Graph.from_file("map1.png") print(g.find_path) Now that we've gone through your manual implementation I have good news and bad news. The good news is that you hopefully have a pretty good feel for why we're using a graph, and how it works. The bad news is that there are libraries to do this work for you. From here on out I'm going to show how we could solve this with NetworkX, a really cool graph library for Python. We're actually going to reuse a lot of our existing code, except with a NetworkX backend, like so import networkx as nx class InvalidNxGraphException(InvalidGraphException): pass _cell_types = { (0, 0, 0): CellType.WALL, (255, 255, 255): CellType.EMPTY, (0, 255, 0): CellType.START, (255, 0, 0): CellType.END, (0, 0, 255): CellType.PATH, CellType.WALL: (0, 0, 0), CellType.EMPTY: (255, 255, 255), CellType.START: (0, 255, 0), CellType.END: (255, 0, 0), CellType.PATH: (0, 0, 255) } class NxGraph: @classmethod def from_file(cls, image_name): return NxGraph(Image.open(image_name)) @property def width(self): return self.image.width @property def height(self): return self.image.height _start = None @property def start(self): return self._start @start.setter def start(self, value): if self._start: raise InvalidNxGraphException("NxGraph can only have one start point") self._start = value _end = None @property def end(self): return self._end @end.setter def end(self, value): if self._end: raise InvalidNxGraphException("NxGraph can only have one end point") self._end = value def _calculate_position(self, index): return index // self.width, index % self.width def __init__(self, image): self.image = image self.graph = nx.Graph() for i, color in enumerate(self.image.getdata()): position = self._calculate_position(i) self.add_node(color, position) if not self.start: raise InvalidNxGraphException("Graph must have a start point") if not self.end: raise InvalidNxGraphException("Graph must have an end point") for node in self.graph.nodes(): if self.graph.node[node]['passable']: x, y = node for position in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)): if position in self.graph.node and self.graph.node[position]['passable']: self.graph.add_edge(position, node) def add_node(self, color, position): cell_type = _cell_types[color] passable = cell_type != CellType.WALL self.graph.add_node(position, color=color, type=cell_type, passable=passable) if cell_type is CellType.START: self.start = position if cell_type is CellType.END: self.end = position def find_path(self): return nx.astar_path(self.graph, self.start, self.end) You'll notice that a lot of our code has been saved, except we cleand up a few spots, and we don't use our Node class anymore because NetworkX lets us put arbitrary attributes on our nodes (each node is a dictionary). Then we use the builtin A* search algorithm instead of your home-grown one, and it'll give us the shortest path. If you wanted you could implement A* search on your own with the old system (it isn't that hard) and avoid the external dependency. It's also relatively easy to add the ability to draw a graph or arbitrary points if you use matplotlib, but I've spent enough hours writing this review so I'll leave that as an exercise for the reader.
{ "pile_set_name": "StackExchange" }
Q: How to animate a bezier curve over a given duration I have created a bezier curve by adding the following script to an empty game object in the inspector. This draws to complete curve at once when I run the code. How can I animate it over a given period of time, say 2 or 3 seconds? public class BCurve : MonoBehaviour { LineRenderer lineRenderer; public Vector3 point0, point1, point2; int numPoints = 50; Vector3[] positions = new Vector3[50]; // Use this for initialization void Start () { lineRenderer = gameObject.AddComponent<LineRenderer>(); lineRenderer.material = new Material (Shader.Find ("Sprites/Default")); lineRenderer.startColor = lineRenderer.endColor = Color.white; lineRenderer.startWidth = lineRenderer.endWidth = 0.1f; lineRenderer.positionCount = numPoints; DrawQuadraticCurve (); } void DrawQuadraticCurve () { for (int i = 1; i < numPoints + 1; i++) { float t = i / (float)numPoints; positions [i - 1] = CalculateLinearBeziearPoint (t, point0, point1, point2); } lineRenderer.SetPositions(positions); } Vector3 CalculateLinearBeziearPoint (float t, Vector3 p0, Vector3 p1, Vector3 p2) { float u = 1 - t; float tt = t * t; float uu = u * u; Vector3 p = uu * p0 + 2 * u * t * p1 + tt * p2; return p; } } A: Use a coroutine: public class BCurve : MonoBehaviour { LineRenderer lineRenderer; public Vector3 point0, point1, point2; int numPoints = 50; Vector3[] positions = new Vector3[50]; // Use this for initialization void Start () { lineRenderer = gameObject.AddComponent<LineRenderer>(); lineRenderer.material = new Material (Shader.Find ("Sprites/Default")); lineRenderer.startColor = lineRenderer.endColor = Color.white; lineRenderer.startWidth = lineRenderer.endWidth = 0.1f; StartCoroutine(DrawQuadraticCurve (3)); } IEnumerator DrawQuadraticCurve (float duration) { //Calculate wait duration for each loop so it match 3 seconds float waitDur = duration / numPoints; for (int i = 1; i < numPoints + 1; i++) { float t = i / (float)numPoints; lineRenderer.positionCount = i; lineRenderer.setPosition(i - 1, CalculateLinearBeziearPoint (t, point0, point1, point2)); yield return new WaitForSeconds(waitDur); } } Vector3 CalculateLinearBeziearPoint (float t, Vector3 p0, Vector3 p1, Vector3 p2) { float u = 1 - t; float tt = t * t; float uu = u * u; Vector3 p = uu * p0 + 2 * u * t * p1 + tt * p2; return p; } } EDIT: Added a specific duration to the call. Note: If duration / numPoints is likely to be less than Time.deltaTime, you may want to use this method instead, which can draw multiple points per frame: IEnumerator DrawQuadraticCurve (float duration) { float progressPerSecond = 1 / duration; float startTime = Time.time; float progress = 0; while (progress < 1) { progress = Mathf.clamp01((Time.time - startTime) * progressPerSecond); int prevPointCount = lineRenderer.positionCount; int curPointCount = progress * numPoints; lineRenderer.positionCount = curPointCount; for (int i = prevPointCount; i < curPointCount; ++i) { float t = i / (float)numPoints; lineRenderer.setPosition(i, CalculateLinearBeziearPoint (t, point0, point1, point2)); } yield return null; } }
{ "pile_set_name": "StackExchange" }
Q: regarding continuation in OnLisp I am still interested in the question which has been answered. continuation in common lisp by macros — regarding an implemetation in OnLisp What will happen if Paul Graham's assumption is correct especially when change from (A 5) to (B 1)? What is cont bound to here? And one more confusion when the text says =bind, is intended to be used in the same way as multiple-value-bind. It takes a list of parameters, an expression, and a body of code: the parameters are bound to the values returned by the expression, and the code body is evaluated with those bindings. I cannot see the binding directly from the macro definition of =bind which looks like (defmacro =bind (parms expr &body body) `(let ((*cont* #'(lambda ,parms ,@body))) ,expr)) Does the binding happens only when =values comes in later? A: The macro sets the continuation, *cont*, to be a lambda which takes all of your variables as arguments, and then evaluates the expression expr. The expression is expected to call the continuation with its final value, which can be done indirectly by calling the =values function, or directly with funcall. Unlike Scheme, where the continuation is implicitly called with the return value of any expression, you must explicitly write your code in continuation-passing style by calling *cont* or using =values instead of returning from any function.
{ "pile_set_name": "StackExchange" }
Q: Django Crispy form will not save/submit I am unable to get the Submit to work with crispy-froms. Normal django forms with bootstrap works fine. I have tried all the tutorials i could find and are at this time unable to find what is wrong with the code. When clicking on sumbit it opens my customer overview page, but no new customer has been added. Not all fields are shown here but the field settings are all set to allow null values. My models.py from django.db import models from django.utils.encoding import smart_unicode class CustomerType(models.Model): customer_type = models.CharField(max_length=120, null=True, blank=True) timestamp_created = models.DateTimeField(auto_now_add=True, auto_now=False) timestamp_updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): return smart_unicode(self.customer_type) class Customer(models.Model): customer_type = models.ForeignKey(CustomerType, null=True, blank=True) customer_name = models.CharField(max_length=120, null=True, blank=True) my views.py def customercrispy(request): form = ExampleForm() return render_to_response("customer-crispy.html", {"example_form": form}, context_instance=RequestContext(request)) my forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit, Div, Field from crispy_forms.bootstrap import TabHolder, Tab, FormActions from .models import Customer class CustomerAddForm(forms.ModelForm): class Meta: model = Customer class ExampleForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ExampleForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_method = 'post' self.helper.form_action = '/customeroverview/' self.helper.add_input(Submit('submit', 'Submit')) class Meta: model = Customer EDIT: CMD output when opening form [08/Oct/2014 12:45:12] "GET /customercrispy/ HTTP/1.1" 200 11203 [08/Oct/2014 12:45:12] "GET /customercrispy/static/js/ie-emulation-modes-warning.js HTTP/1.1" 404 3118 [08/Oct/2014 12:45:12] "GET /assets/js/ie10-viewport-bug-workaround.js HTTP/1.1" 404 3079 CMD output when saving [08/Oct/2014 12:46:52] "POST /customeroverview/ HTTP/1.1" 200 5129 [08/Oct/2014 12:46:52] "GET /customeroverview/static/js/ie-emulation-modes-warning.js HTTP/1.1" 404 3124 [08/Oct/2014 12:46:52] "GET /assets/js/ie10-viewport-bug-workaround.js HTTP/1.1" 404 3079 A: Your view isn't ok. At the moment you only create a form and render it. Nothing is done when the form is posted, it is just rendered again. So in case of a POST, check if the form is valid and save it. So that will make it something like: def customercrispy(request): if request.method == 'POST': form = ExampleForm(request.POST) if form.is_valid(): form.save() return redirect('customercripsy') # name of view stated in urls else: form = ExampleForm() return render_to_response("customer-crispy.html", {"example_form": form}, context_instance=RequestContext(request)) This also avoids you to set '/customeroverview/' as form action. If you really want to post to this url, add the customeroverview view to your question. Btw, I would advice you to use django's reverse function to create your urls. (https://docs.djangoproject.com/en/dev/ref/urlresolvers/#reverse). More documentation about modelforms in your view: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-a-model-formset-in-a-view
{ "pile_set_name": "StackExchange" }
Q: Node js on virtual machine ignores requests from outside this is the first time I use nodejs (and express), so I'm sorry if the question is stupid. I installed nodejs and express on my debin virtual machine and created hello-world application. I run it like DEBUG=myapp ./bin/www Calling my application from virtual machine works just fine, but it ignores requests from outside workspace (windows). I thought it could be related to apache that I also have, so I stopped it, but it doesn't solve the issue. Please advice. Thanks. A: And this is how I solved it. Opened port 3000 in Firewall (not sure if this was required), see how to do this http://windows.microsoft.com/en-us/windows/open-port-windows-firewall Added port forwarding in my vm settings in virtualbox. By default there were ports 80 and 22. So I added 3000 which was the solution.
{ "pile_set_name": "StackExchange" }
Q: Reduce/concat issue when calling a property of a property that doesn't exist If "a_b" does not exist then the following code throws back undefined - which is what I want: var abc= json.reduce((a,c) => a.concat({xyz:c.a_b}), []) However, if I do the following code and look for "media" within "a_b" that does not exist then I get a failure "Cannot read property 'media' of undefined". var abc= json.reduce((a,c) => a.concat({xyz:c.a_b.media}), []) Why is this the case? In both cases "a_b" does not exist yet it is ok with the code if I just call that but not if I try and look for a property within it. Is there a way to get around this? For example, I am trying to use "|| null" but that doesn't seem to work within a concat, as below. var abc= json.reduce((a,c) => a.concat({xyz:c.a_b.media || null}), []) A: Don't use concat method it will create a new array instance, use push instead: var abc = json.reduce((a, c) => { a.push({ xyz: c.a_b && c.a_b.media }); return a; }, []);
{ "pile_set_name": "StackExchange" }
Q: concerning UNION and JOIN in mysql Here is my tables: how to do I get the following from the above table in mysql using union? here is my answer: SELECT name, city(Person) FROM Persons UNION SELECT name, 'something' FROM Persons UION SELECT pname, city(Project) FROM Projects; A: Try something like this: SELECT name, city, 'Person' AS Explanation FROM Persons UNION ALL SELECT pname, place, 'Project' AS Explanation FROM Projects
{ "pile_set_name": "StackExchange" }
Q: Assets Content/Fields not available until entry is saved? I've got Asset location setup with a Photo Caption field. And a Photo Gallery field which references said Asset. When creating a new entry, I'm uploading images to the Photo Gallery field. When the images are uploaded, double-clicking brings up the modal but the Photo Caption field is not available. Only after saving the entry and then re-opening it to edit is the Photo Caption field available in the Assets modal. Is the normal behavior? Did I miss something? It would be ideal for my clients to be able to edit the photo meta information while they're creating a new entry. A: This is an issue with Assets fields if you have a dynamic Subfolder path set on in the field’s settings. It’s been fixed for 2.3 though ;)
{ "pile_set_name": "StackExchange" }
Q: Use only part of a php variable - is this possible? Is it possible to create a new variable with only the left X amount of values automatically? I have a variable being passed to a page, but I need to use this in a query, both the full variable and part of it full variable is like this - Day 55 Left of variable - Day So consequently I would have two variables to use in a query $var1 = "Day 55"; $var2 = "Day"; Sorry if this is a noob question, I'm new to php A: What you want to use is the substring. $var1 = "Day 55"; $var2 = substr($var1,0,3); // 3 characters of $var1, starting with character 0.
{ "pile_set_name": "StackExchange" }
Q: Как разбить 24 часа по 5 минут в виде 12:00, 12:05,12:10 и т.д.? Друзья, прошу помочь с решением. Как разложить 24 часа шагом 5 минут в виде 12:00, 12:05,12:10 и т.д.? Делается для графика! Есть такое решение по дням: $num = cal_days_in_month(CAL_GREGORIAN, $month, $year); for($i=1;$i<=$num;$i++) $mktime=mktime(0,0,0,$month,$i,$year); $date=date("d/m",$mktime); $dates_month[$i]=$date; echo $date } Помогите переделать. A: <?php date_default_timezone_set('UTC'); $num = 86400/300; // Секунд в дне поделить на секунды в 5 минутах for($i=1;$i<=$num;$i++) { $mktime = $i*300; $date=date("H:i",$mktime); $dates_month[$i]=$date; echo $date." "; } ?>
{ "pile_set_name": "StackExchange" }
Q: The data is lost from the project after i import it in to eclipse I accidentally deleted a completed project of mine from eclipse. The deleted project is still in my workspace folder. I tried to import it in to eclipse by clicking, File -> Android -> Existing android code in to workspace. I had checked my data in the project folder, before importing it in to eclipse by opening it in notepad. The data was all there then. But after i opened it in eclipse, the data is all lost. The java files and xml files are there, but with no codes inside. It is all 0kb. Is there any solution to recover it back ? A: easiest way.. start a new workspace and do an android project import of the project form your first workspace. In future yo should get use to the git dev flow which would be to set up the project in another folder rather than the eclipse workspace..other benefit is that whenever you update Eclipse versions workspace etc you still have a non corrupted subfolder with all your pojrects in it.
{ "pile_set_name": "StackExchange" }
Q: Расположение методов в многопоточном приложении При изучении многопоточности в Java столкнулся с непонятным для меня явлением при перестановке двух методов местами внутри одного блока if. Ниже пример, в котором запускаются 10 потоков (ссылка на пример кода в GitHub). Их задача в порядке возрастания Id произвести некую работу, в данном случае вывести сообщение, содержащее Id потока и значение переменной в вспомогательном классе. Пример содержит три класса: Класс Main. В нем в цикле создается 10 экземпляров класса ThreadExample, которые, в свою очередь являются элементами массива. Id первого экземпляра потока, до его старта заносится в переменную вспомогательного класса. После этого поочередно в цикле вызывается метод start всех потоков. package lan.example.thread_example; public class Main { static HelperSingletonBillPugh INSTANCE_TEST_THREAD = HelperSingletonBillPugh.getInstance(); static ThreadExample[] myThreads = new ThreadExample[10]; static final int COUNT = 10; public static void main(String[] args) { for (int i = 0; i < COUNT; i++) { myThreads[i] = new ThreadExample(); if (i == 0) { INSTANCE_TEST_THREAD.setCurentThreadId(myThreads[i].getId()); } myThreads[i].start(); } } } Класс HelperSingletonBillPugh. Это вспомогательный хелпер класс, реализованрый по типу синглетона способом Била Пью. Вроде такой тип реализации синглетона считается потокобезопасным. Класс содержит переменную curentThreadId типа long с Id потока и публичные методы setCurentThreadId(long threadId), getCurentThreadId(), incremenCurentThreadId() для изменения, чтения и инкремента значения этой переменной. package lan.example.thread_example; public class HelperSingletonBillPugh { private HelperSingletonBillPugh() { } private static class SingletonHandler { private static final HelperSingletonBillPugh INSTANCE = new HelperSingletonBillPugh(); } public static HelperSingletonBillPugh getInstance() { return SingletonHandler.INSTANCE; } private long curentThreadId = 0L; // Id потока, который должен выполнить вывод сообщения public long getCurentThreadId() { return this.curentThreadId; } public void setCurentThreadId(long threadId) { this.curentThreadId = threadId; } public void incremenCurentThreadId() { this.curentThreadId++; } } Класс ThreadExample. Класс наследник Thread. В нем вечный цикл, с паузами и постоянным сравнением значения getId() потока с переменной curentThreadId экземпляра вспомогательного класса HelperSingletonBillPugh. Если равенство выполняется, то выводится сообщение, переменная curentThreadId увеличивается на 1 и поток завершает работу. package lan.example.thread_example; public final class ThreadExample extends Thread { static HelperSingletonBillPugh INSTANCE_TEST_THREAD = HelperSingletonBillPugh.getInstance(); @Override public void run() { while (true) { if (INSTANCE_TEST_THREAD.getCurentThreadId() == this.getId()) { // Раскомментируй следующую строку //INSTANCE_TEST_THREAD.incremenCurentThreadId(); System.out.println("Print " + this.getName() + " ### ID:" + this.getId() + " ### getCurentThreadId: " + INSTANCE_TEST_THREAD.getCurentThreadId()); // Закоментируй следующую строку INSTANCE_TEST_THREAD.incremenCurentThreadId(); break; } } } } В данном примере кода сообщения выводятся последовательно и потоки завершают свою работу, все стабильно от запуска к запуску, вот такой вывод: Print Thread-1 ### ID:11 ### getCurentThreadId: 11 Print Thread-2 ### ID:12 ### getCurentThreadId: 12 Print Thread-3 ### ID:13 ### getCurentThreadId: 13 Print Thread-4 ### ID:14 ### getCurentThreadId: 14 Print Thread-5 ### ID:15 ### getCurentThreadId: 15 Print Thread-6 ### ID:16 ### getCurentThreadId: 16 Print Thread-7 ### ID:17 ### getCurentThreadId: 17 Print Thread-8 ### ID:18 ### getCurentThreadId: 18 Print Thread-9 ### ID:19 ### getCurentThreadId: 19 Print Thread-10 ### ID:20 ### getCurentThreadId: 20 Но стоит только переставить местами метод INSTANCE_TEST_THREAD.incremenCurentThreadId() и метод System.out.println() (в коде помечено где убрать и добавить коммент) и результат становится не стабильным и для меня не понятным, хотя перестановка осуществляется внутри блока if. Если быть точнее, то он не всегда стабильный, то есть, несколько запусков может пройти вполне корректно. Вот вывод одного из запусков после перестановки методов местами: Print Thread-1 ### ID:11 ### getCurentThreadId: 12 Print Thread-2 ### ID:12 ### getCurentThreadId: 15 Print Thread-6 ### ID:16 ### getCurentThreadId: 17 Print Thread-5 ### ID:15 ### getCurentThreadId: 16 Print Thread-4 ### ID:14 ### getCurentThreadId: 15 Print Thread-7 ### ID:17 ### getCurentThreadId: 21 Print Thread-3 ### ID:13 ### getCurentThreadId: 21 Print Thread-8 ### ID:18 ### getCurentThreadId: 21 Print Thread-9 ### ID:19 ### getCurentThreadId: 21 Print Thread-10 ### ID:20 ### getCurentThreadId: 21 Из примера видно, что потоки выводят сообщения хаотично и значение переменной getCurentThreadId временами отличается от Id текущего потока более чем на 1. Что-же происходит при изменении местами двух этих методов? Дело в том, что когда System.out.println() находится перед INSTANCE_TEST_THREAD.incremenCurentThreadId(), то у меня нет ни одного непредсказуемого результата. Можно ли считать это стабильной работой или все-таки эта стабильность обманчива и при неких обстоятельствах пример отработает не корректно? P/S. На всякий случай уточню. Я немного имею представление про Java Memory Model, оператор volatile, блок synchronize, про кэши данных и атомарность, правда глубоких знаний пока нет, но добиться гарантированной стабильной работы примера скорее всего смогу. Интересует именно понимание того, какие-такие серьезные изменения происходят при перестановки местами этих двух методов, так влияющие на результат работы примера. И, как следствие, можно ли считать стабильной работу примера в первом случае и почему? Проверял пример на разных операционных системах (Linux Mint 32 и 64 bit, Windows 10 64 bit), но правда только с Oracle JDK. A: На самом деле всё достаточно просто. Вы создаёте несколько потоков, а данный метод разрешает выполняться только 1 с нужным id. Этот id содержится в переменной INSTANCE_TEST_THREAD.getCurentThreadId(). Теперь вы меняете местами. Может быть такая ситуация: 1 поток зашёл, значение 1 1 поток увеличил значение до 2 2 поток зашёл значение 2 2 поток увеличил значение до 3 1 поток вывел 3 (!!) 2 поток вывел 3 (!!) 3 поток увеличил значение до 4 3 поток вывел 4. Думаю идею вы поняли. Поменяв местами мы делаем гонку потоков с непредсказуемым порядком выполнения, по сути сделав весь код синхронизации нерабочим. A: Дело в том, что операция инкремента не является атомарной, а состоит из двух операций: чтения текущего значения и записи увеличенного значения. Если развернуть ее, то цикл в первом сценарии будет выглядеть так: while (...) { <чтение id> // вывод на консоль <чтение id> // инкремент, шаг 1 <запись id> // инкремент, шаг 2 } Такое расположение операций вкупе с хитрым условием while по сути служит локом, дающим доступ к телу цикла только одному потоку. Сначала только первый поток заходит внутрь цикла, а остальные просто прокручивают его ("блокируются"). Когда первый поток записывает увеличенный id и выходит из цикла, то уже он начинает прокручивать цикл ("блокируется"), а второй поток заходит внутрь. И так по очереди для всех потоков. Именно за счет инкремента все потоки получают этот доступ последовательно, согласно своим номерам. Важным здесь является то, что запись id по сути освобождает "лок" текущего потока и "разрешает" выполнение другого потока. Пока она идет последней в теле цикла, проблем не возникает. Во втором сценарии цикл выглядит следующим образом: while (...) { <чтение id> // инкремент, шаг 1 <запись id> // инкремент, шаг 2 <чтение id> // вывод на консоль } Теперь мы видим, что "лок" освобождается чуть раньше. К чему это может привести? К тому, что между записью id и вторым чтением id могут начать исполняться другие потоки, поскольку "лок" свободен и доступ к телу цикла может получить другой поток. Т.е. возникает классическая гонка, в результате которой может происходить следующее: поток на втором чтении id может получить уже обновленное значение (это объясняет, например, почему Thread-2 выводит 15, а не 13) вывод в консоль может перепутаться из-за того, что другие потоки "встревают" сразу после записи id while (...) { <чтение id> // инкремент, шаг 1 <запись id> // инкремент, шаг 2 <возможное исполнение других потоков> <чтение id> // вывод на консоль (потенциально уже нового значения) } Сценарий выполнения для приведенного вами в вопросе лога может выглядеть так: все потоки начинают выполнение все потоки кроме потока 1 "блокируются" на условии while поток 1 читает id (=11) поток 1 увеличивает id (=12) поток 2 "разблокируется" поток 2 читает id (=12) поток 1 читает id и выводит на консоль (=12) поток 1 "засыпает" поток 2 увеличивает id (=13) поток 3 "разблокируется" поток 3 читает id (=13) поток 3 увеличивает id (=14) поток 4 "разблокируется" поток 4 читает id (=14) поток 4 увеличивает id (=15) поток 2 читает id и выводит на консоль (=15) поток 2 "засыпает" поток 5 "разблокируется" поток 5 читает id (=15) поток 5 увеличивает id (=16) поток 6 "разблокируется" поток 6 читает id (=16) поток 6 увеличивает id (=17) поток 6 читает id и выводит на консоль (=17) поток 6 "засыпает" ...и так далее
{ "pile_set_name": "StackExchange" }
Q: Using XPath in XSL to select all attribute values of a node with attribute name starting with a given string I have some xml which looks like this: <row> <anode myattr1="value1" anotherAttr="notthis"> blah </anode> <anothernode myattr1="value1" myattr2="value2" anotherAttr="notthis"> blahBlah </anothernode> </row> I want to turn into something like this: <tr> <td title="value1"> blah </td> <td title="value1\nvalue2"> blahBlah </td> </tr> So I'm trying to use the "fn:starts-with" to select these attribute values, but is not quite working. This is what I have so far: <xsl:for-each select="row"> <tr> <xsl:for-each select="./*"> <xsl:variable name="title"> <xsl:for-each select="./@[fn:starts-with(name(),'myattr')]"> <xsl:value-of select="."/> </xsl:for-each> </xsl:variable> <td title="$title"><xsl:value-of select="."/></td> </xsl:for-each> </tr> </xsl:for-each> But am getting an exception when I run this. Any help would be appreciated. A: A short and simple 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:template match="/"> <tr> <xsl:apply-templates/> </tr> </xsl:template> <xsl:template match="row/*"> <td> <xsl:apply-templates select="@*[starts-with(name(),'myattr')][1]"/> <xsl:value-of select="."/> </td> </xsl:template> <xsl:template match="@*[starts-with(name(),'myattr')][1]"> <xsl:attribute name="title"> <xsl:value-of select="."/> <xsl:apply-templates select= "../@*[starts-with(name(),'myattr')][position()>1]"/> </xsl:attribute> </xsl:template> <xsl:template match="@*[starts-with(name(),'myattr')][position()>1]"> <xsl:value-of select="concat('\n', .)"/> </xsl:template> </xsl:stylesheet> when applied on the provided XML document: <row> <anode anotherAttr="notthis" myattr1="value1" > blah </anode> <anothernode anotherAttr="notthis" myattr1="value1" myattr2="value2" > blahBlah </anothernode> </row> the wanted, correct result is produced: <tr> <td title="value1"> blah </td> <td title="value1\nvalue2"> blahBlah </td> </tr>
{ "pile_set_name": "StackExchange" }
Q: Has the Trump administration revoked these listed LGBT protections? This image is doing the rounds on Facebook: It quotes a tweet by Donald Trump from early 2016, followed by claims that the Trump administration has performed these actions: Thank you to the LGBT community! I will fight for you while Hillary brings in more people that will threaten your freedoms and beliefs. Donald J. Trump – @realDonaldTrump Jan: Removed all content on LGBT civil rights from whitehouse.gov website Feb: Rescinded protections for transgender students on their use of restrooms in public schools Mar: Revoked protections for LGBT workers against discrimination in hiring employment Apr: drops federal lawsuit over North Carolina's statewide prohibition on LGBT equality July: Signals the US military will not "accept or allow" transgender people to serve Did the Trump administration perform all of the claimed actions, on the months cited? A: Jan: removed all content on LGBT civil rights from whitehouse.gov website True During Barack Obama’s presidency, if you typed whitehouse.gov/lgbt into your browser, you reached a page highlighting the administration’s victories and policy changes regarding LGBT rights. It outlined historic court victories and even featured campaigns like the It Gets Better Project to help LGBT youth. Today, however -- just hours after President Donald J. Trump took the oath of office as the United States’ 45th president -- if you type in whitehouse.gov/lgbt, you are redirected to a new “transitionsplash” page. CBS News Feb: Rescinded protections for transgender students on their use of restrooms in public schools True The Trump administration on Wednesday revoked federal guidelines specifying that transgender students have the right to use public school restrooms that match their gender identity, taking a stand on a contentious issue that has become the central battle over LGBT rights. Washington Post, see also Reuters, NPR, NY Times. With regard to the effect of this guidance on court cases, see as an example, this order, which cites both the Obama administration guidance and the Trump administration withdrawal of that guidance as cause for, first, the 4th district to reverse a lower court opinion (the original Obama administration guidance) and then caused the Supreme Court to vacate the 4th district's decision (in response to the Trump administration withdrawal of that guidance). In response to Obama administration guidance In a decision dated April 19, 2016, we reversed the district court’s dismissal of Grimm’s Title IX claim, relying on a guidance document issued by the U.S. Department of Education and U.S. Department of Justice. In response to Trump administration withdrawal After the Supreme Court calendared the case for argument, the new Administration issued a guidance document on February 22, 2017, that withdrew the prior Administration’s guidance document regarding the treatment of transgender students, and the Court then vacated our April 2016 decision and remanded the case to us “for further consideration in light of the [new] guidance document issued by the Department of Education and Department of Justice.” Mar: Revoked protections for LGBT workers against discrimination in hiring employment True - his action was limited to discrimination limits relating to federal contractors. Trump signed an order on Monday revoking protections signed into law by President Obama in 2014. Obama signed an executive order banning LGBT discrimination among federal contractors; he concurrently signed an order requiring contracted businesses prove they're complying with federal laws and executive orders. President Trump rescinded the latter order, making it much more difficult to know whether a business has committed to ending LGBT bias in hiring, firing, and promotions. The Advocate, see also Rolling Stone, Boston Globe, Salon Apr: drops federal lawsuit over North Carolina's statewide prohibition on LGBT equality True- the reason given for dropping the federal suit is that North Carolina repealed one bill and replaced it with another. The new bill was watered down but still attracted intense criticism by LGBT groups who believe the federal suit should have continued against the replacement bill. Officials said that they were abandoning the lawsuit because North Carolina lawmakers last month enacted a law repealing the bathroom bill and replacing it with another measure. The new law, however, has prompted intense criticism from the LGBT groups who long opposed the first bill and are vowing to keep fighting the new measure in court despite the Justice Department’s decision to bow out. Washington Post, see also CNN July: Signals the US military will not "accept or allow" transgender people to serve True Donald Trump said on Wednesday he would not allow transgender individuals to serve in the US military in any capacity, reversing a policy put in place by Barack Obama a year ago. The US president tweeted: “After consultation with my generals and military experts, please be advised that the United States government will not accept or allow … transgender individuals to serve in any capacity in the US military.” The Guardian, see also NY Times A: Jan - mostly true Feb - true Mar - somewhat true Apr - mostly false Jul - true Jan, removed all content on LGBT civil rights from whitehouse.gov website: mostly true This is rather misleading as every new administration removes and archives the content of whitehouse.gov. You can see the old site at obamawhitehouse.archives.gov. Redirects have been added for LGBT content, e.g. whitehouse.gov/the-press-office/2016/06/29/fact-sheet-promoting-and-protecting-human-rights-lgbt-persons. It is arguable whether this is still counted as being "on" whitehouse.gov. The Trump administration has not added any LGBT-related content on the new whitehouse.gov. In fact, the entire website is significantly lighter than it used to be. Compare current and previous issue pages. Perhaps this is due to time in office, preference, or other reasons. Feb, rescinded protections for transgender students on their use of restrooms in public schools: true Obama's Education department issued a letter: When a school [that receives Federal funds] provides sex-segregated activities and facilities, transgender students must be allowed to participate in such activities and access such facilities consistent with their gender identity. This court decision over transgender bathroom use cites that document in its decision. we reversed the district court’s dismissal of Grimm’s Title IX claim, relying on a guidance document issued by the U.S. Department of Education and U.S. Department of Justice Trump's Education department revoked the letter, and therefore any legal basis that relied on it. EDIT: Credit to @DeNovosupportsGoFundMonica for pointing the error of earlier legal opinions I relied on, which stated that Trump (or any other president) could issue opinions but could not actually affect legalities. For context, I leave the erroneous statements from Lambda Legal and the ACLU below: This was only ever "guidance." Trump's actions do not change the law itself -- transgender students remain protected by Title IX of the Education Amendments of 1972 -- but abandoning the guidance intentionally creates confusion about what federal law requires. Rachel Tiven, CEO of Lambda Legal and While it's disappointing to see the Trump administration revoke the guidance, the administration cannot change what Title IX means. James Esseks, ACLU Obama's letter itself did not add any legal protections for transgender bathroom use. Rather, it was a statement of what the executive branch desired to enforce. The courts would decide any such cases independent of the Obama's or Trump's opinion on Title IX. Mar, revoked protections for LGBT workers against discrimination in hiring employment: somewhat true Two caveats: (1) it only ever applied to federal contracts, and (2) it was a purely administrative change, not a legal one. Trump revoked the Executive Order 13673. It required evidence that suppliers for federal contracts of $500k+ were in compliance with Fair Labor Standards Act, Occupational Safety and Health Act, Migrant and Seasonal Agricultural Worker Act, National Labor Relations, Davis-Bacon Act, Service Contract Act, Equal Employment Opportunity Executive Order, Rehabilitation Act, Vietnam Era Veterans' Readjustment Assistance Act, Family and Medical Leave Act, Civil Rights Act, Americans with Disabilities Act, Age Discrimination in Employment Act, Establishing a Minimum Wage for Contractors Executive order, and "equivalent State laws". These are still laws, but compliance will no longer have to be demonstrated for every contract. Importantly, the concurrently issued Executive Order 13672 that actually covered LGBT discrimination remains in force. And none of this matters for employers who are not federal contractors. Apr, drops federal lawsuit over North Carolina's statewide prohibition on LGBT equality: mostly false "Statewide prohibition on LGBT equality" is overly broad on two counts: The Public Facilities Privacy & Security Act pertains only to transgender persons, not any other LGBT person (lesbians, gays, bisexuals). The law is scoped strictly to bathroom use in government facilities. It does not affect housing, employment, taxes, etc. All existing protections remain in place for these. And even more glaring problem with the claim is that North Carolina repealed the law. While technically the Justice Department did perform the legal formality of withdrawing their suit, they did this only because the defendant acquiesced. By any reasonable definition, the Justice Department "won" their case. When North Carolina repealed the law, they did replace it with another prohibiting local governments from legislating in this area. Though the practical consequences of the new law likewise has the ire of transgender groups, there is really no ground for the Justice Department to claim constitutional violations. July, signals the US military will not "accept or allow" transgender people to serve: true Then Donald Trump announced via Twitter the United States Government will not accept or allow...Transgender individuals to serve in any capacity in the U.S. Military. For context, at the time of this answer, openly transgendered recruits have never been permitted in the U.S. military. Obama announced the restriction would be lifted, but not until a full year after he left office, in 2018. EDIT: Note that the claim did not say that President Trump ordered or carried out the ban's continuation; the claim conservately stated that he "signaled" it, and he certainly did that.
{ "pile_set_name": "StackExchange" }
Q: Page Renders in Safari but not in Chrome on iPad Versions: PC OS: Windows 8 iPad OS: iOS 7.0.2 (11A5901) Chrome: 30.0.1599.16 ExtJS 3.4.0 Problem: I have a web application that relies heavily on Javascript (using the ExtJS framework). It all seems to work as I expect except one page. When browsing this page on my iPad using Safari, the page renders correctly. When in Chrome, I only get the part of the page that doesn't need javascript. However, if I click on the chrome menu and request desktop site then the page loads as intended. Things I have tried / searched for: How to debug this page in Chrome on the iPad. All the articles are either old or say to use Safari (because Chrome and Safari use the same engine?), but the page works in Safari. Setting the agent string in my desktop version of Chrome. The page still loaded correctly. I turned off Javascript in Safari (just to see). Safari then behaved like Chrome. I'm just looking for a direction to go or something to try. I'm pretty new when it comes to iPad development. But I think that if I could just see what the developer tools show, I can work it out from there. I can't post a link because the site is behind a login. Any help is appreciated! A: One approach might be to load Firebug Lite on your page. This would allow you to log errors and print JavaScript values to the console.
{ "pile_set_name": "StackExchange" }
Q: How do I fix this error when building Octave? I'm using Ubuntu 13.04 Gnome edition. I'm trying to compile Octave 3.6.4 using the source. the configure went smooth without any errors but the make command returned me following errors: collect2: error: ld returned 1 exit status make[3]: *** [octave] Error 1 make[3]: Leaving directory `/home/ankit/Softwares/octave-3.6.4/src' make[2]: *** [all] Error 2 make[2]: Leaving directory `/home/ankit/Softwares/octave-3.6.4/src' make[1]: *** [all-recursive] Error 1 make[1]: Leaving directory `/home/ankit/Softwares/octave-3.6.4' make: *** [all] Error 2 what more do I require to post to get the problem sorted? A: I finally got the problem sorted. The problem was with the fortran library not communicating with the g++ as I had F77 as the default fortran compiler. So I installed gfortran which helped in the liking and the make process completed successfully. This is the entire discussion thread on the octave help page in case any one requires more help regarding this issue.
{ "pile_set_name": "StackExchange" }
Q: Drawing nodes of multigraph in fixed position What i Have : a multigraph with four nodes and four edge. Each node has a position specified (the nodes form a squadre structure) What i want: drawing the multigraph with nodes posistions. PROBLEM: Positions are ignored in the final layout. This is my code : import networkx as nx import pydot from my_lib import * graph= nx.MultiGraph() #add 4 nodes in the vertexs of a square. X and Y are the coordinates graph.add_node(1,x=10,y=10) graph.add_node(2,x=10,y=20) graph.add_node(3,x=20,y=10) graph.add_node(4,x=20,y=20) graph.add_edge(1,2) graph.add_edge(2,3) graph.add_edge(3,4) graph.add_edge(4,1) #transform the multigraph in pydot for draw it graphDot=nx.to_pydot(graph) #change some attribute for the draw, like shape of nodes and the position of nodes for node in graphDot.get_nodes(): node.set_shape('circle') #getAttrDot is a function that returns the value of attribute passed pos_string='\''+ get_attrDot(node,'x')+','+get_attrDot(node,'y')+'!\'' print 'coordinate: ' + pos_string #the pos_string printed is correct form: 'x,y!' node.set('pos',pos_string) graphDot.write_png('test_position.png') Here the result of this code. The image 'test_position.png' is :[1]: http://imgur.com/dDj3xFl As you can see, the node positions are ignored. Can you help me please? Thanks! EDIT SOLVED: The suggest of Aric solved my problem. THANKS!!! A: You can set the attributes before you convert the graph to a Pydot object: import networkx as nx graph= nx.MultiGraph() #add 4 nodes in the vertexs of a square. X and Y are the coordinates graph.add_node(1,x=100,y=100) graph.add_node(2,x=100,y=200) graph.add_node(3,x=200,y=100) graph.add_node(4,x=200,y=200) graph.add_edge(1,2) graph.add_edge(2,3) graph.add_edge(3,4) graph.add_edge(4,1) # assign positions for n in graph: graph.node[n]['pos'] = '"%d,%d"'%(graph.node[n]['x'], graph.node[n]['y']) p = nx.to_pydot(graph) print p.to_string() p.write('foo.dot') # run neato -n2 -Tpng foo.dot >foo.png The output is: graph G { 1 [y=100, x=100, pos="100,100"]; 2 [y=200, x=100, pos="100,200"]; 3 [y=100, x=200, pos="200,100"]; 4 [y=200, x=200, pos="200,200"]; 1 -- 2 [key=0]; 1 -- 4 [key=0]; 2 -- 3 [key=0]; 3 -- 4 [key=0]; } Run neato -n2 -Tpng foo.dot >foo.png (the -n2 keeps your node positions)
{ "pile_set_name": "StackExchange" }
Q: Microsoft Script Editor for Internet Explorer on XP Home? My understanding is that Microsoft Script Editor is the best debugging utility for IE. To enable debugging in IE6 on XP, I found these instructions: On Windows XP SP2+, the option has been split to two: Go to Tools->Internet Options…->Advanced->Disable Script Debugging (Internet Explorer) Go to Tools->Internet Options…->Advanced->Disable Script Debugging (Other) Unchecking the first will enable debugging for IE. Once enabled, I'm supposed to see a new menu under “View > Script debugger” to activate debugging. Unfortunately, unchecking both check boxes and restarting my computer does reveal this new "Script debugger" option. This worked on Windows 2000, but it fails for XP SP3. Any clues on how to install MSFT Script Editor for IE6 on XP SP3? Recommendations for alternatives to Script Editor for IE6? A: You can debug with visual web express. Instructions here edit: MS's site doesn't play nicely with older versions of IE. It's impossible to get the tabs to expand to get the links to the software. Use Chrome to browse the links above, or use this URL http://go.microsoft.com/?linkid=9730788 A: Thanks for the answer, redsquare. After much experimentation, I finally discovered how to install MSE on XP SP3: 1) Disable the checkboxes as described above. 2) Open MS Excel. Go to Tools -> Macro -> Microsoft Script Editor. Clicking this option will prompt installation of MSE. Install MSE. 3) Once MSE is accessible from Excel, open MSE. Go to Debugging -> Web Debugging. Clicking this option will prompt installation of MSE Web Debugging. Install it.enter code here Once Web Debugging is ready, restart IE, and voila! Under the View menu, you'll now see the Script Debugger option. Finally ...
{ "pile_set_name": "StackExchange" }
Q: Using C# Regular expressions how do i match the vertical bar as a literal? I'm writing a program in C# using Microsoft Visual Studio, i need the program to match the vertical bar, but when I try to escape it like this "\|" it gives me an unrecognized escape sequence error. What am I doing wrong? A: In C# string test = "\|"; Is going to fail because this is a C# string escape sequence, and no such escape exists. Because you are trying to include a backslash in the string, you need to escape the slash so the string actually contains a slash: string test = "\\|"; What will actually be stored in this string is \| A: The reason you get an unrecognized escape sequence is that backslash is used as an escape character in C# string literals as well as in regex. You have several choices to fix this: Use verbatim literals, i.e. @"\|", or Use a second escape inside a regular literal, i.e. "\\|", or Use a character class, i.e. [|] The third one is my personal favorite, because it does not require counting backslashes.
{ "pile_set_name": "StackExchange" }
Q: TFS Team Project Portal permissions I have added users to Contributor Group in Team Project, but they are not able access the Team Project Portal. What could be the problem? A: You have to manage permissions to TFS, Sharepoint and Reporting Services separately. This means that adding people to TFS groups does not automatically add them to Sharepoint and reporting services groups. Please check below MSDN library for information on how to add users to Share Point Portal: http://msdn.microsoft.com/en-us/library/bb558971.aspx You can also use TFS Administration tool, which provides the options to add users to TFS, Sharepoint and Reporting Services from single place.
{ "pile_set_name": "StackExchange" }
Q: List of functions references I'm using boost::function for making references to the functions. Can I make a list of references? For example: boost::function<bool (Entity &handle)> behaviorRef; And I need in a list of such pointers. For example: std::vector<behaviorRef> listPointers; Of course it's wrong code due to behaviorRef isn't a type. So the question is: how can I store a list of pointers for the function? A: typedef boost::function<bool (Entity&)> behaviorRef_type; std::vector<behaviorRef_type> listPointers;
{ "pile_set_name": "StackExchange" }
Q: Jquery UI, use custom or specific date format I have two datepickers input in my form using Jquery UI's Datepicker. I need help formatting the date into my own specific format. I declared two variables for each datepicker's ID like this .datepicker({ dateFormat: 'dd/mmm/yyyy' }).val();, but looks like i'm doing it wrong. var date2 = $('#datepicker2').datepicker({ dateFormat: 'dd/mmm/yyyy' }).val(); var date3 = $('#datepicker3').datepicker({ dateFormat: 'dd/mmm/yyyy' }).val(); $(function() { $("#datepicker2").datepicker(); }); $(function() { $("#datepicker3").datepicker(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> Input Data Date: <input type="text" class="form-control" name="p2" id="datepicker2"><br> Birth Date: <input type="text" class="form-control" name="p2" id="datepicker3"><br> When i choose a date, what i got is mm/dd/yyy. Can anyone help me, please? A: You are not mentioning what your specific format is You need to check formatDate Here is an example $(function() { $("#datepicker2").datepicker({ onSelect: function(dateText) { console.log("Selected date: " + dateText + "; input's current value: " + $.datepicker.formatDate("dd M yy", new Date(this.value))); } }); $("#datepicker3").datepicker({ dateFormat: 'dd-mm-yy', onSelect: function(dateText) { console.log("Selected birth date: " + dateText + "; input's current value: " + this.value); } }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> Input Data Date: <input type="text" class="form-control" name="p2" id="datepicker2"><br> Birth Date: <input type="text" class="form-control" name="p2" id="datepicker3"><br>
{ "pile_set_name": "StackExchange" }
Q: calling public function from another php I'm working on WordPress plugin where I have 2 php files. class.php has code as: class Plugin_Name { public function say_hello() { echo "Hello"; } } Now I want to call this say_hello() function from another welcome.php file. I tried $hello_function = new Plugin_Name(); $hello_function->say_hello(); But it doesn't work. Is there any way to call public function from another php ? A: You need to include the first function in the other file, that way the other file knows the code is there. At the top of welcome.php add require_once('/path/to/class.php'); $hello_function = new Plugin_Name(); $hello_function->say_hello();
{ "pile_set_name": "StackExchange" }
Q: Como criar, acessar e manipular arrays associativos? Estou usando GNU-Bash no meu terminal MingW (bash --version: GNU bash, version 4.4.12(1)-release (i686-pc-msys)). Estou precisando criar um dicionário de dados para verificar se uma nova chave foi encontrada e associar essa nova chave a um índice. Para isso, creio que a melhor solução seria um array associativo. Porém, não estou conseguindo fazer esse array funcionar! Para testes, estou atribuindo valores incrementais às chaves, uma chave por linha. Por exemplo, espero obter os seguintes pares de chave/valor para essa entrada: ./array_assoc_platonico.sh << EOL > bash > scripting > is > tought > as > bash > is > pretty > EOL bash:1 scripting:2 is:3 tought:4 as:5 pretty:6 A impressão não me importa, mas o conteúdo do meu array deveria ser algo assim. Meu script até o momento: #!/bin/bash NEXT_IDX=1 while read line; do if [ "x${chaves[$line]}" = "x" ]; then # então chave nova chaves[$line]=$NEXT_IDX NEXT_IDX=$(( NEXT_IDX + 1 )) echo "$line:${chaves[$line]}" fi done Entretanto, minha saída obtida está sendo: ./array_assoc_falho.sh << EOL > bash > scripting > is > tought > as > bash > is > pretty > EOL bash:1 Quando eu dou um declare -p chaves no final da leitura, obtenho o seguinte: declare -a chaves=([0]="1") Onde estou errando no uso do array associativo em bash? A: O correto é declare -A chaves, a variável "chaves" será tratada como uma matriz. #!/bin/bash declare -A chaves NEXT_IDX=1 while read line; do if [ "x${chaves[$line]}" = "x" ]; then # então chave nova chaves[$line]=$NEXT_IDX NEXT_IDX=$(( NEXT_IDX + 1 )) echo "$line:${chaves[$line]}" fi done Saída: bash:1 scripting:2 is:3 tought:4 as:5 pretty:6 Variáveis no Bash Ao informar o parâmetro -a você cria um array indexado, ou seja, uma variável contendo uma lista onde os índices são números. #!/bin/bash declare -a CARROS=("Gol" "Argo" "C3" "Saveiro") for ((I=0;I<3;I++)); do echo $I ${CARROS[I]}; done A saída sera: 0 Gol 1 Argo 2 C3 O parâmetro -A tem seu funcionamento igual ao array indexado, a diferença é em utilizar como chave uma string ao invés de índice numérico. O parâmetro -i define a variável como um número inteiro $ declare -i NUMERO=2018 $ echo ${NUMERO} 2018 $ NUMERO+=2 $ echo ${NUMERO} 2020 $ NUMERO="UM NOME QUALQUER" # IRÁ RETORNAR ZERO 0 Os parâmetros -l e -u servem para converter string em minusculas e maiúsculas. $ declare -l SITE="Pt.StaCkOverFlow.com" $ echo ${SITE} pt.stackoverflow.com $ declare -u SITE="pt.stackoverflow.com" $ echo ${SITE} PT.STACKOVERFLOW.COM O parâmetro -r torna a variável somente leitura. $ declare -r VAR="Minha variável" $ echo ${VAR} Minha variável $ VAR="Novo conteúdo" # FOI DECLARADA COMO LEITURA, RETORNARA ERRO ./teste.sh: line 5: VAR: a variável permite somente leitura O parâmetro -p serve para exibir os atributos e os valores de uma variável. $ declare -a VAR=("Corsa" "Gol" "Palio" "Uno") $ declare -p VAR declare -a VAR='([0]="Corsa" [1]="Gol" [2]="Palio" [3]="Uno")'
{ "pile_set_name": "StackExchange" }
Q: Is there another word for a sub-team specialized in a certain subject matter please? Is there another word I can use to name a sub-team specialized in a certain subject matter? A few of us within a leadership group are getting together across job functions to form a sub-team for Food Safety. Purpose of group is to update each other across related functions, agree then communicate to the clients to whom we consult. Thanks in advance! A: Although there's nothing wrong with either unit or committee per se, if sub-team has already been ruled out, than so must the larger team be ruled out—and team is synonymous with both unit and committee. I had been going to suggest task force, which is a group formed for a specific purpose, but a comment under the question clarified that the sub-team would be permanent—and task forces are normally disbanded when their jobs are done. (Although not commonly done, so it would be a little unusual, the term could be used on a more permanent basis if it was desired.) However, drawing from terminology used in technical and professional fields, I suggest the following: subject-matter expert (SME) From Wikipedia: A subject-matter expert (SME) is a person who is an authority in a particular area or topic … In engineering and technical fields, an SME is the one who is an authority in the design concept, calculations and performance of a system or process. In the scientific and academic fields subject matter experts are recruited to perform peer reviews, and are used as oversight personnel to review reports in the accounting and financial fields. A lawyer in an administrative agency may be designated an SME if he or she specializes in a particular field of law, such as tort, intellectual property rights, etc. A law firm may seek out and use an SME as an expert witness. Of note is that the person who wrote this article is pronouncing SME as if it were an initialism: "an s-m-e." However, in my professional line of work in the technology industry, everybody I know has always pronounced it as an acronym: "a smee." While SME can refer to an individual who is an expert in a field, it can also refer to a group of such people. So when, for example, somebody means to say, "Ask the group of experts on the design team," they can either say ask the design SMEs [people] or ask the design SME [group of experts]. At least in my experience, SME is often kept singular, whether we refer to an individual or a team. We can also say that somebody is part of a SME. It's a blurring of the definition that's understood from context. So, in the case of this question, you could say the same thing in a few ways, where its reference to a person or group is implied. As a group: Let's create a Food Safety SME. As inviduals: Let's create a team of Food Safety SMEs. Ambiguously (where it could refer to either a group or an individual): Let's use a Food Safety SME.
{ "pile_set_name": "StackExchange" }
Q: Cant find the mistake in code Hi people i have a small problem i cganged the sql database code and my activity code... Now the app crashes when i try to start the activity(1). I am giving you the sql database code too(2). And the text from logcat(3). (1): package com.peky.smartornot; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.TabHost; import android.widget.Toast; import android.widget.TabHost.TabSpec; import android.widget.TextView; public class POV1 extends Activity { Sql ulaz = new Sql(this); TextView joke4text; TextView joke3text; TextView joke2text; TextView joke1text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pov1); sve(); } public void sve() { // TODO Auto-generated method stub ulaz.open(); int joker1 = ulaz.procitaj(), joker2 = ulaz.procitaj2(), joker3 = ulaz .procitaj3(), joker4 = ulaz.procitaj4(); ulaz.close(); TabHost joker = (TabHost) findViewById(R.id.tabhost); joker.setup(); TabSpec izgled = joker.newTabSpec("tag1"); izgled.setContent(R.id.tab1); izgled.setIndicator("Joker 1"); joker.addTab(izgled); izgled = joker.newTabSpec("tag2"); izgled.setContent(R.id.tab2); izgled.setIndicator("Joker 2"); joker.addTab(izgled); izgled = joker.newTabSpec("tag3"); izgled.setContent(R.id.tab3); izgled.setIndicator("Joker 3"); joker.addTab(izgled); izgled = joker.newTabSpec("tag4"); izgled.setContent(R.id.tab4); izgled.setIndicator("Joker 4"); joker.addTab(izgled); joke1text = (TextView) findViewById(R.id.joker1text); joke1text.setText("You have " + joker1 + " jokers !"); joke2text = (TextView) findViewById(R.id.joker2text); joke2text.setText("You have " + joker2 + " jokers !"); joke3text = (TextView) findViewById(R.id.joker3text); joke3text.setText("You have " + joker3 + " jokers !"); joke4text = (TextView) findViewById(R.id.joker4text); joke4text.setText("You have " + joker4 + " jokers !"); } public void joker1(View view) { Button netocan = (Button) findViewById(R.id.button5); Button netocan2 = (Button) findViewById(R.id.button4); Button netocan3 = (Button) findViewById(R.id.button2); ulaz.open(); int joker1=ulaz.procitaj(),joker2,joker3,joker4; ulaz.close(); if (joker1 != 0) { if(netocan.getVisibility()==View.VISIBLE){ netocan.setVisibility(View.INVISIBLE); ulaz.open(); joker1=joker1-1; joker2=ulaz.procitaj2(); joker3=ulaz.procitaj3(); joker4=ulaz.procitaj4(); ulaz.spremijoker(joker1, joker2, joker3, joker4); ulaz.close(); joke1text = (TextView) findViewById(R.id.joker1text); joke1text.setText("You have " + joker1 + " jokers !"); }else if(netocan2.getVisibility()==View.VISIBLE){ netocan2.setVisibility(View.INVISIBLE); ulaz.open(); joker1=joker1-1; joker2=ulaz.procitaj2(); joker3=ulaz.procitaj3(); joker4=ulaz.procitaj4(); ulaz.spremijoker(joker1, joker2, joker3, joker4); ulaz.close(); joke1text = (TextView) findViewById(R.id.joker1text); joke1text.setText("You have " + joker1 + " jokers !"); }else if(netocan3.getVisibility()==View.VISIBLE){ netocan3.setVisibility(View.INVISIBLE); ulaz.open(); joker1=joker1-1; joker2=ulaz.procitaj2(); joker3=ulaz.procitaj3(); joker4=ulaz.procitaj4(); ulaz.spremijoker(joker1, joker2, joker3, joker4); ulaz.close(); joke1text = (TextView) findViewById(R.id.joker1text); joke1text.setText("You have " + joker1 + " jokers !"); }else{ Toast imasodgovor=Toast.makeText(getApplicationContext(), "You can not use more JOKERS1 on this question !", Toast.LENGTH_SHORT); imasodgovor.show(); } }else{ Toast nemasjokera=Toast.makeText(getApplicationContext(), "You dont have enought JOKERS1 !", Toast.LENGTH_SHORT); nemasjokera.show(); } } public void joker4(View view) { ulaz.open(); int joker1,joker2,joker3,joker4=ulaz.procitaj4(); ulaz.close(); Button netocan = (Button) findViewById(R.id.button5); Button netocan2 = (Button) findViewById(R.id.button4); Button netocan3 = (Button) findViewById(R.id.button2); if (joker4 != 0) { if(netocan.getVisibility()==View.VISIBLE || netocan2.getVisibility()==View.VISIBLE || netocan3.getVisibility()==View.VISIBLE){ netocan.setVisibility(View.INVISIBLE); netocan2.setVisibility(View.INVISIBLE); netocan3.setVisibility(View.INVISIBLE); ulaz.open(); joker1=ulaz.procitaj(); joker2=ulaz.procitaj2(); joker3=ulaz.procitaj3(); joker4=joker4 - 1;; ulaz.spremijoker(joker1, joker2, joker3, joker4); ulaz.close(); joke4text = (TextView) findViewById(R.id.joker4text); joke4text.setText("You have " + joker4 + " jokers !");}else{ Toast imasodgovor=Toast.makeText(getApplicationContext(), "You can not use more JOKERS4 on this question !", Toast.LENGTH_SHORT); imasodgovor.show(); } } else { Toast jokertext = Toast.makeText(getApplicationContext(), "Not enought JOKERS4", Toast.LENGTH_SHORT); jokertext.show(); } } public void joker2(View view){ } public void tocan(View view){ } public void netocanodgovor(View view) { } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.pov1, menu); return false; } } (2): package com.peky.smartornot; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class Sql { public static final String KEY_ROWID = "_id"; public static final String KEY_JOKER1 = "joker"; public static final String KEY_JOKER2 = "joker2"; public static final String KEY_JOKER3 = "joker3"; public static final String KEY_JOKER4 = "joker4"; private static final String DATABASE_NAME = "SQL"; private static final String DATABASE_TABLE = "peoples_table"; private static final int DATABASE_VERSION = 1; private DbHelper ourHelper; private final Context ourContext; private SQLiteDatabase ourDatabase; private static class DbHelper extends SQLiteOpenHelper { public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_JOKER1 + " INTEGER, " + KEY_JOKER2 + " INTEGER, " + KEY_JOKER3 + " INTEGER, " + KEY_JOKER4 + " INTEGER);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); onCreate(db); } } public Sql(Context c) { ourContext = c; } public Sql open() { ourHelper = new DbHelper(ourContext); ourDatabase = ourHelper.getWritableDatabase(); return this; } public void close() { ourHelper.close(); } public long spremijoker(int joker1, int joker2, int joker3, int joker4) { // TODO Auto-generated method stub ContentValues cv = new ContentValues(); cv.put(KEY_JOKER1, joker1); cv.put(KEY_JOKER2, joker2); cv.put(KEY_JOKER3, joker3); cv.put(KEY_JOKER4, joker4); return ourDatabase.insert(DATABASE_TABLE, null, cv); } public int procitaj() { // TODO Auto-generated method stub String[] columns = new String[] { KEY_ROWID, KEY_JOKER1 }; Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null); int citac = 0; int iJokerammount = c.getColumnIndex(KEY_JOKER1); c.moveToLast(); citac = c.getInt(iJokerammount); return citac; } public int procitaj2() { // TODO Auto-generated method stub // TODO Auto-generated method stub String[] columns = new String[] { KEY_ROWID, KEY_JOKER2 }; Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null); int citac = 0; int iJoker2 = c.getColumnIndex(KEY_JOKER2); c.moveToLast(); citac = c.getInt(iJoker2); return citac; } public int procitaj3() { // TODO Auto-generated method stub // TODO Auto-generated method stub String[] columns = new String[] { KEY_ROWID, KEY_JOKER3 }; Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null); int citac = 0; int iJoker3 = c.getColumnIndex(KEY_JOKER3); c.moveToLast(); citac = c.getInt(iJoker3); return citac; } public int procitaj4() { // TODO Auto-generated method stub // TODO Auto-generated method stub String[] columns = new String[] { KEY_ROWID, KEY_JOKER4 }; Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null); int citac = 0; int iJoker4 = c.getColumnIndex(KEY_JOKER4); c.moveToLast(); citac = c.getInt(iJoker4); return citac; } } (3): 03-16 19:32:11.580: E/AndroidRuntime(26569): FATAL EXCEPTION: main 03-16 19:32:11.580: E/AndroidRuntime(26569): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.peky.smartornot/com.peky.smartornot.POV1}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0 03-16 19:32:11.580: E/AndroidRuntime(26569): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970) A: Your error says it all: CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0 You are attempting to access an empty list of something with an element index of -1. -1 is never a valid array index in Java, so you have two problems: Why is the list empty, if that is indeed not wanted? What is causing the incorrect index value of -1? Since android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970) is where the problem is being caused, that is where you need to look. What in your code is calling it? Since performLaunchActivity is nowhere in your posted code (nor is your main function), and since your stack trace is not more thorough, we'll need more information before we can help you further.
{ "pile_set_name": "StackExchange" }
Q: rails should i push schema.rb file for new created migrations I am working on rails 4 application and I am working with 4 more other developers. We all can generate the migration and create tables. We maintain our code on git repo. So while creating a new migration should we push our schema.rb file ti git repo. OR I need to write it in gitignore file? Thanks. A: You need not have to push the schema.rb file. When you run the migrations and other stuffs in the server the schema automatically get updated. Even if u push the schema.rb file no problem happens.
{ "pile_set_name": "StackExchange" }
Q: (java/math) how to find quotient in mod? This may be a rather simple problem. I'll show an example. I have A and B (take it as client and server set-up). A does the following (2^10) mod 23 = 12. It then sends the value 12 over to B Now, B has the equation 12 = (2^x) mod 23. (It has the modulus and the base value). How would I find the value 10? I tried inverse mod, but that seems to work only for a power of -1. Google doesn't seem to help much either. Just the math help would be great, but if there is a Java function for it, it would be even better. A: You can sometimes find the solution by trying with the first values and see what happens : public static void main(String[] args) { for(int i = 0; i< 100; i++) { System.out.println("" + i +" : " + (int)Math.pow(2, i) % 23); } } Here is the result : 0 : 1 1 : 2 2 : 4 3 : 8 4 : 16 5 : 9 6 : 18 7 : 13 8 : 3 9 : 6 10 : 12 11 : 1 12 : 2 13 : 4 14 : 8 15 : 16 16 : 9 17 : 18 18 : 13 19 : 3 20 : 6 21 : 12 22 : 1 23 : 2 24 : 4 25 : 8 26 : 16 27 : 9 28 : 18 29 : 13 30 : 3 31 : 5 32 : 5 33 : 5 I cut the output but for each value after 33, the result will be 5, because of some overflows. But you can see that there is a loop in the results : 1 2 4 8 16 9 18 13 3 6 12. This is explained because of this mathematical relationship : (2^(n+1)) mod 23 = ((2 ^ n) mod 23) * 2 mod 23 (in english, multiply the previous result by 2 and apply a mod 23 if necessary) So when n = 10, the result is 12 when n = 11, the result is 12 * 2 mod 23 = 24 mod 23 = 1 and there you go for a new cycle 1, 2, 4 etc Hence the answer is that eihter you find the corresponding value in the first 10 tries or you will never find it. Trying to find a value of 5 or 7 will end in an infinite loop.
{ "pile_set_name": "StackExchange" }
Q: Getting information on a JS constructed button on click Is it possible to get information, such as the id, value, of a button created by a javascript loop? For example, the following code, which creates a button for each line in a table formed by an array of objects? var table = document.createElement("TABLE"); table.setAttribute("id", "tableOfArray"); var array = [ (a large array of objects here) ]; for (var i = 0; i < array.length; i++) { row = table.insertRow(i); cell1 = row.insertCell(0); cell2 = row.insertCell(1); cell3 = row.insertCell(2); cell4 = row.insertCell(3); cell5 = row.insertCell(4); cell6 = row.insertCell(5); cell1.innerHTML = i + 1; //for numbering the table cell2.innerHTML = array[i].property1; cell3.innerHTML = array[i].property2; cell4.innerHTML = array[i].property3; cell5.innerHTML = array[i].property4; var button = document.createElement("BUTTON"); var buttonText = document.createTextNode("Remove Line"); button.appendChild(buttonText); button.setAttribute("id", String(i)); button.setAttribute("value", String(i)); button.setAttribute("onClick", "remove()"); cell6.appendChild(button); } function remove() { ?? //gets the value of the button that was pressed var buttonValue = ??; //assigns the value of button to the variable arrayTable = document.getElementById("tableOfArray"); table.deleteRow(buttonValue); } Is there a method that can be used to get the id or value of the button in order to perform the remove action? A: you can pass the current context by passing this button.setAttribute("onClick", "remove(this.id)"); function remove(id){ var _id=id;// id of the button; } Else you can use the event object function remove(event){ var _target = event.target; var _getId = _target.id; var _getParentTD = _target.parentElement; // will give the td which contain button var _getParentTR = _target.parentElement.parentElement; // will return tr }
{ "pile_set_name": "StackExchange" }
Q: Config test failed when restarting Apache 2 ServerAdmin [email protected] ServerName creansys.com ServerAlias www.creansys.com DocumentRoot /var/www/creansys.com/public_html <Directory / > Options FollowSymLinks Allow Override All </Directory> <Directory /var/www/> Options Indexes FollowSymLinks MultiViews Allow Override All Order Allow,Deny allow From all </Directory> When i tried to restart apache i got following error Syntax error allow and deny must be followed by 'from'. Action 'configtest' failed. can anybody help me with a solution A: You have some typos in your configuration: Use <Directory /> Options FollowSymLinks AllowOverride All </Directory> and <Directory /var/www/> Options Indexes FollowSymLinks MultiViews AllowOverride all Order allow,deny Allow from all </Directory> After that you should see % apachectl configtest Syntax OK Why? Because I've tested it on my system, especially for you. ;)
{ "pile_set_name": "StackExchange" }
Q: Making an object disappear when no longer visible on screen I am making a simple ApplePicker prototype in Unity and am having trouble with destroying objects. In my script attached to my basket object I want to put this if statement in my Update() function which says that if an apple reaches a certain y value (i.e falls out of view), to destroy one of the baskets. if(...) { Destroy(this.gameObject); } but I don't know what to put as a condition. can someone help me out? In case it is needed, the apple object has the tag "Apple" A: The transform variable which is a type of Transform is used to access the position, rotation and scale of any GameObject in the scene. You would have to use if (transform.position.y < someValue) to see if the position is less than any value or if (transform.position.y > someValue) to check if it is more than the value. void Update() { float someValue = 10; if (transform.position.y < someValue) { Destroy(this.gameObject); } } For rotation and scale, use transform.localEulerAngles and transform.localScale respectively. Am I able to check the position of an apple from a script attached to the basket object, because I need to check the position of the apple not the basket It's the-same thing. Find apple from your other script, store the reference then perform the-same action above. GameObject apple; void Start() { //Find apple by tag apple = GameObject.FindWithTag("Apple"); } void Update() { float someValue = 10; if (apple.transform.position.y < someValue) { Destroy(apple); } } There is really a better way to check if object is no longer before destroying it. This removes the need of hard-coding the someValue value. Just check for the screen size. GameObject apple; void Start() { //Find apple bt tag apple = GameObject.FindWithTag("Apple"); } void Update() { if (!IsVisibleOnScreen(apple)) { Destroy(apple); } } private bool IsVisibleOnScreen(GameObject target) { Camera mainCam = Camera.main; Vector3 targetScreenPoint = mainCam.WorldToScreenPoint(target.GetComponent<Renderer>().bounds.center); if ((targetScreenPoint.x < 0) || (targetScreenPoint.x > Screen.width) || (targetScreenPoint.y < 0) || (targetScreenPoint.y > Screen.height)) { return false; } if (targetScreenPoint.z < 0) { return false; } return true; }
{ "pile_set_name": "StackExchange" }
Q: jQuery - Trying to filter divs on keyup Revised Code jQuery(function($) { $("#filter").keyup(function () { var filter = $(this).val(), count = 0; $(".filtered h2").each(function () { if ($(this).text().search(new RegExp(filter, "i")) != -1) { $(this).parent().addClass("hidden"); } else { $(this).parent().removeClass("hidden"); count++; } $("#filter-count").text(count); }); }); }); I have a number of divs that are listed and I want to be able to add an input field that will allow a user to start typing and the divs are filtered according to each divs h2 tag. I'm trying the code below, but it's not filtering. It's not throwing up any errors either, so I'm not sure what to do at this point... Here's the html markup: <input id="filter" name="filter" size="40"/> <div class="filtered"> <div class="archive-row clearfix"> <label>Creator: </label><h2 class="hidden">Alchemy</h2> <label>Title: </label> <p>Cras velit eros, eleifend ut viverra </p> <label>Summary: </label><p>Etiam lobortis, risus a dignissim tempor, neque sapien lobortis mi, quis semper sapien nisi dictum nisi. Integer neque neque</p> </div> <div class="archive-row clearfix"> <label>Creator: </label><h2 class="hidden">Mathematics</h2> <label>Title: </label> <p>Cras velit eros, eleifend ut viverra </p> <label>Summary: </label><p>Etiam lobortis, risus a dignissim tempor, neque sapien lobortis mi, quis semper sapien nisi dictum nisi. Integer neque neque</p> </div> <div class="archive-row clearfix"> <label>Creator: </label><h2 class="hidden">English</h2> <label>Title: </label> <p>Cras velit eros, eleifend ut viverra </p> <label>Summary: </label><p>Etiam lobortis, risus a dignissim tempor, neque sapien lobortis mi, quis semper sapien nisi dictum nisi. Integer neque neque</p> </div> </div> Here's the jquery... $(document).ready(function() { $("#filter").keyup(function () { var filter = $(this).val(), count = 0; $(".filtered h2").each(function () { if ($(this).text().search(new RegExp(filter, "i")) < 0) { $(this).addClass("hidden"); } else { $(this).removeClass("hidden"); count++; } }); $("#filter-count").text(count); }); }); A: <input id="filter" name="filter" size="40"/> <div class="filtered"> <div class="archive-row clearfix"> <label>Creator: </label><h2 >Alchemy</h2> <label>Title: </label> <p>Cras velit eros, eleifend ut viverra </p> <label>Summary: </label><p>Etiam lobortis, risus a dignissim tempor, neque sapien lobortis mi, quis semper sapien nisi dictum nisi. Integer neque neque</p> </div> <div class="archive-row clearfix"> <label>Creator: </label><h2 >Mathematics</h2> <label>Title: </label> <p>Cras velit eros, eleifend ut viverra </p> <label>Summary: </label><p>Etiam lobortis, risus a dignissim tempor, neque sapien lobortis mi, quis semper sapien nisi dictum nisi. Integer neque neque</p> </div> <div class="archive-row clearfix"> <label>Creator: </label><h2>English</h2> <label>Title: </label> <p>Cras velit eros, eleifend ut viverra </p> <label>Summary: </label><p>Etiam lobortis, risus a dignissim tempor, neque sapien lobortis mi, quis semper sapien nisi dictum nisi. Integer neque neque</p> </div> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <script> $(document).ready(function() { $("#filter").keyup(function () { var filter = $(this).val(), count = 0; $(".filtered h2").each(function () { var parent = $(this).parent(), length = $(this).text().length>0; if ( length && $(this).text().search(new RegExp(filter, "i")) < 0) { parent.hide(); } else { parent.show(); count++; } }); $("#filter-count").text(count); }); }); </script> <div id="filter-count"></div>
{ "pile_set_name": "StackExchange" }
Q: Tags are not prefixed in the on the MSE question We had a brief conversation regarding tags at the <title> tag of our SE questions in this question. According to our SE tagging system, most tags will automatically be prefixed into the title of the questions unless it's already in the title somewhere. Note that the system automatically prefixes the title with the most common tag (unless it's already in the title somewhere) to help search engines find it more easily. Ref: https://meta.stackexchange.com/a/130208/245772 last line of this answer But I didn't find any tag for this question at the <title></title> markup of the HTML page. Screenshot: A: Ref: https://meta.stackexchange.com/a/130208/245772 last line of this answer You have taken that a bit out of context. The first sentence in that answer states: Stack Overflow has an extensive tag system... It is discussing Stack Overflow specifically, which is a main site, and (as Shadow Wizard states) a tag being automatically prefixed into the title only applies on main sites, not Metas. So the reason you did not see this occur in a title here on MSE is because it's a Meta (as per the name - meta.stackexchange.com) ;)
{ "pile_set_name": "StackExchange" }
Q: How to detect when a shell is owned by a remote SSH session? My question is similar to this one, but I'm looking for something slightly different. I have a notebook PC that I use to access Linux machines on a network in two different scenarios: I have a direct, wired connection to the network. I have an indirect connection to the network. There is a gateway machine on the network exposed to the Internet, which I can use to establish SSH tunnels to hosts on the network. This is obviously a much slower, higher-latency connection. My home directory is network-accessible from all machines, so they share a copy of my .bashrc. I would like to add functionality to .bashrc to detect which of the two scenarios I'm in and act accordingly (technically, there would be three scenarios, where the third is that I'm logging into my local machine, but that should be easily handled). I would like to do things like: alias ssh ssh -X when I'm on the local network, but I don't want to use X forwarding over the Internet. export EDITOR=gvim when I'm on the local network, but export EDITOR=vim when I'm remote. And so on. Based on the previous answer, it looks like I should be able to accomplish something like this by checking the contents of SSH_CLIENT (if it exists) and seeing if the client IP address matches one of the network adapters on my local machine. I thought I would see if there is a slicker or more robust way to accomplish this. A: To detect an SSH session, use $SSH_CLIENT. To distinguish between local and remote sessions, there are two possible approaches: client-side or server-side. On the server side, compare $SSH_CLIENT with the local IP address or routing table; this'll usually tell you whether the connection is from the LAN. On the client side, you may want to put ForwardX11 settings in your ~/.ssh/config: set it to yes for LAN hosts and to no for WAN hosts. This implies having a different ~/.ssh/config on different sites; that's what I do, and I generate mine with a shell script. If X11 forwarding is on for LAN connections and off for WAN connections, then you can set your favorite editor to take $DISPLAY into account. The server-side settings would normally go into your .profile (or .bash_profile if your login shell is bash and you use .bash_profile, or .zprofile if your login shell is zsh). case ${SSH_CLIENT%% *}//$(/sbin/ifconfig | sed -n 's/^.* addr:\([0-9][0-9.]*\) .*/\1/p' | tr '\n' /)/ in "") :;;# local session 10.42.*/10.42.*) :;; # LAN session 1.2.3.*/1.2.3.*) :;; # LAN session *) unset DISPLAY;; # WAN session esac export EDITOR=vim if [ -n "$DISPLAY" ] && type gvim >/dev/null 2>/dev/null; then EDITOR=gvim fi export VISUAL="$EDITOR"
{ "pile_set_name": "StackExchange" }
Q: Solving $\dfrac{\partial{u}}{\partial{t}} + u = \dfrac{\partial^2{u}}{\partial{x}^2} + 4\dfrac{\partial{u}}{\partial{x}}$ Using Separation. Proceeding as follows, use the method of separation of variables to solve $\dfrac{\partial{u}}{\partial{t}} + u = \dfrac{\partial^2{u}}{\partial{x}^2} + 4\dfrac{\partial{u}}{\partial{x}}$ subject to $u(0, t) = 0$ and $u(1, t) = 0$ for $t > 0$ and $u(x, 0) = 1$ for $0 < x < 1$. (a) Try $u(x, t) = X(x)T(t)$ to get a pair of ordinary differential equations. There is a discrepancy between my solution and that of the instructor. The instructor's solution is as follows: $X(x)T'(t) + X(x)T(t) = X''(x)T(t) + 4X'(x)T(t)$ $\implies \dfrac{X'' + 4X'}{X} = \dfrac{T' + T}{T} = -\lambda$ $\therefore X'' + 4X' + \lambda X = 0$ and $T' + (1 + \lambda)T = 0$. My solution is as follows: $X(x)T'(t) + X(x)T(t) = X''(x)T(t) + 4X'(x)T(t)$ $\implies XT' + XT = X''T + 4X'T$ $\implies XT' = X''T + 4X'T - XT$ $\implies XT' = T(X'' 4X' - X)$ $\implies \dfrac{T'}{T} = \dfrac{X'' + 4X' - X}{X}$ $\therefore \dfrac{T'}{T} = - \lambda = \dfrac{X'' + 4X' - X}{X}$ $\therefore$ The two ordinary differential equations are $T' + \lambda T = 0$ and $X'' + 4X' - X + \lambda X = 0 \implies X'' + 4X' + X(\lambda - 1) = 0$ I was wondering if people could please take the time to clarify as to whether both solutions are correct or I have made an error? A: Your solution is equivalent to the instructor's solution. Only the symbols chosen for the constants $\lambda$ are different, but related : $$\lambda_{You}=\lambda_{Instructor}+1$$ It doesn't matter since $\lambda$ is arbitrary.
{ "pile_set_name": "StackExchange" }