_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d18001
test
iOS creates a synthetic leading for all fonts, even those which don't have leading specified in the font files. The only way to achieve this is to draw the label text yourself.
unknown
d18002
test
addClass takes a space separated string, so all you need to do is replace dots with spaces: var classes = '.myclass.myclass2'; $(element).addClass(classes.replace(/\./g,' ').trim())) A: create two classes inside style tag like this .a { backgroud-color:red; } .b{ color:blue; } </style> now add your jquery codes then inside javascript code <script type="text/javascript"> $(document).ready(function(){ $('#mydiv').addClass(a).addCLass(b); or $("#mydiv").addClass({a,b}); or $('#mydiv').addClass(a); $('#mydiv').addClass(b); }); </script> here is the html <html> <body> <div id="mydiv"></div> </body> </html> A: You can add this to your script: $.fn.oldAddClass = $.fn.addClass; $.fn.addClass = function(x){ if(typeof x == 'string'){ this.oldAddClass(x.replace(/\./g, ' ')); }else{ this.oldAddClass(x); } } Then call addClass() with your dot : $(el).addClass('.class1.class2'); Fiddle : http://jsfiddle.net/8hBDr/ A: You cannot add css selectors (like #elemid.myclass) directly to an element in native jQuery. The example below shows how to add multiple classes using a space delimited string. $(elem).addClass("myclass mycalss2") And the documentation: http://api.jquery.com/addClass/
unknown
d18003
test
Press the menu key and then press 'O' or 'o'. More about Menu Key: http://en.wikipedia.org/wiki/Menu_key A: Create a macro with the following. The cell with the link should only include text of the hyperlink (and not use the Excel function hyperlink with an embedded link). Note that the "... chrome.exe " has a [space] between exe and quote ("). Sub ClickHyperlnk() ' ' ClickHyperlnk Macro ' ' Keyboard Shortcut: Ctrl+d ' With Selection.Interior URL = ActiveCell.Value Shell "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe " & URL, vbNormalNoFocus End With End Sub A: To open a hyperlinked file in excel, try the following Select the cell. Press application key (menu key). Press O key twice. Press enter key. This works well for me. A: Sub hyhperlink() ' ' hyhperlink Macro ' opens hyperlink ' ' Keyboard Shortcut: Ctrl+Shift+X ' With Selection.Interior Selection.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True End With End Sub or record a macro for this operation A: go in excel view tab * *Click on micro *Click Record micro *type text in shortcut key i.e.(Ctr+Q or q) *enter OK *Press the menu key and then press 'O' or 'o' in excel Where is your hyper link data & Enter *again go in view > micro > click on stop micro Now you can use your short cut key i.e. Ctr+Q or q For hyperlink cells in excel A: This is an old post but maybe it could help someone searching for this shortcut. To open a link without going through "Edit Links" follow these couple of steps: * *click on a cell that is linked to another file *then press Ctrl + [ This will open the linked file. Hope this helps. A: In Excel 2016 (English version), I would say that the simplest way to do this is to * *press the menu key (that has a similar effect to a right click) *press "o" twice *press "Enter". The first "o" goes to "sort" ; the second "o" goes to "Open Hyperlink", and "Enter" then opens the hyperlink. On a keyboard that does not have a menu key, one can press Shift + F10 instead. A: I found out this command doesn't work for me with the 'o' twice, maybe because i have a column of hyperlinks? who knows. What I do is: * *Select cell *Menu key *Up_Arrow *Enter Opening the link is the last proposition of the menu, so going up goes to the last option. Pressing enter activates it. Chears Ben A: You can make keyboard shortcut for hyperlinks formula / function. Just press ALT + F11 copy and paste the script below: Sub OpenHyp() Workbooks.Open "FOLDER ADDRESS\" & ActiveCell.Value & "FILE EXTENSION" End Sub replace the FOLDER ADDRESS = you can find it on address bar of the file location just copy, paste and add "\" at the end of file address. no need to replace ActiveCell.Value = this is the filename of your file which is usually the content of cell. replace the FILEEXTENSION = for pdf used ".pdf", for normal excel file used ".xlsx" and so on. Then, go to developer tab, click Macros, select the code we make which is "OpenHyp" and click "Option". Now you can put the shortcut key I hope this helps.
unknown
d18004
test
For $.each(), you can stop the iteration with return false; in the callback, as described in the jQuery documentation. This won't return from the calling function, but you can set a flag and test it in the outer function. If you want an easy way to return from the outer function from inside the loop, you're better off with a simple for loop: var array = [ 'hi', 'there' ]; for( var i = 0; i < array.length; ++i ) { var e = array[i]; console.log(e); return; } alert("I don't want to be called"); For $.get(), you should add some console.log() calls to your code and observe the order in which they are called: function outer() { console.log( 'in outer before $.get is called' ); $.get('http://test.com', function (data) { console.log( 'inside $.get callback' ); }); console.log( 'in outer after $.get returns' ); } Now what you'll notice is the order of the log messages: in outer before $.get is called in outer after $.get returns inside $.get callback See how the callback is the last thing? It's called after the outer function finishes. Therefore, there is nothing this callback can do to prevent the rest of outer from executing. So you need to think some more about what you need to do and figure out a different way to accomplish it. A: Here is a summary of how it all works. .each() return true; // skips to the next iteration of .each() return false; // exits the .each() loop In short there's no way of breaking out of the function containing .each() in a single statement. $.get() return [true|false]; // makes no sense at all. As the return in $.get() does not get executed until the ajax call is complete, it wont serve much purpose. Even when you make a synchronous ajax call, a return statement in the success callback still does not do anything substantive. Think of a return from a function as a value to be assigned to the calling statement. What's making it necessary to break out of your functions? A: If you use $.ajax() instead of the short hand $.get(), it is possible to specify that it be executed synchronously. $.ajax({ url: 'http://test.com', success: function (data) { }, async: false }); Typically, when you want to make a decision based on the return value of a function you have it return a value and then use a conditional statement to determine what happens next.
unknown
d18005
test
When I had an issue with the documents directory on IOS5 I found this article which discusses the cache amongst other subjects. As I understand it; yes the OS handles the cache and it will clear it when disk space is low. What low actually means in size I do not know.
unknown
d18006
test
As Jeroen Mostert pointed out in the comments to your question, the forward slash has a special meaning in date/time format strings. From the documentation: The "/" custom format specifier The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture. Note To change the date separator for a particular date and time string, specify the separator character within a literal string delimiter. For example, the custom format string mm'/'dd'/'yyyy produces a result string in which "/" is always used as the date separator. To change the date separator for all dates for a culture, either change the value of the DateTimeFormatInfo.DateSeparator property of the current culture, or instantiate a DateTimeFormatInfo object, assign the character to its DateSeparator property, and call an overload of the formatting method that includes an IFormatProvider parameter. For matching a literal forward slash instead of the date separator defined in the system's regional settings escape it with a backslash ('MM\/dd\/yyyy'). Also, passing $null for the format provider is not recommended. Either specify the correct culture for the date string, or use InvariantCulture if you want the string parsed independent of a particular culture. [DateTime]::ParseExact('10/14/2016', 'MM\/dd\/yyyy', [Globalization.CultureInfo]::InvariantCulture) A: Use the InvariantCulture if you have a non-localized value to handle. PS C:\> ([Globalization.CultureInfo]::InvariantCulture).DateTimeFormat.DateSeparator / On my system, I have the date format set for ISO-8601. That causes my separator to be a hyphen -. PS C:\> (Get-Culture).DateTimeFormat.DateSeparator - Interesting conversion. PS C:\> (Get-Date).ToString("MM/dd/yyyy") 11-12-2016 A: Long form: Get-Date -Format "yyyy\/MM\/dd" Short-hand: date -f "yyyy\/MM\/dd" Note that, yes, in this instance, you use backslashes as the escape character, instead of tildes. A: you can use this : get-date -format "yyyy/MM/dd"
unknown
d18007
test
After doing some more digging and research, I have hacked together a working solution to my problem. I'm posting here in case anyone else needs to do something like this: function redirect(url, outsite){if(outsite){location.href = url;}else{location.href = 'http://siteurl.com/' + url;}} function editdialog(editid){ var editwin = '<div><form action="formprocess/'+editid+'" method="post" class="inform"><div id="editorheader"><label for="coltitle">Column Title: </label><input type="text" name="coltitle" id="coltitle"></div><br><div id="editorcontent"><textarea id="ckeditcolcontent"></textarea></div><input type="hidden" value="edit"></form></div>'; var $dialog = $(editwin).dialog({ autoOpen: false, title: "Editor", height: 520, width: 640, closeOnEscape: false, modal: true, open: function(event, ui){ $(this).parent().children().children(".ui-dialog-titlebar-close").hide(); }, buttons: { "Save and Close": function(){ var editor = $("#ckeditcolcontent").ckeditorGet(); var coltitle = $("#coltitle").val(); var colcontent = $("#ckeditcolcontent").val(); $.post("formprocess/"+editid, { coltitle: coltitle, colcontent: colcontent }, function(data){ redirect(location.href, 1); } ); }, "Cancel": function(){ redirect(location.href, 1); } } }); $.getJSON("ajax/" + editid, function(data){ $("#coltitle").attr("value", data.header); $("#ckeditcolcontent").val(data.content).ckeditor(config); $("<div></div>").addClass("ui-widget-overlay").appendTo(document.body).css({width:$(document).width(),height:$(document).height()}); $dialog.dialog("open"); }); } var config = new Array(); config.height = "280px"; config.resize_enabled = false; config.tabSpaces = 4; config.toolbarCanCollapse = false; config.width = "600px"; config.toolbar_Full = [["Cut","Copy","Paste","-","Undo","Redo","-","Bold","Italic","Underline", "-", "NumberedList","BulletedList","-","Link","Unlink","-","Image","Table"]]; $(document).ready(function(){ $("a.admineditlink").click(function(){ var editid = $(this).attr("href"); editdialog(editid); return false; }); });
unknown
d18008
test
You are wrong. The message is: SetupAppRunningError=Setup has detected that %1 is currently running.%n%nPlease close all instances of it now, then click OK to continue, or Cancel to exit. Where the %1 is replaced by value of the AppName directive: ExpandedAppName := ExpandConst(SetupHeader.AppName); ... { Check if app is running } while CheckForMutexes(ExpandedAppMutex) do if LoggedMsgBox(FmtSetupMessage1(msgSetupAppRunningError, ExpandedAppName), SetupMessages[msgSetupAppTitle], mbError, MB_OKCANCEL, True, IDCANCEL) <> IDOK then Abort; So the version is included in the message, only if you have included the version in the AppName directive. What is wrong, the directive value may not include the version, as the documentation says: Do not include the version number, as that is defined by the AppVersion and/or AppVerName directives.
unknown
d18009
test
I was able to solve it by slicing the file by specifying attributes of where to begin the slice and where to end which will be the chunk, I then enclosed it in a while loop so that for each loop chunk position will shift according to the desired chunk size until the end of the file. But after running it, I end up getting the last value of the chunk in the text area, so to display all the binary string i concatenate the output on each iteration. <html> <head> <title>Read File</title> </head> <body> <input type="file" id="myFile"> <hr> <textarea style="width:500px;height: 400px" id="output"></textarea> <script> var input = document.getElementById("myFile"); var output = document.getElementById("output"); var chunk_size = 2048; var offset = 0; input.addEventListener("change", function () { if (this.files && this.files[0]) { var myFile = this.files[0]; var size = myFile.size; //getting the file size so that we can use it for loop statement var i=0; while( i<size){ var blob = myFile.slice(offset, offset + chunk_size); //slice the file by specifying the index(chunk size) var reader = new FileReader(); reader.addEventListener('load', function (e) { output.textContent += e.target.result; //concatenate the output on each iteration. }); reader.readAsBinaryString(blob); offset += chunk_size; // Increment the index position(chunk) i += chunk_size; // Keeping track of when to exit, by incrementing till we reach file size(end of file). } } }); </script> </body> </html> A: So the issue isn't with FileReader, it's with : output.textContent = e.target.result; Because you are trying to dump 10MB+ worth of string into that textarea all at once. I'm not even sure there is a "right" way to do what you are wanting, since even if you did have it in chunks, it would still have to concat the previous value of output.textContent on each loop through those chunks, so that as it gets closer to the end, it would start slowing down in the same way (worse, really, because it would be doing the slow memory hogging business on every loop). So I think part of the looping process is going to have to be adding a new element (like a new textarea to push the current chunk to (so it doesn't have to do any concatenation to preserve what has already been output). I haven't worked that part out yet, but here's what I've got so far: var input = document.getElementById("myFile"); var output = document.getElementById("output"); var chunk_length = 2048; //2KB as you mentioned var chunker = new RegExp('[^]{1,' + chunk_length + '}', 'g'); var chunked_results; input.addEventListener("change", function () { if (this.files && this.files[0]) { var myFile = this.files[0]; var reader = new FileReader(); reader.addEventListener('load', function (e) { chunked_results = e.target.result.match(chunker); output.textContent = chunked_results[0]; }); reader.readAsBinaryString(myFile); } }); This is just outputting the first string in the array of 2KB chunks. You would want to do your thing as far as adding a new element/node in the DOM document for outputting all the other chunks. Using RegExp and match for the actual chunking was lifted from a clever gist I found. A: You can do that using fs.createReadStream(), The amount of data potentially buffered depends on the highWaterMark option passed into the streams constructor. So you would do it like this: var read = fs.createReadStream('/something/something', { highWaterMark: 64 }); here's an example : var fs = require('fs') var read = fs.createReadStream('readfile.txt',{highWaterMark:64}) var write = fs.createWriteStream('written.txt') read.on('open', function () { read.pipe(write); }); see how it reads 64 bytes at a time (Very Slow), you can view it on explorer in a fun way, but make sure you have a large text file to test it not a gigabyte but at least 17 megabytes like I did "fill it with any dummy text" make the file view to "details" and keep refreshing the destination in windows explorer, you will see the size increase on every refresh. I assumed you know about the pipe method if you don't, no problem! it's very simple, here is a link: https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options or a quick explanation : readable.pipe(writable) The pipe() function reads data from a readable stream as it becomes available and writes it to a destination writable stream.
unknown
d18010
test
You should use dup() and dup2() to clone a file descriptor. int stdin_copy = dup(0); int stdout_copy = dup(1); close(0); close(1); int file1 = open(...); int file2 = open(...); < do your work. file1 and file2 must be 0 and 1, because open always returns lowest unused fd > close(file1); close(file2); dup2(stdin_copy, 0); dup2(stdout_copy, 1); close(stdin_copy); close(stdout_copy); However, there's a minor detail you might want to be careful with (from man dup): The two descriptors do not share file descriptor flags (the close-on-execflag). The close-on-exec flag (FD_CLOEXEC; see fcntl(2)) for the duplicate descriptor is off. If this is a problem, you might have to restore the close-on-exec flag, possibly using dup3() instead of dup2() to avoid race conditions. Also, be aware that if your program is multi-threaded, other threads may accidentally write/read to your remapped stdin/stdout. A: I think you can "save" the descriptors before redirecting: int save_in, save_out; save_in = dup(STDIN_FILENO); save_out = dup(STDOUT_FILENO); Later on you can use dup2 to restore them: /* Time passes, STDIN_FILENO isn't what it used to be. */ dup2(save_in, STDIN_FILENO); I am not doing any error checking in that example - you should. A: You could create a child process, and set up the redirection inside the child only. Then wait for the child to terminate, and continue working in the parent process. That way you don't have to worry about reversing your redirection at all. Just look for examples of code using fork() and wait ().
unknown
d18011
test
I would focus my efforts on the web config and building my presentation layer around config settings stored at server side. Also, I'm not entirely sure how logically different your pages will be, but having different CSS styles can dramatically change the look of your websites. This post was kinda vague, I hope I helped spurn some ideas...
unknown
d18012
test
How about this for a test. Create HBITMAPs in a loop. Counting the number of bytes theoretically used (Based on the bitdepth of your video card). How many bytes worth of HBITMAPs can you allocate before they start to fail? (Or, alternately, until you do start to see an impact on memory). DDBs are managed by device drivers. Hence they tend to be stored in one of two places :- kernel mode paged pool or in the Video Cards memory itself. Both of which will not be reflected in any process memory count. In theory device drivers can allocate system memory storage for bitmaps, moving them across to vram as and when needed... but some video card drivers think that video memory should be enough and simply allocate all HBITMAPs on the card. Which means you run out of space for HBITMAPs at either the 2Gb mark (if they're allocated in kernel paged pool; depending on available ram and assuming 32bit windows editions), or 256Mb mark (or however much memory the video card has). That discussion covered Device Dependent Bitmaps. DIBSections are a special case as they're allocated in memory accessible from kernel mode, but available in userspace. As such, any application that uses a lot of bitmaps probably should use DIBSections where possible as there should be much less opportunity to starve the system of space to store DDBs. I suspect that one still has a system wide limit of up to 2Gb worth of DIBSections (on 32bit Windows versions) as there is no concept of 'current process' in kernel mode where the video device drivers will need access.
unknown
d18013
test
Try this layout i hope it will help you <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:scaleType="fitXY" android:src="@drawable/top_header_bg" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="horizontal" > <ImageView android:id="@+id/imageView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:src="@drawable/ic_launcher" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:layout_marginRight="20dp" android:orientation="vertical" > <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> </LinearLayout> </LinearLayout> </RelativeLayout> </LinearLayout> A: hi try the following code it will help you i didn't make any changes. i simply add an ImageView to your layout. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LayoutforbgImage" android:layout_width="match_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" android:baselineAligned="false" android:orientation="horizontal" > <ImageView android:id="@+id/your_image" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:background="@drawable/top_bar" /> <LinearLayout android:id="@+id/LinearLayoutforImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="10dp" android:paddingLeft="5dp" android:paddingTop="10dp" tools:ignore="RtlSymmetry,RtlHardcoded" > <ImageView android:id="@+id/imageforprofile" android:layout_width="60dp" android:layout_height="60dp" android:src="@drawable/images12" /> </LinearLayout> <TextView android:id="@+id/textforprofile" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toRightOf="@+id/LinearLayoutforImage" android:gravity="left" android:paddingLeft="5dp" android:paddingTop="16dp" android:text="My Name My Name" android:textColor="#FFFFFF" android:textStyle="bold" tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" /> <TextView android:id="@+id/textforprofileemail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/textforprofile" android:layout_toRightOf="@+id/LinearLayoutforImage" android:gravity="left" android:paddingBottom="10dp" android:paddingLeft="5dp" android:text="[email protected]" android:textColor="#FFFFFF" android:textStyle="bold" tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" /> </RelativeLayout> A: Try this way hope it will solve your problem <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <RelativeLayout android:id="@+id/topBarRelative" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" > <ImageView android:id="@+id/imageHeader" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:adjustViewBounds="true" android:cropToPadding="false" android:src="@drawable/right_top_bg" /> <ImageView android:id="@+id/imageforprofile" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:layout_marginLeft="9dp" android:src="@drawable/ic_launcher" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginRight="9dp" android:layout_toRightOf="@+id/imageforprofile" android:gravity="center" android:orientation="vertical" > <TextView android:id="@+id/textforprofile" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="3dp" android:text="My Name My Name" android:textColor="#FFFFFF" android:textStyle="bold" /> <TextView android:id="@+id/textforprofileemail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="[email protected]" android:textColor="#FFFFFF" android:textStyle="bold" /> </LinearLayout> </RelativeLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_below="@+id/topBarRelative" android:layout_margin="8dp" android:background="@drawable/content_bg" android:orientation="vertical" > </LinearLayout> </RelativeLayout> Screen shot from Eclipse
unknown
d18014
test
Check if the apostrophes are valid, but to avoid this use the selection args with the ? operator. cursor = sqlDb.query(MYTABLE, thecolumns, NAME + " LIKE ?", new String[]{"%" + name + "%"}, null, null, null);
unknown
d18015
test
If you're using the Auth component with the ControllerAuthorize authorization adapter yes. If you want to use something else use one of the other adapters or write your own. See the documentation for a basic introduction on how the auth component works.
unknown
d18016
test
when you perform A* search you change state of priority queue. When you come to finish you put away the best vertex nearest to the finish. Also there some other vertices near finish already, you can peek them from the queue too and get "another best path". But you can get different results: sometimes the paths can diff in only last edge. Like this: -------<=>finish. If there is really another best path with similar length then you will find it. I think Google provides many paths because they use different metrics simultaneously. The metrics give different results and solve path optimization problem using different parameters. A: Getting the exact second-shortest path requires something like this. If you don't care about that kind of precision, then you can introduce a bit of randomness into the shortest path: * *Cut a vertex or edge from the shortest path and recompute. *At some point along the shortest path, make an intentional wrong turn somewhere and recompute from there. A: Recompute the A* algorithm using the same graph but with different weightings. The weighting on each arc, for the fastest journey, ought to be the time taken to traverse that arc, which is the length of the arc divided by the expected speed to travel along it. You can create a new set of weightings using only the distance, not the expected speed (it is more convenient to assign the same speed to every arc). That will give the shortest path, not the fastest one. You can then create a compromise between shortest and fastest. You now have three (possibly) different routes. Other options: (i) add a weight to every arc to account for the junctions at start and end; tinker with this weight, allowing you to create routes that minimise turns. You can also add extra weights for very sharp turns, or turns across the traffic flow (right turns in UK, Australia, India, etc.; left turns in USA, France, etc.). (ii) Create a route that avoids motorways / freeways by setting the cost of them to a very high value. (iii) Use time of day, or actual on-line information, to estimate traffic flow and modify weightings based on that.
unknown
d18017
test
Assuming you have a hash: my @item3s; for my $item (@{ $hash{two}{items} }){ push @item3s, $item->{itemthree}; } print "$_\n" for @item3s; If it's in fact a hash reference, change $hash{two}{items} to $hash->{two}{items}
unknown
d18018
test
Create a selectbox with id "cat": <select id="cat"> add the selected value of this select to searchUrl in function searchLocationsNear: var e = document.getElementById("cat"); var cat = e.options[e.selectedIndex].value; var searchUrl = 'phpsqlajax_search.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius; searchurl += '&cat=' + cat; add your filter to the query in phpsqlsearch_genxml.php: // Search the rows in the markers table $query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers WHERE `category`='%s' HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20", mysql_real_escape_string($center_lat), mysql_real_escape_string($center_lng), mysql_real_escape_string($center_lat), mysql_real_escape_string(empty($_GET['cat'])?'':$_GET['cat'])) mysql_real_escape_string($radius); $result = mysql_query($query);
unknown
d18019
test
Start with including: Option Explicit at the top of the module. Then try with: Function fMakeBackup() As Boolean Dim objFSO As Object Dim Source As String Dim Target As String Dim retval As Integer ' Disable error handling during development. ' On Error GoTo sysBackup_Err Source = CurrentDb.Name ' Adjust if if backup folder is not \backups\. Target = CurrentProject.Path & "\backups\" Target = Target & Format(Now, "yyyymmdd-hhnn") & ".accdb" ' To run every time, use this line in plade of If DateDiff ...: ' If True Then If DateDiff("d", DLookup("[BackupDate]", "[WinAutoBackup]", "[BckID] = 1"), Date) >= 3 Then Set objFSO = CreateObject("Scripting.FileSystemObject") retval = objFSO.CopyFile(Source, Target, True) Set objFSO = Nothing DoCmd.SetWarnings False DoCmd.RunSQL "UPDATE WinAutoBackup SET WinAutoBackup.BackupDate = Date() WHERE [BckID] = 1;" DoCmd.SetWarnings True MsgBox "Backup successful. Next auto backup in 3 days." End If sysBackup_Exit: Exit Function sysBackup_Err: MsgBox Err.Description, , "sysBackup()" Resume sysBackup_Exit End Function
unknown
d18020
test
In the index method of your controller public function index() { return view('Myview.Firstpage')->with('tasks',Superior::all()); } Keep in mind that the all() method returns a collection which you want to loop through in your view. In your view, you should have: @foreach($tasks as $task) {{ $task->title }} @endforeach You need to also update your route to make use of the controller: Route::get('/', 'TaskController@index'); You could visit https://laravel.com/docs/5.8/collections#method-all to learn more about collections. A: Hi please try to pass you variable to view like this: $Tasks = Superior::all(); return view('Myview.Firstpage', compact('Tasks')); And then use a loop in your view like suggested in above comments. @foreach($Tasks as $task) {{ $task->title }} @endforeach
unknown
d18021
test
It would seem that the piece of the puzzle you're missing is the ability to pass values into jq using command-line options such as --arg. The following should therefore get you over the hump: while read -r ts ip do jq --arg ts "$ts" --arg ip "$ip" ' select(.timestamp==$ts and .ip_str==$ip) ' extract_3month_fromshodan.json done < <(cat<<EOF 2018-08-11T04:56:17.312039 126.100.105.198 EOF ) inputfile.txt So if inputfile.txt contains the ts-ip pairs as above, you could write: while read -r ts ip do jq --arg ts "$ts" --arg ip "$ip" ' select(.timestamp==$ts and .ip_str==$ip) ' extract_3month_fromshodan.json done < inputfile.txt
unknown
d18022
test
if you have a date object handy great. If not, something like this (pseudocode/JS): date = new Date; date = date.toISOString(); then, here is the query from the docs: { "$search": { "index": "default", "range": { "path": "anyField", "gte": "2000-01-30T20:19:53.123Z", "lte": date, } } } A: According to mongodb engineers, the queryString operators only accept AND and OR. It doesn't accept any other operator like TO, used in range filters.
unknown
d18023
test
You might take a look at this question: split-files-using-tar-gz-zip-or-bzip2 I assume the reason you want to split it is to move it? And that you know you probably wont be able to import a small slice of the file into a database?
unknown
d18024
test
cache_dir must be a directory : This problem came generally when you move your code to another host or server . There are mainly two solution for this problem 1 - Make sure your cache directory is writable or you can make writable to var folder of magento but sometimes this situation does not work so here is the alternate solution. Go to this location lib/Zend/Cache/Backend/ and open file.php file you’ll see the code something like this protected $_options = array( 'cache_dir' => null, 'file_locking' => true, 'read_control' => true, 'read_control_type' => 'crc32', 'hashed_directory_level' => 0, 'hashed_directory_umask' => 0700, 'file_name_prefix' => 'zend_cache', 'cache_file_umask' => 0600, 'metadatas_array_max_size' => 100 ); change this code as below protected $_options = array( 'cache_dir' => '/var/www/html/webkul/magento/tmp', 'file_locking' => true, 'read_control' => true, 'read_control_type' => 'crc32', 'hashed_directory_level' => 0, 'hashed_directory_umask' => 0700, 'file_name_prefix' => 'zend_cache', 'cache_file_umask' => 0600, 'metadatas_array_max_size' => 100 ); assign path of cache_dir as per your configuration . A: May be Zend is not able to find your cache directory. Try to se this in Bootstrap.php like this protected function _initCache() { $frontend = array( 'lifetime' => $time, 'automatic_serialization' => true ); $backend = array( 'cache_dir' => sys_get_temp_dir(), /**automatically detects**/ ); $cache = Zend_Cache::factory('core', 'File', $frontend, $backend); Zend_Registry::set('cache', $cache); } A: Remove the _initCaching function from your bootstrap, you shouldn't have this and the application.ini entries as they are both trying to setup the same thing (but using different cache locations). Your cache dir is set to APPLICATION_PATH "/../tmp" - i.e. a folder called 'tmp' at the root of your application (NOT in the application folder). Are you 100% sure that your tmp folder exists at this location? If so, you could try changing the application.ini configuration to use a full path instead: resources.cachemanager.configFiles.backend.options.cache_dir = "/home/daan/domains/whatever/tmp" just to see if that fixes the problem. If you still can't get it working please post more information about the file structure of your application. A: The answer of this question is that open File.php file and change the path of the tmp folder. This issue mostly comes when you tranfer your site from one server to another. When you transfer the site then the path of the tmp folder doesn't changed to the the new one. So edit the file.php and change the path of the tmp folder. A: magento root Creating "tmp" file in the magento directory solved this error for me. I was able to access admin easily A: assign full path for your cache directory. For example, 'cache_dir' => '/var/www/html/var/cache1', A: Change path in /install/config/, edit file vfs.php and put new path name. A: One of the causes for this problem in CentOS/RedHat could be Selinux. I got rid of this issue by just disabling Selinux Edit the /etc/selinux/config file and set the SELINUX to disabled.
unknown
d18025
test
I haven't used Grape so there may be some extra magic here that you need that I don't know about, but this is easy to do in Ruby/Rails. Based on your question "generating the class Entity for all child of ApplicationRecord automagically" you can do this: class ApplicationRecord < ActiveRecord::Base self.abstract_class = true class Entity < Grape::Entity # whatever shared stuff you want end end Book will then have access to the parent Entity: > Book::Entity => ApplicationRecord::Entity If you want to add extra code only to the Book::Entity, you can subclass it in Book, like this: class Book < ApplicationRecord class Entity < Entity # subclasses the parent Entity, don't forget this # whatever Book-specific stuff you want end end Then Book::Entity will be its own class. > Book::Entity => Book::Entity To combine this with your need for get_entity to be called on an inherited class, you can use the #inherited method to automatically call get_entity any time ApplicationRecord is subclassed: class ApplicationRecord < ActiveRecord::Base self.abstract_class = true def self.get_entity(target) target.columns_hash.each do |name, column| target.expose name, documentation: { desc: "Col #{name} of #{self.to_s}" } end end def self.inherited(subclass) super get_entity(subclass) end class Entity < Grape::Entity # whatever shared stuff you want end end
unknown
d18026
test
Assuming you're using the standard Bootstrap modal markup, you could handle the modal 'hidden' event like this.. $('#myModal').on('hidden', function () { document.location.reload(); }) Demo: http://www.bootply.com/62174 A: For BS3 it Should be something like $('body').on('hidden.bs.modal', '.modal', function () { document.location.reload(); });
unknown
d18027
test
@ComponentScan annotation will scan all classes with @Compoment or @Configuration annotation. Then spring ioc will add them all to spring controlled beans. If you want to only add specific configurations, you can use @import annotation. example: @Configuration @Import(NameOfTheConfigurationYouWantToImport.class) public class Config { } @Import Annotation Doc A: The easiest way is to scan the package that the @Configuration class is in. @ComponentScan("com.acme.otherJar.config") or to just load it as a spring bean: @Bean public MyConfig myConfig() { MyConfig myConfig = new MyConfig (); return myConfig; } Where MyConfig is something like: @Configuration public class MyConfig { // various @Bean definitions ... } See docs
unknown
d18028
test
Alright... I solved this by myself... I am not familiar with iteration and hope someone gives me an easier understand way in some pandas functions. Small Station is a dataframe called aqstation. Main Station is a dataframe called meostation. l = [] # All I want to do is to merge Main Station weather information into Small Stations... Calculate the Euclidean distance then classify small stations into main stations. for i in range(len(aqstation)): station = meostation['station_id'][(((aqstation['longitude'][i]-meostation['longitude'])**2+(aqstation['latitude'][i]-meostation['latitude'])**2)**(0.5)).idxmin()] l.append(station) # print(len(l)) aqstation['station_id'] = l del aqstation['longitude'] del aqstation['latitude'] del meostation['longitude'] del meostation['latitude'] Merge the two dataframes. aqstation = pd.merge(aqstation, meostation, how='left', on='station_id') print(aqstation.head(10)) Station ID station_id temperature \ 0 dongsi_aq chaoyang_meo -0.7 1 tiantan_aq beijing_meo -2.5 2 guanyuan_aq hadian_meo -1.6 3 wanshouxigong_aq fengtai_meo -1.4 4 aotizhongxin_aq hadian_meo -1.6 5 nongzhanguan_aq chaoyang_meo -0.7 6 wanliu_aq hadian_meo -1.6 7 beibuxinqu_aq pingchang_meo -3.0 8 zhiwuyuan_aq shijingshan_meo -1.8 9 fengtaihuayuan_aq fengtai_meo -1.4 pressure humidity wind_direction wind_speed weather 0 1027.9 13 239.0 2.7 Sunny/clear 1 1028.5 16 225.0 2.4 Haze 2 1026.1 14 231.0 2.5 Sunny/clear 3 1025.2 16 210.0 1.4 Sunny/clear 4 1026.1 14 231.0 2.5 Sunny/clear 5 1027.9 13 239.0 2.7 Sunny/clear 6 1026.1 14 231.0 2.5 Sunny/clear 7 1022.5 17 108.0 1.1 Sunny/clear 8 1024.0 12 201.0 2.5 Sunny/clear 9 1025.2 16 210.0 1.4 Sunny/clear My code is very lengthy. Hope someone can make it simpler.
unknown
d18029
test
This does not work with your current relationship, I don't understand why you would want to add duplicates, but if you have to, then you'd have to create a new entity for that. One example would be something like this: @Entity public class ProductBatch { @Id private String id; @OneToOne private Product product; private Integer count; // getter & setter } and then you change your Client like this: @Entity public class Client { @Id private String id; @OneToMany private List<ProductBatch> products; } this makes something like this possible for your addNewProduct function: public Client addNewProduct(Client client, Product newProduct) { List<ProductBatch> products = client.getProducts(); boolean exists = false; for(ProductBatch product : products) { if(product.getProduct().equals(newProduct)) { product.setCount(product.getCount() + 1); exists = true; } } if(!exists) { BatchProduct product = new BatchProduct(); product.setProduct(newProduct); product.setCount(0); products.add(product); } client.setProducts(products); return clientRepository.save(client); } A: That has nothing to do with JPA or Hibernate. A constraint is a Database constraint and it is right. If a Foreign Key is already part of the table, trying to add it again, violates this constraint. An ID is unique and it should stay that way. So adding duplicates (at least with the same ID) will not work.
unknown
d18030
test
If you would have default value let this parameter unfilled: doc = QTextDocument() doc.find("aaa") If you would like to use flag, do not read value from documentation, but use QTextDocument.FindBackward QTextDocument.FindCaseSensitively QTextDocument.FindWholeWords If you would like to have or use | operator: QTextDocument.FindWholeWords | QTextDocument.FindBackward If you have default value in function signature, you not need to provide this argument. A: The error is caused by a minor bug that occasionally appears in PyQt. If you update to the latest version, the error will probably go away. However, if you can't update, or if you want to bullet-proof your code against this problem, a work-around is to initialise the variable like this: >>> option = QTextDocument.FindFlag(0) >>> option = option | QTextDocument.FindBackward This will now guarantee that option has the expected type. The correct flag to use can be found by explicitly checking the type of one of the enum values: >>> print(type(QTextDocument.FindBackward)) <class 'PyQt5.QtGui.QTextDocument.FindFlag'> Or you can just look up the relevant enum in the docs: QTextDocument.
unknown
d18031
test
Migrations to create a new M2M relationship are not supported yet in EF5.0RC per my experience trying to track down the same issue. Thus why it will work on standard DB creation but doesn't work with Migration features. You can export the create SQL from the standard code first database initialization and run it manually on the migration for now. This should be resolved when EF5.0 goes RTM but for now we have to wait it out.
unknown
d18032
test
I found two issues with your code. The first one is that you request for 'local' authentication strategy while you register a BasicStrategy. In order to do that you should replace 'local' with 'basic'. The second one is that, if you want to use the BasicStrategy, you have to use the Base Authentication supported by the HTTP protocol, otherwise the BasicStrategy's callback will not be called and your authentication callback will run with err == null and user == false. I tested this with Postman, and only after I sent Basic Auth info, did the BasicStrategy callback run. I hope this helps.
unknown
d18033
test
One option is to specify category as json object like below {"code":"123","description":"bananas","category": { "id" : 1}}
unknown
d18034
test
g++ -lmgl -lpng /shitfile.cpp -o /shitfile care friend
unknown
d18035
test
Let's start with your second problem, which is easier to solve. B38400 is available in Swift, it just has the wrong type. So you have to convert it explicitly: var settings = termios() cfsetspeed(&settings, speed_t(B38400)) Your first problem has no "nice" solution that I know of. Fixed sized arrays are imported to Swift as tuples, and – as far as I know – you cannot address a tuple element with a variable. However,Swift preserves the memory layout of structures imported from C, as confirmed by Apple engineer Joe Groff:. Therefore you can take the address of the tuple and “rebind” it to a pointer to the element type: var settings = termios() withUnsafeMutablePointer(to: &settings.c_cc) { (tuplePtr) -> Void in tuplePtr.withMemoryRebound(to: cc_t.self, capacity: MemoryLayout.size(ofValue: settings.c_cc)) { $0[Int(VMIN)] = 1 } } (Code updated for Swift 4+.)
unknown
d18036
test
You could use array_map to get new array with only the first two characters of each item: $input = ['1_name', '0_sex', '2_age']; var_dump(array_map(function($v) { return substr($v, 0, 2); }, $input)); A: Use a foreach loop this way: <?php $a = ["1_name", "0_sex", "2_age"]; foreach ($a as $aa) { echo substr($aa, 0, 2) . "\n"; } Output: 1_ 0_ 2_ You can use the array_map() function as well to return an array. array_map(function ($a) { return substr($a, 0, 2); }, $input); A: Using indexes will work for you as well. Source-Code index.php <?php $array = [ '1_name', '0_sex', '2_age' ]; echo 'First element is ' . $array[0][0] . $array[0][1] . '<br>'; echo 'Second element is ' . $array[1][0] . $array[1][1] . '<br>'; echo 'Third element is ' . $array[2][0] . $array[2][1] . '<br>'; Result First element is 1_ Second element is 0_ Third element is 2_
unknown
d18037
test
Change <input type='submit' id='submit' name='submit' value='submit'> to a type button <input type='button' id='submit' name='submit' value='submit'> Handle button click so it opens confirm or whatever confirmation thing you will be using. And then, based on the result yes or no submit the form http://www.w3schools.com/jsref/met_form_submit.asp The problem with your implementation it that document.getElementById('myLink').click(); doesn't really return true or false, at least the result cannot be interpreted as what you expect
unknown
d18038
test
http://jsfiddle.net/sailorob/4cdTV/5/ I've removed your CSS for simplicity's sake and simplified your functions by utilizing jQuery slideUp and slideDown, which essentially handle many of the css properties you were managing with your functions. From here, I think it would be fairly simple to work back in some of your CSS. When utilizing javascript/jQuery/animation on menus, I highly suggest using timers (setTimeout) for firing mouseenters and 'leaves. This way, your menu is more forgiving when a user accidentally moves their mouse a few pixels out of the menu and it closes. A: Well, in debugging the JS and CSS I found that if you remove ALL the JS you have, the drop down menu with sub menus work fine. The Other li opens up the ul below it just fine. Note, it doesn't animate without the JS though. Here's a forked fiddle. I tested it in latest Chrome and Firefox.
unknown
d18039
test
Its mainly because of this: html = new WebClient().DownloadString(string.Format("{0}/{1}/GetMenu", currentDomain, controllerName)); This line uses WebClient class to get the html, but the WebClient class is stateless, and each time its called it uses another request with no cookies, so the server thinks it a new request, and starts a new session. A: The WebClient request is recursively starting a new session. As a hack, you could modify your Session_Start() to check if the incoming url is /{controller}/GetMenu and simply avoid the WebClient call. See: https://stackoverflow.com/a/18656561. Otherwise, perhaps decorating your MenuController with SessionStateAttribute (https://msdn.microsoft.com/en-us/library/system.web.mvc.sessionstateattribute(v=vs.118).aspx) might avoid the Session_Start altogether (if GetMenu() doesn't use the session state).
unknown
d18040
test
You may see: ASP.NET State Management Overview Profile Properties You can use: ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This feature is similar to session state, except that the profile data is not lost when a user's session expires. The profile-properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner. A: You can use asp.net cache or save data from one page in to some persistent medium and other page would read from that medium could be database or xml etc. A: Beside your requirements(not using QueryString or Session values or Cookies) yes you can use public property like public String YourProperty { get { return "Return What you want to pass"; } } Check this MSDN article for full code
unknown
d18041
test
You are close. It's even simpler than you think, you can extract without reference to indices: def func(name): # do something return value1, value2 x, y = func(var) func returns a tuple (note parentheses are not required). You can then unpack via sequence unpacking. I would advise you choose variable names that are informative.
unknown
d18042
test
You're trying to use a feature of the Commercial Edition, but you're running the Open Source Edition.
unknown
d18043
test
You can implement gen_server, as seems the messages are coming from some MQ. So, you can get the messages in handle_info. Once there you can do whatever you want to do with them. A: Well, it all depends on how your subscriber is implemented (is it another process, TCP listener, do you use gen_event behaviour, does it decode any data for you .... ). Since you are using AMQP protocol for communication, you could use RabbitMQ as client. You would get whole AMQP implementation (with all responses to your broker), and some model for getting messages or subscribing to channels. Code-base is mature, whole project is stable, and most of logic is written for you, so I would strongly recommend using this approach. The "invoked everytime we have new message on the queue" is somewhat explained in subscibe to que section.
unknown
d18044
test
Given you have 8 columns, you probably need to do something like this: WITH t AS ( SELECT CASE WHEN (colA IS NULL AND colB IS NULL AND colC IS NULL AND colD IS NULL AND colE IS NULL AND colF IS NULL AND colG IS NULL AND colH IS NULL) THEN 'ALL' ELSE '' END [ALL], CASE WHEN colA IS NULL THEN 'A' ELSE '' END [A], CASE WHEN colB IS NULL THEN 'B' ELSE '' END [B], CASE WHEN colC IS NULL THEN 'C' ELSE '' END [C], CASE WHEN colD IS NULL THEN 'D' ELSE '' END [D], CASE WHEN colE IS NULL THEN 'E' ELSE '' END [E], CASE WHEN colF IS NULL THEN 'F' ELSE '' END [F], CASE WHEN colG IS NULL THEN 'G' ELSE '' END [G], CASE WHEN colH IS NULL THEN 'H' ELSE '' END [H] FROM <TABLENAME>) SELECT CASE WHEN [ALL] = 'ALL' THEN 'ALL are NULL' ELSE [ALL] + ',' + A + ',' + B + ',' + C + ',' + D + ',' + E + ',' + F + ',' + G + ',' + H + ' are NULL' END FROM T In the final select statement, you could make further alterations to present the results as you want.
unknown
d18045
test
One possible solution would be to have a hidden window that owns all the windows in your app. You would declare it something like: <Window Opacity="0" ShowInTaskbar="False" AllowsTransparency="true" WindowStyle="None"> Be sure to remove StartupUri from your App.xaml. And in your App.xaml.cs you would override OnStartup to look something like: protected override void OnStartup(StartupEventArgs e) { HiddenMainWindow window = new HiddenMainWindow(); window.Show(); Window1 one = new Window1(); one.Owner = window; one.Show(); Window2 two = new Window2(); two.Owner = window; two.Show(); } Another difficulty will be how you want to handle closing the actual application. If one of these windows is considered the MainWindow you can just change the application ShutdownMode to ShutdownMode.OnMainWindowClose and then set the MainWindow property to either of those windows. Otherwise you will need to determine when all windows are closed and call Shutdown explicitly.
unknown
d18046
test
It is actually an leftJoin instead of join: $result1 = DB::table('blacklist') ->leftJoin('rules', 'blacklist.rule_id', '=', 'rules.id') ->select('blacklist.*', 'rules.clicks', 'rules.minutes') ->groupBy('blacklist.address') ->where('blacklist.user_id', JWTAuth::user()->id) ->get(); A: try this $result2 = DB::table('blacklist') ->select('blacklist.*') ->groupBy('blacklist.address') ->where(function ($result2) { $result2->where('blacklist.user_id', JWTAuth::user()->id) ->orWhereNull('blacklist.user_id'); } ->get();
unknown
d18047
test
You're close, you just need to combine that with a FileStream object var fileStream:FileStream = new FileStream(); fileStream.open(file, FileMode.READ); var str:String = fileStream.readMultiByte(file.size, File.systemCharset); trace(str); more info here A: If you want to read the content of a file, use the following code: var stream:FileStream = new FileStream(); stream.open("some path here", FileMode.READ); var fileData:String = stream.readUTFBytes(stream.bytesAvailable); trace(fileData); The data property is inherited from FileReference class and it will be populated only after a load call (see this link).
unknown
d18048
test
I'll focus on explaining what the error means, there are too few hints in the question to provide a simple answer. A "stub" is used in COM when you make calls across an execution boundary. It wasn't stated explicitly in the question but your Ada program is probably an EXE and implements an out-of-process COM server. Crossing the boundary between processes in Windows is difficult due to their strong isolation. This is done in Windows by RPC, Remote Procedure Call, a protocol for making calls across such boundaries, a network being the typical case. To make an RPC call, the arguments of a function must be serialized into a network packet. COM doesn't know how to do this because it doesn't know enough about the actual arguments to a function, it needs the help of a proxy. A piece of code that does know what the argument types are. On the receiving end is a very similar piece of code that does the exact opposite of what the proxy does. It deserializes the arguments and makes the internal call. This is the stub. One way this can fail is when the stub receives a network packet and it contains more or less data than required for the function argument values. Clearly it won't know what to do with that packet, there is no sensible way to turn that into a StructData_Type value, and it will fail with "The stub received bad data" error. So the very first explanation for this error to consider is a DLL Hell problem. A mismatch between the proxy and the stub. If this app has been stable for a long time then this is not a happy explanation. There's another aspect about your code snippet that is likely to induce this problem. Structures are very troublesome beasts in software, their members are aligned to their natural storage boundary and the alignment rules are subject to interpretation by the respective compilers. This can certainly be the case for the structure you quoted. It needs 10 bytes to store the fields, 4 + 4 + 2 and they align naturally. But the structure is actually 12 bytes long. Two bytes are padded at the end to ensure that the ints still align when the structure is stored in an array. It also makes COM's job very difficult, since COM hides implementation detail and structure alignment is a massive detail. It needs help to copy a structure, the job of the IRecordInfo interface. The stub will also fail when it cannot find an implementation of that interface. I'll talk a bit about the proxy, stub and IRecordInfo. There are two basic ways a proxy/stub pair are generated. One way is by describing the interfaces in a language called IDL, Interface Description Language, and compile that with MIDL. That compiler is capable of auto-generating the proxy/stub code, since it knows the function argument types. You'll get a DLL that needs to be registered on both the client and the server. Your server might be using that, I don't know. The second way is what VB6 uses, it takes advantage of a universal proxy that's built into Windows. Called FactoryBuffer, its CLSID is {00000320-0000-0000-C000-000000000046}. It works by using a type library. A type library is a machine readable description of the functions in a COM server, good enough for FactoryBuffer to figure out how to serialize the function arguments. This type library is also the one that provides the info that IRecordInfo needs to figure out how the members of a structure are aligned. I don't know how it is done on the server side, never heard of GNATCOM before. So a strong explanation for this problem is that you are having a problem with the type library. Especially tricky in VB6 because you cannot directly control the guids that it uses. It likes to generate new ones when you make trivial changes, the only way to avoid it is by selecting the binary compatibility option. Which uses an old copy of the type library and tries to keep the new one as compatible as possible. If you don't have that option turned on then do expect trouble, especially for the guid of the structure. Kaboom if it changed and the other end is still using the old guid. Just some hints on where to start looking. Do not assume it is a problem caused by SP3, this COM infrastructure hasn't changed for a very long time. But certainly expect this kind of problem due to a new operating system version being installed and having to re-register everything. SysInternals' ProcMon is a good utility to see the programs use the registry to find the proxy, stub and type library. And you'd certainly get help from a COM Spy kind of utility, albeit that they are very hard to find these days. A: If it suddenly stopped working happily on XP, the first culprit I'd look for is type mismatches. It is possible that "long" on such systems is now 64-bits, while your Ada COM code (and/or perhaps your C ints) are exepecting 32-bits. With a traditionally-compiled system this would have been checked for you by your compiler, but the extra indirection you have with COM makes that difficult. The bit you wrote in there about "when we compile for 64-bit systems" makes me particularly leery. 64-bit compiles may change the size of many C types, you know. A: This Related Post suggests you need padding in your struct, as marshalling code may expect more data than you actually send (which is a bug, of course). Your struct contains 9 bytes (assuming 4 bytes for each of the ints/longs and one for the boolean). Try to add padding so that your struct contains a multiple of 4 bytes (or, failing that, multiple of 8, as the post isn't clear on the expected size) A: I am also suggesting that the problem is due to a padding issue in your structure. I don't know whether you can control this using a #pragma, but it might be worth looking at your documentation. I think it would be a good idea to try and patch your struct so that the resulting type library struct is a multiple of four (or eight). Your Status member takes up 2 bytes, so maybe you should insert a dummy value of the same type either before or after Status - which should bring it up to 12 bytes (if packing to eight bytes, this would have to be three dummy variables).
unknown
d18049
test
This is from the Apple document, "About File Metadata Queries" : iOS allows metadata searches within iCloud to find files corresponding files. It provides only the Objective-C interface to file metadata query, NSMetadataQuery and NSMetadataItem, as well as only supporting the search scope that searches iCloud. Unlike the desktop, the iOS application’s sandbox is not searchable using the metadata classes. In order to search your application’s sandbox, you will need to traverse the files within the sandbox file system recursively using the NSFileManager class. Once matching file or files is found, you can access that file in the manner that you require. You are also able to use the NSMedatataItem class to retrieve metadata for that particular file. So, you have to use NSFileManager instead.
unknown
d18050
test
Do your stuff without the inline JS, and remember to close the <a> element and use a ready function <a id="test">Show box</a> <script type="text/javascript"> $(document).ready(function() { $("#test").on({ mouseenter: function() { $("#SlideMenu").slideDown(); }, mouseleave: function() { $("#SlideMenu").slideUp(); }, click: function(e) { e.preventDefault(); } }); }); </script> FIDDLE A: As you're using jQuery I believe it would be beneficial for you to use something similar to: $("#box").hover( function() { //.stop() to prevent propagation $(this).stop().animate({"bottom": "200px"}, "fast"); }, function() { $(this).stop().animate({"bottom": "0px"}, "fast"); } ); What this will mean is that whilst the mouse is over the menu, the menu will stay in its open position. When the mouse exits the menu it will close. Obviously change the id, and animation CSS values to suit your needs :)! Here is a working example: http://jsfiddle.net/V3PYs/1/ A: Really there is no problem here - the script is doing exactly what you told it to. However, from what I understand, what you want is for the menu to stay open when you leave the "trigger" element if the user's mouse is now over the menu. Try this: <script type="text/javascript"> var timeout=250;//timeout in milliseconds to wait before hiding the menu var menuMouseout; $(document).ready(function() { $("#trigger").hover(function(){ $("#SlideMenu").slideDown(); }, function(){ menuMouseout=setTimeout("$('#SlideMenu').slideUp();", timeout); }); $("#SlideMenu").hover(function(){ clearTimeout(menuMouseout); }, function(){ menuMouseout=setTimeout("$('#SlideMenu').slideUp();", timeout); }); }); </script> This way, the user is left some time after mousing out of the trigger element to get to the menu. You might need to fiddle with the timeout, but this should work. I tested this and it seems to be working. Just be sure, if necessary, to wrap this in $(document).ready to make sure all elements are loaded and ready. Demo: http://www.dstrout.net/pub/menu.htm A: If you're using jQuery this would be the proper way to go about it: <a href="#" id="showBoxHref">Show box</a> <script type="text/javascript"> $("#showBoxHref").hover(function() { $(this).slideDown(); }, function() { $(this).slideUp(); }); </script> (just copy/paste this in and it should work)
unknown
d18051
test
URL::equals reference URL urlOne = new URL("http://stackoverflow.com"); URL urlTwo = new URL("http://stackoverflow.com/"); if( urlOne.equals(urlTwo) ) { // .... } Note from docs - Two URL objects are equal if they have the same protocol, reference equivalent hosts, have the same port number on the host, and the same file and fragment of the file. Two hosts are considered equivalent if both host names can be resolved into the same IP addresses; else if either host name can't be resolved, the host names must be equal without regard to case; or both host names equal to null. Since hosts comparison requires name resolution, this operation is a blocking operation. Note: The defined behavior for equals is known to be inconsistent with virtual hosting in HTTP. So, instead you should prefer URI::equals reference as @Joachim suggested. A: While URI.equals() (as well as the problematic URL.equals()) does not return true for these specific examples, I think it's the only case where equivalence can be assumed (because there is no empty path in the HTTP protocol). The URIs http://stackoverflow.com/foo and http://stackoverflow.com/foo/ can not be assumed to be equivalent. Maybe you can use URI.equals() wrapped in a utility method that handles this specific case explicitly. A: The following may work for you - it validates that 2 urls are equal, allows the parameters to be supplied in different orders, and allows a variety of options to be configured, that being: * *Is the host case sensitive *Is the path case sensitive *Are query string parameters case sensitive *Are query string values case sensitive *Is the scheme case sensitive You can test it like so: class Main { public static void main(String[] args) { UrlComparer urlComparer = new UrlComparer(); expectResult(false, "key a case different", urlComparer.urlsMatch("//test.com?A=a&B=b", "//test.com?a=a&b=b")); expectResult(false, "key a case different", urlComparer.urlsMatch("https://WWW.TEST.COM?A=1&b=2", "https://www.test.com?b=2&a=1")); expectResult(false, "key a value different", urlComparer.urlsMatch("/test?a=2&A=A", "/test?a=A&a=2")); expectResult(false, "key a value different", urlComparer.urlsMatch("https://WWW.TEST.COM?A=a&b=2", "https://www.test.com?b=2&A=1")); expectResult(false, "null", urlComparer.urlsMatch("/test", null)); expectResult(false, "null", urlComparer.urlsMatch(null, "/test")); expectResult(false, "port different", urlComparer.urlsMatch("//test.com:22?A=a&B=b", "//test.com:443?A=a&B=b")); expectResult(false, "port different", urlComparer.urlsMatch("https://WWW.TEST.COM:8443", "https://www.test.com")); expectResult(false, "protocol different", urlComparer.urlsMatch("http://WWW.TEST.COM:2121", "https://www.test.com:2121")); expectResult(false, "protocol different", urlComparer.urlsMatch("http://WWW.TEST.COM?A=a&b=2", "https://www.test.com?b=2&A=a")); expectResult(true, "both null", urlComparer.urlsMatch(null, null)); expectResult(true, "host and scheme different case", urlComparer.urlsMatch("HTTPS://WWW.TEST.COM", "https://www.test.com")); expectResult(true, "host different case", urlComparer.urlsMatch("https://WWW.TEST.COM:443", "https://www.test.com")); expectResult(true, "identical urls", urlComparer.urlsMatch("//test.com:443?A=a&B=b", "//test.com:443?A=a&B=b")); expectResult(true, "identical urls", urlComparer.urlsMatch("/test?a=A&a=2", "/test?a=A&a=2")); expectResult(true, "identical urls", urlComparer.urlsMatch("https://www.test.com", "https://www.test.com")); expectResult(true, "parameter order changed", urlComparer.urlsMatch("https://www.test.com?a=1&b=2&c=522%2fMe", "https://www.test.com?c=522%2fMe&b=2&a=1")); expectResult(true, "parmeter order changed", urlComparer.urlsMatch("https://WWW.TEST.COM?a=1&b=2", "https://www.test.com?b=2&a=1")); } public static void expectResult(boolean expectedResult, String msg, boolean result) { if (expectedResult != result) throw new RuntimeException(msg); } } UrlComparer.java import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.TreeMap; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; public class UrlComparer { private boolean hostIsCaseSensitive = false; private boolean pathIsCaseSensitive = true; private boolean queryStringKeysAreCaseSensitive = true; private boolean queryStringValuesAreCaseSensitive = false; private boolean schemeIsCaseSensitive = false; public boolean urlsMatch(String url1, String url2) { try { if (Objects.equals(url1, url2)) return true; URI uri1 = new URI(url1); URI uri2 = new URI(url2); // Compare Query String Parameters Map<String, String> mapParams1 = getQueryStringParams(uri1); Map<String, String> mapParams2 = getQueryStringParams(uri2); if (!mapsAreEqual(mapParams1, mapParams2, getQueryStringValuesAreCaseSensitive())) return false; // Compare scheme (http or https) if (!stringsAreEqual(uri1.getScheme(), uri2.getScheme(), getSchemeIsCaseSensitive())) return false; // Compare host if (!stringsAreEqual(uri1.getHost(), uri2.getHost(), getHostIsCaseSensitive())) return false; // Compare path if (!stringsAreEqual(uri1.getPath(), uri2.getPath(), getPathIsCaseSensitive())) return false; // Compare ports if (!portsAreEqual(uri1, uri2)) return false; return true; } catch (Exception e) { return false; } } protected Map<String, String> getQueryStringParams(URI uri) { Map<String, String> result = getListAsMap(URLEncodedUtils.parse(uri, "UTF-8"), getQueryStringKeysAreCaseSensitive()); return result; } protected boolean stringsAreEqual(String s1, String s2, boolean caseSensitive) { // Eliminate null cases if (s1 == null || s2 == null) { if (s1 == s2) return true; return false; } if (caseSensitive) { return s1.equals(s2); } return s1.equalsIgnoreCase(s2); } protected boolean mapsAreEqual(Map<String, String> map1, Map<String, String> map2, boolean caseSensitiveValues) { for (Map.Entry<String, String> entry : map1.entrySet()) { String key = entry.getKey(); String map1value = entry.getValue(); String map2value = map2.get(key); if (!stringsAreEqual(map1value, map2value, caseSensitiveValues)) return false; } for (Map.Entry<String, String> entry : map2.entrySet()) { String key = entry.getKey(); String map2value = entry.getValue(); String map1value = map2.get(key); if (!stringsAreEqual(map1value, map2value, caseSensitiveValues)) return false; } return true; } protected boolean portsAreEqual(URI uri1, URI uri2) { int port1 = uri1.getPort(); int port2 = uri2.getPort(); if (port1 == port2) return true; if (port1 == -1) { String scheme1 = (uri1.getScheme() == null ? "http" : uri1.getScheme()).toLowerCase(); port1 = scheme1.equals("http") ? 80 : 443; } if (port2 == -1) { String scheme2 = (uri2.getScheme() == null ? "http" : uri2.getScheme()).toLowerCase(); port2 = scheme2.equals("http") ? 80 : 443; } boolean result = (port1 == port2); return result; } protected Map<String, String> getListAsMap(List<NameValuePair> list, boolean caseSensitiveKeys) { Map<String, String> result; if (caseSensitiveKeys) { result = new HashMap<String, String>(); } else { result = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); } for (NameValuePair param : list) { if (caseSensitiveKeys) { if (!result.containsKey(param.getName())) result.put(param.getName(), param.getValue()); } else { result.put(param.getName(), param.getValue()); } } return result; } public boolean getSchemeIsCaseSensitive() { return schemeIsCaseSensitive; } public void setSchemeIsCaseSensitive(boolean schemeIsCaseSensitive) { this.schemeIsCaseSensitive = schemeIsCaseSensitive; } public boolean getHostIsCaseSensitive() { return hostIsCaseSensitive; } public void setHostIsCaseSensitive(boolean hostIsCaseSensitive) { this.hostIsCaseSensitive = hostIsCaseSensitive; } public boolean getPathIsCaseSensitive() { return pathIsCaseSensitive; } public void setPathIsCaseSensitive(boolean pathIsCaseSensitive) { this.pathIsCaseSensitive = pathIsCaseSensitive; } public boolean getQueryStringKeysAreCaseSensitive() { return queryStringKeysAreCaseSensitive; } public void setQueryStringKeysAreCaseSensitive(boolean queryStringKeysAreCaseSensitive) { this.queryStringKeysAreCaseSensitive = queryStringKeysAreCaseSensitive; } public boolean getQueryStringValuesAreCaseSensitive() { return queryStringValuesAreCaseSensitive; } public void setQueryStringValuesAreCaseSensitive(boolean queryStringValuesAreCaseSensitive) { this.queryStringValuesAreCaseSensitive = queryStringValuesAreCaseSensitive; } } A: sameFile public boolean sameFile(URL other)Compares two URLs, excluding the fragment component. Returns true if this URL and the other argument are equal without taking the fragment component into consideration. Parameters: other - the URL to compare against. Returns: true if they reference the same remote object; false otherwise. also please go through this link http://download.oracle.com/javase/6/docs/api/java/net/URL.html#sameFile(java.net.URL) As iam unable to add comment , browser throwing Javascript error. so iam adding my comment here. regret for inconvience. //this what i suggeted >URL url1 = new URL("http://stackoverflow.com/foo"); >URL url2 = new URL("http://stackoverflow.com/foo/"); >System.out.println(url1.sameFile(url2)); // this is suggested by Joachim Sauer >URI uri = new URI("http://stackoverflow.com/foo/"); >System.out.println(uri.equals("http://stackoverflow.com/foo")); // Both are giving same result so Joachim Sauer check once.
unknown
d18052
test
You don't need to generate your json config file during your build process (unless you generate the users initial username, password , database name, etc during any application registration / purchase process). Instead, make this function part of your applications start-up / first run code. During the initialisation phase of your application starting, look for existence of the json config file. The best place for this file to be stored is in the user’s data directory, appended by your applications name. See app.getPath('userData') for more information. If the json config file exists, load it (obviously in your main process) and reference it's values as per normal. If the file does not exist (IE: First run), create it with default values. You can also give the user (if you want) the option to change the default values during the first run by popping up a dialog (or something similar) with the appropriate config fields. The json config values should be changeable by your applications UI for users who are not comfortable editing the json config file directly. Those who do edit the json config file directly will see their changes take effect immediately upon application restart. You could also make any changes hot reloadable though that would require a file watcher, etc (or a manual 'reload' button in the UI). If the json config file is allowed to be edited by the user, you should validate the structure and content of the file during application start-up (or after hot reloading), else any malformed json config file would crash your application.
unknown
d18053
test
According to the error, you need to add sqlite3 gem to your Gemfile (it's just a plain text file that should be on your Redmine root folder). Edit it and add something like.- gem 'sqlite3' You may also find this thread useful.- Ruby on Rails - "Add 'gem sqlite3'' to your Gemfile"
unknown
d18054
test
Geofencing (http://mobile.tutsplus.com/tutorials/iphone/geofencing-with-core-location/) Geofencing is the process in which one or more geofences are monitored and action is taken when a particular geofence is entered or exited. Geofencing is a technology very well suited for mobile devices. A good example is Apple’s Reminders application. You can attach a geofence to a reminder so that the application notifies you when you are in the vicinity of a particular location (figure 1). This is incredibly powerful and much more intuitive that using traditional reminders that remind you at a certain date or time. IOS Module Implementation for Titanium: http://www.clearlyinnovative.com/blog/post/34758523489/appcelerator-titanium-quickie-ios-geofencing-module#.UZVL3CtARYg I believe there is a tutorial on converting Skyhook's SDK to a module in Titanium. This looks like the result. https://github.com/aaronksaunders/ClearlyInnovativeSkyhookModule
unknown
d18055
test
Inside the airport entity, the mappedBy reference should be like the following... @OneToMany(mappedBy = "startLocation") @OneToMany(mappedBy = "destination") A: Define a relationship in Airport Entity, and specify the property mappedBy="". MappedBy basically tells the hibernate not to create another join table as the relationship is already being mapped by the opposite entity of this relationship. That basically refers to the variables used in Flight Entity like startLocation and destination. It should look like this:- public class Airport { ... @OneToMany(mappedBy = "startLocation") private Flight flight_departure_location; @OneToMany(mappedBy = "destination") private Flight flight_destination; } It should be something like this.
unknown
d18056
test
Try this: $('#link_id')[0].click(); A: You can try something link this. window.open($("#link_id").attr("href")) Working fiddle here
unknown
d18057
test
var res = XDocument.Load(filename) .Descendants("fieldLayout") .OrderByDescending(x => x.Descendants("field").Count()) .First(); A: var fieldLayout = xDoc.Root .Element("FieldLayout") .Elements("fieldLayout") .OrderByDescending(fl => fl.Element("fields") .Elements("field") .Count()) .First();
unknown
d18058
test
Windows XP used SHA1 hashes in the signatures, which is not supported on 10: Source: The following table shows which OS's support SHA-1 and SHA-256 code signatures: +---------------------+-------------------------------+------------------------------+ | Windows OS | SHA-1 | SHA-256 | +---------------------+-------------------------------+------------------------------+ | XP SP3, Server 2003 | Yes | No (need KB968730, KB938397) | | Vista, Server 2008 | Yes | No (need KB2763674) | | 7, Server 2008 R2 | No (if signed after 1/1/2016) | Yes (with latest updates) | | 8.1, Server 2012 R2 | No (if signed after 1/1/2016) | Yes | | 10, Server 2016 | No (if signed after 1/1/2016) | Yes | +---------------------+-------------------------------+------------------------------+
unknown
d18059
test
$.each(data, function(i,item) { var container = $('<div class="sex" />'); $('<img/>').attr("src", item.media_path).wrap('<div class="friend_pic' + item.id + '"></div>').appendTo(container); $('<div class="friends-name' + item.id + '" id="fname_' + item.id + '" />').html(item.fname).appendTo(container); container.appendTo('.mutual_row'); });
unknown
d18060
test
You must either run the command from the directory your file exists in, or provide a relative or absolute path to the file. Let's do the latter: cd /home/jsmith mkdir cw cd cw tar zxvf /home/jsmith/Downloads/fileNameHere.tgz A: You should use the command with the options preceded by dash like this: tar -zxvf filename.tar.gz If you want to specify the directory to save all the files use -C: tar -zxf filename.tar.gz -C /root/Desktop/folder
unknown
d18061
test
Try looping using an Iterator, since per Oracle Iterator.remove() is the only safe way to remove an item from a Collection (including a Stack) during iteration. From http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress. So something like the following should work: Stack<Particle> particles = new Stack<Particle>(); ... // Add a bunch of particles Iterator<Particle> iter = particles.iterator(); while (iter.hasNext()) { Particle p = iter.next(); if (!p.isAlive()) { iter.remove(); } } I've used this approach in a real Android app (OneBusAway Android - see code here), and it worked for me. Note that in the code for this app I also included a try/catch block in case the platform throws an exception, and in this case just iterate through a copy of the collection and then remove the item from the original collection. For you, this would look like: try { ... // above code using iterator.remove } catch(UnsupportedOperationException e) { Log.w(TAG, "Problem removing from stack using iterator: " + e); // The platform apparently didn't like the efficient way to do this, so we'll just // loop through a copy and remove what we don't want from the original ArrayList<Particle> copy = new ArrayList<Particle>(particles); for (Particle p : copy) { if (!p.isAlive()) { particles.remove(p); } } } This way you get the more efficient approach if the platform supports it, and if not you still have a backup. A: Have you ever try this: Stack<String> stack = new Stack<String>(); stack.push("S"); stack.push("d"); for (String s : stack){ stack.pop(); }
unknown
d18062
test
please use this you can also remove the size tag but in this case your view hight and width must be equal <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <stroke android:width="1dp" android:color="#E0D8D0" /> <size android:width="80dp" android:height="80dp"/> </shape> A: Actually you almost get it right. A circle is an oval with with same width and height so you can just set the width and height inside the shape and you will get circle in every device <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <solid android:color="@color/white"/> <size android:width="100dp" android:height="100dp"/> </shape> A: if You want a circle You use this but your View hight and width must be equal <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <gradient android:angle="270" android:endColor="#80FF00FF" android:startColor="#FFFF0000" /> </shape> and You also use this <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <gradient android:angle="270" android:endColor="#80FF00FF" android:startColor="#FFFF0000" /> <size android:width="80dp" android:height="80dp"/> </shape>
unknown
d18063
test
You cannot use alias that way. You have to do it using let this way: var query=from d in db.tblAttributeDatas let str = d.strValue // hold value here select new { a=str, // now assign here b=str }; A: assign the same value to b .. there is no harm.. var query = from d in db.tblAttributeDatas select new { a = d.strValue, b = d.strValue }; A: Basically, you can't do this because of the nature of object initializers (which is: initializing objects using the object literal notation { ... }). This simple line of code... var x = new { a = 1, b = 2 }; ...is executed in IL code as... <>f__AnonymousType0<System.Int32,System.Int32>..ctor So you see that the anonymous type is created having a two-parameter constructor. Suppose this constructor would be visible as... class X { public X(int a, int b) { } } It's obvious you can't call this constructor by var x = new X(1, a); You must supply two values. One constructor argument can't "borrow" the value of the other argument.
unknown
d18064
test
Edit: Relevant extension is this PHP Snippets VS Code on the marketplace which works even inside html files without the <?php tag declaration. Since that extension doesn't have any settings for itself. The easy way of doing this is to create a workspace setting file, settings.json in you project/.vscode/ folder. And add this to the settings settings.json { // all other settings "files.associations": { "*.html": "php", } } .code-workspace file { "folders": [ { "path": "." } ], "settings": { "files.associations": { "*.html": "php", } } } What this does is tell VScode to treat all HTML files as PHP. It shouldn't be much of an issue because, Emmet snippets will work along with the snippets from this extension. This is better to be added as workspace/project setting because, it won't affect other projects where you might be working on another language. One more way is to doing manually file by file, if you want to. You can click on the language identifier in the status bar and change it to PHP and you will enable snippets in the file.
unknown
d18065
test
If you want to change the color every 0.25 seconds, that should be the interval of the animation: import matplotlib.pyplot as plt from matplotlib.patches import Circle from matplotlib.animation import FuncAnimation fig, ax = plt.subplots() ax.axis('square') c = Circle(xy = (0, 0), color = "red") ax.add_patch(c) ax.set_xlim([-50, 50]) ax.set_ylim([-50, 50]) def change_color(i): c.set_fc((i/100, 0, 0, 1)) ani = FuncAnimation(fig, change_color, frames = range(100), interval=250) plt.show()
unknown
d18066
test
This is done because of thread safety, and prevention of exception raising in the case the delegate turns null. Consider this code: if (this.OnStart != null) { this.OnStart(this, System.EventArgs.Empty); } Between the execution of the if and the execution of this.OnStart, the OnStart delegate could have been manipulated (possibly changed to null, which would result in an exception). In the form you provided in your question, a copy of the delegate is made and used when executing. Any change in the original delegate will not be reflected in the copy, which will prevent an exception from coming up. There is a disadvantage with this though: As any changes in the meantime will not be reflected in the copy, which also includes any non-null state, will result in either calling delegates already removed or not calling delegates recently added to it.
unknown
d18067
test
24 * (log(2) / log(10)) = 7.2247199 That's pretty representative for the problem. It makes no sense whatsoever to express the number of significant digits with an accuracy of 0.0000001 digits. You are converting numbers to text for the benefit of a human, not a machine. A human couldn't care less, and would much prefer, if you wrote 24 * (log(2) / log(10)) = 7 Trying to display 8 significant digits just generates random noise digits. With non-zero odds that 7 is already too much because floating point error accumulates in calculations. Above all, print numbers using a reasonable unit of measure. People are interested in millimeters, grams, pounds, inches, etcetera. No architect will care about the size of a window expressed more accurately than 1 mm. No window manufacturing plant will promise a window sized as accurate as that. Last but not least, you cannot ignore the accuracy of the numbers you feed into your program. Measuring the speed of an unladen European swallow down to 7 digits is not possible. It is roughly 11 meters per second, 2 digits at best. So performing calculations on that speed and printing a result that has more significant digits produces nonsensical results that promise accuracy that isn't there. A: If you have a C library that is conforming to C99 (and if your float types have a base that is a power of 2 :) the printf format character %a can print floating point values without lack of precision in hexadecimal form, and utilities as scanf and strod will be able to read them. A: If the program is meant to be read by a computer, I would do the simple trick of using char* aliasing. * *alias float* to char* *copy into an unsigned (or whatever unsigned type is sufficiently large) via char* aliasing *print the unsigned value Decoding is just reversing the process (and on most platform a direct reinterpret_cast can be used). A: In order to guarantee that a binary->decimal->binary roundtrip recovers the original binary value, IEEE 754 requires The original binary value will be preserved by converting to decimal and back again using:[10] 5 decimal digits for binary16 9 decimal digits for binary32 17 decimal digits for binary64 36 decimal digits for binary128 For other binary formats the required number of decimal digits is 1 + ceiling(p*log10(2)) where p is the number of significant bits in the binary format, e.g. 24 bits for binary32. In C, the functions you can use for these conversions are snprintf() and strtof/strtod/strtold(). Of course, in some cases even more digits can be useful (no, they are not always "noise", depending on the implementation of the decimal conversion routines such as snprintf() ). Consider e.g. printing dyadic fractions. A: The floating-point-to-decimal conversion used in Java is guaranteed to be produce the least number of decimal digits beyond the decimal point needed to distinguish the number from its neighbors (more or less). You can copy the algorithm from here: http://www.docjar.com/html/api/sun/misc/FloatingDecimal.java.html Pay attention to the FloatingDecimal(float) constructor and the toJavaFormatString() method. A: If you read these papers (see below), you'll find that there are some algorithm that print the minimum number of decimal digits such that the number can be re-interpreted unchanged (i.e. by scanf). Since there might be several such numbers, the algorithm also pick the nearest decimal fraction to the original binary fraction (I named float value). A pity that there's no such standard library in C. * *http://www.cs.indiana.edu/~burger/FP-Printing-PLDI96.pdf *http://grouper.ieee.org/groups/754/email/pdfq3pavhBfih.pdf A: You can use sprintf. I am not sure whether this answers your question exactly though, but anyways, here is the sample code #include <stdio.h> int main( void ) { float d_n = 123.45; char s_cp[13] = { '\0' }; char s_cnp[4] = { '\0' }; /* * with sprintf you need to make sure there's enough space * declared in the array */ sprintf( s_cp, "%.2f", d_n ); printf( "%s\n", s_cp ); /* * snprinft allows to control how much is read into array. * it might have portable issues if you are not using C99 */ snprintf( s_cnp, sizeof s_cnp - 1 , "%f", d_n ); printf( "%s\n", s_cnp ); getchar(); return 0; } /* output : * 123.45 * 123 */ A: With something like def f(a): b=0 while a != int(a): a*=2; b+=1 return a, b (which is Python) you should be able to get mantissa and exponent in a loss-free way. In C, this would probably be struct float_decomp { float mantissa; int exponent; } struct float_decomp decomp(float x) { struct float_decomp ret = { .mantissa = x, .exponent = 0}; while x != floor(x) { ret.mantissa *= 2; ret.exponent += 1; } return ret; } But be aware that still not all values can be represented in that way, it is just a quick shot which should give the idea, but probably needs improvement.
unknown
d18068
test
The dot is not uniquely a racket thing, but a lisp thing. A list is made out of pairs and one pair has the literal form (car . cdr) and a list of the elements 2, 3 is made up like (2 . (3 . ())) and the reader can read this, however a list that has a pair as it's cdr can be shown without the dot and the parens such that (2 . (3 . ())) is the same as (2 3 . ()). Also a dot with the special empty list in the end can be omitted so that (2 3) is how it can be read and the only way display and the REPL would print it. What happens if you don't have a pair or null as the cdr? Then the only way to represent it is as a dotted. With (2 . (3 . 5)) you can only simplify the first dot so it's (2 3 . 5). The literal data structure looks like an assoc with pairs as elements where the car is the key and cdr is the value. Using a new pair is just wast of space. As an parameter list an interpreter looks at the elements and if it's a pair it binds the symbol in car, but if it's not a pair it is either finished with null or you have a rest argument symbol. It's convenient way to express it. Clojure that don't have dotted pairs use a & element while Common Lisp does dotted in structures, but not as a parameter specification since it supports more features than Scheme and Clojure and thus use special keywords to express it instead. The second is #lang racket specific and is indeed used to support infix. If you write (5 . + . 6) a reader extension will change it to (+ 5 6) before it gets evaluated. It works the same way even if it's quoted or actual code and curlies are of course equal to normal and square parentheses so the second one actually becomes: (define new-post-formlet (formlet (#%# ,(=> input-string title) ,(=> input-string body)) (values title body))) If you were to use #!r5rs or #!r6rs in racket (5 . + . 6) will give you a read error.
unknown
d18069
test
You get an infinite loop because of these lines: (defun subset-sum (numbers capacity counter) (let ((exclude (subset-sum (cdr numbers) capacity counter)) You keep calling subset-sum recursively, and it never terminates. Even when you get to the end of the list, and numbers is (), you keep going, because (cdr '()) is '(). You handled this in the original by checking (null numbers) (though it might be more idiomatic to use (endp numbers)). Now you can do something like: (defun subset-sum (numbers capacity counter) (if (endp numbers) counter (let ((exclude (subset-sum (cdr numbers) capacity counter)) ;... ) (cond ; ... ))))
unknown
d18070
test
It looks like you're updating the wrong property in state. Updating editCodes array, but never reading from it. In addEditCode method, shouldn't this line: this.setState({ editCodes: arrayCode }) be this: this.setState({ arrayCodes: arrayCode }) ? A: You want something like this: class Testing extends React.Component { state = { arrayCodes: ["A1", "A2"], currentCode: "" }; addEditCode = inputCode => { const { arrayCodes } = this.state; arrayCodes.push(inputCode); this.setState({ arrayCodes }); }; setCurrentCode = input => { this.setState({ currentCode: input }); }; render() { return ( <div> <input type="text" name="enteredCode" placeholder="Enter an edit code to add..." onChange={event => this.setCurrentCode(event.target.value)} /> <button onClick={() => this.addEditCode(this.state.currentCode)}> Click to add </button> <h1> Current array in state: {this.state.arrayCodes.reduce((acc, c) => { return acc + c; }, "")} </h1> </div> ); } } Working example here. A: Well the problem is in the states * *editCodes ==> the one getting updated but not in the render method *arrayCodes ==>the one you are showing in the render method *currentCode ==> saving the value temporarily for the new value Just Change it to addEditCode = inputCode => { let arrayCodes = this.state.arrayCodes; arrayCodes.push(inputCode); this.setState({ arrayCodes }); }; Happy Coding \m/ In addition to that Use map or reduce to render the updated array
unknown
d18071
test
I've ran into the same Issue. It's difficult to test wether notifyListeners was called or not especially for async functions. So I took your Idea with the listenerCallCount and put it to one function you can use. At first you need a ChangeNotifier: class Foo extends ChangeNotifier{ int _i = 0; int get i => _i; Future<bool> increment2() async{ _i++; notifyListeners(); _i++; notifyListeners(); return true; } } Then the function: Future<R> expectNotifyListenerCalls<T extends ChangeNotifier, R>( T notifier, Future<R> Function() testFunction, Function(T) testValue, List<dynamic> matcherList) async { int i = 0; notifier.addListener(() { expect(testValue(notifier), matcherList[i]); i++; }); final R result = await testFunction(); expect(i, matcherList.length); return result; } Arguments: * *The ChangeNotifier you want to test. *The function which should fire notifyListeners (just the reference to the function). *A function to the state you want to test after each notifyListeners. *A List of the expected values of the state you want to test after each notifyListeners (the order is important and the length has to equal the notifyListeners calls). And this is how to test the ChangeNotifier: test('should call notifyListeners', () async { Foo foo = Foo(); expect(foo.i, 0); bool result = await expectNotifyListenerCalls( foo, foo.increment2, (Foo foo) => foo.i, <dynamic>[isA<int>(), 2]); expect(result, true); }); A: Your approach seems fine to me but if you want to have a more descriptive way you could also use Mockito to register a mock callback function and test whether and how often the notifier is firing and thus notifying your registered mock instead of incrementing a counter: import 'package:mobile_app/example_model.dart'; import 'package:test/test.dart'; /// Mocks a callback function on which you can use verify class MockCallbackFunction extends Mock { call(); } void main() { group('$ExampleModel', () { late ExampleModel exampleModel; final notifyListenerCallback = MockCallbackFunction(); // Your callback function mock setUp(() { exampleModel = ExampleModel() ..addListener(notifyListenerCallback); reset(notifyListenerCallback); // resets your mock before each test }); test('increments value and calls listeners', () { exampleModel.increment(); expect(exampleModel.value, 1); exampleModel.increment(); verify(notifyListenerCallback()).called(2); // verify listener were notified twice }); test('unit tests are independent from each other', () { exampleModel.increment(); expect(exampleModel.value, 1); exampleModel.increment(); expect(notifyListenerCallback()).called(2); // verify listener were notified twice. This only works, if you have reset your mocks }); }); } Just keep in mind that if you trigger the same mock callback function in multiple tests you have to reset your mock callback function in the setup to reset its counter. A: I have wrap it to the function import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; dynamic checkNotifierCalled( ChangeNotifier notifier, Function() action, [ Matcher? matcher, ]) { var isFired = false; void setter() { isFired = true; notifier.removeListener(setter); } notifier.addListener(setter); final result = action(); // if asynchronous if (result is Future) { return result.then((value) { if (matcher != null) { expect(value, matcher); } return isFired; }); } else { if (matcher != null) { expect(result, matcher); } return isFired; } } and call it by: final isCalled = checkNotifierCalled(counter, () => counter.increment(), equals(2)); expect(isCalled, isTrue);
unknown
d18072
test
I would suggest a bunch of changes. * *Stop using globals or higher scoped variables or undeclared variables. Declare local variables where they are used/needed and don't share variables with other functions. *Don't mix the async library with promises. Since you're already promisifying your async functions, then use promise functions to manage multiple async operations. You can just remove the async library from this project entirely. *Promisify at the lowest level that is practical so all higher level uses can just use promises directly. So, rather than promisifying getPage(), you should promisify request() and then use that in getPage(). *Since you have the Bluebird promise library, you can use it's higher level iteration functions such as Promise.map() to iterate your collection, collect all the results and return a single promise that tells you when everything is done. Using these concepts, you can then use code like this: // promisified request() function getRequest(url) { return new Promise(function(resolve, reject) { request(url, function(err, response, body) { if (err) { reject(err); } else { resolve(body); } }); }); } // resolves to scraped contents for one page function getPage(url, config) { return getRequest(url).then(function(body) { return sX.scrape(body, config); }); } // resolves to an array of scraped contents for an array of objects // that each have a link in them function getDetailPage(arr, config) { return Promise.map(arr, function(item) { return getPage('http://www.shirts4mike.com' + '/' + item.link); }); }
unknown
d18073
test
You can add a mapping for all requests with the * extension to the ASP.NET isapi dll (GET/POST) verbs. You will need to uncheck the "verify file is on disk" checkbox when mapping the extension in IIS. (In IIS7 integrated mode, you map the extension in the web.config as well). Note that this will caause everything to be served by asp.net, even images and script files, which can slow things down. Then create a handler mapping in your web.config to a http handler you create. From there, in the ProcessRequest() method of the handler, you have access to the HttpContext that spawned the request and can manipulate the URL from there. That is the easiest option, you could also create a HttpModule, or have the default page at root redirect to http://www.domain.com/default.aspx/this is my text, in the code-behind of default.aspx, you will be able to get the text following the page and slash.
unknown
d18074
test
First, you should close all your <tr> and <td> tags. Second, you're not sending any file with your form, and hence you're getting this Undefined index: file error, so remove these lines, $file_filename=$_FILES['file']['name']; $target_path = "Newfolder1"; $image_path = $target_path . DIRECTORY_SEPARATOR . "filename"; $image_format = strtolower(pathinfo('filename', PATHINFO_EXTENSION)); So after user hits view button, you should process your form and display image like this, // your code if (isset($_POST['View']) ){ $pdf=new fpdf(); $pdf->ADDPage(); $pdf->setfont('Arial','B', 16); $pdf->Cell(40,10, 'sname',1,0,'c'); $pdf->Cell(40,10, 'sadd',1,0,'c'); $pdf->Cell(40,10, 'category',1,0,'c'); $pdf->Cell(40,10, 'scode',1,0,'c'); $con = mysqli_connect("localhost","root","","school"); if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $sql="SELECT * FROM imagetable WHERE ID= '$_POST[search]'"; $result = mysqli_query($con, $sql); if(!mysqli_query($con, $sql)){ die( "Could not execute sql: $sql"); } $row = mysqli_fetch_array($result); $image_path = $row['file'] . DIRECTORY_SEPARATOR . $row['filename']; // path should be like this, process/upload/8/cdv_photo_001.jpg $image_format = strtolower(pathinfo($image_path, PATHINFO_EXTENSION)); $pdf->Cell(40,10, $row['sname'],1,0,'c'); $pdf->Cell(40,10, $row['sadd'],1,0,'c'); $pdf->Cell(40,10, $row['category'],1,0,'c'); $pdf->Image($image_path,50,100,50,20,$image_format); $pdf->ln(); $pdf->output(); } // your code
unknown
d18075
test
Doubles are not objects, so referring to them as strong and weak does not make sense because they do not have reference counts. In practice, they obey the typical rules of variable scope. However, they should really not be a cause for significant memory usage, unless you are using very large arrays of them. My feeling is that something else is probably going on - probably to do with other data types present and how data is being passed between the functions.
unknown
d18076
test
You have to fill in the Category and Action field at the very least for GA to register a hit. (Categoira, Accion, I guess) Those aren't filter fields, they are the fields sent in an event hit. You will need to use something like the macros {{element text}} or something you want to record to see hits in GA. Check out the Event Tracking Guide by Google for more details.
unknown
d18077
test
This page covers the minimum recommended specification for running Couchbase Server. The minimum hardware specifications to install and effectively operate Couchbase Server are: Dual-core x86 CPU running at 2GHz. 4GB RAM (physical). It then goes on to say... The specification can be as low as 1GB of free RAM beyond operating system requirements and a single CPU core.
unknown
d18078
test
The solution was to add this bit to the policy of the service role: { "Effect": "Allow", "Action": "codestar-connections:UseConnection", "Resource": "insert ARN of the CodeStar connection here" }
unknown
d18079
test
You can use readObject and writeObject methods for this purpose. writeObject method will be executed when serializing your object reference. Basically, you will do it like this: public class MyClassToSerialize implements Serializable { private int data; /* ... methods ... */ private void writeObject(ObjectOutputStream os) throws IOException { os.defaultWrite(); //serialization of the current serializable fields //add behavior here } } More info on the usage of these methods: http://docs.oracle.com/javase/7/docs/platform/serialization/spec/serialTOC.html
unknown
d18080
test
First of all, it is a bad idea to use a Socket to make HTTP requests. It is better to use an existing library class / method; for example: new URL("https://example.com/foo/bar?param=xxx").openConnection(); This gives you some subclass of URLConnnection that you can use to form the request and get the reply from the server There are alternative libraries for making HTTP / HTTPS requests. For example, the Apache HttpComponents libraries can be a good choice, if your requirements are complicated. However, I suspect that the real reason that you are getting nothing back from your request, is that you are trying to talk to an "https" server (port 443) without using an SSL / TLS connection. That ain't going to work. The server is likely to just close the socket. While it is possible to establish an SSL / TLS connection over a plain Socket (in theory) or use an SSLSocket, it is simpler to use a properly formed "https://..." URL and (for example) URL.openConnection() as above. Moving past that, the header lines in your supposed request look syntactically invalid. Both Accept value: ... and Host value: .... are wrong. If really want to implement the HTTP message handling yourself, you need to read the HTTP 1.1 specification, and implement it to the letter. And finally (as @EJP points out) your code isn't even reading the response. Writing to an OutputStream is not going to "return" anything. You need to read the response from an InputStream ... even if only to check that the request was accepted. A: The problem is that the webService is not called. You haven't provided any evidence to that effect, and it is impossible to tell from the code you've posted. The getOutputStream() retuns an OutputStream that has no message from the WebService. This is meaningless. OutputStreams don't contain messages from the peer. They are used to send messages to the peer. This statement and your title are completely nonsensical. Is there anyway to check that the WebService has been called successfully? Yes. Read the response, and return it, instead of hardwiring "OK". And you've just posted code that does exactly that. Agreed it is not the most beautiful code. It isn't even correct code. The HTTP headers are invalid, and it makes no attempt to read a response. It's just incompetent. Use the HttpURLConnection code you posted.
unknown
d18081
test
Yes. You can use whatever you want for your model layer. Note, you can use raw SQL queries with LINQ To SQL as well. Northwnd db = new Northwnd(@"c:\northwnd.mdf"); IEnumerable<Customer> results = db.ExecuteQuery<Customer> (@"SELECT c1.custid as CustomerID, c2.custName as ContactName FROM customer1 as c1, customer2 as c2 WHERE c1.custid = c2.custid" ); Or perhaps your instructor wants straight up ADO.NET, which works fine too. There is an example here. A: You can use raw SQL queries in ASP.Net MVC the same way you use them anywhere else. It can be helpful to use idioms like using (var reader = command.ExecuteReader()) return View(reader.Select(dr => new { Name = dr["Name"], ... })); EDIT: It appears that you're asking how to use ADO.Net in general. Try this tutorial. A: Of course you can use SQL in ASP.NET MVC. I'd consider keeping the SQL code on stored procedures rather than hard-coding the SQL directly in the application code. It's better to maintain and it's a good practice that will probably be looked upon by your instructor. A: SQL has nothing to do with ASP.NET MVC. ASP.NET MVC is a web framework for building web sites and applications. My suggestion is that you try to abstract as much as possible, the MVC application shouldn't know if you're using SQL (stored procedures), Entity Framework, Linq-to-sql or if you get your data from a web-service.
unknown
d18082
test
If your installer needs systemd running, I think you will need to launch a container with the base centos/systemd image, manually run the commands, and then save the result using docker commit. The base image ENTRYPOINT and CMD are not run while child images are getting built, but they do run if you launch a container and make your changes. After manually executing the installer, run docker commit {my_intermediate_container} {my_image}:{my_version}, replacing the bits in curly braces with the container name/hash, your desired image name, and image version. You might also be able to change your Dockerfile to launch init before running your installer. I am not sure if that will work here in the context of building an image, but that would look like: FROM centos/systemd COPY ./ZendServer-9.1.0-RepositoryInstaller-linux.tar.gz /opt RUN tar -xvf /opt/ZendServer-9.1.0-RepositoryInstaller-linux.tar.gz -C /opt/ \ && /usr/sbin/init \ && /opt/ZendServer-RepositoryInstaller-linux/install_zs.sh 7.1 java --automatic A: A LAMP stack inside a docker container does not need systemd - I have made to work with the docker-systemctl-replacement script. It is able to start and stop a service according to what's written in the *.service file. You could try it with what the ZendServer is normally doing outside a docker container.
unknown
d18083
test
It is really a good practice to use key attribute while rendering a collection, it helps react to rerender collections of components correctly. So i can assume you should try to add unique key attribute to the place, where you render Note component, e.g <Note key={'some unique id'} /> A: There is an issue with your delete case in reducer. You are not returning the boolean, so no items will be returned, case "DELETE_COMPONENT": return { ...state, components: state.components.filter( (component: any) => { console.log(component.id, action.payload) console.log(component.id !== action.payload) return component.id !== action.payload // here is the fix }) };
unknown
d18084
test
If you just want to do it in procedural PHP, you could do something like this: $runningTitle = ''; while($row=$stmt->fetch(PDO::FETCH_BOTH)) { if ($row['title'] != $runningTitle) { $runningTitle = $row['title']; print "<h1>"; print utf8_encode($row['title']); print "</h1>"; } // now render images. } However I would recommend using a more object orientated approach to build the html string and then return it as a single string, to echo at the end, rather than rendering everything out procedurally. It's often tidier to complete all your program logic before rendering a page, rather than rendering while you are still asking the code to make decisions. You are using PHP in it's traditional form - as a templating language. It has come a long way since then. A: It's some easy and fast and if your "join" images are few, not many. Your group by, use a GROUP BY and get all images concatenated by SEPARATOR with GROUP_CONCAT SELECT posts.*, COUNT(0) total, GROUP_CONCAT(dir_image SEPARATOR '|') images FROM posts INNER JOIN images ON (posts.id_post = images.post_id ) WHERE slug=:slug GROUP BY id_post This is your loop, create an array exploding the SEPARATOR over field "images" and do the loop while ($row = $stmt->fetch(PDO::FETCH_BOTH)) { $aImages = explode('|', $row['images']); ?> <h1><?php print utf8_encode($row['title']); ?></h1> <div> <ul> <?php echo '<li>' . implode('</li><li>', $aImages) . '</li>' ?> </ul> </div> <?php } ?> Or while ($row = $stmt->fetch(PDO::FETCH_BOTH)) { $aImages = explode('|', $row['images']); ?> <h1><?php print utf8_encode($row['title']); ?></h1> <div> <?php foreach ($aImages as $sImage) { ?> <a href="<?php echo $sImage;?>"><?php echo $sImage; ?></a> <?php } ?> </div> <?php } ?>
unknown
d18085
test
The error IndexError: index 37 is out of bounds for axis 0 with size 37 means that there is no element with index 37 in your object. In python, if you have an object like array or list, which has elements indexed numerically, if it has n elements, indexes will go from 0 to n-1 (this is the general case, with the exception of reindexing in dataframes). So, if you ahve 37 elements you can only retrieve elements from 0-36. A: This is a multi-class classifier with a huge Number of Classes (38 classes). It seems like GridSearchCV isn't spliting your dataset by stratified sampling, may be because you haven't enough data and/or your dataset isn't class-balanced. According to the documentation: For integer/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used. By using categorical_crossentropy, KerasClassifier will convert targets (a class vector (integers)) to binary class matrix using keras.utils.to_categorical. Since there are 38 classes, each target will be converted to a binary vector of dimension 38 (index from 0 to 37). I guess that in some splits, the validation set doesn't have samples from all the 38 classes, so targets are converted to vectors of dimension < 38, but since GridSearchCV is fitted with samples from all the 38 classes, it expects vectors of dimension = 38, which causes this error. A: Take a look at the shape of your y_train. It need to be a some sort of one hot with shape (,37)
unknown
d18086
test
You can do Ajax request add id to form :id => "question-form" = form_for :question, :url => question_path, :remote => true, :html =>{:class => 'question-form', :id => "question-form"} do |form| and anywhere in javascript file $("#question-form").on("submit", function(e){ e.preventDefault(); var form = $(this); var request = $.ajax({ method: "POST", beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}, url: "/questions", dataType: "json", data: form.serialize() }) request.done(function(res){ console.log(res.success); }) request.catch(function(jqXHR){ console.log(jqXHR.responseJSON) }) })
unknown
d18087
test
I think you could. The language seems well suited for such situations, assuming you trust the compiler enough to use it in mission critical situation. Remember that in mission critical situations it is not only your code that is under scrutiny, but all other components too. That includes compiler (Haskell compiler is not among the easiest ones to code review), appropriate certified hardware that runs the software, appropriate hardware that compiles your code, hardware that bootstraps the compilation of the compiler that will compile your code, hell - even wires that connect that all to the power grid and frequency of voltage change in the socket. If you are interested in looking at mission critical software quality, I suggest looking at NASA software quality procedures. They are very strict and formal, but well these guys throw millions of dollars in space in hope it will survive pretty rough conditions and will make it to Mars or wherever and then autonomously operate and send some nice photos of Martians back to earth. So, there you go: Haskell is good for mission critical situations, but it'd be an expensive process to bootstrap its usage there.
unknown
d18088
test
You can create a ListSlice<T> class that represents a slice of an existing list. The slice will behave as a read-only list and because it keeps a reference to the original list you are not supposed to add or remove elements in the original list. This cannot be enforced unless you implement your own list but I will not do that here. You will have to implement the entire IList<T> interface including the IEnumerator<T> you need for enumerating the slice. Here is an example: class ListSlice<T> : IList<T> { readonly IList<T> list; readonly Int32 startIndex; readonly Int32 length; public ListSlice(IList<T> list, Int32 startIndex, Int32 length) { if (list == null) throw new ArgumentNullException("list"); if (!(0 <= startIndex && startIndex < list.Count)) throw new ArgumentException("startIndex"); if (!(0 <= length && length <= list.Count - startIndex)) throw new ArgumentException("length"); this.list = list; this.startIndex = startIndex; this.length = length; } public T this[Int32 index] { get { if (!(0 <= index && index < this.length)) throw new ArgumentOutOfRangeException(); return this.list[this.startIndex + index]; } set { if (!(0 <= index && index < this.length)) throw new ArgumentOutOfRangeException(); this.list[this.startIndex + index] = value; } } public Int32 IndexOf(T item) { var index = this.list.IndexOf(item); return index == -1 || index >= this.startIndex + this.length ? -1 : index - this.startIndex; } public void Insert(Int32 index, T item) { throw new NotSupportedException(); } public void RemoveAt(Int32 index) { throw new NotSupportedException(); } public Int32 Count { get { return this.length; } } public Boolean IsReadOnly { get { return true; } } public void Add(T item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public Boolean Contains(T item) { return IndexOf(item) != -1; } public void CopyTo(T[] array, Int32 arrayIndex) { for (var i = this.startIndex; i < this.length; i += 1) array[i + arrayIndex] = this.list[i]; } public Boolean Remove(T item) { throw new NotSupportedException(); } public IEnumerator<T> GetEnumerator() { return new Enumerator(this.list, this.startIndex, this.length); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } class Enumerator : IEnumerator<T> { readonly IList<T> list; readonly Int32 startIndex; readonly Int32 length; Int32 index; T current; public Enumerator(IList<T> list, Int32 startIndex, Int32 length) { this.list = list; this.startIndex = startIndex; this.length = length; } public T Current { get { return this.current; } } Object IEnumerator.Current { get { if (this.index == 0 || this.index == this.length + 1) throw new InvalidOperationException(); return Current; } } public Boolean MoveNext() { if (this.index < this.length) { this.current = this.list[this.index + this.startIndex]; this.index += 1; return true; } this.current = default(T); return false; } public void Reset() { this.index = 0; this.current = default(T); } public void Dispose() { } } } You can write an extension method to make it easier to work with slices: static class ListExtensions { public static ListSlice<T> Slice<T>(this IList<T> list, Int32 startIndex, Int32 length) { return new ListSlice<T>(list, startIndex, length); } } To use the slice you can write code like this: var list = new List<String> { "Tyrannosaurus", "Amargasaurus", "Mamenchisaurus" }; var slice = list.Slice(1, 2); slice[0] = "Stegosaurus"; Now list[1] as well as slice[0] contains "Stegosaurus". A: Assuming you really did mean clone and not copy... List<string> myoriginalstring = new List<string> { "Tyrannosaurus", "Amargasaurus", "Mamenchisaurus" }; List<string> myCloneString = myoriginalstring.GetRange(1, myoriginalstring.Count() -1 ); A: On the first glance, it seems as if var list2 = myoriginalstring.SkipWhile((str, i)=>!(i>=1 && i<=2)).ToList(); list2[1]="Stegosaurus"; would be the solution. But it is not, because list2 is a independent list which contains its own elements. The code above works, but it replaces only the element in the (new) list2, not in myoriginalstring. As you pointed out, this is not what you wanted to do. Solution Unlike other languages like C, you don't have access to pointers directly in C#. Hence, the solution is more complex. Instead of using strings directly, you need to create an object, like the following: public class Dino { public string Value { get; set; } public object[] Parent { get; set; } public int ParentIndex; } Then, create some helper extension methods, like so: public static class Extensions { public static Dino AsDino(this string name) { return new Dino() {Value=name}; } public static Dino AsDino(this string name, object[] reference, int parentIndex) { return new Dino() {Value=name, Parent=reference, ParentIndex=parentIndex }; } public static Dino Replace(this object item, Dino replacementItem) { replacementItem.ParentIndex=((Dino)item).ParentIndex; replacementItem.Parent=((Dino)item).Parent; ((Dino)item).Parent[replacementItem.ParentIndex]=replacementItem; return replacementItem; } } With those helpers, you can do it: // create array with 3 elements var myoriginalstring = new object[3]; // fill in the dinosours and keep track of the array object and positions within myoriginalstring[0]="Tyrannosaurus".AsDino(myoriginalstring, 0); myoriginalstring[1]="Amargasaurus".AsDino(myoriginalstring, 1); myoriginalstring[2]="Mamenchisaurus".AsDino(myoriginalstring, 2); // get a subset of the array var list2 = myoriginalstring.SkipWhile((str, i)=>!(i>=1 && i<=2)).ToList<object>(); // replace the value at index 1 in list2. This will also replace the value // in the original array myoriginalstring list2[1].Replace("Stegosaurus".AsDino()); The trick is, that the Dino class keeps track of its origin (the array myoriginalstring) and the position within it (i.e. its index).
unknown
d18089
test
Here's one way: $ sed 's/:/" "/g; s/.*/"&"/' example1.txt "1.2.3.4" "21" "172.16.1.2" "80" "192.168.5.4" "443" "192.168.10.1" "7007" The first s command replaces every colon with " " and the second just adds the leading and trailing double-quotes. Use the i flag if you need to save the changes to the original file. A: sed with a single s//: $ sed 's/\([^:]*\):\(.*\)/"\1" "\2"/' input.txt "1.2.3.4" "21" "172.16.1.2" "80" "192.168.5.4" "443" "192.168.10.1" "7007" A: This might work for you (GNU sed): sed 's/[^:]*/"&"/g;y/:/ /' file Surround fields delimited by :s by double quotes and replace :'s by spaces. A: Since there isn't an awk solution posted yet: $ awk -F':' -v OFS='" "' '{$1=$1; print "\"" $0 "\""}' file "1.2.3.4" "21" "172.16.1.2" "80" "192.168.5.4" "443" "192.168.10.1" "7007"
unknown
d18090
test
Unfortunately, to my knowledge there's no way to define what types input should have in Laravel/Lumen when the value is accessed. PHP interprets all user input as strings (or arrays of strings). In Illuminate\Validation\Validator, the method that determines if a value is an integer uses filter_var() to test if the string value provided by the user conforms to the rules of the int type. Here's what it's actually doing: /** * Validate that an attribute is an integer. * * @param string $attribute * @param mixed $value * @return bool */ protected function validateInteger($attribute, $value) { if (! $this->hasAttribute($attribute)) { return true; } return is_null($value) || filter_var($value, FILTER_VALIDATE_INT) !== false; } Alas, it does not then update the type of the field it checks, as you have seen. I think your use of intval() is probably the most appropriate option if you absolutely need the value of the user_id field to be interpreted as an integer. Really the only caveat of using intval() is that it is limited to returning integers according to your operating system. From the documentation (http://php.net/manual/en/function.intval.php): 32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. So for example on such a system, intval('1000000000000') will return 2147483647. The maximum signed integer value for 64 bit systems is 9223372036854775807. So as long as you keep your user-base to less than 2,147,483,647 users, you shouldn't have any issues with intval() if you're on a 32-bit system. Wouldn't we all be so lucky as to have to worry about having too many users? Joking aside, I bring it up because if you're using intval() for a user-entered number that might be huge, you run the risk of hitting that cap. Probably not a huge concern though. And of course, intval() will return 0 for non-numeric string input.
unknown
d18091
test
Q.all accepts an array of promises and returns Promise which is resolved if all promises are resolved or rejected if one of them is rejected. Your calls to Q.all(promise, promise, promise) are not valid. It has to be Q.all([promise, promise, promise]). Returned promise is resolved with an array of results from promises, in your case it will be 3 same persons. Little example (will print 1, 2, 3 to console): Q.all([ Promise.resolve(1), Promise.resolve(2), Promise.resolve(3) ]).then(function(numbers) { console.log(numbers); }; To make it work, you need to change your code like this https://jsfiddle.net/g8sgqrof/
unknown
d18092
test
It appears that LDA has a learn rate thats computed based on (but stored separately from) the global learning rate. LDA's learning/decay rates don't appear to be printed anywhere, so you wouldn't see them in the logs. https://github.com/VowpalWabbit/vowpal_wabbit/blob/master/vowpalwabbit/lda_core.cc#L892
unknown
d18093
test
val MyCustomService = new MyService() with MyOtherTableName should work If you want to also inherit from the DefaultDBProvider and DefaultTableNames, you would have to either list them explicitly as well: val MyCustomService = new MyService() with MyOtherTableName with DefaultDBProvider with DefaultTableNames or create an intermediate trait in the common library: trait DefaultService extends MyService with DefaultDBProvider with DefaultTableNames A: You cannot override constructed type like that because MyService() is an object not a type anymore. So to reuse your code you might create a class like class ConfiguredMyService extends DefaultDBProvider with DefaultTableNames in the first app you can declare object MyService { def apply() = new ConfiguredMyService } and in the second val MyCustomService = new ConfiguredMyService with MyOtherTableName Note: Nowadays, Cake pattern is considered an anti-pattern, so I recommend you checkout Dependency Injection.
unknown
d18094
test
async is a reserved keyword in Python 3.7+, and you'll need to use the latest version of Spyne, which doesn't use that reserved keyword as a parameter in its functions, if you want to use it with Python 3.7+. Either update Spyne to spyne-2.13.2-alpha, or use Python 3.6 or lower. Sources: * *https://docs.python.org/3/whatsnew/3.7.html *https://pypi.org/project/spyne/2.13.2a0/
unknown
d18095
test
Use str_detect from stringr which is vectorized for both string and pattern library(stringr) library(dplyr) df %>% mutate(match = str_detect(b, a)) a b match 1 ABC XXC FALSE 2 ABB XCT ABB TRUE 3 ACC TTG WHO ACC TRUE 4 AAG AAG TRUE A: A base R option transform( df, match = mapply(grepl, a, b, USE.NAMES = FALSE) ) gives a b match 1 ABC XXC TTZ FALSE 2 ABB XCT ABB TRUE 3 ACC TTG WHO ACC TRUE 4 AAG AAG TRUE
unknown
d18096
test
For model binding to work, your form element's name should match with the your view model property name(s)/hierarchy. So if you are doing a normal form submit, it is best if you add a new form element to your form ( a hidden element) and store the value there. As long as you have the name attribute value matching with the view model property name, model binding will simply work. Assuming you have a view model like this public class CreatePost { public IList<DateTime> MyDates { set; get; } //Some other properties for the view } Now, lets create a javascript method which will create a new form element and append that to the form.The below example assumes you included jQuery in your page. function addHiddenDate(dateString) { var itemCount = $("input.myDates").length; var dat = $("<input type='hidden' class='myDates' name='MyDates[" + itemCount++ + "]' />").val(dateString); $("form").append(dat); } And whenver user add's a new date, instead of adding to the array, call this method and pass the date value. $(function(){ $("#addBtn").click(function(e){ e.preventDefault(); addHiddenDate($("#DateInputField").val()); }); }); Now when you submit the form, Model binding will correctly map the posted form data to the action method parameter, assuming the parameter is of type CreatePost [HttpPost] public ActionResult Create(CreatePost model) { // check model.MyDates // to do : Return something }
unknown
d18097
test
The reason that you find these chips only in smart cards is that that is the best method of developing on them without hassle. There are also form factors for use in e.g. key fobs, which is probably what you're after. That means smaller antenna space and less chance of a good response. These chips and antenna's are tricky to get right so that all distances and orientations work well. Paper smart cards are commonly not smart cards but throw away memory cards like MiFare or MiFare ultra-light. Usually smart cards come in credit card form, like -uh- those in credit cards. And then they are in plastic (PVC) or polycarbonate for the higher end cards. Demo cards are usually plastic though. Manufacturers aren't shy of not putting any chips or antenna's in there at all when it comes to demo cards (they might be showing off their printing capabilities instead). The classic Java cards can be in any form factor. However, the more memory the larger the die may be. That can be an issue with some packaging, the small container that the IC is put in and to which the antenna's are connected. Although Java Card 3 is somewhat of a jump in functionality, most cards capable of version 2 would also be OK to run version 3 of Java Card. The failed web-based "connected" Java Card requires a lot of memory and if you can find it, it will probably be limited to specific form factors. Java Card 3.1 seems to be another jump in functionality for the common "classic" platform and I would expect for high end smart cards to lead the way. Generally we don't talk prices here. If you are interested in bulk pricing for specific form factors then you need to contact the resellers, not us. But I would first try and read into it. There are some great general purpose books out there on smart cards. That way you'd at least know a bit what you're talking about when contacting such vendor, and in that case you're more likely to be taken seriously.
unknown
d18098
test
First of all create two outlets and connect hose to the views in your ViewController. @IBOutlet weak var firstView: UIView! @IBOutlet weak var secondView: UIView! And Change the code like: @IBAction func indexChanged(sender: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: firstView.hidden = false secondView.hidden = true case 1: firstView.hidden = true secondView.hidden = false default: break; } } If you don't want to create Outlets, assign the views individual tags (Say 101 and 102) and you can do it like: @IBAction func indexChanged(sender: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: self.view.viewWithTag(101)?.hidden = false self.view.viewWithTag(102)?.hidden = true case 1: self.view.viewWithTag(101)?.hidden = true self.view.viewWithTag(102)?.hidden = false default: break; } } A: If you want to do UI layout in Xcode for the two overlapping subviews, a better solution is to use two UIContainerViewController, and use the same way of setting the hidden property as suggested in the above answer. A: You can use the isHidden property of the UIView to show/hide your required views. First you have to link both views to IBOutlets through the Interface builder @IBOutlet weak var historyView: UIView! @IBOutlet weak var popularView: UIView! @IBAction func indexChanged(_ sender: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: historyView.isHidden = true popularView.isHidden = false case 1: historyView.isHidden = false popularView.isHidden = true default: break; } } Note: it was named hidden in Swift 1 and 2. A: Add both views to the view controller in the story board and set one of them to be hidden = yes or alpha = 0. When your index changed function gets called set the current view on screen to hidden = yes/alpha of 0 and set the previously hidden view to hidden = no/alpha = 1. This should achieve what you want. A: @IBAction func acSegmentAction(_ sender: Any) { switch acSegmentedControl.selectedSegmentIndex { case 0: // print("addressview selected") addressView.isHidden = false contactProviderView.isHidden = true case 1: //print("contact provider selected") addressView.isHidden = true contactProviderView.isHidden = false default: break; } } A: If it is a simple view, not a part of the screen, you can indeed use isHidden property of two subviews of your view controller view. But I don't like this approach because it's hard to understand latter what is going on with your nib when all of the subviews are in one pile. I would add and remove those two views as child view controllers programmatically. It's the cleanest way there is, in my opinion. But even if you decided to go with just views, don't put them directly on view controller's view. Use nibs, preferably with owner class. And in many cases consider adding and constraint them programmatically. It's more code, but also cleaner and conserves resources. A: So what is written above does not work for me, so I figured out myself in Xcode 11 with Swift 5. (view1 = historyView, view2 = popularView) @IBOutlet weak var view1: UITableView! @IBOutlet weak var view2: UITableView! @IBAction func segmentedControlChanged(_ sender: Any) { func showView1() { view1.isHidden = false view2.isHidden = true } func showView2() { view1.isHidden = true view2.isHidden = false } guard let segmentedControl = sender as? UISegmentedControl else { return } if segmentedControl.selectedSegmentIndex == 0 { showView1() } else { showView2() } } Maybe this helps anyone.
unknown
d18099
test
There are several problems with the code you've provided. The first problem is finalize() timing. java.sql.Blob implementation depends on the jdbc driver and usually the implementing class stores only identifier of the blob and when content is accessed (using getBinaryStream() for example) another call(s) to database is performed. This implies that at the moment when getBinaryStream() is invoked connection which was used to get blob should be still opened. But JVM doesn't provide any guaranties when finalize will be invoked so accessing Blob in finalize is incorrect. I don't know for sure if PostgreSQL jdbc driver uses this logic for blobs but I know for sure that java.sql.Array implementation has this limitation (that is you cannot invoke methods of array after connection is closed). The second problem is that though blob mapping is defined as lazy even if client didn't use it blob field will always be loaded by finalize(). In general it is responsibility of the client to perform clean up when using blobs. The pattern for usage the blob is: try { blob = entity.getContent(); // ... use blob } finally { // ... do blob cleanup }
unknown
d18100
test
The 'MOLAP' flavour of OLAP (as distinguished from 'ROLAP') is a data store in its own right, separate from the Data Warehouse. Usually, the MOLAP server gets its data from the Data Warehouse on a regular basis. So the data does indeed reside in both. The difference is that a MOLAP server is a specific kind of database (cube) that precalculates totals at levels in hierarchies, and furthermore structures the data to be even easier for users to query and navigate than a data warehouse (with the right tools at their disposal). Although a data warehouse may be dimensionally modelled, it is still often stored in a relational data model in an RDBMS. Hence MOLAP cubes (or other modern alternatives) provide both performance gains and a 'semantic layer' that makes it easier to understand data stored in a data warehouse. The user can then query the MOLAP server rather than the Data Warehouse. That doesn't stop users querying the Data Warehouse directly, if that's what your solution needs. You're right that when the user queries a ROLAP server, it passes on the queries to the underlying database, which may be an OLTP system, but is more often going to be a data warehouse, because those are designed for reporting and query performance and understandability in mind. ROLAP therefore provides the user-friendly 'semantic layer' but relies on the performance of the data warehouse for speed of queries.
unknown