text
stringlengths
15
59.8k
meta
dict
Q: Element to save results with different length in R I want to extract similar text strings using the agrep function and save them in a list or vector, but the result has different length (even replacement could has length zero),so I get an error. How can I define a list or vector in order to save the results even if they have different length? Here is a reproducible example: x <- c("REF.E600J","SIN MODELO","REF.E705N","24-53793A-K","24-53646A-K","33-53633A-K", "REF.E522N","CON MODELO","VAR MODELO","REF.E610L") similitud <- list() for (i in c(1:length(x))) { similitud[i] <- agrep(x[i],x[-i],max=3,value=T) } #Error and warning Error in similitud[i] <- agrep(x[i], x[-i], max = 3, value = T) : replacement has length zero In addition: Warning messages: 1: In similitud[i] <- agrep(x[i], x[-i], max = 3, value = T) : number of items to replace is not a multiple of replacement length 2: In similitud[i] <- agrep(x[i], x[-i], max = 3, value = T) : number of items to replace is not a multiple of replacement length 3: In similitud[i] <- agrep(x[i], x[-i], max = 3, value = T) : number of items to replace is not a multiple of replacement length A: For lists, you use [[ not [ to assign/get a single element ([ returns a sublist). for (i in c(1:length(x))) { similitud[[i]] <- agrep(x[i],x[-i],max=3,value=T) } Just change your similitud[i] to a similitud[[i]].
{ "language": "en", "url": "https://stackoverflow.com/questions/31421460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: If SELECT COUNT is less than or equal to 10, input reservation details I'm trying to make a simple reservations form in PHP. If the amount of bookings with the same date and time is less than or equal to 10, I want it to input the details to the table. Anything else, I want a message to say "Booking failure! We're fully booked at that time." The issue: I have 10 reservations on one specific date and time and the moment for testing, however all of my messages are coming back as "Booking failure! We're fully booked at that time." whatever the time. Nothing's being imported either. I've tested the input process without a SELECT COUNT query and it successfully inputs, so I know something's wrong with my "less than or equal to" query. I'd massively appreciate any help! Thanks <?php require_once('lib/php/functions.php'); require_once('lib/php/db_connect.php'); //Grab Form Data $reservationName = trim($_POST['reservationName']); $reservationEmail = trim($_POST['reservationEmail']); $reservationNumber = trim($_POST['reservationNumber']); $reservationDate = trim($_POST['reservationDate']); $reservationTime = trim($_POST['reservationTime']); $submit = trim($_POST['submit']); $message = ''; if (!$db_server){ die("Unable to connect to MySQL: " . mysqli_connect_error()); $db_status = "not connected"; }else{ //If submit comment pressed, get data and input if (isset($submit) && $submit == 'Submit reservation'){ if ($reservationName&&$reservationEmail&&$reservationNumber&&$reservationDate&&$reservationTime){ $reservationName = clean_string($db_server, $reservationName); $reservationEmail = clean_string($db_server, $reservationEmail); $reservationNumber = clean_string($db_server, $reservationNumber); $reservationDate = clean_string($db_server, $reservationDate); $reservationTime = clean_string($db_server, $reservationTime); mysqli_select_db($db_server, $db_database); $query="SELECT COUNT(*) FROM reservations AS reservationCount WHERE reservationDate='$reservationDate' AND reservationTime='$reservationTime'"; $result=mysqli_query($db_server, $query); $row=mysqli_fetch_array($result); if ($row <= 10){ $query = "INSERT INTO reservations (reservationName, reservationEmail, reservationNumber, reservationDate, reservationTime) VALUES ('$reservationName', '$reservationEmail', '$reservationNumber', '$reservationDate', '$reservationTime')"; mysqli_select_db($db_server, $db_database); mysqli_query($db_server, $query) or die("Insert failed: " . mysqli_error($db_server)) . $query; $message = "<p class='success'>Booking successful! See you soon.</p>"; }else{ $message = "<p class='fail'>Booking failure! We're fully booked at that time.</p>"; } }else{ $message = "<p class='fail'>Booking failure! Please fill in all the fields.</p>"; } } } ?> A: First of all, your query is wrong. Update it to this: $query="SELECT COUNT(*) AS reservationCount FROM reservations WHERE reservationDate='$reservationDate' AND reservationTime='$reservationTime'"; Reason why your query was wrong was because, if you add as reservationCount after your table name, it becomes a table alias, not result field alias. Then update the code that does the check like this: if ($row['reservationCount'] <= 10){ P.S. your code looks open to SQL Injection. Look into using MySQLi library in object orientated way and bind params to prevent sql injection. Take a look at this example, it covers both recommendations: http://php.net/manual/en/mysqli.prepare.php#refsect1-mysqli.prepare-examples A: The COUNT(*) returns one single value in one single row, and you're checking for the number of rows, so it will always be true because 1 <= 10 is always true. Change it to: if ($row[0] <= 10){
{ "language": "en", "url": "https://stackoverflow.com/questions/23135177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: JS, show marker as string in google api using geojson I'm new with Javascript and i wonder how to show a marker as a value that loaded from geojson file. for example: a marker with the number 17.6396, where the coordinates is 35.04226 32.76994. like in this map: http://www.meteo.co.il//MeteoMap.aspx <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> html, body, #map-canvas { height: 100%; margin: 0px; padding: 0px } </style> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script> <script> var map; google.maps.event.addDomListener(window, 'load', function() { map = new google.maps.Map(document.getElementById('map-canvas'), { center: { lat: 32.7, lng: 35.1 }, zoom: 7, }); var script = document.createElement('script'); //data.json- this is the geojson script.setAttribute('src', 'data.json'); document.getElementsByTagName('head')[0].appendChild(script); }); // Defines the callback function referenced in the json file. function temp_callback(data) { map.data.addGeoJson(data); } </script> </head> <body id="map-container"> <div id="map-canvas"></div> </body> </html> data.json example: temp_callback({ "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 35.02026,32.78685 ] }, "properties": { "type":"Feature", "id":1, "weight":16.49633, "geometry.type":"Point", "time":"2015-03-24T14:55:00", "coordinates":"35.02026 32.78685" } }, { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 35.04226,32.76994 ] }, "properties": { "type":"Feature", "id":2, "weight":17.6396, "geometry.type":"Point", "time":"2015-03-24T14:50:00", "coordinates":"35.04226 32.76994" } } ] }) A: Well, you can add numbers on custom markers using the following tutorial: Link and after that attach infowindow to each custom marker: Link
{ "language": "en", "url": "https://stackoverflow.com/questions/29366446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deserialize object into assembly that is now signed and versioned I used to serialize a treeview with the BinaryFormatter (c#). The Assembly that did just that and which contains the all the serializable classes has now a strong name and is signed and also got a new version number (however, implementation didn't change). When I try to deserialize the byte[] array, the line (TreeViewData)binaryFormatter.Deserialize(memoryStream); produces an ArgumentNullException. (Parametername: type) I thought the versionnumber is the problem, so I implemented an own Binder. I overwrote the BindToType method and made sure that the version is corrected and the correct type is returned. However, at the very moment, the program leaves the BindToType method, I still get the exception mentioned above. How do I fix this? A: You could try using a serialization surrogate, but without something we can reproduce it will be hard to give a decent answer. The fundamental problem, however, is that BinaryFormatter is simply very, very brittle when it comes to things like assemblies. Heck, it is brittle enough even within an assembly. It sounds like TreeViewData is tree based, so I wonder whether xml would have been a better (i.e. more version tolerant) option. If efficiency is a concern, there are custom binary formats (like protobuf-net) that offer high performance, version tolerant, portable binary serialization. If your data is already serialized... I wonder if it might be time to change track? Try using the old assembly to deserialize the data, and switch to a more robust serialization strategy. A: You can use a SerializationBinder to solve this: private class WeakToStrongNameUpgradeBinder : SerializationBinder { public override Type BindToType(string assemblyName, string typeName) { try { //Get the name of the assembly, ignoring versions and public keys. string shortAssemblyName = assemblyName.Split(',')[0]; var assembly = Assembly.Load(shortAssemblyName); var type = assembly.GetType(typeName); return type; } catch (Exception) { //Revert to default binding behaviour. return null; } } } Then var formatter = new BinaryFormatter(); formatter.Binder = new WeakToStrongNameUpgradeBinder(); Voila, your old serialized objects can be deserialized with this formatter. If the type have also changed you can use a SerializationSurrogate to deserialize the old types into your new types. As others have mentioned, doing your own serialization rather than relying on IFormatter is a good idea as you have much more control over versioning and serialized size. A: My recommendation is to never use the builtin serializes for your persistent storage. Always code your own if for no other reason someday in the future you will need to read and write your file formats from another language.
{ "language": "en", "url": "https://stackoverflow.com/questions/780739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Troubles switching from VC++ Directories to User Macros for Boost Good day, I have previously successfully used boost in Visual Studio 2010 by using Include and Library Directory paths under VC++ Directories in project settings. However not long ago I have been forced to switch to using "User Macros" to do the linking due to a new lecturer where I study. I had no issues moving my other libraries to using User Macros, I simply used the same include and library path when creating the macros. Boost however is not playing so nice. While having the boost folder linked under VC++ Directories it worked as it should, but when I try moving the include and library paths to User Macros, Visual Studio refuses to recognize the path and I'm getting the following normal error: error C1083: Cannot open include file: 'boost/filesystem.hpp': No such file or directory When I move back to using VC++ Directories it works again. Is there any simple explanation why boost doesn't want to be linked with macros, while all my other libs are totally fine with it? The other libraries include DevIL, SDL, glew, glm and assimp as of now. A: I seem to have found the solution. I had to add my boost macro names under "Project settings - C/C++ - Additional Include Directories" and "project settings - linker - Additional Library Directories". Somehow the other macros I have made have appeared in those two lists automatically, and I'm not sure why the boost macros were not added automatically too. Now it's working as it should though, so I'll just go with it like this.
{ "language": "en", "url": "https://stackoverflow.com/questions/14796824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Class literal from a class object based on an interface At first look it doesn't look like this might be possible so it would be good to hear some design patterns or a work around to make this work. I need to provide an external library with the class literal Class<T> in order for it to find the right type and annotations and pull from dynamodb. Here is the signature public <T> T load(java.lang.Class<T> clazz, java.lang.Object hashKey) However in my application needed class type is dynamic and gets resolved dynamically from the interface. Here is an example where I resolve the class's full name dynamically from an interface. String dynamoDBTypeName = getDynamoDBClassName(someInterface); Class<?> clazz = Class.forName(dynamoDBTypeName); and then I need convert clazz to class literal so it can be passed to mapper.load(SomeClazz.class, hashKey) I couldn't find a solution on how to convert a class object to a class literal so I can pass the actual type to the lib. Is there such one? Or is there a more elegant solution of dynamically resolving an interface to the class literal? A: If I'm interpreting your intent correctly, then you can just do this: String dynamoDBTypeName = getDynamoDBClassName(someInterface); Class<?> clazz = Class.forName(dynamoDBTypeName); Object loaded = mapper.load(clazz, hashKey); Whether you get the class from Someclass.class or Class.forName(...), it's the same class object. The values of type parameters are only defined at compile time, so there is absolutely no difference in the information passed to mapper.load, the code that implements mapper.load, or the value that it returns. The only difference is that if you pass a Class<X> to mapper.load() then the compiler knows that it will return an X and you can assign it to a variable of type X without casting. If you pass a Class<?> the compiler only knows that it will return an Object. It can be cast to an instance of the class by some code that knows what type it's supposed to be.
{ "language": "en", "url": "https://stackoverflow.com/questions/33818338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ORDER BY id DESC LIMIT 100 returns first rows instead of last Using latest versions of Postgres, Node and node pg. Trying to figure out why ORDER BY col DESC LIMIT 100 always returns the first rows regardless of order. Here's the table: CREATE TABLE transactions ( id BIGSERIAL NOT NULL, timestamp timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, user_id INT NOT NULL, to_id INT NOT NULL, amount NUMERIC(10, 2) DEFAULT 0 NOT NULL, comment VARCHAR(100) DEFAULT '' NOT NULL, rate INT DEFAULT 0 NOT NULL, PRIMARY KEY (id) ); CREATE INDEX index_transactions_id ON transactions(id); CREATE INDEX index_transactions_user_id ON transactions(user_id); CREATE INDEX index_transactions_timestamp ON transactions(timestamp); Here's the query: SELECT * FROM transactions ORDER BY $1 DESC LIMIT 100; Where $1 is id and passed via params. Rows in transactions are sometimes deleted, so there are empty ranges. The returned rows from this query are always the first 100. Tried NULLS FIRST/LAST and the result is the same. What's happening? A: Where $1 is id and passed via params. SQL does not allow to parametrize object names like column names. In most cases you get a syntax error right away if you try this kind of nonsense. Unfortunately, the ORDER BY clause does not necessarily expect a column name, but allows expressions including a constant (typed) value (which can be parameterized). If you pass 'id' to this prepared query, this is what happens: SELECT * FROM transactions ORDER BY 'id'::text DESC LIMIT 100; ORDER BY <constant value> is just noise and has no effect on the result. Turn on the server logs to check what the database actually receives. To parameterize column names like you seem to have in mind, you need dynamic SQL, i.e. first concatenate the query string and then execute it.
{ "language": "en", "url": "https://stackoverflow.com/questions/73179341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: basic query on associative arrays How to do I query this in? Graph is working on this query $dataPoints = array(); $result = mysqli_query($conn, "SELECT * FROM service_booking GROUP BY service_id"); while($row = mysqli_fetch_array($result)) { $point = array("label" => $row['service_id'] , "y" => $row['booking_id']); array_push($dataPoints, $point); } but I want the "label" $row['service_id'] display as a ['services'] coming from a different parent table. services (tbl1) service_booking (tbl2) services || service_id service_id || booking id A: Join the tables SELECT b.*, s.services FROM service_booking AS b JOIN services AS s ON s.service_id = b.service_id
{ "language": "en", "url": "https://stackoverflow.com/questions/56945167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Possibility to modify or extend code in D365FO to suppress thrown error Original class function creates an SQL query and executes it. Since there is an syntax error in the query it throws an error. What's the correct way to achieve fixation? Class extension does not work, because CoC executes the complete original function. originalFunction(..) { createSomeSQLQueryWithSyntayErrorInIt(); executeQuery(); } The class in question is ReqDemPlanMissingForecastFiller. In method insertMissingDatesForecastEntries a direct SQL statement string is generated. The date variable nonFrozenForecastStartDate is added to the string, but is not escaped correctly as it seems. If the SQL statement is executed, a syntax error occurs. If the statement is fixed, it can be executed e.g. in SQL Server Management Studio (SSMS). A: In this specific case, based on your comments, you may be able to sidestep. Create a new class ReqDemPlanMissingForecastFiller_Fix extending ReqDemPlanMissingForecastFiller then copy/paste the erroneous function and correct the mistake. Create an extension class and change the newParameters static funcion. [ExtensionOf(classStr(ReqDemPlanMissingForecastFiller))] class ReqDemPlanMissingForecastFiller_Extention { public static ReqDemPlanMissingForecastFiller newParameters( ReqDemPlanCreateForecastDataContract _dataContract, ReqDemPlanAllocationKeyFilterTmp _allocationKeyFilter, ReqDemPlanTaskLoggerInterface _logger = null) { ReqDemPlanMissingForecastFiller filler = next newParameters(_dataContract, _allocationKeyFilter, _logger); filler = new ReqDemPlanMissingForecastFiller_Fix(); //Throw away previous value filler.parmDataContract(_dataContract); filler.parmAttributeManager(_dataContract.attributeManager()); filler.parmAllocationKeyFilter(_allocationKeyFilter); filler.parmLogger(_logger); filler.init(); return filler; } } Code above was based on AX 2012 code. Stupid solution to a stupid problem. It goes almost without saying that you should report the problem to Microsoft. A: @Jan B. Kjeldsen's answer describes how the specific case can be solved without involving Microsoft. Since overlayering is no longer possible, the solution involves copying a fair bit of standard code. This brings its own risks, because future changes by Microsoft for that code are not reflected in the copied code. Though it cannot always be avoided, other options should be evaluated first: * *As @Jan B. Kjeldsen mentioned, errors in the standard code should be reported to Microsoft (see Get support for Finance and Operations apps or Lifecycle Services (LCS)). This enables them to fix the error. * *Pro: No further work needed. *Con: Microsoft may decline the fix or take a long time to implement it. *If unlike in this specific case the issue is not a downright error, but a lack of extension options, an extensibility request can be created with Microsoft. They will then add an extension option. * *Pro: No further work needed. *Con: Microsoft may decline the extensibility request or take a long time to implement it. *For both errors as well as missing extension options, Microsoft also offers the Community Driven Engineering program (CDE). This enables you to develop changes in the standard code directly via a special Microsoft hosted repository where the standard code is not locked for changes. * *Pro: Most flexible and fastest of all options involving Microsoft. *Con: You have to do the work yourself. Microsoft may decline the change. It can still take some time before the change is available in a GA version. You can also consider a hybrid approach: For a quick solution, copy standard code and customize it as required. But also report an error, create an extensibility request or fix it yourself in the CDE program. When the change is available in standard code, you can then remove the copied code again.
{ "language": "en", "url": "https://stackoverflow.com/questions/72001147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Array for multiple columns and paste into different sheet, getting #ref at the last row? I want to copy put a range of columns into an array and paste columns based into a different worksheet using an array. I want to put column A2 to H from RESOURCEPLANNING into an array and paste column A,B,D,F & G into Resource_Output worksheet, however I get #REF! error at the bottom of my table. Currently my code is: Sub Resourceplanning_array() Dim Var As Variant Dim my_Arange As Variant Dim rp As Worksheet, rp_opt As Worksheet Set rp = Sheets("RESOURCE_PLANNING") Set rp_opt = Sheets("RP_Output") Dim cell As Range my_Arange = rp.Range("A2", rp.Range("H" & Rows.Count).End(xlUp)) Var = Application.Index(my_Arange, Evaluate("row(1:" & [a1].CurrentRegion.Rows.Count & ")"), Array(1, 2, 4, 6, 8)) rp_opt.Range("A1:E" & UBound(Var)) = Var 'Output the Array. End Sub A: Slice a 2D Array * *It is assumed that the data starts in A1 and has a row of headers. *You have to use 7 instead of 8 to copy column G instead of column H. *[A1].CurrentRegion.Rows.Count may yield different results depending on which worksheet is active, so you should rather qualify the range: rp.Range("A1").CurrentRegion.Rows.Count. *rp.Range("A1").CurrentRegion.Rows.Count may be different than rp.Range("H" & rp.Rows.Count).End(xlUp).Row, so you should opt for one (I've opted for the former). *A quick fix could be [a1].CurrentRegion.Rows.Count - 1, but is not recommended due to the previous two reasons. rp.Range("A1").CurrentRegion.Rows.Count - 1 would be better. *Both solutions do the same except for the out-commented 'exclude-headers-parts' in the first solution, which you could use to not include the headers, and the 'clear-contents-part' in the second solution, which you could use to clear the contents below the destination range. *Adjust the values in the constants section, the workbook reference, and if headers should be excluded (and if the contents below the destination range should be cleared). Option Explicit Sub sliceArray() Const sName As String = "RESOURCE_PLANNING" Const sCols As String = "A:H" Const dName As String = "RP_Output" Const dFirst As String = "A1" Dim dCols As Variant: dCols = VBA.Array(1, 2, 4, 6, 8) ' 'VBA': zero-based Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code 'Dim wb As Workbook: Set wb = ActiveWorkbook ' workbook you're looking at ' Source Worksheet Dim sws As Worksheet: Set sws = wb.Worksheets(sName) ' Source/Destination Rows Count Dim rCount As Long: rCount = sws.Range("A1").CurrentRegion.Rows.Count ' No headers 'Dim rCount As Long: rCount = sws.Range("A1").CurrentRegion.Rows.Count - 1 ' Source Array Dim sData As Variant sData = sws.Columns(sCols).Resize(rCount).Value ' No headers 'sData = sws.Columns(sCols).Resize(rCount).Offset(1).Value ' Destination Array Dim dData As Variant dData = Application.Index(sData, Evaluate("Row(1:" & rCount & ")"), dCols) ' Destination Columns Count Dim dcCount As Long: dcCount = UBound(dCols) + 1 ' = UBound(dData, 2) ' Destination Worksheet Dim dws As Worksheet: Set dws = wb.Worksheets(dName) ' Destination Range Dim drg As Range: Set drg = dws.Range(dFirst).Resize(rCount, dcCount) ' Write drg.Value = dData End Sub Sub sliceArrayShort() Const sName As String = "RESOURCE_PLANNING" Const sCols As String = "A:H" Const dName As String = "RP_Output" Const dFirst As String = "A1" Dim dCols As Variant: dCols = VBA.Array(1, 2, 4, 6, 8) Dim wb As Workbook: Set wb = ThisWorkbook ' Read Dim rCount As Long Dim sData As Variant With wb.Worksheets(sName) rCount = .Range("A1").CurrentRegion.Rows.Count sData = .Columns(sCols).Resize(rCount).Value End With ' Slice Dim dData As Variant dData = Application.Index(sData, Evaluate("Row(1:" & rCount & ")"), dCols) ' Write (& Clear) With wb.Worksheets(dName).Range(dFirst).Resize(, UBound(dCols) + 1) .Resize(rCount).Value = dData '.Resize(.Worksheet.Rows.Count - .Row - rCount + 1) _ .Offset(rCount).ClearContents End With End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/67345586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Element.focus() doesn't work when called within a function handler for addEventListener() Here is my code. For some reason, this code does not give focus to the textbox with the id "dude" even though the paragraph tag with id "answer" does get the key code of the button that I clicked. It is like the line with the focus() command gets completely ignored. document.getElementById("thing").addEventListener("keypress", function() { myFunction(event); }); function myFunction(event) { document.getElementById("answer").innerHTML = event.keyCode; document.getElementById("dude").focus(); } <!DOCTYPE html> <html> <body> <input type="text" id="thing"> <input type="text" id="dude"> <p id="answer"></p> </body> </html> However, if I were to make a slight modification and put the line with the focus() outside of the addEventListener(), then the focus() would work. For example, the following code works: document.getElementById("dude").focus(); document.getElementById("thing").addEventListener("keypress", function() { myFunction(event); }); function myFunction(event) { document.getElementById("answer").innerHTML = event.keyCode; } <!DOCTYPE html> <html> <body> <input type="text" id="thing"> <input type="text" id="dude"> <p id="answer"></p> </body> </html> The above code would actually start by giving the "dude" textbox focus. Is there any reason for this and anything that I can do about this? A: The keypress event handler fires too early - the user hasn't finished pressing the key down and entering in the value at that point, so the focus reverts to the initial input field. See how if you change the focus after a setTimeout it'll work: document.getElementById("thing").addEventListener("keypress", function() { myFunction(event); }); function myFunction(event) { document.getElementById("answer").innerHTML = event.keyCode; setTimeout(() => document.getElementById("dude").focus()); } <input type="text" id="thing"> <input type="text" id="dude"> <p id="answer"></p> Or watch for the keyup event instead: document.getElementById("thing").addEventListener("keyup", function() { myFunction(event); }); function myFunction(event) { document.getElementById("answer").innerHTML = event.keyCode; document.getElementById("dude").focus(); } <input type="text" id="thing"> <input type="text" id="dude"> <p id="answer"></p> For example, the following code works: Not exactly, because with that code, you're focusing the dude input on pageload, rather than when the thing input has stuff typed into it. You also should avoid using keypress in modern code, it's deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. Since this event has been deprecated, you should look to use beforeinput or keydown instead. keyCode is too, technically, but the replacement for it - .code - isn't compatible everywhere. A: Use the keyup event instead of keypress, because the default action of the keypress event sets the focus back to that input element. document.getElementById("thing").addEventListener("keyup", function() { myFunction(event); }); function myFunction(event) { document.getElementById("answer").innerHTML = event.keyCode; document.getElementById("dude").focus(); } <!DOCTYPE html> <html> <body> <input type="text" id="thing"> <input type="text" id="dude"> <p id="answer"></p> </body> </html> A: It seems like you are trying to shift focus from input "thing" to input "dude" after you complete a "keypress" or "keyup" on input "thing". I don't understand the use case for this. But, IMO if you are trying to change the focus state after you input a value, I would recommend placing an event listener on the "change" event. You could simply press your "TAB" key on your keyboard after you are done inputting data into input "thing" and focus will be shifted to the input "dude" and the function will execute. Both achieved! document.getElementById('thing').addEventListener('change', function (event) { myFunction(event.target.value) }) function myFunction(answer) { document.getElementById('answer').innerText = answer } <input type="text" id="thing" /> <input type="text" id="dude" /> <p id="answer"></p>
{ "language": "en", "url": "https://stackoverflow.com/questions/72411275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Running shell script against Localstack in docker container I've been using localstack to develop a service against locally. I've just been running their docker image via docker run --rm -p 4567-4583:4567-4583 -p 8080:8080 localstack/localstack And then I manually run a small script to set up my S3 buckets, SQS queues, etc. Now, I'd like to make this easier for others so I thought I'd just add a Dockerfile and docker-compose.yml file. Unfortunately, when I try to get this up and running, using docker-compose up I get an error that the command from my setup script can't connect to the localstack services. make_bucket failed: s3://localbucket Could not connect to the endpoint URL: "http://localhost:4572/localbucket" Dockerfile: FROM localstack/localstack #since this is just local dev set up, localstack doesn't require anything specific here. ENV AWS_DEFAULT_REGION='[useast1]' ENV AWS_ACCESS_KEY_ID='[lloyd]' ENV AWS_SECRET_ACCESS_KEY='[christmas]' COPY bin/localSetup.sh /localSetup.sh COPY fixtures/notifications.json /notifications.json RUN ["chmod", "+x", "/localSetup.sh"] RUN pip install awscli # expose service & web dashboard ports EXPOSE 4567-4582 8080 ENTRYPOINT ["/localSetup.sh"] docker-compose.yml version: '3' services: localstack: build: . ports: - "8080:8080" - "4567-4582:4567-4582" localSetup.sh #!/bin/bash aws --endpoint-url=http://localhost:4572 s3 mb s3://localbucket #additional similar calls but left off for brevity I've tried switching localhost to 127.0.0.1 in my script commands, but I wind up with the same error. I'm probably missing something silly here. A: There is another way to create your custom AWS resources when localstack freshly starts up. Since you already have a bash script for your resources, you can simply volume mount your script to /docker-entrypoint-initaws.d/. So my docker-compose file would be: localstack: image: localstack/localstack:latest container_name: localstack_aws ports: - '4566:4566' volumes: - './localSetup.sh:/etc/localstack/init/ready.d/init-aws.sh' Also, I would prefer awslocal over aws --endpoint in the bash script, as it leverages the credentials work and endpoint for you. A: try adding hostname to the docker-compose file and editing your entrypoint file to reflect that hostname. docker-compose.yml version: '3' services: localstack: build: . hostname: localstack ports: - "8080:8080" - "4567-4582:4567-4582" localSetup.sh #!/bin/bash aws --endpoint-url=http://localstack:4572 s3 mb s3://localbucket This was my docker-compose-dev.yaml I used for testing out an app that was using localstack. I used the command docker-compose -f docker-compose-dev.yaml up, I also used the same localSetup.sh you used. version: '3' services: localstack: image: localstack/localstack hostname: localstack ports: - "4567-4584:4567-4584" - "${PORT_WEB_UI-8082}:${PORT_WEB_UI-8082}" environment: - SERVICES=s3 - DEBUG=1 - DATA_DIR=${DATA_DIR- } - PORT_WEB_UI=${PORT_WEB_UI- } - DOCKER_HOST=unix:///var/run/docker.sock volumes: - "${TMPDIR:-/tmp/localstack}:/tmp/localstack" - "/var/run/docker.sock:/var/run/docker.sock" networks: - backend sample-app: image: "sample-app/sample-app:latest" networks: - backend links: - localstack depends_on: - "localstack" networks: backend: driver: 'bridge'
{ "language": "en", "url": "https://stackoverflow.com/questions/53563942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: How to use a file to migrate data from mysql to a clickhouse? I need to migrate the data from Mysql to ClickHouse and do some testing. These two database networks are not working, I have to use files to transfer. The first thing I think of is that I can use the mysqldump tool to export .sql files. mysqldump -t -h192.168.212.128 -P3306 --default-character-set=utf8 -uroot -proot database_name table_name > test.sql Then I found that there are 120 million pieces of data in the mysql table. The insert statement of the .sql file exported in this way is very long. How to avoid this situation, such as exporting 1000 data each time as an insert statement ? In addition, this .sql file is too big, can it be divided into small files, what needs to be done? A: mysqldump has an option to turn on or off using multi-value inserts. You can do either of the following according to which you prefer: Separate Insert statements per value: mysqldump -t -h192.168.212.128 -P3306 --default-character-set=utf8 --skip-extended-insert -uroot -proot database_name table_name > test.sql Multi-value insert statements: mysqldump -t -h192.168.212.128 -P3306 --default-character-set=utf8 --extended-insert -uroot -proot database_name table_name > test.sql So what you can do is dump the schema first with the following: mysqldump -t -h192.168.212.128 -P3306 --default-character-set=utf8 --no-data -uroot -proot database_name > dbschema.sql Then dump the data as individual insert statements by themselves: mysqldump -t -h192.168.212.128 -P3306 --default-character-set=utf8 --skip-extended-insert --no-create-info -uroot -proot database_name table_name > test.sql You can then split the INSERT file into as many pieces as possible. If you're on UNIX use the split command, for example. And if you're worried about how long the import takes you might also want to add the --disable-keys option to speed up inserts as well.. BUT my recommendation is not to worry about this so much. mysqldump should not exceed MySQL's ability to import in a single statement and it should run faster than individual inserts. As to file size, one nice thing about SQL is that it compresses beautifully. That multi-gigabyte SQL dump will turn into a nicely compact gzip or bzip or zip file. EDIT: If you really want to adjust the amount of values per insert in a multi-value insert dump, you can add the --max_allowed_packet option. E.g. --max_allowed_packet=24M . Packet size determines the size of a single data packet (e.g. an insert) so if you set it low enough it should reduce the number of values per insert. Still, I'd try it as is before you start messing with that. A: clickhouse-client --host="localhost" --port="9000" --max_threads="1" --query="INSERT INTO database_name.table_name FORMAT Native" < clickhouse_dump.sql
{ "language": "en", "url": "https://stackoverflow.com/questions/52345137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android: select Tab programatic if in Dropdown List mode Depending on the number of tabs and on screen orientation tabs are displayed next to each other or in a dropdown list. I wrote a function to set the current tab. This works but not in dropdown list mode. What has to be done? static class TabsListener implements ActionBar.TabListener { private static ActionBar mActionBar; private final ViewPager mViewPager; private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>(); ... public void setTab(int i) { mViewPager.setCurrentItem(i); } A: If you are trying to have the tab/drop-down selection change when the user swipes a tab, that will not work in drop-down mode, due to a bug in setSelectedNavigationItem(). I am not aware of a workaround while still using tabs in the action bar. Personally, this is one of the reasons why I prefer PagerTabStrip (or the tab indicator from the ViewPagerIndicator library) over action bar tabs.
{ "language": "en", "url": "https://stackoverflow.com/questions/12986991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: "No valid predicate" error when upgraded from Meta_search to Ransack? I've got an ActiveRecord model with a method defined like this: def state if deleted? :deleted else :expired end end The 'search_method' is defined in the model as: search_method :state In the view: = form.select :state, { :expired => 'Expired', :deleted => 'Deleted' }.invert, :include_blank => 'All' With Meta_search, this method was working fine. But when I replaced the gem with Ransack, I get: ArgumentError in Sample Controller No valid predicate for state. I'm following this behavior from meta_search search_methods, so I might be taking the wrong approach. Any one help me, please? A: Ransack uses a predicate added on to the end of the field you're searching for to indicate how to search for it. If you have an attribute of :state on your model, you could search for states that match to 'expired' or 'deleted' using form.select :state_match, where the _match says to match records with state of whatever you selected. (Things like _cont (contains) or _start (starts with)). Ransack makes SQL queries to find records, so if you had an attribute on your model like :deleted_at you could search by presence or lack-of. It won't look at methods, just the information stored in the db. More predicates and info are here: https://github.com/activerecord-hackery/ransack/wiki/Basic-Searching
{ "language": "en", "url": "https://stackoverflow.com/questions/20992463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How are shared libraries referenced by various programs? I understand that shared libraries are loaded into memory and used by various programs. How can a program know where in memory the library is? A: When a shared library is used, there are two parts to the linkage process. At compile time, the linker program, ld in Linux, links against the shared library in order to learn which symbols are defined by it. However, none of the code or data initializers from the shared library are actually included in the ultimate a.out file. Instead, ld just records which dynamic libraries were linked against and the information is placed into an auxiliary section of the a.out file. The second phase takes placed at execution time, before main gets invoked. The kernel loads a small helper program, ld.so, into the address space and this gets executed. Therefore, the start address of the program is not main or even _start (if you have heard of it). Rather, it is actually the start address of the dynamic library loader. In Linux, the kernel maps the ld.so loader code into a convenient place in the precess address space and sets up the stack so that the list of required shared libraries (and other necessary info) is present. The dynamic loader finds each of the required libraries by looking at a sequence of directories which are often point in the LD_LIBRARY_PATH environment variable. There is also a pre-defined list which is hard-coded into ld.so (and additional search places can be hard-coded into the a.out during link time). For each of the libraries, the dynamic loader reads its header and then uses mmap to create memory regions for the library. Now for the fun part. Since the actual libraries used at run-time to satisfy the requirements are not known at link-time, we need to figure out a way to access functions defined in the shared library and global variables that are exported by the shared library (this practice is deprecated since exporting global variables is not thread-safe, but it is still something we try to handle). Global variables are assigned a statics address at link time and are then accessed by absolute memory address. For functions exported by the library, the user of the library is going to emit a series of call assembly instructions, which reference an absolute memory address. But, the exact absolute memory address of the referenced function is not known at link time. How do we deal with this? Well, the linker creates what is known as a Procedure Linkage Table, which is a series of jmp (assembly jump) instructions. The target of the jump is filled in at run time. Now, when dealing with the dynamic portions of the code (i.e. the .o files that have been compiled with -fpic), there are no absolute memory references whatsoever. In order to access global variables which are also visible to the static portion of the code, another table called the Global Offset Table is used. This table is an array of pointers. At link time, since the absolute memory addresses of the global variables are known, the linker populates this table. Then, at run time, dynamic code is able to access the global variables by first finding the Global Offset Table, then loading the address of the correct variable from the appropriate slot in the table, and finally dereferencing the pointer.
{ "language": "en", "url": "https://stackoverflow.com/questions/62296128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: New page opening seamlessly as a popup with different url on apple.com. How did they do it? I was trying to replicate the effect I saw on apple.com but with no success. On https://www.apple.com/uk/apple-watch-series-3/ if you click on learn more button (middle of the page - sports watch section) you get something like a popup, but it is not a classic popup - more something like a new page wich hides complete html structure of the main page. When you click on close, url changes and gets you back on the main page. How did they do it? Where should I start searching? Thanks A: They are making use of the Use the HTML5 History API, this link will show you how you can accompish the same effect.
{ "language": "en", "url": "https://stackoverflow.com/questions/48784799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass a PHP variable into a Javascript cookie on submit of form? I am setting up a custom form to be used in my wordpress site. What I would like to do is grab the AUTO_INCREMENT ID of that submission and pass it into a Javascript cookie when the form is submitted. Currently the ID is working, but because the ID isn't grabbed until after the form is submitted, I'm having trouble figuring out how I can pass the variable into the cookie immediately after the form has been submitted(currently I have to submit the form twice before the cookie with the ID is created, and its 1 number lower than it should be since it's a submission behind). Here's what I have currently: <?php if(isset($_POST["submit"])) { $name = $_POST['full_name']; $city = $_POST['city']; $state = $_POST['state']; $email = $_POST['email']; $wpdb->insert( 'reps', array( 'name' => stripslashes($name), 'city' => stripslashes($city), 'state' => stripslashes($state), 'email' => stripslashes($email) ) ); $lastid = $wpdb->insert_id; } ?> <script> $('#dealer-form').submit(function() { var repID = '<?php echo $lastid ?>'; setCookie('ID', repID); }); </script> As I mentioned this code works on the second submission(since the variable has no value on the first submission), and the ID is 1 number behind because it is grabbing the ID of the previous submission before reassigning the variable value. A: PHP, being a server-side scripting language, is executed before the data is sent to your browser. JavaScript, a client-side scripting language, is executed as soon as the script is encountered by the browser. Your approach is forgetting this separation between front- and back-end. To accomplish what you're trying to do, simply output the setCookie call when you've submitted your form in php: <?php if(isset($_POST["submit"])) { $name = $_POST['full_name']; $city = $_POST['city']; $state = $_POST['state']; $email = $_POST['email']; $wpdb->insert( 'reps', array( 'name' => stripslashes($name), 'city' => stripslashes($city), 'state' => stripslashes($state), 'email' => stripslashes($email) ) ); $lastid = $wpdb->insert_id; printf( '<script>setCookie("ID", %d);</script>', $lastid ); } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/37260159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How I insert a time-date-stamp in MongoDB with a Golang Sruct? I have the following struct: type TypeIncidence struct { Number int bson:"number" json:"number" Description string bson:"description" json:"description" Date_time_stamp string bson:"dateTimeStamp" json:"date_time_stamp" } and I want insert a document in a collection: type TypeIncidence struct { Number int `bson:"number" json:"number"` Description string `bson:"description" json:"description"` Date_time_stamp **string?** } var incidence TypeIncidence incidence.Number = 1 Description =" Text" Date_time_stamp = **string?** What data type would I have to use in a Golang structure to store date_time_struct a string? If I want to store with the following format 'YYYY-MM-DD hh:mm:ss', what module and/or function should I use in golang? (in local machine or server converting zone time) Thanks in advance A: You can use time.Time: CreatedAt time.Time `json:"created_at" bson:"created_at"` However, I would recommend that you store Epoch Unix timestamp (the number of seconds since Jan 1st 1970) because it is universal: CreatedAt int64 `json:"created_at" bson:"created_at"` I have tried in the past to store time.Time in MongoDB through Golang but then I had trouble when I parsed the same information into a datetime object in Python. If you would like to be compatible across languages and technologies, storing the Epoch Unix timestamp would be a great option.
{ "language": "en", "url": "https://stackoverflow.com/questions/70589570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Testing pico cli commands, Java I've developed a Java API and I've built a command line interface to consume it using PicoCli What is the proper way to test my pico commands? Thanks in advance A: You can do black box testing by verifying the exit code and the output of the program to the standard output stream and standard error stream. You can do white box testing by keeping a reference to your application and asserting on the state of your application after giving it various command line inputs. For example: MyApp app = new MyApp(); StringWriter sw = new StringWriter(); CommandLine cmd = new CommandLine(app); cmd.setOut(new PrintWriter(sw)); // black box testing int exitCode = cmd.execute("-x", "-y=123"); assertEquals(0, exitCode); assertEquals("Your output is abc...", sw.toString()); // white box testing assertEquals("expectedValue1", app.getState1()); assertEquals("expectedValue2", app.getState2()); Update: the picocli user manual now has a separate section about Testing.
{ "language": "en", "url": "https://stackoverflow.com/questions/59661608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Math command fails to produce output on PyCharm Completely new to python, I'm trying to get the math packages included in anaconda to work. If I run a math command in IP Notebook, I get the right answer: But under the same settings, if I run the equivalent command on a .py file on PyCharm nothing happens: It can be a very, very basic misunderstanding of how to run code in .py on the console within PyCharms, but I don't know the answer. A: The results of expressions in a Python script are not normally printed - this is a feature of the interpreter and the notebook. In a script it would not make much sense to compute x * y and do nothing with it. Try this instead: print(3j * 9)
{ "language": "en", "url": "https://stackoverflow.com/questions/34747669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Update excel file (xlsx) with csv logs using Python I'm getting daily logs in a csv format and currently opening them in excel and copy/pasting into my master excel file. I'd like to make a Python script that can read a new csv file and write to the master excel file on a specific sheet and starting from a specific cell (one column over from where the last day's data was written). Alternatively, if it's easier to first save the csv file as an excel file and then write that to the master excel file, that would work too. Edit - I ended up doing this (it's probably pretty ugly but it works for now): from xlrd import open_workbook from xlutils.copy import copy def add_data(master_file, csv_file): rb = open_workbook((master_file), formatting_info=True, on_demand=True) sheet_name = csv_file[:-4] total_sheets = len(rb.sheet_names()) wb = copy(rb) wb.add_sheet(sheet_name) row = 0 with open(csv_file, 'rb') as csv: reader = csv.readlines() for line in range(len(reader)): new = reader[line].split(',') for i in range(len(new)): if new[i] == '\n': row += 1 elif new[i][-1] == '\n': new[i] = new[i][:-1] wb.get_sheet(total_sheets).write(row,i,new[i]) row += 1 else: wb.get_sheet(total_sheets).write(row,i,new[i]) wb.save('new_'+master_file) print sheet_name + " added successfully..."
{ "language": "en", "url": "https://stackoverflow.com/questions/28442237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to mapping hibernate entity to db view Could you help me how can I mapping to any entity to db view? Scenario is here, We create a view on db with native sql we have to do like this and we want to mapping this view to ours entity. How can we do that? We try to create an entity with same columns on view but it doesn't work? A: Hibernate-specific @Immutable annotation which I use in the following code snippet. View can be mapped as like below.... @Entity @Immutable public class <NAME>View { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", updatable = false, nullable = false) private Long id; @Version @Column(name = "version") private int version; The @Immutable annotation tells Hibernate to ignore all changes on this entity, but you can use it to retrieve data from the database. List<View> views = em.createQuery("SELECT v FROM View v", View.class).getResultList();
{ "language": "en", "url": "https://stackoverflow.com/questions/38991169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML tabs with content in separate files I am at the moment using this code for HTML/JS tabs. But the code gets way to messy since it is all in one file, is it possible to separate the code in tab one, tab two etc? <!-- Tab links --> <div class="tab"> <button class="tablinks" onclick="openCity(event, 'London')">London</button> <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button> <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button> </div> <!-- Tab content --> <div id="London" class="tabcontent"> <h3>London</h3> <p>London is the capital city of England.</p> </div> <div id="Paris" class="tabcontent"> <h3>Paris</h3> <p>Paris is the capital of France.</p> </div> <div id="Tokyo" class="tabcontent"> <h3>Tokyo</h3> <p>Tokyo is the capital of Japan.</p> </div> And the JavaScript function openCity(evt, cityName) { // Declare all variables var i, tabcontent, tablinks; // Get all elements with class="tabcontent" and hide them tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } // Get all elements with class="tablinks" and remove the class "active" tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } // Show the current tab, and add an "active" class to the button that opened the tab document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } Also, at the moment it does not show which tab you are on. Ideally would be to have /#tab1, /#tab2 etc. Any suggestions? A: Well, that code is OK. So this should mean your not including your JS correctly. I just copied your code and pasted ( I just modified the begining of the script to hide all tabcontents) var tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } function openCity(evt, cityName) { // Declare all variables var i, tabcontent, tablinks; // Get all elements with class="tabcontent" and hide them tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } // Get all elements with class="tablinks" and remove the class "active" tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } // Show the current tab, and add an "active" class to the button that opened the tab document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } <div class="tab"> <button class="tablinks" onclick="openCity(event, 'London')">London</button> <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button> <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button> </div> <!-- Tab content --> <div id="London" class="tabcontent"> <h3>London</h3> <p>London is the capital city of England.</p> </div> <div id="Paris" class="tabcontent"> <h3>Paris</h3> <p>Paris is the capital of France.</p> </div> <div id="Tokyo" class="tabcontent"> <h3>Tokyo</h3> <p>Tokyo is the capital of Japan.</p> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/49918732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery Ajax html (Select multiple) I m searching something of easy. I must pass value from a form html to a file PHP by jquery. I try this code with zero result. If someone can say me where i m mistaking. Thx for JQUERY $('#Save').click(function(){ var realvalues = new Array();//storing the selected values inside an array $('#Privilege[] :selected').each(function(i, selected) { realvalues[i] = $(selected).val(); }); $.ajax({ type: "POST", url: "test5.php", data: {"Privilege[]": realvalues}, success:function(data){ $("#subscrres").html(data) } }); }); For HTML <form method="post"> <select id="Privilege[]" multiple> <option value="yahoo">yahoo</option> <option value="chrome">chrome</option> <option value="mozilla">mozilla</option> </select> <input type="button" id="Save" Value="SEND"/> For PHP. Content file test5.php if(isset($_POST['Privilege'])){ $myvar =$_POST['Privilege']; foreach($_POST['Privilege'] as $one) echo $one."<br/>"; } I don't receive nothing on PHP. Someone can help me ? A: If you are trying to access multi select element using id the you don't need to set id like Privilege[], you can set any unique identity like privilege-selector but if you are giving name for any multi select element then name must be like Privilege[] Here is the html : <form id="form" method="post"> <select id="privilege-selector" multiple> <option value="yahoo">yahoo</option> <option value="chrome">chrome</option> <option value="mozilla">mozilla</option> </select> <input type="button" id="Save" Value="SEND"/> </form> Please check this below ajax request to post selected data to the server $("#Save").on("click",function(){ var selection = []; $.each($("#privilege-selector option:selected"),function(index,element){ selection.push($(element).val()); }) $.ajax({ url : "test5.php", type : "POST", data : {Privilege:selection}, success : function(_response){ var res = JSON.parse(_response); if(res.code == "1"){ console.log(res.data); } else { alert(res.message); } } }) }); and here is your server file that will handle the incoming request data $serverResponse = []; if(isset($_POST['Privilege']) && !empty($_POST['Privilege'])){ $formattedData = []; foreach($_POST['Privilege'] as $key => $value){ $formattedData[] = array( "id" => $key+1, "name" => $value ); } $serverResponse = ["code"=>"1","message"=>"formatted data","data"=>$formattedData]; } else { $serverResponse = ["code"=>"0","message"=>"Please select at least on value"]; } echo json_encode($serverResponse);
{ "language": "en", "url": "https://stackoverflow.com/questions/63306176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add toggleBoldface option to a UITextView in iOS? I wish to add toggleBoldface, toggleItalics and toggleUnderline to the editting options of a UITextView. How can this be done? Preferrably in Swift please. A: Enable the text view's allowsEditingTextAttributes property. A: For those who came here because they enabled Allows Editing Attributes in IB but don't see the BIU UIMenu in the app: apparently that checkbox only activates attribute editing for the pre-defined string displayed in IB, but not in the actual UITextView presented to the user. You still have to enable the allowsEditingTextAttributes property somewhere in your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/35325394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why does the callstack not show the previous calls? In my VS2022 C++ project, something goes wrong after some time. Because the error occurs after 10 minutes only, I need to inspect the call stack to see what went on before the error occured. However, the call stack is too small. It just shows this: I have set break points manually to follow it back, so I know that there are several of my own functions before "ProcessTxtLine" (which is shownn in the call stack), but in the call stack they are not there. So I can not double click them in order to get there quickly. Because I don't know what else might be important, I am posting a screenshot of my entire VS 2022 window. Thank you. Edit: According to a suggestion, I clicked the first entries, then selected Load Symbols. However, that did not help. It does show some more, but still not "my" calls. A: The message in the callstack is the relevant hint: You need to load more debug symbols for the callstack to be displayed correctly. You can right-click on the first entry in the callstack (the KernelBase.dll... line) and select "Load symbols". You might have to load symbols for more modules than this, but you should get new messages telling you about this. This issue is unique to 32bit applications. Due to the way the 32bit calling convention works, it is not possible to generate a call stack without debug symbols for all the topmost stack entries. If you compile your application for 64bit, this problem will go away.
{ "language": "en", "url": "https://stackoverflow.com/questions/74049038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Firefox dropping style selectors involving :before and :after I work on a project where we quite often have LESS looking kind of like this: .boxed, .boxed-band, .boxed-band:before, .boxed-band:after, .boxed-image { background-color: green; &.section{ // Adds padding for all children except the headline. h2 { border-bottom: 1px solid white; } } } Apparently if you throw the resulting compiled code at Firefox it simply gives up and chooses not to interpret the rule at all. All other major browsers seems to have no issues understanding what is going on. If you don't believe me, check this pen: http://codepen.io/webconsult/pen/wKPLRL?editors=110 We have experienced the problem many times and it seems the only consistent solution is to do something like this: .boxed, .boxed-band, .boxed-image { // Some rules. } .boxed-band:before, .boxed-band:after { // Same rules as above ...duplicated... yuck!... } Have anyone else experienced something like this and have you found solutions that does not involve replicating CSS properties over and over?
{ "language": "en", "url": "https://stackoverflow.com/questions/33217835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP : how to get original value of number after being scaled (for zoom logic) currently i am making some "zoom in / zoom out" logic in php, and now i have some problem with scaling value and reverting it back to original value in php (if applicable to js it would be awesome). here is the codes $scale = 1; $currentScale = 1; $position = 50; $step = 5; // or 10 for($index = 1; $index <= $step; $index++){ echo('-----------------------------------------------------<br>'); $currentScale = $scale / $index; $position = $position * $currentScale; $originalPosition = (($scale / $currentScale) * $position) * (($scale / $currentScale) / $scale); echo('current scale : ' . $currentScale . '<br>'); echo('current position : ' . $position . '<br>'); echo('original position : ' . $originalPosition . '<br>'); } the goal is to make the $originalPosition value same as the first $position value (on every scale), i have tried many formula but no luck, hope you guys can help. thanks in advance. rule $originalPosition not stored before loop A: ok, i think i found out the solution, i'll leave this code here in case somebody facing same problem $scale = 1; $currentScale = 1; $position = 80; // change it to any value $step = 5; echo('original position : ' . $position . '<br>'); for($i = $step; $i >= 1; $i--){ echo('-----------------------------------------------------<br>'); $currentScale = ($scale / $step) * $i; $position = $position * $currentScale; $originalPosition = $position; $maxLoop = $step - $i; if($maxLoop){ for($j = $maxLoop; $j >= 0 ; $j--){ $tempScale = $scale - (($scale / $step) * $j); $originalPosition = $originalPosition / $tempScale; } } echo('max rescale loop : ' . $maxLoop . '<br>'); echo('current scale : ' . $currentScale . ' ( ' . $currentScale * 100 . '% )<br>'); echo('current position : ' . $position . '<br>'); echo('original position : ' . $originalPosition . '<br>'); } exit; here is the result, the original position stays the same as initial value
{ "language": "en", "url": "https://stackoverflow.com/questions/52632793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Docker runs fine but commands crashes with error I'm not a pro in Docker for Windows but have been using it for few months and everything was fine. My setup: Windows 10 Pro x64 Docker for Windows version 17.12.0-ce, build c97c6d6 One day after my system rebooted I've got this error for every docker command (with about 40 seconds delay for response): error during connect: Get http://192.168.99.100:2375/v1.35/images/json: dial tcp 192.168.99.100:2375: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. Virtualization is enabled, Hyper-V is seems to running fine. I have reinstalled Docker few times, removed Hyper-V adapters as well - same result. Docker shows no errors during the installation, starting and running. Seems like the only Docker command that runs normally is docker --version, but it takes about 10 seconds as well. A: Seems the problem was in the environment variables. I checked them and there was DOCKER_HOST pointing to 192.168.99.100, after deleting it everything's working fine. Where it comes from is still a mystery. A: I got the same problem. The problems was: I used to have Docker Toolbox on my PC before. So, I had Environmental Variables: DOCKER_TLS_VERIFY, DOCKER_CERT_PATH, DOCKER_HOST, DOCKER_TOOLBOX_INSTALL_PATH. I deleted them and it helped.
{ "language": "en", "url": "https://stackoverflow.com/questions/48803548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert old Japanese text encodings? I run MacBook Pro under 10.6.7, and I am competent in Unix. I have old Japanese text files in various encodings (EUC, SJS, New-JIS) that I can no longer read or display. The old program jconv.c does not help, since it only converts among these encodings. Is there a way to convert them (or any one of them) to the current "normal" Japanese text that can be seen in TextEdit, etc.? I have set the Terminal preferences to SJS and EUC (can't find NewJIS), among others, including UTF-8. Eleanor A: I recommend you look into iconv for doing such conversions. A: nkf is a Linux command line program which can meet your requirement. I am sure it is available at Debian. So you can download sorce code from the Net.
{ "language": "en", "url": "https://stackoverflow.com/questions/6020273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to display multiple location markers by address using google map api? I don't want to display multiple markers using latitude and longitude, Only by addresses which are stored in mysql database. Latitude and Longitude are not stores in the table. I have worked on it and was successful in displaying one marker, but my web app requires me to display multiple markers according to the location Here's the code: <?php include_once("dbcon.php") ; ?> <html> <?php $search = $_POST['search']; $results = mysql_query("SELECT * FROM eventsTable WHERE eventLocation LIKE '%$search%'"); while ($row = mysql_fetch_assoc($results)) { $ename = $row["eventName"]; $edate = $row["eventDate"]; $edetail=$row["eventDetails"]; $eloc = $row["eventLocation"]; $ecity = $row["eventCity"]; echo "<p> ".json_encode($eloc)."</p>"; echo json_encode($ecity); } ?> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>Google Maps JavaScript API v3 Example: Geocoding Simple</title> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript"> var geocoder; var map; var address = "<?php echo $eloc; ?>,<?php echo $ecity; ?>, PK"; function initialize() { geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(30.51687, 69.40949); var myOptions = { zoom: 10, center: latlng, mapTypeControl: true, mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}, navigationControl: true, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); if (geocoder) { geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if (status != google.maps.GeocoderStatus.ZERO_RESULTS) { map.setCenter(results[0].geometry.location); var infowindow = new google.maps.InfoWindow( { content: '<b>'+address+'</b>', size: new google.maps.Size(150,50) }); var marker = new google.maps.Marker({ position: results[0].geometry.location, map: map, title:address }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); } else { alert("No results found"); } } else { alert("Geocode was not successful for the following reason: " + status); } }); } } </script> </head> <body style="margin:0px; padding:0px;" onload="initialize()"> <div id="map_canvas" style= "right-padding=0px; width:50%; height:50%"> </body> </html> A: I don't want to display multiple markers using latitude and longitude, Only by addresses which are stored in mysql database. Unfortunately, Google Maps API requires latitude/longitude in order to add a marker to a map. You should consider using the GeoLocation API to convert your addresses into coordinates first, then you can add the markers in the traditional fashion. If this isn't possible, you can use AJAX to retrieve the latitude/longitude in a loop (like in this answer), but you might hit the rate limit as mentioned in this question's comments. A: You are only outputting one address in your PHP code: var address = "<?php echo $eloc; ?>,<?php echo $ecity; ?>, PK"; You need to create an array of addresses and process that array. Proof of issues with array of more than 11 addresses See OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down? (Andrew Leach's answer) for a way to deal with the OVER_QUERY_LIMIT.
{ "language": "en", "url": "https://stackoverflow.com/questions/30312499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Java Maze Shortest Path misunderstanding Here is code, using recursion, I am trying to solve maze with shortest pathing, but it is getting solved with a longer way and I don't really understand why. Here is code of recursion : public boolean findPath(int row, int col) { board[row][col].visit(); if ((col == 7) && (row == 7)) { board[row][col].selectCell(); return true; } if ((row > 0) && !board[row - 1][col].marked() && !board[row - 1][col].blocked() && !board[row - 1][col].visited()) { block(row, col); if (findPath(row - 1, col)) { board[row][col].selectCell(); return true; } unblock(row, col); } if ((row < 7) && !board[row + 1][col].marked() && !board[row + 1][col].blocked() && !board[row + 1][col].visited()) { block(row, col); if (findPath(row + 1, col)) { board[row][col].selectCell(); return true; } unblock(row, col); } if ((col > 0) && !board[row][col - 1].marked() && !board[row][col - 1].blocked() && !board[row][col - 1].visited()) { block(row,col); if (findPath(row, col - 1)) { board[row][col].selectCell(); return true; } unblock(row,col); } if ((col < 7) && !board[row][col + 1].marked() && !board[row][col + 1].blocked() && !board[row][col + 1].visited()) { block(row,col); if (findPath(row, col + 1)) { board[row][col].selectCell(); return true; } unblock(row,col); } return false; } it's 8x8 board, the block function works like this: public void block(int row, int col) { if (row > 0) { board[row - 1][col].block(); } if (row < 7) { board[row + 1][col].block(); } if (col > 0) { board[row][col - 1].block(); } if (col < 7) { board[row][col + 1].block(); } } When I try to solve it gives me someting like this : instead of : Any help would be greatly appriecated! A: Try this, it should work and go straight to finish: public boolean findPath(int row, int col) { board[row][col].visit(); if ((col == 7) && (row == 7)) { board[row][col].selectCell(); return true; } if ((row < 7) && !board[row + 1][col].marked() && !board[row + 1][col].blocked() && !board[row + 1][col].visited()) { block(row, col); if (findPath(row + 1, col)) { board[row][col].selectCell(); return true; } unblock(row, col); } if ((col > 0) && !board[row][col - 1].marked() && !board[row][col - 1].blocked() && !board[row][col - 1].visited()) { block(row,col); if (findPath(row, col - 1)) { board[row][col].selectCell(); return true; } unblock(row,col); } if ((col < 7) && !board[row][col + 1].marked() && !board[row][col + 1].blocked() && !board[row][col + 1].visited()) { block(row,col); if (findPath(row, col + 1)) { board[row][col].selectCell(); return true; } unblock(row,col); } if ((row > 0) && !board[row - 1][col].marked() && !board[row - 1][col].blocked() && !board[row - 1][col].visited()) { block(row, col); if (findPath(row - 1, col)) { board[row][col].selectCell(); return true; } unblock(row, col); } return false; } You needed to change orders.
{ "language": "en", "url": "https://stackoverflow.com/questions/34479670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Re Use of DefaultTableModel DefaultTableModel dtm = new DefaultTableModel(new Object[]{"SR#", "Date", "Name", "Description", "Quantity", "Weight", "Rate", "Total", "Balance","Paid","Net Pay"},0); table = new JTable(); table.setModel(dtm); JScrollPane scroller=new JScrollPane(table); table.setBackground(new java.awt.Color(255,226,226)); scroller.setBounds(0,0,1335,380); p2.add(scroller); while(rs.next()){ dtm.addRow(new Object[]{rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8),rs.getString(9),rs.getString(10),rs.getString(11)}); How can I re use this code several times in my program without creating a new object every time when an event is occurred. A: Seems like you have declared the JTable globally and initializing every time when some action event is triggered. As like JTable, you can declare your DefaultTableModel globally and initialize both JTable and TableModel. If you don't want to maintain the old records in JTable, you can clear the JTable every time when some action event is trigerred. A: Finally I got the solution to my Problem. I just need to call 2 methods whenever I press a button before running the SQL Query. Those 2 methods are panel.removeAll(); and panel.validate(); This erase everything on your previous panel from your screen and displays only the result which you desire to see.
{ "language": "en", "url": "https://stackoverflow.com/questions/32208590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Why does MD5 Hash For FileStream and String Differ C# I generate a MD5 Hash from a String and from a File Containing the Same String using System.Security.Cryptography.MD5. However the Hash Values Differ. Here is the code to generate from a string byte[] data = Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog"); byte[] hash = MD5.Create().ComputeHash(data); return BitConverter.ToString(hash).Replace("-", "").ToLower(); And Here is the code when I generate the hash from the file internal static string CalculateFileHashTotal(string fileLocation) { using(var md5 = MD5.Create()) { using (var stream = File.OpenRead(fileLocation)) { byte[] b = md5.ComputeHash(stream); stream.Close(); return BitConverter.ToString(b).Replace("-", "").ToLower(); } } } The Hash from the string is correct, So I assume the Hash from the file reads some extra stuffs or doesn't read the entire file. I couldn't find an answer on Google. Any Ideas? A: The hash differs because the data differs. The file is UTF-8, not ASCII, so you should use the UTF-8 encoding to convert the string to bytes to get the same result: byte[] data = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog"); Also, the file may contain a BOM (byte order mark) at the beginning. That is included in the data, as the file isn't read as text. Adding the UTF-8 BOM at the beginning of the data would give the same hash: byte[] bom = { 239, 187, 191 }; byte[] data = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog"); byte[] bomdata = new byte[bom.Length + data.Length]; bom.CopyTo(bomdata, 0); data.CopyTo(bomdata, bom.Length); byte[] hash = MD5.Create().ComputeHash(bomdata); A: Did you trim the string from the file for whitespace and new lines?
{ "language": "en", "url": "https://stackoverflow.com/questions/13245842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: show div on right click of element I am trying to show div on click of right click event, this right click is working fine but event is not applied Correctly. Fiddle:: http://jsfiddle.net/SRX3y/82/ Code:: $.event.special.rightclick = { bindType: "contextmenu", delegateType: "contextmenu" }; $(document).on("rightclick", "div", function() { alert("hello"); $('#popup').css('display','inline-block'); return false; }); A: Try this..selector name is mistake.it should be #pop_up $(document).on("rightclick", "div", function() { alert("hello"); $('#pop_up').css('display','block'); return false; }); DEMO A: Your code is working fine. Just change from $('#popup').css('display','inline-block'); to $('#pop_up').css('display','inline-block'); A: you have wrong id Its pop_up and not popup
{ "language": "en", "url": "https://stackoverflow.com/questions/20045460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Why won't int variable come before char array in terms of addressing no matter how I code it in C? I'm reading Hacking: The Art of Exploitation (2nd Edition), and I'm currently on the section about buffer overflows. In the first example, the variables are declared/initialized in this order: int auth_flag = 0; char password_buffer[16]; The example goes on to explain that you can use gdb to examine auth_flag and password_buffer's addresses, and you'll notice that auth_flag's address is higher than password_buffer's. Things to keep in mind: I'm running all of this in Ubuntu within Virtualbox on a Macbook Pro (Intel processor, 64-bit). I compiled the first example's code like this: gcc -g -fno-stack-protector -o auth_overflow auth_overflow.c As expected, auth_flag's address is higher than password_buffer's. To remedy the problem presented above, the author explains you should switch the ordering of the declarations: char password_buffer[16]; int auth_flag = 0; I compiled the code the same way: gcc -g -fno-stack-protector -o auth_overflow2 auth_overflow2.c Unfortunately, I did not see auth_flag's address being lower than password_buffer's. In fact, it was still higher. Why is this? What am I doing wrong? A: The compiler is allowed to choose whatever order it wants, in order to provide more optimal code, or even just random because it's easier to implement. One thing you might try is -O0 flag which disables all optimizations. A: Compilers are free to rearrange variables as they feel is best. I believe that the only restriction in the order of struct members. Those must be in memory in the same order as declared in the struct. A: I found this thread quite interesting: http://www.mail-archive.com/avr-gcc-list@nongnu.org/msg05043.html Quote: In theory it can be done -fdata-section A: Apple has a security feature to prevent just the type of hacking you are talking about - There is a degree of randomization to where everything is stored in memory, so you can't for example find the memory allocated for a certain program, and go to the 1502nd byte where the function to open the high security vault locks sits, cause it isn't always in the same place in memory. See http://en.wikipedia.org/wiki/Address_space_layout_randomization for details on how this works. Funny coincidence that you would encounter this, and that Matt Joiner would stumble on the answer while trying to burn apple.
{ "language": "en", "url": "https://stackoverflow.com/questions/3481930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How To Save A URL Object As A Text File? I have an assingment I have to do so please do not post the code, but can someone explain to me logically how it is possible to save a URL source code as a text file? So far I have this code from the Oracle docs: import java.net.*; import java.io.*; public class URLConnectionReader { public static void main(String[] args) throws Exception { URL oracle = new URL("http://www.oracle.com/"); URLConnection yc = oracle.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } } So this is basically showing me the entire source code in the console, but I want to turn it into a text file which I can then analyze to find trends in the data. A: I think below code will help you public static void main(String[] args) throws IOException{ downloadFunction("http://google.com.vn", "/tmp/google.html", "someHeaderValue"); } private static void downloadFunction(String url, String outPut, String headerValue) throws IOException{ URL website = new URL(url); URLConnection connection = website.openConnection(); connection.setRequestProperty("headerKey", headerValue); InputStream response = connection.getInputStream(); ReadableByteChannel rbc = Channels.newChannel(response); FileOutputStream fos = new FileOutputStream(outPut); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); }
{ "language": "en", "url": "https://stackoverflow.com/questions/23051262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add newline return or linebreak to string (Typescript & React) I have a variable called resultElem which is created after reading an array. As it reads the array, I want to add a newline '\n' or at the end of it, following a space. for (let l=0; l<answer.questions.length; l++) { var questionMap = [answer.questions[l].questionId, answer.questions[l].answers]; let resultElem :any; for (let m =0; m< employmentAnswerMap[l].answerKVs.length; m++){ if (questionMap[1].includes(employmentAnswerMap[l].answerKVs[m].id)) { resultElem = resultElem + employmentAnswerMap[l].answerKVs[m].text + ' ' + '\n';// I have tried + '\n' and + 'br' } } result.push(resultElem); } I have also tried .appendChild() but I didn't like it since I just want to use resultElem to make the data. return ( <dl> <dt>Health Needs</dt> <dd>{result[0]}</dd> </dl> ...more ui code It gets displayed, but as one big text paragraph without newlines, like so healthNeed1 healthNeed2 healthNeeds3 healthNeed1 healthNeed2 healthNeeds3 A: I am able to print the strings in seperate line by using '\n'. I am adding demo below. Can you please update that as per the issue you are facing so that we can look into that. Demo : const answer = { questions: [{ questionId: 1, answers: ['answer1', 'answer2', 'answer3'] }] }; const employmentAnswerMap = [ { answerKVs: [{ id: 1, text: 'healthNeed1' }, { id: 2, text: 'healthNeed2' }, { id: 3, text: 'healthNeed3' }] } ]; const result = []; for (let l=0; l<answer.questions.length; l++) { var questionMap = [answer.questions[l].questionId, answer.questions[l].answers]; let resultElem = ''; for (let m =0; m < employmentAnswerMap[l].answerKVs.length; m++){ if (questionMap[1].find((elem) => elem.includes(employmentAnswerMap[l].answerKVs[m].id)).length > 0) { resultElem = resultElem + employmentAnswerMap[l].answerKVs[m].text + ' ' + '\n'; } } result.push(resultElem); } console.log(result[0]); A: HTML doesn't really like to add line breaks, even if you include them. If you have to include them, template literals are the easiest way. To use those, use backticks(`) instead of single(') or double quotes("). Template Literals take literally what you type as the string, and can only be escaped at the end of the string, or by encapsulating your escaped javascript with ${}. It looks like this: let bob=true; `Look at me, I'm using backticks! ${bob ? "No literals here!" : "But you can use the 'ternary operator'!"}` Unfortunately, it doesn't look like the code sample likes backticks. But I assure you, they work! Of course, even with the return inside the template literals, HTML is going to mostly ignore them unless you use the new CSS white-space property. You could also add append a new <p> tag for each one, which can be styled however you like, including to make them have a new line. A: I had to wrap my HTML around this div in order for the newlines ("/n") to display properly <div style={{whiteSpace: "pre-wrap"}}>
{ "language": "en", "url": "https://stackoverflow.com/questions/71178689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change name server in GoDaddy may hosting in hostinger I want change name server in GoDaddy my hosting on hostinger vps hosting and my control panel is cent os control panel where I get me name server A: You should get your Name server on Email when you order the Hosting server also you can find the name server on logged in cpanel.
{ "language": "en", "url": "https://stackoverflow.com/questions/59823618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: POST JSON data with cURL I want to POST some JSON data to a server. I have constructed one javascript object for that: var formData; formData[0] = { value : accx.toString(); } Now the post function is: function postdata(){ var accx = acc.x; } acc.x is generated in a function and I will call postdata() function from that function. The cURL data POST example I got is: curl -i -X PUT https://abcd.com/v1/feeds/5e5530142d3wecwecwec28265eabe/streams/acc_x -H "X-API-KEY: 2b9e2596eafwefwef6a7956e6f7a" -H "Content-Type: application/json" -d '{ "value": "40" }' Now what I want is I want send data like -d '{ "acc_x": "0.2319393291" }' continuously [generated data, not same value] But I am not getting how to that. Anyone please help :) Another problem is, the // in url will be seen as comment. so how to address this? Please suggest and help. A: Do you get an error back? I suggest you change your -i to -v, in order to get a verbose response to give you more information. Also your curl command uses PUT and not POST as you say; please clarify if the question is about one or the other? Finally, try to remove the quote marks from you numeric values, you don't need them.
{ "language": "en", "url": "https://stackoverflow.com/questions/25363804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Second End View puzzle, Prolog I write code in swi-prolog to solve Second End View Pazzles 7*7 (example http://www.funwithpuzzles.com/2009/10/abcd-second-end-view-ev4.html like this 5*5) for numbers 1-6 :- [library(clpfd)]. gen_row(Ls):-length(Ls, 7), Ls ins 0..6. abc_view :- maplist(gen_row, [R1,R2,R3,R4,R5,R6,R7]), transpose([R1,R2,R3,R4,R5,R6,R7], [C1,C2,C3,C4,C5,C6,C7]), maplist(all_distinct, [R1,R2,R3,R4,R5,R6,R7]), maplist(all_distinct, [C1,C2,C3,C4,C5,C6,C7]), start(R1, 4), start(R2, 2), start(R3, 3), start(R4, 5), start(R5, 3), finish(R1, 6), finish(R2, 4), finish(R3, 2), finish(R5, 1), finish(R7, 2), start(C2, 3), start(C3, 4), start(C4, 3), start(C5, 5), start(C6, 4), start(C7, 1), finish(C1, 3), finish(C2, 2), finish(C3, 5), finish(C4, 5), finish(C5, 6), finish(C6, 1), finish(C7, 4), maplist(writeln, [R1,R2,R3,R4,R5,R6,R7]). How logic i need to write to solve it, maybe on more simple example for 4*4 or 5*5.. i'll be happy for any help. i need to write it for 3 tests but it will be grait for even one. A: I got a solution, effectively the problem is much more simple that the 'SkyScrape & Fences' puzzle I solved previously. I'm afraid I previously misunderstood the problem and placed a wrong comment, suggesting you to abandon the (right) path you already took. /* File: second_end_view_puzzle.pl Author: Carlo,,, Created: Oct 8 2012 Purpose: help to solve Second End View puzzle as quested at https://stackoverflow.com/q/12717609/874024 */ :- [library(clpfd)]. gen_row(Ls) :- length(Ls, 7), Ls ins 0..6. abc_view :- Rows = [R1,R2,R3,R4,R5,_R6,R7], maplist(gen_row, Rows), transpose(Rows, [C1,C2,C3,C4,C5,C6,C7]), maplist(all_distinct, Rows), maplist(all_distinct, [C1,C2,C3,C4,C5,C6,C7]), start(R1, 4), start(R2, 2), start(R3, 3), start(R4, 5), start(R5, 3), finish(R1, 6), finish(R2, 4), finish(R3, 2), finish(R5, 1), finish(R7, 2), start(C2, 3), start(C3, 4), start(C4, 3), start(C5, 5), start(C6, 4), start(C7, 1), finish(C1, 3), finish(C2, 2), finish(C3, 5), finish(C4, 5), finish(C5, 6), finish(C6, 1), finish(C7, 4), maplist(label, Rows), maplist(writeln, Rows). % place the constraint 'SECOND in that direction' using a reified check start(Vars, Num) :- Vars = [A,B,C|_], X #<==> ( A #= 0 #\/ B #= 0 ) #/\ C #= Num, Y #<==> A #\= 0 #/\ B #= Num, X + Y #= 1 . finish(Vars, Num) :- reverse(Vars, Sarv), start(Sarv, Num). edit test: ?- abc_view. [5,4,0,2,1,6,3] [6,0,2,3,5,4,1] [1,3,4,6,2,5,0] [2,5,1,4,0,3,6] [0,6,3,5,4,1,2] [3,2,5,1,6,0,4] [4,1,6,0,3,2,5] true ; false. edit here is the 'porting' to GnuProlog. I've copied from SWI-Prolog CLP(FD) library the transpose/2 code. /* File: second_end_view_puzzle.pl Author: Carlo,,, Created: Oct 8 2012 Purpose: help to solve Second End View puzzle as quested at https://stackoverflow.com/q/12717609/874024 */ gen_row(Ls) :- length(Ls, 7), fd_domain(Ls, 0, 6). transpose(Ms, Ts) :- %must_be(list(list), Ms), ( Ms = [] -> Ts = [] ; Ms = [F|_], transpose(F, Ms, Ts) ). transpose([], _, []). transpose([_|Rs], Ms, [Ts|Tss]) :- lists_firsts_rests(Ms, Ts, Ms1), transpose(Rs, Ms1, Tss). lists_firsts_rests([], [], []). lists_firsts_rests([[F|Os]|Rest], [F|Fs], [Os|Oss]) :- lists_firsts_rests(Rest, Fs, Oss). writeln(X) :- write(X), nl. abc_view :- Rows = [R1,R2,R3,R4,R5,_R6,R7], maplist(gen_row, Rows), transpose(Rows, [C1,C2,C3,C4,C5,C6,C7]), maplist(fd_all_different, Rows), maplist(fd_all_different, [C1,C2,C3,C4,C5,C6,C7]), start(R1, 4), start(R2, 2), start(R3, 3), start(R4, 5), start(R5, 3), finish(R1, 6), finish(R2, 4), finish(R3, 2), finish(R5, 1), finish(R7, 2), start(C2, 3), start(C3, 4), start(C4, 3), start(C5, 5), start(C6, 4), start(C7, 1), finish(C1, 3), finish(C2, 2), finish(C3, 5), finish(C4, 5), finish(C5, 6), finish(C6, 1), finish(C7, 4), maplist(fd_labeling, Rows), maplist(writeln, Rows). % place the constraint 'SECOND in that direction' using a reified check start(Vars, Num) :- Vars = [A,B,C|_], X #<=> ( A #= 0 #\/ B #= 0 ) #/\ C #= Num, Y #<=> A #\= 0 #/\ B #= Num, X + Y #= 1 . finish(Vars, Num) :- reverse(Vars, Sarv), start(Sarv, Num).
{ "language": "en", "url": "https://stackoverflow.com/questions/12717609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Multi undefined variables from a form and subsequent sql statement The outcome I seek is to loop through items taken from a form that isset or true and then have a sql statement query the database. The complication comes from I have 9 fields that the user could choose one or more or all fields (It is a search database but every time you choose an extra field it refines the search). The part of the code to return true I can get my head around by using a foreach loop but how would you link it to SQL query if the outcome is varied? A: You generate a different query depending on which fields are entered. Luckily this isn't too hard in SQL: all those fields are in the WHERE clause: $where = [ 'foo' => 'bar', 'baz' => 0 ]; $sth = $db->prepare( "SELECT * FROM $table WHERE " . implode( " AND ", array_map( function($i) { return "$i=?"; }, array_keys( $where ) ) ) ); $sth->execute( array_values( $where ) ); Of course, if there are relationships between the fields, the query may become more complicated, but this is the gist of it. A: Learning this takes time and patience I have cut past the variables from the form if(isset($_POST['Search'])){ $packID = $_POST['packID']; $supplier_name = $_POST['supplier_name']; $timber_species = $_POST['timber_species']; $timber_product = $_POST['timber_product']; $timber_grade = $_POST['timber_grade']; $timber_finish = $_POST['timber_finish']; $timber_treatment = $_POST['timber_treatment']; $width = $_POST['width']; $thickness = $_POST['thickness']; $length = $_POST['length']; $markup = $_POST['markup']; } else{ $packID=""; $supplier_name=""; $timber_species=""; $timber_product=""; $timber_grade=""; $timber_finish=""; $timber_treatment=""; $width= ""; $thickness= ""; $length=""; } How would you write this Kenney when the variables may or may not be set. I must admit I am a novice and keen to learn. It takes time and patience.
{ "language": "en", "url": "https://stackoverflow.com/questions/33600707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the difference between creating String as new() (inside heap not in string pool)and literal(inside string pool)? When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap. is it right ???????? Is my explanation correct.....
{ "language": "en", "url": "https://stackoverflow.com/questions/29159269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any way to prevent destroying a component in angular? We know that there is a method ngOnDestroy() in angular which runs on destroying a component but I want to know that is there any way to prevent it from destroying? A: The CanDeactivate guard has access to the instance of the active component, so you can implement a hasChanges() that check if there have been changes and conditionally ask for the user confirmation before leave. In the following example the CanDeactivateComponent implements the methods hasChanges() that returns a boolean value indicating if the components has detected any changes. The implementation of CanDeactivate guard is similar to the CanActivate guard implelementaion (you can create a function, or a class that implements the CanDeactivate interface): import { CanDeactivate } from '@angular/router'; import { CanDeactivateComponent } from './app/can-deactivate'; export class ConfirmDeactivateGuard implements CanDeactivate<CanDeactivateComponent> { canDeactivate(target: CanDeactivateComponent) { if(target.hasChanges()){ return window.confirm('Do you really want to cancel?'); } return true; } } Even though, this is a very trivial implementation, CanDeactivate uses a generic, so you need to specify what component type you want to deactivate. In the Angular router of the component: { path: '', component: SomeComponent, canDeactivate: [ConfirmDeactivateGuard] } Last, like all other services on Angular, this guard needs to be registered accordingly: @NgModule({ ... providers: [ ... ConfirmDeactivateGuard ] }) export class AppModule {} You can have multiple guards protecting a single route, which helps you implementing sophisticated use cases, where a chain of different checks is needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/48514644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Should we ask users to confirm an e-mail address when they change it? I have a service that requires an active e-mail address where users can receive notifications. Users can optionally receive notifications on multiple e-mail addresses by adding them. * *Should I require a new e-mail address be confirmed before I activate it? *Should I require an e-mail address be confirmed before changing it? I'm looking for best practices. I'm not dealing with any sensitive or billing information. A: Yes, it would be best to do so. Imagine.. What if the email address they provided is not correct(misspelled) or not existing or worse--someone else's? Regarding the last case, I don't mean that your service is spam, but simply that the notifications they had hoped to receive would be sent to someone else. I think it would still be beside the point even if no important information is included in the notification--it would be a matter of the wrong person receiving notifications meant for someone else. :) A: I would suggest that you have to confirm the new email before it can be changed so you still have contact with the user. The old email could potentially be stored in a separate database so is not visible to the user and only deleted when he/she has confirmed the new email. A: Yes. Doing so protects users who have had their site accounts compromised from having someone change the main e-mail address and completely lock the user out of his account. This is good practice regardless of whether or not the account protects sensitive information because nobody wants to deal with being locked out of an account by an attacker.
{ "language": "en", "url": "https://stackoverflow.com/questions/8202272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CodeIgniter sess_destroy() for current session I have this code in Session.php: // Is the session current? if (($session['last_activity'] + $this->sess_expiration) < $this->now) { $this->sess_destroy(); return FALSE; } for each session CodeIgniter sets cookies expire date as $this->sess_expiration + time(); if i set this->sess_expiration = 5, and send get request after 6 seconds it will contain no cookie, because browser will destroy it due to exp date. So CI will just create new session record, what is the solution for deleting old ones? A: You need to cleanup the session table in database, which is used to store the session information. This table should be named ci_sessions.
{ "language": "en", "url": "https://stackoverflow.com/questions/5702609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting the center of a grid's cell - unity I'm working on an isometric game with Unity and I need to know the centre of the cell in the world coordinates. I'm using the tilemap's GetCellCenterWorld() method, but it gives me back bad results. Here is what I expect to be the centre of the cell (basically the logical centre), but here is what Unity gives back (the top vertex of the cell?). I believe it has something to do with the sprite's pivot point (now set to its top centre) or the cell anchor in the tilemap's properties (I set it to (1,1)). Here's the code I use to "select" the tiles: public class GridSelection : MonoBehaviour { public Tilemap tilemap; public Transform selector; void Update() { Vector3 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition); worldPos.z = 0; Vector3Int tilemapPos = tilemap.WorldToCell(worldPos); selector.position = tilemap.GetCellCenterWorld(tilemapPos); } } How do I get the actual middle point of the cell? A: Okay, I think I found what the issue was. If anyone has the same problem, here's how I resolved it: * *Set the sprite pivot point to the place you want the middle of the cell to be (in my case, the centre of the grass section) *Set tile anchor back to (0.5, 0.5) *Use the GetCellCenterWorld() method normally The code I've posted in the question works just fine now. A: [SerializeField] private Tilemap map; private Camera camera; [SerializeField] private Transform playerTransform; void Start(){ camera = Camera.main; } // Update is called once per frame void Update(){ if (Input.GetMouseButtonDown(0)){ var worldPos = camera.ScreenToWorldPoint(Input.mousePosition); Vector3Int tilemapPos = map.WorldToCell(worldPos); playerTransform.position = map.CellToWorld(tilemapPos); Debug.Log(tilemapPos); } } playerTransform.position = map.CellToWorld(clickedCellPosition); Just convert it back and provide tilemapPos A: Try tilemap.cellBounds.center https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.html
{ "language": "en", "url": "https://stackoverflow.com/questions/64143308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Performance comparison of atomic operations on different sizes How do the performance of atomic operations operating on the natural word size of the processor (4-byte or 8-byte) compare to that of operating on other sizes (2-byte or 1-byte)? If I need to maintain a boolean atomic variable, I'm trying to figure out the what the best practice is: use 1-byte to optimize for space, or 4/8-byte to (potentially) optimize for performance. A: http://agner.org/optimize/ for lots of details. On x86, an array of 1-byte data should be good. It can be loaded with movzx (zero-extend) just as fast as with a plain mov. x86 has bit ops to support atomic bitfields, if you want to pack your data by another factor of 8. I'm not sure how well compilers will do at making efficient code for that case, though. Even a write-only operation requires a slow atomic RMW cycle for the byte holding the bit you want to write. (On x86, it would a lock OR instruction, which is a full memory barrier. It's 8 uops on Intel Haswell, vs. 1 for a byte store. A factor of 19 in throughput.) This is probably still worth it if it means the difference between lots of cache misses and few cache misses, esp. if most of the access is read-only. (Reading a bit is fast, exactly the same as the non-atomic case.) 2-byte (16bit) operations are potentially slow on x86, esp. on Intel CPUs. Intel instruction decoders slow down a lot when they have to decode an instruction with a 16bit immediate operand. This is the dreaded LCP stall from the operand-size prefix. (8b ops have a whole different opcode, and 32 vs. 64bit is selected by the REX prefix, which doesn't slow down the decoders). So 16b is the odd-one-out, and you should be careful using it. Prefer to load 16b memory into 32b variables to avoid partial-register penalties and 16bit immediates when working with a temporary. (AMD CPUs aren't quite as efficient at handling movzx loads (takes an ALU unit and extra 1 cycle latency), but the savings in memory are still almost always worth it (for cache reasons)). 32b is the "optimal" size to use for local scratch variables. No prefix is needed to select that size (increasing code density), and there won't be partial-register stalls or extra uops when using the full register again after using the low 8b. I believe this is the purpose of the int_fast32_t type, but on x86 Linux that type is unfortunately 64bit.
{ "language": "en", "url": "https://stackoverflow.com/questions/29322218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Haskell Zip Parse Error I am trying to use the zip function in Haskell to join two lists together. The lists could be defined and info gathered as follows: priority <- getLine let priorityList = [] priority : priorityList name<- getLine let nameList = [] name : nameList After gathering the info, the expected output would be priorityList = [1,2,3] & nameList = [test1, test2, test3]. However, this is unimportant for the purpose of the question, it can be assumed that the two lists are in the following format: priorityList = [1,2,3] nameList = [test1, test2, test3] I need to combine the lists and print with the following function. However, i am getting the error 'parse error on input `zip'' printList :: IO () printList = do putStrLn "Printed Combined List" zip [nameList][priorityList] A: printList :: IO () printList = do putStrLn "Printed Combined List" zip [NameList][PriorityList] There are many things wrong with this code. The parse error you are seeing is because the do block is not properly aligned. The zip on the last line must line up with the putStrLn on the line before. So either printList :: IO () printList = do putStrLn "Printed Combined List" zip [NameList][PriorityList] or printList :: IO () printList = do putStrLn "Printed Combined List" zip [NameList][PriorityList] But that still won't work. printList is declared to be an IO action, which means the final line of the do block must be an IO action also... but zip produces a list. You may have meant this: printList :: IO [(String, Int)] printList = do putStrLn "Printed Combined List" return (zip [NameList][PriorityList]) but that will only print out the result when you run it directly from the ghci prompt. Better to print it out explicitly: printList :: IO () printList = do putStrLn "Printed Combined List" print (zip [NameList][PriorityList]) But it still won't do what you want! Because NameList and PriorityList are, presumably, lists. That you want zipped together. But that's not what you're giving to zip: you're giving zip two new single element lists. You no doubt intended just to pass the lists directly. printList :: IO () printList = do putStrLn "Printed Combined List" print (zip NameList PriorityList) Oh, but it still won't work. Won't even compile. And why is that? Because variable names must start with lower case letters (or an underscore). And you've started both NameList and PriorityList with capital letters. Which is one reason why your first block of code so obviously could not have worked. printList :: IO () printList = do putStrLn "Printed Combined List" print (zip nameList priorityList) A: Using the above assistance, i have been able to construct a function (below) to achieve a successful ZIP (Excluding information gathering). printList :: IO () printList = do let nameList = ["test1", "test2", "test3"] let prioirtyList = [1, 2, 3] putStrLn "Printed Combined List" print (zip nameList prioirtyList) My output is as follows: *Main> printList Printed Combined List [("test1",1),("test2",2),("test3",3)]
{ "language": "en", "url": "https://stackoverflow.com/questions/15635012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Adding A Node To A Nodelist Using XmlParser In Groovy When I add a Node to a NodeList using the XmlParser in Groovy, the NodeList does not appear to reflect the change. Here is the code that I'm testing within the GroovyConsole. If you run this code, you should see the output "ADD FAILED" followed by a dump of the three elements of the NodeList. I've also tried the same thing with XmlSlurper but switched to XmlParser when I read that the DOM in XmlSluper is basically immutable and that changes only get applied during serialize. But with XmlParser, should this work? def xml = ''' <site id='myCoolSite'> <pages/> <templates/> <properties> <property name='good' value='true'/> <property name='nice' value='true'/> <property name='expensive' value='false'/> </properties> <stuff/> </site> ''' site = new XmlParser().parseText( xml ) assert site != null assert site.properties.property instanceof NodeList assert site.properties.property.size() == 3 def newNode = new Node(null, "property", [name: "foo", value: "bar"] ) site.properties.property.add( 0, newNode ) def foo = site.properties.property.find { it.@name == "foo" } if ( foo == null ) { println "ADD FAILED. Here are the only properties found: " site.properties.property.each { println "${it.@name}=${it.@value}" } } else { println "SUCCESS" } A: It works if you add it to the children of properties rather than the property node-list. Ie change: site.properties.property.add( 0, newNode ) To site.properties[0].children().add( 0, newNode )
{ "language": "en", "url": "https://stackoverflow.com/questions/36610537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In a pure user level thread strategy, why can't a multithreaded application take advantage of multiprocessing? My textbook states the following: In a pure ULT (user level thread) strategy, a multithreaded application cannot take advantage of multiprocessing. A kernel assigns one process to only one processor at a time. Therefore, only a single thread within a process can execute at a time. In effect, we have application-level multiprogramming within a single process. While this multiprogramming can result in a significant speedup of the application, there are applications that would benefit from the ability to execute portions of code simultaneously. I understand the elementary concepts, such as user level threads, multithreading, and multiprocessing. However, I don't understand the above justification for why a multithreaded application can't take advantage of multiprocessing in a pure ULT strategy. I would greatly appreciate it if someone could please take the time to clarify this with a clearer explanation. A: The important fact is that user level threads (or green threads) are handled by the programming language and are not exposed to the operating system. In ULT the threads are entirely "hidden within the python runtime". This has the advantage that the programming processing envinroment has the full control over the threads. To the OS the program looks like a single thread and thus only runs on one core at a time. On the other hand, kernel threads are handled by the OS. They can run on different cores at once and benefit from this speed improvement. The downside is that things like "thread safe memory access" need to be handled by the threads themselves and there is no "outside language scheduler" (as in user level threads) which can guarantee the thread safety. That's why for instance in python there's a "global interpreter lock" which guarantees, that two kernel threads never run at the same time. That's just a short summary. If you're interested to know more, look up "global interpreter lock" (python, ruby) or see this answer
{ "language": "en", "url": "https://stackoverflow.com/questions/42037109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pascal's triangle series in php I am trying to get pascal's triangle using two dimensional array. But it not works. can anyone solve this program. Thanks in advance. <html> <body> <div> <form name="form1" action="pascaltriangle4.php" method="post"> Enter the number of rows in pyramid of stars you wish to see : <input type="text" name="n"> <input type="submit" name="submit" value="submit"> </form> </div> <div> <table> <?php if($_POST['submit']==='submit') { ini_set('display_errors', 1); error_reporting(E_ALL); $n=$_POST['n']; $arr=array(); //print_r($arr); for($i=0;$i<=$n;$i++) { echo "<tr>"; for($j=0;$j<=$i;$j++) { if($j==0) { //echo "1"; $arr[$i][$j]=1; //print_r($arr); if($n!=$i) { echo "<td colspan='".($n-$i)."'></td>"; } echo "<td>".$arr[$i][$j]."</td>"; echo "<td></td>"; } elseif($i==$j) { //echo "1"; $arr[$i][$j]=1; //echo $arr; echo "<td>".$arr[$i][$j]."</td>"; //echo "<td></td>"; } else { $arr[$i][$j]=$arr[$i-1][$j-1]+$arr[$i-1][$j]; echo "<td>".$arr[$i][$j]."</td>"; echo "<td></td>"; } }echo "</tr>"; } //echo "<pre>"; //print_r($arr); //echo "</pre>"; } ?> </table></div> <body> </body> </html> A: $size = 32; $pascal = array( array(1), ); for ($i = 1; $i <= $size; ++$i) { $prevCount = count($pascal[$i-1]); for ($j = 0; $j <= $prevCount; ++$j) { $pascal[$i][$j] = ( (isset($pascal[$i-1][$j-1]) ? $pascal[$i-1][$j-1] : 0) + (isset($pascal[$i-1][$j]) ? $pascal[$i-1][$j] : 0) ); } } var_dump($pascal);
{ "language": "en", "url": "https://stackoverflow.com/questions/17994347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Docker Port forwarding doesn't call css and images I have setup port concepts in docker to access my container magento2 to locally connected another system. This is Docker Container Setup: docker run -it -d --name containerName -h www.myhost.net -v /var/www/html -p 3000:80 --net mynetwork --ip 172.11.0.10 --privileged myimagename then, Execute the Container: docker exec -it containerName bin/bash volume path /var/www/html with in the volume path i write one index.html file and access to anoter locally connected system its working fine. hostmachineip:3000 After I installed magnento2 in my container with in volume(/var/www/html), Then test Its working for me.But Doesn't call css and images. hostmachineip:3000 But Magento2 Working file in host machine and also port forwarding working file, Because if i call hostmachineip:3000/index.html It working fine. But: if I call host machine its working file, hostmachineip:3000 Its redirect to right server, show magento2 home page with css and images. remote machine only not calling css and images. Configuration File: /etc/nginx/site-available/default (server 172.10.0.30) # nginx Confoguraration server { listen 80; server_name www.xxxxx.net xxxx.net; access_log /var/log/nginx/access_log; error_log /var/log/nginx/error_log; root /var/www/html; location / { index index.html index.php; try_files $uri $uri/ @handler; } # Deny access to specific directories no one # in particular needs access to anyways. location /app/ { deny all; } location /includes/ { deny all; } location /lib/ { deny all; } location /media/downloadable/ { deny all; } location /pkginfo/ { deny all; } location /report/config.xml { deny all; } # location /var/ { deny all; } # Allow only those who have a login name and password # to view the export folder. Refer to /etc/nginx/htpassword. location /var/export/ { auth_basic "Restricted"; auth_basic_user_file htpasswd; autoindex on; } # Deny all attempts to access hidden files # such as .htaccess, .htpasswd, etc... location ~ /\. { deny all; access_log off; log_not_found off; } # This redirect is added so to use Magentos # common front handler when handling incoming URLs. location @handler { rewrite / /index.php; } # Forward paths such as /js/index.php/x.js # to their relevant handler. location ~ .php/ { rewrite ^(.*.php)/ $1 last; } # my proxy Configuration # pass the PHP scripts to FPM socket location ~ \.php$ { try_files $uri =404; # fastcgi_split_path_info ^(.+\.php)(/.+)$; # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini # fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_pass unix:/run/php/php7.0-fpm.sock; #fastcgi_param SCRIPT_FILENAME /usr/share/nginx/www$fastcgi_script_name; fastcgi_param DOCUMENT_ROOT /var/www/html; fastcgi_param SCRIPT_FILENAME /var/www/html$fastcgi_script_name; # send bad requests to 404 fastcgi_intercept_errors on; include fastcgi_params; } } Loadbalancer Machine Conf file: upstream backend { ip_hash; server 172.10.0.30 weight=5; server 172.10.0.40 weight=2; } server { listen 80; server_name chennaihousing.net www.chennaihousing.net; location / { proxy_pass http://backend; include /etc/nginx/proxy_params; } } include /etc/nginx/proxy_params File: proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 100M; client_body_buffer_size 1m; proxy_intercept_errors on; proxy_buffering on; proxy_buffer_size 128k; proxy_buffers 256 16k; proxy_busy_buffers_size 256k; proxy_temp_file_write_size 256k; proxy_max_temp_file_size 0; proxy_read_timeout 300; Why? magento 2 need php support for install in hostmachine, So, Remote Machine also need same Support?. or Any think i miss in this Configuration? Suggest Me How to resolve this problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/39543285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to convert string to integer in BIRT after fetching it from the database? I use BIRT for reports and i am a beginner BIRT user. In my report i must calculate the average of a column. (database is an oracle) In my open script I have sth. like this: sqlText = "select A, B, C, D, ((date1-date2) day to second) as differencedate from problem"; difference date column values are like this: 0 0:22:15 and in my fetch I have if (!maximoDataSet.fetch()) return (false); row["A"] = maximoDataSet.getString("A"); row["B"] = maximoDataSet.getDate("B"); .... row["differencedate"]=maximoDataSet.getString("differencedate"); return (true); I tried to split the string and get the seconds from the differencedate and convert it to integer using plain JavaScript but I am getting an error like "split null" etc. So my question is how can i convert this column to integer in BIRT? A: Try retrieving the date difference from the database as a number - like so: select A, B, C, D, ((date1-date2) day to second) as differencedate, (date1-date2) * 86400 as differenceseconds from problem
{ "language": "en", "url": "https://stackoverflow.com/questions/12971579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jquery calculate the total of all textboxes (addition and subtraction) Hello I am trying to calculate the total of multiple fields in a row (my code will contain multiple rows) on key press (some of them uses addition method and some of them uses subtract method) but as I am newbie I am not too much familiar to JQuery. In my scenario B.Salary, Rec.comm, Sal.comm will add into total field and Advance, deduction fields will subtract from total field and the adjustment field will use addition method if contains positive value and subtraction method if contains negative value. I tried my best to figure out some related scenario but no success. Here is my HTML <div class="col-md-12"> <div ng-controller="customersCrtl"> <!-- Adjustment Code Start --> <!-- Heading Data Start --> <div class="row parts_title space_bottom" style="border-bottom:1px solid #ddd; padding-bottom:5px;"> <div class="col-xs-1 col-md-1" style="text-align:left !important;">#</div> <div class="col-xs-2 col-md-2" style="text-align:left !important;">Employee#</div> <div class="col-xs-2 col-md-2" style="text-align:left !important;">FullName</div> <div class="col-xs-1 col-md-1">B.Salary</div> <div class="col-xs-1 col-md-1">Advance</div> <div class="col-xs-1 col-md-1">Rec.Comm</div> <div class="col-xs-1 col-md-1">Sal.Comm</div> <div class="col-xs-1 col-md-1">Deduction</div> <div class="col-xs-1 col-md-1">Adjustment</div> <div class="col-xs-1 col-md-1">Total</div> </div> <!-- Heading Data End --> <div class="row space_bottom"> <div class="col-xs-1 col-md-1"><input name="checked1" checked="" type="checkbox"></div> <div class="col-xs-2 col-md-2">E17-00001</div> <div class="col-xs-2 col-md-2">Employee Name 1</div> <div class="col-xs-1 col-md-1"><input class="form-control input-sm" value="50000" name="txtMonthlyRate1" type="text"></div> <div class="col-xs-1 col-md-1"><input class="form-control input-sm" value="0" name="txtAdvance1" type="text"></div> <div class="col-xs-1 col-md-1"><input class="form-control input-sm" value="35" name="txtRecovery1" type="text"></div> <div class="col-xs-1 col-md-1"><input class="form-control input-sm" value="2350" name="txtsales1" type="text"></div> <div class="col-xs-1 col-md-1"><input class="form-control input-sm" value="0.00" name="txtdeduction1" type="text"></div> <div class="col-xs-1 col-md-1"><input class="form-control input-sm" value="0.00" name="txtadjustment1" type="text"></div> <div class="col-xs-1 col-md-1"><input class="form-control input-sm" value="52385" name="txttotal1" type="text"></div> </div> <div class="row space_bottom"> <div class="col-xs-1 col-md-1"><input name="checked2" checked="" type="checkbox"></div> <div class="col-xs-2 col-md-2">E17-00002</div> <div class="col-xs-2 col-md-2">Employee Name 2</div> <div class="col-xs-1 col-md-1"><input class="form-control input-sm" value="10000" name="txtMonthlyRate2" type="text"></div> <div class="col-xs-1 col-md-1"><input class="form-control input-sm" value="0" name="txtAdvance2" type="text"></div> <div class="col-xs-1 col-md-1"><input class="form-control input-sm" value="0" name="txtRecovery2" type="text"></div> <div class="col-xs-1 col-md-1"><input class="form-control input-sm" value="0" name="txtsales2" type="text"></div> <div class="col-xs-1 col-md-1"><input class="form-control input-sm" value="0.00" name="txtdeduction2" type="text"></div> <div class="col-xs-1 col-md-1"><input class="form-control input-sm" value="0.00" name="txtadjustment2" type="text"></div> <div class="col-xs-1 col-md-1"><input class="form-control input-sm" value="10000" name="txttotal2" type="text"></div> </div> <!-- Adjustment Code End --> </div> </div> Here is My JS $(document).ready(function(){ $("[input[name^=txt]").keyup(function(){ calcPullTotal(); console.log(calcPullTotal); ); function calcPullTotal() { var basic_salary = parseInt($('input[name^=txtMonthlyRate]').val()); var advance_salary = parseInt($('input[name^=txtAdvance]').val()); var recover_comm = parseInt($('input[name^=txtRecovery]').val()); var sales_comm = parseInt($('input[name^=txtSales]').val()); var deduction_salary = parseInt($('input[name^=txtDeduction]').val()); var adjustment_salary = parseInt($('input[name^=txtAdjustment]').val()); var total_sum = ((basic_salary+recover_comm+sales_comm) - (deduction_salary + advance_salary)) + adjustment_salary; $('input[name^=txtAdjustment]').val(total_sum); } }); A: A exemple add and remove divs by id (jquery) $( '#add' ).click(function() { var n = 0; n = $( "div" ).length; if(n!=1){ n = n-2; } n = n+1; var div_id = "div_"+n; $( document.body ).append( $( '<div id = "'+ div_id+ '">' )); $( "#count" ).val("There are " + n + " divs."); }) // Trigger the click to start //.trigger( "click" ); $( '#remove' ).click(function() { var n = 0; n = $( "div" ).length; if(n!=1){ n = n-2; } var div_id = "div_"+n; $( "#"+div_id ).remove( ); if(n!=0){ n = n-1; } $( "#count" ).val("There are " + n + " divs."); }) body { cursor: pointer; } div { width: 50px; height: 30px; margin: 5px; float: left; background: blue; } span { color: red; } <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> Create and remove divs by id </p> <input id = "count" type = "text" val = "0"> <button id = "remove" >Remove</button> <button id = "add" >Add</button> <br> </br> To add div with id: $( document.body ).append( $( '<div id = "'+ div_id+ '">' )); To remove div with id: $( "#"+div_id ).remove( ); To calculate the number of divs: n = $( "div" ).length; For a specific type of class: var numItems = $('.clas').length;
{ "language": "en", "url": "https://stackoverflow.com/questions/43710779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Resetting ThreadLocal Value I initialize my ThreadLocal with a valueFactory Func. I would also like to reset the Value back to null on occasion. Perhaps I'm doing something wrong, but if I set my threadLocal.Value = null, it still seems to think that threadLocal.IsValueCreated == true. How can I truly reset the threadlocal so that it will regenerate the Value lazily when it is asked for? A: Not that I'm aware of. You could always make it a ThreadLocal<Lazy<T>>, and set it to a new Lazy<T> whenever you wanted to reset it. If this is something you use more than once, you might want to consider encapsulating it as a ResettableThreadLocal<T> or something like that.
{ "language": "en", "url": "https://stackoverflow.com/questions/4974605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Facebook og:image (link image) does not display when sharing my website I cannot get the image to show when sharing my site in FB. Below is my open graph code. I have rescraped using the FB sharing debugging tool (https://developers.facebook.com/tools/debug). soooo many times, and it never displays, in the tool or in a share. The debugger reports no errors, and lists the correct image. The image is 1200x630 and exists on the same site. Using open graph checker displays the expected image. https://iplocation.io/open-graph-checker. I have tried everything i can find in posts. but i really need this working for marketing. Hope someone has the secret sauce. cheers, <meta property="fb:app_id" content="123456789"/> <meta property="og:type" content="website"/> <meta property="og:image" content="http://www.example.com/images/og2.jpg"/> <meta property="og:image:secure_url" content="https://www.example.com/images/og2.jpg"/> <meta property="og:image:type" content="image/jpeg" /> <meta property="og:title" content="my title"/> <meta property="og:description" content="my description."/> <meta property="og:image:width" content="1200"/> <meta property="og:image:height" content="630"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/73089116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sequencing RXJS chaining / processing of NGRX observables in an HttpInterceptor I am having trouble attaching a JWT access token to the header of an HTTP request within a class which derives from the HttpInterceptor (Angular 8) base class. I have narrowed the issue down to the sequence in which the operations are performed within the Http Interceptor. It appears the request is sent to the caller before the token is returned back from the NGRX store (async). I am unclear how to ensure that the request is only returned back once the token has been received back from the NGRX store. export class ServerInterceptor implements HttpInterceptor, OnDestroy { private state$: Observable<any>; private unsubscribeAll: Subject<any>; constructor( private store: Store<AuthenticationState> ) { this.unsubscribeAll = new Subject(); this.state$ = this.store.select(getAccessToken); } ngOnDestroy(): void { this.unsubscribeAll.next(); this.unsubscribeAll.complete(); } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const output = next.handle(request).pipe( takeUntil(this.unsubscribeAll), withLatestFrom( this.store.select(selectAuthenticationState), (_action, state) => { console.log(state.accessToken); if (state.accessToken) { request = request.clone({ setHeaders: { Authorization: `Bearer ${state.accessToken}` } }); } console.log('1'); return request; } ), switchMap((req) => { console.log('2'); return next.handle(req); }), ); console.log('3'); return output; } } The output of the console processes the interceptor in the sequence 3, 1 and 2. It should be processed 1, 2 and 3. A: You can consider using select operator with your selector getAccessToken, and "chain" observables. No need to subscribe if you use first() or take(1) operators. Observable will automatically complete after one value. Your code for HttpInterceptor could looks like below: export class ServerInterceptor implements HttpInterceptor { constructor( private store: Store<AuthenticationState> ) {} intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return this.store.pipe( select(getAccessToken), first(), mergeMap(accessToken => { const authReq = !!accessToken ? request.clone({ headers: request.headers.set('Authorization', `Bearer ${accessToken}`) }) : request; return next.handle(authReq); }) ); } } Some resources on the subject : * *Using NgRx Store Auth Token with Angular HttpInterceptor by Antony Derham *Add JWT Token to Angular HTTP Requests Using NGRX by WASi
{ "language": "en", "url": "https://stackoverflow.com/questions/56851126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple Submit Changes and Exceptions Simple scenarios. Reading data from one source and saving to SQL database using LinqToSQL. There are many rows in the file. It's possible that SQL exception can occur for some rows but we want to ignore it (log exception) and still save the rest of the data. Currently we do submitchanges after each row of input data. The first time SQL Exception is encountered none of the following rows can be processed because the same exceptions seems to be resubmitted. What is the best way to handle this? A: Ok. I seem to have found a solution and wanted to share it. The way to do this is to clear out all pending changes before proceeding. So if the SubmitChanges fails I now call this extension method on the datacontext - RejectPendingChanges(). When the next row is processed it now longer tries to resubmit bad data. public static void RejectPendingChanges(this System.Data.Linq.DataContext db){ var chgset = db.GetChangeSet(); if (chgset != null) { foreach (object objToInsert in chgset.Inserts) { db.GetTable(objToInsert.GetType()).DeleteOnSubmit(objToInsert); } //Undo deletes foreach (object objToDelete in chgset.Deletes) { db.GetTable(objToDelete.GetType()).InsertOnSubmit(objToDelete); } ///this._DB.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, chgset.Deletes); db.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, chgset.Updates); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/27384758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to optimize navigation and user-experience into a login form? I have developed an Universal app that uses a login form, that allowing users to connect or to create an account. It is a simple page that looks like this: This XAML code is also very simple: <ScrollViewer> <StackPanel> <TextBlock x:Uid="loginRegisterTextblockMessage" Style="{StaticResource TitleTextBlockStyle}" Text="Remplissez vos informations d'inscription" /> <TextBox x:Uid="loginRegisterTextboxOrganizationURL" Header="Organisation ou URL" IsSpellCheckEnabled="False" IsHitTestVisible="True" IsTextPredictionEnabled="False" Text="{Binding OrganizationURL, Mode=TwoWay}" /> <TextBox x:Uid="loginRegisterTextboxLastName" Header="Nom" Text="{Binding LastName, Mode=TwoWay}" /> <TextBox x:Uid="loginRegisterTextboxFirstName" Header="Prénom" Text="{Binding FirstName, Mode=TwoWay}" /> <TextBox x:Uid="loginRegisterTextboxEmail" Header="Email" InputScope="EmailSmtpAddress" Text="{Binding Email, Mode=TwoWay}"/> <PasswordBox x:Uid="loginRegisterPasswordboxPassword" Header="Mot de passe" Password="{Binding Password, Mode=TwoWay}" /> <PasswordBox x:Uid="loginRegisterPasswordboxConfirmPassword" Header="Confirmez le mot de passe" Password="{Binding PasswordConfirmation, Mode=TwoWay}" /> <CheckBox x:Uid="loginRegisterCheckboxTermsOfUse" IsChecked="{Binding TermsOfUse, Mode=TwoWay}" > <TextBlock Style="{StaticResource BaseTextBlockStyle}"> <Run x:Uid="loginRegisterTextblockTermsOfUse1" Text="J'accepte les " /> <Underline> <Hyperlink x:Uid="loginRegisterHyperlinkTermsOfUse" NavigateUri="http://termsofuse.html" > <Run x:Uid="loginRegisterTextblockTermsOfUse2" Text="conditions générales d'utilisation" /> </Hyperlink> </Underline> </TextBlock> </CheckBox> <Button x:Uid="loginRegisterButtonRegister" Content="S'inscrire" Command="{Binding RegisterCommand}" /> </StackPanel> </ScrollViewer> But I meet a "problem" for navigating between each fields of this page: => The user must click outside of a TextBlock to hide the keyboard and select the next field: this is not very user-friendly I took a look at a similar "system" form: the page used to create an account to access to the Windows Store. The page looks very similar to my own page: But it is there possible to activate the next field by clicking on its header: The focus moved on the field and the keyboard is also automatically displayed: If I click on the the next header "Nom d'utilisateur", I can see that the next field is now "Domaine", by moving automatically into the displayed content: => Is there an easy way to reproduce this comportment? Is it based on the "Header" of the "TextBox", or by using seperated "TextBlock" to show the header? A: I always looking for a good solution but I didn't find it. I've added events in the XAML for the TextBox and PasswordBox on GetFocus and KeyDown. In the Code-Behind, I can now manage the "Enter" Key, that gives the focus to the next TextBox: private void RegisterTextBox_KeyDown(object sender, KeyRoutedEventArgs e) { TextBox currentTextBox = (TextBox)sender; if (currentTextBox != null) { if (e.Key == Windows.System.VirtualKey.Enter) { FocusManager.TryMoveFocus(FocusNavigationDirection.Next); } } } But I haven't yet managed the ScrollViewer autoscroll like I hope. I tried to inspire me from this link, but to no avail: Keyboard-Overlaps-Textbox => Is there really a way to reproduce the autoscroll that is used on the registration form for the Windows Store?
{ "language": "en", "url": "https://stackoverflow.com/questions/33099987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get map values by index when inside each loop in JavaScript? I try to write tests in a clean way. I iterate through the rows (each of which shows info about attached file) of the table on the page and verify if each attached file has correct size: it('attaches many documents', () => { const fileSizes = ['17.19 KB', '12.06 KB', '67.75 KB'] cy.get('input[type="file"]').attachFile([excelFilePath, docxFilePath, pdfFilePath]) cy.get('div.table-body>.table-row').each(($el, index) => { expect($el.find('.col-upload-size')).to.contain.text(fileSizes[index]) }) }) But earlier in the code I have this map defined: const fileSizesMap = new Map([ ["excelFileSize", "17.19 KB"], ["docxFileSize", "12.06 KB"], ["pdfFileSize", "67.75 KB"] ]); Can I somehow get rid of fileSizes list inside of the test and make use of fileSizesMap instead? A: I understand you want to replace fileSizes with the values from your fileSizesMap: const fileSizes = Array.from(fileSizesMap.values()) A: You could try to return an iterable for values and do your assertions: const fileSizesMap = new Map([ ["excelFileSize", "17.19 KB"], ["docxFileSize", "12.06 KB"], ["pdfFileSize", "67.75 KB"] ]); it('attaches many documents', () => { cy.get('input[type="file"]').attachFile([excelFilePath, docxFilePath, pdfFilePath]) for (const value of fileSizesMap.values()) { cy.get('div.table-body>.table-row').then(() => { expect($el.find('.col-upload-size')).to.contain.text(value) }) } })
{ "language": "en", "url": "https://stackoverflow.com/questions/69827066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Input 0 of layer time_distributed_30 is incompatible with the layer: expected ndim=5, found ndim=4. Full shape received: (None, None, None, None) * *I am trying for classification of MSTAR data set with 10 classes *I have used the modal that contains DCNN and BILSTM with 15 time steps My questions are: * *How to overcome the error *How to get the good classification results. My code is: inputs=Input(shape=(15,60,60,3)) model = Sequential() # 1st Convolutional Layer model.add(TimeDistributed(Conv2D(filters=16 ,kernel_size=(5,5), padding='valid'),input_shape=(15,60,60,3))) model.add(TimeDistributed(Activation('relu'))) # Batch Normalisation model.add(TimeDistributed(BatchNormalization())) # Pooling model.add(TimeDistributed(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))) # 2nd Convolutional Layer model.add(TimeDistributed(Conv2D(filters=32, kernel_size=(5,5), padding='valid'))) model.add(TimeDistributed(Activation('relu'))) # Batch Normalisation model.add(TimeDistributed(BatchNormalization())) # Pooling model.add(TimeDistributed(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))) # 3rd Convolutional Layer model.add(TimeDistributed(Conv2D(filters=64, kernel_size=(5,5), padding='valid'))) model.add(Activation('relu')) # Batch Normalisation model.add(TimeDistributed(BatchNormalization())) # Pooling model.add(TimeDistributed(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))) # 4th Convolutional Layer model.add(TimeDistributed(Conv2D(filters=128, kernel_size=(4,4), padding='valid'))) model.add(TimeDistributed(Activation('relu'))) # Batch Normalisation model.add(TimeDistributed(BatchNormalization())) model.add(TimeDistributed(Flatten())) #add dropout model.add(Dropout(0.0)) #bidirectional lstm model.add(Bidirectional(LSTM(1024,activation='tanh',return_sequences=True))) #2 nd bidirectional layer model.add(Bidirectional(LSTM(1024,activation='tanh',return_sequences=False))) # Output Layer model.add(Dense(10)) model.add(Activation('softmax')) # (4) Compile model.compile(loss='categorical_crossentropy', optimizer='adam',\ metrics=['accuracy']) model.summary()
{ "language": "en", "url": "https://stackoverflow.com/questions/67898846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to call a UDF from a JSON file in Python? I'm working on a chatbot project which fetches "delivery status" information from a database. I've defined a function (lets call it db_info) which will connect to my DB and then get the results. I have a .json file which has different intents like "Greeting", "Status Check", "Closing" etc. The way the application works is - whenever the user types in something, the text is classified into an intent. For ex: when the user types "Hi" the application recognizes it is from the intent "Greeting" and then gives out one of the responses I hard coded in the .json file. However, for the "Status Check" intent I don't want the application to give out some hard coded response from .json file. Instead, I'd like it to call the db_info function when the intent "Status Check" is identified. I'm aware that a function map (dictionary) can be created in .py file and then its value can be called in the json file. But I'm not sure how this is done exactly. def db_info(): --> lives in .py file # connect to postgres and get some information if intent == 'greetings': # pick random statement from "responses" of tag "greeting" from json file if intent == 'status_check': # go to "responses" under tag "status_check" and run the func mentioned there def db_info(): # instead of picking up a random statement from "response" this func needs to be called My json file: {"tag": "greetings", "pattern": ["Hi", "How are you", "Hey", "Hello", "Good Day"], "responses": ["Hello!", "Hey there", "Hi, how can I help you today?"] }, {"tag": "status_check", "pattern": ["Where's my shipment", "Track my shipment"], "responses": ["GetDBInfo function"] } A: You can modify your json to match the following parsing process: * *find the intent the pattern matches *get a response *pass it as an argument to the function of that intent This means that you will add a "function" field to the json and call it when you parse. All intents will simply have it as "print" (or whatever other default operation you're doing) and the "Status_Check" intent will have its own special function. Then, just map the names to actual function objects that you can call. So the json can look like this: [{"tag": "greetings", "pattern": ["Hi", "How are you", "Hey", "Hello", "Good Day"], "function": "print", "responses": ["Hello!", "Hey there", "Hi, how can I help you today?"] }, {"tag": "status_check", "pattern": ["Where's my shipment", "Track my shipment"], "function": "GetDBInfo", "responses": [""] }] And to parse it: import json import random def db_info(useless_arg): print("from func") func_mapping = {"print": print, "GetDBInfo": db_info} with open("test.json") as file: intents = json.load(file) text = input("input: ") for intent in intents: if text in intent["pattern"]: function = intent["function"] arg = random.choice(intent["responses"]) func_mapping[function](arg) An example run: input: Where's my shipment from func input: Hi Hello!
{ "language": "en", "url": "https://stackoverflow.com/questions/70113384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to plot wide dataframe After training a model, I want to plot the accuracy, validation accuracy, etc. In Seaborn, this is what I tried to do: df_model_history = pd.DataFrame( np.array([ history.history['accuracy'], history.history['val_accuracy'] ]).T, columns=['Accuracy', 'Validation Accuracy'] ) df_model_history.index.name = 'Epochs' That creates a data frame that looks like this: Epochs Accuracy Validation Accuracy 0 0.769296 0.766673 1 0.858553 0.894064 2 0.915641 0.901508 3 0.936782 0.892285 And when I want to plot, I do this: sns.set(rc={'figure.figsize':(11.7,8.27)}) sns.lineplot( x='Epochs', y='Accuracy', data=df_model_history ) However, this only plots a single variable in the figure, but I wanted both 'accuracy' and 'val_accuracy' in the same figure. Also, compared to Matplotlib, I have a lot more steps in Seaborn to plot the same output, so I was wondering if I'm doing it incorrectly.
{ "language": "en", "url": "https://stackoverflow.com/questions/72128851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Interrupting DataAdapters? I have a circumstance where I'm popping up a dialog window containing a "Please Wait" message, running an SQL query, then replacing the "Please Wait" message with a DataGridView containing the collected results. The code I'm using for this is basically: Dim X As New Data.SqlClient.SqlCommand X.CommandText = "SELECT some_data FROM someTable" Dim XAdapter As New System.Data.SqlClient.SqlDataAdapter(X) Dim XSet As New DataSet XAdapter.Fill(XSet, "MyTable") Me.someDataGridView.DataSource = XSet.Tables("MyTable").DefaultView I would like to put the retrieval of this data into a background thread, so that the UI doesn't freeze up while I'm loading larger datasets, but, having done this, I'd also like to allow the user to cancel and close the dialog, if accessing the data takes longer than they want to wait. At the moment, this Dialog window can take some arbitrary SQL string and display the results (using SQLDataAdapter) without any extra code. How can I make this process interruptible, while also retaining the ease of access of the SQLDataAdapter? A: How can I make this process interruptible, while also retaining the ease of access of the SQLDataAdapter? According to the documentation you should be able to call Close on the underlying SqlConnection instance. The documentation says this will terminate and rollback any pending transactions. Also, instead of using a SqlDataAdapter (which unfortunately does not have the async Fill methods) you could use SqlCommand.BeginExecuteReader and once that is done you can fill a DataTable by calling the overload of DataTable.Load that accepts an IDataReader. If you want to interrupt a pending a command just call Close.
{ "language": "en", "url": "https://stackoverflow.com/questions/5820327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android Video View turns black This seems to be a very common problem, but I couldn't search for it on SO. I have a simple videoview and it play video from a mp4 file. It continously plays video and loop through the video. Problem is when playing I went to settings and came back then video turns black. This is my Code: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video); video = (VideoView) findViewById(R.id.video); // Load and start the movie Uri video1 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.videoplayback); video.setVideoURI(video1); video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.setLooping(true); } }); video.start(); I don't want anything special in this, just a full screen of video playback which loops video till user tap back button. A: try this private int stopPosition; private VideoView splashVideoView; <-- my Video view in onCreate //video player if (savedInstanceState != null) { stopPosition = savedInstanceState.getInt("position"); } @Override protected void onResume() { super.onResume(); splashVideoView.seekTo(stopPosition); splashVideoView.start(); } // This gets called before onPause so pause video here. @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); stopPosition = splashVideoView.getCurrentPosition(); splashVideoView.pause(); outState.putInt("position", stopPosition); } A: try this private int videoViewStopPosition ; @Override protected void OnPause(){ super.onPause(); videoViewStopPosition = vidView.getCurrentPosition(); vidView.pause(); } @Override protected void OnResume() { super.onResume(); vidView.seekTo(videoViewStopPosition); vidView.start(); } A: I had the same issue. I found that the main reason for that was the use of FrameLayout as the parent layout. I changed it into RelativeLayout as parent layout of the VideoView and the problem get solved. A: You need to create Video view in onResume() also. Try this: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video); setVideoBackground(); } @Override protected void onResume() { super.onResume(); setVideoBackground(); } private void setVideoBackground(){ video = (VideoView) findViewById(R.id.video); // Load and start the movie Uri video1 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.videoplayback); video.setVideoURI(video1); video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.setLooping(true); } }); video.start(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/38814775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: QList destructor behavior - Does call delete/free() on pointers in the list? I have a class SomeObjectList : public QList<SomeObject*> I am creating pointers to SomeObject and sticking them in the list like so: SomeObjectList MyClass::getSomeObjects() { SomeObjectList list; for( int i=0; i<10; ++i ) { list << new SomeObject(); } return list; // Crashes approximately here in QList::~QList } I'm getting a crash in the QList destructor, and it looks like free() may be being called. I found the source code for the function (Qt 4.8.2) and it looks like this: template <typename T> Q_OUTOFLINE_TEMPLATE QList<T>::~QList() { if (!d->ref.deref()) free(d); } Does this mean that free() is being called on any pointers left in the list when the destructor is called? I have used lists in other places without this problem. Under what circumstances does the destructor call free()? A: To elaborate: destroying a QList will destroy the elements of the list. If the elements are pointers, the pointers themselves are destroyed, not the pointees. You can use qDeleteAll to delete the pointees. (That will use operator delete, which is the right choice if and only if you're using operator new; malloc will always require free and operator new[] will always require operator delete[]). That having been said, returning a QList by value won't destroy it, as its refcount won't drop to 0. Getting a crash there means it's very likely that you have some memory corruption. Use valgrind or similar tools to debug that.
{ "language": "en", "url": "https://stackoverflow.com/questions/17349150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create thrift service We have a some mobile service, google maps based (mobile applications for iOS and Android). So, the server part is a Java application, which accepts connection from clients. In one moment, without me, server was moved (relocated) to another one, and they not moved the Thrift service on the new server. Server works fine, but Android app works only via Apache Thrift. So, the Android developer provided to me the .thrift file. Can I create service with this data? How? What do I need to read? The part of .thrift file: namespace cpp gb65.HelpMeService namespace csharp gb65.HelpMeService namespace java com.gb65.HelpMeService namespace php com.gb65.HelpMeService //Version const i32 SERVICE_API_MAJOR_VERSION = 1; const i32 SERVICE_API_MINOR_VERSION = 0; enum Res { SUCCESS = 0, EMAIL_AND_PASSWORD_NOT_FOUND = 1, EMAIL_NOT_UNIQUE = 2, EMAIL_VALUE_WRONG = 3, CELLPHONE_NOT_UNIQUE = 4, CELLPHONE_VALUE_WRONG = 5, FIRST_NAME_VALUE_WRONG = 6, LAST_NAME_VALUE_WRONG = 7, PASSWORD_VALUE_WRONG = 8, PHOTO_IS_TOO_LARGE = 9, SESSION_NOT_FOUND = 10, TASK_NOT_FOUND = 11, PHOTO_NOT_FOUND = 12, USER_NOT_FOUND = 13, OTHER = 14, MESSAGE_NOT_FOUND = 15, OFFER_NOT_FOUND = 16, ALREADY_FRIENDS = 17, FRIENDSHIP_OFFER_NOT_FOUND = 18, _LAST = 19 } If needed, I can provide all of the .thrift file code. A: Like CORBA, Thrift has developped a neutral language. As shown in this tutorial, you have to compile the .thrift file with thrift -r --gen java YourFile.Thrift After that you have to implement the client calls.
{ "language": "en", "url": "https://stackoverflow.com/questions/30280437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ValueError: Metric 'cosine' not valid. Use sorted(sklearn.neighbors.VALID_METRICS['ball_tree']) I'm trying to use cosine metric with Ball_tree algorithm since my data is of high dimensions. e.g. nbrs = NearestNeighbors(n_neighbors=2,algorithm='ball_tree',metric='cosine').fit(data_seed) However i get the following error: ValueError: Metric 'cosine' not valid. Use sorted(sklearn.neighbors.VALID_METRICS['ball_tree']) to get valid options. Metric can also be a callable function. I don't understand why i cannot use cosine similarity with ball tree? A: check valid matrics sklearn.neighbors.VALID_METRICS['ball_tree']) and use instead of cosine
{ "language": "en", "url": "https://stackoverflow.com/questions/72260849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why the function strlen() returns different values for the same length of two char arrays? #include <stdio.h> #include<string.h> int main() { char a[50],b[50];// same sized arrays for(int j =0;j<50;j++){ b[j]='b';a[j]='a';// initializing with the same number of elements } printf("the size of a is %ld,",strlen(a)); printf("the size of B is %ld",strlen(b)); return 0; } The output is the size of a is 50, the size of B is 54 But what i expect is the size of a is 50 the size of B is 50 what is the problem here? A: what is the problem here? The problem is that you don't terminate your strings. C requires strings to be null terminated: The length of a C string is found by searching for the (first) NUL byte. This can be slow as it takes O(n) (linear time) with respect to the string length. It also means that a string cannot contain a NUL character (there is a NUL in memory, but it is after the last character, not "in" the string). #include <stdio.h> #include<string.h> int main() { char a[50],b[50];// same sized arrays for(int j =0;j<50;j++){ b[j]='b';a[j]='a';// initializing with the same number of elements } // Terminate strings a[49] = b[49] = 0; printf("the size of a is %ld,",strlen(a)); printf("the size of B is %ld",strlen(b)); return 0; } Gives the correct result.
{ "language": "en", "url": "https://stackoverflow.com/questions/61946882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: reuse a widget in GWT I have a label widget and im trying to add this widget to the multiple cells in the flex table but the widget is appearing only in the first cell. Is it possible to reuse a widget in gwt?? how? Label l1=new Label("USER") ; tweetFlexTable.setWidget(0,0,l1); tweetFlexTable.setWidget(0,1,l1); A: Every widget can only have one parent. So you have to create as many widgets as you have cells, like this: Label l1=new Label("USER") ; tweetFlexTable.setWidget(0,0,l1); Label l2=new Label("dunno") ; tweetFlexTable.setWidget(0,1,l2);
{ "language": "en", "url": "https://stackoverflow.com/questions/8133060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: copy the same row from multiple sheets into one sheet in excel I need to copy the same row from multiple sheets into one row. Example: I have an excel file with 5 sheets. I have to copy the 10th row (or the 15th row, or the 21th row) of every sheet in a 6th sheet, in the order of the sheets. Thanks in advance. A: This code will copy 7th row from all first 5 sheets into 6th sheet. Sub row_copy() For i = 1 To Worksheets.Count - 1 Sheets(i).Rows(7).Copy Sheets(6).Cells(i, 1) Next i End Sub A: Here is a sample for 6 sheets and rows # 7: Sub copyrow() Dim Nrow As Long, Nsheet As Long Dim i As Long Nrow = 7 Nsheet = 6 For i = 1 To Nsheet - 1 Sheets(i).Cells(Nrow, 1).EntireRow.Copy Sheets(Nsheet).Cells(i, 1) Next i End Sub The row # 7 from the first 5 sheets will be copied into the 6th sheet.
{ "language": "en", "url": "https://stackoverflow.com/questions/37835442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Reflection to get property from field I have these classes: public class Foo { public Bar bar; } public class Bar { public List<int> Something { get; set; } public string Else { get; set; } } I have a lot of classes like Foo. They all contain exactly one field. This field, Bar in my example, will be a different type of object every time, it doesn't have to be of type Bar. Whatever object it is (Bar or otherwise), this field will always be an object that has two properties, Something and Else. My challenge: given any object that's like Foo (with one Field that holds two properties), get the value of the two properties. Given this method: public void DoStuff(object myObject) { var asdf = myObject.GetType().GetFields().First(); } I can get the FieldInfo for Bar. What I'm looking for is the values of Something and Else. The names of these properties never change. Whatever the type is of the Field, it will always have two properties named Something and Else that will be of the same type. Sadly, my problem involves auto generated code, and there are no shared interfaces or base types I can easily use. A: Using this code you can retrieve the PropertyInfos for the Something and for the Else property: Foo myObject = new Foo { bar = new Bar() }; // the FieldInfo for Foo.bar var barField = myObject.GetType().GetFields().First(); // the Bar instance, i.e. myObject.bar var barValue = barField.GetValue(myObject); var somethingProperty = barField.FieldType.GetProperty("Something", BindingFlags.Instance | BindingFlags.Public); var elseProperty = barField.FieldType.GetProperty("Else", BindingFlags.Instance | BindingFlags.Public); as PsiHamster noted, you can then use GetValue and SetValue to retrieve and set the values of somethingProperty and elseProperty like this: // get the value var somethingValue = somethingProperty.GetValue(barValue); // set the value somethingProperty.SetValue(barValue, new List<int>()); A: //Get Bar FieldInfo var barFieldInfo = myObject.GetType().GetFields().First(); // Get all public instance properties info var barProps = barFieldInfo.FieldType.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); // Get Something and Else properties info var smthPropInfo = barProps.First(prop => prop.Name == nameof(Bar.Something)); var elsePropInfo = barProps.First(prop => prop.Name == nameof(Bar.Else)); // Get values var bar = barFieldInfo.GetValue(myObject); var smth = smthPropInfo.GetValue(bar); var else = elsePropInfo.GetValue(bar);
{ "language": "en", "url": "https://stackoverflow.com/questions/67932888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Transform a function into something that lapply works on properly (lists) I'm trying to make a list with 10 elements, each element consisting of 5 * i items drawn from a uniform distribution, i being the ith entry, and I want to use lapply. Currently I made this function: z_list <- list() z_list_generator <- function(n) { for(i in 1:n){ a <- runif(5 * i) tmp <- list(a) mybiglist[[i]] <- tmp } mybiglist } This function does give the correct outcome when I just put z_list_generator(2), it prints a list with the first element consisting of 5 elements, the second of 10 elements. What I want to achieve is that I do lapply(some number, z_list_generator) such that it generates this same list, and such that when I do length(lapply(some number, z_list_generator)), the outcome is 'some number'. A: Do you mean something like this? z_list_generator <- function(k) lapply(1:k, function(i) runif(5 * i)) set.seed(2018) # Fixed random seed for reproducibility z_list_generator(2) #[[1]] #[1] 0.33615347 0.46372327 0.06058539 0.19743361 0.47431419 # #[[2]] # [1] 0.3010486 0.6067589 0.1300121 0.9586547 0.5468495 0.3956160 0.6645386 # [8] 0.9821123 0.6782154 0.8060278 length(z_list_generator(2)) #[1] 2 A: Your z_list_generator is strange. 1) You do not initialise mybiglist in your function code. It probably modifies some global variable. 2) You assign mybiglist elements with another list (of lenght 1), which first element contains a sample from a uniform distrubution. Better assign a, not tmp there.
{ "language": "en", "url": "https://stackoverflow.com/questions/54723064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: django-tables2: Adding columns/fields dynamically I want to add a new field when somebody checks an option in my web page ("Add column 'external id' ") table = IssueTable(issue_list) show_ext = request.GET.get('show_ext', 0) if show_ext: table._meta.fields = table._meta.fields + ('external_id',) I thought doing that it was the solution but I didn't succeed. The external_id is part of the model. table._meta.fields doesnt get updated and of course I cannot see the column in the table when this one is rendered. class IssueTable(tables.Table): def render_id(self, value, record): if record.status.upper() in ['RESOLVED', 'INVALID']: return mark_safe('<a href="%s"><s>#%s</s></a>' % (reverse('issues.views.view', args=(record.pk,)), record.pk)) else: return mark_safe('<a href="%s">#%s</a>' % (reverse('issues.views.view', args=(record.pk,)), record.pk)) def render_title(self, value, record): return mark_safe('<a href="%s">%s</a>' % (reverse('issues.views.view', args=(record.id,)), value)) class Meta(object): model = Issue fields = ('id', 'title', 'product', 'type', 'priority', 'status', 'created') attrs = {'class': 'table table-bordered'} empty_text = _('No records found') Any ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/32094118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C#, I want to call a method with parameters like var test = new test1.test2.Method("parameter1","parameter2") I want to call a method in a fixed structure like below in C#: var Test = new test1.test2.test3("parameter1","parameter2"); Is this possible in C#? Here test1 and test2 can be classes and test3 is my method name and it will return string text. I can manage if need to remove new keyword. I am assuming it should something like this :- Public class test1 { Public class test2 { Public string test3("parameter1","parameter2") { //Do something } } } A: Yes, you can if test3 is public structure type nested inside public structure type test2 which is nested inside test1 struct test1{ public struct test2{ public struct test3{ public test3(string p1,string p2) {/*do something*/} //some params } //some params //some params } Also test1 and test2 could be namespaces.
{ "language": "en", "url": "https://stackoverflow.com/questions/19494320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to delete all files with certain suffix before file extension I was just handed a directory with some 40,000+ images, and the directory includes three versions of every file, which makes it a bear to have to transfer between servers. I'm looking for a way using bash (OSX Terminal) to find and remove (rm) all files, for example, with _web, or _thumb on the end of the filename, just before the .jpg (or .gif, or .png, or .bmp, etc.) extension. So, to be clear, I have the following files: 1.jpg 1_web.jpg 1_thumb.jpg 2.gif 2_web.gif 2_thumb.gif etc. And I only want "1.jpg", "2.gif", etc. to remain. I've been able to rename extensions in the past, but my command-line-fu is pretty weak, and I'm at my wits end trying to figure out something that's reusable (I'm going to need to do this a couple times, as I'm working on a continuous migration script for this project). Edit: After a bit more work on this, I found a few odd limitations of rm and xargs that I had to work around. I basically adapted the accepted answer below and ended up with: $ find . -name '*_thumb.*' -print0 | xargs -0 rm -f $ find . -name '*_web.*' -print0 | xargs -0 rm -f Now I'm down to about 10,000 files - quite a savings in terms of pushing files around on the web! A: One (relatively robust) option is to run find . -iregex ".*\(_web\|_thumb\)\.\(jpg\|png\|bmp\)" -delete Assuming that you don't have anything other than image files in the directory, another (simpler) option is to run rm *_web.* *_thumb.* Warning: this will also delete files that are named something like my_web.file.jpg, so if you want to play safe, you'll have to add all the extensions instead of relying on .* If you know that your extensions are always going to be 3 characters long, you can use something like *_thumb.??? A: I don't have a MAC or a UNIX terminal in front of me, but I imagine something like the following might work rm *_web.jpg rm *_web.jpg rm *_thumb.gif
{ "language": "en", "url": "https://stackoverflow.com/questions/6839966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Update jquery scrollbar after ng-repeat render Scrollbar don't see height of div because scrollbar update apply before child elements render. How i can watch what elements is compiled? I used watch to see when object adding to array. It works fine, but tinyscrollab_update sees empty div, because ng-repeat no compiled yet. $scope.$watch('comments', function(){ angular.element('#comment-list').tinyscrollbar_update('relative'); }); A: I write it in directive. app.directive('commentsDirective', function(){ $scope.$watch('comments', function(){ angular.element('#comment-list').tinyscrollbar_update('relative'); }); })
{ "language": "en", "url": "https://stackoverflow.com/questions/15309094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CasperJS click() doesn't load new html I'm trying to use CasperJS' click() to follow a link which generates a modal on the current screen. When I query the proper selector and click it in the browser console using document.querySelector().click() it works, but even when I casper.evaluate() this it doesn't work. I found someone who had a very similar problem, but his question remains unanswered, and I am experiencing almost identical problems. casperjs button click doesn't navigate to next page the code I'm currently using is this.waitForSelector('div.talk-sharing__tools a.rate-button', function() { this.then(function() { this.evaluate(function() { document.querySelector('a.rate-button').click(); }); the page I'm trying to scrape is http://www.ted.com/talks/uri_alon_why_truly_innovative_science_demands_a_leap_into_the_unknown A: It is really impossible to do those navigation steps with the phantomjs engine. It seems that the QtWebkit fork of phantom (version 1.9.7) is not up to the task anymore. Although your code works fine as is with slimerjs. You can comfortably install slimerjs through npm: npm install -g slimerjs and run your script with casperjs --engine=slimerjs script.js I tried several things with phantomjs that did not work. I added casper.on listeners for remote.message and resource.error, but those didn't show any errors when running the script in phantom. logLevel: "debug" also didn't show anything. First: Using a casperjs function. casper.thenClick("div.talk-sharing__tools a.rate-button"); Second: Trying to explicitly show the modal for the button (specific to the page). casper.then(function(){ var name = this.evaluate(function(){ var modal = document.querySelectorAll(".modal-wrapper > .modal")[0]; modal.className += " modal--show"; return modal.className; }); this.echo("name: "+name); // null }); casper.waitUntilVisible(".modal__head__title"); Third: Let jQuery do the work. var casper = require('casper').create({ remoteScripts: [ "http://code.jquery.com/jquery-1.11.1.min.js" ] }); casper.waitForSelector(selector, function() { this.evaluate(function() { jQuery("a.rate-button").click(); }); }); A: Encountered similar issue today. After executing this.click() on start page (which I verified that PhantomJS is executing - by hooking into resource.requested and resource.received events), current page remained on start page (and it should go to clicked link page). Solution was to update to the latest PhantomJS (1.9.8 at this moment). Please note that I had PhantomJS 1.9.7 when the above described problem occurred.
{ "language": "en", "url": "https://stackoverflow.com/questions/24197587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Getting binary data directly off the windows clipboard I've been beating my head against the desk for about an hour now just trying to find some way of getting say... an array of bytes off the clipboard. Instead, all I can seem to find is information on how to get plain text from the clipboard... that's not helpful at all. I've tried following this: Java getting bytes of clipboard I've also tried following this: http://mrbool.com/manipulating-clipboard-content-with-java/24758 Every time I run into the silly DataFlavor being "unsupported". Surely there's just something simple that I'm missing here... I mean... how can it support plain text, images, and java objects, but NOT have the basic functionality that just has to be under the hood of all this? Sorry if I sound sarcastic and pissed off here... Java seems to have that effect on me. :( A: Awt Clipboard and MIME types InsideClipboard shows that the content's MIME type is application/spark editor You should be able to create a MIME type DataFlavor by using the constructor DataFlavor(String mimeType, String humanReadableFormat) in which case the class representation will be an InputStream from which you can extract bytes in a classic manner... However, this clipboard implementation is very strict on the mime type definition and you cannot use spaces in the format id, which is too bad because your editor seems to put a space there :( Possible solution, if you have access to JavaFX JavaFX's clipboard management is more lenient and tolerates various "Format Names" (as InsideClipboard calls them) in the clipboard, not just no-space type/subtype mime formats like in awt. For example, using LibreOffice Draw 4.2 and copying a Rectangle shape, awt only sees a application/x-java-rawimage format whereas JavaFX sees all the same formats as InsideClipboard : [application/x-java-rawimage], [PNG], [Star Object Descriptor (XML)], [cf3], [Windows Bitmap], [GDIMetaFile], [cf17], [Star Embed Source (XML)], [Drawing Format] You can then get the raw data from the JavaFX clipboard in a java.nio.ByteBuffer //with awt DataFlavor[] availableDataFlavors = Toolkit.getDefaultToolkit().getSystemClipboard().getAvailableDataFlavors(); System.out.println("Awt detected flavors : "+availableDataFlavors.length); for (DataFlavor f : availableDataFlavors) { System.out.println(f); } //with JavaFX (called from JavaFX thread, eg start method in a javaFX Application Set<DataFormat> contentTypes = Clipboard.getSystemClipboard().getContentTypes(); System.out.println("JavaFX detected flavors : " + contentTypes.size()); for (DataFormat s : contentTypes) { System.out.println(s); } //let's attempt to extract bytes from the clipboard containing data from the game editor // (note : some types will be automatically mapped to Java classes, and unknown types to a ByteBuffer) // another reproducable example is type "Drawing Format" with a Rectangle shape copied from LibreOffice Draw 4.2 DataFormat df = DataFormat.lookupMimeType("application/spark editor"); if (df != null) { Object content = Clipboard.getSystemClipboard().getContent(df); if (content instanceof ByteBuffer) { ByteBuffer buffer = (ByteBuffer) content; System.err.println(new String(buffer.array(), "UTF-8")); } else System.err.println(content); }
{ "language": "en", "url": "https://stackoverflow.com/questions/24844971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Migration from SherlockActionBar to ActionBar I just migrate to native actionBar, before, with ABS it was working great. Now, I don't need anymore compatibility as I develop for API 16+ I changed all references, and now, my menu only shows in text, with physic button, it doesn't show up in action bar... I don't know what am I missing... Here is my code : main.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" > <item android:id="@+id/menu_sync" android:icon="@drawable/ic_action_update" android:orderInCategory="80" android:showAsAction="ifRoom" android:title="Sync"/> <item android:id="@+id/more" android:icon="@drawable/ic_action_core_overflow" android:orderInCategory="90" android:showAsAction="always" android:title="See more options"> <menu> <item android:id="@+id/menu_send_coords" android:icon="@drawable/ic_action_send_coords" android:orderInCategory="80" android:showAsAction="ifRoom" android:title="Send Coords" android:visible="true"/> <item android:id="@+id/menu_foto" android:icon="@drawable/ic_action_device_access_camera" android:orderInCategory="100" android:showAsAction="ifRoom" android:title="Foto" android:visible="true"/> </menu> </item> In my Activity : public class DashBoard extends BaseActivity { //BaseActivity extends ActionBarActivity ... @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } I tried to change the menu xml to another one ( google example), but it did not work. I made a search fro any reference to Sherlock* and replace all of them In my manifest I have : <application ... android:theme="@style/Theme.AppCompat" > In my style.xml I have : <style name="AppBaseTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar"> <!-- nothing API level dependent yet --> </style> <!-- Application theme. --> <style name="AppTheme" parent="AppBaseTheme"> <!-- All customizations that are NOT specific to a particular API-level can go here. --> </style> I've followed each step of : http://www.grokkingandroid.com/migrating-actionbarsherlock-actionbarcompat/ What are the common issues when migrating from ActionBarSherlock to ActionBarCompat? ActionBarCompat menu item is not showing I don't know what more can I do??? Any help would be appreciated ! A: I think you should change your style.xml and your Android Theme since you don't ne the Android appcompat libarary anymore. styles.xml: <style name="AppBaseTheme" parent="@style/Theme.Holo.Light.DarkActionBar"> <!-- nothing API level dependent yet --> </style> <!-- Application theme. --> <style name="AppTheme" parent="AppBaseTheme"> <!-- All customizations that are NOT specific to a particular API-level can go here. --> </style> AndroidManifest.xml: <application android:theme="@style/AppTheme" ...
{ "language": "en", "url": "https://stackoverflow.com/questions/24336739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how can i add a timeout function to javascript? $('.btn').click(function() { $(this).toggleClass('spinner'); }); and i want to add a timeout function to it i added it like this but it does not work, any ideas why? $('.btn').click(function() { $(this).toggleClass('spinner'); setTimeout(function() { $this.button('reset'); }, 8000); });
{ "language": "en", "url": "https://stackoverflow.com/questions/50540136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error installing mariadb-server mariadb-client on Chromebook I'm trying install wordpress locally on my chromebook following these instructions. I successfully ran: ` sudo apt update sudo apt upgrade sudo apt install nano ` But then get an error when I try to run ` sudo apt install mariadb-server mariadb-client -y ` Here's the error from my terminal: ` Reading package lists... Done Building dependency tree... Done Reading state information... Done Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: libdbi-perl : Depends: perlapi-5.32.0 E: Unable to correct problems, you have held broken packages. ` I'm a complete newb at Linux and spend hours googling / trying solutions to no avail. Any help is appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/74903871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: undefined method `stringify_keys' for "/users/sign_out":String (Devise gem) In my project i am using devise gem .And also using link_to_if url helper because when users not isn't signed in , it will provide new_user_session_path and also when they signed in it will provide destroy_user_session_path. For this at first I tried this code: <%= link_to_if(current_user.nil?, "Sign in", new_user_session_path) do link_to(user_signed_in?, "Sign out", destroy_user_session_path, method: :delete ) end %> its says "wrong number of arguments (4 for 3)" Then I tried this code: <%= link_to_if(current_user.nil?, "Sign in", new_user_session_path) do link_to(user_signed_in?, "Sign out", destroy_user_session_path) end %> its says "undefined method `stringify_keys' for "/users/sign_out":String" Please help me out of this. A: You're using a condition in your link_to call, just remove the first argument like this :). link_to("Sign out", destroy_user_session_path)
{ "language": "en", "url": "https://stackoverflow.com/questions/25731905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: localstorage not defined ionic 2 i'm trying to import "local storage" from 'ionic-angular' and it says me "LocalStorage is not defined".. in addtion I got this error RangeError: Maximum call stack size exceeded at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:153:20) at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18) at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18) at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18) at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18) at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18) at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18) at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18) at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18) at deepClone (C:\Users\Adir\MyApps\ToDoApp\node_modules\rollup\dist\rollup.js:165:18) first time I got these error on this morning. yesterday I worked fine with another ionic 2 project. by the way, that's my code import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import {Storage,LocalStorage} from 'ionic-angular'; /* Generated class for the Admin page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-admin', templateUrl: 'admin.html' }) export class AdminPage { data: any; public local: Storage; public getsession:any; constructor(public navCtrl: NavController) { this.data={}; this.data.title=""; this.data.desc=""; this.local=new Storage(LocalStorage); this.local.set('session','true'); this.getsession=this.local.get('session'); this.getsession.then((value)=>{ let x=value; console.log(x); }) } ionViewDidLoad() { } } A: The ionic storage has moved to '@ionic/storage' as of rc.0 so import { Storage } from '@ionic/storage'; You can't specify whether its localstorage/sql or anything. But it uses each in order until its able to use one. Just create an instance and use it new Storage().set("key","value"); A: Old Question... but it just came up in my Google Results: import { Storage } from '@ionic/storage'; Current as of RC4
{ "language": "en", "url": "https://stackoverflow.com/questions/39767816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTTP Post by android always return result 0 i supposed to send http post to web service in the form POST[messageTitle, messageContent, messageFrom] it's like array with the name post i searched around and some people said i should do : nameValuePairs.add(new BasicNameValuePair("POST[]", messageTitle.getText().toString())); nameValuePairs.add(new BasicNameValuePair("POST[]", messageContent.getId())); nameValuePairs.add(new BasicNameValuePair("POST[]", messageFrom.getText().toString())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request try { HttpResponse response = httpclient.execute(httppost); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader( new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } } else { Log.e("JSON", "Failed to download file"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { // TODO Auto-generated catch block } Log.d("Cat", stringBuilder.toString()); } but it returned {"result":0} and supposed to return {"result":"row"}
{ "language": "en", "url": "https://stackoverflow.com/questions/19963389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change the existing html text in a D3 rect? How to change the existing html text in a D3 rect to something else on the click of a button. There is an image on the top right corner of a D3 rect. When I click on that image the text inside the rect has to change to another html text like This is new text . It would be great if anyone could help me figure out a way to do it. <!DOCTYPE html> <html> <head> <!-- <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js" ></script> --> <script src="https://d3js.org/d3.v6.min.js"></script> </head> <body> <script> function wrap(text, width) { text.each(function () { var text = d3.select(this), words = text.text().split(/\s+/).reverse(), word, line = [], lineNumber = 0, lineHeight = 1.1, // ems y = text.attr('y'), x = text.attr('x') dy = parseFloat(text.attr('dy')), tspan = text .text(null) .append('tspan') .attr('x', x) .attr('y', y) .attr('dy', dy + 'em'); while ((word = words.pop())) { line.push(word); tspan.text(line.join(' ')); if (tspan.node().getComputedTextLength() > width) { line.pop(); tspan.text(line.join(' ')); line = [word]; tspan = text .append('tspan') .attr('x', x) .attr('y', y) .attr('dy', ++lineNumber * lineHeight + dy + 'em') .text(word); } } }); } var svg = d3 .select('body') .append('svg') .attr('width', 500) .attr('height', 5000); // var longText = // 'This is very very long text. This is very very long text. This is very very long text. This is very very long text. This is very very long text. This is very very long text.'; var longText = '<span>This is very very long textThis is very very long textThis is very very long textThis is very very long text</span>'; var totHeight = 0; drawRect(); function drawRect() { //var someWidth = randomIntFromInterval(40, 300); var someWidth = 212; var g = svg .append('g') .attr('transform', 'translate(20,' + totHeight + ')'); var rect = g .append('rect') .style('fill', 'steelblue') .attr('x', 50) .attr('y', 50) .attr('width', someWidth) .attr('height', 1); var txt = g .append('text') .html(longText) .attr('x', 70) .attr('y', 70) .attr('dy', '.71em') .style('fill', 'black') .call(wrap, someWidth - 28); var img = g.append('svg:image') .attr('x', 250) .attr('y', 40) .attr('width', 24) .attr('height', 24) .attr( 'xlink:href', './img/edit-24-px.svg' ); img.on('click', function () { //d3.append('text').html("<span> bye </span>"); console.log('hi'); }); var height = txt.node().getBBox().height + 25; totHeight += height + 10; rect.attr('height', height); } </script> </body> </html> https://jsfiddle.net/passionateCoder/prh2acot/ I am not able to add an image to the JSFiddle. A: This should work. img.on('click', function () { txt.text('this is new text') }); Or for innerHTML: img.on('click', function () { txt.html('this is new text') }); Remember that you cannot use traditional HTML in SVG Texts. Read here: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/text
{ "language": "en", "url": "https://stackoverflow.com/questions/64447776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run on the page typed js I'm currently working on a project which requires me to run by the user typed javascript in the form of a string. I've tried adding an empty <script> tag to the html and appending the string (containing the users freshly typed (after the page was loaded) javascript) to this script tag but this doesn't work. (since the code inside the script tag will be run immediately after the page is loaded). So I tried a different approach. I wrapped the js string inside of a function like so: function runCode() { userString } This is what the string I now append to the empty script tag looks like: var code = "function runCode() { "+ userString +" }" However this still doesn't work. The code (userString) shows up in the script tag according to the chrome dev tools, but trying to run the function causes the following error: Uncaught ReferenceError: runCode is not defined Does somebody know how this works? What is the proper way for me to do this? Some background: The project I'm working on is an online tool to draw using js. The goal here is to use the two.js library and link it to a modified textarea. (codemirror) Clicking the button will take your typed in code and use it to modify the two.js canvas on the other half of the screen. This will make it easier to draw using the library, since you don't have to set up all the html, css and js files yourself, but instead you can focus on the code. Note: The js you type into the textarea can by any valid js, so simple things as alerts, or even jQuery lines will work just fine. A: Use eval() function. However be aware that this is by design a HUGE hole of security. A: You have to use eval(). Extract the user input from an onclick event and pass it into eval like so: eval(userString)
{ "language": "en", "url": "https://stackoverflow.com/questions/39265535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get the real error message in HttpClient response.ReasonPhrase? My Setting I have 2 WebApi projects with the following flow: * *User makes request to API 1 *API 1 makes request to API 2 on behalf of the user (using an HttpClient). using (var client = new HttpClient()) { client.SetBearerToken(token); string endpoint = PbbSettings.Identity.Users.Delete.Replace("{userId}", userId); // Attempt deletion of the user using (var response = await client.DeleteAsync(endpoint)) { // Throw exception if not succeeded EnsureSuccess(response); } } The Problem So the flow of control and information works fine. The problem is that when API 2 responds with an error, response.ReasonPhrase says "Bad Request" or "Internal Server Error", instead of the message I set in the exception. Been spitting blood on this for a whole day now. Any insights? More Info (TLDR) For clarity, all my APIs have a global exception filter registered to handle errors: public class RepositoryExceptionsHandlerAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { HandleException(context); base.OnException(context); } public override Task OnExceptionAsync(HttpActionExecutedContext context, CancellationToken cancellationToken) { HandleException(context); return base.OnExceptionAsync(context, cancellationToken); } /// <summary> /// Recognizes common repository exceptions and if necessary creates a response and updates the context. /// </summary> /// <param name="context">The context in which the exception was thrown.</param> private void HandleException(HttpActionExecutedContext context) { var response = CreateResponse(context.Request, context.Exception); if (response != null) context.Response = response; } /// <summary> /// Recognizes common repository exceptions and creates a corresponding error response. /// </summary> /// <param name="request">The request to which the response should be created.</param> /// <param name="ex">The exception to handle.</param> /// <returns>An error response containing the status code and exception data, or null if this is not a common exception.</returns> private HttpResponseMessage CreateResponse(HttpRequestMessage request, Exception ex) { string message = ex.Message; if (ex is KeyNotFoundException) return request.CreateErrorResponse(HttpStatusCode.NotFound, message); if (ex is ArgumentException) return request.CreateErrorResponse(HttpStatusCode.BadRequest, message); if (ex is InvalidOperationException) return request.CreateErrorResponse(HttpStatusCode.BadRequest, message); if (ex is UnauthorizedAccessException) return request.CreateErrorResponse(HttpStatusCode.Unauthorized, message); #if !DEBUG // For security reasons, when an exception is not handled the system should return a general error, not exposing the real error information // In development time, the programmer will need the details of the error, so this general message is disabled. request.CreateErrorResponse(HttpStatusCode.InternalServerError, Errors.InternalServerError); #endif return null; } } This works fine between the user and API 1. But when API 1 and API 2 do their thing, the response creation ignores the message I put in and sets the status as the reason. A: The new CreateResponse() method: /// <summary> /// Recognizes common repository exceptions and creates a corresponding error response. /// </summary> /// <param name="request">The request to which the response should be created.</param> /// <param name="ex">The exception to handle.</param> /// <returns>An error response containing the status code and exception data, or null if this is not a common exception.</returns> private HttpResponseMessage CreateResponse(HttpRequestMessage request, Exception ex) { string message = ex.Message; HttpStatusCode code = 0; if (ex is KeyNotFoundException) code = HttpStatusCode.NotFound; else if (ex is ArgumentException) code = HttpStatusCode.BadRequest; else if (ex is InvalidOperationException) code = HttpStatusCode.BadRequest; else if (ex is UnauthorizedAccessException) code = HttpStatusCode.Unauthorized; else if (ex is HttpException) { // HttpExceptions are thrown when request between IdentityServer and the API server have failed. // IdentityServer has generated an error, the API server received it and now it needs to relay it back to the client. var httpException = (HttpException) ex; code = (HttpStatusCode) httpException.GetHttpCode(); message = httpException.Message; } else { code = HttpStatusCode.InternalServerError; // For security reasons, when an exception is not handled the system should return a general error, not exposing the real error information // In development time, the programmer will need the details of the error, so this general message is disabled. #if DEBUG message = ex.Message; #else message = Errors.InternalServerError; #endif } // For some reason the request.CreateErrorResponse() method ignores the message given to it and parses its own message. // The error response is constructed manually. return CreateErrorResponse(request, code, message); } private HttpResponseMessage CreateErrorResponse(HttpRequestMessage request, HttpStatusCode code, string message) { var content = new { Message = message }; return new HttpResponseMessage(code) { ReasonPhrase = message, RequestMessage = request, Content = new ObjectContent(content.GetType(), content, new JsonMediaTypeFormatter()) }; } } Hope this just saved someone's day... ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/40136132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: error: could not find or load main class First.class I have made program in java using netbeans. it is located in d:\sudhanshu\documents\netbeansprojects\Firstapp\src\firstapp. its name is First.java. it is running successfully and showing output in netbeans IDE. but when i m trying to run it through cmd its showing the above error. PATH is set to c:\program files\java\jdk1.7.0_07\bin classpath is set to . i have also tried setting classpath to c:\program files\java\jdk1.7.0_07\bin but there was no change in the error.. javac First.java is running and CLASS file is getting created in the same folder where the program is. please help me out.. i cannot debug it.. A: Most probably you are missing execution using package name. You would be executing main class from src directory as : D:\sudhanshu\documents\netbeansprojects\Firstapp\src> java firstapp.First A: If your package is : somepackage, And you have saved your .java file at: d:\sudhanshu\documents\netbeansprojects\Firstapp\src\firstapp then in command prompt, go to the above directory and compile using: - javac -d . First.java // Don't use javac First.java Then your class file will be created inside the folder somepackage inside the above path.. i.e. your class file will be at d:\sudhanshu\documents\netbeansprojects\Firstapp\src\firstapp\somepackage\First.class Then you should go at the directory where your .java. file is saved, and run as: - java First From d:\sudhanshu\documents\netbeansprojects\Firstapp\src\firstapp directory.. If you want to run this class file from anywhere: - Add d:\sudhanshu\documents\netbeansprojects\Firstapp\src\firstapp directory in your classpath.. Note: - You need to add the directory containing your package directory to classpath.. A: - If you are able to create a .class file then i think you have successfully installed your Java Tip: Always do a java -version on the command prompt, and if it returns with the version of JDK installed on your system, then you have successfully installed your Java. - Now i will advice you to do this from the same directory where you class file is located to execute the file. java First
{ "language": "en", "url": "https://stackoverflow.com/questions/12759313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Character encoding for US Census Cartographic Boundary Files I'm trying to import the US Census cartographic boundary files (available here: http://www.census.gov/geo/www/cob/bdy_files.html ) into a GeoDjango application. However, python is complaining about UnicodeDecodeErrors (for example, for the non-ascii characters in Puerto Rico). The shapefile description file (*.dbf) doesn't specify what character encoding it uses; this is not defined by the spec for shapefiles. What is the correct character encoding to use? A: I was having the same issue with CBSA and Place data from 2010 Census full geometry shapes. These are not the clipped carto files. IBM850 Did not work correctly for me. On a whim, I tried latin1 and it worked perfectly. A: The US Census cartographic boundary files use the IBM850 character encoding. Python code to properly encode these strings would be as follows: unicode(featurestring.decode("IBM850"))
{ "language": "en", "url": "https://stackoverflow.com/questions/2477360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Force Chromewebdriver to download text,jpg instead of opening in a new tab I have a need to download txt and jpg files that are basically links in a web page. I am using chrome webdriver to do the same. My code to set the chrome settings is as below: prefs = { :download => {:prompt_for_download => false,:default_directory => download_directory} , :managed_default_content_settings => {:images => 2 }, :webprefs => {:loads_images_automatically => 'false' } } @browser = Watir::Browser.new :chrome , :prefs => prefs When I click on these links, I the files opens in a new window instead of a download prompt. Is there a way to force chrome webdriver NOT to open these automatically?
{ "language": "en", "url": "https://stackoverflow.com/questions/25171261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ajax call fails in IE with requests from HTTPS to HTTP I'm making a trivial ajax CORS request from HTTPS to HTTP, and it's working fine on every browser, except IE. It's not even trying to make a request and fails immediately. There is no error messages in console. This fails even without trying (there is no network traffic), then executed from secure site: $.ajax({ url:'http://foo.bar' }).done(function() { alert('success'); }).fail(function() { alert('fail'); }); I'm using IE 10 in Standards Mode. Is there any way to make it work with HTTP? It's obvious it blocks unsecure request from secure site, but maybe it's possible to change this using browser settings? A: Unfortunatelly there seems to be no solution for this. Your best alternative option (for quick solution) is to implement HTTPS (directly or as a proxy for external HTTP-only service) using self-signed certificate and add it to exception list.
{ "language": "en", "url": "https://stackoverflow.com/questions/21876122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting undefined when using "var" instead of "let" with Object.assign() var name = { nameValue: 'John' }; console.log(name.nameValue); // undefined var surname = { surnameValue: 'Doe' }; Object.assign(name, surname); console.log(name.surnameValue); // undefined I am getting undefined when using var but everything is working good with let and I am running this code on jsbin.com A: Global scope (i.e. window in this case) already has a property name. You'll need to either create a new scope by wrapping your code with a function. Or use block scoped variable declaration let console.log(typeof name); // string var name = { nameValue: 'John' }; console.log(name.nameValue); // undefined var surname = { surnameValue: 'Doe' }; Object.assign(name, surname); console.log(name.surnameValue); // undefined function run() { var name = { nameValue: 'John' }; console.log(name.nameValue); // John var surname = { surnameValue: 'Doe' }; Object.assign(name, surname); console.log(name.surnameValue); // Doe } run(); A: Because 'name' is existed in window, you can use other name of variable var name0 = { nameValue: 'John' }; console.log(name0.nameValue); A: (Window.)name is a specific value of the global window object that can be used (but pretty uncommon) for setting forms and hyperlinks targets. The name property is not read only but is limited to the primitive type string. Therefore, any value that you assign to window.name will turn into a string. This is essentially why you got undefined when used name.nameValue. name is not an object. var name = { hello: "world!" }; console.log(name + ' - ' + name.hello); // "[object Object] - undefined" var name = "Hello World!" console.log(name); // "Hello World!"; A: You are setting the variable name in the global scope in window object. When you set the value of name in window object, its get method will call the toString method. As specified in here var name = {first:"Vignesh"}; console.log(name); //(1) console.log(name.first); //(2) (1) will give the value [object Object] as string instead of {first: "Vignesh"}. (2) depicts that you are accessing an unassigned property of a string. i.e., [object Object].first which becomes undefined. You have to declare the name object in some other scope like if...else block, function block to achieve what you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/48316036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: No ads error from adcontrol I'm checking out ads in a Windows Phone app for the first time. When I tried with the test settings, the test app showed up. When I replace the info by the applicationID and AdUnitId from PubCenter, nothing at all appeared (when debugging on a device). I suscribed to the erroroccured event: private void AdControlInBorder_ErrorOccurred(object sender, Microsoft.Advertising.AdErrorEventArgs e) { MessageBox.Show(e.Error.Message.ToString()); } And I get: "No ad available". This is about a second after the app started up. Extra info: I'm in Belgium, checked it with the phone plugged to pc, unplugged, I'm on wifi and I have internet available. A: AdDUplex is just for promote your app not for gain money :) In your case, you can't have ads in debug mode. Send your app in beta test and look if ads is available. Pub center have the best fill rate in wp8 platform. But you need to choice your app usage. If you app is a type like rss flow or news you need ads because you will have a lot of users connected for a long time and frequently. If you app is a productivity app, you will add in app purchase or send your app like a paid app or donation. Don't forget if you add ads, the possibility to remove.
{ "language": "en", "url": "https://stackoverflow.com/questions/22590169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Infinispan file system store plus sql database I am trying to use infinispan to achieve the following: - n JVM instances in cluster - All data replicated between one node and the remaining nodes - Data to be backed up by the filesystem to that the node can recover from the local file store - I want some specific data to be persisted in the database (sql) asynchronously, but first to be written on the filesystem synchronously and once the transaction has been committed – then trigger the asynchronous persistence to the sql database What is unclear from the documentation, it seems I will have to do everything myself – and infinispan just gives me jgroups clustering It is unclear also how to remove data from the file store once the sql persistence successfully takes place – within an “atomic” transaction. So data replication aside, I must be able to: * *Store data to the local cache (in-memory and file-system) *Recover from the local cache (if the JVM crashes) and/or remote caches *For some data, add to the cache, then FS, then asynchronously persist and remove from the FS It seems that I can do all of this obviously, but Infinispan vs. me using jgroups and do it myself? A: Infinispan allows you to chain cache stores together (by defining multiple stores within the persistence XML section), and each can be configured to either be synchronous or asynchronous (see here). However, transactional persistence stores are not supported (see here)
{ "language": "en", "url": "https://stackoverflow.com/questions/34131139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Transforming OLTP Relational Database to Data Warehousing Model What are the common design approaches taken in loading data from a typical Entity-Relationship OLTP database model into a Kimball star schema Data Warehouse/Marts model? * *Do you use a staging area to perform the transformation and then load into the warehouse? *How do you link data between the warehouse and the OLTP database? *Where/How do you manage the transformation process - in the database as sprocs, dts/ssis packages, or SQL from application code? A: Personally, I tend to work as follows: * *Design the data warehouse first. In particular, design the tables that are needed as part of the DW, ignoring any staging tables. *Design the ETL, using SSIS, but sometimes with SSIS calling stored procedures in the involved databases. *If any staging tables are required as part of the ETL, fine, but at the same time make sure they get cleaned up. A staging table used only as part of a single series of ETL steps should be truncated after those steps are completed, with or without success. *I have the SSIS packages refer to the OLTP database at least to pull data into the staging tables. Depending on the situation, they may process the OLTP tables directly into the data warehouse. All such queries are performed WITH(NOLOCK). *Document, Document, Document. Make it clear what inputs are used by each package, and where the output goes. Make sure to document the criteria by which the input are selected (last 24 hours? since last success? new identity values? all rows?) This has worked well for me, though I admit I haven't done many of these projects, nor any really large ones. A: I'm currently working on a small/mid size dataware house. We're adopting some of the concepts that Kimball puts forward, i.e. the star scheme with fact and dimension tables. We structure it so that facts only join to dimensions (not fact to fact or dimension to dimension - but this is our choice, not saying it's the way it should be done), so we flatten all dimension joins to the fact table. We use SSIS to move the data from the production DB -> source DB -> staging DB -> reporting DB (we probably could have have used less DBs, but that's the way it's fallen). SSIS is really nice as it's lets you structure your data flows very logically. We use a combination of SSIS components and stored procs, where one nice feature of SSIS is the ability to provide SQL commands as a transform between a source/destination data-flow. This means we can call stored procs on every row if we want, which can be useful (albeit a bit slower). We're also using a new SQL Server 2008 feature called change data capture (CDC) which allows you to audit all changes on a table (you can specify which columns you want to look at in those tables), so we use that on the production DB to tell what has changed so we can move just those records across to the source DB for processing. A: I agree with the highly rated answer but thought I'd add the following: * Do you use a staging area to perform the transformation and then load into the warehouse? It depends on the type of transformation whether it will require staging. Staging offers benefits of breaking the ETL into more manageable chunks, but also provides a working area that allows manipulations to take place on the data without affecting the warehouse. It can help to have (at least) some dimension lookups in a staging area which store the keys from the OLTP system and the key of the latest dim record, to use as a lookup when loading your fact records. The transformation happens in the ETL process itself, but it may or may not require some staging to help it along the way. * How do you link data between the warehouse and the OLTP database? It is useful to load the business keys (or actual primary keys if available) into the data warehouse as a reference back to the OLTP system. Also, auditing in the DW process should record the lineage of each bit of data by recording the load process that has loaded it. * Where/How do you manage the transformation process - in the database as sprocs, dts/ssis packages, or SQL from application code? This would typically be in SSIS packages, but often it is more performant to transform in the source query. Unfortunately this makes the source query quite complicated to understand and therefore maintain, so if performance is not an issue then transforming in the SSIS code is best. When you do this, this is another reason for having a staging area as then you can make more joins in the source query between different tables. A: John Saunders' process explanation is a good. If you are looking to implement a Datawarehouse project in SQL Server you will find all the information you require for the delivering the entire project within the excellent text "The Microsoft Data Warehouse Toolkit". Funilly enough, one of the authors is Ralph Kimball :-) A: You may want to take a look at Data Vault Modeling. It claims solving some loner term issues like changing attributes.
{ "language": "en", "url": "https://stackoverflow.com/questions/868247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Using Custom Font - Failed to decode downloaded font in Oracle Apex I'm trying to use some customized font in my application. So i tried downloading Pacifico and trying to use in my application. But getting Failed to decode downloaded font and the font is not loading Below is my CSS . @font-face { font-family: 'MyWebFont'; src: url('#WORKSPACE_IMAGES#Pacifico.ttf') format('ttf'); } body { font-family: 'MyWebFont', sans-serif; font-weight: 300; line-height: 25px; font-size: 14px; } This is not working. So i tried converting this to .woff as per suggestions found in web and tried below. Even this is failing. I'm using Chrome 74.0 version . How to solve this? @font-face { font-family: 'MyWebFont'; src: url('#WORKSPACE_IMAGES#Pacifico.ttf') format('ttf'), url('#WORKSPACE_IMAGES#Pacifico.woff') format('woff'), url('#WORKSPACE_IMAGES#Pacifico.woff2') format('woff2'); } body { font-family: 'MyWebFont', sans-serif; font-weight: 300; line-height: 25px; font-size: 14px; } A: Problem here is you need upload the font into /i/ @font-face { font-family: "Pacifico"; src: url("http://localhost:8080/i/Pacifico.ttf"); } body { font-family: "Pacifico", serif; font-weight: 300 !important; line-height: 25px !important; font-size: 14px !important; } I don't know why Apex is not resolving the #WORKSPACE_IMAGES# but you can upload the font in the web server. In my case I'm using tomcat
{ "language": "en", "url": "https://stackoverflow.com/questions/56374987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: usort Date Assistance I am trying, unsuccessfully, to sort my list by one of my template fields ($fields[3]) which is a text input field with a date inside it. The problem is that because of the format of the date it will not sort correctly because I guess it is just comparing numbers. I think I need to change the dateformat before sorting occurs but have so far failed to do this. I am trying to use the usort function like so (field 3 is the one with the date in which is formatted like this dd/mm/yyyy), if (!function_exists('do_sort')) { function do_sort($a, $b) { return $a->fields[3] > $b->fields[3]; }} $data = $params['data']; usort($data, 'do_sort'); $smarty->assign('sorted', $data); This sorts the data but as before, because I haven't changed anything, not in the correct order. Can anyone help me reformat the date prior to sorting? Many thanks Chris A: Managed to do it. If anyone else is interested I used the following function: function date_compare($a, $b) { $t1 = strtotime($a->fields[3]); $t2 = strtotime($b->fields[3]); return $t1 - $t2; } $data = $params['data']; usort($data, 'date_compare'); $smarty->assign('sorted', $data); A: Try converting the strings to timestamps first: function do_sort($a, $b) { $aval = strtotime($a); $bval = strtotime($b); if ($aval == $bval) { return 0; } return $aval < $bval ? -1 : 1; }
{ "language": "en", "url": "https://stackoverflow.com/questions/11583822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }