source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0008263393.txt" ]
Q: Timestamp generated by two threads I have two thread in my code. One thread is a generator which creates messages. A timestamp is generated before a message is transmitted. The other thread is a receiver which accepts replies from multiple clients. A timestamp is created for each reply. Two threads are running at the same time. I find the timestamp generated by the receivers is earlier than the timestamp generated by the generator. The correct order should be the timestamp for the receiver is later than the timestamp for the generator. If I give a high priority for the generator thread, this problem does not occcur. But this can also slow down the performance. Is there other way to guarantee the correct order and less effection on the performance? Thanks. A: Based on the comment thread in the question, this is likely the effect of the optimizer. This is really a problem with the design more than anything else - it assumes that the clocks between the producer and consumer are shared or tightly synchronized. This assumption seems reasonable until you need to distribute the processing between more than one computer. Clocks are rarely (if ever) tightly synchronized between different computers. The common algorithm for synchronizing computers is the Network Time Protocol. You can achieve very close to millisecond synchronization on the local area network but even that is difficult. There are two solutions to this problem that come to mind. The first is to have the producer's timestamp is passed through the client and into the receiver. If the receiver receives a timestamp that is earlier than it's notion of the current time, then it simply resets the timestamp to the current time. This type of normalization will allow assumptions about time being a monotonically increasing sequence continue to hold. The other solution is to disable optimization and hope that the problem goes away. As you might expect, your mileage may vary considerably with this solution. Depending on the problem that you are trying to solve you may be able to provide your own synchronized clock between the different threads. Use an atomically incrementing number instead of the wall time. java.util.concurrent.atomic.AtomicInteger or one of its relatives can be used to provide a single number that is incremented every time that a message is generated. This allows the producer and receiver to have a shared value to use as a clock of sorts. In any case, clocks are really hard to use correctly especially for synchronization purposes. If you can find some way to remove assumptions about time from distributed systems, your architectures and solutions will be more resilient and more deterministic.
[ "stackoverflow", "0003560641.txt" ]
Q: Running an Rscript on Mac OS X I have a BATCH File script on a Windows machine that consists of the following line: c:\R\bin\Rscript.exe "c:\Users\user\Documents\Shares.R" I want to do the same thing but using Mac OS X at the moment I am using Automator => Run Shell Script and the following line: open "/usr/bin/Rscript" "/Users/usr/Documents/Shares.R" It opens R, finds the file and displays the R code. I want the R code contained in the script to run (like it does in Windows). Any ideas? Anthony. A: This will be enough : /usr/bin/Rscript "/Users/usr/Documents/Shares.R"
[ "math.stackexchange", "0000056116.txt" ]
Q: $A\in M_n(\mathbb{R})$ symmetric matrix , $A-\lambda I$ is Positive-definite matrix- prove: $\det A\geq a^n $ Let $a>1$ and $A\in M_n(\mathbb{R})$ symmetric matrix such that $A-\lambda I$ is Positive-definite matrix (All eigenvalues $> 0$) for every $\lambda <a$. I need to prove that $\det A\geq a^n $. First, I'm not sure what does it mean that $A-\lambda I$ is positive definite for every $\lambda <a$. It's whether $A>0$ and all eigenvalues are bigger than $0$ or it's not. Then, If it's symmetric I can diagonalize it, I'm not sure what to do... Thanks! A: $A-\lambda I$ is positive definite for every $\lambda<a$ means for all $\epsilon>0$, $A-(a-\epsilon) I$ is positive definite. That means, each eigenvalue of $A$ is larger than $a-\epsilon$, thus their product $\det A\ge \prod (a-\epsilon)$ ... let $\epsilon$ goes to zero, you get what you want.
[ "stackoverflow", "0021448808.txt" ]
Q: How to move all images into one group in xcode All images and header files are looking very confusing. So i want to separate all images and other files into different groups. Anyone please help me A: To organize your files on disk, simply make the folders you want to make in the Finder and drag the files to them. To do this, open the folder containing your .xcodeproj file in the Finder. Use Cmd-Shift-N to create a new folder or choose "New Folder" from the "File" menu. You'll be prompted to give the folder a name. You'll probably want to name it something like "Images" or "Headers". Once the folder is created, you can simply click on an image file and drag it to the "Images" folder (or whatever you named it). Repeat the process for any files you want to move. Once you've done the above, the files may display as red in Xcode's Project Navigator. If that's the case, you need to select the file in Xcode's Project Navigator and show the "Utilities" pane (the right-most button in the toolbar opens and closes the Utilities pane). There are 2 tabs in the Utilities pane - the File Inspector and Quick Help. Click on the File Inspector. It should display the name of your file, the type, and the location. Next to the "Location" is an icon of a folder. Click on the folder and you'll be presented with a file navigation dialog. Navigate to the new location of the file and select it. Click the "Choose" button and the file will be re-connected in Xcode. You may need to repeat the process for any files you moved into new folders.
[ "stackoverflow", "0015870763.txt" ]
Q: how to make a javascript not apply pagewide in Rails? I am trying to apply a thirdparty script on my website. Here's the format below <script type="text/javascript" src="http://thirdpartysite.com/front.asp?id=xxxx"></script> In my Rails3 app, I want this script to be only applied on certain images contained within posts (only images/posts where value copyright==true). So I tried using it in this code: <% if post.copyright == true %> <script type="text/javascript" src="http://thirdpartysite.com/front.asp?id=xxxx"></script> <% else %> <% end %> Unfortunately, this javascript affects ALL of the images on the pages. There are multiple posts per page and I am trying to individualize this javascript into each post. Any ideas how I can get this to work? Can I get this to work using <div id ="%=post.id" %>, CSS selectors, or some way? (not really sure) I do not have access to the source code of the javascript as it's from a third party site. I'm not able to customize it. All I have is this script code that they gave me and I thought that I would be able to apply it only to certain images/posts on my website. A: The script will execute in the context of the entire document. It sounds like you're listing a bunch of posts on the page and including the same script multiple times depending on the logic; you would typically include the script just once. You'll have to inspect the third party code (or their documentation) to see how it is selecting the images to manipulate. It may reveal a way to add a class to images or parent elements that allow you to filter out images you don't want manipulated.
[ "stackoverflow", "0028981666.txt" ]
Q: Enabling mp4/mpeg4/avc support for Qt5 WebEngine on Linux i installed Qt 5.4.1 x64 on LUbuntu and created an app which uses the new QtWebEngine. I`m trying to display a html5 page with that component which is using the tag. All works fine except if I try to playback a mp4 video. The video area remains black. It works if I use other video types like webm/ogg as source. I know this is due to license restrictions, so that mp4 is deactivated by default in Ubuntu/Linux for Qt. What is needed in Qt to activate it to allow mp4 playback and on what do I have pay attention in case of license terms (I read that statically linking the library is allowed?) ? I`ve already tried to copy over the x64 distribution of libffmpegsuo.so which is included in Chrome (2,2Mb) over to the Qt directory to /plugins/webengine/ and replaced that one that was already there (1,1 Mb) but it had no effect. In Chrome playback works fine btw. If you need more details like paths etc. please tell me. Thanks ! A: You can explicitly enable proprietary codecs (H264, MP3) when compiling Qt WebEngine: In /path-to-qt-src-dir/qtwebengine execute: qmake WEBENGINE_CONFIG+=use_proprietary_codecs You should be able to see in the output that H264 codec is enabled, which is not the default configuration.
[ "stackoverflow", "0053938778.txt" ]
Q: How do I simply generate a numbered list from a data frame? I am trying to construct a code chunk that, after inputting data from an Excel sheet, constructs a data frame of "refereed publications" from within the past five years (the initial data are filtered through a couple of subset commands on lines 1 and 2). I've pasted some of the code below that I think helps explain what I'm trying to do and how I am trying to do it. The third line pubsfive <- within(pubsfive, rwnum <- 1) is to initialize a new column within the pubsfive data frame. Lastly, I'm trying to run a for loop in an attempt to number each line by its row name (1 through 10, in this case). I don't exactly know what I'm doing with the for loop, but I'm trying to code for each row in the new column called, rwnum that simply outputs the row number. I should be able to concatenate all of the columns and then pass the object to kable to then print a nice 5-year publications list. This probably isn't the most eloquent code, so I am open to any clarifying questions or tips. pubsfive <- subset(pubs, pubs$Contribution == "Refereed Publications") pubsfive<- subset(pubsfive, pubsfive$year >= 2014, select = c(Authors, year, Title)) pubsfive <- within(pubsfive, rwnum <- 1) pubsfive <- for (i in 1:nrow(pubsfive)) {within(pubsfive, rwnum <- rownames(pubsfive)[i])} A: I'm not sure what's wrong with this: pubsfive <- subset(pubs, Contribution == "Refereed Publications" & year > 2014, select = c(Authors, year, Title)) pubsfive$rwnum <- rownames(pubsfive) The first line is a slightly more compact way of doing your first two lines, the third assigns a vector to the new column rwnum ... if you want the row numbers first you might prefer pubsfive <- data.frame(rwname=rownames(pubsfive), pubsfive) It's not clear to me whether you want the row names or seq(nrow(pubsfive)) ...
[ "stackoverflow", "0028692044.txt" ]
Q: Mobile - Codename - How can it be faster than native language? Context : Starting to write a mobile application for android and ios. Looking at many alternatives. Can't stand the html5/webview thing. Most of the times it is sluggish. I tried many demo apps (phonegap/steroid..) and didn't feel at home. Not smooth enough. More, some games are coming : so no way. I want a NATIVE development. In itself, objective-c is not the problem. But if I can create the app with only one development, with a language that is easy to code in (java), that sounds nice. Question : CodenameOne claims greater performance than objective-c via their java vm. Maybe they are using the C api, but this api is mostly obj-c now. Do some devs or even the creators can tell me if I really don't have to code in the native iOS language (obj-c) and get better results through a java vm? it seems odd to me. A: A quote right from the page you have linked to: A small disclaimer is that the Objective-C benchmark is a bit heavy on the method/message calls which biases the benchmark in our favor. Method invocations in Codename One are naturally much faster than the equivalent Objective-C code due to the semantics of that language. Doesn't that explain exactly what you have asked? Objective-C has an architecture due to which dynamic dispatch cannot be optimized, whereas Java's architecture allows for things like the monomorphic call site and even full method inlining. A benchmark which heavily focuses on exactly that aspect will skew the results in favor of the JVM, but the performance of actual apps is almost never dominated by method dispatch overhead.
[ "stackoverflow", "0004193113.txt" ]
Q: jqGrid tree grid with pager How do we make a tree grid with pager using jqGrid? I have checked and try the demos, but it didn't show any pager, even though there is a pager div in the code How do create the pager ? A: Tree grid has some limitations which are documented: Pager functionality currently disabled for treeGrid In other place of the documentation you can read almost the same: Since jqGrid currently does not support paging, when we have a treegrid the pager elements are disabled automatically. A: I got pagination to work by modifying the setTreeGrid function. I commented out the following line: $t.p.pgbuttons = false;$t.p.pginput = false; The buttons then appeared and the requests were going back to the server to request the information. Now for this I was loading the entire tree to a local variable then using setJSONData to load the data into the tree. It functions the way I would expect it to but I haven't thoroughly tested it. For RowList $t.p.multiselect = false;$t.p.rowList = [10,15,20,30];
[ "stackoverflow", "0031531726.txt" ]
Q: Android Json Image parsing error i have parsed json data and set to list view . When i click on list view object(image) it is showing error. What i should do. android.content.ContextWrapper.getCacheDir(ContextWrapper.java:208) A: If your just beginning with Xamarin then a WebClient should do the trick, it's really straight forward. private void SendSomeData (string url) { WebClient client = new WebClient(); //POST variables NameValueCollection parameters = new NameValueCollection(); parameters.Add("Key1", "Value1"); parameters.Add("Key2", "Value2"); //register a callback client.UploadValuesCompleted += (object sender, UploadValuesCompletedEventArgs e) => { if (e.Result != null) { //you'll need to download and reference Json.Net string jsonData = System.Text.Encoding.Default.GetString(e.Result); JsonConvert.DeserializeObject<MyCustomClass>(jsonData); } }; //Don't forget to call it :) client.UploadValuesAsync(new Uri(url), parameters); } Hope this helps, if you're looking for something more modern look into HttpClient, you may have to familiarize yourself with asynchronous programming with C# however.
[ "stackoverflow", "0018275289.txt" ]
Q: listview items are not shown I have a listview in C# , I simply add this to it, listView1.Items.Add("asdasdasd"); , but the only thing shown is a listview without any item ( but when I debug it, it is shown that listview HAS an item) I have no idea why it is not shown. A: I guess that your ListView has no columns set or the width of first column is set to zero. Try adding a column to the list (you can do it via property browser).
[ "stackoverflow", "0030947928.txt" ]
Q: Python: 'q)+' is not recognized as an internal or external command Python newbie here. I have a program named zeroOrMore.py It reads a regular expression (regex) from stdin. I invoke the program like this: python zeroOrMode.py (ab)*(p|q)+ That results in this error message: 'q)+' is not recognized as an internal or external command, operable program or batch file. I discovered that if I enclose the regex in double quotes: python zeroOrMode.py "(ab)*(p|q)+" then there is no error. Is there a way to accomplish this without wrapping the regex in double quotes? Here's how my program inputs the regex: regex = sys.argv[1] A: This isn't Python; it's CMD. The regex you're giving to Python is being interpreted by the command prompt first. The pipe (|) is the batch command for piping input to the following program. Basically, CMD is reading the command line like so: python zeroOrMode.py (ab)*(p | q)+ It's trying to take the result of running zeroOrMode.py (I think you meant more?) with (ab)*(p and piping the output to the (nonexistent) program q)+. There isn't really much of a solution to this, unfortunately. You could always escape the pipe like so: python zeroOrMode.py (ab)*(p^|q)+ The caret (^) will cause any special meanings the next character has to be ignored.
[ "stackoverflow", "0000690330.txt" ]
Q: does this switch statement smell bad? Switch(some case) { case 1: // compute something ... return something; break; case 2: // compute something ... return something; break; /* some more cases ... */ case X: // compute something ... return something; break; default: // do something return something; break; } In my opinion: Assuming this switch statement is justifiable, the return and break just doesnt look right or feel right. The break is obviously redundant, but is omission poor style (or is this poor style to begin with?) ? I personally dont do this, but there is some of this in the codebase at work. And no, im not going to be self-righteous and correct the codebase. A: No, omission is not poor style - inclusion is poor style. Those are unreachable statements. Get rid of them. I like the fact that the cases return directly instead of setting a local variable and then returning just at the bottom - it means that it's incredibly clear when you're reading the code that it does just need to return, and that's all. Side-note in terms of switching in the first place: As for whether using a switch statement is the right thing to do here, it really depends on other things. Would it make sense to use a polymorphic type instead? If you're in Java, could you use a smart enum? (You can mimic these in C#, but there isn't as much support.) I'd say this should at least prompt considering different designs - but it may well be the simplest way to do what you want. A: The C# Compiler gives a warning if you do this saying that the break is unreachable code. So in my book it is bad form to have both return and break. A: In my opinion, I would omit the 'break' keyword. I personally think it helps remind people that 'Execution has ended! Nothing more to see here!'.
[ "magento.stackexchange", "0000113059.txt" ]
Q: Where do I find magento 2 cart buttons action? I'm using magento 2 , and I need to find the cart close button and go to checkout button actions , and edit it , but I can't find the right files for that, does anyone knows where to find them ? A: Go to file path, vendor/magento/module-checkout/view/frontend/web/js/view/minicart.js check below part for close button html like, <button type="button" id="btn-minicart-close" class="action close" data-action="close" data-bind="attr: { title: $t('Close') }" title="Close"> <span><!-- ko i18n: 'Close' --><span>Close</span><!-- /ko --></span> </button> For close button html in minicart above display we can find data-action="close" from js file. closeSidebar: function() { var minicart = $('[data-block="minicart"]'); minicart.on('click', '[data-action="close"]', function(event) { event.stopPropagation(); minicart.find('[data-role="dropdownDialog"]').dropdownDialog("close"); }); return true; } Here list of url for checkout, update button, login url, remove button "url": { "checkout": window.checkout.checkoutUrl, "update": window.checkout.updateItemQtyUrl, "remove": window.checkout.removeItemUrl, "loginUrl": window.checkout.customerLoginUrl, "isRedirectRequired": window.checkout.isRedirectRequired }, "button": { "checkout": "#top-cart-btn-checkout", "remove": "#mini-cart a.action.delete", "close": "#btn-minicart-close" }
[ "music.stackexchange", "0000056254.txt" ]
Q: What is stopping me from Singing? I can sing well (well I think so). It's just the fact that something's a bit off in my voice, as if there's something blocking my singing voice. I've trained on a 6-week course and I've seen a lot of changes in my voice, but I can't explain whats happening. Anyone know? A: Hang in there, @Josh. Nobody has ever improved by quitting. Just keep at it. In the end you may have to relearn some things if your voice changes are permanent, but that will take practice, as I'm sure you know. May I please share something personal that is similar? I am dealing with a falsetto that has dropped by one single full note, and it bugs the heck out of me. I can project well until I get to that note that used to work but then I have to switch to what is essentially a humming voice. Very frustrating. I am finding that more practice hasn't changed the projection issue up there, so am trying to figure out how to deal with it. But yet I keep practicing. So, don't give up is the moral to that story. It might also be advisable to get a medical opinion.
[ "stackoverflow", "0013171561.txt" ]
Q: TCL : find and remove all characters in a string from the first occurrence of a character in a string I am a newbie in TCL and in need of a TCL method / utility / code which can find and remove all characters (including itself) in a string from its first occurrence in a string. I have a string like below: Func::set()->method(); In the above string I need to find first occurrence of '(' and remove all it and after that so that the resultant string would be just: Func::set A: You can do it with a regular expression: set the_string [regsub {\(.*} $the_string ""] or if you're not familiar with regexp then you can do it the more traditional way: set the_string [ string range $the_string 0 [ expr {[string first "(" $the_string]-1} ] ] For further info, read the manual pages for [string], [regsub] and [re_syntax].
[ "stackoverflow", "0024325173.txt" ]
Q: Functional vs Safety / Static vs Dynamic instantiations I'm in a situation where I think that two implementations are correct, and I don't know which one to choose. I've an application simulating card readers. It has a GUI where you choose which serial port, and speed to use, and a play and stop button. I'm looking for the best implementation for reader construction. I have a SimulatorCore class who's living as long as my application SimulatorCore instantiate the Reader class. And it will be possible to simulate multiple readers on multiple serial port. Two possibilities: My Reader is a pointer (dynamic instantiation), I instantiate it when play button is hit, delete it when stop button is hit. My Reader is an object (static instantiation), I instantiate it in SimulatorCore constructor then create and call Reader.init() and Reader.cleanup() into my Reader class and call these when play and stop are being hit I personally see the functional side, and I clearly want to use pointer, and do not have any reader instantiate if no reader are simulated. Someone say me that I should use static instantiation (Reason : for safety, and because "it's bad to use pointer when you have choice to not use them") I'm not familiar with them, but I think I can also use smart pointer. Code samples: 1st solution: class SimulatorCore { play(){reader = new Reader();}; stop(){delete reader; reader = nullptr;}; private: Reader *reader; } Code samples: 2nd solution: class SimulatorCore { play(){reader.init();}; stop(){reader.cleanup();}; private: Reader reader; } The code is unstest, I've juste wite it for illustration. What is the best solution? Why? A: You can easily use shared_ptr/unique_ptr: class SimulatorCore { play(){_reader = make_shared<Reader>();}; stop(){_reader = nullptr}; private: shared_ptr<Reader> _reader; } That will solve your problem right way, I guess. Dynamic allocation gives some problems, for example, with throwing exception (there can be memory losing if between play() and stop() there will be thrown exception, for example, and stop() will never be called). Or you can just forget somewhere call stop() before destruction of SimulatorCore, it is possible if program is heavy. If you never tried smart pointers, it is good chance to start doing it. A: You should generally avoid performing dynamic allocation with new yourself, so if you were going to go with the 1st solution, you should use smart pointers instead. However, the main question here is a question of logic. A real card reader exists in an idle state until it is being used. In the 2nd solution, what do init and cleanup do? Do they simply setup the card reader into an idle state or do they start simulating actually having a card being read? If it's the first case, I suggest that this behaviour should be in the constructor and destructor of Reader, and then creating a Reader object denotes bringing a card reader into existence. If it's the second case, then I'd say the 2nd solution is pretty much correct, just that the functions are badly named. What seems most logical to me is something more like this: class SimulatorCore { play(){reader.start();}; stop(){reader.stop();}; private: Reader reader; } Yes, all I've done is change the function names for Reader. However, the functions now are not responsible for initialising or cleaning up the reader - that responsibility is in the hands of Reader's constructor and destructor. Instead, start and stop begin and end simulation of the Reader. A single Reader instance can then enter and exit this simulation mode multiple times in its lifetime. If you later want to extend this idea to multiple Readers, you can just change the member to: std::vector<Reader> readers; However, I cannot know for certain that this is what you want because I don't know the logic of your program. Hopefully this will give you some ideas though. Again, whatever you decide to do, you should avoid using new to allocate your Readers and then also avoid using raw pointers to refer to those Readers. Use smart pointers and their corresponding make_... functions to dynamically allocate those objects.
[ "superuser", "0000973547.txt" ]
Q: How can I display all 8 NTFS timestamps? I understand that there are 8 NTFS timestamps http://www.governmentsecurity.org/forum/topic/30896-frustrating-ntfs-time-stamp-forensics/ NTFS MACE (Modified, Accessed, Created and MFT Entry modified ) values . NTFS comes with 8 time-stamp values 4 of which resides in $Standard_Information attribute (SI) and the other 4 in $FILE_NAME (FN) attribute of MFT entry. How can I display all 8? A: This command can do it MFTRCRD.exe c:\crp\a.a -d indxdump=off 1024 -s As for how I knew the parameters, well, doing MFTCRD said there are 4 parameters and gave an example of MFTRCRD C:\boot.ini -d indxdump=off 1024 -s so you can change for whatever filename/path. C:\blah>MFTRCRD.exe c:\crp\a.a -d indxdump=off 1024 -s Starting MFTRCRD by Joakim Schicht Version 1.0.0.37 Target is a File Filesystem on c: is NTFS File IndexNumber: 64587 ............................ $STANDARD_INFORMATION 1: File Create Time (CTime): 2014-12-06 03:49:51:714:3290 File Modified Time (ATime): 2015-09-15 16:23:33:791:7170 MFT Entry modified Time (MTime): 2015-09-15 16:23:33:791:7170 File Last Access Time (RTime): 2014-12-06 03:49:51:794:3335 ........... $FILE_NAME 1: Parent MFTReference: 80564 ParentSequenceNo: 10 File Create Time (CTime): 2014-12-06 03:49:51:714:3290 File Modified Time (ATime): 2014-12-06 03:49:51:794:3335 MFT Entry modified Time (MTime): 2014-12-06 03:49:51:794:3335 File Last Access Time (RTime): 2014-12-06 03:49:51:794:3335 (note those abbreviations from MFTRCRD of ATime for modified and others, like Rtime, look really absurd e.g. googling Rtime doesn't show anything. So you can ignore the abbreviations that that command gives you and go by the descriptions. But there are abbreviations that linux uses (MAC) and that windows NTFS uses (MACE) which I describe below) Linux does not store the time the file was created. (updated- some modern linux file systems do, see note at the end) Windows does creation time. It looks like Linux has 3 times. MAC time. mtime atime ctime . In Linux, ctime is changed time, rather than creation time, and the 'changed' time, in linux is different to the file being modified (the modified time). The changed time in linux is when the entry in the file system got changed e.g. when / even when, the file permissions change, then the ctime in linux changes. Windows NTFS uses MACE and the C in MACE is creation. The E in MACE seems to be like the c in linux i.e. the E in MACE is the entry being changed. http://forensicswiki.org/wiki/MAC_times MAC times The term MAC times refers to the timestamps of the latest modification (mtime) or last written time, access (atime) or change (ctime) of a certain file. Unix systems maintain the historical interpretation of ctime as the time when certain file metadata, not its contents, were last changed, such as the file's permissions or owner (e.g. 'This files metadata was changed on 05/05/02 12:15pm'). Windows systems are the only systems that use birth (btime) or creation (crtime) time (e.g. 'This file was created on 05/05/02 12:15pm'). Hence MACB; Modification, Access, Change and Birth. Further look at linux for contrast is beneficial. http://www.linux-faqs.info/general/difference-between-mtime-ctime-and-atime A common mistake is that ctime is the file creation time. This is not correct, it is the inode/file change time. mtime is the file modification time. A often heard question is "What is the ctime, mtime and atime?".This is confusing so let me explain the difference between ctime, mtime and atime. ctime ctime is the inode or file change time. The ctime gets updated when the file attributes are changed, like changing the owner, changing the permission or moving the file to an other filesystem but will also be updated when you modify a file. mtime mtime is the file modify time. The mtime gets updated when you modify a file. Whenever you update content of a file or save a file the mtime gets updated. Most of the times ctime and mtime will be the same, unless only the file attributes are updated. In that case only the ctime gets updated. atime atime is the file access time. The atime gets updated when you open a file but also when a file is used for other operations like grep, sort, cat, head, tail and so on. cygwin can show 4 time stamps, as can timestomp c:\blah>timestomp a.a -v Modified: Tuesday 9/15/2015 17:23:33 Accessed: Saturday 12/6/2014 4:49:51 Created: Saturday 12/6/2014 4:49:51 Entry Modified: Tuesday 9/15/2015 17:23:33 - $ stat a.a File: 'a.a' Size: 45 Blocks: 4 IO Block: 65536 regular file Device: b411d580h/3021067648d Inode: 102738366499454027 Links: 1 Access: (0070/----rwx---) Uid: ( 1000/ harvey) Gid: ( 513/ None) Access: 2014-12-06 03:49:51.794333500 +0000 Modify: 2015-09-15 17:23:33.791717000 +0100 Change: 2015-09-15 17:23:33.791717000 +0100 Birth: 2014-12-06 03:49:51.714329000 +0000 Apparently setMACE is like timestomp but better. However, I can't see it showing the 8 timestamps. And the setMACE description mentioned MFTCRD that shows the timestamps. You can get MFTRCRD from here https://github.com/jschicht/MftRcrd Github seems to be a bit odd, don't right click and save as, otherwise it's an HTML file with extension EXE. And when you try to run it on cmd you get an error on cmd about 64bit and 32bit. Try left clicking it then the next page gives you a download of the actual file. And you need to be in an administrative command prompt, otherwise you get a mesage about do you trust programs from this publisher, and if you say yes then a cmd window flashes up and goes(and whether cmd /k or not). But it works fine from an administrative cmd prompt. ADDED Some modern linux file systems store file creation time. (may be known as crtime. Definitely not ctime, for reasons mentioned above) https://unix.stackexchange.com/questions/91197/how-to-find-creation-date-of-file
[ "stackoverflow", "0020047692.txt" ]
Q: How to post nested JSON data in Android? I need to post the below JSON data from Android to a Webservice. This is JSON data {"AutoMobileName":"Mercedes","Engine":"V4","BrandInfo":{"Model":"C500","ColorType" : "Black","DatePurchased":"1990"}} Using Android Java i am doing like this. JSONObject holder = new JSONObject(); holder.put("AutoMobileName", "Mercedes"); holder.put("Engine", "V4"); StringEntity se = new StringEntity(holder.toString()); httpost.setEntity(se); Using the above code, the two parameters gets posted , but how do i send the BrandInfo data as it nested. How do i put it inside the holder object and post it ? A: Do it like this: JSONObject holder = new JSONObject(); //BrandInfo JSONObject brandInfo = new JSONObject(); brandInfo.put("Model", "C500"); brandInfo.put("ColorType", "Black"); brandInfo.put("DatePurchased", "1990"); holder.put("AutoMobileName", "Mercedes"); holder.put("Engine", "V4"); holder.put("BrandInfo", brandInfo); System.out.println(holder);
[ "stackoverflow", "0055075853.txt" ]
Q: ReactJS project is not showing on localhost Yesterday when I was working on my project everything was fine, but today when I start project with npm start I can see only blank screen on chrome A: On the screenshot of the HTML in the Network tab the syntax highlighting seems to stop after the <script...>-Tag for apis.google.com, maybe there is something wrong with the closing of that tag? VSCode also shows the "/> in red. A: Like you can see in this post you must properly close script tag. Even your IDE is complaining over it, and in last screenshot you can see that something is wrong after that script tag...
[ "stackoverflow", "0055894975.txt" ]
Q: Why using with() as function in a map() call does not work in this example? library(tidyverse) formulas <- list( mpg ~ disp, mpg ~ I(1 / disp), mpg ~ disp + wt, mpg ~ I(1 / disp) + wt ) # this works map(formulas, ~ {lm(.x, mtcars)}) # this doesn't map(formulas, ~ {with(mtcars, lm(.x))}) Error in eval(predvars, data, env) : object 'disp' not found Working through the exercises in https://adv-r.hadley.nz/functionals.html#exercises-28, I tried to solve exercise number 6, by trying to evaluate lm() inside mtcars environment with with(), but it throws an error. Why the last call doesn't work? A: It is the environment issue. One option would be quote the components so that it would not be executed formulas <- list( quote(mpg ~ disp), quote(mpg ~ I(1 / disp)), quote(mpg ~ disp + wt), quote(mpg ~ I(1 / disp) + wt) ) out1 <- map(formulas, ~ with(mtcars, lm(eval(.x)))) out1 #[[1]] #Call: #lm(formula = eval(.x)) #Coefficients: #(Intercept) disp # 29.59985 -0.04122 #[[2]] #Call: #lm(formula = eval(.x)) #Coefficients: #(Intercept) I(1/disp) # 10.75 1557.67 #[[3]] #Call: #lm(formula = eval(.x)) #Coefficients: #(Intercept) disp wt # 34.96055 -0.01772 -3.35083 #[[4]] #Call: #lm(formula = eval(.x)) #Coefficients: #(Intercept) I(1/disp) wt # 19.024 1142.560 -1.798 It should also work with the first method out2 <- map(formulas, ~ lm(.x, mtcars)) There would be slight changes in the attributes and in the call, but if that is ignored, out1[[1]]$call <- out2[[1]]$call all.equal(out1[[1]], out2[[1]], check.attributes = FALSE) #[1] TRUE
[ "stackoverflow", "0019885763.txt" ]
Q: How can I get a browser cookie from the server in Meteor for session handling? I am currently re-writing a PHP+Mongodb application in Meteor. In the application, a session cookie that contains only a unique identifier is used. The server gets the browser's cookie and uses its value to load data from a collection. This is useful for knowing the client's current state. Using Meteor I need to be able to get the value of the browser cookie from the server code. How can I accomplish this? In PHP, one might do it like so: if(isset($_COOKIE["cookie_name"])) { //there is a browser cookie set with a name "cookie_name", //and now I can act on that cookie's value, straight from the server echo $_COOKIE["cookie_name"]; } I'm not sure if meteor's Session is what I'm looking for mostly because: It doesn't seem to persist between page reloads (it creates a fresh session each reload) There must be a way to disconnect the session by simply deleting the browser cookie I'd like to handle this on the server because I want my sessions data to be private. Data about a session that isn't presented through a view (except for the session's unique identifier) must never be sent to the client. A: If I'm understanding correctly, you don't actually care about the cookie, you care about having user-specific data. Comparison to PHP Meteor clients communicate with the server via DDP which is an abstraction on top of http. Things like 'cookies' don't exist in the DDP level. Rather, you have access to powerful constructs like sync'd database collections and built-in remote procedure calls. Meteor's Session object is a client-only concept that is designed for reactivity. It is not persisted between client visits and the server does not have access to it. The rough equivalent to PHP's SESSION is a Meteor Collection, which is actually more durable than PHP's SESSION because it is persisted to the database. User-specific data Tracking user-specific data like you want in Meteor can be broken down into two parts: authenticated users anonymous users Re: #1 - authenticated users As @Tarang and @Cuberto have pointed out, the Meteor Accounts system (ex. accounts-password) has the concept of user-specific data built-in. It creates and manages the Meteor.users collection for you and provides the Meteor.user() function for getting an object specific to that user. It even has a built-in method for user-modifiable data in the profile field of the user object. The profile field is automatically published and is reactive as well (since Meteor.user() is reactive). function doSomething () { var currentUser = Meteor.user(), profile; if (!currentUser) { // handle 'not authenticated' case } else { // already logged in profile = currentUser.profile || {name:'<not set>'}; console.log('user ', profile.name, ' wants to doSomething'); } } You can build your own authentication method but that seems like a recipe for disaster. Easier to write a script that converts from your existing DB structure to the Meteor Accounts structure and do it once in a big dump when you are ready to migrate your users over. So the Meteor convention is: User-specific data that the user should be able to modify goes in the user.profile field. Ex. user.profile.firstname, user.profile.lastname User-specific data that is restricted should go on the root user object. Ex. The meteor-roles package stores user roles in a restricted, user.roles field. Here are the relevant docs: http://docs.meteor.com/#meteor_user Re: #2 - anonymous users Meteor Accounts does not track anonymous users so you will need to track them yourself. You can use various methods to do this but the core is to store some identifying token on the client's machine in client code (either into localStorage or a cookie). If you don't need to store user-specific data on the server and only want to change client-side stuff, such as what the users see, then you can do everything from the client. If you need to store data on the server for anonymous users then you'll have to send the identifying token to the server along with each Meteor method call or database interaction (essentially what PHP does with the SESSION cookie). On the server, create a Collection called 'anonymousData' which will contain all of the user-specific info for your anonymous users, keyed by id token. The server-side functions can query that Collection with the id token the client passes to retrieve user-specific info for that user. Keep in mind that if the user clears their cookies or deletes localStorage that data will be orphaned so some kind of a last-used check is important.
[ "stackoverflow", "0019891543.txt" ]
Q: Time counter MSQl I have a column of TIME type in my db, the column is supposed to hold the sum of two other TIMEs, the problem is that when the number of hours of the result exceeds 24 hours the column is reseted to 00:00:00 again, instead of viewing 25:00:00 which is the result that I want to see, any help on how can I get that without changing the column type? A: If you want to store numbers that are bigger than a possible time then that data type is inappropriate. Use another way to store the data like the sum of seconds. You could use an unsigned int for that.
[ "stackoverflow", "0016322711.txt" ]
Q: Datepicker creating a six months calendar I am triying to do a page with a Calendar. The idea is to put in the page the six first months in the year and with a button, show the other six months. I tried with datapicker, searching in the web and using different methods, but I dont achieve that. Someone knows hot to put, at less, the six months separately? A: You can set the defaultDate to the beginning of the current year. Combined with the numberOfMonths and stepMonths methods, we should be able to achieve something similar to what you're looking for. JS: // Get the first day of the year (ie. Jan 1, 2013) var firstOfTheYear = new Date(new Date().getFullYear(), 0, 1); // Set your datepicker options $(".calendar").datepicker({ numberOfMonths: [2, 3], stepMonths: 6, defaultDate: firstOfTheYear }); http://jsfiddle.net/RyanWalters/VYvLb/
[ "stackoverflow", "0026943983.txt" ]
Q: Printing value at array index returns hashcode Just playing around with displaying values in a two dimensional array and noticed my code prints some hashcodes and then the values. But I am not printing the array object itself (as done in the post here) or at least explicitly calling the toString or hashcode method of the array object. Instead, I'm directly accessing and printing the values in the array using arrayObj[i] and arrayObj[i][j]. Here's my code: class PrintTwoDimArray { public int [][] createArray () { int counter = 0; int[][] intArray = new int [2][4]; for (int i = 0; i < intArray.length; i++) { for (int j = 0; j < intArray[i].length; j++) { intArray[i][j] = ++counter; } } return intArray; } public void printArray ( int [][] arrayObj ) { for (int i = 0; i < arrayObj.length; i++) { System.out.print(arrayObj[i] + " "); for (int j = 0; j < arrayObj[i].length; j++) { System.out.print(arrayObj[i][j] + " "); } System.out.println(); } } } class TestPrintTwoDimArray { public static void main (String[] args) { PrintTwoDimArray twoDim = new PrintTwoDimArray(); int [][] multiArray = new int [2][4]; multiArray = twoDim.createArray(); twoDim.printArray(multiArray); } } My output is as follows: It seems that my code is somehow calling the toString or hashcode method of the array. Thoughts? How can I modify to print just the values? javac and java version 1.8.0 A: A two dimensional array is an array of arrays. The array you create (int[2][4]) looks like this [ 0 ] -> [ 1, 2, 3, 4 ] [ 1 ] -> [ 5, 6, 7, 8 ] So when you only access the first dimension you will get the array that holds the second dimension. int[][] arr = createArray(); System.out.println(arr[0]); will output something like [I@1db9742 To print an array's values you can use Arrays.toString(arr). In this case you can omit the inner loop, because Arrays.toString() will do it for you. public void printArray ( int [][] arrayObj ) { for (int i = 0; i < arrayObj.length; i++) { System.out.println(Arrays.toString(arrayObj[i])); } }
[ "stackoverflow", "0032303994.txt" ]
Q: Data type mismatch I got this error when I tried to select userid from a database to datatable. The first userid is an autonumber, the second USERID is a number, and the database is a MS Access DB. private void () { OdbcDataAdapter ad = new OdbcDataAdapter("select userid from userinfo where BadgeNumber='" + UserID + "'", this.FM.Cn); DataTable t = new DataTable(); ad.Fill(t); ad.Dispose(); if (t.Rows.Count > 0) { OdbcCommand cmd = new OdbcCommand(); cmd.Connection = this.FM.Cn; string id = t.Rows[0][0].ToString(); //Check Date OdbcDataAdapter add = new OdbcDataAdapter("Select USERID from checkinout where Userid='" + id + "'", this.FM.Cn); DataTable tc = new DataTable(); add.Fill(tc); // <- I gotta error here. add.Dispose(); } } A: Change your query to: "Select USERID from checkinout where Userid=" + id In SQL queries, strings literals (or chars) are required to be enclosed within a pair of single quotes ', which are used to delimiter the string. A delimiter is pretty much a character used to identify boundaries - in the case of a string, the single quotes specify where the string starts and where it ends. Because of the nature of numbers (integers for example), it is not necessary to indicate a delimiter such as single quotes. Your code was failing because when the database engine saw the single quotes, it was expecting a string, but your column was a number datatype, and this is why you obtained a Data type mismatch error when executing your query.
[ "stackoverflow", "0033367409.txt" ]
Q: SQLSTATE[42S02]: Base table or view not found: 1146 Table I am creating laravel's registration part. My table name is 'owner' and in code I wrote 'owner' as a table name, but still when I try to submit the registration form I am getting the error page as, SQLSTATE[42S02]: Base table or view not found: 1146 Table 'engage.owners' doesn't exist (SQL: insert into owners..... As there is no owners table in my engage database, I don't know why it's trying to insert into owners table rather than owner table. A: Accourding to the docs: http://laravel.com/docs/5.1/eloquent you can change it like this: namespace App; use Illuminate\Database\Eloquent\Model; class Flight extends Model { /** * The table associated with the model. * * @var string */ protected $table = 'my_flights'; } Keep in mind i never worked with laravel.
[ "stackoverflow", "0023297270.txt" ]
Q: Purify revealed a potential free memory read when using std::list::remove() Purify revealed a potential free memory read when using std::list::remove(). I noticed that std::list::remove() uses the type's operator== to do the comparison. However, what I have also noticed is that if the first element in the list is passed to std::list::remove(), it is deleted when it matches, but then it is still used to compare against all the other items in the list. This causes Purify to flag this as a "potential free memory read". I replaced the std::list::remove() call with erase() and an iterator, which is more efficient because it makes it loop only once versus twice in my situation. Is there a reason std::list::remove() keeps the first element around? A: This was GCC bug# 17012, fixed in 4.3.0. See also Library Working Group Defect Report 526.
[ "stackoverflow", "0023451310.txt" ]
Q: Why doesn't Python allow to put a for followed by an if on the same line? Why is this code for i in range(10): if i == 5: print i valid while the compound statement (I know that PEP 8 discourages such coding style) for i in range(10): if i == 5: print i is not? A: This is because python has strict rules about indentation being used to represent blocks of code and by putting an for followed by an if, you create ambiguous indentation interpretations and thus python does not allow it. For python, you can put as many lines as you want after a if statement: if 1==1: print 'Y'; print 'E'; print 'S'; print '!'; as long as they all have the same indentation level, i.e., no if, while, for as they introduce a deeper indentation level. Hope that helps A: The reason why you cannot is because the language simply doesn't support it: for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] It has been suggested many times on the Python mailing lists, but has never really gained traction because it's already possible to do using existing mechanisms... Such as a filtered generator expression: for i in (i for i in range(10) if i == 5): ... The advantage of this over the list comprehension is that it doesn't generate the entire list before iterating over it.
[ "stackoverflow", "0020195094.txt" ]
Q: Which Wordpress template does the posts page use as standard? I'm just wondering which page template the standard blog posts use. I am using the Roots.io theme and I don't have blog posts on the home page, I have them on a page called 'news' - I just wondered which template file this will use, or what I will need to create, as I can't seem to find which template it is using, so I can modify it. I have checked the hierarchy. they are not custom post types. A: If you have a peek inside of the templates directory you will see the list of included templates for the roots theme. For styling pages and posts use the content-*.php files.
[ "stackoverflow", "0036951424.txt" ]
Q: Find position where the member of two lists differs I have the following two lists of strings with the same size: l1 = ['foo', 'foo','bar','cho'] l2 = ['foo', 'qux','bar','cxx'] * * What I want to do is to find the position where the members differs, yielding: 1, 3 How can we do that? A: You can use list comprehension: >>> [i for i, v1 in enumerate(l1) if v1 != l2[i]] [1, 3] This will iterate over the first list, and compare the values with the second list, and incase they do not match, adds the index to the result.
[ "stackoverflow", "0024143758.txt" ]
Q: What's wrong with my let syntax? What's wrong with my let syntax in scheme? error: Cannot read property 'car' of undefined (define (test x) (let (a 1)) ) A: The correct syntax is: (let ((a value1) (b value2)) exp) You forgot an opening bracket.
[ "math.stackexchange", "0002842130.txt" ]
Q: Probability of Normal Dice An urn has $100$ normal dice, plus $75$ dice whose face numbers are $2, 2, 4, 4, 6, 6,$ and plus $25$ dice whose face numbers are $1, 1, 3, 3, 5, 5$. One die was chosen at random. If I just rolled one $6$ with this die, what is the probability that I chose a normal die? I have no clue how to go about this problem. Your help would be really appreciated. A: You could argue completely with Bayes' theorem, but you can also observe that uniformly picking a die and rolling it once amounts to uniformly picking one of the $ 1200$ faces. You picked a six (out of $250$ sixes). There are $150$ sixes on "even" dice and $100$ sixes on normal dice (plus none on "odd" dice). Hence the probability that your particular six is on a normal die is $\frac{100}{250}$.
[ "drupal.stackexchange", "0000256692.txt" ]
Q: Add code to for specific content type What would be the best way to add code inside the tag of specific content type? Display Suite is being used for layout and we are using a custom theme. Have created html.html.twig. If I add anything to the head tags of this file, of course, it shows on all the pages. Can we create a separate template such as html--content-type.html.twig then add the code there? If not what would be the Drupal way of adding this code to the head tags for only specific content type? <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <script> (adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-3********", enable_page_level_ads: true }); </script> A: The quick way and maybe some will call it dirty way would be to add in your THEMENAME.theme file function THEMENAME_preprocess_html(&$vars) { $node = \Drupal::routeMatch()->getParameter('node'); if ($node instanceof \Drupal\node\NodeInterface) { // You can get nid and anything else you need from the node object. $vars["content_type"] = $node->bundle(); } } and then in your html.html.twig {% if content_type == "page" %} <script> ... </script> {% endif %} alternatively you can just put it in a .js file and include like this function my_module_preprocess_html(&$variables) { // To get around the issue of D8 core escaping inline js we cram our js // file into a twig variable for printing "raw" in "html.html.twig" like so: // {{ my_module_script|raw }} $variables['my_module_script'] = '<script type="text/javascript">' . file_get_contents(dirname(__FILE__) . '/js/script.js') . '</script>'; } as described in this comment proper way is probably to Define a library and then to attach it following this guide
[ "stackoverflow", "0017407010.txt" ]
Q: Selecting column based on a field value in MYSQL I need to select a different column from a database based on a value in a different field. Players: ID EVENT_ID NAME TEAM -------------------------------- 1 1 Ann 1 2 1 Bob 2 3 2 Claire 1 Events: ID EVENT_NAME TEAM_1 TEAM_2 ---------------------------------------------- 1 Football All Stars Tornadoes 2 Tennis Dynamos Best Team Based on my tables I want to be able to search for player ID 2 and get their team name depending on the players.team value. so something like this: SELECT players.*, (SELECT team+"players.team" AS team_name FROM events WHERE players.event_id = events.id) WHERE players.id = '2' that gets the result: Player.ID: 1 Player.Name: Bob Team_Name: Tornadoes A: You can use CASE for that: SELECT p.id, p.name, CASE WHEN p.team = 1 THEN e.team_1 ELSE e.team_2 END AS Team_Name FROM Players p LEFT JOIN Events e ON e.id = p.event_id WHERE p.id = 2
[ "stackoverflow", "0040383984.txt" ]
Q: Finding Duplicate Integers in Word Array in MIPS I'm writing a MIPS program that solves a randomly generated maze using a left-hand rule algorithm. I'm trying to find a way to track the best path through the maze as it completes the LHR algorithm. In the program, $t9 is a 32-bit number that stores the current location and direction of the car that is traversing the maze. Bits 31-24 store the row location in an 8-bit 2C number and 23-16 store the column location. I've already figured out how to isolate the row and column numbers, and I know how to store them into arrays of word in the .data space, but I'm not sure how I'd go about finding which spaces have already been visited, aka duplicate values in the array. So far, as it completes the maze the array would look something like this: 0001020110 [starts in 0,0, goes to 0,1, goes to 0,2, goes to 0,1, then 1,0], and I need to find a way to copy this into a new array, or basically weed out 0,1 since it visited that space twice and make it 000210. Alternatively, I could split the rows and columns into two separate arrays. Any help is greatly appreciated. Here is the code for the algorithm so far. I only included my main function, since the other functions described only link to functions that move the car, and don't change the location of the car. .data rows: .space 100 cols: .space 100 location: .space 100 .text la $a0, location jal _leftHandRule j endProgram _leftHandRule: #a0: address of location space .text goForward: addi $t8, $zero, 1 andi $t4, $t9, 0x80000 #if the value in 0x80000 (bit 19, row 8) is not 0, then the car is in row 8, and has finished the maze #row srl $t5, $t9, 24 andi $t6, $t5, 0xff sw $t6, location($t7) addi $t7, $t7, 1 #increments t7 in as the array location counter #column srl $t5, $t9, 16 andi $t6, $t5, 0xff sw $t6, location($t7) addi $t7, $t7, 1 #increments t7 for the next loop bne $t4, $zero, endLeftHandRule andi $t0, $t9, 0x08 bne $t0, $zero, hitWall #if the value in 0x08 is not zero, there is a wall in front of the car andi $t2, $t9, 0x04 beq $t2, $zero, noLeftWall #if the value in 0x04 is zero, there is no left wall beside the car j goForward A: I wouldn't look for duplicate coordinate pairs in the stream of locations, as that's O(N) (where N is length of path). I would instead initialize MxN bit visited array to zero at the start of algorithm (M, N = maximum maze sizes for columns/rows) (so size of array is M*N/8 bytes, or when whole byte is used instead of bit, then M*N bytes). Then when you visit particular [x,y] location, you set corresponding bit/byte in visited to one, like visited[y*N + x] = 1. To test if you already were to some location, you look up into visited[y*N + x] value. That's O(1) test. And finally, if your maze definition is already M*N, and there is some free unused bit in each cell, which you can modify, you can use that one instead of separate array (it's not obvious from question, how is the maze defined, but there's some bit magic in the code like separate front/left walls, so maybe it would be possible to cram this visited-bit into it). If you can destroy the maze definition during LHR, you can also add fake-walls to it to mark ways you already tried (so once you go forward, you would create "forward" wall behind you on original location, preventing the LHR to go "forward" next time, when it visits the original location, it will now see the route blocked). Actually I'm not sure how this info will help with creating optimal path by LHR algorithm, I took a 5s thought, and I would need something else for it, incorporating recursion probably, so I would know about visited cells by returning to particular recursion depth. Then again that would be huge strain on stack, to write it like that, so I would go for array, and probably change from LHR into some wide-first search, as LHR is sort of depth-first, which is less optimal... so I'm already off your path. Take my answer only as description how to mark particular cell as visited, how you will use it is up to you. Thinking about it for 5s more. You actually probably really want to find that particular first visit of cell in your "location" output, to overwrite the blind branch which returned back to it. You can do that by reading the "location" data from start up to $t7 and when you find two bytes with current row/column, reset t7 after it, otherwise when t7 is reached, it's "not found" (so for every single step you do O(N) search in "location" data). But I would still go with another "maze" array, this time storing not only "visited" flag, but "direction to next". Simply overwriting it during LHR without any test (O(1) "test" per LHR step). After reaching end of maze, I would go back to start and just follow the "direction to next", producing the "location" data with coordinates. It will follow the LHR path from start to end without the dead-end branches (as only the last "direction of next" of particular cell will remain, which leads to exit.
[ "blender.stackexchange", "0000023194.txt" ]
Q: Edit multiple meshes at once? I want to edit a game model and I can't join the meshes with CtrlJ because the model will not work in the game anymore. If I use P in Edit Mode, the meshes will split into even more meshes than before, with different names, and it will not work anymore. The model is separated into multiple meshes. I can edit the vertices of each mesh, but I can't edit multiple meshes at once, so that they stay "synchronized". Any idea how to do this without CtrlJ or a way to "unjoin" keeping the same meshes names before joining? A: There is an addon called MultiEdit, that will enable you to edit multiple objects at once. Here is the post on blender artists where the download can be found. After you have installed and activated the addon, you just select the objects that you want to edit together, and click on the MultiEdit Enter button in the tool shelf. Then when you are done, toggle back out of edit mode and click on the MultiEdit Exit button.
[ "stackoverflow", "0061725501.txt" ]
Q: Unknown field Actions (Service: AmazonIdentityManagement; Status Code: 400) I keep getting this Error everytime the stack is forming and it rolls back. I do not know why. "Unknown field Actions (Service: AmazonIdentityManagement; Status Code: 400; Error Code: MalformedPolicyDocument; Request ID: 9c392f93-5d03-4b0c-a90b-00d2db58cb0b)" tried looking up what the error means and couldn't find anything. { "AWSTemplateFormatVersion": "2010-09-09", "Parameters": { "CodeCommitBranchName": { "Description": "CodeCommit branch name", "Type": "String", "Default": "master" } }, "Resources": { "ManualApprovalSns": { "Type": "AWS::SNS::Topic", "Properties": { "Subscription": [ { "Endpoint": "<myemail>", "Protocol": "email" } ] } }, "JavaProjectRepository": { "Type": "AWS::CodeCommit::Repository", "Properties": { "Code": { "S3":{ "Bucket": "seis615-public", "Key": "java-project.zip" } }, "RepositoryName": "java-project", "RepositoryDescription": "Java-project code" } }, "ArtifactBucket": { "Type": "AWS::S3::Bucket", "Properties": { "BucketEncryption": { "ServerSideEncryptionConfiguration": [ { "ServerSideEncryptionByDefault": { "SSEAlgorithm": "AES256" } } ] } } }, "ArtifactBucketPolicy": { "Type": "AWS::S3::BucketPolicy", "Properties": { "Bucket": { "Ref": "ArtifactBucket" }, "PolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Sid": "DenyUnEncryptedObjectUploads", "Effect": "Deny", "Principal": "*", "Action": "s3:PutObject", "Resource": { "Fn::Join": [ "", [ { "Fn::GetAtt": [ "ArtifactBucket", "Arn" ] }, "/*" ] ] }, "Condition": { "StringNotEquals": { "s3:x-amz-server-side-encryption": "aws:kms" } } } ] } } }, "AppBuildProject": { "Type": "AWS::CodeBuild::Project", "Properties": { "Artifacts": { "Type": "CODEPIPELINE" }, "Description": "app build project", "Environment": { "ComputeType": "BUILD_GENERAL1_SMALL", "Image": "aws/codebuild/standard:2.0", "ImagePullCredentialsType": "CODEBUILD", "Type": "LINUX_CONTAINER" }, "ServiceRole": { "Fn::GetAtt": [ "AppBuildRole", "Arn" ] }, "Source": { "Type": "CODECOMMIT" } } }, "AppBuildRole": { "Type": "AWS::IAM::Role", "Properties": { "AssumeRolePolicyDocument": { "Version" : "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "codebuild.amazonaws.com" ] }, "Action": [ "sts:AssumeRole" ] } ] }, "Path": "/", "Policies": [ { "PolicyName": "CodeBuildAccess", "PolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Resource": [ {"Fn::Sub": "arn:aws:s3:::codepipeline-${AWS::Region}-*"} ], "Action": [ "s3:PutObject", "s3:GetObject", "s3:GetObjectVersion", "s3:GetBucketAcl", "s3:GetBucketLocation" ] }, { "Effect": "Allow", "Resource": [ { "Fn::GetAtt": [ "ArtifactBucket", "Arn" ] }, {"Fn::Join": [ "", [ { "Fn::GetAtt": [ "ArtifactBucket", "Arn" ] }, "/*" ] ]} ], "Action": [ "s3:PutObject", "s3:GetObject", "s3:GetBucketAcl", "s3:GetBucketLocation" ] }, { "Sid": "CodeCommitPolicy", "Effect": "Allow", "Action": [ "codecommit:GitPull" ], "Resource": [ "*" ] }, { "Sid": "CloudWatchLogAccessPolicy", "Effect": "Allow", "Action": [ "logs:*" ], "Resource": "*" }, { "Action": [ "elasticbeanstalk:*", "ec2:*", "elasticloadbalancing:*", "autoscaling:*", "cloudwatch:*", "s3:*", "sns:*", "cloudformation:*", "rds:*", "sqs:*", "ecs:*" ], "Resource": "*", "Effect": "Allow" } ] } } ] } }, "BuildLogPolicy": { "Type": "AWS::IAM::Policy", "Properties": { "PolicyName": "BuildLogAccess", "PolicyDocument": { "Version" : "2012-10-17", "Statement": [ { "Effect": "Allow", "Resource": [ {"Fn::Sub": [ "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${project}", {"project": { "Ref": "AppBuildProject" } } ] }, {"Fn::Sub": [ "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${project}:*", {"project": { "Ref": "AppBuildProject" } } ] } ], "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ] } ] }, "Roles": [ { "Ref": "AppBuildRole" }] } }, "AppCodePipeline": { "Type": "AWS::CodePipeline::Pipeline", "Properties": { "ArtifactStore": { "Location": {"Ref": "ArtifactBucket"}, "Type": "S3" }, "RoleArn": {"Fn::GetAtt": ["CodePipelineServiceRole", "Arn"]}, "Stages": [ { "Name": "Source", "Action": [ { "Name": "GetSource", "ActionTypeId": { "Category": "Source", "Owner": "AWS", "Provider": "CodeCommit", "Version": "1" }, "Configuration": { "RepositoryName": {"Fn::GetAtt": ["JavaProjectRepository", "Name"]}, "BranchName": {"Ref": "CodeCommitBranchName"}, "PollForSourceChanges": "false" }, "OutputArtifacts": [ { "Name": "SourceCode" } ] } ] }, { "Name": "Build", "Actions": [ { "Name": "BuildSource", "InputArtifacts": [ { "Name": "SourceCode" } ], "ActionTypeId": { "Category": "Build", "Owner": "AWS", "Provider": "CodeBuild", "Version": "1" }, "Configuration": { "ProjectName": {"Ref": "AppBuildProject"} }, "OutputArtifacts": [ { "Name": "CodeArtifact" } ] } ] }, { "Name": "ManualTest", "Actions": [ { "Name": "ManualApproval", "ActionTypeId": { "Category": "Approval", "Owner": "AWS", "Version": "1", "Provider": "Manual" }, "InputArticles": [], "OutputArtifacts": [], "Configuration": { "NotificationArn": {"Ref": "ManualApprovalSns"}, "ExternalEntityLink": {"Fn::GetAtt": ["ArtifactBucket", "DomainName"]}, "CustomData": "Assignment 6 - Manual Approval Stage." } } ] } ] } }, "CodePipelineServiceRole": { "Type": "AWS::IAM::Role", "Properties": { "AssumeRolePolicyDocument": { "Statement": [ { "Actions": [ "sts:AssumeRole" ], "Effect": "Allow", "Principal": { "Service": [ "codepipeline.amazonaws.com" ] } } ] }, "Path": "/service-role/", "Policies": [ { "PolicyDocument": { "Statement": [ { "Effect": "Allow", "Action": "sns:Publish", "Resource": "*" }, { "Action": [ "iam:PassRoll" ], "Resource": "*", "Effect": "Allow", "Condition": { "StringEqualsIfExists": { "iam:PassedToService": [ "cloudformation.amazonaws.com", "elasticbeanstalk.amazonaws.com", "ec2.amazonaws.com", "ecs-tasks.amazonaws.com" ] } } }, { "Action": [ "codecommit:CancelUploadArchive", "codecommit:GetBranch", "codecommit:GetCommit", "codecommit:GetUploadArchiveStatus", "codecommit:UploadArchive" ], "Resource": "*", "Effect": "Allow" }, { "Action": [ "elasticbeanstalk:*", "ec2:*", "elasticloadbalancing:*", "autoscaling:*", "cloudwatch:*", "s3:*", "sns:*", "cloudformation:*", "rds:*", "sqs:*", "ecs:*" ], "Resource": "*", "Effect": "Allow" }, { "Action": [ "lambda:InvokrFunction", "lambda:ListFunctions" ], "Resource": "*", "Effect": "Allow" }, { "Action": [ "opsworks:CreateDeployment", "opsworks:DescribeApps", "opsworks:DescribeCommands", "opsworks:DescribeDeployments", "opsworks:DescribeInstances", "opsworks:DescribeStacks", "opsworks:UpdateApp", "opsworks:UpdateStack" ], "Resource": "*", "Effect": "Allow" }, { "Action": [ "cloudformation:CreateStack", "cloudformation:DeleteStack", "cloudformation:DescribeStacks", "cloudformation:UpdateStack", "cloudformation:CreateChangeSet", "cloudformation:DeleteChangeSet", "cloudformation:DescribeChangeSet", "cloudformation:ExcecuteChangeSet", "cloudformation:SetStackPolicy", "cloudformation:ValidateTemplate" ], "Resource": "*", "Effect": "Allow" }, { "Action": [ "codebuild:BatchGetBuilds", "codebuild:StartBuild" ], "Resource": "*", "Effect": "Allow" }, { "Effect": "Allow", "Action": [ "devicefarm:ListProjects", "devicefarm:ListDevicePools", "devicefarm:GetRun", "devicefarm:GetUpload", "devicefarm:CreateUpload", "devicefarm:ScheduleRun" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "servicecatalog:ListProvisionArtifacts", "servicecatalog:CreateProvisioningArtifact", "servicecatalog:DescribeProvisioningArtifact", "servicecatalog:DeleteProvisioningArtifact", "servicecatalog:UpdateProduct", "servicecatalog:DescribeProvisioningArtifact", "servicecatalog:DeleteProvisioningArtifact", "servicecatalog:UpdateProduct" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "cloudformation:ValidateTemplate" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "ecr:DescribeImages" ], "Resource": "*" } ], "Version": "2012-10-17" }, "PolicyName": "ec2codedeploy" } ] } } }, "Outputs": { "S3BucketDomain": { "Description": "S3Bucket domain name", "Value": {"Fn::GetAtt":["ArtifactBucket", "DomainName"]} } } } A: There is: "Actions": ["sts:AssumeRole"] But it should be: "Action": ["sts:AssumeRole"] Not Actions, but Action.
[ "stackoverflow", "0016736901.txt" ]
Q: Angular JS, filter table with a select box I have a table. I want to filter the table depending on which value is choosen in an select box. The comparison value is {{pipe.pipe_id}} in the select box and {{dimension.pipe_id}} in the table. Guess there's a simple solution for this? Any suggestion? Pipe: <select id="select01"> <option ng-repeat="pipe in pipes">{{pipe.code}} - {{pipe.title_en}}</option> </select> <table class="table table-striped"> <thead> <tr> <th>Pipe</th> <th>Size</th> <th>Inner diameter</th> <th>Outer diameter</th> </tr> </thead> <tbody> <tr ng-repeat="dimension in dimensions" > <td>{{dimension.pipe_id}}</td> <td>{{dimension.nominalsize}}</td> <td>{{dimension.innerdiameter}}</td> <td>{{dimension.outerdiameter}}</td> </tr> </tbody> </table> A: I would recommend using the ng-filter. This link is a simple example using a to-do list. jsfiddle using ng-filter You will need to bind whatever input you are using with ng-model="varname" The ng-filter defaults to all fields in the array. It can be filtered to a single column or point to a function in your controller. Search Field <select ng-model="searchparam"> <option value="1">One</option> <option value="2">Two</option> </select> To Search a single column <select ng-model="searchparam.columnOne"> <option value="1">One</option> <option value="2">Two</option> </select> Repeated Section (the filter model stays the same even when your input specifies a specific column) <tr ng-repeat="dimension in dimensions | filter: searchparam"> <td>{{dimension.columnOne}}</td> <td>{{dimension.columnTwo}}</td> </tr>
[ "stackoverflow", "0057837995.txt" ]
Q: C++ Error - no matching function for call I am having some problems trying to compile my code because of an error. It is in function mergeSort , line: merge(a, from, mid, to); : Invalid arguments ' Candidates are: 2 merge(#0, #0, #1, #1, #2, #3) 2 merge(#0, #0, #1, #1, #2) ' no matching function for call to merge(std::vector >&, int&, int&, int&) void mergeSort(vector<string> &a, int from, int to) { if (from == to) { return; } int mid = (from + to) / 2; mergeSort(a, from, mid); mergeSort(a, mid + 1, to); merge(a, from, mid, to); } // end mergeSort void merge(vector<string> &a, int from, int mid, int to) { int n = to - from + 1; vector<string> b(n); int i1 = from; int i2 = mid + 1; int j = 0; while (i1 <= mid && i2 <= to) { if (a[i1].compare(a[i2]) < 0) { b[j] = a[i1]; i1++; } else { b[j] = a[i2]; i2++; } j++; } while (i1 <= mid) { b[j] = a[i1]; i1++; j++; } while (i2 <= to) { b[j] = a[i2]; i2++; j++; } for (j = 0; j < n; j++) { a[from + j] = b[j]; } } int main() { vector<string> v = {"Apple", "Fruit", "Banana", "apple", "4apples", "applesauce", "3bananas", "\"apple\""} // Print original vector cout << "******Original*******"<< endl; for (vector<string>::size_type i = 0; i < v.size(); ++i) { cout << v[i] << endl; } mergeSort(v, 0, v.size() - 1); cout << "******MERGE SORTED*******"<< endl; for (vector<string>::size_type i = 0; i < v.size(); ++i) { cout << v[i] << endl; } } A: The standard C++ library has its own std::merge() functions. Those are the candidates you see described in the compiler error as not matching. It does not appear the compiler is even considering your merge() function. This implies that you have not declared your function before trying to use it, and that you have a using namespace std statement in your code. You need to declare your function. And you need to either get rid of the using statement or else declare your function in its own namespace, and then have mergeSort() be explicit about which namespace to pull merge() from.
[ "stackoverflow", "0013481125.txt" ]
Q: What if TinyURL API doesn't work..? I have a vbscript function to create a tinyurl from a regular url. FUNCTION GetShortURL(strUrl) Dim oXml,strTinyUrl,strReturnVal strTinyUrl = "http://tinyurl.com/api-create.php?url=" & strUrl set oXml = Server.CreateObject("Msxml2.ServerXMLHTTP.3.0") oXml.Open "GET", strTinyUrl, false oXml.Send strReturnVal = oXml.responseText Set oXml = nothing GetShortURL = strReturnVal END FUNCTION I have come across the problem when the tinyurl api is down or inaccessible, making my script fail: msxml3.dll error '80072efe' The connection with the server was terminated abnormally Is there a safeguard I can add to this function to prevent the error and use the long url it has..? Many thanks in advance, neojakey A: If you want to just return strUrl if the call fails, you can use On Error Resume Next FUNCTION GetShortURL(strUrl) on error resume next Dim oXml,strTinyUrl,strReturnVal strTinyUrl = "http://tinyurl.com/api-create.php?url=" & strUrl set oXml = Server.CreateObject("Msxml2.ServerXMLHTTP.3.0") oXml.Open "GET", strTinyUrl, false oXml.Send strReturnVal = oXml.responseText Set oXml = nothing 'Check if an error occurred. if err.number = 0 then GetShortURL = strReturnVal else GetShortURL = strUrl end if END FUNCTION
[ "stackoverflow", "0006714020.txt" ]
Q: How can a service listen for touch gestures/events? I'm wondering how apps like SwipePad and Wave Launcher are able to detect touch gestures/events simply through a service. These apps are able to detect a touch gestures even though it is not in their own Activity. I've looked all over the Internet and haven't found how they can do that. My main question is how a service can listen in on touch guestures/events just as a regular Activity may receive MotionEvents even though it may not be in the original Activity or context. I'm essentially trying a build an app that will recongize a particular touch gesture from a user regardless which Activity is on top and do something when that gesture is recongized. The touch recongition will be a thread running in the background as a service. A: I had this same problem and I've finally figured it out! Thanks to this post: Creating a system overlay window (always on top). You need to use an alert window instead of an overlay (and this also means you can use it in Andoid ICS): WindowManager.LayoutParams params = new WindowManager.LayoutParams( WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL|WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, PixelFormat.TRANSLUCENT); Then just attach a GestureListener in this manner: GestureDetector gestureDetector = new GestureDetector(this, new AwesomeGestureListener()); View.OnTouchListener gestureListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event); } }; overlayView.setOnTouchListener(gestureListener); Yay! A: Interesting question. I don't know how they did that and I found google group posts which tell me that there is no global touch listener. But I have an idea anyways... I found this post where someone succeeds to display a popupwindow from a service. If I would make that popup transparent and fullscreen, I'm sure I could capture the touches since I'm allowed to set a touch interceptor. Edit: Please report results when you try that, would be interesting to know if this works... A: I tested every possible solution but nothing worked some didn't fired touch event which did they frozed the screen . So I did some reverse engineering and now posting solution which works WindowManager.LayoutParams params = new android.view.WindowManager.LayoutParams(0, 0, 0, 0, 2003, 0x40028, -3); View mView = new View(this); mView.setOnTouchListener(this); WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE); wm.addView(mView, params);
[ "stackoverflow", "0058449832.txt" ]
Q: Refer to cell B2 with text "B2" I have a text "B1" in a random cell of an excel sheet Is there a way to make excel read out the text "B1" and convert it to the coordinate of the cell B1 and give me the value of B1? A: Use the INDIRECT function like this: =INDIRECT(A1) Now just replace A1 with the cell that contains the text "B1".
[ "math.stackexchange", "0000609521.txt" ]
Q: Confusion over an example of weak limit in L2 I understand the definition of weak limit, but I'm confused about the weak $L^2$ limit of the sequence $g_n = n1_{[0,1/n^2]}$. The $L^2$-norm of each of these functions is $1$. Does this mean the weak limit is the Dirac delta function? A: The Dirac delta function is not an object in $L^2[0,1]$. You have, for any $k\in\mathbb N\cup\{0\}$, $$ \int_0^1g_n(t)\,t^k\,dm(t)=\frac1{k+1}\,\frac1{n^{2k+1}}\to0. $$ This shows that $\int_0^1g_n\,p\to0$ for any polynomial $p$. Now, polynomials are dense in $L^2[0,1]$, so a trivial application of Hölder lets you show that $$ \int_0^1g_n\,f\to0 $$ for all $f\in L^2[0,1]$. That is, $g_n\to0$ weakly.
[ "ru.stackoverflow", "0001116403.txt" ]
Q: Перехват вывода CMD и Powershell в переменную string? Как сделать вывод результата команд CMD и Powershell не в консоль и не в текстовый файл, а сразу в переменную string? A: static void Main() { //cmd Process processCMD = Process.Start(new ProcessStartInfo { FileName = "cmd", //нужно использовать кодировку иначе будут кракозябры Arguments = "/c chcp 65001 & ipconfig", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden } ); string t1 = processCMD.StandardOutput.ReadToEnd(); //PewerShell Process processPowerShell = Process.Start(new ProcessStartInfo { FileName = "powershell", Arguments = "/command Get-Date", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden } ); string t2 = processPowerShell.StandardOutput.ReadToEnd(); }
[ "stackoverflow", "0033683060.txt" ]
Q: Is WebRequest (System.Net) a safe choice in Unity? First of all, let me state my problem: my game server does not provide WebAPI (we do not have resources for it now), but rather our client is tring to work like a web browser and I need cookie support for Session ID. Searching around with Google, I see the best I can do is manually set the headers of request and get the response header. I am ok with that, because I am originally ASP.NET MVC developer. However, I then realize they use Dictionary for both the request and response. Now that's the problem. We know that the header can be duplicated, in my case is the Set-Cookie. Then I tried another, and find out UnityWebRequest class, which is still in UnityEngine.Experimental.Networking namespace (so I suppose it is still in beta?), but I try my luck anyway; only sad to realize they also use Dictionary for header items. So now my only chance is the vanilla .NET WebRequest (in System.Net namespace). However, I see no documentation on the .NET Framework compability in Unity. Can anyone tell me if it is supported on most platform? My main targets are Windows, Android and Web. If possible, even for WebClient would be nicer. Here is my current solution, which work good in the Unity Editor, but I have yet to test them on other devices. Is there any solution for this? public class CookieWebRequest { private CookieContainer cookieContainer; public CookieWebRequest() { this.cookieContainer = new CookieContainer(); } public void GetAsync(Uri uri, Action<HttpWebResponse> onFinished) { var webRequest = HttpWebRequest.Create(uri) as HttpWebRequest; webRequest.Method = WebRequestMethods.Http.Get; webRequest.CookieContainer = this.cookieContainer; new Thread(() => { HttpWebResponse httpResponse; try { httpResponse = webRequest.GetResponse() as HttpWebResponse; } catch (WebException ex) { if (onFinished != null) { onFinished(ex.Response as HttpWebResponse); } return; } if (httpResponse.Cookies != null && httpResponse.Cookies.Count > 0) { this.cookieContainer.Add(httpResponse.Cookies); } if (onFinished != null) { onFinished(httpResponse); } httpResponse.GetResponseStream().Dispose(); }).Start(); } } A: System.Net.HttpWebRequest and System.Net.WebClient work on most platforms supported by Unity. However when you want to build for the Unity Web Player or WebGL you will run into problems since Unity does not support most of the System.Net networking stuff since javascript does not have direct access to IP Sockets. WebGL network restictions As you already mentioned UnityWebRequest or the legacy WWW object from Unity is your best bet. With Unity 5.3 UnityWebRequest work on most platforms including WebGL and the Unity Web player. But as you also already mentioned the complete UnityWebRequest is still experimental but is under constant development and will probably improve in every new update. The only downside, using the WWW or UnityWebRequest object is (as far as I understood the UnityWebRequest object) that they need to run in the Unity main thread so you will have to use Coroutines instead of pushing the request into a different thread. As long as you do not have millions of webrequest this should not lead into any performance issues of your app. And is probably less error prone.
[ "math.stackexchange", "0002393701.txt" ]
Q: Is every commutative ring without non trivial idempotent ,local? Is every commutative ring without non trivial idempotent ,local? I know that every local ring doesn't contain nontrivial idempotent because the number of maximal ideals in R is equal to the sum of maximals in S and T where R=ST. I thought since the ring doesn't contain nontrivial idempotent it can not be the direct product of two rings and each factor contains a maximal ideal so perhaps there us just one... A: No, for example any non-local domain is a counterexample. For a non-domain example, an interesting one is $\mathbb Z[x]/(x^2-1)$ lacks nontrivial idempotents, but has distinct maximal ideals. You can find this and several more examples using this search at DaRT.
[ "security.stackexchange", "0000108102.txt" ]
Q: What are attackers trying to achieve when doing attacks on local programs such as buffer overflows? In attacks on programs, such as stack buffer overflows, what is the objective of the attacker? I’m having trouble learning the technical details of the attack (such as overwriting the function’s return address) because it’s not clear what such attacks are intended to achieve. For example, in SQL injection, it’s usually done to get confidential information or make the server run code. It seems like the prerequisite for a buffer overflow attack is for the attacker to already have the ability to run code on the machine, so what more do they want? Is it usually a program on a remote computer that is being attacked in these situations? By the way I'm more familiar with C++ than C. A: An aspect which hasn't been mentioned yet very clearly: suppose you have a multi-user system (as all modern PC OSes like Windows, Linux, Unix and so on are), and suppose you are a normal (non-privileged) user who can run "normal" application programs. Now you want to do something malicious to your PC (like installing a keylogger to get all passwords which the other users of the PC are typing, or reading other users' emails). But you can't do that because you are just a normal user, do not have administrative rights, can't install software and can't view other users' data. So your goal is to become a user with administrative rights (administrator in Windows, root in Linux / Unix, etc.). Besides tricking the administrator into giving you his password, another way to achieve that is to attack a vulnerable program which already is running with administrative rights. If you could make such a program run your code (for example, by abusing a buffer overflow), then this code would run with administrative privileges as well, and -bang- you could do anything what you like with the machine. This is called privilege escalation. Please note that (due to technical reasons which can't be explained here in detail) practically every system has lots of (server) processes with root privileges running in the background, so this is a real scenario (actually, I am estimating that most of the attacks against local programs are done for privilege escalation). So the key factor is: when you (a normal user) run a program, this program runs with your own privileges and access restrictions, but when you can make a program which is already running with administrative privileges run your own code by abusing buffer overflows and similar techniques, your code runs with administrative privileges as well. Please note that this explanation is heavily simplified (for example, in Linux / Unix there are SUID programs and so on), but hopefully expresses the underlying idea. One last thing: privilege escalation is often the goal whether or not the attack is done locally or remotely. Often enough, attacks work in two steps: First, the attacker gets a naive user's password (for example, because it is too weak, is the birthday of his wife or the name of his dog) and then uses these credentials to get onto the respective machine remotely. Then, as the second step, being that user, the attacker scans the respective machine for vulnerable, privileged software and, for example by abusing buffer overflows in that software, lets that software run his malicious code which in turn is executed with the same privileges as the vulnerable software, effectively making the attacker an administrator. Of course, there are also many cases where an attacker directly abuses privileged software running on a remote system (for example, web server processes running on Linux under root). But since you have primarily asked for the sense of local attacks, we'll leave that away for now. A: Most of the exploits which takes advantage of Buffer Overflow vulnerability does Code Execution on the victim's machine, and this is the main intention of the attacker, to take control of others computer remotely or locally.
[ "stackoverflow", "0054244998.txt" ]
Q: Accessing dynamically to a Kotlin class property I want to set dynamically a backgroundColor to a text view in a RecyleView, and thus not all my item will have the same background color for their tag. This is the pseudo code I'd like to use : val name = item.type.toLowerCase() color = ContextCompat(item.context, R.color[name]) But this syntax does not seem to work in Kotlin, and I really have no idea how to fetch the color value from the resource depending on the type of the item. I also tried this: val lowerType = pokemon.type.toLowerCase() val id = holder.context.resources.getIdentifier(lowerType, "id", holder.context.packageName) val color = ContextCompat.getColor(holder.context, id) But this crashes too A: It's not a good idea to access the resources in a dynamic way, you will lose compile-time safety and code completion. In your case, you could create a Map that associates every view type to the resource you want (i.e. color). Example /* colors.xml */ <color name="color_view_1">#AA000000</color> <color name="color_view_2">#AB000000</color> <color name="color_view_3">#AC000000</color> <color name="color_view_4">#AD000000</color> <color name="color_view_default">#AE000000</color> /* Adapter */ enum class ViewType { TYPE1, TYPE2, TYPE3 } val colors = mapOf( ViewType.TYPE1 to R.color.color_view_1, ViewType.TYPE2 to R.color.color_view_2, ViewType.TYPE3 to R.color.color_view_3 ) /* onBindViewHolder */ val color = colors[viewType] ?: R.color.color_view_default
[ "stackoverflow", "0042097598.txt" ]
Q: Adding Analytics Event Tracking to A Tag or Div Tag? I have a button on my website that I would like to track in Google Analytics. <div id="contact_btn" class="col-xs-12 col-sm-5"> <a href="{{ ('mailto:' + job.poster.email) if request.authenticated_userid else request.route_path('login_signup') }}" class="btn btn-primary btn-block" role="button" id="gaContactBtn">Contact Poster</a> </div> From another Stack question I ran into this code; onclick="ga('send', 'event', 'button', 'click', 'contact_btn');" So I created a custom Goal in Google Analytics with the following settings. Category: button Action: click Label: gaContactBtn Value: My question is.. Can I put the code above on the A tag, or the DIV tag? Will it still work? After doing some searching I found a jQuery event tracking generator which provided me with this code. $(document).ready(function() { $("a#gaContactBtn").each(function() { var href = $(this).attr("href"); var target = $(this).attr("target"); var text = $(this).text(); $(this).click(function(event) { // when someone clicks these links event.preventDefault(); // don't open the link yet _gaq.push(["_trackEvent", "Link", "Click", text, , false]); // create a custom event setTimeout(function() { // now wait 300 milliseconds... window.open(href,(!target?"_self":target)); // ...and open the link as usual },300); }); }); }); Is this a better solution? A: The function you call called ga() can be applied from any place of the dom or the javascript after the google analytics loaded. So yes you can use it from anywhere and anytime you want...
[ "stackoverflow", "0024960490.txt" ]
Q: storing html code in mysql and render it using php? I am storing some html codes in mysql database. but when I get the codes in my PHP file, I get the html file echo-ed on my page! example html code: &lt;span style="background-color: #eeeeee;"&gt;&lt;a href="http://www.amazon.co.uk/gp/product/B00ISQWBEG/ref=as_li_tf_il?ie=UTF8&amp;camp=1634&amp;creative=6738&amp;creativeASIN=B00ISQWBEG&amp;linkCode=as2&amp;tag=wwwtrafficelb-21"&gt;&lt;img border="0" src="http://ws-eu.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;ASIN=B00ISQWBEG&amp;Format=_SL250_&amp;ID=AsinImage&amp;MarketPlace=GB&amp;ServiceVersion=20070822&amp;WS=1&amp;tag=wwwtrafficelb-21" &gt;&lt;/a&gt;&lt;img src="http://ir-uk.amazon-adsystem.com/e/ir?t=wwwtrafficelb-21&amp;l=as2&amp;o=2&amp;a=B00ISQWBEG" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt;<br> and this is how it gets displayed on my php page: <span style="background-color: #eeeeee;"><a href="http://www.amazon.co.uk/gp/product/B00ISQWBEG/ref=as_li_tf_il?ie=UTF8&camp=1634&creative=6738&creativeASIN=B00ISQWBEG&linkCode=as2&tag=wwwtrafficelb-21"><img border="0" src="http://ws-eu.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=B00ISQWBEG&Format=_SL250_&ID=AsinImage&MarketPlace=GB&ServiceVersion=20070822&WS=1&tag=wwwtrafficelb-21" ></a><img src="http://ir-uk.amazon-adsystem.com/e/ir?t=wwwtrafficelb-21&l=as2&o=2&a=B00ISQWBEG" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /> I did try this: $body2 = strip_tags($body); echo $body2; but that didn't work! could someone please help me out with this? A: You could try applying the htmlspecialchars_decode method to undo the damage that htmlspecialchars did when insert it into the database.
[ "stackoverflow", "0026428693.txt" ]
Q: load javascript and css only when needed RAILS I am learning ruby on rails and javascript. Is there anyway to load js file only when needed by the railsapp? I tried to create simple application but when I check on the log, I realize it always load all the js, even the unneeded library. I already searched it and found that it is using configuration to load a specific js only for specific pages.It's good, but I guess when we deal with a library that is used by many pages,, will make it hard to maintain. Could anyone give a good advice? thank you A: Take a look at requireJS : http://requirejs.org/ RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
[ "stackoverflow", "0020570999.txt" ]
Q: Killing linux process by piping the id I want to kill a process and I get its id with: pgrep -f "python myscript.py" I would like to call kill -s SIGINT on it, but I can't find any way to do it. (the command needs to be in one line) A: Read the man page, pgrep and pkill are the same program. Use pkill to send a signal to one or more processes which you can select in the same way as pgrep. pkill -INT -f "python myscript.py" See also this question and answer on unix.se (where this question would be a better fit). A: Try the backtick operator for evaluating a sub-command kill -s SIGINT `pgrep -f "python myscript.py"` (untested)
[ "japanese.stackexchange", "0000029795.txt" ]
Q: What is the meaning of 店頭分? I visited a shopping website, and I read 予約を含め在庫がなくなった場合、店頭分をご用意できない場合がございますことを予めご了承ください。I couldn't understand 店頭分 properly. What does it mean? A: 店頭 means "store front" and 店頭分 means " items which is sold in a shop".
[ "stackoverflow", "0048872973.txt" ]
Q: Create associative array php similar to Hashmap in java were key is string and value is list of string I have a mysql resultset as below ------------------------------------- name | sector ------------------------------------- walmart retail subway restaurant papaya retail dennys restaurant I want a php array as below ( "retail" -> "walmart, papaya" , "restaurant" -> "subway, dennys") What is the bestway to create an associative array as above. All I have till now is this. $query = "SELECT bd.businessname, bd.businesssector FROM businessdetail bd , businessoffer bo WHERE bd.id = bo.businessid and bd.isactive=1 and bo.isactive=1 GROUP BY bd.businessname, bd.businesssector"; $result = $mysqli->query($query); $resultset = array(); while ($row = $result->fetch_row()) { // create associative array } A: Use $result->fetch_assoc() instead of $result->fetch_row(), then in the while loop: $resultset[$row['businesssector']][] = $row['businessname']; After you are done iterating you'd have an associative array where the key is your business sector and the value is another array containing names of the businesses. Later you can use implode() to create a string with all the names delimited by a character of your choice OR in the while loop you can actually append to a string instead of pushing elements to the array.
[ "stackoverflow", "0035535000.txt" ]
Q: Errors installing OMake on OSX 10.10.5 I'm trying to install OMake so I can install Teyjus so I can start writing a bit of Lambda Prolog but I'm getting I'm getting a bunch of errors on OS X 10.10.5. The most current one, that I can't figure out, is: *** omake: 497/1193 targets are up to date *** omake: failed (5.99 sec, 124/124 scans, 81/94 rules, 258/1153 digests) *** omake: targets were not rebuilt because of errors: src/libmojave/lm_printf.cmx src/libmojave/lm_printf.o Has anyone run into this? Does anyone know of a fix? Would love to be able to get started. A: Inspired by your posts (here and on /r/prolog) I decided to try and build Teyjus as well, and installed OCaml and OMake along the way. The following describes the steps I took to successfully install OCaml and OMake: Installing OCaml OCaml.org said the best way to install OCaml was to go through OPAM. However, since I chose to install OPAM with homebrew, and OCaml was a prereq, I ended up with the latest version of OCaml set up after the first two of the following steps: Install opam via homebrew: Following instructions from https://opam.ocaml.org/doc/Install.html $ brew update $ brew upgrade $ brew install opam Initialize opam Following the instructions provided by the homebrew results, I ran $ opam init # then `y` to allow alterations to the shell profile and another init file $ eval `opam config env` Installing standard libraries If I'm going to have OCaml installed any how, I might as well get it set up for proper use, cause eventually I'll want to play around with OCaml itself again too. Thus, I took the advice of the OCaml installation instructions and ran $ opam install batteries core Installing OMake The OMake download page scared me. I thought, "hey, I've just installed the robust OCaml package manager, OPAM, and OMake is written in OCaml – so maybe I can find an OMake package on OPAM and dodge all those deadly bullet-points". Thus I ran $ opam show omake And saw that omake 0.9.8.6-0 was on offer, which appears to be the most recent one. So I installed it $ opam update # just to be sure ;) But all was up to date $ opam install omake That should be it! I was able to build Teyjus from source subsequently (I'll post the whole record of my steps on the reddit thread). As an FYI, adding information that answers a question you didn't ask, it looks like Teyjus binaries are also available for OSX: https://github.com/teyjus/teyjus/releases
[ "math.stackexchange", "0002849256.txt" ]
Q: If $R$ is a commutative ring with identity then $R[x_1, x_2, ..., x_n]$ is not a P.I.D.? I am working on problem $7$, section $9.1$ in Dummit & Foote: Let $R$ be a commutative ring with $1$. Prove that a polynomial ring in more than one variable over $R$ is not a principal ideal domain. My Strategy: It is enough to show it for polynomials of two variables. Then, for any polynomial ring $R[x_1, x_2, ..., x_n]$ we can view it as $R[x_1, x_2, ..., x_{n-2}] [x_{n-1}, x_n]$ (I think). And since $R[x_1, x_2, ..., x_{n-2}]$ is commutative with identity, $R[x_1, x_2, ..., x_n]$ will not be a P.I.D. The Difficulty: I am having trouble proving it for two variables. The issue is that there may be zero divisors in $R$. The previous problem in the book asked to prove that $(x, y)$ is not a principal ideal in $\mathbb{Q}[x, y]$. I proved it using the theorem that $\deg p \cdot q = \deg p + \deg q$ when there are no zero divisors in the coefficient ring. So I would like to also show that $(x,y)$ is not principal in $R[x, y]$ when $R$ is just commutative with identity, but I don't know how to get around the issue of possible zero divisors. A: If $R$ has zero divisors, then so does $R[x,y]$, whence $R[x,y]$ is not a principal ideal domain, since by definition a principle ideal domain is also an integral domain.
[ "meta.stackexchange", "0000238315.txt" ]
Q: chat.stackexchange.com's chat box does not show text as I'm typing in Chrome When I try to type in something to send, nothing happens. The caret doesn't even blink. However, if I scroll up the page and then back down, suddenly the chat box shows what I typed. Running Chrome 36.0.1985.143. Is this a known bug or could there be something interfering with the chat box? A: The culprit was the extension "ColumnCopy" v0.3.5, which I wouldn't have suspected. It disrupts the chat box.
[ "android.stackexchange", "0000010153.txt" ]
Q: The music player keeps displaying deleted songs. How do I remove them or refresh the library? I am using a Droid X with rooted Gingerbread that is otherwise stock. I have root access, but have not used it to do anything. I have inspected the /Music folder multiple times and the 500+ songs I deleted are physically not in the filesystem any more. I tried rebooting the phone multiple times. I tried deleting the Cache and data for the app in Settings > Application, as well as running SDrescan to remount and rescan the card. I even tried deleting them from the music player app itself. No matter what I try, these songs will not disappear. (Though they obviously fail when I try to play them because they don't exist) Is there a file where the Music library cache is being kept that isn't getting updated? I would love to find it and just delete it. I also use Songbird for Android, and it had the same problem. New songs show up, but the old ones will not go away at all. Though, now Songbird won't even load at all. Sometimes loading it causes the phone to reboot. I have currently uninstalled it. In addition, it causes the phone to become very unstable whenever I try to play music. Accidentally playing a non-existent song can cause the phone to crash and get stuck on a black screen, requiring a battery pull and reboot. A: What I've done in the past (and appears to have worked here, too): Go to Settings->Applications->Manage Applications Clear the data/cache for the Media Storage app (it's a system service/app) Unmount and remount your SD card via some means. Re-launching a music app after doing this will force it to rebuild the database, which can take a little bit of time but will ultimately refresh the list to reflect the most recent contents of the SD card.
[ "stackoverflow", "0061471609.txt" ]
Q: Django: How to update an Integerfield and decrement its value This seemingly innocuous problem has turned out to be quite difficult to find any information on. I just want to decrement the value of an Integerfield column by 1 in my database, by calling a function. views.py function call StudentProfile.objects.add_lesson(student_id) managers.py class StudentQuerySet(models.QuerySet): def add_lesson(self, sid): self.filter(student_id=sid).update(remaining_lessons=remaining - 1) class StudentProfileManager(models.Manager): def add_lesson(self, sid): self.get_queryset().add_lesson(sid) Full StudentProfile model class StudentProfile(models.Model): student = models.OneToOneField( User, related_name='student', primary_key=True, parent_link=True, on_delete=models.CASCADE) portrait = models.ImageField( upload_to='studentphotos', verbose_name=_('Student Photo')) about_me = models.TextField(verbose_name=_("About Me")) spoken_languages = models.CharField(max_length=255) teacher_default = models.OneToOneField( 'teachers.TeacherProfile', related_name='teacher_default', parent_link=True, on_delete=models.CASCADE, default=None, blank=True, null=True) membership_start = models.DateTimeField( verbose_name="Membership Start Date", default=now, editable=False) membership_end = models.DateTimeField( verbose_name="Membership End Date", default=now, editable=False) remaining_lessons = models.IntegerField( verbose_name="Membership remaining lessons", default=0) objects = StudentProfileManager() def __str__(self): return User.objects.get_student_name(self.student_id) I know this is totally wrong, any help is appreciated. A: I tried using the F expression, and I have no clue why, but it was decrementing by 3 instead of by 1. Maybe Django runs that code 3 times when it is called in the view. I found a solution that accomplishes this without a function, in the view, it does exactly what I expect, a decrement of 1: student_id = request.user.id student_queryset = StudentProfile.objects.get(student_id=student_id) student_queryset.remaining_lessons = student_queryset.remaining_lessons - 1 student_queryset.save()
[ "stackoverflow", "0041341527.txt" ]
Q: when hover on image or text the both scale i want when the user hover on the image or the text and the image scale.i have tried this but only one scale .top3 , .top1 { transition: all 1s ease; } .top3:hover ,.top1:hover { transform: scale(1.17); } <div class="top3" id="DSC0123"><a href=""><img src="images/DSC0123.png"></a></div> <div class="top3" id="Layer4"><a href=""><img src="images/Layer4.png"></a></div> <div class="top3" id="DSC0416"><a href=""><img src="images/DSC0416.png"></a></div> <div class="top3" id="IMG0541"><a href=""><img src="images/IMG0541.png"></a></div> <div class="top3 top3" id="DSC0331"><a href=""><img src="images/DSC03311.png"></a></div> <div class="top1 top3" id="Food"><a href="">Food</a></div> <div class="top1 top3" id="portrait"><a href="">Food</a></div> <div class="top1 top3" id="LANSCAPES"><a href="">Food</a></div> <div class="top1 top3" id="kids"><a href="">Food</a></div> <div class="top1 top3" id="SPORTS"><a href="">Food</a></div> A: The user wants BOTH to scale (the img and the text) You should put the text div inside the image div, like this: <div class="top3" id="DSC0123"> <a href=""><img src="http://www.w3schools.com/css/trolltunga.jpg" /></a> <div class="top1 top3" id="Food"> <a href="">Food</a> </div> </div> https://jsfiddle.net/933ex7pv/2/ (working fiddle) Add transform-origin: 0 0; (or some other values that you like) to make it scale in the center.
[ "es.stackoverflow", "0000333519.txt" ]
Q: Duda sobre archivo *.pro Si quiero hacer una aplicación que se pueda compilar tanto en windows como en linux, intento hacer esto en el archivo *.pro: unix { INCLUDEPATH += /usr/include/python3.6m LIBS += -L /usr/local/lib/python3.6 -lpython3.6m DEPENDPATH += /usr/include/python3.6m } win32 { INCLUDEPATH += C:\Python\Python37\include LIBS += -L C:\Python\Python37\libs -lpython37 DEPENDPATH += C:\Python\Python37\include } De forma que supuestamente busco las librerías o cabeceras en una u otra ruta, según en que ordenador esté. Sin embargo cuando estoy en linux se queja de las rutas de windows y viceversa, por lo que he de comentar las líneas que no proceden en cada caso. ¿Estoy haciendo algo mal o este es el comportamiento esperado? Gracias A: De la documentación de qmake: Scope Syntax Scopes consist of a condition followed by an opening brace on the same line, a sequence of commands and definitions, and a closing brace on a new line. The opening brace must be written on the same line as the condition. Traducción libre por mi parte: Sintaxis de los ámbitos. Un ámbito consiste en una condición seguida en la misma línea de una llave de abrir, y a continuación una secuencia de comandos y definiciones; para terminar con una llave de cerrar en una nueva línea. La llave de abrir ha de estar en la misma línea que la condición. Poco que añadir.
[ "stackoverflow", "0011206155.txt" ]
Q: Adding key/value into array where value is a object Adding key/value into array where value is a object I want to add some text as a key and Object as a value. Example $('#clickme').on('click' , function() { push to array => "some_text" as (value) and $(this) as key }) A: Just use a normal object which works as an associative array anyway: var myObj = {}; $('#clickme').on('click' , function() { myObj["some_text"] = $(this); });
[ "stackoverflow", "0040380946.txt" ]
Q: Trying to delete multiple records at once in Laravel I'm trying to make table with checkboxes where admin can check multiple products and delete them. So far I've made the form @foreach($products as $product) {{ Form::open() }} <input type="checkbox" name="delete[]" value="{{ $product->product_id }}"> <a class="btn btn-primary" href="{{ URL::to('/admin/products/multiDdelete') }}?_token={{ csrf_token() }}">Delete</a> {{ Form::close() }} @endforeach This is in my route Route::get ('/admin/products/multiDdelete', ['uses' => 'AdminController@testDelete', 'before' => 'csrf|admin']); And this in the controller public function testDelete() { $delete = Input::only('delete')['delete']; $pDel = Product::where('product_id', $delete); $pDel->delete(); return Redirect::to('/admin/test')->with('message', 'Product(s) deleted.'); } So far when I check products and hit Delete page reload and I get Product(s) deleted but products aren't deleted. I think the problem is in how I pass ID's.. but I can't figured it out. A: Your query isn't returning anything useful here. Even with ->get(), it would return a collection, which you can't use the way you want. You can add delete to your query instead: Product::whereIn('product_id', $delete)->delete();
[ "stackoverflow", "0029131293.txt" ]
Q: IIS ARR + Request Filtering? We're looking to implement load balancing for our asp.net site using IIS Application Request Routing (ARR). Weighted Round Robin seems like a decent starting point, but we would like to do something custom and we're hoping that someone out there can help point us in the right direction. We would like the ability to route certain requests to specific servers, but let the rest of the requests function like a round robin to the remaining load balanced servers. For example, consider the following five requests that come into our load balancer running ARR: 1.) https://example.com/api/myendpoint/36321 2.) https://example.com/somepage.aspx 3.) https://example.com/documents/upload.aspx 4.) https://example.com/orders/orderdetails.aspx 5.) https://example.com/anotherpage.aspx?p1=432 We would like request #1 to be routed to our api server based on the "/api/" in the url. We would like request #3 to be routed to our documents server based on the "/documents/" in the url. The other three requests should follow round robin and be distributed accordingly to our generic load balanced servers. Is this possible using ARR? If so, how would we configure it? If not, what tools are available to accomplish this? Thanks! A: If you want to stick purely to IIS then I'd follow the pattern below. The trick will be getting your rules setup, but in general you'll need 3 re-writes: Write a rule that matches ./api/. and route it to your api server. Write a rule that matches ./documents/. and route it to your documents server. Write a rule that doesn't match ./documents/. ./api/. and direct it to your round robin server farm. For the round robin you should read this article: http://www.iis.net/learn/extensions/configuring-application-request-routing-%28arr%29/http-load-balancing-using-application-request-routing and this article: http://www.iis.net/learn/extensions/configuring-application-request-routing-(arr)/define-and-configure-an-application-request-routing-server-farm To learn more about writing the rules, see: http://www.iis.net/learn/extensions/url-rewrite-module/creating-rewrite-rules-for-the-url-rewrite-module
[ "stackoverflow", "0005295045.txt" ]
Q: Whats wrong with LINQ to EF? I am using EF. This is my LINQ query public List<Tuple<int, string>> GetList() { return (from c in DALContext.MST select new Tuple<int, string>(c.CD, c.NAME)).ToList(); } When i call GetList() it throws an exception : Only parameterless constructors and initializers are supported in LINQ to Entities Instead when i rewrite this query: List<Tuple<int, string>> lst = new List<Tuple<int, string>>(); var query= (from c in DALContext.MST select new{c.CD, c.NAME}); foreach (var item in query) { lst.Add(new Tuple<int,string>(item.CD,item.NAME)); } return lst; It just works fine. Whats wrong with my first query??? A: The other answers are correct about what's going on, but I didn't see anyone mention the best way to make your code work: AsEnumerable() public List<Tuple<int, string>> GetList() { return (from c in DALContext.MST.AsEnumerable() select Tuple.Create(c.CD, c.NAME)).ToList(); } The AsEnumerable method acts as a boundary between the code that should be translated into SQL and executed in the database server, and the code that should be executed in memory after we've gotten a response from the database. Putting it right after the table name tells EF to get all the records from the MST table, and then run the following code that creates tuples from the values that are returned. I changed your new Tuple<int, string> into Tuple.Create mostly because I don't like typing generic type parameters any more than I have to. A: LINQ to EF deals with queries a bit differently than LINQ to SQL. In LINQ to EF, you can not put a constructor with parameters in a LINQ expression, like you did here in the first bit of code: from c in DALContext.MST select new Tuple<int, string>(c.CD, c.NAME) The constructor of Tuple is taking two parameters, and that is not allowed in LINQ to EF. The reason is explained here: In part this is a matter of wanting LINQ to Entities to be more explicit about the boundary between what parts of your query execute on the server and what part execute on the client. With LINQ to SQL, for instance, it is possible to write a LINQ query which not only involves data from the server and functions on the server but also functions that can only be executed on the client and to mix them in together. The LINQ to SQL provider will then do its best to untangle things and execute the parts that it can on the server and other parts on the client. This is nice because it is easy to just write whatever query you want and if at all possible it will work. On the other hand, it's not so nice if you accidentally write a query where the only part which can execute on the server is the most basic thing that returns all the data in one or more tables and then have all the filtering happen on the client (with very nasty perf consequences). With LINQ to Entities, the boundaries are more explicit. When you write a LINQ query against a LINQ to Entities IQueryable implementation, the entire query executes on the server, and if some part of the query cannot be executed on the server, then an explicit boundary must be created with something like ToQueryable() or ToList(). Once that query is executed and the data retrieved, then you can use LINQ to Objects to further refine the query if you so choose. This way you explicitly know where your boundaries are, and it's easier to track down performance issues and the like. One of the related limitations is that the select statement in LINQ to Entities can create anonymous types or other types as long as they have a default constructor and settable parameters. This minimizes the chance that the select statement has major side effects.
[ "stackoverflow", "0031170495.txt" ]
Q: Angular Charts cannot get labels working how i need I'm creating a chart with angular charts, and am having problems getting the chart how i need. I would like the x axis to have the date and the mouse over to show the client name, which are all being fed from a loop on an array of resource object. Here is the loop: angular.forEach(charts, function(chart, key) { var d = new Date(chart.appointment_date).toDateString(); $scope.labels.push(d); $scope.total_earnings += chart.cost.dollars; $scope.data[0].push(chart.cost.dollars); if (!chart.refundObj[0]){ $scope.data[1].push(0); } else { $scope.data[1].push((chart.refundObj[0].amount/100)); } }); And but this only sets the date property on the x axis, as well as in the mouse over. If i create an object using the following: $scope.labels.push({date: d, name: clientName}); the result only says [Object, Object]. I'm using the following as the basis for the charts: http://jtblin.github.io/angular-chart.js/#getting_started A: angular-chart is based on Chart.js. Chart.js expects an array of strings for labels. When you insert an object Chart.js converts it to a string using toString which for an object becomes [Object, Object] when toString is not defined. It's pretty simple get what you want by constructing the right object and setting an option. HTML <div ng-app="app"> <div ng-controller="ctrlr"> <canvas id="line" class="chart chart-line" data="data" labels="labels" options="options"></canvas> </div> </div> JS Here we construct a special object SpecialLabel that returns the axis label when toString is called. We also override the tooltipTemplate to return tooltipLabel when constructing the tooltip var app = angular.module('app', ['chart.js']); app.controller('ctrlr', ['$scope', function ($scope) { var SpecialLabel = function (axisLabel, tooltipLabel) { this.axisLabel = axisLabel; this.tooltipLabel = tooltipLabel; } SpecialLabel.prototype.toString = function () { return this.axisLabel } $scope.labels = [ new SpecialLabel("10-Jan", "Client 1"), new SpecialLabel("11-Jan", "Client 2"), new SpecialLabel("12-Jan", "Client 3"), new SpecialLabel("13-Jan", "Client 4"), new SpecialLabel("14-Jan", "Client 5"), new SpecialLabel("15-Jan", "Client 6"), new SpecialLabel("16-Jan", "Client 7")]; $scope.data = [ [65, 59, 80, 81, 56, 55, 40] ]; $scope.options = { tooltipTemplate: "<%if (label){%><%=label.tooltipLabel%>: <%}%><%= value %>" } }]) Fiddle - http://jsfiddle.net/xg2pd1cu/
[ "stackoverflow", "0027553004.txt" ]
Q: How to save state of a JFrame java 1.6 How would I make it so when my frame is closed it saves itself, and if started again it continues from where it was last. I am coding in Java 1.6 on eclipse A: There is no automatic way to save the state of a window and all of it's components. You have to do it manually. Usually this is done with config files. When the frame closes, you store all of it's components values in a file, and when the frame opens it reads that file and reloads the component's values. Take a look at Properties, something perfectly fit for that need. here is a good tutorial to start with: http://www.mkyong.com/java/java-properties-file-examples/
[ "stackoverflow", "0022701330.txt" ]
Q: Where are my files on a new ec2 instance? I need to install appscale on a fresh AMI instance. I logged in as ec2-user and created a new folder with mkdir ec2. Now, when i ftp into the server i cannot fine my new folder called ec2. Anyone know where to look? Thanks A: ec2-user directory is in /home/ec2-user Be sure you are using the same user for SSH and FTP. On a security point of view, I would discourage to use FTP as it is sending password in clear text. SCP is recommended.
[ "stackoverflow", "0054646079.txt" ]
Q: my query not null select even with null in mysql database what is the correct syntax here? Why doesn't my Sql-statement select only not null values? I only want to select the not null values from empsched My data table This is my query: SELECT empID, FirstName, MiddleName, LastName, Gender, Address, Zipcode, Position, Rate, DateHired, TelNo, empSched, Pstatus, image, Red FROM employee WHERE empSched IS NOT NULL A: Since your empSched column is not null it gives you all the rows. you can try like this: SELECT empID, FirstName, MiddleName, LastName, Gender, Address, Zipcode, Position, Rate, DateHired, TelNo, empSched, Pstatus, image, Red FROM employee WHERE empSched IS NOT NULL and empSched <> ''
[ "math.stackexchange", "0001669306.txt" ]
Q: Area of a triangle with vertices $p_{1}(x_{1},y_{1}), p_{2}(x_{2},y_{2}), p_{3}(x_{3},y_{3})$ The formula to find the area of such a triangle is $\frac{1}{2} \begin{vmatrix} x_{1} & y_{1} & 1 \\ x_{2} & y_{2} & 1 \\ x_{3} & y_{3} & 1 \\ \end{vmatrix}$ when the triangle is traversed counterclockwise from $p_{1}$ to $p_{2}$ to $p_{3}$. And my textbook says the area would be negative if the direction is clockwise. Why does the direction have to be counterclockwise in order to get a positive answer? A: If you carefully draw a picture and do some algebra you will find that $$\eqalign{ x_3-x_1&=r((x_2-x_1)\cos\theta-(y_2-y_1)\sin\theta)\cr y_3-y_1&=r((x_2-x_1)\sin\theta+(y_2-y_1)\cos\theta)\cr}$$ for some positive factor $r$ and some angle $\theta$ with $-\pi<\theta<\pi$. You will also observe that the triangle goes couterclockwise if $\theta$ is positive, clockwise if $\theta$ is negative. If you now carefully work out your determinant, starting with $$\frac12\left|\matrix{x_1&x_2&1\cr x_2&y_2&1\cr x_3&y_3&1\cr}\right| =\frac12\left|\matrix{x_1&y_1&1\cr x_2-x_1&y_2-y_1&0\cr x_3-x_1&y_3-y_1&0\cr}\right|$$ and substituting the above formulae, you will get the result $$\tfrac12r\bigl((x_2-x_1)^2+(y_2-y_1)^2\bigr)\sin\theta\ .$$ In this formula everything is positive except for the $\sin\theta$, which is positive if $\theta$ is positive and negative if $\theta$ is negative. So the determinant is positive if the triangle is counterclockwise, negative if it is clockwise.
[ "rpg.stackexchange", "0000115755.txt" ]
Q: Can I resist damage from Fireball spell, if I have fire resistance trait? Can I reduce fire damage from spells, if I have fire resistance? Or does it only help with non-magic damage? If the latter is right, what does the Elemental Adept feat mean "Spells you cast ignore resistance to damage", if damage from spells is already magical? A: Fire resistance applies to any and all damage that’s called fire. This is described on page 197 of Player’s Handbook: If a creature or an object has resistance to a damage type, damage of that type is halved against it. No ifs, ands, or buts here; damage of the indicated type is halved. So if your resistance says fire, and the spells says fire, the spell does half damage. Elemental Adept defeats that protection, however. Later in that same section, Player’s Handbook even includes an example of fire resistance explicitly combined with nonmagical resistance: Multiple instances of resistance or vulnerability that affect the same damage type count as only one instance. For example, if a creature has resistance to fire damage as well as resistance to nonmagical damage, the damage of a nonmagical fire is reduced by half against that creature, not reduced by three-quarters. This example would not make very much sense if fire resistance only worked for nonmagical fire, because then the fire resistance would be completely redundant.
[ "stackoverflow", "0026446922.txt" ]
Q: What is the difference between handler( ChannelHandler c) and childHandler( ChannelHandler c) for ServerBootstrap? I am new to Netty. One thing I find confusing is that ServerBootstrap has two methods: handler( ChannelHandler c), which is inherited from AbstractBootstrap, and childHandler( ChannelHandler c), both of which seem to be doing the same thing, based on the javadoc. So, is that true? Are there any differences between the two methods? A: The handler, which is defined in the AbstractBootstrap is used when writing Netty based clients. When writing netty based servers, that can work upon multiple accepted channels, use a child handler which will handle I/O and data for the accepted channes, by using childHandler as defined in the ServerBootstrap.
[ "stackoverflow", "0058479730.txt" ]
Q: Error When SignOut Users - invertase React Native Firebase I'm trying to signOut users from My App, but I'm having this message from console. Possible Unhandled Promise Rejection (id: 1): TypeError: undefined is not an object (evaluating '_auth.firebase.auth.currentUser.signOut') following documentation (https://invertase.io/oss/react-native-firebase/v6/auth/reference/module#signOut) I made a function like this async function LogoutUser() { firebase.auth.currentUser.signOut(); } but nothing happens with user Account. Please, could anyone help me? A: signOut is function of auth. try below code firebase.auth().signOut().then(function(){ console.log('Signed Out'); },function(error){ });
[ "stackoverflow", "0011524026.txt" ]
Q: Django Admin Individual Access I have a phonebook application - an internal app in our org. I am investigating whether its possible to allow employees update their own record. Does djangos auth system allow access to only your own details. IE - if i looked up Active Directory for their username, and it corresponds to the username I have - then let them edit. A: This is not supported directly in the admin interface. If you're talking about editing django.contrib.auth.models.User then I'd recommend just using a regular view instead of the admin interface. You may be able to inject custom validation to check that the request.user == user but it's hacky. If you're talking about editing a UserProfile object then it's easier to add custom validation to the admin form to check for authorization.
[ "stackoverflow", "0004340972.txt" ]
Q: Best Rails 3 XML parser Which XML library, GEM would you recommend to use with Rails 3? A: Nokogiri is widely used.
[ "pt.stackoverflow", "0000332934.txt" ]
Q: Finalizar o script PHP com "exit" deletaria todas as variáveis e destrói objetos? Olá, no PHP usando as funções unset($variavel) eu deleto a $variavel, no $Objeto->__destruct eu destruo mas ainda sim uso unset($Objeto). Minha duvida é, caso eu use a função exit sem deletar ou destruir nada... a finalização do script deletaria tudo que foi iniciado ou não ? como isso faz diferença e qual importância de deletar tudo que foi chamado ou vamos dizer criado (variáveis, array e objetos)? A: SIM. Está no manual: http://php.net/manual/en/function.exit.php (pra variar, em português faltam pedaços importantes na tradução) exit — Output a message and terminate the current script Description void exit ([ string $status ] ) void exit ( int $status ) Terminates execution of the script. Shutdown functions and object destructors will always be executed even if exit is called. A parte grifada é mais ou menos isto: Funções de encerramento e destrutores de objeto são sempre executados, mesmo se usado exit ("Mesmo usado exit", pois isto ocorre ao final do script, de qualquer forma) Resumo: usar exit ou seu sinônimo die dá na mesma que o script acabar "naturalmente". São liberados todos os recursos (o que é uma das razões para OOP em PHP ser um desperdício de recursos, cada requisição tem que recriar tudo quanto é classe de novo pra poder usar). Outra coisa, unset não é coisa normal de se usar em PHP. Tem que ter uma razão muito boa pra isso, em situações muito específicas. Em condições normais o PHP, como a maior parte das linguagens de script, gerencia a memória para você. Um exemplo de uso válido do unset é o mencionado pelo colega Jorge Matheus nos comentários, quando se aplica a uma variável da $_SESSION. Isto porque aí já não se trata mais de memória, e sim de dados que são gravados normalmente no disco, para que o próximo script recupere. Aí faz sentido limpar, pois é algo que o PHP vai gravar no encerramento, e se é algo não mais desejável, não tem razão de preservar a informação. Ainda assim, vale a observação sobre OOP feita antes, pois um objeto persistido na session precisa ser lido do arquivo ou DB, e de-serializado para se transformar em objeto de novo.
[ "stackoverflow", "0059705656.txt" ]
Q: What is the difference between a Pod and a Job resources in k8s? Is Pod and Job resource the same ? apiVersion: v1 kind: Pod metadata: name: "" labels: or apiVersion: v1 kind: Job metadata: name: "" labels: The Job will still create a pod I think. Just wondering when do I use one instead of the other. A: Pod is basic unit to express a runnable process on Kubernetes. Job is a higher level abstraction that uses pods to run a completable task. You might be thinking of using a pod with restartPolicy: Never to run a completable task. But in the event of node failure, pod on that node managed by Job are rescheduled to other node but an unmanaged pod is not. Job also has extra features like completions and parallelism using which you can run multiple instances.
[ "stackoverflow", "0020784632.txt" ]
Q: RabbitMQ client hanging up in channel.close() and connection.close() I am using amqp-client in java but JVM hangs up infinitely while closing channel. If I remove channel.close() it jvm hang up infinitely on connection.close(). I went through API classes and saw that in both cases RabbitMQ API take timeout as infinite an it just waits reply. Please tell if their is any workaround to this. I am using amqp-client-3.1.3. Many thanks. A: Finally I figure out the solution to the problem Memory of the rabbitmq server was full. It started working as soon as i cleared it.
[ "stackoverflow", "0046657324.txt" ]
Q: regex search and delete everything in brackets <> Just learning vim and trying to delete everything between brackets <>. Tried %s/<*>//g but that just deletes the ending > bracket. I want to delete everything between and including the <> tags A: * is a modifier -- it doesn't match text by itself, it modifies the immediately previous thing to match zero or more times. So your pattern will match zero or more < characters followed by a single > -- > or <> or <<> or <<<<<<<<>, but not if there's anything else between the <>. To match any character, the special pattern . matches any single character. So you could use %s/<.*>/, except that will cause problems if you have multiple tags on a line -- it will match the < of the first tag and the > of the last tag and delete them and everything in between. Since tags can't be nested (you can't have a > or < inside a tag), you can get around this by using any "anything but" pattern: %s/<[^>]*>//g
[ "superuser", "0000962290.txt" ]
Q: How to disable calculator in windows? I have a key on my keyboard that brings it up, and I hit all of the time accidentally. It's a proprietary Logitech Calculator key, and their own program doesn't let you remap it. This seems to be a hard problem that many people are failing at solving - the google results were awful. Apparently if you munge the EXE file windows will just fix it against your will. A: The answer is Applocker. Start=>Run=>secpol.msc Security Settings=>Application Control Policies=>Applocker Add new rule (type=path) to deny everyone %SYSTEM32%\calc.exe Make sure to let it create the default rules it "wants" to create when you do this.
[ "stackoverflow", "0016348466.txt" ]
Q: How to reference .jar from other project with ant? I have project A. A needs to refernce the android support library which I have in project B. I would think it should be as easy as adding a class path entry such as: <classpathentry kind="lib" path="../B/libs/android-support-v4.jar"/> For some reason, this is not working. It works fine from within Eclipse, but not from ant. Any suggestions? Note: Both A & B are Android library projects -- not sure if this is what is causing the issue. A: A needs to refernce the android support library which I have in project B Unless A itself depends upon B, please put a copy of the Android Support package JAR in A's libs/ directory. So long as A and B have the same JAR for the same name, when Android builds an app that uses A and B, it will only use one copy of the JAR.
[ "stackoverflow", "0017692638.txt" ]
Q: Func<> getting the parameter info How to get the value of the passed parameter of the Func<> Lambda in C# IEnumerable<AccountSummary> _data = await accountRepo.GetAsync(); string _query = "1011"; Accounts = _data.Filter(p => p.AccountNumber == _query); and this is my extension method public static ObservableCollection<T> Filter<T>(this IEnumerable<T> collection, Func<T, bool> predicate) { string _target = predicate.Target.ToString(); // i want to get the value of query here.. , i expect "1011" throw new NotImplementedException(); } I want to get the value of query inside the Filter extension method assigned to _target A: If you want to get the parameter you will have to pass expression. By passing a "Func" you will pass the compiled lambda, so you cannot access the expression tree any more. public static class FilterStatic { // passing expression, accessing value public static IEnumerable<T> Filter<T>(this IEnumerable<T> collection, Expression<Func<T, bool>> predicate) { var binExpr = predicate.Body as BinaryExpression; var value = binExpr.Right; var func = predicate.Compile(); return collection.Where(func); } // passing Func public static IEnumerable<T> Filter2<T>(this IEnumerable<T> collection, Func<T, bool> predicate) { return collection.Where(predicate); } } Testmethod var accountList = new List<Account> { new Account { Name = "Acc1" }, new Account { Name = "Acc2" }, new Account { Name = "Acc3" }, }; var result = accountList.Filter(p => p.Name == "Acc2"); // passing expression var result2 = accountList.Filter2(p => p.Name == "Acc2"); // passing function
[ "stackoverflow", "0014739144.txt" ]
Q: TFS express edition - installing on a server or local machine? This is how we have TFS express edition set up among 5 developers. We have our lead programmer install TFS 2012 Express edition on his machine. That comes with an install of SQL Server Express 2012 editions. Remaining 4 developers also install TFS Express and SQL Server express 2012 on their respective machines. From inside Visual studio of their individual machines, the 4 developers connect to lead programmers path of tfs code. Is this the right set up? I am thinking, if the lead developer turns off his machine, the code db also goes down and hence the other developers can no longer access the source repository? is that correct? To avoid this happening, do I need to install TFS 2012 express edition on its own dedicated server box and have all 5 developers connect to it, so atleast the server will be accessible all the time. Am I thinking correctly? please advise. A: TFS is the server software, and Visual Studio is the client software. To use TFS, you would typically install the TFS server (including SQL etc) on one computer, and then all your developers would connect to it from their installs of Visual Studio. The developers should not install TFS on their own PCs. If you turn off the TFS computer, then the server will not be running, so none of the developers will be able to access it - they will not be able to use source control, report bugs, etc without it. However, they can work "offline" until the server is turned back on - as long as they have the code they need on their PC, they do not need the server running. Most people would recommend using a dedicated PC as the TFS server - it's not really a good idea to use the server as a develolpment PC. For 5 users the load on the server will be very low, so it will not need to be a particularly powerful PC in order to run SQL and TFS, as long as it has plenty of disk space for its source control databases (preferably with redundant RAID and/or a decent backup solution so you won't lose all your source code if the server fails). I suggest you do some more reading up on TFS to get a better idea about how it works before you start installing it - it's a serious/complex bit of software and you'll need to follow the installation instructions carefully.
[ "stackoverflow", "0017128762.txt" ]
Q: can't get php const value to work in pdo initialization I am defining constants in a class class config { const DB_PDO_Connect = "'mysql:host=localhost;dbname=XdbX','XuserX','XpwX'"; } In another class I try to create a new PDO object class user { function login() { $db = new PDO(config::DB_PDO_Connect); After that line, $db is not an object so something is not working, but if I replace it with; class user { function login() { $db = new PDO('mysql:host=localhost;dbname=XdbX','XuserX','XpwX'); (copy and paste the string from the config class) it works. I can echo config::DB_PDO_Connect so it can read it, the PDO just doesn't like it. A: What you've actually done there is this: $db = new PDO("'mysql:host=localhost;dbname=XdbX','XuserX','XpwX'"); Note that you've only actually passed in one parameter (which is in an unexpected format) and the last two are missing. Architectural decisions aside (because you should really have a DB class to manage DB connections, and it's better to keep your config in its own file) why not add those two params to your config class? class config { const PDO_DB = 'mysql:host=localhost;dbname=XdbX'; const PDO_USER = 'XuserX'; const PDO_PASS = 'XpwX'; } Then you can: $db = new PDO(config::PDO_DB, config::PDO_USER, config::PDO_PASS);
[ "unix.stackexchange", "0000047773.txt" ]
Q: Rebinding "clear prompt" in mutt By default, when entering information at the command prompt in mutt, you can clear the prompt with Ctrlg, as described in the manual: ^G n/a abort I have been trying to bind this function to Escape. Unfortunately, abort is not listed in the available functions, either in the manual, or in the source. I have tried using this in my .muttrc: bind editor <esc> abort but it throws an error: Error in /home/jason/.mutt/muttrc, line 143: abort: no such function in map I have tried using a different map, like (generic) and experimented with other fictitious functions, like clear, to no avail. How would I bind Escape to clear the prompt line? A: mutt It's not possible with key bindings. Ctrl-G is hardcoded in mutt at a lower level than the macro or keybinding processing (see mutt_getch() in mutt's source code, at the core of all user input in mutt that returns an error upon ^G). macro editor \e '^G' wouldn't work either. What you can do is configure your terminal to send ^G upon pressing Escape With xterm: xterm -xrm 'XTerm.VT100.translations: #override <KeyPress> Escape: string(0x7)' If you're using screen, you can also do screen -X bindkey $'\e' stuff $'\a' before calling mutt and restore it afterwards (unfortunately, it doesn't seem you can have per screen window key bindings in screen). Also, it's going to be a problem if your editor for email messages is vi. neomutt Since release 20200313 There's $abort_key config variable to change the default Ctrl-G.
[ "stackoverflow", "0044749110.txt" ]
Q: Get inner object from array I have a component called MovieSearchComponent. This imports a service MovieSearchService and a model Movie. @Component({ selector: 'movie_search', templateUrl: './movie_search-component.html', providers: [MovieSearchService] }) export class MovieSearchComponent{ movies: Movie[] = []; constructor(private movieSearchService: MovieSearchService){}; ngOnInit(){ this.getMovies(); } getMovies(){ this.movieSearchService.getMovies() .subscribe((response)=>{ this.movies = response; console.log(this.movies) }); } } The service. import {Movie} from "../movie"; @Injectable() export class MovieSearchService{ private results = {}; private api = '***7039633f2065942cd8a28d7cadad4'; private url = 'https://api.themoviedb.org/3/search/movie?api_key=' + this.api + '&language=en-US&query=Batman&page=1&include_adult=false;'; constructor(private http: Http){} getMovies(): Observable<Movie[]>{ return this.http.get(this.url) .map(res => res.json()) } } The template: <div> <ul> <li *ngFor="let movie of movies.results"> {{ movie.title }} </li> </ul> </div> This does show all the titles from the movies that are returned from the service. But I have to select the result array which has all the movie objects in the template, which doesn't look right to me. When I change the console.log(this.movies) to console.log(this.movies.results) in the MovieSearchComponent I get the error property 'results' does not exist on type Movie[]. This is the movie model: export class Movie{ constructor( public id: number, public title: string, ){} } So why can't I use console.log(this.movies.results) when I can use it in the template. A: Because results is not defined in Movie Class. Change your getMovies method to: getMovies(): Observable<Movie[]>{ return this.http.get(this.url) .map(res => res.json().results) }
[ "stackoverflow", "0055964853.txt" ]
Q: Tensorflow 1.13.1 tf.data map multiple images with a single row together I'm building my tf dataset where there are multiple inputs (images and numerical/categorical data). The problem I am having is that multiple images correspond to the same row in the pd.Dataframe I have. I am doing regression. So how, (even when shuffling all the inputs) do I ensure that each image gets mapped to the correct row? Again, say I have 10 rows, and 100 images, with 10 images corresponding to a particular row. Now we shuffle the dataset, and we want to make sure that the shuffled images all correspond to their respective row. I am using tf.data.Dataset to do this. I also have a directory structure such that the folder name corresponds to an element in the DataFrame, which is what I was thinking of using if I knew how to do the mapping i.e. folder1 would be in the df with cols like dir_name, feature1, feature2, .... Naturally, the dir_names should not be passed as data into the model to fit on. #images path_ds = tf.data.Dataset.from_tensor_slices(paths) image_ds = path_ds.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE) #numerical&categorical features. First remove the dirs x_train_input = X_train[X_train.columns.difference(['dir_name'])] x_train_input=np.expand_dims(x_train_input, axis=1) text_ds = tf.data.Dataset.from_tensor_slices(x_train_input) #labels, y_train's cols are: 'label' and 'dir_name' label_ds = tf.data.Dataset.from_tensor_slices( tf.cast(y_train['label'], tf.float32)) # test creation of dataset without prior shuffling. xtrain_ = tf.data.Dataset.zip((image_ds, text_ds)) model_ds = tf.data.Dataset.zip((xtrain_, label_ds)) # Shuffling BATCH_SIZE = 64 # Setting a shuffle buffer size as large as the dataset ensures that # data is completely shuffled ds = model_ds.shuffle(buffer_size=len(paths)) ds = ds.repeat() ds = ds.batch(BATCH_SIZE) # prefetch lets the dataset fetch batches in the background while the # model is training # ds = ds.prefetch(buffer_size=AUTOTUNE) ds = ds.prefetch(buffer_size=BATCH_SIZE) A: My solution would be to utilize TFRecords for storing the data and holding it's integrity. This will also open doors for other efficiencies as well. What the below code is doing... Create dummy data. All need to be arrays with the same datatype found in the _parse_function. You can change that dtype, just also ensure you change it for your data too. Create a dictionary that holds the arrays by name Create feature_dimensions object that holds the shape of all arrays Create TFRecords by looping over data dict. You can create one large file, or many small ones. This is a good starting point for you however. Declare functions for generating the dataset. You can add and modify whatever logic you want there. The key, however, is that these functions use the feature_dimensions object to remember how to put the data back together Create a dataset Generate a sample. The result is a dictionary with a batch-size worth of data. You should be able to just run this sample code all by itself and have no issues. Then just make the changes you need for it to work in your problem. import tensorflow as tf import pandas as pd import numpy as np from functools import partial # Create dummy data, TODO replace with your own logic # 10 images per row in DF images_per_example = 10 examples = 200 # Save name for TFRecords, you can create multiple and pass a list of the names as well save_name = "my_tfrecords.tfrecords" # DF, dataframe with random categorical data x_data = pd.DataFrame(data=(np.random.normal(size=(examples, 50)) > 0).astype(np.float32)) y_data = np.random.uniform(0, 1, size=(examples, )).reshape(-1, 1).astype(np.float32) def load_and_preprocess_image(file): # For dummy purposes generating instead of loading img = np.random.uniform(high=255, low=0, size=(15, 15)) return (img / 255.).astype(np.float32) # I would preprocess your images prior to creating the tfrecords file img_data = np.array([[load_and_preprocess_image("add_logic") for j in range(images_per_example)] for k in range(examples)]) # Prepare for tfrecords data_dict = dict() data_dict["images"] = img_data # Already an array data_dict["x_data"] = x_data.values # Ensure it's an array data_dict["y_data"] = y_data # Already an array # Remember the dimensions for later restoration, replacing number of examples with -1 feature_dimensions = {k: v.shape for k, v in data_dict.items()} feature_dimensions = {k: tuple([-1] + list(v[1:])) for k, v in feature_dimensions.items()} def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) writer = tf.python_io.TFRecordWriter(save_name) # Create TFRecords file for i in range(examples): example_dict = dict() # New dictionary for each single example for name, data in data_dict.items(): # if name == "images": # break example_dict[name] = data[i] # Define the features of your tfrecord feature = {k: _bytes_feature(tf.compat.as_bytes(v.tostring())) for k, v in example_dict.items()} # Serialize to string and write to file example = tf.train.Example(features=tf.train.Features(feature=feature)) writer.write(example.SerializeToString()) writer.close() # Declare functions for creating dataset def _parse_function(proto, feature_dimensions_: dict): # define your tfrecord again. Remember that you saved your image as a string. keys_to_features = {k: tf.FixedLenFeature([], tf.string) for k in feature_dimensions_.keys()} # Load one example parsed_features = tf.parse_single_example(proto, keys_to_features) # Split data for k, v in parsed_features.items(): parsed_features[k] = tf.decode_raw(v, tf.float32) return parsed_features def create_tf_dataset(file_paths: str, feature_dimensions_: dict, batch_size=64): # This works with arrays as well dataset = tf.data.TFRecordDataset(file_paths) # Maps the parser on every filepath in the array. You can set the number of parallel loaders here parse_function = partial(_parse_function, feature_dimensions_=feature_dimensions_) dataset = dataset.map(parse_function, num_parallel_calls=1) # This dataset will go on forever dataset = dataset.repeat() # Set the number of datapoints you want to load and shuffle dataset = dataset.shuffle(batch_size) # Put whatever you want here # Set the batchsize dataset = dataset.batch(batch_size) # Set up a pipeline dataset = dataset.prefetch(batch_size) # Put whatever you want here # Create an iterator iterator = dataset.make_one_shot_iterator() # Create your tf representation of the iterator parsed_features = iterator.get_next() # Reshape arrays and cast to float for k, v in parsed_features.items(): parsed_features[k] = tf.reshape(v, feature_dimensions_[k]) for k, v in parsed_features.items(): parsed_features[k] = tf.cast(v, tf.float32) return parsed_features # Create dataset ds = create_tf_dataset(save_name, feature_dimensions, batch_size=64) # The final result is a dictionary with the names used above sample = tf.Session().run(ds) print("Sample Length:", len(sample)) print("Sample Keys:", sample.keys()) print("images shape:", sample["images"].shape) print("x_data shape:", sample["x_data"].shape) print("y_data shape:", sample["y_data"].shape) Printed Results Sample Length: 3 Sample Keys: dict_keys(['images', 'x_data', 'y_data']) images shape: (64, 10, 15, 15) x_data shape: (64, 50) y_data shape: (64, 1)
[ "stackoverflow", "0032154387.txt" ]
Q: Why is the mutable reference not moved here? I was under the impression that mutable references (i.e. &mut T) are always moved. That makes perfect sense, since they allow exclusive mutable access. In the following piece of code I assign a mutable reference to another mutable reference and the original is moved. As a result I cannot use the original any more: let mut value = 900; let r_original = &mut value; let r_new = r_original; *r_original; // error: use of moved value *r_original If I have a function like this: fn make_move(_: &mut i32) { } and modify my original example to look like this: let mut value = 900; let r_original = &mut value; make_move(r_original); *r_original; // no complain I would expect that the mutable reference r_original is moved when I call the function make_move with it. However that does not happen. I am still able to use the reference after the call. If I use a generic function make_move_gen: fn make_move_gen<T>(_: T) { } and call it like this: let mut value = 900; let r_original = &mut value; make_move_gen(r_original); *r_original; // error: use of moved value *r_original The reference is moved again and therefore the program behaves as I would expect. Why is the reference not moved when calling the function make_move? Code example A: There might actually be a good reason for this. &mut T isn't actually a type: all borrows are parametrized by some (potentially inexpressible) lifetime. When one writes fn move_try(val: &mut ()) { { let new = val; } *val } fn main() { move_try(&mut ()); } the type inference engine infers typeof new == typeof val, so they share the original lifetime. This means the borrow from new does not end until the borrow from val does. This means it's equivalent to fn move_try<'a>(val: &'a mut ()) { { let new: &'a mut _ = val; } *val } fn main() { move_try(&mut ()); } However, when you write fn move_try(val: &mut ()) { { let new: &mut _ = val; } *val } fn main() { move_try(&mut ()); } a cast happens - the same kind of thing that lets you cast away pointer mutability. This means that the lifetime is some (seemingly unspecifiable) 'b < 'a. This involves a cast, and thus a reborrow, and so the reborrow is able to fall out of scope. An always-reborrow rule would probably be nicer, but explicit declaration isn't too problematic. A: I asked something along those lines here. It seems that in some (many?) cases, instead of a move, a re-borrow takes place. Memory safety is not violated, only the "moved" value is still around. I could not find any docs on that behavior either. @Levans opened a github issue here, although I'm not entirely convinced this is just a doc issue: dependably moving out of a &mut reference seems central to Rust's approach of ownership.
[ "mathematica.stackexchange", "0000115721.txt" ]
Q: zooming out and adding text to revolutionplot3D I am trying to work some details for to the following animation: Animate[RevolutionPlot3D[Sin[x],{x,0,u},Axes->False,Mesh->5,MeshStyle->Thick, ViewPoint->Front,RevolutionAxis->{1,0,0},ViewVertical->{-1,0,0}, BoxRatios->1],{u,0,Pi},AnimationRepetitions->1] So I am interested in: completely removing the box zooming out; as you see here the animation starts with showing the top half of the spheroid and then it gets squeezed upwards as the rest of the spheroid comes in. I want both the top and the bottom points to be inside the screen at the same time. I want to add text to the top and the bottom point and add other features around the shape, like arrows, etc. I appreciate any advice that you might have. A: I'm always of the opinion that you should make a List of images that you then feed to ListAnimate rather than just giving the image function to Animate. The problem is how Animate deals with errors can really hog up your resources, and have it spitting out error messages all over the place. This is just a proof-of-principle, you will need to adjust it to suit your needs. What I'm doing here is using a function to spit out the PlotRange, this function interpolates between zoomed really close and zoomed out to show the whole plot. plot = RevolutionPlot3D[Sin[x], {x, 0, \[Pi]}, Axes -> False, Mesh -> 5, MeshStyle -> Thick, ViewPoint -> Front, RevolutionAxis -> {1, 0, 0}, ViewVertical -> {-1, 0, 0}, BoxRatios -> 1, PlotPoints -> 80, Boxed -> False]; zoomfunc = Interpolation[{{0, {{0, .1}, {-.1, .1}, {-.1, .1}}}, {1, {{-.1, 3.3}, {-1.1, 1.1}, {-1.1, 1.1}}}}, InterpolationOrder -> 1]; imglist = Show[plot , Graphics3D[Text[Style["This is the top", 22], {-0.25, 0, 0}]] , Graphics3D[Text[Style["This is the bottom", 22], {3.25, 0, 0}]], PlotRange -> zoomfunc[#], ImagePadding -> None] & /@ Subdivide[30]; ListAnimate[imglist, AnimationRepetitions -> 1]
[ "stackoverflow", "0012156756.txt" ]
Q: "stack overflow on call to Landroid/database/sqlite/SQLiteOpenHelper;.:VLLLI" New to both Android development and Java, trying to separate my queries into query / command files which inherit from a database managing QueryBase.java file. When I run my application I get the following error: 08-28 09:31:02.266: I/dalvikvm(536): threadid=1: stack overflow on call to Landroid/database/sqlite/SQLiteOpenHelper;.<init>:VLLLI 08-28 09:31:02.266: I/dalvikvm(536): method requires 32+20+8=60 bytes, fp is 0x432d1318 (24 left) 08-28 09:31:02.266: I/dalvikvm(536): expanding stack end (0x432d1300 to 0x432d1000) 08-28 09:31:02.266: I/dalvikvm(536): Shrank stack (to 0x432d1300, curFrame is 0x432d3eb8) 08-28 09:31:02.266: D/AndroidRuntime(536): Shutting down VM 08-28 09:31:02.266: W/dalvikvm(536): threadid=1: thread exiting with uncaught exception (group=0x4001d800) 08-28 09:31:02.356: D/dalvikvm(536): GC_FOR_MALLOC freed 4131 objects / 329392 bytes in 47ms 08-28 09:31:02.366: E/AndroidRuntime(536): FATAL EXCEPTION: main 08-28 09:31:02.366: E/AndroidRuntime(536): java.lang.StackOverflowError 08-28 09:31:02.366: E/AndroidRuntime(536): at com.childsoft.icantalk.queries.QueryBase.<init>(QueryBase.java:18) I've never actually run into a stack overflow error before! I'm unsure how to rectify this hrrrm. I have a seperate SchemaHelper which generates my database - working fine. My QueryBase.java looks like this: public class QueryBase extends SQLiteOpenHelper { private static final String DATABASE_NAME = "icantalk.db"; private static final int DATABASE_VERSION = 1; protected SQLiteDatabase sqdb; protected QueryBase sqh; public QueryBase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.sqh = new QueryBase(context); this.sqdb = sqh.getWritableDatabase(); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } Line 18 on QueryBase is this: super(context, DATABASE_NAME, null, DATABASE_VERSION); An example command file that inherits from QueryBase looks like this: public class ChildCommands extends QueryBase { public ChildCommands(Context context) { super(context); } public long addChild(String name) { ContentValues cv = new ContentValues(); cv.put(ChildrenTable.NAME, name); SQLiteDatabase sd = super.getWritableDatabase(); long result = sd.insert(ChildrenTable.TABLE_NAME, ChildrenTable.NAME, cv); return result; } } And an example call on this method would look something like: private ChildCommands command; ..... this.command = new ChildCommands(this); command.addChild(childsNameValue); A: public QueryBase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.sqh = new QueryBase(context); this.sqdb = sqh.getWritableDatabase(); } This results in creating a new object of QueryBase while creating a new object of QueryBase. This is a never ending call. Use this: public QueryBase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.sqh = this; this.sqdb = sqh.getWritableDatabase(); } Edit: btw sqh is not needed as this variable contains the same instance it is located in (non static!) so sqh == this...
[ "meta.stackexchange", "0000058025.txt" ]
Q: Should you be able to vote for your own tag synonym proposals? You seem to be able to vote for your own tag synonym proposals. Is this a bug or by design? (My proposal noframework/no-framework that I voted on) A: No this is not by design and should not be allowed. I think there was a miscommunication on our team here.
[ "stackoverflow", "0001506451.txt" ]
Q: How to direct subdomains to the correct JBoss App? new to JBoss and am configuring some applications. I know how to do this in apache webserver, but not using Jboss. I have successfully deployed 3 applications on a redhat box, JBoss 4.2. If my server is called fruit.mycompany.com, I can access the three apps this way: http://fruit.mycompany.com:8080/quince http://fruit.mycompany.com:8080/pineapple http://fruit.mycompany.com:8080/lime Next, I created three subdomains, which are aliases of the server fruit. http://quince.mycompany.com http://pineapple.mycompany.com http://lime.mycompany.com How can I get each subdomain to point at it's corresponding application? I want http://quince.mycompany.com to actually open http://fruit.mycompany.com:8080/quince. In apache, I would use the VirtualHost tag to point each subdomain to the correct Document Root. How do I do it with JBoss or Tomcat? Can I do it with redirection ( does Tomcat have something like mod_rewrite )? A: Tomcat supports virtual hosts. You'll basically have to: 1) Change tomcat's "listen" port to 80 instead of 8080. 2) Modify tomcat's server.xml to list your servers: <Engine name="Catalina" defaultHost="quince"> <Host name="quince" appBase="quince_apps"/> <Host name="pineapple" appBase="pineapple_apps"/> <Host name="lime" appBase="lime_apps"/> </Engine> 3) Move each application to 'ROOT' folder of corresponding "_apps" folder. When I was in a similar situation, I chose to use Apache redirection instead; however I had Apache already serving static pages (public website). A: I gave up with Tomcat. The situation became too complicated. I have a web site running on port 80 already (on a separate instance of JBoss). I have these three applications, quince, pineapple and lime running on their own JBoss instance on port 8080. To solve my problem, I just wrote a javascript function on the index page of the website running on port 80. I check location to see which domain is being called and then redirect to the appropriate website on port 8080. The script looks something like this: var whois=location+" "; if (whois.indexOf("quince.mycompany.com") > -1) { setTimeout('window.location.replace("http://quince.mycompany.com:8080/quince/");', 10); exit; } if (whois.indexOf("lime.mycompany.com") > -1) { setTimeout('window.location.replace("http://lime.mycompany.com:8080/lime/");', 10); exit; } ... // otherwise redirect to the app running on port 80 setTimeout('window.location.replace("http://fruit.mycompany.com/otherapp/");', 10); It's not exactly what I wanted, but at least my users now have a shortcut URL, and they don't have to remember port numbers: http://lime.mycompany.com redirects to -> http://lime.langara.bc.ca:8080/lime
[ "stackoverflow", "0008433016.txt" ]
Q: Customize navigation bar with title view I am trying to add a custom view in the center of a navigation bar and I am using the following code to test it: UIView * testView = [[UIView alloc] init]; [testView setBackgroundColor:[UIColor blackColor]]; testView.frame = CGRectMake(0, 0, 100, 35); [self.navigationController.navigationItem.titleView addSubview:testView]; I am setting this up in the viewDidLoad method of my view controller but when i run my program nothing seems to change in my navigation bar. Could you help me with this? A: This works. Give frame at the time of initialisation UIView *iv = [[UIView alloc] initWithFrame:CGRectMake(0,0,32,32)]; [iv setBackgroundColor:[UIColor whiteColor]]; self.navigationItem.titleView = iv; A: If you want to just customize the title for one view controller you can use UILabel *lblTitle = [[UILabel alloc] init]; lblTitle.text = @"Diga-nos o motivo"; lblTitle.backgroundColor = [UIColor clearColor]; lblTitle.textColor = [UIColor colorWithRed:77.0/255.0 green:77.0/255.0 blue:77.0/255.0 alpha:1.0]; lblTitle.shadowColor = [UIColor whiteColor]; lblTitle.shadowOffset = CGSizeMake(0, 1); lblTitle.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:18.0]; [lblTitle sizeToFit]; self.navigationItem.titleView = lblTitle; or if you want to customize for all view controllers use [[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys: [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0], UITextAttributeTextColor, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8], UITextAttributeTextShadowColor, [NSValue valueWithUIOffset:UIOffsetMake(0, -1)], UITextAttributeTextShadowOffset, [UIFont fontWithName:@"Arial-Bold" size:10.0], UITextAttributeFont, nil]]; A: Replace [self.navigationController.navigationItem.titleView addSubview:testView]; to self.navigationItem.titleView = testView; Edit: Note: You cannot add subviews to titleView cause it's default value is nil, you need to set a new view as the titleView.
[ "wordpress.stackexchange", "0000346856.txt" ]
Q: Remove style tags from head is there a filter for removing style-tags from the <head></head> area in wordpress? I want remove this style for instance: <head> <style> @import url('https://fonts.googleapis.com/css?family=Chilanka&display=swap'); </style> </head> I already achieved to remove link-tags by using this wordpress filter and some regex: add_filter( 'style_loader_tag', 'removeGoogleLinks'); I guess i havbe to use wp_head somehow but I'm not sure how to use this as filter? add_filter( 'wp_head', $removeGoogleFontStyle); public function removeGoogleFontStyle($content){ //Filter googleapi styles with regex but //how to use this funtion/filter? } A: My solution removes now all <link></link> tags and <style>@import url()</style> googleapi entries in the given HTML: add_action( 'wp_footer', 'SPDSGVOPublic::removeGoogleFonts' ); /** * Remove all occurrences of google fonts */ public static function removeGoogleFonts() { ob_start(); $content = ob_get_clean(); $patternImportUrl = '/(@import[\s]url\((?:"|\')((?:https?:)?\/\/fonts\.googleapis\.com\/css(?:(?!\1).)+)(?:"|\')\)\;)/'; $patternLinkTag = '/<link(?:\s+(?:(?!href\s*=\s*)[^>])+)?(?:\s+href\s*=\s*([\'"])((?:https?:)?\/\/fonts\.googleapis\.com\/css(?:(?!\1).)+)\1)(?:\s+[^>]*)?>/'; preg_match_all($patternImportUrl, $content, $matchesImportUrl); preg_match_all($patternLinkTag, $content, $matchesLinkTag); $matches = array_merge($matchesImportUrl,$matchesLinkTag); foreach( $matches as $match ) { $content = str_replace( $match, '', $content ); } echo $content; }
[ "stackoverflow", "0007258357.txt" ]
Q: Post Serialized data and Make the insert I have a form with several radio buttons grouped by the same name, and those radio buttons are generated dinamically, there are 20 in total, but it will only be submitted 4 each time. Each radio button group as an ID as name of the group. When post the form to PHP (using jQuery Serialize) I get something like this: 1=3&2=6&4=9&7=2 I need to get the values of each parameter, in this case 1, 2, 4 and 7 and also to know which was the fields submitted (in this case the field 1, 2, 4 and 7 was submitted) I did something like this, but not working: for ($c = 1; $c <= 20; $c++){ if (isset($_GET[$c])){ $question_id = $c; $answer_score = $_GET[$c]; echo $answer_score; $gravar = "INSERT INTO iMood_ColabsQuestionAnswers (colab_id, answer_id, score) VALUES (?, ?, ?)"; /* Set parameter values. */ $valores = array($user, $question_id, $answer_score); echo $valores.'<br />'; /* Prepare and execute the query. */ $inserirResposta = sqlsrv_query( $conn, $gravar, $valores); sqlsrv_free_stmt($inserirRespota); sqlsrv_close($conn); } } Can't find a solution for this, because the above solution, doesn't see any record and if use $_GET['$c']; It returns an error in SQL query, saying that found an unexpected (. A: How are you submitting that serialized string from jquery? Doing something like $.ajax(function() { data: '1=3&2=6&4=9&7=2' ... }); would lead to the problem you're having. This would submit a complete string containing those "query" variables, but do it without an associated field name, so PHP will NOT pick up the fact that this string contains individual key/value pairs. However, using data: { data: '1=3&2=6&4=9&7=2' } will let things work in PHP properly, and you'd get at the data like this: $query = parse_str($_GET['data']); foreach($query as $question_id => $answer_score) { ... do database stuff ... }
[ "stackoverflow", "0034871159.txt" ]
Q: Javascript search in string from array of values How can I search in string from a array with values without a each? Something like this: this.preImage.src.search(['jpg', 'jpeg', 'png', 'gif']); A: Use a constructed regular expression (inspired by @Alexey Ten's comment) var endings = ['jpg', 'jpeg', 'png', 'gif'] var regexp = new RegExp('(' + endings.join('|') + ')', 'i') var isimg = regexp.test(this.preImage.src); isimg will be true if the string contains any of the endings in any (upper- or lower-) case
[ "stackoverflow", "0063184248.txt" ]
Q: How to get document length in real time I am getting the comment count by querying the documents data length from db. Before getting the document count it will take time to load, its either i refresh the app or i restart the app. I wanted the comment count to update after the comment is added to the db like stream builder. this is what i have done so far getCommentCount() async { QuerySnapshot snapshot = await commentsRef .document(widget.postId) .collection('comments') .getDocuments(); if (!mounted) { return; } setState(() { commentCount = snapshot.documents.length; }); } A: You can add a listener to get real-time changes. QuerySnapshot snapshot = await commentRef.document(widget.potId).collection('comments') .snapshot().listen((val)=>{ if(mounted){ setState((){ commentCount= val.documents.length;}) } }) You may call it in initState
[ "stackoverflow", "0044272345.txt" ]
Q: How to use currencyFormatter with a decimal I'm trying to take a decimal I'm storing in CoreData and run it through the currency formatter in Swift 3. Here is what I'm trying to use: var currencyFormatter = NumberFormatter() currencyFormatter.usesGroupingSeparator = true currencyFormatter.numberStyle = NumberFormatter.Style.currency // localize to your grouping and decimal separator currencyFormatter.locale = NSLocale.current var priceString = currencyFormatter.stringFromNumber(NSNumber(totalAmount)) Where totalAmount is the decimal I'm using for CoreData. But . I get this error when trying to convert my decimal to a NSNumber() Argument labels '(_:)' do not match any available overloads A: stringFromNumber got renamed to string(from:), e.g. var priceString = currencyFormatter.string(from: NSNumber(totalAmount)) but you don't have to convert to NSNumber var priceString = currencyFormatter.string(for: totalAmount)
[ "vi.stackexchange", "0000016948.txt" ]
Q: How can I see which buffers are in diff mode? :ls shows my buffers and lists flags for each buffer, but doesn't list whether &diff is set. Plugins like unite's buffer source just rely on :ls output. Is there an easy way to list and manage which buffers are in diff mode (for those times when :diffget fails due to more than two buffers in diff mode). Ideally, I'd like something like :Unite buffer that includes 'diff' for buffers with &l:diff. A unite source that showed which buffers have certain variables would be cool: :Unite var diff scrollbind that works like :Unite buffer but appends 'diff' or 'scrollbind' to files with those options enabled. A: Something like :echo join( \ filter( \ map( \ range(1, winnr('$')), \ 'getwinvar(v:val, "&diff") ? "window:".v:val." buffer:".winbufnr(v:val)." -> ".bufname(winbufnr(v:val)) : ""'), \ '!empty(v:val)'), \ "\n") will return you the information you're looking for. First of all, &diff is a window-local option. This means you can fetch its value with getwinvar(winnr, '&diff'), on all windows with range(1, winnr('$')). From there, if true, you have the window number, you can extract the buffer number with winbufnr(winnr) and display the name of the associated buffer with bufname(bufnr). The join + filter part helps to keep only what matters and print one result per line.