text
stringlengths
15
59.8k
meta
dict
Q: Inserting Events to google calendar from a script Anyone know the proper way to authenticate and publish directly to a calendar without relying on a currently logged in user? Several weeks ago I built a calendar that used the standard Oauth 2.0 protocol but this relied sessions stored by a user's we browser. I have one calendar that I want to pass events to from an application I am writing with a basic PHP framework. I'm more concerned with what are the best practices that others are using. Your answer could be simply, don't do it. Thanks alot. A: try Zend_Gdata_Calendar with this library you are able to insert or get events from any user(with the right username and password obviously) from google calendar and integrate with your own calendar or display it..here a short example: $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; $client = Zend_Gdata_ClientLogin::getHttpClient('gmail@user.com', 'gmailpassword', $service); $service = new Zend_Gdata_Calendar($client); $query = $service->newEventQuery(); $query->setUser('default'); $query->setVisibility('private'); try { $eventFeed = $service->getCalendarEventFeed($query); } catch (Zend_Gdata_App_Exception $e) { echo "Error: " . $e->getMessage(); } echo "<ul>"; foreach ($eventFeed as $event) { echo "<li>" . $event->title . " (Event ID: " . $event->id . ")</li>"; } echo "</ul>"; $eventURL = "http://www.google.com/calendar/feeds/default/private/full/Dir0FthEpUbl1cGma1lCalendAr"; try { $event = $service->getCalendarEventEntry($eventURL); echo 'Evento: ' . $event->getTitle() .'<br>'; echo 'detalles: ' . $event->getContent().'<br>'; foreach ($event->getWhen() as $dato) { echo 'inicia: ' . substr($dato->startTime, 0,-19) . ' a las: ' . substr($dato->startTime, 11,-10) .'<br>'; echo 'termina: ' .substr($dato->endTime,0,-19) . ' a las: ' . substr($dato->endTime,11,-10) .'<br>'; } } catch (Zend_Gdata_App_Exception $e) { echo "Error: " . $e->getMessage(); } with this you can add, update, edit or delete events from calendar form any user with mail and password... A: Use OAuth 2 and the Authorization Code flow (web server flow), with offline enabled. Store the refresh tokens (which last indefinitely until the user has revoked), and you'll be able to upload events to Google Calendar even when the user isn't currently logged in. More info: https://developers.google.com/accounts/docs/OAuth2WebServer#offline
{ "language": "en", "url": "https://stackoverflow.com/questions/11908768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Many aggregate functions in select query I'm not sure what the best way to approach this is so I figured I'd toss it to SO. I'm writing a view for an application which will display some grid data based on a few tables in our database. I know I can do this with aggregate functions in the select portion of the query, but I'm wondering if there is a more efficient way (possibly with sub-selects) or if this will be good enough. Example: Table A (LineItems) -------- OrderID Weight1 Weight2 UnitPrice Table B (Orders) -------- ID Query example: SELECT Orders.ID, SUM(LineItems.Weight1) as W1, SUM(LineItems.Weight2) as W2, ABS(SUM(LineItems.Weight1) - SUM(LineItems.Weight2)), ABS(SUM(LineItems.Weight1) - SUM(LineItems.Weight2)) FROM Orders RIGHT OUTER JOIN LineItems ON Orders.ID = OrderLines.OrderID WHERE Orders.RecordDeleted <> 'TRUE' GROUP BY Orders.ID To clarify, this is just a sample. The select query will include functions for calculating price from the lineitems as well as a few other things that need to be used in aggregate functions (all pretty basic math operations). A: As long as you are grouping using the same column you should be to go. Unfortunately it is not the case if you want to group on different columns. The counts will be narrowed to the whole list of the GROUP BY, for example if you want to group by OrderLines.ID as well. For a better performance, I would use calculated columns in the Orders table. First you need to create a user defined function: CREATE FUNCTION dbo.GetOrderWeight(@Key int) RETURNS int AS BEGIN RETURN ( SELECT SUM(Weight1) FROM LineItems WHERE OrderID = @Key ) END Then add a calculated column to the table: ALTER TABLE Orders ADD OrderWeight AS dbo.GetOrderWeight(ID) Follow with the same for other aggregate methods you have. Please be aware that this is a performance killer if used with function that has varchar(max) as input parameter type. A: This is should be more effective then using subselects. Just be sure that you have proper indexes to get the best performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/20245670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handling $http AngularJS return data Here is client side in AngularJS (works fine): $scope.ajaxLogin = function(){ var fn = document.getElementById("username").value; var pw = document.getElementById("password").value; $http({ url: "myurl", method: "POST", headers: {'Content-Type': 'application/x-www-form-urlencoded'}, data: { username: fn, password: pw } }).success(function(data, status, headers, config) { // this callback will be called asynchronously // when the response is available $scope.showAlertError(); }).error(function(data, status, headers, config) { // called asynchronously if an error occurs // or server returns response with an error status. $scope.showAlertError(); }); }; I expect to have success only if user and password are matched. Server side: if ($result=mysqli_query($con,$sql)) { $rowcount=mysqli_num_rows($result); printf($rowcount); mysqli_free_result($result); } Before AngularJS I used normal AJAX handling. this is how i did earlier: function ajax_post(){ // Create our XMLHttpRequest object var hr = new XMLHttpRequest(); // Create some variables we need to send to our PHP file var url = "myurl"; var fn = document.getElementById("username").value; var ln = document.getElementById("password").value; var vars = "username="+fn+"&password="+ln; hr.open("POST", url, true); // Set content type header information for sending url encoded variables in the request hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // Access the onreadystatechange event for the XMLHttpRequest object hr.onreadystatechange = function() { if(hr.readyState == 4 && hr.status == 200) { var return_data = hr.responseText; if(return_data=="1"){ console.log("this is return data"+return_data); }else{ ons.notification.alert({message: 'Login Failed!'}); } } } // Send the data to PHP now... and wait for response to update the status div hr.send(vars); // Actually execute the request } How can I use this with AngularJS? I tried putting similar code in success handler, but it always goes to else block. A: did you try this: .success(function(data, status, headers, config) { if(status === 200) { var return_data = data; if(return_data==="1"){ location.href = "home.html?username=" + fn; } else{ ons.notification.alert({message: 'Login Failed!'}); } } } A: $scope.ajaxLogin = function(){ var fn = document.getElementById("username").value; var pw = document.getElementById("password").value; $http({ url: "myurl", method: "POST", headers: {'Content-Type': 'application/x-www-form-urlencoded'}, data: { username: fn, password: pw } }).success(function(data, status, headers, config) { //Your server output is received here. if(data){console.log('username and password matches');} else {console.log('username and password does not match');} $scope.showAlertError(); }). error(function(data, status, headers, config) { // called asynchronously if an error occurs // or server returns response with an error status. $scope.showAlertError(); }); };
{ "language": "en", "url": "https://stackoverflow.com/questions/28514318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to change background at runtime on openscenegraph I try to add an 3d object on viewer and change background dynamically. I capture webcam using opencv VideoCapture. I did below steps : * *Open video capture and get frame *Create openscenegraph root *Add a child to root ( read from .osg file 3d object) *Create a texture2d object for background *Set image of background *Create a camera to view background *Add camera to root *Set data of viewer (viewer.setScenedat(root)) *Run viewer.run() These steps add first frame as background and add a 3d object to scene. But I can't change background each frame. How can I do it? Code : cv::VideoCapture cap(0); cv::Mat frame; if(!cap.isOpened()) { std::cout << "Webcam cannot open!\n"; return; } osgViewer::Viewer viewer; osg::ref_ptr<osg::Group> root = new osg::Group(); osg::ref_ptr<osg::Texture2D> bg = new osg::Texture2D(); root->addChild(osgDB::readNodeFile("object.osg")); bg->setFilter(osg::Texture::FilterParameter::MIN_FILTER, osg::Texture::FilterMode::LINEAR); bg->setFilter(osg::Texture::FilterParameter::MAG_FILTER, osg::Texture::FilterMode::LINEAR); bg->setDataVariance(osg::Object::DYNAMIC); cap >> frame; osg::ref_ptr<osg::Image> osgImage = new osg::Image; osgImage->setImage(frame.cols, frame.rows, 3, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, (uchar*)(frame.data), osg::Image::AllocationMode::NO_DELETE, 1); bg->setImage(osgImage); osg::ref_ptr<osg::Camera> bg_cam = new osg::Camera(); bg_cam->setProjectionMatrixAsOrtho2D(-0.5, 0.5, -0.5, 0.5); bg_cam->setViewMatrixAsLookAt( osg::Vec3(0.5, 0.5, -1.0), osg::Vec3(0.5, 0.5, 0.0), osg::Vec3(0.0, -1.0, 0.0) ); bg_cam->setRenderOrder(osg::Camera::PRE_RENDER); bg_cam->setReferenceFrame(osg::Camera::ABSOLUTE_RF); bg_cam->addChild(initializeBackground(bg)); root->addChild(bg_cam); viewer.setSceneData(root); viewer.getCamera()->setProjectionMatrixAsPerspective( 40., 1., 1., 100.); viewer.getCamera()->setClearMask(GL_DEPTH_BUFFER_BIT); viewer.getCamera()->setClearColor(osg::Vec4(1.0, 0.0, 0.0, 1.0)); viewer.run(); A: viewer.getCamera()->setClearMask(GL_DEPTH_BUFFER_BIT); viewer.getCamera()->setClearColor(osg::Vec4(1.0, 0.0, 0.0, 1.0)); bg->setDataVariance(osg::Object::DYNAMIC); viewer.realize(); // set up windows and associated threads. while(!viewer.done()) { cap >> frame; osg::ref_ptr<osg::Image> osgImage = new osg::Image; osgImage->setImage(frame.cols, frame.rows, 3, GL_RGB, GL_BGR, GL_UNSIGNED_BYTE, (uchar*)(frame.data), osg::Image::AllocationMode::NO_DELETE, 1); bg->setImage(osgImage); viewer.frame(); } This code changes background dynamially.
{ "language": "en", "url": "https://stackoverflow.com/questions/30532671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Data population on asp GridView during population of data table My VB.net application has to fetch a large amount of data and populate the GridView. Now the data population is happening after getting full data to data table. I want to know is it possible to display the data in GridView when ever one row is added to the data table?.. A: I suppose you have a routine/method which is continuously checking for updates to the Data Source. Once you receive the update, you would need to call the DataBind() method again on the grid. UPDATE: GridView control will show what's is in DataSource, so you need to modify the DataSource. One of the possible way could be using asynchronous calls from your Server Side C# code and on the Callback you can reset the DataSource Property. If you are flexible then you can also try Knockout binding using MVVM pattern, have a HTML table bound to knockout Observable Array in View Model.
{ "language": "en", "url": "https://stackoverflow.com/questions/31446078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: implicit declaration of function 'time' [-Wimplicit-function-declaration]| Whenever I try to use srand function I get this warning "implicit declaration of function 'time' [-Wimplicit-function-declaration]|" and a windows error report appears when running the compiled file, I'm a novice to c programming, I found this on a text book, but it doesn't work for me. srand (time()); int x= (rand()%10) +1; int y= (rand()%10) +1; printf("\nx=%d,y=%d", x,y); What do I need to correct this? A: You need to make sure that you #include the right headers, in this case: #include <stdlib.h> // rand(), srand() #include <time.h> // time() When in doubt, check the man pages: $ man rand $ man time One further problem: time() requires an argument, which can be NULL, so your call to srand() should be: srand(time(NULL)); A: Note that time() function uses current time (expressed in seconds since 1970) both in its return value and in its address argument. A: I had this issue, and the problem was that in windows you need to include sys/time.h, but in linux you need time.h and I didn't notice. I fixed this by adding a simple platform check: #ifdef _WIN32 #include <sys/time.h> #else #include <time.h> #endif Note that this is for windows and linux, because that's what I needed for my program.
{ "language": "en", "url": "https://stackoverflow.com/questions/15458393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Standardization before or after categorical encoding? I'm working on a regression algorithm, in this case k-NearestNeighbors to predict a certain price of a product. So I have a Training set which has only one categorical feature with 4 possible values. I've dealt with it using a one-to-k categorical encoding scheme which means now I have 3 more columns in my Pandas DataFrame with a 0/1 depending the value present. The other features in the DataFrame are mostly distances like latitud - longitude for locations and prices, all numerical. Should I standardize (Gaussian distribution with zero mean and unit variance) and normalize before or after the categorical encoding? I'm thinking it might be benefitial to normalize after encoding so that every feature is to the estimator as important as every other when measuring distances between neighbors but I'm not really sure. A: Seems like an open problem, thus I'd like to answer even though it's late. I am also unsure how much the similarity between the vectors would be affected, but in my practical experience you should first encode your features and then scale them. I have tried the opposite with scikit learn preprocessing.StandardScaler() and it doesn't work if your feature vectors do not have the same length: scaler.fit(X_train) yields ValueError: setting an array element with a sequence. I can see from your description that your data have a fixed number of features, but I think for generalization purposes (maybe you have new features in the future?), it's good to assume that each data instance has a unique feature vector length. For instance, I transform my text documents into word indices with Keras text_to_word_sequence (this gives me the different vector length), then I convert them to one-hot vectors and then I standardize them. I have actually not seen a big improvement with the standardization. I think you should also reconsider which of your features to standardize, as dummies might not need to be standardized. Here it doesn't seem like categorical attributes need any standardization or normalization. K-nearest neighbors is distance-based, thus it can be affected by these preprocessing techniques. I would suggest trying either standardization or normalization and check how different models react with your dataset and task. A: After. Just imagine that you have not numerical variables in your column but strings. You can't standardize strings - right? :) But given what you wrote about categories. If they are represented with values, I suppose there is some kind of ranking inside. Probably, you can use raw column rather than one-hot-encoded. Just thoughts. A: You generally want to standardize all your features so it would be done after the encoding (that is assuming that you want to standardize to begin with, considering that there are some machine learning algorithms that do not need features to be standardized to work well). A: So there is 50/50 voting on whether to standardize data or not. I would suggest, given the positive effects in terms of improvement gains no matter how small and no adverse effects, one should do standardization before splitting and training estimator
{ "language": "en", "url": "https://stackoverflow.com/questions/47272033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Loading several Json files from a folder in Python I'm trying to load a set of json files from a separate director, which appears to work when loading them in. jsonlist is loaded in and looks like this: ['recording0.json', 'recording1.json', 'recording2.json', 'recording3.json'] However, when I want to load in the actual data, it tells me there is no json file to load in. I think it's to do with the path but I have no idea. There's a very similar question on here, but the answer doesn't seem to wrok for me. for data in jsonlist: datafile = INPUT_DIR + data with open(datafile, 'r') as json_file: json_data = json_file.read() stamps_and_coordinates = json.loads(json_data) "No JSON object could be decoded" EDIT: I'm loading in jsonlist with this: filelist = [f for f in listdir(INPUT_DIR) if isfile(join(INPUT_DIR, f))] jsonlist = [] for i in filelist: if i.endswith('.json'): jsonlist.append(i) Incredibly shortened version example of json content below: [{"Timestamp":"1184134472","DeltaTime":"42147765","PerceptorStamp":"39.6890000000005","X":1182.913,"Y":677.6516}, {"Timestamp":"1184149377","DeltaTime":"42162670","PerceptorStamp":"39.7120000000006","X":1175.157,"Y":679.6996}, {"Timestamp":"1184162553","DeltaTime":"42175846","PerceptorStamp":"39.7120000000006","X":1193.353,"Y":671.6687}]
{ "language": "en", "url": "https://stackoverflow.com/questions/36860729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Defining optional inputs in CoreML for recurrent network I have recently stumbled upon an article on the CoreML docs site that discusses an implementation of a recurrent model for predicting text. I am trying to replicate this, or at least something similar, and have hit a wall as to how the author was able to define the "stateIn" input in the model as optional. Does anyone have any info that may point me in the right direction? I'm building the network using keras and plan on converting to CoreML after training. The process used in this article would apply perfectly to my model. Outputting the state of the last layer and passing it back into the model for the next item in the sequence seems like a great approach, however I am unclear on how this is achievable using CoreML. Any information or help would be greatly appreciated! Thanks ahead of time Link to the article: https://developer.apple.com/documentation/coreml/core_ml_api/making_predictions_with_a_sequence_of_inputs A: It doesn't look like the coremltools Keras converter lets you specify which inputs are optional. However, the proto files that contain the MLModel definition say that a Model object has a ModelDescription, which has an array of FeatureDescription object for the inputs, which has a FeatureType object, which has an isOptional boolean. So something like this should work: mlmodel = keras.convert(...) spec = mlmodel._spec spec.description.input[1].type.isOptional = True mlmodel.save(...) I didn't actually try this, so the exact syntax may be different, but this is the general idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/48418651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Having issues with Infragistics column resizing I have a grid and I would like to automatically resize the columns. I'm running into inconsistencies when using different parameter values for PerformAutoResize(). When passing in the values below, where the true means include column headers: PerformAutoResize(PerformAutoSizeType.VisibleRows, true); some columns will be resized based solely on the header, while others will resize properly based on both the header and the row values. However, if I hardcode in a value: PerformAutoResize(20); It works fine for every column. Why is this? UPDATE Through some trial and error I've come to the conclusion that I think the issue is that I bring in the data and then have it auto-sort by a certain row. When using a hard coded value, it appears to auto-size the columns after that initial auto-sort, whereas when I use PerformAutoSizeType.VisibleRows it appears to auto-size the columns before the initial auto-sort. A: Does PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true); give you the results that you are looking for? If so then is it possible that when you make the call that the row that you want to size the grid by isn't visible?
{ "language": "en", "url": "https://stackoverflow.com/questions/16486552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get distinct values separately in string array? i have two string array string[] oldname = ["arun","jack","tom"]; string[] newname = ["jack","hardy","arun"]; here i want compare these two string arrays to get these distinct values separately like : oldname = ["tom"]; newname = ["hardy"]; how to achieve these ... A: string[] oldNameDistinct = oldname.Where(s => !newname.Contains(s)).ToArray(); string[] newNameDistinct = newname.Where(s => !oldname.Contains(s)).ToArray(); A: Let the two arrays were defined like the following: string[] oldname = new[] { "arun", "jack", "tom" }; string[] newname = new string[] { "jack", "hardy", "arun" }; Then you can use the Extension method .Except to achieve the result that you are looking for. Consider the following code and the working example var distinctInOld = oldname.Except(newname); var distinctInNew = newname.Except(oldname); A: Try this : string[] oldname = new string[] { "arun", "jack", "tom" }; string[] newname = new string[] { "jack", "hardy", "arun" }; List<string> distinctoldname = new List<string>(); List<string> distinctnewname = new List<string>(); foreach (string txt in oldname) { if (Array.IndexOf(newname, txt) == -1) distinctoldname.Add(txt); } foreach (string txt in newname) { if (Array.IndexOf(oldname, txt) == -1) distinctnewname.Add(txt); } //here you can get both the arrays separately Hope this help :) A: string[] oldname = new []{"arun","jack","tom"}; string[] newname = new []{"jack","hardy","arun"}; // use linq to loop through through each list and return values not included in the other list. var distinctOldName = oldname.Where(o => newname.All(n => n != o)); var distinctNewName = newname.Where(n => oldname.All(o => o != n)); distinctOldName.Dump(); // result is tom distinctNewName.Dump(); // result is hardy
{ "language": "en", "url": "https://stackoverflow.com/questions/42218992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cannot load video or image on visual studio 2015+opencv3 I install opencv 3 on visual studio 2015 follow exactly google. First I build Opencv + Opencv_contrib + cmake use visual studio 2015. After that i install it into visual and i do exactly step by step follow tutorial in google include: 1)add path into Evironment Variables 2)C/C++ >> general >> Additional Include Directory = C:\opencv\build\install\include 3)Linker >> General >> Additional Library Directories = c:\opencv\build\install\x64\vc14\lib 4)Linker >> input >> Additional Dependencies = opencv_core331d.lib + ... + And finaly i make a example to test #include "opencv2/core.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/objdetect.hpp" #include <iostream> #include <fstream> #include <sstream> using namespace cv; using namespace std; int main() { cv::Mat frame = cv::imread("iphone.jpg"); cv::namedWindow("test", CV_WINDOW_AUTOSIZE); cv::imshow("test", frame); system("pause"); } instead of it will slow the image, but dont. The result is enter image description here And i dont know what I wrong or mistake please help me. Any idea will appreciate. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/51798819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I locate element by pixel (css position)? Java, Selenium public void ReorderColumns() { // Element which needs to drag. WebElement From = driver.findElement(By.cssSelector( "body > div:nth-child(3) > div > div.dynamic > div > div:nth-child(2) > div > div.dynamic.dynamic > svg")); Actions act = new Actions(driver); // Drag and Drop by Pixel. act.dragAndDropBy(From, 146, 214).build().perform(); } I need to drag and drop an icon to reorder the column header on the web page, each header has its own reorder icon and there is no way to specify it by any Element locate methods(xpath/CSS selector/link..etc) Is there any way to locate elements by the pixel(CSS position)? Above is my code: * *In CSS selector "dynamic" means those generated dynamically so that I don't want to use it. *But to perform the act.dragAndDropBy I need a WebElement parameter: dragAndDrop(source, target) dragAndDropBy(source, xOffset, yOffset) *146, 214 is the position I want to drag the first reorder icon to. A: I think this can help you to solve the problem: WebElement a = driver.findElement(By.cssSelector("your_selector")); WebElement b = driver.findElement(By.cssSelector("your_selector")); int x = b.getLocation().x; int y = b.getLocation().y; Actions actions = new Actions(driver); actions.moveToElement(a) .pause(Duration.ofSeconds(1)) .clickAndHold(a) .pause(Duration.ofSeconds(1)) .moveByOffset(x, y) .moveToElement(b) .moveByOffset(x,y) .pause(Duration.ofSeconds(1)) .release().build().perform();
{ "language": "en", "url": "https://stackoverflow.com/questions/63335463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: The referenced component 'ceTe.DynamicPDF.40' could not be found in VS Source Control I am trying to debug a web app in VS Source Control. But, I am getting the error The type or namespace name 'ceTe' could not be found (are you missing a using directive or an assembly reference?) The referenced component 'ceTe.DynamicPDF.40' could not be found On expanding the References folder in the Solution Explorer in Visual Studio, ceTe.DynamicPDF.40 is listed but marked with a yellow warning icon. How do I fix this? I referred to this Refrenced Toolkit could not be found question but my problem is with the source control code. I do not have the related dll in my local repository of the project so I can't add it's reference. A: Resolved this by copying over the respective dll file from the server.
{ "language": "en", "url": "https://stackoverflow.com/questions/61503189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error when building java web app outside eclipse using ANT I have a java web project on which I use ANT to perform the build. If I pull code from CVS repository inside the Eclipse workspace using Eclipse tooling to pull code, and then use the build.xml ANT file to perform the build, it builds succesfully and I am able to deploy to the web container and login. If I pull code from CVS repository outside the Eclipse workspace using a linux cvs client and then use the build.xml ANT file to perform the build, it builds succesfully and I am able to deploy to the web container, but when I try to login I am presented with some errors stating "Could not find the required X class...". In Eclipse workspace, the files that differ from remote CVS are .classpath and .factorypath. These two files are not referenced in the build.xml and are supposed not to be used as part of ANT build. I am wondering if these two files might be the answer to why when I build/deploy from Eclipse workspace I see no errors when I login and when I do it outside Eclipse workspace I am unable to login without errors, any ideas? I am wondering also if it could be related to deployment assembly and/or bound/unbound projects.
{ "language": "en", "url": "https://stackoverflow.com/questions/45969803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: React Native What I'm doing wrong here with constant I'm trying to implement one functional component. Here I am doing below, But I'm getting error about props. Could someone help me. import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; const TextField = () => { return ( <Text> {this.props.title} </Text> ) } export default TextField; // APP Component import TextField from './Components/TextField' export default class App extends React.Component { render() { return ( <View style={styles.container}> <TextField title= "Simple App"/> </View> ); } } A: The reason is this.props is not defined in a functional component. They receive the props as an argument. Change your TextField to take argument props and use props.title const TextField = (props) => { return ( <Text> {props.title} </Text> ) }
{ "language": "en", "url": "https://stackoverflow.com/questions/51910896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Deep copy object properties (including those with private setter) to another object of the same type I have done some research and only found "superficial" methods that actually copy your properties from one object to another, such as: public static void CopyPropertiesTo<T, TU>(this T source, TU dest) { var sourceProps = typeof(T).GetProperties().Where(x => x.CanRead).ToList(); var destProps = typeof(TU).GetProperties() .Where(x => x.CanWrite) .ToList(); foreach (var sourceProp in sourceProps) { if (destProps.Any(x => x.Name == sourceProp.Name)) { var p = destProps.First(x => x.Name == sourceProp.Name); if (p.CanWrite) { // check if the property can be set or no. p.SetValue(dest, sourceProp.GetValue(source, null), null); } } } } The problem with the above method is that it doesn't copy the private fields too. I have a class like this: class myType{ public object prop1; private bool flag; private otherType prop2; //recursive deep property copy loop needed on this object. myType(bool flag){ this.flag = flag; } } Now let's suppose I will run the above method on these two classes: myType obj1 = new myType(false); myType obj2 = new myType(true); obj1.CopyPropertiesTo(obj2); The outcome will be that obj2.flag value will remain unchanged`. I am looking for a method that actually deep copies all properties including those with private setters. A: This is because Type.GetProperties only returns properties. What you are searching for is essentially the same code as the CopyPropertiesTo above, but you want to replace GetProperties with GetFields. You also need to specify BindingFlags in the parameters of the method to get private members. Try this out: public static void CopyFieldsTo<T, TU>(this T source, TU dest) { var sourceFields = typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).ToList(); var destFields = typeof(TU).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).ToList(); foreach (var sourceField in sourceFields) { if (destFields.Any(x => x.Name == sourceField.Name)) { var f = destFields.First(x => x.Name == sourceField.Name); f.SetValue(dest, sourceField.GetValue(source)); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/53711862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Fail to post(CURL) the form to EPayment GatewayFail to post(CURL) the form to EPayment Gateway Here is a donation page . I tried to save the data to MYSQL db and curl the essential info to the EPayment Gateway(Paydollar) ,e.g. merchantId ,amount ,currCode.... If I activate the <form name="payFormCcard" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">,it will jump to the db storage and will not do the epayment action . If I activate the <form action="https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp" id="payFormCcard" method="post" name="payFormCcard"> ,it won't do the MYSQL storage . Now , I blind both form action methods :<form name="payFormCcard" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> & <form action="https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp" id="payFormCcard" method="post" name="payFormCcard">, no submit actions will be done . It seems that it cannot pass the parameters to the EPayment Gateway by POST-CURL curl_setopt($ch, CURLOPT_URL,"https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp"); curl_setopt($ch, CURLOPT_POST, 1); =>It seems that this code cannot be activated . How should I fix the code? create.php <?php // Include config file require_once 'database.php'; header("Content-Type:text/html; charset=big5"); print_r($_POST); // Define variables and initialize with empty values $CName = $Address = $Phone = $Amount= $Purpose= $Ticket = ""; $CName_err = $Address_err = $Phone_err = $Amount_err = $Purpose_err = $Ticket_err=""; // Processing form data when form is submitted if ($_SERVER["REQUEST_METHOD"] == "POST") { // Validate name $input_CName = trim($_POST["CName"]); if (empty($input_CName)) { $CName_err = "Please enter a name."; } elseif (!filter_var(trim($_POST["CName"]), FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => "/^[a-zA-Z'-.\s ]+$/")))) { $CName_err = 'Please enter a valid name.'; } else { $CName = $input_CName; } // Validate address $input_Address = trim($_POST["Address"]); if (empty($input_Address)) { $Address_err = 'Please enter an address.'; } else { $Address = $input_Address; } // Validate Phone $input_Phone = trim($_POST["Phone"]); if (empty($input_Phone)) { $Phone_err = "Please enter your phone number again."; } elseif (!ctype_digit($input_Phone)) { $Phone_err = 'Please enter a positive integer value.'; } else { $Phone = $input_Phone; } // Validate Amount $input_Amount = trim($_POST["Amount"]); if (empty($input_Amount)) { $Amount_err = "Please enter the amount."; } elseif (!ctype_digit($input_Amount)) { $Amount_err = 'Please enter a positive integer value.'; } else { $Amount = $input_Amount; } // Check input errors before inserting in database if (empty($CName_err) && empty($Address_err) && empty($Amount_err) && empty($Phone_err)) { // Prepare an insert statement $pdo = Database::connect(); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO donation (CName, Address, Phone, Amount ,Ticket, Purpose) VALUES (?, ?, ?, ? ,?, ?)"; $q = $pdo->prepare($sql); $q->execute(array($CName, $Address, $Phone, $Amount ,$Ticket ,$Purpose)); Database::disconnect(); header("Location: index.php"); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array ( 'merchantId' => 'sth', 'orderRef' => 'sth', 'currCode' => 'sth', 'mpsMode' => 'NIL', 'successUrl' =>'http://www.yourdomain.com/Success.html', 'failUrl' =>'http://www.yourdomain.com/Fail.html', 'cancelUrl'=>'http://www.yourdomain.com/Cancel.html', 'payType' =>'sth', 'lang' =>'sth', 'payMethod' => 'sth', 'secureHash'=> 'sth' ))); // receive server response ... curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $server_output = curl_exec ($ch); curl_close ($ch); } ?> <!DOCTYPE html> <!--<html lang="en">--> <html> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <title> </title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"> <style type="text/css"> .wrapper{ width: 500px; margin: 0 auto; } </style> </head> <body> <div class="wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="page-header"> <h2> form </h2> </div> <p> </p><br> <p> </p><!-- <form name="payFormCcard" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> --> <!-- <form action="https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp" id="payFormCcard" method="post" name="payFormCcard"> --> <div class="form-group &lt;?php echo (!empty($CName_err)) ? 'has-error' : ''; ?&gt;"> <label>*English Name</label> <input class="form-control" name="CName" type="text" value="<?php echo $CName; ?>"> <span class="help-block"><?php echo $CName_err; ?></span> </div> <div class="form-group &lt;?php echo (!empty($Phone_err)) ? 'has-error' : ''; ?&gt;"> <label>*Contact No.</label> <input class="form-control" name="Phone" type="text" value="<?php echo $Amount; ?>"> <span class="help-block"><?php echo $Phone_err; ?></span> </div> <div class="form-group &lt;?php echo (!empty($Address_err)) ? 'has-error' : ''; ?&gt;"> <label>* Email Address</label> <textarea class="form-control" name="Address"><?php echo $Address; ?></textarea> <span class="help-block"><?php echo $Address_err; ?></span> </div> <div class="form-group &lt;?php echo (!empty($Amount_err)) ? 'has-error' : ''; ?&gt;"> <label>*Donation Amount</label> <input class="form-control" list="Amount" multiple name="Amount"> <datalist id="Amount"> <option value="100"> </option> <option value="300"> </option> <option value="500"> </option> <option value="1000"> </option> </datalist> <span class="help-block"><?php echo $Amount_err; ?></span> </div> </div><input class="btn btn-primary" type="submit" value="Submit"> <a class="btn btn-primary" href="index.php">Cancel</a> </form> <p> </p><br> <p> Thank you for your support </p> </div> </div> </div> </div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/51033463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get a linefeed when writing files with ActionScript with Adobe Indesign Scripting I'm writing some scripts in ActionScript to automate some tasks in Adobe Indesign 2019 (part of the Creative Cloud Suite), but this applies to all scripting for all applications in Adobe Creative Cloud. I don't want to use ExtendScript Toolkit for editing/running the script, because it is terribly slow. Because there is no such thing as console.log() available (at least that I'm aware of) and alert() will stop for user input to continue, I created a small file logger, but it does not append the file, but keeps on overwriting the first line. I use tail -f indesign.log to monitor the log file. Here is the code of the logger function logger(message){ var logFilePath = new File ('indesign.log'); logFilePath.encoding = 'UTF-8'; try { logFilePath.open('a'); } catch(err) { logFilePath.close(); logFilePath.open('a'); } logFilePath.write(new Date().toLocaleString() +": " + message + "\n"); //logFilePath.writeln(new Date().toLocaleString() +": " + message + "\n"); logFilePath.close() } logger("Script started") logger("2nd line") logger("3rd line") logger("4th line") logger("Script finished") I tried also using writeln instead of write, but it does not make a difference. I tried different line feeds, like "\n" and "\r\n", but it does not make a difference. I tried different File.open options like .open('w'), .open('ra'). The documentation about this is either not clear or really outdated (Or I just can't find it). Any suggestions in the comments about the best IDE to edit/run ActionScripts is highly appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/54551028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why inner class can access to a private member of another inner class? I just found out that an inner class can access another inner class's private member like this: public class TestOutter { class TestInner1 { private int mInt = 1; } class TestInner2 { public int foo(TestInner1 value) { return value.mInt; } } } Method foo of TestInner2 can access the private member mInt of TestInner1. But I have never see this case before. I don't know the meaning of letting code in TestInner2 can access to the private member of TestInner1. I was searched about inner class in google, none of the search results shows that inner class have this feature. I also look up to The Java Language Specification, but it still not mention about that. A: "Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor." JLS 6.6.1 In this case, TestOutter is the top-level class, so all private fields inside it are visible. Basically, the purpose of declaring a member private is to help ensure correctness by keeping other classes (subclasses or otherwise) from meddling with it. Since a top-level class is the Java compilation unit, the spec assumes that access within the same file has been appropriately managed. A: This is because the inner class, as a member of the outer class, has access to all the private variables of its outer class. And since the other inner class is also a member of the outer class, all of its private variables are accessible as well. Edit: Think of it like you have a couple of couch cushion forts(inner classes) in a house(outer class), one yours the other your siblings. Your forts are both in the house so you have access to all the things in your house. And mom(Java) is being totally lame and saying you have to share with your sibling because everything in the house is everyone elses and if you want your own fort you are going to have to buy it with your own money(make another class?).
{ "language": "en", "url": "https://stackoverflow.com/questions/18093850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why does the string Remove() method allow a char as a parameter? Consider this code: var x = "tesx".Remove('x'); If I run this code, I get this exception: startIndex must be less than length of string. Why can I pass a char instead of an int to this method? Why don't I get a compilation error? Why does the compiler have this behavior? A: you try to remove 'x' which is a declared as char, x is equal to 120 The .Remove only takes 2 parameters of type int the start and (optional) count to remove from the string. If you pass a char, it will be converted to the integer representation. Meaning if you pass 'x' -> 120 is greater than the string's .Length and that's why it will throw this error! A: Remove takes an int parameter for the index within the string to start removing characters, see msdn. The remove call must automatically convert the char to its ASCII integer index and try to remove the character at that index from the string, it is not trying to remove the character itself. If you just want to remove any cases where x occurs in the string do: "testx".Replace("x",string.Empty); If you want to remove the first index of x in the string do: var value = "testx1x2"; var newValue = value.Remove(value.IndexOf('x'), 1); A: Implicit conversion lets you compile this code since char can be converted to int and no explicit conversion is required. This will also compile and the answer will be 600 (120*5) - char c = 'x'; int i = c; int j = 5; int answer = i * j; From MSDN, implicit conversion is summarized as below - As other's have stated you could use Replace or Remove with valid inputs. A: There is no overload of Remove that takes a char, so the character is implicitly converted to an int and the Remove method tries to use it as an index into the string, which is way outside the string. That's why you get that runtime error instead of a compile time error saying that the parameter type is wrong. To use Remove to remove part of a string, you first need to find where in the string that part is. Example: var x = "tesx"; var x = x.Remove(x.IndexOf('x'), 1); This will remove the first occurance of 'x' in the string. If there could be more than one occurance, and you want to remove all, using Replace is more efficient: var x = "tesx".Replace("x", String.Empty); A: Since you are passing a char in the function and this value is getting converted to int at runtime hence you are getting the runtime error because the value of char at runtime is more than the length of the string.You may try like this:- var x = "tesx"; var s = x.Remove(x.IndexOf('x'), 1); or var s = x.Replace("x",string.Empty); .Remove takes the int as parameter. Remove takes two parameters. The first one is what position in your string you want to start at. (The count starts at zero.) The second parameter is how many characters you want to delete, starting from the position you specified. On a side note: From MSDN: This method(.Remove) does not modify the value of the current instance. Instead, it returns a new string in which the number of characters specified by the count parameter have been removed. The characters are removed at the position specified by startIndex. A: You can use extension methods to create your own methods for already existing classes. Consider following example: using System; using MyExtensions; namespace ConsoleApplication { class Program { static void Main(string[] args) { const string str1 = "tesx"; var x = str1.RemoveByChar('x'); Console.WriteLine(x); Console.ReadKey(); } } } namespace MyExtensions { public static class StringExtensions { public static string RemoveByChar(this String str, char c) { return str.Remove(str.IndexOf(c), 1); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/19343958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "59" }
Q: how to create a child in a tree view in ext.js I need to create a child in a tree view how to do that kindly help. I have tried like this but it's not working. var myLocations = new Ext.Panel({ title: 'my work', id: 'student', height: 100, autoScroll: true, iconCls: 'myPanel', // ,autoLoad: { url: 'UserLocDetails.aspx?UserName=' + strUser } children: [{ text: "Leaf node (<i>no folder/arrow icon</i>)", title: 'dasdasd', leaf: true, id: 'myLoc', qtitle: 'Sample Tip Title', qtip: 'Tip body' }] }); A: You need to create a TreeStore in order to store data for a tree, and some component that can display a tree, for example a TreePanel. Try the following code, it is for Ext JS 7.3.0 Classic Material, but can be adopted to other versions: Ext.define('myTreeStore', { extend: 'Ext.data.TreeStore', root: { expanded: true }, proxy: { type: 'memory', reader: { type: 'json' } }, data: { children: [{ text: 'Main 1', leaf: true }, { text: 'Main 2', children: [{ text: 'Sub 21', leaf: true },{ text: 'Sub 22', leaf: true }] }, { text: 'Main 3', leaf: true }] } }) Ext.application({ name: 'Fiddle', launch: function () { const treeStore = Ext.create('myTreeStore'); Ext.create('Ext.tree.Panel', { rootVisible: false, renderTo: Ext.getBody(), title: 'Tree Example', width: 400, store: treeStore, }); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/69912902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visual Studio 2019 JUCE C++ fields "undefined" in cpp file When trying to initialize or use my fields in the cpp file, I receive a compiler error that the "identifier is undefined" when I have defined them all in the header file. SynthVoice.H #pragma once #include <JuceHeader.h> #include "SynthSound.h" class SynthVoice : public juce::SynthesiserVoice { public: bool canPlaySound(juce::SynthesiserSound* sound) override; void setPitchBend(int pitchWheelPos); float pitchBendCents(); static double noteHz(int midiNoteNumber, double centsOffset); void getOscType(float* selection); void getOsc2Type(float* selection); double setEnvelope(); void getWillsParams(float* mGain, float* blend, float* pbup, float* pbdn); void getFilterParams(float* filterType, float* filterCutoff, float* filterRes); void startNote(int midiNoteNumber, float velocity, juce::SynthesiserSound* sound, int currentPitchWheelPosition) override; void stopNote(float velocity, bool allowTailOff) override; void controllerMoved(int controllerNumber, int newControllerValue) override; void prepareToPlay(double sampleRate, int samplesPerBlock, int outputChannels); void renderNextBlock(juce::AudioBuffer <float>& outputBuffer, int startSample, int numSamples); private: double level; double frequency; int theWave, theWave2; float masterGain; float osc2blend; int noteNumber; float pitchBend = 0.0f; float pitchBendUpSemitones = 2.0f; float pitchBendDownSemitones = 2.0f; int filterChoice; float cutoff; float resonance; bool isPrepared{ false }; }; SynthVoice.cpp #pragma once #include "SynthVoice.h" class SynthVoice : public juce::SynthesiserVoice { public: bool SynthVoice::canPlaySound(juce::SynthesiserSound* sound) override { return dynamic_cast <SynthSound*>(sound) != nullptr; } void SynthVoice::setPitchBend(int pitchWheelPos) { if (pitchWheelPos > 8192) { // shifting up pitchBend = float(pitchWheelPos - 8192) / (16383 - 8192); } else { // shifting down pitchBend = float(8192 - pitchWheelPos) / -8192; // negative number } } float SynthVoice::pitchBendCents() { if (pitchBend >= 0.0f) { // shifting up return pitchBend * pitchBendUpSemitones * 100; } else { // shifting down return pitchBend * pitchBendDownSemitones * 100; } } static double SynthVoice::noteHz(int midiNoteNumber, double centsOffset) { double hertz = juce::MidiMessage::getMidiNoteInHertz(midiNoteNumber); hertz *= std::pow(2.0, centsOffset / 1200); return hertz; } //======================================================= void SynthVoice::getOscType(float* selection) { theWave = *selection; } void SynthVoice::getOsc2Type(float* selection) { theWave2 = *selection; } //======================================================= double SynthVoice::setEnvelope() { return env1.adsr(setOscType(), env1.trigger); } //======================================================= void SynthVoice::getWillsParams(float* mGain, float* blend, float* pbup, float* pbdn) { masterGain = *mGain; osc2blend = *blend; pitchBendUpSemitones = *pbup; pitchBendDownSemitones = *pbdn; } void SynthVoice::getFilterParams(float* filterType, float* filterCutoff, float* filterRes) { filterChoice = *filterType; cutoff = *filterCutoff; resonance = *filterRes; } //======================================================= void SynthVoice::startNote(int midiNoteNumber, float velocity, juce::SynthesiserSound* sound, int currentPitchWheelPosition) override { noteNumber = midiNoteNumber; env1.trigger = 1; setPitchBend(currentPitchWheelPosition); frequency = noteHz(noteNumber, pitchBendCents()); level = velocity; } //======================================================= void SynthVoice::stopNote(float velocity, bool allowTailOff) override { env1.trigger = 0; allowTailOff = true; if (velocity == 0) clearCurrentNote(); } //======================================================= void SynthVoice::pitchWheelMoved(int newPitchWheelValue) override { setPitchBend(newPitchWheelValue); SynthVoice::frequency = noteHz(noteNumber, pitchBendCents()); } //======================================================= void SynthVoice::controllerMoved(int controllerNumber, int newControllerValue) override { } //======================================================= void SynthVoice::prepareToPlay(double sampleRate, int samplesPerBlock, int outputChannels) { isPrepared = true; } //======================================================= void SynthVoice::renderNextBlock(juce::AudioBuffer <float>& outputBuffer, int startSample, int numSamples) { for (int sample = 0; sample < numSamples; ++sample) { for (int channel = 0; channel < outputBuffer.getNumChannels(); ++channel) { outputBuffer.addSample(channel, startSample, setEnvelope() * masterGain); } ++startSample; } } }; I'm getting the red underline on ALL the private fields in the cpp file before I attempt to build it. I'm not exactly sure why. Originally I thought it was because I didn't have a constructor but this isn't the case for the instructor I'm watching. A: You defined the class SynthVoice in the header SynthVoice.H class SynthVoice : public juce::SynthesiserVoice { //... }; and then redefined it in the file SynthVoice.cpp with member function definitions class SynthVoice : public juce::SynthesiserVoice { //... }; If you want to define member functions declared in the class defined in the header then what you need is to write for example bool SynthVoice::canPlaySound(juce::SynthesiserSound* sound) { return dynamic_cast <SynthSound*>(sound) != nullptr; } outside the class definition. Here is a simple program that demonstrates how member functions are defined outside a class where they are declared. #include <iostream> class A { private: int x; public: A( int ); const int & get_x() const ; void set_x( int ); }; A::A( int x ) : x( x ) {} const int & A::get_x() const { return x; } void A::set_x( int x ) { A::x = x; } int main() { A a( 10 ); std::cout << a.get_x() << '\n'; return 0; } The program output is 10
{ "language": "en", "url": "https://stackoverflow.com/questions/67641173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rendering Divs in an Index action with bootstrap I am building a Ruby on Rails app with a TradingCard model. I have an index action and corresponding view where I am trying to print out each TradingCard object. Here's basically what I've got in my controller, under my index action: @trading_cards = TradingCard.all Here's my issue: I am using bootstrap to help me out with the basic grid-like approach of the styling, as well as its convenience on small mobile screens. I'm using bootstrap to help with the general layout and flow, but I've constructed my own little trading-card-esque container for each TradingCard object; I wrote it with my own CSS. It has no specified height, so it can be as tall as it needs to be to fit in all of the text specific to that individual object. On medium sized screens, I would like for my Index view to simply display three trading cards per row, WHERE EACH ROW ISN'T OBSTRUCTED BY A TRADING CARD FROM THE ROW BELOW IT. This is a problem, because best practice is to simply include the following in your index view, (of course with a _trading_card partial in the view folder): <%= render @trading_cards %> And in my _trading_card partial I have something like this: <div class="col-md-4"> <%= trading_card.body %> </div> The only problem with this approach is that I can't really tell the layout to create a new row every 3 trading cards. Instead, I have to just keep spitting out col-md-4 into one really really long row and as a result, some of the taller trading cards end up squeezing themselves up into the rows above them, and it looks really odd. Is there a better way to go about this entire approach? Am I missing something? Or is there a way to specify in my controller that I want to load the objects in bundles of 3 so that I can just write an iteration that creates a new row with every time through the loop? Any help is so much appreciated. Sorry if this question was really long. You guys are always so helpful and I really can't thank you all enough. Thanks in advance for any help!!!! A: Instead of using render @trading_cards to loop through your TradingCards for you. You could do that yourself in slices of 3 (as @alfie suggested). <% @trading_cards.each_slice(3) do |cards| %> <div class="row"> <% cards.each do |card| %> <%= render card %> <!-- This will render your `_trading_card` partial --> <% end %> </div> <% end %>
{ "language": "en", "url": "https://stackoverflow.com/questions/36816304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Swift Full Text Search Recommended Solution I was wondering if there was a recommended solution/library in Swift for integrating full text search (i.e. search bar that filters on presented data as you type, autocomplete)? I am currently using Firestore as my backend. Something I've glanced on is Algolia? A: You can use NSPredicate to search the text inside your objects, like this let searchString = "test" var arr:NSArray = [["value" : "its a test text to find"], ["value" : "another text"], ["value" : "find this text"], ["value" : "lorem ipsum is a placeholder text commonly"], ["value" : "lorem ipsum is a"]] var pre:NSPredicate = NSPredicate(format: "value CONTAINS[c] %@", searchString) var result:NSArray = arr.filtered(using: pre) as NSArray print(result) it will return a array with the result based on the text that you search A: Algolia is probably the best solution right now, and is something Firebase themselves recommend. Just a few things to bear in mind is that you'll need a paid for Firebase plan to implement as you'll need a Cloud Function that sends data over to Algolia for indexing. Once your data is in Algolia there is a great Swift library you can use to implement the Search Bars / Autocompletion you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/49667038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Call custom constructor with Dapper? I'm trying to use Dapper to interface with the ASP.NET SQL Membership Provider tables. I wrapped the SqlMembershipProvider class and added an additional method to get me the MembershipUsers given a certain criteria relating to some custom tables I have. When querying the data with Dapper, it appears that Dapper first instantiates the class with a parameter-less constructor, and then "maps" the returned columns into the properties on the object. However, the UserName property on the MembershipUser class has a no setter. Judging from around line 1417 in the Dapper SqlMapper.cs, the method GetSettableProps() only gets settable properties. I tried to do a MultiMap query to invoke the constructor, but the problem with that is the objects passed into the query are already missing the UserName. I'm guessing I could modify the GetSettableProps() method, but I'm not sure if that will work, or if it will affect my existing code. Is there anyway for me to invoke the custom constructor that the MembershipUser class has? Or is there a reasonable change that I could make to Dapper to support my situation? ** UPDATE ** Marc's answer to use the non-generic/dynamic Query() method was correct, but for posterity, this is the method I was referring to inside Dapper: static List<PropInfo> GetSettableProps(Type t) { return t .GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .Select(p => new PropInfo { Name = p.Name, Setter = p.DeclaringType == t ? p.GetSetMethod(true) : p.DeclaringType.GetProperty(p.Name).GetSetMethod(true), Type = p.PropertyType }) .Where(info => info.Setter != null) .ToList(); } A: I use this maybe it's help someone YourList = connection.Query<YourQueryClass>(Query, arg) .Select(f => new ClassWithConstructor(f.foo,f.bar)) .ToList(); A: I would use the non-generic Query API here... return connection.Query(sql, args).Select(row => new AnyType((string)row.Foo, (int)row.Bar) { Other = (float)row.Other }).ToList(); Using this you can use both non-default constructors and property assignments, without any changes, by using "dynamic" as an intermediate step. A: I came across this question and it inspired me to think a bit differently than the other answers. My approach: internal class SqlMyObject: MyObject { public SqlMyObject(string foo, int bar, float other): base(foo, bar, other) { } } ... return connection.Query<SqlMyObject>(sql, args); Using a "private" derived class (I used internal to expose it to Unit Tests, personal preference) I was able to specify one constructor that the derived class has, this can also do some mapping or business logic to get to the desired base class/params as necessary; this is useful if the only time that object should be initiated in that way is when it's pulling from the DB. Also, can use Linq's .Cast<MyObject>() on the collection to eliminate any type check issues down the line if need be without having to check for derived/base types.
{ "language": "en", "url": "https://stackoverflow.com/questions/8994933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: VB.Net Document Interface Is there a way to create a VB.Net form that has a document editor in which the user can drag and drop items from a toolbar into the document. Sort of like this https://corporate.morningstar.com/us/documents/MarketingOneSheets/AWO/ADV_AWO_OfficeReportStudio.pdf The items that would be dragged in would be Live SSRS reports and we want the ability to the let the end user position them where they want on the document. I tried finding document controls but I was unable to find one that would fit these requirements. Any thoughts or suggestions would be greatly appreciated. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/25669575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Regexp change link format On my forum I have a lot of redundant link data like: [url:30l7ypk7]http://www.box.net/shared/0p28sf6hib[/url:30l7ypk7] In regexp how can I change these to the format: <a href="http://www.box.net/shared/0p28sf6hib" rel="nofollow">http://www.box.net/shared/0p28sf6hib</a> A: string orig = "[url:30l7ypk7]http://www.box.net/shared/0p28sf6hib[/url:30l7ypk7]"; string replace = "<a href=\"$1\" rel=\"nofollow\">$1</a>"; string regex = @"\[url:.*?](.*?)\[/url:.*?]"; string fixedLink = Regex.Replace(orig, regex, replace); A: This should capture the string \[([^\]]+)\]([^[]+)\[/\1\] and group it so you can pull out the URL like this: Regex re = new Regex(@"\[([^\]]+)\]([^[]+)\[/\1\]"); var s = @"[url:30l7ypk7]http://www.box.net/shared/0p28sf6hib[/url:30l7ypk7]"; var replaced = s.Replace(s, string.Format("<a href=\"{0}\" rel=\"nofollow\">{0}</a>", re.Match(s).Groups[1].Value)); Console.WriteLine(replaced) A: This isn't doing it totally in Regex but will still work... string oldUrl = "[url:30l7ypk7]http://www.box.net/shared/0p28sf6hib[/url:30l7ypk7]"; Regex regExp = new Regex(@"http://[^\[]*"); var match = regExp.Match(oldUrl); string newUrl = string.Format("<a href='{0}' rel='nofollow'>{0}</a>", match.Value); A: This is just from memory but I will try to check it over when I have more time. Should help get you started. string matchPattern = @"\[(url\:\w)\](.+?)\[/\1\]"; String replacePattern = @"<a href='$2' rel='nofollow'>$2</a>"; String blogText = ...; blogText = Regex.Replace(matchPattern, blogText, replacePattern);
{ "language": "en", "url": "https://stackoverflow.com/questions/5628160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: System.ArgumentException occurred I'm getting a strange behavior. This is the code: ... private Object lockobj = new Object(); private Dictionary<String, BasicTagBean> toVerifyTags = null; public void verifyTags(List<BasicTagBean> tags) { System.Diagnostics.Debug.WriteLine("Thread ID: " + Thread.CurrentThread.ManagedThreadId); lock (lockobj) { foreach (BasicTagBean tag in tags) { if (!alreadyVerified.ContainsKey(tag.EPC)) { toVerifyTags.Add(tag.EPC, tag); } } } ... Sometimes I got this exception 'System.ArgumentException' occurred in mscorlib.dll at this line of code: toVerifyTags.Add(tag.EPC, tag); the exception refer to wrong add of an already existing element into collection, but I check this. Maybe a thread problem but application output shows always the same thread id. I'm using c# pocketpc version 3.5. A: The exception seems to tell you that the key you are trying to add in toVerifyTags already exists. You weren't checking if the key already existed in the right dictionary. public void verifyTags(List<BasicTagBean> tags) { System.Diagnostics.Debug.WriteLine("Thread ID: " + Thread.CurrentThread.ManagedThreadId); lock (lockobj) { foreach (BasicTagBean tag in tags) { if (!toVerifyTags.ContainsKey(tag.EPC)) { toVerifyTags.Add(tag.EPC, tag); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/24613246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to handle database exceptions in .NET? I'm using Oracle through their official managed drivers for .NET (a Nuget package). My application uses the same connection to the DB from the beginning and it's used from several locations to perform queries. In some cases, there may be connection "hiccups" that cause exceptions. The problem is that I don't know what's the best strategy to retry to perform a query when this happens. Is there a common way to solve this situation? Thank you. A: I agree with the comment from Habib. The oracle .NET Package uses connection pooling. Even if you open up multiple connections, it will manage them accordingly so that you don't have to keep it open. That means that your code can be simplified, into something like this pseudo-code: using(OracleConnection conn = MakeConnection()) { //do stuff with connection //not necessary, but I always manually close connection. Doesn't hurt. conn.Close(); } If you're uncertain of connection issues even in that small of an execution, you can wrap it in a try-catch block like so: try { using(OracleConnection conn = MakeConnection()) { //do stuff with connection //not necessary, but I always manually close connection. Doesn't hurt. conn.Close(); } } catch(OracleException ex) { //handle exception. } OracleException looks to be the main exception with the .NET oracle package. Please note that there may be others you want to catch more specifically. A: It would be easier to instantiate the connection on the fly when the query is being made. I don't think a simple try/catch would help you here because even if you reinitialized the connection in the catch block, you would have to somehow re-execute your query. I don't recommend this but you could use a Retry class that reinitializes the connection if an exception is caught.... public class Retry { public static void Do(Action action, TimeSpan retryInterval, int retryCount = 3) { Do<object>(() => { action(); return null; }, retryInterval, retryCount); } public static T Do<T>(Func<T> action, TimeSpan retryInterval, int retryCount = 3) { var exceptions = new List<Exception>(); for (int retry = 0; retry < retryCount; retry++) { try { if (retry > 0) Thread.Sleep(retryInterval); return action(); } catch (ConnectionException ex) { // ***Handle the reconnection in here*** exceptions.Add(ex); } } throw new AggregateException(exceptions); } } Then you can call your query like Retry.Do(() => MyQueryMethod, TimeSpan.FromSeconds(5)); I got the basis for this Retry code from SO a long time ago, don't recall the thread but it isn't my original code. I have used it quite a bit for some things though.
{ "language": "en", "url": "https://stackoverflow.com/questions/36752117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why authorization content is not available in access token? I am trying to add keycloak as identity server in my Asp.net mVC application by using Owin , keycloak identity model library. I am getting all information in access token except Authorization content . What will be reason for this ? . Below I mentioned what are things I done in keycloak server and ASP.net mvc Application. KeyCloak: * *I created Realm with Name as HMIS. *I created client with Name as Administrator. In this Client I change access type as confidential. *Then I allowed authorization in same client and I set valid URL for redirect *Then I created resource , scope , user based policy and it permission under authorization. ( default policy and permission also there ) . *During authorization evaluate in keycloak UI I got below decode access token. { "exp": 1607412284, "iat": 1607411984, "jti": "9d74f32a-3e2c-4fac-95d7-11feb5566d32", "aud": [ "Administrator", "account" ], "sub": "5cf9079d-3a75-48ca-906a-19e813727ee0", "typ": "Bearer", "azp": "Administrator", "session_state": "cf1b8e41-a015-4279-8e2a-2796643a4174", "acr": "1", "realm_access": { "roles": [ "offline_access", "uma_authorization" ] }, "resource_access": { "Administrator": { "roles": [ "User", "uma_protection" ] }, "account": { "roles": [ "manage-account", "manage-account-links", "view-profile" ] } }, "authorization": { "permissions": [ { "scopes": [ "NEW", "PRINT", "EXCEL", "EDIT" ], "rsid": "f7e6cbef-f203-4d71-9806-c7cdec402077", "rsname": "Area" } ] }, "scope": "Audience email profile", "email_verified": false, "preferred_username": "karthick" } *During client scope evaluation in keycloak UI . I am getting below decode access token in which authorization content is not available. { "exp": 1607412523, "iat": 1607412223, "jti": "c8a08432-0993-41d6-9786-dac65aeb33b1", "iss": "http://localhost:8080/auth/realms/HMIS", "aud": [ "Administrator", "account" ], "sub": "5cf9079d-3a75-48ca-906a-19e813727ee0", "typ": "Bearer", "azp": "Administrator", "session_state": "833d6dae-0501-4815-beac-c6373d3b19a6", "acr": "1", "realm_access": { "roles": [ "offline_access", "uma_authorization" ] }, "resource_access": { "Administrator": { "roles": [ "User", "uma_protection" ] }, "account": { "roles": [ "manage-account", "manage-account-links", "view-profile" ] } }, "scope": "openid Audience email profile", "email_verified": false, "preferred_username": "karthick" } Asp.net MVC * *In Asp.net Mvc application I used Owin and keycloak identity mode libraries to get access token from keycloak server ( using client secret key ) and I decode it by using JWT libraries. *In received access token also authorization content is not available. after decoding Like below I am receiving json format data ( which is same as client scope evaluation json format ). { "exp": 1607412523, "iat": 1607412223, "jti": "c8a08432-0993-41d6-9786-dac65aeb33b1", "iss": "http://localhost:8080/auth/realms/HMIS", "aud": [ "Administrator", "account" ], "sub": "5cf9079d-3a75-48ca-906a-19e813727ee0", "typ": "Bearer", "azp": "Administrator", "session_state": "833d6dae-0501-4815-beac-c6373d3b19a6", "acr": "1", "realm_access": { "roles": [ "offline_access", "uma_authorization" ] }, "resource_access": { "Administrator": { "roles": [ "User", "uma_protection" ] }, "account": { "roles": [ "manage-account", "manage-account-links", "view-profile" ] } }, "scope": "openid Audience email profile", "email_verified": false, "preferred_username": "karthick" } Below Code I using in asp.net mvc for authenticating. public void Configuration(IAppBuilder app) { // Name of the persistent authentication middleware for lookup const string persistentAuthType = "testKeycloak_cookie_auth"; // --- Cookie Authentication Middleware - Persists user sessions between requests app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = persistentAuthType }); app.SetDefaultSignInAsAuthenticationType(persistentAuthType); // Cookie is primary session store // --- Keycloak Authentication Middleware - Connects to central Keycloak database app.UseKeycloakAuthentication(new KeycloakAuthenticationOptions { // App-Specific Settings ClientId = "Administrator", // *Required* SOLUTION ClientSecret = "e6022499-9e91-417f-95de-b9312b67f5b0", // If using public authentication, delete this line SECRET ID SOLUTIONS VirtualDirectory = "", // Set this if you use a virtual directory when deploying to IIS //Scope="BTNPRINT", // Instance-Specific Settings Realm = "HMIS", // Don't change this unless told to do so KeycloakUrl = "http://localhost:8080/auth", // Enter your Keycloak URL here // Template-Specific Settings SignInAsAuthenticationType = persistentAuthType, // Sets the above cookie with the Keycloak data AuthenticationType = persistentAuthType, // Unique identifier for the auth middleware AllowUnsignedTokens = false, DisableIssuerSigningKeyValidation = false, DisableIssuerValidation = false, DisableAudienceValidation = true, //TokenClockSkew = TimeSpan.FromSeconds(2), DisableRefreshTokenSignatureValidation = true, }); So what will reason for missing of authorization content ?. I knew some where I missed to configure .
{ "language": "en", "url": "https://stackoverflow.com/questions/65194852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set different expanded title and collapsed title for CollapsingToolbarLayout Currently we can set only one title using the setTitle() method. Is there a way to achieve something like this: In expanded mode: In collapsed mode: (Please ignore my poor Paint skills.)
{ "language": "en", "url": "https://stackoverflow.com/questions/32524053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Yii2 select2 update value blank *****SOLVED(Updated)****** I am using kartik select2 widget inside my form. After I insert the value when I click update the value will be blank. I did search online for some solution and this is what I come out with. Is there anything I miss or misplaced in the code? Controller: public function actionUpdate($id) { $request = Yii::$app->request; $model = $this->findModel($id); if($request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; if($request->isGet) { $query = OpClient::find() ->where(['id'=>$model->id]) ->one(); return [ 'title'=> "Update OpClient", 'content'=>$this->renderAjax('update', [ 'model' => $model, 'query' => $query, ]), 'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]). Html::button('Save',['class'=>'btn btn-primary','type'=>"submit"]) ]; } else if($model->load($request->post())) { $model->unit_id = json_encode(Yii::$app->request->post( 'OpClient' )['unit_id']); $model->save(); return [ 'forceReload'=>'#crud-datatable-pjax', 'title'=> "OpClient", 'content'=>'<span class="text-success">Do you want to update '.$model->op_contact->name.' Contact Billing Address?</span>', 'footer'=> Html::button('No',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]). // Html::button('Yes',['class'=>'btn btn-default pull-right','data-dismiss'=>"modal"]) Html::a('Yes',['compare','contactid'=>$model->contact_id],['class'=>'btn btn-primary']) ]; } else { return [ 'title'=> "Update OpClient ", 'content'=>$this->renderAjax('update', [ 'model' => $model, 'query' => $query, ]), 'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]). Html::button('Save',['class'=>'btn btn-primary','type'=>"submit"]) ]; } } else { if ($model->load($request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $id]); } else { return $this->render('update', [ 'model' => $model, ]); } } } Update: <?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model frontend\models\OpClient */ ?> <div class="op-client-update"> <?= $this->render('_form', [ 'model' => $model, 'query' => $query, ]) ?> </div> Form://updated $update = json_decode($query->unit_id); <div class="row"> <div class="col-md-12">'. $form->field($model, 'unit_id')->widget(Select2::classname(), [ 'data' => $getunit, 'language' => 'en', 'options' => ['placeholder' => 'Select','multiple'=>true,'value'=>$update], 'pluginOptions' => [ 'allowClear' => true, 'tags'=>true, 'maximumInputLength'=>10, ], ]).' </div> </div><br> For $query I did get the location array of the value that I created. But it still did not display when I try to update. Any advice? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/43930780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I persist a detached object? I have a simple editor UI for performing CRUD on a database table. Under Hibernate 5.1, the process was: * *Create a session. Read in data objects. Close session, detaching the objects. *With the detached objects, populate the UI widgets. *Allow user to add/edit/remove entries in the UI, modifying the detached objects. *On a user "save" action: Create a new session. Persist new/updated objects with saveOrUpdate(). Close session. *Repeat as required. Hibernate 5.2 strongly recommends moving from the Hibernate-native API to the JPA API. JPA does not allow you to reattach detached objects. There are a couple of workarounds: * *Use unwrap to get the Hibernate session from the JPA EntityManager, and use it to call saveOrUpdate. I don't like this option because it relies on functionality that is not part of the JPA. *Use JPA merge, which will update the persisted object, although I've got to ensure I don't break any associations. This gives me 2 copies of the same object, one persisted, one detached... which is messy. *Perform a manual merge operation, copying modified fields from the detached object to the persisted object. This is extra work. *Keep a single EntityManager instance alive through the whole process. Unfortunately, other threads could perform CRUD operations while this session is still open, taking the persisted context out of sync with the database table. So I'm not a fan of this approach either. Is there any good way to do this, or are these the only options available? A: JPA does not allow you to reattach detached objects. The JPA specification defines the merge() operation. The operation seems to be useful to implement the described use case. Please refer to the specification: 3.2.7.1 Merging Detached Entity State The merge operation allows for the propagation of state from detached entities onto persistent entities managed by the entity manager. The semantics of the merge operation applied to an entity X are as follows: * *If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created. *If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'. *If X is a removed entity instance, an IllegalArgumentException will be thrown by the merge operation (or the transaction commit will fail). *If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value cascade=MERGE or cascade=ALL annotation. *For all entities Y referenced by relationships from X having the cascade element value cascade=MERGE or cascade=ALL, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.) *If X is an entity merged to X', with a reference to another entity Y, where cascade=MERGE or cascade=ALL is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y. The persistence provider must not merge fields marked LAZY that have not been fetched: it must ignore such fields when merging. Any Version columns used by the entity must be checked by the persistence runtime implementation during the merge operation and/or at flush or commit time. In the absence of Version columns there is no additional version checking done by the persistence provider runtime during the merge operation. — JSR 338: JavaTM Persistence API, Version 2.1, Final Release. A: I guess you need JPA merge together with optimistic locks (Version based field in your entity). If the entity was changed you won't be able to save it back. So detach it and merge back (including the version). There is still business logic question what to do if object is changed, retry with the updated values or send an error to end user but final decision is not technology issue/
{ "language": "en", "url": "https://stackoverflow.com/questions/45734475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Codeblock compiled exe link to a dll without system-path-variable (C++) I'm creating a small framework which multiple programmers is working on at the same time. We are all working on windows 7 machines with Code::Blocks, MinGW and C++. We are using OpenCV in this project. Is there a way where the dll's used in the project can be copied into the folder with the compiled executable. Or is there a way where that we can tell the executable that the dll is in one of the parent folders without defining a new path in the windows system-path-variable? Thank you all in advance! A: I'm not familiar with Code::Blocks, but Visual Studio has a concept of a post-build event. After a successful build, Visual Studio will execute instructions (DOS commands) listed in the post-build events section of a project's properties. I'm sure Code::blocks will have a similar mechanism. You could use this to copy the DLLs to wherever you need them. You should also be aware of the DLL search order on Windows. You could also copy the DLLs to a standard location, and your program will look for them there, if they're not found in the same folder as the executable. I wouldn't be too afraid of modifying the Path variable, it's less permanent than copying various DLLs all over the place! Sounds like an interesting project. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/9386326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring jpa hibernate how to map a relationship to multiple objects of the same entity I am creating an airline application using Spring boot, and there is an entity called Flight that has two attributes of the same entity: public class Flight { // more code here @ManyToOne @JoinColumn(name = "airport_id", referencedColumnName = "id") private Airport startLocation; @ManyToOne @JoinColumn(name = "airport_id", referencedColumnName = "id") private Airport destination; // more code here } An airport has a OneToMany relationship of a List of flights. How can I correctly map this relationship? Spring now gives me the error: mappedBy reference an unknown target entity property (airport-flights) Thanks in advance. A: Inside the airport entity, the mappedBy reference should be like the following... @OneToMany(mappedBy = "startLocation") @OneToMany(mappedBy = "destination") A: Define a relationship in Airport Entity, and specify the property mappedBy="". MappedBy basically tells the hibernate not to create another join table as the relationship is already being mapped by the opposite entity of this relationship. That basically refers to the variables used in Flight Entity like startLocation and destination. It should look like this:- public class Airport { ... @OneToMany(mappedBy = "startLocation") private Flight flight_departure_location; @OneToMany(mappedBy = "destination") private Flight flight_destination; } It should be something like this.
{ "language": "en", "url": "https://stackoverflow.com/questions/69714446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read GPIO status from server I have a raspberry PI install on a client (with windows iot OS). My question is how can I access remotely to Pin Status of RPI from another client? I installed PIGPIO to connect remotely with IP and port PiGPIO.PigsClient piClient= new PiGPIO.PigsClient("192.168.1.36", 5463); await piClient.ConnectAsync(); if (piClient.IsConnected) { piClient.READ(6); //pin number } but port is not open on RPI. What is the best solution on this case? Thank You A: if you want to connect to a Windows IoT Core raspberry-pi computer and wish to control GPIO remotely over the internet, you could download w3pi.info web-server and download the flipled atl server (visual c++) sample (requires raspberry pi 2). The flipled sample is configured to read the LED light on the raspberry pi 2 board, but you could re-code the sample to use a different pin number.
{ "language": "en", "url": "https://stackoverflow.com/questions/56544441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add a downward force to an Instantiated prefab? I am trying to get my prefabs to just fall at some speed. Right now they get created and then gravity acts on it, so it starts off slow and then builds as it is in the air. I want it to be a constant speed from the moment it is created. I have tried doing an AddForce, but that doesn't seem to work. void Wave1() { Debug.Log("Wave1"); delay = .5f; Instantiate(smallFlame, new Vector3(drop1, dropHeight, 0), Quaternion.identity); Instantiate(smallFlame, new Vector3(drop2, dropHeight, 0), Quaternion.identity); Instantiate(smallFlame, new Vector3(drop3, dropHeight, 0), Quaternion.identity); smallFlame.GetComponent<Rigidbody2D>().AddForce(new Vector2(0, fallSpeed), ForceMode2D.Impulse); } A: Just add to their position in the update loop rather than using the physics engine. void Update() { transform.position += Vector3.down * Time.deltaTime; } This will move any object that it is attached to down at a constant rate. Put this in a script and add it to the prefab that you are instantiating. A: I Think you should set to zero the "Gravity Scale" of the RigitBody2D atached to the smallFlame. This should stop the acceleration. To add moviment to them. Use Rigitbody2D.velocity
{ "language": "en", "url": "https://stackoverflow.com/questions/37106861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Replace text within a file Hello I've tried a lot of researching but cant find what I need and haven't been able to successfully piece this together myself. Each of my users have a XML file within their profile that I would like to edit. The file contains a reference to their computer name and clientname, which are out of date each time they login to a new terminal. I need to replace these with the current computername and clientname. The bit I cannot figure out how to do is how to search the XML for the computername when I only know the first few characters, then replace it. my XML will have any entry something like this "InstalledPrinter name="\WHBCVDI0109\LabelPrinter650 (from IGEL-00E0C533943E)" I need to search the file and replace the WHBCVDI0109 and the IGEL-00E0C533943E with the correct entries. My script successfully gets those entries I just dont know how to find and replace them in the file. My script looks like this: Const ForReading = 1 Const ForWriting = 2 Set oShell = CreateObject( "WScript.Shell" ) 'Get Variables user=oShell.ExpandEnvironmentStrings("%UserName%") appdata=oShell.ExpandEnvironmentStrings("%appdata%") strComputerName = oshell.ExpandEnvironmentStrings( "%COMPUTERNAME%" ) 'Set XML location strfile = appdata & "\Smart Label Printer\SlpUserConfig.xml" 'Open Set objfso = CreateObject("Scripting.FileSystemObject") Set filetxt = objfso.OpenTextFile(strfile, ForWriting) strTemp = "HKEY_LOCAL_MACHINE\SOFTWARE\Citrix\ICA\Session\ClientName" WScript.Echo "client name is : " & oShell.RegRead(strTemp) An pointers would be much appreciated. A: You shouldn't use the FileSystemObject and String/RegExp operations to edit an XML file. Using the canonical tool - msxml2.domdocument - is less error prone and scales much better. See here for an example (edit text); or here for another one (edit attribute). If you publish (the relevant parts of) your .XML file, I'm willing to add same demo code specific for your use case here.
{ "language": "en", "url": "https://stackoverflow.com/questions/32252562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Triggering lesser reflows in JavaScript - How to edit elements in cloned element? I have this HTML structure: <p id="lorem"> <span class="part" id="n01">L</span><span class="part" id="n02">o</span><span class="part" id="n03">r</span><span class="part" id="n04">e</span><span class="part" id="n05">m</span> <span class="part" id="n06">i</span><span class="part" id="n07">p</span><span class="part" id="n08">s</span><span class="part" id="n09">u</span><span class="part" id="n10">m</span> </p> ​<h1>Click Me</h1>​​​​​​​​​​​​​​​​​ and this JavaScript code: ​arrRed = ["#n01", "#n04", "#n05", "#n09"];​​​​​​​​​ arrBlue = ["#n02", "#n07", "#n08"]; $("h1").click(function(){ $.each(arrRed, function( i, v ){ $(v).addClass("red"); }); $.each(arrBlue, function( i, v ){ $(v).addClass("blue"); }); }) http://jsfiddle.net/FF2Dr/ When the h1 is clicked, certain letters get a certain color. The problem with that is the performance, I trigger too much reflows/repaints. ​ In another question someone told me to use parent.cloneNode(true) and parent.parentNode.replaceChild(clone, parent). So I clone the elements, change them and but them back in place, triggering only one reflow. So I cloned the parent element: var doc = document; var lorem = doc.getElementById("lorem"); var clone = lorem.cloneNode(true) But how do I have to proceed now? I somehow have to modify the elements in clone and then replace them, but using $.each again to edit them does not seem to be a good idea. http://jsfiddle.net/FF2Dr/1/ A: Try this: $("h1").click(function(){ var lorem = $("#lorem"), clone = lorem.clone(true); clone.children().filter(function() { return $.inArray('#' + this.id, arrRed) != -1; }).addClass("red").end().filter(function() { return $.inArray('#' + this.id, arrBlue) != -1; }).addClass("blue"); lorem.replaceWith(clone); }); Fiddle Create a clone, filter the children of this new cloned element twice to apply the classes and finally replace the old element entirely with the new one. Or, if you prefer, using find instead of filter while iterating over the arrays: $("h1").click(function(){ var lorem = $("#lorem"), clone = lorem.clone(true); $.each(arrRed, function(i, v) { clone.find(v).addClass("red"); }); $.each(arrBlue, function(i, v) { clone.find(v).addClass("blue"); }); lorem.replaceWith(clone); }); Fiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/11518129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to replace inline comment a full-line comment for Fortran file I am handling several large Fortran code files and I encounter a tricky problem, which is I want to make inline comment a full-line comment. Clearly it is absurd to do it manually line by line. All characters following an exclamation mark, !, except in a character string, are commentary, and are ignored by the compiler. That is to say change x = 9 !initialize x to x = 9 !initialize x That would be great if it can be implemented via vim or atom. Code example ex.f90 subroutine sample_photon(e0,zz,sgam,ierr) use EBL_fit use constants use user_variables, only : ethr,model use internal, only : debug implicit none integer ierr,nrej,nrejmax,nrenorm real(kind=8) e0,zz,sgam,de,emin,emin0 & ,etrans1,etrans2,aw1,aw2,aw3,gb,gb0,gbmax,gbnorm,rrr,gnorm1,gnorm2,gnorm3 real(kind=8) psran,sigpair,w_EBL_density de=4.d0*e0 emin0=ame**2/e0 ! minimal required energy for EBL photon if (emin0.ge.eirmax) then ! wrong kinematics !!! write(*,*)'photon:',emin0,eirmax,e0 ierr=1 return end if nrej=0 nrejmax=3000 ! user-defined limit on the N of rejections nrenorm=0 gbmax=0.d0 gbnorm=2.5d0 ! normalization factor for rejection etrans1=1.d-6 ! parameters for 'proposal function' etrans2=eirmin*(1.d0+zz)**1.25 ! partial weights for different energy intervals for 'proposal function ! sample emin (= sgam/de) according to the 'proposal function'; ! define 'rejection function' ( gb = f(emin) / f_proposal(emin) ) sgam=emin*de ! c.m. energy for gamma-gamma interaction gb=w_EBL_density(emin,zz)*sigpair(sgam)*emin/gb0 ! if (gb.gt.1.d0.and.nrenorm.eq.0) write(*,*)'sample_cmb(photon): gb=' & ! ,gb,nrenorm,emin,emin0,emin0/etrans2 !/1.d3 if (psran().gt.gb) then ! rejection nrej=nrej+1 ! total number of rejections for current sampling gbmax=max(gbmax,gb) ! maximal value for rejection function if(nrej.gt.nrejmax)then ! too many rejections if(gbmax.le.0.d0)then ! wrong kinematics write(*,*)'photon: gbmax=0!!!' ierr=1 return else ! write(*,*)'nrej(gamma)>nrejmax',nrej,emin0/etrans2,nrenorm,e0/1.d12,gbmax gbnorm=gbnorm*gbmax*2.d0 ! change normalization for the rejection function gbmax=0.d0 nrenorm=nrenorm+1 nrej=0 endif endif goto 1 ! new try end if end subroutine sample_photon A: Let's build this gradually, and start with a simple substitution that prepends a newline (\r) to any sequence of comment prefixes (!): :%substitute/!\+.*$/\r&/ This leaves behind trailing whitespace. We can match that as well, and use a capture group (\(...\)) for the actual comment. This removes the whitespace: :%substitute/\s*\(!\+.*$\)/\r\1/ But it still matches comments at the start of a line, and introduces an additional empty line in front. We can add a lookbehind assertion that the line must not start with a !, but this now gets ugly: :%substitute/^\%(^[^!].*\)\@=.*\zs\s*\(!\+.*$\)/\r\1/ Instead, it's easier to use another Vim command, :global (or its inverted sister :vglobal), to only match lines not starting with !, and then apply the :substitute there: :%vglobal/^!/substitute/\s*\(!\+.*$\)/\r\1/ The final requirement is that exclamation marks within strings should be kept. This would add another regular expression, and integrating it into the overall match would be really hard, and could probably be only done approximately. Fortunately, with syntax highlighting, Vim already knows what is a Fortran string! My PatternsOnText plugin has (among others) a :SubstituteIf / :SubstituteUnless combo that can do substitutions only if a condition is true / false. The library it depends on provides a wrapper around synIdAttr() that makes it easy to define a predicate for Fortran strings: function! IsFortranString() return ingo#syntaxitem#IsOnSyntax(getpos('.'), '^fortranString') endfunction We then only need to replace :substitute with :SubstituteUnless + predicate: :%vglobal/^!/SubstituteUnless/\s*\(!\+.*$\)/\r\1/ IsFortranString() The same can also be achieved without the plugin (using :help sub-replace-special and synstack() / synIdAttr()), but it'd be more complex.
{ "language": "en", "url": "https://stackoverflow.com/questions/52278484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Resize family instance during the insertion I'm creating an addin for Revit 2014. I want to insert a parallelepiped inside a project, the parallelepiped must have the width, depth, and/or height set during the insertion. I've created a family with a cube of 1x1x1 and 3 instance parameters that automatically resizes the cube accordingly to them values (parameters are named "Width", "Depth", Height"). If I import the family in the drawing and place an instance of it, and AFTER the placement I change the parameter, then the cube is resized correctly. I wonder if there is a way to resize the cube BEFORE inserting an instance inside the project, I want that the preview under the mouse cursor has the correct size. I'm using the following instructions in order to place the instance: Application.ActiveUIDocument.PromptForFamilyInstancePlacement(familySymbol); Thank you A: I agree with everything said above. Yes, you can only change the family instance dimension parameter values after the instance has been placed. Yes, you could define different types for different values, and then place the type. You could create those types on the fly immediately before placing the instance. In Revit 2015, you can define which family type is placed by PromptForFamilyInstancePlacement. Where do the width and height etc. come from? Can you determine them immediately before the call to PromptForFamilyInstancePlacement? If so, then you could create a new family type with those dimensions on the fly and set that to be the active type right before the call to PromptForFamilyInstancePlacement. Cheers, Jeremy. A: I believe the only solution to resizing the element before placement would be to create different family types for each size you need. Depending on your needs, this may or may not be a practical solution. The rest of my answer is focused on manipulating the elements after placement. Do you need your users to be able to select the location of the placement? If not, then you can use the NewFamilyInstance method to place the element (there is no preview, and you must provide a location point). This function returns the element that was just placed, so you would be able to modify it after placement. You may be able to use the Selection.PickPoint method to allow the user to pick a point for placement which you can pass to NewFamilyInstance, but I'm not sure how this works with elevations. The alternative is to use a FilteredElementCollector after the element has been placed. You could use a FamilyInstanceFilter to find all of the instances of the FamilySymbol you are using. Since Revit ElementId's increase as new elements are placed (with some exceptions due to worksharing/synchronizing that aren't relevant here), you could retrieve the element with the highest ElementId and safely assume that it's the one you just placed. Another suggestion would be to run the FilteredElementCollector before you place your elements, and then run it again after. The difference would be the element/s that you just placed. A: Doesn't the familySymbol object have the get_Parameter() method? I think you can use it to achieve your goal.
{ "language": "en", "url": "https://stackoverflow.com/questions/21913344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python: Replacing unknown number of string variables I need to define a function to go through a string and replace all replacement fields, without knowing how many there will be. I do know that the replacement fields will be named a specific way. For example, If i know that all fields will be named 'name' & 'position': Test1 = "I think {name} should be our {position}. Only {name} is experienced. Who else could be a {position}?" Test2 = "{name} is the only qualified person to be our {position}." I need one function that would process both of these the same way, with output like: >>Test1 = ModString(Test1) >>Test2 = ModString(Test2) >>Test1 >>'I think Mary should be our boss. Only Mary is experienced. Who else could be a boss?' >>Test2 >>'Mary is the only qualified person to be our boss.' I feel like this should be simple, but my mind can't seem to get past the multiples and the unknown quantity. A: str.format() I got too in my head about this. A: bphi is right, use string formatting e.g. test1 = "I think {name} should be our {position}. Only {name} is experienced. Who else could be a {position}?" test1.format(name="Bob", position="top cat") > 'I think Bob should be our top cat. Only Bob is experienced. Who else could be a top cat?' A: def ModString(s, name_replacement, position_replacement): return s.replace("{name}",name_replacement).replace("{position}", position_replacement) Then: Test1 = ModString(Test1, "Mary", "boss") Test2 = ModString(Test2, "Mary", "boss") or you can just use .format(), which is recommended def ModString(s, name_replacement, position_replacement): return s.format(name=name_replacement, position=position_replacement) A: You have to use replace() Method, for example, read here: https://www.tutorialspoint.com/python/string_replace.htm Test1 = "I think {name} should be our {position}. Only {name} is experienced. Who else could be a {position}?" Test2 = "{name} is the only qualified person to be our {position}." def ModString(str, name, position): str = str.replace("{name}", name) str = str.replace("{position}", position) return str Test1 = replaceWord(Test1, "Mary", "boss") Test2 = replaceWord(Test2, "Mary", "boss")
{ "language": "en", "url": "https://stackoverflow.com/questions/52450808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: std::async blocks even with std::launch::async flag depending on whether the returned future is used or ignored Description of the problem std::async seems to block even with std::launch::async flag: #include <iostream> #include <future> #include <chrono> int main(void) { using namespace std::chrono_literals; auto f = [](const char* s) { std::cout << s; std::this_thread::sleep_for(2s); std::cout << s; }; std::cout << "start\n"; (void)std::async(std::launch::async, f, "1\n"); std::cout << "in between\n"; (void)std::async(std::launch::async, f, "2\n"); std::cout << "end\n"; return 0; } output shows that the execution is serialized. Even with std::launch::async flag. start 1 1 in between 2 2 end But if I use returned std::future, it suddenly starts to not block! The only change I made is removing (void) and adding auto r1 = instead: #include <iostream> #include <future> #include <chrono> int main(void) { using namespace std::chrono_literals; auto f = [](const char* s) { std::cout << s; std::this_thread::sleep_for(2s); std::cout << s; }; std::cout << "start\n"; auto r1 = std::async(std::launch::async, f, "1\n"); std::cout << "in between\n"; auto r2 = std::async(std::launch::async, f, "2\n"); std::cout << "end\n"; return 0; } And, the result is quite different. It definitely shows that the execution is in parallel. start in between 1 end 2 1 2 I used gcc for CentOS devtoolset-7. gcc (GCC) 7.2.1 20170829 (Red Hat 7.2.1-1) Copyright (C) 2017 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. My Makefile is: .PHONY: all clean all: foo SRCS := $(shell find . -name '*.cpp') OBJS := $(SRCS:.cpp=.o) foo: $(OBJS) gcc -o $@ $^ -lstdc++ -pthread %.o: %.cpp gcc -std=c++17 -c -g -Wall -O0 -pthread -o $@ $< clean: rm -rf foo *.o Question Is this behaviour in the specification? Or is it a gcc implementation bug? Why does this happen? Can someone explain this to me, please? A: The std::future destructor will block if it’s a future from std::async and is the last reference to the shared state. I believe what you’re seeing here is * *the call to async returns a future, but *that future is not being captured, so *the destructor for that future fires, which *blocks, causing the tasks to be done in serial. Explicitly capturing the return value causes the two destructors to fire only at the end of the function, which leaves both tasks running until they’re done.
{ "language": "en", "url": "https://stackoverflow.com/questions/61788498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: using clEnqueueNativeKernel in OpenCL Is there any example of using clEnqueueNativeKernel in OpenCL? In this way one can write a kernel in a c or c++ language. Do other commands remain unchanged? A: Native C++ "kernels" are essentially just functions that you want to execute within command queue to preserve order of commands. AFAIK they are not supported on GPU. If you want to execute C++ functions across all devices, you should consider to use cl_event callbacks (when status == CL_COMPLETE). Assume you have a buffer object you want to read from device and pass to your C++ function. Also you want to pass some integer value as well (I use C++ OpenCL wrapper): // First of all, we should define a struct which describes our arguments list. struct Arguments { int integer; void* buffer_host; }; // Define C/C++ function you want to call. void CFunction(void *args) { Arguments args = reinterpret_cast<Arguments*>(args); // Do something with args->integer and args->buffer_host. } // ... Arguments args = {.integer = 0, .buffer_host = NULL}; // First, we should define Buffer objects in arguments. std::vector<cl::Memory> buffers_dev; buffers_dev.push_back(a_buffer); // Then we should define pointers to *pointer in args* which will be set // when OpenCL read data from buffers_dev to the host memory. std::vector<const void*> buffers_host; buffers_host.push_back(&args.buffer_host); // Finally, set integer args.integer = 10; queue.enqueueNativeKernel(CFunction, std::make_pair(&args, siezof(Arguments)), &buffers_dev, &buffers_host); // At this point args were copied by OpenCL and you may reuse or delete it.
{ "language": "en", "url": "https://stackoverflow.com/questions/10140494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamically resolve C stdlib functions from .NET I want to resolve the addresses of functions like those from the C stdlib such as malloc at run-time from .NET code (so I can JIT machine code that calls to these addresses for my VM). I believe I should use LoadLibrary and GetProcAddress supplying the kernel32.dll but this does not work. Using F# interactive I get: > [<DllImport("kernel32.dll", CharSet=CharSet.Ansi, SetLastError=true)>] extern IntPtr LoadLibrary(string fileName);; val LoadLibrary : string -> IntPtr > [<DllImport("kernel32.dll", CharSet=CharSet.Ansi, SetLastError=true)>] extern uint32 GetProcAddress(IntPtr hModule, string fn);; val GetProcAddress : IntPtr * string -> uint32 > let kernel32 = LoadLibrary @"kernel32.dll";; val kernel32 : IntPtr = 1993146368n > let malloc = GetProcAddress(kernel32, "malloc");; val malloc : uint32 = 0u So this appears to have obtained a handle to the DLL but trying to resolve malloc has returned a NULL pointer. How should I do this? A: AFAIK mallocis NOT part of kernel32.dll. It is part of the MS C runtime DLLs - since you don't provide any details about how/where you want to use this just some links with relevant information: * *http://msdn.microsoft.com/en-us/library/abx4dbyh.aspx *http://www.codeproject.com/Articles/20248/A-Short-Story-about-VC-CRT Basically you have to load the respective DLL and then resolve the needed function, as an example: let SomeMSCRT = LoadLibrary @"SomeMSCRT.dll";; let malloc = GetProcAddress(SomeMSCRT, "malloc");; One note though: Depending on what exactly you want to do you might run into serious and hard to debug problems - for example using malloc from F# is IMHO a bad idea... you need to keep in mind that the C runtime needs proper initialization (in case of MS CRT you need to call CRT_INIT as the very first thing) etc. The C runtime is NOT aware of any .NET specifics and thus may lead to unstable behaviour... esp. since the CLR might be using the CRT (perhaps a different version) internally... Another point: Generating machine code at runtime and executing it by jumping into that memory area is subject to several security measures (depending on Windows version etc.). You might need to mark the respective memory segment as "executable" which is NOT possible via C runtime, it is only possible using Windows API calls (like VirtualAllocEx) with proper permissions... see for a starting point here and here. A: I don't believe malloc is part of kernel32.dll. However, if I recall correctly, all malloc implementations eventually drill down to HeapAlloc, which is available in kernel32.dll. A: I want to resolve the addresses of functions like those from the C stdlib There's your problem. You speak as if there's a single C runtime library. In fact there are many. Every compiler provides its own, in several different flavors (debug, release, static link, dynamic link) and all of these are mutually incompatible. If you knew which one you were trying to use, the answer to your question would become obvious. If you want the OS-provided libraries shared between all Windows applications, then kernel32.dll is the correct place to look, but the functions conform to the Win32 API specification, not the ANSI or ISO C standard.
{ "language": "en", "url": "https://stackoverflow.com/questions/9930730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: flex not working in firefox 53 Bit stuck here. I am testing my site with Firefox 53. The pages are not filling the full height. I verified on Chrome and Safari and all looks well. I verified with www.caniuse.com that Firefox 53 supports Flex. Still the page does not render correctly. Here is the site http://actionmary.com/newSite/contact.html. Try on Chrome where it renders correctly and Firefox 53 where it does not. Here is the Relevant CSS html{ background-color: black; } body { /*min-width:800px; suppose you want minimun width of 1000px */ /*width: auto !important; Firefox will set width as auto */ width:100%; margin:0; font-family: 'futura-pt', sans-serif; font-style: normal; font-weight: 400; display: flex; flex-flow: column; background-repeat:no-repeat; background-size:cover; } .content { width: 100%; flex: 1 1 auto; overflow: hidden; } A: You're working with percentage heights. For example: .blackbox { min-height: 23%; } You're also not defining a height on parent elements, which some browsers require in order to render a percentage height on the child. You can expect rendering variations among browsers with this method. For a reliable, cross-browser solution, give the body element: height: 100vh; Or, if you want the body to expand with content: min-height: 100vh; More details here: * *Working with the CSS height property and percentage values *Chrome / Safari not filling 100% height of flex parent
{ "language": "en", "url": "https://stackoverflow.com/questions/43548008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Strange behavior when reading and writing "float" and "double" types in C When I put 1 for example this return 1.000 (that's fine to me): #include <stdio.h> main() { float num; printf("Double: "); scanf("%f", &num); printf("%f\n", num); } So, when I put 1 at this it returns 0.000. I don't understand because I used %f to read and write correctly. Can you guys explain me? #include <stdio.h> main() { double num; printf("Double: "); scanf("%f", &num); printf("%f\n", num); }
{ "language": "en", "url": "https://stackoverflow.com/questions/37971950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: INVALID_BLOB_KEY on retrieving image from Google Cloud storage using java I'm trying to use Google Cloud storage to store images that I'll be using in jsp files. I've created the bucket, uploaded an image (for testing purposes) and try to retrieve a Url to it from a java class. I keep getting the error message HTTP ERROR 500 Problem accessing /. Reason: INVALID_BLOB_KEY: Could not read blob. Caused by: java.lang.IllegalArgumentException: INVALID_BLOB_KEY: Could not read blob. at com.google.appengine.api.images.ImagesServiceImpl.getServingUrl(ImagesServiceImpl.java:282) The Bucket I created The code I use to retrieve the Url (BUCKETNAME is a static string with the name of the bucket) public static String getImageURL(String inFilename) { String key = "/gs/" + BUCKETNAME + "/" + inFilename; ImagesService imagesService = ImagesServiceFactory.getImagesService(); ServingUrlOptions options = ServingUrlOptions.Builder.withGoogleStorageFileName(key); String servingUrl = imagesService.getServingUrl(options); return servingUrl; } I've tried to make the image public, but that didn't help. I've looked through various answers here, but I'm a bit lost. Any help would be appreciated A: I also faced the same issue. For future people, make sure you have made the bucket public. From the same method you can also generate thumbnails and secured urls to your images public static String getImageURL(String inFilename) { String key = "/gs/" + BUCKETNAME + "/" + inFilename; ImagesService imagesService = ImagesServiceFactory.getImagesService(); ServingUrlOptions options = ServingUrlOptions.Builder .withGoogleStorageFileName(key).imageSize(150).secureUrl(true); String servingUrl = imagesService.getServingUrl(options); return servingUrl; }
{ "language": "en", "url": "https://stackoverflow.com/questions/35253044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to search an encrypted attribute? I have a sensitive attribute that must be encrypted at all times except during display (not my rule and I think it's overkill, but I must follow this rule). Additionally, the secret used to encrypt/decrypt this data must not be on or accessible through the database. So currently I have a session for the user that stores their encrypted password and decrypts this data when needed. However, now I need to find records by the encrypted attribute. I currently utilize ActiveSupport::MessageEncryptor for encryption/decryption of the attribute. Here's the direction I think I should go to accomplish this: decryptor = ActiveSupport::MessageEncryptor.new(encrypted_password) Family.where("decryptor.decrypt_and_verify(name) == ?", some_search_name) Obviously the first side of that condition does not work as-is, but I need some way to do that. Any ideas? A: Quick Primer to Passwords in the DB This goes to show that encryption in the database is hard, and that you shouldn't do it unless you have thought carefully through your threat model and understand what all the tradeoffs are. To be honest, I have serious doubts that an ORM can ever give you the security you need where you need encryption (for important knowledge reasons), and on PostgreSQL, it is particularly hard because of the possibility of key disclosure in the log files. In general you really need to properly protect both encrypted and plain text with regard to passwords, so you really don't want a relational interface here but a functional one, with a query running under a totally different set of permissions. Now, I can't tell in your example whether you are trying to protect passwords, but if you are, that's entirely the wrong way to go about it. My example below is going to use MD5. Now I am aware that MD5 is frowned upon by the crypto community because of the relatively short output, but it has the advantage in this case of not requiring pg_crypto to support and being likely stronger than attacking the password directly (in the context of short password strings, it is likely "good enough" particularly when combined with other measures). Now what you want to do is this: you want to salt the password, then hash it, and then search the hashed value. The most performant way to do this would be to have a users table which does not include the password, but does include the salt, and a shadow table which includes the hashed password but not the user-accessible data. The shadow table would be restricted to its owner and that owner would have access to the user table too. Then you could write a function like this: CREATE OR REPLACE FUNCTION get_userid_by_password(in_username text, in_password text) RETURNS INT LANGUAGE SQL AS $$ SELECT user_id FROM shadow JOIN users ON users.id = shadow.user_id WHERE users.username = $1 AND shadow.hashed_password = md5(users.salt || $2); $$ SECURITY DEFINER; ALTER FUNCTION get_userid_by_password(text, text) OWNER TO shadow_owner; You would then have to drop to SQL to run this function (don't go through your ORM). However you could index shadow.hashed_password and have it work with an index here (because the matching hash could be generated before scanning the table), and you are reasonably protected against SQL injections giving away the password hashes. You still have to make sure that logging will not be generally enabled of these queries and there are a host of other things to consider, but it gives you an idea of how best to manage passwords per se. Alternatively in your ORM you could do something that would have a resulting SQL query like: SELECT * FROM users WHERE id = get_userid_by_password($username, $password) (The above is pseudocode and intended only for illustration purposes. If you use a raw query like that assembled as a text string you are asking for SQL injection.) What if it isn't a password? If you need reversible encryption, then you need to go further. Note that in the example above, the index could be used because I was searching merely for an equality on the encrypted data. Searching for an unencrypted data means that indexes are not usable. If you index the unencrypted data then why are you encrypting it in the first place? Also decryption does place burdens on the processor so it will be slow. In all cases you need to carefully think through your threat model and ask how other vulnerabilities could make your passwords less secure.
{ "language": "en", "url": "https://stackoverflow.com/questions/18086060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Loading kendo.timezone in to page I want to use timezone feature provided by Kendo. It is not bundled with kendo.all.js. As per documentation I have to include kendo.timezone.js into page before using timezone features. My development environment includes - fully built kendo.all.js and requirejs Now the issue is kendo.timezone.js is written as AMD compliant specifying dependency on ./kendo.core which causes requirejs to load kendo.core.js. It results into requirejs error 'kendo.core.js not present'. To avoid this error either I have to rename my file to kendo.core.js or I have to modify kendo.timezone.js to depend on kendo.all.js. Which is better of the two solutions(licensing and maintenance problems)? Is there any better way to include kendo.timezone.js into my page? A: I had similar problem and solved it adding map in the rjs config like this: map: { '*': { 'kendo.core.min': 'kendo' } } It seems to work :)
{ "language": "en", "url": "https://stackoverflow.com/questions/30372945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iOS "specialized" TableView Crash I am getting this crash report in Xcode from a little application I am currently running. When I open the crash in the project I do not get anymore information made available to me. My cellForRowAt function is below. This is my first iOS application and I am not sure what is causing this crash. The crash seems to be very intermittent. The application can hours or even days without crashing and then will suddenly crash, usually while in the background. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "eventCell", for: indexPath) as! eventTableCell let eventData = LocationService.locationInstance.eventLogArray[indexPath.row] let approval = eventData.approved if approval == false { cell.imageView?.image = UIImage(named: "unapproved") } else { cell.imageView?.image = UIImage(named: "approved") } cell.textLabel?.text = "\(LocationService.locationInstance.eventLogArray[indexPath.row].customer) \(secondsToHoursMinutesString(seconds: Int(LocationService.locationInstance.eventLogArray[indexPath.row].duration * 60)))" return cell } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var eventData:Int print ( LocationService.locationInstance.eventLogArray.count) if LocationService.locationInstance.eventLogArray.count == 0 { eventData = 0 notifyTableIsEmpty() } else { notifyTableNotEmpty() eventData = LocationService.locationInstance.eventLogArray.count } return eventData } Table cell class: import Foundation import UIKit class eventTableCell: UITableViewCell { @IBOutlet weak var customerName: UILabel! @IBOutlet weak var customerTime: UILabel! }
{ "language": "en", "url": "https://stackoverflow.com/questions/50987364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Media Player not removed using MediaSource and webRTC streaming I am trying to stream multiple media files (sequentially) from one webRTC device to another using the mediasource API on the receive side. The files are received and played on the same video source element on the page but each time i stream a new file (or the sameone over again), a player shows up on the Google chrome://media-internals/ but the other players from the prior transmissions are also still shown. My concern is that resources have been allocated but are not released (or more likely i am not doing something correctly) when a new mediasource is allocated for the new stream (from the webRTC). Any thoughts on how to explicitly release or remote a mediasource which was allocated and played? A: I would suggest using a different peer connection for each stream and in addition you should call stop() on the media stream. As part of the clean up between playback instances, you may also want to clear the link to the stream in the element like so: if (moz) { document.getElementById('yourvideoelementid').mozSrcObject = undefined; } else { document.getElementById('yourvideoelementid').src = ""; } The moz indicates the browser is Mozilla/Firefox.
{ "language": "en", "url": "https://stackoverflow.com/questions/28015426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: facebook like button won't show comment box I have created a site that includes facebook 'like' buttons (see http://www.rupertheath.com) and they work except, when you click them, no comment box appears. When I first installed the buttons, the comment box did appear but I've spent some time styling the buttons (for positioning) and seem to have stopped that functionality working. Can anyone explain why? A: Problem is, you set overflow: hidden on a parent container: <div class="socialmediabuttons"> .... </div> Remove that style and the comment box should reappear. Note that you need to change other styles as well as it will break the hairlines around the social media buttons (but it is doable). EDIT Try something along the lines of: .socialmediabuttons { border-bottom: 1px solid #CCCCCC; border-top: 1px solid #CCCCCC; + height: 26px; margin-bottom: 25px !important; margin-left: 20px; - overflow: hidden; padding: 5px 0 3px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/14430598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a MAVLink mission commands list available? I am new to Dronekit. I was wondering if there is place where I can find a list of all the available mission commands. A: For a complete list of mission commands, see the MAV_CMD section in this list at https://pixhawk.ethz.ch. Not every flight controller that speaks mavlink implements every mission command. You'll need to research your particular flight control software to see what it supports. You'll also need to learn what each command does and how it is used, which isn't always obvious. This page at the ArduPilot wiki is a good place to start, because it describes the commands implemented by a popular flight controller (ArduCopter), describes what the commands do, and exactly what the command parameters mean: http://copter.ardupilot.com/wiki/mission-planning-and-analysis/mission-command-list/ You will have to do a little translation because that page uses command names as they show up in a ground control station; For example Takeoff -> MAV_CMD_NAV_TAKEOFF, Condition-Delay -> MAV_CMD_CONDITION_DELAY. There are a lot of commands, and some of them are esoteric, but to fly a basic mission where the vehicle takes off, flies through some waypoints, and then lands, you only need a few commands: MAV_CMD_NAV_TAKEOFF MAV_CMD_NAV_LAND MAV_CMD_NAV_WAYPOINT A: The best list of mission commands for ArduPilot flight controller is MAVLink Mission Command Messages (MAV_CMD). This lists all the mission commands and parameters that are actually supported on all of the vehicle platforms (which is not quite the same thing as what information is listed in the MAVLink protocol definition. If you're working on Copter, the Copter Mission Command List is useful for working with Mission Planner. However it is not quite as useful for working with DroneKit as it doesn't map the actual command parameters. If you're working on any other flight controller then you'll have to work out what set of commands they support. A: Just started looking at DroneKit myself, so hopefully others will chime in to better answer your question. The DroneKit API documentation identifies the built in commands here: http://python.dronekit.io/automodule.html That said, it looks like the DroneKit function send_mavlink() should allow you to send any mavlink message to your vehicle, in the event that there is a specific mavlink command not available in DroneKit. I think this is where you can find the list of mavlink message types: https://pixhawk.ethz.ch/mavlink/ Good luck
{ "language": "en", "url": "https://stackoverflow.com/questions/29527513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: To change data adapter from jdbc to jpa I used connection from jdbc tu fill my report in jasperreport. Now I have changed tecnology to connect to my db and I use jpa with Hibernate. When I try to connect to my db from Jaspersoft Studio, I get this exception: net.sf.jasperreports.engine.JRException: java.lang.reflect.InvocationTargetException at net.sf.jasperreports.data.ejbql.EjbqlDataAdapterService.contributeParameters(EjbqlDataAdapterService.java:95) at com.jaspersoft.studio.data.reader.DatasetReader.start(DatasetReader.java:190) at com.jaspersoft.studio.property.dataset.dialog.DataPreviewTable$4.run(DataPreviewTable.java:248) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at net.sf.jasperreports.data.ejbql.EjbqlDataAdapterService.contributeParameters(EjbqlDataAdapterService.java:79) ... 3 more Caused by: java.lang.NoSuchMethodError: javax.persistence.OneToMany.orphanRemoval()Z at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:2021) at org.hibernate.cfg.AnnotationBinder.processIdPropertiesIfNotAlready(AnnotationBinder.java:895) at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:728) at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3625) at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3579) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1381) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1786) at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96) at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915) at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:900) at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:59) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:60) ... 8 more In my classpath there is this list of library: Now I use the JRBeanCollectionDataSource class to pass a collection of bean to my report: JRBeanCollectionDataSource beanCollectionDataSource=new JRBeanCollectionDataSource(lista); jp = JasperFillManager.fillReport(JASPER_REPORT_FOLDER + "java.jasper", parameters, beanCollectionDataSource); but, What should I use instead of JRBeanCollectionDataSource? (Obviously, if your application will work) Thank you very much!!!
{ "language": "en", "url": "https://stackoverflow.com/questions/30864625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I create a portal for this navbar (React) This is my index.html (Where the portal is supposed to lead to) <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="navbarRoot"></div> <div id="root"></div> </body> Here is my navbar component const Navbar = () => { const [isOpen , setIsOpen] = useState(false) const navButtonHandler = () => { setIsOpen(!isOpen) } return ( <> <nav className='navbar'> <span><img src={logo} alt='home' className='logo' /></span> <div className={`menuMask ${isOpen && "open"}`} onClick={navButtonHandler}></div> <div className={`menuContainer ${isOpen && "open"}`}> <ul className={`navitems ${isOpen && "open"}`}> <a href="/" className='home'> <li>Home</li> </a> <a href="/" className='whoWeHelp'> <li>Who We Help</li> </a> <a href="/" className='services'> <li>Services</li> </a> <a href="/" className='about'> <li>About</li> </a> <a href="/" className='caseStudies'> <li>Case Studies</li> </a> <li> <PrimaryButton link={'https://hadizouhbi.website'}>Client Login</PrimaryButton> </li> <li> <SecondaryButton link={'https://hadizouhbi.website'}>Contact</SecondaryButton> </li> </ul> </div> <div className={`navToggle ${isOpen && "open"}`} onClick={navButtonHandler}> <div className='bar'> </div> </div> </nav> </> ) } Where in the code do I use this {ReactDom.createPortal(<Navbar />, document.getElementById('navbarRoot'))} Am i doing something wrong? because I have no idea where to put that line however I do think the syntax for that is correct just where to put it is the issue. Any help is greatly appreciated ! I am a beginner to react A: the code {ReactDom.createPortal(<Navbar />, document.getElementById('navbarRoot'))} goes inside the return statement. eg: import Navbar from "component" function MainPage(){ ... ... return( <> ... {ReactDom.createPortal(<Navbar />, document.getElementById('navbarRoot'))} </> ); } A: If you meant to render the whole NavBar component as a portal then return in the Navbar should be like below. import { useState } from "react"; import ReactDOM from "react-dom"; const domNode = document.getElementById("navbarRoot"); const Navbar = () => { const [isOpen, setIsOpen] = useState(false); const navButtonHandler = () => { setIsOpen(!isOpen); }; const navContent = ( <> <nav className="navbar"> <span>{/* <img src={logo} alt="home" className="logo" /> */}</span> <div className={`menuMask ${isOpen && "open"}`} onClick={navButtonHandler} ></div> <div className={`menuContainer ${isOpen && "open"}`}> <ul className={`navitems ${isOpen && "open"}`}> <a href="/" className="home"> <li>Home</li> </a> ... ... </ul> </div> <div className={`navToggle ${isOpen && "open"}`} onClick={navButtonHandler} > <div className="bar"></div> </div> </nav> </> ); return ReactDOM.createPortal(navContent, domNode); }; Use Navbar in any other place. In spite of where you try to render it in your component tree, it will always appear in the div with navbarRoot as the id. export default function App() { return ( <div className="App"> <Navbar /> </div> ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/71251306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can Cube (js metrics framework) return more than 1000 events? The Cube software (https://github.com/square/cube) allows you to retrieve events. I want to retrieve a lot of events. But it appears that I am capped at 1000. There are well over 9000 in mongodb in the collection and time range I am querying Example http GET queries I issue: # 1000 results http://1.2.3.4:1081/1.0/event?expression=my_event_type # 1000 results http://1.2.3.4:1081/1.0/event?expression=my_event_type&start=2012-02-02&stop=2013-07-03 # 7 results http://1.2.3.4:1081/1.0/event?expression=my_event_type&limit=7 # 1000 results http://1.2.3.4:1081/1.0/event?expression=my_event_type&limit=9999 It appears that the limit is pinned: https://github.com/square/cube/blob/28dad4af27a6680deb46077b16952590f2c21cad/lib/cube/event.js Line 166 based on the 'batchSize=1000' Is it possible that you can 'page' through the data in some way? Or is this just a hard limit? A: Looks like there is a hard cap on results in three places that need to be updated for large domains: * *event.js - line 166 *metric.js - line 11 *metric.js - line 12 In addition, I was unable to find any query-string apis for the parameters. Ideally, we can leave the cap at 1000 (to avoid server bloat for people not tuning their queries correctly) and allow the consumer to define override behavior.
{ "language": "en", "url": "https://stackoverflow.com/questions/17437811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Switching between databases Spring MongoDb I have a case, where I need to switch between the mongo databases using Spring mongodata (Version: 1.6.2). Currently, I have default database configured in db-config.xml with mongo template, and have annotated repositories; Need is to switch from one db/template to another at runtime; do necessary actions and switch back to default one. I referred to couple of links, Spring-data-mongodb connect to multiple databases in one Mongo instance and Making spring-data-mongodb multi-tenant I need to use same set of repositories at runtime. Is it possible to handle my case at configuration level? or do we need to extend Dbfactory to achieve this? with Dbfactory, can I use same set of annotated repositories? Appreciate any help. A: I once had a very similar problem. I published the code on github, check it out multi-tenant-spring-mongodb You basically have to extend SimpleMongoDbFactory and handle other hosts too. I just did handle multiple databases on the same server. That shouldn't be a problem. A: You can extend: 1. `SimpleMongoDbFactory`: returning custom DB in DB `getDb(String dbName)`. 2. `MongoTemplate`: Supplying above factory. Use appropriate MongoTemplate with the help of @Qualifier.
{ "language": "en", "url": "https://stackoverflow.com/questions/29477668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to can I get all special character, where is not SPACE, using Regex? When I use \W in Regex, it will get all special character, but I wan not get Space. How to can I get all special character using Regex, where it is not Space, in javascript? A: You can use negated character class instead: [^\w\s] This will match a character that is not a word character and not a white-space. RegEx Demo A: You could simply use [^\s\w] which will return all characters that are not space nor letters Regex101
{ "language": "en", "url": "https://stackoverflow.com/questions/32704146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP read UTF-8 CSV I have a PHP script that reads from a CSV file, the file is in UTF-8 format and the code below is treating it as ASCII. How can I change the code to read the file as UTF-8? if (($handle = fopen("books.csv", "r")) === FALSE) throw new Exception("Couldn't open books.csv"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { [EDIT] One of the issues with my current code is that the first value on the first line always has the three bytes that identifies UTF-8 files appended at the beginning. So I guess a solution that operates on a value by value or a row by row might not be good enough? A: Use fgets() get file all string in variable $date, then mb_convert_encoding() convert encoding, then str_getcsv() convert string to array. if (($handle = fopen("books.csv", "r")) === FALSE) throw new Exception("Couldn't open books.csv"); $data = ""; // get file all strin in data while (!feof($handle)) { $data .= fgets($handle, 5000); } // convert encoding $data = mb_convert_encoding($data, "UTF-8", "auto"); // str_getcsv $array = str_getcsv($data);
{ "language": "en", "url": "https://stackoverflow.com/questions/42149852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: timer that calls every n milliseconds a function without .after or threading I need a timer that calls a function every n milliseconds. This should not be in a endloss loop (while true) or something like that import threading def printit(): threading.Timer(5.0, printit).start() print "Hello, World!" Or def printit(): root.after(100,printit()) As I have a GUI that should be able to interact. So that I can stop the timer. Some ideas? Thanks! A: Your question explictly says not to use after, but that's exactly how you do it with tkinter (assuming your function doesn't take more than a couple hundred ms to complete). For example: def printit(): if not stopFlag: root.after(100,printit) ... def stop(): global stopFlag stopFlag = False ... printit() The above will cause printit to be called every 100ms until some other piece of code sets stopFlag to False. Note: this will not work very well if printit takes more than 100ms. If the function takes two much time, your only choices are to move the function into a thread, or move it to another process. If printit takes 100ms or less, the above code is sufficient to keep your UI responsive. A: From Python Documentation from threading import Timer def hello(): print "hello, world" t = Timer(30.0, hello) t.start() # after 30 seconds, "hello, world" will be printed`
{ "language": "en", "url": "https://stackoverflow.com/questions/30800871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: BeautifulSoup is providing different results for .find and .find_all I am trying to work through an exercise in a Practical Data Analysis book where the goal is to scrape the price of gold from a website. The original code does not work and I have traced it down to what I think is a re-working of the website from the time of the original script. To try to still get the exercise to work I have been working on revamping the script a bit: from bs4 import BeautifulSoup import requests import re from time import sleep from datetime import datetime def getGoldPrice(): url = "http://www.gold.org" req = requests.get(url) soup = BeautifulSoup(req.text, "lxml") price = soup.find_all("dd", class_="value")[1] return price with open("goldPrice.out","w") as f: for x in range(0,3): sNow = datetime.now().strftime("%I:%M:%S%p") f.write("{0}, {1} \n ".format(sNow, getGoldPrice())) sleep(59) This worked for the initial part until I realized it was not pulling the active tags updating every minute (the original goal). After doing a bit more research I found out that I could dig into that a bit more with a soup.find('script', type="text/javascript").text in place of the .find_all() usage and run a regex on the script. This worked very well with the exception of the original posts regex so I was working on figuring out what to use to get the price for the "ask" group. When I went back to call this updated regex on the file my expression no longer provided the same base result. Currently if I do a soup.find_all('script', type="text/javascript") I get a different set of results than with a soup.find('script', type="text/javascript").text unfortunately I can't seem to take the soup.find_all result into a .text command like I can for the soup.find command. Is there a portion of this command that I am missing that I am getting such different results? Thanks for the help! EDIT: Using the help from the answer I ended up using the following bits of line to replace the price component to get what I was looking for! js_text = soup.find_all('script', type="text/javascript")[10] js_text = js_text.string regex = re.compile('"ask":{"css":"minus","price":"(.*)","performance":-1}},"G') price = re.findall(regex, js_text) Admittedly my regex is very specific to my problem. A: for a in soup.find_all('script', type="text/javascript"): print(a.text) find_all() will return a tag list like: [tag1, tag2, tag3] find() will only return the first tag: tag1 if you want to get all the tag in the tag list, use for loop to iterate it.
{ "language": "en", "url": "https://stackoverflow.com/questions/41886437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Terraform variables within variables First off - apologies - I’m extremely new (3 hours in!) to using terraform. I am looking to try and use the value of a variable inside the declaration of another variable. Below is my code - what am I doing wrong? variables.tf: variable "EnvironmentName" { type = "string" } variable "tags" { type = "map" default = { Environment = "${var.EnvironmentName}" CostCentre = "C1234" Project = "TerraformTest" Department = "Systems" } } Variables-dev.tfvars: EnvShortName = "Dev" EnvironmentName = "Development1" #Location Location = "westeurope" main.tf: resource “azurerm_resource_group” “TestAppRG” { name = “EUW-RGs-${var.EnvShortName}” location = “${var.Location}” tags = “${var.tags}” } I am getting the following error: Error: Variables not allowed on variables.tf line 18, in variable “tags”: 18: Environment = “${var.EnvironmentName}” Variables may not be used here. I understand that the error message is fairly self explanatory and it is probably my approach that is wrong - but how do I use a variable in the definition of another variable map? is this even possible? I will be standing up multiple resources - so want the tags to be built as a map and be passed into each resource - but I also want to recycle the map with other tfvars files to deploy multiple instances for different teams to work on. A: Terraform does not support variables inside a variable. If you want to generate a value based on two or more variables then you can try Terraform locals (https://www.terraform.io/docs/configuration/locals.html). Locals should help you here to achieve goal. something like locals { tags = { Environment = "${var.EnvironmentName}" CostCentre = "C1234" Project = "TerraformTest" Department = "Systems" } } And then you can use as local.tags resource “azurerm_resource_group” “TestAppRG” { name = “EUW-RGs-${var.EnvShortName}” location = “${var.Location}” tags = “${local.tags}” } Hope this helps A: You need to use locals to do the sort of transform you are after variables.tf: variable "EnvironmentName" { type = "string" } locals.tf locals { tags = { Environment = var.EnvironmentName CostCentre = "C1234" Project = "TerraformTest" Department = "Systems" } } Variables-dev.tfvars: EnvShortName = "Dev" EnvironmentName = "Development1" #Location Location = "westeurope" main.tf: resource “azurerm_resource_group” “TestAppRG” { name = “EUW-RGs-${var.EnvShortName}” location = var.Location tags = local.tags } You can do things like `tags = merge(local.tags,{"key"="value"}) to extend your tags.
{ "language": "en", "url": "https://stackoverflow.com/questions/58841060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "46" }
Q: Why do not all started applications save the wanted information in the text files as expected? I am trying to create a batch file on a USB drive that will run an .exe, save its text to a .txt file, and then close the .exe. I am currently running into a weird problem, only 5 of the 18 .exe's are actually saving their text to a file. This is the convention I am using to complete my task: start IEPassView.exe /stext Results/IEPassView.txt taskkill /f /im IEPassView.exe start MailPassView.exe /stext Results/MailPassView.txt taskkill /f /im MailPassView.exe start MessenPass.exe /stext Results/MessenPass.txt taskkill /f /im MessenPass.exe start RouterPassView.exe /stext Results/RouterPassView.txt taskkill /f /im RouterPassView.exe start ProtectedStoragePassView.exe /stext Results/ProtectedStoragePassView.txt taskkill /f /im ProtectedStoragePassView.exe start DialUpPassView.exe /stext Results/DialUpPassView.txt taskkill /f /im DialUpPassView.exe I have 18 of the above blocks in a row all calling different small programs and even though 5 of them actually save the files none of them save a .cfg file as they sometimes do. Any help would be greatly appreciated, thanks. A: There are mainly 3 different types of executables: * *A console application is reading from stdin or a file and writing to stdout or a file and outputs error messages to stderr. The processing of a batch file is halted on starting a console application until the console application terminated itself. The correct term is therefore: calling a console application. The exit code of the console application is assigned to environment variable ERRORLEVEL and can be also directly evaluated for example with if errorlevel X rem do something Many *.exe in System32 directory of Windows are such console applications, like find.exe, findstr.exe, ping.exe, ... *A GUI (graphical user interface) application is started as new process which means the Windows command processor does not halt batch processing until the GUI application terminates itself. It is not easily possible to get something from within a command process from such applications. GUI applications are designed for interacting via a graphical user interface with a user and not via standard streams or files with a command process. A typical example for such applications is Windows Explorer explorer.exe in Windows directory. *A hybrid application supports both interfaces and can be therefore used from within a command process as well as by a user via GUI. Hybrid applications are rare because not easy to code. The behavior of hybrid applications on usage from within a batch file must be find out by testing. Example for such applications are Windows Registry Editor regedit.exe or shareware archiver tool WinRAR WinRAR.exe. It is best to look on simple examples to see the differences regarding starting/calling all 3 types of applications from within a batch file. Example for console application: @echo off cls %SystemRoot%\System32\ping.exe 127.0.0.1 -n 5 echo. echo Ping finished pinging the own computer (localhost). echo. pause The command processing is halted until ping.exe terminated itself which takes 4 seconds. There is no need for start or call for such applications, except the console application should be intentionally executed in a separate process. Example for a GUI application: @echo off cls %WinDir%\Explorer.exe echo. echo Windows Explorer opened and is still running! echo. pause This batch file outputs the text and message prompt to press any key immediately after starting Windows Explorer indicating that Windows Explorer was started as separate process and Windows command processor immediately continued on the next lines of the batch file. So although Windows Explorer was started and is still running, the batch processing continued, too. Example for a hybrid application: @echo off cls "%ProgramFiles%\WinRAR\WinRAR.exe" echo. echo User exited WinRAR. echo. pause This batch file starts WinRAR without any parameter (usually not useful from within a batch file) if being installed at all in default installation directory. But batch processing is halted until the user exited WinRAR for example by clicking on X symbol of the WinRAR´s application window. But opening a command prompt window and executing from within the window "%ProgramFiles%\WinRAR\WinRAR.exe" results in getting immediately the prompt back in command window to type and execute the next command. So WinRAR finds out what is the parent process and acts accordingly. Windows Registry Editor shows the same behavior. Executing from within a command prompt window %WinDir%\regedit.exe results in opening Windows Registry Editor, but next command can be immediately entered in command prompt window. But using this command in a batch file results in halting batch processing until GUI window of Windows Registry Editor is closed by the user. Therefore hybrid applications are used from within a batch file mainly with parameters to avoid the necessity of user interaction. Okay, back to the question after this brief lesson about various types of applications. First suggestion is using Result\TextFileName.txt instead of Result/TextFileName.txt as the directory separator on Windows is the backslash character, except the executables require forward slashes as directory separator because of being badly ported from Unix/Linux to Windows. Second suggestion is finding out type of application. Is command start really necessary because the applications don't start itself in a separate process and need user interaction to terminate itself? Note: Command start interprets first double quoted string as title string. Therefore it is always good to specify as first parameter "" (empty title string) on starting a GUI or hybrid application as a separate process. On starting a console application as a separate process it is in general a good idea to give the console window a meaningful title. And last if the started applications really would need user interaction to terminate, it would be definitely better to either start and kill them after waiting 1 or more seconds between start and kill or start them all, wait a few seconds and finally kill them all at once. Example for first solution with starting and killing each application separately: @echo off setlocal set TimeoutInSeconds=3 call :RunApp IEPassView call :RunApp MailPassView call :RunApp MessenPass call :RunApp RouterPassView call :RunApp ProtectedStoragePassView call :RunApp DialUpPassView endlocal goto :EOF :RunApp start "" "%~1.exe" /stext "Results\%~1.txt" set /A RetryNumber=TimeoutInSeconds + 1 %SystemRoot%\System32\ping.exe 127.0.0.1 -n %RetryNumber% >nul %SystemRoot%\System32\taskkill.exe /f /im "%~1.exe" goto :EOF It is also possible to use timeout instead of ping for the delay if the batch file is only for Windows Vista and later Windows versions. Example for second solution with starting all applications, wait some seconds and kill them finally all: @echo off call :StartApp IEPassView call :StartApp MailPassView call :StartApp MessenPass call :StartApp RouterPassView call :StartApp ProtectedStoragePassView call :StartApp DialUpPassView %SystemRoot%\System32\ping.exe 127.0.0.1 -n 6 >nul call :KillApp IEPassView call :KillApp MailPassView call :KillApp MessenPass call :KillApp RouterPassView call :KillApp ProtectedStoragePassView call :KillApp DialUpPassView goto :EOF :StartApp start "" "%~1.exe" /stext "Results\%~1.txt" goto :EOF :KillApp %SystemRoot%\System32\taskkill.exe /f /im "%~1.exe" goto :EOF For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully. * *call /? *echo /? *endlocal /? *goto /? *ping /? *set /? *setlocal /? *start /? *taskkill /? See also the Microsoft article about Using command redirection operators. PS: The last two batch code blocks were not tested by me because of not having available the applications. A: I suggest killing all tasks at once, at the end of the very end, possibly after a timeout command with a amount of time appropriate to your system's speed. That may help the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/36995755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Zooming in proteced sheet Currently on my excel documents I have it coded so that when you click on these designated cells the screen view zooms into the cell, making it more readable. Now when I protect the sheet and use the cell I get the error code - Runtime Error '1004' I need to protect the sheet whilst still being able to get the screen to zoom into my designated cells, any advice? Current Code- Private Sub Worksheet_SelectionChange(ByVal Target As Range) With Range("B5000") If Not Intersect(Target, Range("B8:B5000")) Is Nothing Then If .Value <> "zoomed" Then ActiveWindow.Zoom = 100 .Value = "zoomed" End If ElseIf .Value = "zoomed" Then ActiveWindow.Zoom = 60 .ClearContents End If End With What coding do I require for this to work and where do I add this within the current code?
{ "language": "en", "url": "https://stackoverflow.com/questions/73306844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DataGrid Values not updating after the Edit/Update function I am using the following code to update the data in my datagrid. But when I click update the value is updated in the database but it still shows old value in datagrid. If I refresh the page after that then datagrid shows the updated value. What could be wrong? Code On Update Command: protected void MySQLDataGrid2_UpdateCommand(object source, DataGridCommandEventArgs e) { string newData; TextBox aTextBox; aTextBox = (TextBox)(e.Item.Cells[0].Controls[0]); newData = aTextBox.Text; decimal comm = Convert.ToDecimal(newData); string UpdateHiveCommission = "Update tbl_HiveCommission set Commission = '" + Convert.ToDecimal(newData) + "'"; MySqlConnection objMyCon3 = new MySqlConnection(strProvider); objMyCon3.Open(); MySqlCommand cmd3 = new MySqlCommand(UpdateHiveCommission, objMyCon3); cmd3.ExecuteNonQuery(); objMyCon3.Close(); MySQLDataGrid2.EditItemIndex = -1; MySQLDataGrid2.DataBind(); } A: I think you need to call your load mechanism again - since the datasource of your grid isn't updated so it will hold the old data from your last select. If you have performance issues loading the data again, you could manually alter the data of the edited row. A: quick fix: You can try to move this line to Page_Load() MySQLDataGrid2.DataBind(); Or, after executing the update command, "Refresh" the page by: Response.Redirect(Request.RawUrl); A: After Successful Edit. Try to call your Databind Method. something like: private void BindMEthod() { //Your code in binding data to your datagridview. } protected void MySQLDataGrid2_UpdateCommand(object source, DataGridCommandEventArgs e) { string newData; TextBox aTextBox; aTextBox = (TextBox)(e.Item.Cells[0].Controls[0]); newData = aTextBox.Text; decimal comm = Convert.ToDecimal(newData); string UpdateHiveCommission = "Update tbl_HiveCommission set Commission = '" + Convert.ToDecimal(newData) + "'"; MySqlConnection objMyCon3 = new MySqlConnection(strProvider); objMyCon3.Open(); MySqlCommand cmd3 = new MySqlCommand(UpdateHiveCommission, objMyCon3); cmd3.ExecuteNonQuery(); objMyCon3.Close(); // MySQLDataGrid2.EditItemIndex = -1; -- // MySQLDataGrid2.DataBind(); //Replace with this BindMEthod(); } Hope this help. Regards
{ "language": "en", "url": "https://stackoverflow.com/questions/5416727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to extract only non-empty deques in dict where key-value pair is int - collections.deque pairs I have a dict of collection.deque objects, dqs, where the key is some integer id. I would like to create another dict that only has the entries in dqs where the deque is non-empty. Is there a quick way to do this without iterating through the deque? A: Empty deques are falsey, non-empty deques are truthy: >>> bool(deque([])) False >>> bool(deque([1, 2])) True This will not iterate through each deque: non_empty_dqs = {k: v for k, v in dqs.items() if v}
{ "language": "en", "url": "https://stackoverflow.com/questions/75618983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Safari Location Popup In my website i use location permission in Mozilla Firefox etc. browser it works properly. But when I open it in Safari browser it ask multiple time on every page on page refresh. Anyone help Me ?
{ "language": "en", "url": "https://stackoverflow.com/questions/72008490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bootstrap 5 ReOrdering will not work correctly past 4 columns I have setup a container that should alternate the image & text when the size is md or above. The intention is to have the images above text on small and alternate image, text, text, image etc. As soon as I exceed 4 columns the ordering does not work. Please help advise where I am going wrong? Working code example 4 columns <!-- Block 1 Re order order-* from md upwards --> <div class="container"> <div class="row"> <div class="col-md-6 order-md-1 odd-row"> <img class="img-fluid rounded mb-4 mb-lg-0" src="images/security_alarm.png" alt="Security Alarm System"> </div> <div class="col-md-6 order-md-2 even-row"> <h1 class="font-weight-light">Is your home insurance proof?</h1> <p>Most insurance companies now ask that you upgrade the security of your home to qualify for home insurance. Did you know you must have kite marked locks on the front and back doors to qualify for a valid claim? </p> </div> <div class="col-md-6 order-md-4 odd-row"> <div class="col-lg-4"><img class="img-fluid rounded mb-4 mb-lg-0" src="images/security_alarm.png" alt="Security Alarm System"></div> </div> <div class="col-md-6 order-md-3 even-row"> <h1 class="font-weight-light">Is your home insurance proof?</h1> <p>Most insurance companies now ask that you upgrade the security of your home to qualify for home insurance. Did you know you must have kite marked locks on the front and back doors to qualify for a valid claim? </p> </div> </div> Above 4 columns when the code/order does not work (breaks)..... <!-- Block 1 Re order order-* from md upwards --> <div class="container"> <div class="row"> <div class="col-md-6 order-md-1 odd-row"> <img class="img-fluid rounded mb-4 mb-lg-0" src="images/security_alarm.png" alt="Security Alarm System"> </div> <div class="col-md-6 order-md-2 even-row"> <h1 class="font-weight-light">Is your home insurance proof?</h1> <p>Most insurance companies now ask that you upgrade the security of your home to qualify for home insurance. Did you know you must have kite marked locks on the front and back doors to qualify for a valid claim? </p> </div> <div class="col-md-6 order-md-4 odd-row"> <div class="col-lg-4"><img class="img-fluid rounded mb-4 mb-lg-0" src="images/security_alarm.png" alt="Security Alarm System"></div> </div> <div class="col-md-6 order-md-3 even-row"> <h1 class="font-weight-light">Is your home insurance proof?</h1> <p>Most insurance companies now ask that you upgrade the security of your home to qualify for home insurance. Did you know you must have kite marked locks on the front and back doors to qualify for a valid claim? </p> </div> <div class="col-md-6 order-md-5 odd-row"> <img class="img-fluid rounded mb-4 mb-lg-0" src="images/security_alarm.png" alt="Security Alarm System"> </div> <div class="col-md-6 order-md-6 even-row"> <h1 class="font-weight-light">Is your home insurance proof?</h1> <p>Most insurance companies now ask that you upgrade the security of your home to qualify for home insurance. Did you know you must have kite marked locks on the front and back doors to qualify for a valid claim? </p> </div> </div> A: Your problem The .order-* classes are limited at 5. It's in the documentation: Includes support for 1 through 5 across all six grid tiers. If you need more .order-* classes, you can modify the default number via Sass variable. And .order-6 is equal to order: last. Easy solution Add your own CSS classes. @media (min-width: 768px) { .order-md-6 { order: 6; } .order-md-7 { order: 7; } .order-md-8 { order: 8; } .order-md-9 { order: 9; } .order-md-10 { order: 10; } } <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> <div class="container"> <div class="row"> <div class="col-md-6 order-md-1"> img </div> <div class="col-md-6 order-md-2"> text </div> <div class="col-md-6 order-md-4"> img </div> <div class="col-md-6 order-md-3"> text </div> <div class="col-md-6 order-md-5"> img </div> <div class="col-md-6 order-md-6"> text </div> <div class="col-md-6 order-md-8"> img </div> <div class="col-md-6 order-md-7"> text </div> <div class="col-md-6 order-md-9"> img </div> <div class="col-md-6 order-md-10"> text </div> </div> </div> Alternative solution Overwrite the Sass. It can be found in the _utilities.scss. Here it is in Github. If you don't know how to do this, there are many tutorials to get you started, even here on SO.
{ "language": "en", "url": "https://stackoverflow.com/questions/74971725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: textAlign: TextAlign.center, flutter not working I'm a student who is new to learning flutter. I won't align my text and buttons to the center of the screen. I use this code to align the center. also, I used separate widgets to create them as shown in the code. textAlign: TextAlign.center, it doesn't work for me. also, the text box I created is not displaying at all. how to fix these errors on my app. import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class babyNameScreen extends StatefulWidget { const babyNameScreen({Key? key}) : super(key: key); @override _babyNameScreenState createState() => _babyNameScreenState(); } class _babyNameScreenState extends State<babyNameScreen> { @override @override void initState() { // TODO: implement initState super.initState(); SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []); } Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.white, leading: IconButton( icon: new Icon( Icons.arrow_back_rounded, color: Colors.black, ), onPressed: () { // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => WelcomeScreen())); }, ), ), body: Padding( padding: const EdgeInsets.only(top: 40), child: ListView( children: [ StepText(), SizedBox( height: 25, ), NameText(), SizedBox( height: 25, ), EnterNameText(), // SizedBox( // height: 25, // ), TextBox(), //text field ContinueButton(), //elevated button ], ), ), ); } } Widget StepText() => Container( child: Row(children: [ Text( 'STEP 2/5', textAlign: TextAlign.center, style: TextStyle( fontSize: 12, color: Colors.deepPurple, fontWeight: FontWeight.w700, ), ), ]), ); Widget NameText() => Container( child: Row(children: [ Text( 'What is her name?', textAlign: TextAlign.center, style: TextStyle( fontSize: 25, color: Colors.black, fontWeight: FontWeight.w700, ), ), ]), ); Widget EnterNameText() => Container( child: Row(children: [ Text( 'Enter name of your new profile.', textAlign: TextAlign.center, style: TextStyle( fontSize: 15, color: Colors.grey, fontWeight: FontWeight.w500, ), ), ]), ); //text field Widget TextBox()=> Container( child: Row( children: [ TextField( decoration: InputDecoration( border: OutlineInputBorder(), hintText: 'Enter a search term', ), ), ], ), ); //elevated button Widget ContinueButton()=> Container ( child: Row( children: [ ElevatedButton( onPressed: () { //playSound(soundNumber); }, child: Text('Continue'), style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>(Colors.deepPurple), ), ), ], ), ); A: Use, mainAxisAlignment: MainAxisAlignment.center in Row. Like this, Widget StepText() => Container( child: Row( mainAxisAlignment: MainAxisAlignment.center, // Add this line... children: [ Text( 'STEP 2/5', textAlign: TextAlign.center, style: TextStyle( fontSize: 12, color: Colors.deepPurple, fontWeight: FontWeight.w700, ), ), ]), ); For more info : https://docs.flutter.dev/development/ui/layout For remove shadow of AppBar use elevation, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0.0,) For more info : https://api.flutter.dev/flutter/material/Material/elevation.html A: You can use this way to achieve the layout you want import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class babyNameScreen extends StatefulWidget { const babyNameScreen({Key? key}) : super(key: key); @override _babyNameScreenState createState() => _babyNameScreenState(); } class _babyNameScreenState extends State<babyNameScreen> { @override @override void initState() { // TODO: implement initState super.initState(); SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []); } Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.white, leading: IconButton( icon: new Icon( Icons.arrow_back_rounded, color: Colors.black, ), onPressed: () { // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => WelcomeScreen())); }, ), ), body: Padding( padding: const EdgeInsets.only(top: 40), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ StepText(), SizedBox( height: 25, ), NameText(), SizedBox( height: 25, ), EnterNameText(), // SizedBox( // height: 25, // ), TextBox(), //text field ContinueButton(), //elevated button ], ), ), ); } } Widget StepText() => Container( child: Text( 'STEP 2/5', textAlign: TextAlign.center, style: TextStyle( fontSize: 12, color: Colors.deepPurple, fontWeight: FontWeight.w700, ), ), ); Widget NameText() => Container( child: Text( 'What is her name?', textAlign: TextAlign.center, style: TextStyle( fontSize: 25, color: Colors.black, fontWeight: FontWeight.w700, ), ), ); Widget EnterNameText() => Container( child: Text( 'Enter name of your new profile.', textAlign: TextAlign.center, style: TextStyle( fontSize: 15, color: Colors.grey, fontWeight: FontWeight.w500, ), ), ); //text field Widget TextBox()=> Container( child: TextField( decoration: InputDecoration( border: OutlineInputBorder(), hintText: 'Enter a search term', ), ), ); //elevated button Widget ContinueButton()=> Container ( child: ElevatedButton( onPressed: () { //playSound(soundNumber); }, child: Text('Continue'), style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>(Colors.deepPurple), ), ), );
{ "language": "en", "url": "https://stackoverflow.com/questions/70859659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to split a sequence in k homogeneous parts? I'd like to split a sequence into k parts, and optimize the homogeneity of these sub-parts. Example : 0 0 0 0 0 1 1 2 3 3 3 2 2 3 2 1 0 0 0 Result : 0 0 0 0 0 | 1 1 2 | 3 3 3 2 2 3 2 | 1 0 0 0 when you ask for 4 parts (k = 4) Here, the algorithm did not try to split in fixed-length parts, but instead tried to make sure elements in the same parts are as homogeneous as possible. What algorithm should I use ? Is there an implementation of it in R ? A: Maybe you can use Expectation-maximization algorithm. Your points would be (value, position). In your example, this would be something like: With the E-M algorithm, the result would be something like (by hand): This is the desired output, so you can consider using this, and if it really works in all your scenarios. An annotation, you must assign previously the number of clusters you want, but I think it's not a problem for you, as you have set out your question. Let me know if this worked ;) Edit: See this picture, is what you talked about. With k-means you should control the delta value, this is, how the position increment, to have its value to the same scale that value. But with E-M this doesn't matter. Edit 2: Ok I was not correct, you need to control the delta value. It is not the same if you increment position by 1 or by 3: (two clusters) Thus, as you said, this algorithm could decide to cluster points that are not neighbours if their position is far but their value is close. You need to guarantee this not to happen, with a high increment of delta. I think that with a increment of 2 * (max - min) values of your sequence this wouldn't happen. Now, your points would have the form (value, delta * position).
{ "language": "en", "url": "https://stackoverflow.com/questions/39224665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby to return my entries alphabetically works for all but my first entry This is what it looks like. word = 'word' words = [] puts 'enter some words, man. ill tell em to you in alphabetical order.' puts 'when your\'re done, just press enter without typing anything before.' puts '' word = gets.chomp while word != '' word = gets.chomp list = list.push word end puts '' puts 'Your alphabetically ordered words are:' puts list.sort puts '' Again, this works, except for the first word I submit to it. Any hints or help is much appreciated. A: Now it will work word = gets.chomp while word != '' list = list.push word word = gets.chomp end In your case, before pushing the first word to list( when you just entered into the while loop), you are calling again Kernel#gets and assigned it to word. That's why you lost the first word, and from that second one you started to pushing the words into the array. A: Compare with functional approach: sorted_words = (1..Float::INFINITY) .lazy .map { gets.chomp } .take_while { |word| !word.empty? } .sort A: You can make this cleaner if you realize that assignment returns the assigned value. list = [] until (word = gets.chomp).empty? do list << word end A: Here is another way your program can be rewritten, perhaps in a little more intuitive and expressive way: word = 'word' list = [] puts 'enter some words, man. ill tell em to you in alphabetical order.' puts 'when your\'re done, just press enter without typing anything before.' puts '' keep_going = true while keep_going word = gets.chomp keep_going = false if word.empty? list = list.push word if keep_going end puts '' puts 'Your alphabetically ordered words are:' puts list.sort puts ''
{ "language": "en", "url": "https://stackoverflow.com/questions/24311724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calculate posterior distribution of unknown mis-classification with PRTools in MATLAB I'm using the PRTools MATLAB library to train some classifiers, generating test data and testing the classifiers. I have the following details: * *N: Total # of test examples *k: # of mis-classification for each classifier and class I want to do: Calculate and plot Bayesian posterior distributions of the unknown probabilities of mis-classification (denoted q), that is, as probability density functions over q itself (so, P(q) will be plotted over q, from 0 to 1). I have that (math formulae, not matlab code!): Posterior = Likelihood * Prior / Normalization constant = P(q|k,N) = P(k|q,N) * P(q|N) / P(k|N) The prior is set to 1, so I only need to calculate the likelihood and normalization constant. I know that the likelihood can be expressed as (where B(N,k) is the binomial coefficient): P(k|q,N) = B(N,k) * q^k * (1-q)^(N-k) ... so the Normalization constant is simply an integral of the posterior above, from 0 to 1: P(k|N) = B(N,k) * integralFromZeroToOne( q^k * (1-q)^(N-k) ) (The Binomial coefficient ( B(N,k) ) can be omitted though as it appears in both the likelihood and normalization constant) Now, I've heard that the integral for the normalization constant should be able to be calculated as a series ... something like: k!(N-k)! / (N+1)! Is that correct? (I have some lecture notes with this series, but can't figure out if it is for the normalization constant integral, or for the overall distribution of mis-classification (q)) Also, hints are welcome as how to practically calculate this? (factorials are easily creating truncation errors right?) ... AND, how to practically calculate the final plot (the posterior distribution over q, from 0 to 1). A: I really haven't done much with Bayesian posterior distributions ( and not for a while), but I'll try to help with what you've given. First, k!(N-k)! / (N+1)! = 1 / (B(N,k) * (N + 1)) and you can calculate the binomial coefficients in Matlab with nchoosek() though it does say in the docs that there can be accuracy problems for large coefficients. How big are N and k? Second, according to Mathematica, integralFromZeroToOne( q^k * (1-q)^(N-k) ) = pi * csc((k-N)*pi) * Gamma(1+k)/(Gamma(k-N) * Gamma(2+N)) where csc() is the cosecant function and Gamma() is the gamma function. However, Gamma(x) = (x-1)! which we'll use in a moment. The problem is that we have a function Gamma(k-N) on the bottom and k-N will be negative. However, the reflection formula will help us with that so that we end up with: = (N-k)! * k! / (N+1)! Apparently, your notes were correct. A: Let q be the probability of mis-classification. Then the probability that you would observe k mis-classifications in N runs is given by: P(k|N,q) = B(N,k) q^k (1-q)^(N-k) You need to then assume a suitable prior for q which is bounded between 0 and 1. A conjugate prior for the above is the beta distribution. If q ~ Beta(a,b) then the posterior is also a Beta distribution. For your info the posterior is: f(q|-) ~ Beta(a+k,b+N-k) Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/2908923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NoClassDefFoundError with gradle, giraph, and hadoop So, I've been looking around a lot and I haven't found a good answer to my question, and this is driving me crazy, so I figured I'd ask here and hopefully I can get help. I'm trying to do automated testing in a Giraph project using gradle. I'm a total beginner with gradle. Just to get started, I copied the test code for the SimpleShortestPathComputation class into my project, to make sure I could get the tests up and running. When I do gradle test, however, I get the following error: $ gradle test --info <skipping some output here...> Successfully started process 'Gradle Test Executor 1' Gradle Test Executor 1 started executing tests. WCCTest > testToyData FAILED java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at org.apache.hadoop.conf.Configuration.<clinit>(Configuration.java:142) at WCCTest.testToyData(WCCTest.java:180) Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) ... 2 more Gradle Test Executor 1 finished executing tests. WCCTest > testOnShorterPathFound FAILED java.lang.NoClassDefFoundError: org.apache.hadoop.conf.Configuration at sun.reflect.GeneratedSerializationConstructorAccessor33.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Constructor.java:525) at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:40) at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:59) at org.mockito.internal.creation.jmock.ClassImposterizer.createProxy(ClassImposterizer.java:128) at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:63) at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:56) at org.mockito.internal.creation.CglibMockMaker.createMock(CglibMockMaker.java:23) at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:26) at org.mockito.internal.MockitoCore.mock(MockitoCore.java:51) at org.mockito.Mockito.mock(Mockito.java:1243) at org.mockito.Mockito.mock(Mockito.java:1120) at org.apache.giraph.utils.MockUtils$MockedEnvironment.<init>(MockUtils.java:68) at org.apache.giraph.utils.MockUtils.prepareVertexAndComputation(MockUtils.java:132) at WCCTest.testOnShorterPathFound(WCCTest.java:64) WCCTest > testToyDataJson FAILED java.lang.NoClassDefFoundError: Could not initialize class org.apache.giraph.conf.GiraphConfiguration at WCCTest.testToyDataJson(WCCTest.java:127) WCCTest > testOnNoShorterPathFound FAILED java.lang.NoClassDefFoundError: org.apache.hadoop.conf.Configuration at sun.reflect.GeneratedSerializationConstructorAccessor33.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Constructor.java:525) at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:40) at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:59) at org.mockito.internal.creation.jmock.ClassImposterizer.createProxy(ClassImposterizer.java:128) at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:63) at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:56) at org.mockito.internal.creation.CglibMockMaker.createMock(CglibMockMaker.java:23) at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:26) at org.mockito.internal.MockitoCore.mock(MockitoCore.java:51) at org.mockito.Mockito.mock(Mockito.java:1243) at org.mockito.Mockito.mock(Mockito.java:1120) at org.apache.giraph.utils.MockUtils$MockedEnvironment.<init>(MockUtils.java:68) at org.apache.giraph.utils.MockUtils.prepareVertexAndComputation(MockUtils.java:132) at WCCTest.testOnNoShorterPathFound(WCCTest.java:95) 4 tests completed, 4 failed <more output...> :test FAILED :test (Thread[main,5,main]) completed. Took 1.663 secs. FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':test'. > There were failing tests. See the report at: file:///...build/reports/tests/index.html BUILD FAILED I'm using the totally standard project directory structure, and this is my build.gradle file: apply plugin: 'java' repositories { mavenCentral() } dependencies { compile files('$GIRAPH_HOME/giraph-core/target/giraph-1.1.0-SNAPSHOT-for-hadoop-0.20.203.0-jar-with-dependencies.jar') compile files('$GIRAPH_HOME/giraph-examples/target/giraph-examples-1.1.0-SNAPSHOT-for-hadoop-0.20.203.0-jar-with-dependencies.jar') compile files('$HADOOP_HOME/hadoop-core-0.20.203.0.jar') testCompile group: 'junit', name: 'junit', version: '4.+' testCompile group: 'org.mockito', name: 'mockito-all', version: '1.9.5' } It compiles with no problem, and the jar files I'm including as dependences include the classes for which it says NoClassDefFoundError (according to jar tf). Any ideas what I'm doing wrong? Thanks in advance. A: try add following into your build.gradle println("HADOOP_HOME=$HADOOP_HOME") compile files("$HADOOP_HOME/hadoop-core-0.20.203.0.jar") println("System.env.HADOOP_HOME=$System.env.HADOOP_HOME") compile files("$System.env.HADOOP_HOME/hadoop-core-0.20.203.0.jar") A: It turned out I just had to add some of the jars from the $HADOOP_HOME/lib directory to the dependencies and it worked. Once I added the dependency for org/apache/commons/logging/LogFactory it cleared up the error for the hadoop Configuration class, and then I just had to add the other required jars later.
{ "language": "en", "url": "https://stackoverflow.com/questions/24613054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Entity Framework n to n relationship add object to another object I have a Model with Clients: public class Client { [Key] public int id { get; set; } [Required] public string? Hostname { get; set; } public ICollection<Software>? Softwares { get; set; } } And a Model with Software: public class Software { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int id { get; set; } public string Name { get; set; } public ICollection<Client>? Clients { get; set; } } This is supposed to be an n to n connection. How can I add software to my clients? What I've tried: public async void add(Software software) { using (var repo = new ClientRepository(contextFactory.CreateDbContext())) { client.Softwares.Add(software); await repo.Save(client); } Repository: public async Task Save(Client client) { _context.Clients.Update(client); _context.SaveChanges(); } } This works for the first software I add, but gives me the following error if I try to add a second one: SqlException: Violation of PRIMARY KEY constraint 'PK_ClientSoftware'. Cannot insert duplicate key in object 'dbo.ClientSoftware'. The duplicate key value is (7003, 5002). A: It seems you are adding more than one relation of the same. Before adding software to a client, make sure a relation does not exist yet, then you can go ahead and add software to client. Also, you can improve your entities. Use better naming for the primary keys and add [Key] attribute to Software class as well. Client: public class Client { public Client() { Softwares = new HashSet<Software>(); } [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ClientId { get; set; } [Required] public string Hostname { get; set; } public ICollection<Software> Softwares { get; set; } } Software: public class Software { public Software() { Clients = new HashSet<Client>(); } [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int SoftwareId { get; set; } public string Name { get; set; } public ICollection<Client> Clients { get; set; } } Check if relation already exists: // Get the client including its related softwares var client = dbContext.Clients.Include(x => x.Softwares) .FirstOrDefault(x => x.Hostname == "Ibrahim"); if (client != null) { // Check with unique property such as name of software // If it does not exist in this current client, then add software if (!client.Softwares.Any(x => x.Name == software.Name)) client.Softwares.Add(software); dbContext.SaveChanges(); } Note: If you update your entities, remember to create new migration and database. A: Q: Do you make a new one with new() every time? A: no, its a software that already exists Then that is the error. The first SaveChanges() will start tracking it as Existing. You can check: The Id will be != 0. When you then later add it to the same Client you'll get the duplicate error. So somewher in your code: await add(software); // existing software = new Software(); // add this Related, change: public async void add(Software software) to public async Task Add(Software software) Always avoid async void.
{ "language": "en", "url": "https://stackoverflow.com/questions/74361667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: List private property names of the class I need to use some subset of class properties names as values in a map to use inside of the class. In following example I've replaced map by array. The problem is that if property is marked private it's not listed in keyof list. How can I specify type of keys if I need to include private names? var keys: Array<keyof A> = ["x", "y"]; // Error class A { private x = 7; public y = 8; private keys: Array<keyof A> = ["x", "y"]; // Error } There is the same error both for variable outside of the class and for private property inside of it: Type '"x"' is not assignable to type '"y"'. A: As you noticed, private and protected properties of a class C do not appear as part of keyof C. This is usually desirable behavior, since most attempts to index into a class with a private/protected property will cause a compile error. There is a suggestion at microsoft/TypeScript#22677 to allow mapping a type to a version where the private/protected properties are public, which would give you a way to do this... but this feature has not been implemented as of TypeScript 4.9. So this doesn't work: namespace Privates { export class A { private x: string = "a"; public y: number = 1; private keys: Array<keyof A> = ["x", "y"]; // Error } var keys: Array<keyof A> = ["x", "y"]; // Error } const privateA = new Privates.A(); privateA.y; // number privateA.x; // error: it's private privateA.keys; // error: it's private But maybe you don't actually need the properties to be private, so much as not visible to outside users of the class. You can use a module/namespace to export only the facets of your class that you want, like this: namespace NotExported { class _A { x: string = "a"; y: number = 1; keys: Array<keyof _A> = ["x", "y"]; // okay } export interface A extends Omit<_A, "x" | "keys"> {} export const A: new () => A = _A; var keys: Array<keyof _A> = ["x", "y"]; // okay } const notExportedA = new NotExported.A(); notExportedA.y; // number notExportedA.x; // error: property does not exist notExportedA.keys; // error: property does not exist In NotExported, the class constructor _A and the corresponding type _A are not directly exported. Internally, keyof _A contains both the "x" and "y" keys. What we do export is a constructor A and a corresponding type A that omits the x property (and keys property) from _A. So you get the internal behavior you desire, while the external behavior of NotExported.A is similar to that of Privates.A. Instead of x and keys being inaccessible due to private violation, they are inaccessible because they are not part of the exported A type. I actually prefer the latter method of not exporting implementation details rather than exposing the existence of private properties, since private properties actually have a lot of impact on how the corresponding classes can be used. That is, private is about access control, not about encapsulation. Link to code
{ "language": "en", "url": "https://stackoverflow.com/questions/57066049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Get div content and then modify it The scenario is, I want to get a div content and then modify it in order to insert it in another div. Code below : $("#loupe").live("click",function(){ $('#divBody').empty(); $('#divTitle').empty(); var title = $(this).closest('div').find('.stepTitle').text(); var divContent = $(this).closest('div').html(); // code to modify the content to be inserted in the modal $('#divBody').append(divContent); $('#divTitle').append(title); $('#div').modal({ dynamic: true }); }); more in detail , the first div contains a title that i want to remove before inserting content into the new div , so the new div must contains content without title <div> <h4 class="StepTitle">Planing des congés pour le service de <%=service.getNomService() %> au <%=month%> / <%=year%> <span style="float: right;"> <i class="icon-white icon-search" style="cursor: pointer;" id="loupe"> </i> <i class="icon-white icon-remove" style="cursor: pointer;" onclick="$(this).closest('div').remove();"> </i> </span> </h4> <table border="1" style="border-color: gray;"> </table> </div> //************the div into which content will be inserted <div id="div" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h3 id="divTitle"> //here the title </h3> </div> <div id="divBody" class="modal-body"> here the other content </div> <div class="modal-footer"> <input type="button" class="btn" class="close" data-dismiss="modal" value="fermer"> </div> </div> A: jQuery allows you to work with fragments of a page (as well as XML). Once you've used the .html method to assign the HTML of an element to a variable, you can operate on the HTML like so: var html, withoutTitle; html = $('#someDiv').html(); withoutTitle = $(html).remove('#title').html(); $('#someOtherDiv').html(withoutTitle); I haven't tested this code, so you may need to tweak it a bit to suit your purposes.
{ "language": "en", "url": "https://stackoverflow.com/questions/15763818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sequentially arranged and add placeholders in text file I have a text file which contains data. There are 3 columns, each column starts at a specific location and ends a specific location in the file. The first column which is (300, 301, 302, 304...) is always number based. the second column is a string, and the last column is currency. The current .txt file is missing numbers which is (303, 305). I was able to find the missing numbers and add it to an array then write it to the file. My goal is to write all the columns data sequentially to the text file even the missing ones. As for column 2 and 3, I want 0 to be the placeholder for the missing data and aligned with its own column. I'm close but need help //read file string[] lines = File.ReadAllLines(FilePath); var Numbers = new List<int>(); int i = 0; foreach (var line in lines) { //get value of first column var FirstColumn = line.Substring(0, 3); //add it to array Numbers.Add(Convert.ToInt32(FirstColumn)); ++i; } //find missing numbers add to array var result = Enumerable.Range(Numbers.Min(), Numbers.Count); //write to file using (StreamWriter file = new StreamWriter(OutPutFile, true)) { foreach (var item in result.ToArray()) { file.WriteLine(item); } } Console.ReadKey(); Current .txt file 300 Family Guy 1,123 301 Dexters Lab 456 302 Rugrats 1,789.52 304 Scooby-Doo 321 306 Recess 2,654 307 Popeye 1,987.02 GOAL: Desired Output .txt file 300 Family Guy 1,123 301 Dexters Lab 456 302 Rugrats 1,789.52 303 0 0 304 Scooby-Doo 321 305 0 0 306 Recess 2,654 307 Popeye 1,987.02 A: You are reading the first column, but not the rest. What I do is create a dictionary, using the first number as the index, and stuffing the other two fields into a System.ValueTuple (you need to include the ValueTyple Nuget package to get this to work). First I set some stuff up: const int column1Start = 0; const int column1Length = 3; const int column2Start = 8; const int column2Length = 15; const int column3Start = 24; int indexMin = int.MaxValue; //calculated during the first int indexMax = int.MinValue; //pass through the file Then I create my dictionary. That (string, decimal) syntax describes a 2-tuple that contains a string and a decimal number (kind of like the ordered-pairs you were taught about in high school). Dictionary<int, (string, decimal)> data = new Dictionary<int, (string, decimal)>(); Then I make a pass through the file's lines, reading through the data, and stuffing the results in my dictionary (and calculating the max and min values for that first column): var lines = File.ReadAllLines(fileName); foreach (var line in lines) { //no error checking var indexString = line.Substring(column1Start, column1Length); var cartoon = line.Substring(column2Start, column2Length).TrimEnd(); var numberString = line.Substring(column3Start); if (int.TryParse(indexString, out var index)) { //I have to parse the first number - otherwise there's nothing to index on if (!decimal.TryParse(numberString, out var number)){ number = 0.0M; } data.Add(index, (cartoon, number)); if (index < indexMin) { indexMin = index; } if (index > indexMax) { indexMax = index; } } } Finally, with all my data in hand, I iterate from the min value to the max value, fetching the other two columns out of my dictionary: for (int i = indexMin; i <= indexMax; ++i) { if (!data.TryGetValue(i, out var val)){ val = ("0", 0.0M); } Console.WriteLine($"{i,5} {val.Item1,-column2Length - 2} {val.Item2, 10:N}"); } My formatting isn't quite the same as yours (I cleaned it up a bit). You can do what you want. My results look like: 300 Family Guy 1,123.00 301 Dexters Lab 456.00 302 Rugrats 1,789.52 303 0 0.00 304 Scooby-Doo 321.00 305 0 0.00 306 Recess 2,654.00 307 Popeye 1,987.02
{ "language": "en", "url": "https://stackoverflow.com/questions/53644844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Automatically abbreviate the length string in matplotlib Is there a way to automatically reduce the length of string in matplotlib if it conflicts with neighboring texts such as in: What I'm looking for is if matplotlib detects a conflict with another text, it automatically reduce the texts in order for all the texts to be readable. Note that one could of course rotate the labels or make the fontsize smaller to prevent overlap. But here I'm asking how to cut the text in case of overlap.
{ "language": "en", "url": "https://stackoverflow.com/questions/57824734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# Visual Studio 2013 suppress 'Class is never instantiated' I have a web api project which accepts HttpPost communications. The controller's methods always accepting a single validated object. For example: public sealed class NumbersRequest { [NumberOne] public string Number1 { get; set; } [NumberTwo] public string Number2 { get; set; } } Since I never declare NumbersRequest req = new NumbersRequest() and they only serve as a request object, Im getting the class is never instantiated How can I suppress the warning? (its more like a green underline..) Maybe something with annontations? Thanks. A: This looks like a ReSharper warning and as such you can ask ReSharper to be silent about these things. You can either configure ReSharper to stop complaining about this overall, you do this simply by hitting Alt+Enter on the squiggly in question and use the bottom menu item that usually allows you to configure the inspection severity. You can opt to save this in your global settings, which means it will affect every project you open from now on, or you can save it to a team-shared settings file which you can then check into source control alongside your project, to make it only count for this one solution. Now, if you want to keep the warning overall but ask it to stop complaining about one or more particular types, methods, properties or the likes, you can use the attributes that ReSharper provides. You have several ways of bringing these attributes into your project: * *Add a reference to the Nuget package "JetBrains ReSharper annotations" *Use the options dialog for ReSharper and find the page where it allows you to grab a copy of the source for those attributes onto the clipboard, then simply paste this into a file in your project. *Define just the one or two attributes you want, even in your own namespace (which you then have to tell ReSharper about) The recommended way is option 1, use the nuget package. Assuming you now have the attributes available you can use either PublicAPIAttribute or the UsedImplicitlyAttribute. Either one should suffice but they may have different connotations. Since you're flagging objects being transferred to or from clients I would go with the PublicAPIAttribute first. Since you say in a comment that the PublicAPIAttribute didn't work but UsedImplicitlyAttribute did then I guess they do have different meanings.
{ "language": "en", "url": "https://stackoverflow.com/questions/39506938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is wrong passing a 2D array to a respective pointer argument? I've been doing some matrix calculation in C for university the other day where I had a 5x5 matrix to begin with so I hard-coded it into the source. It was a 2D array of doubles like: /** * This is the probability-matrix for reaching from any profile * to another by randomly selecting a friend from the friendlist. */ static const double F[5][5] = { /* P , F , L , A , S */ /* Peter */ {0 , 0.5 , 0.5 , 0 , 0 }, /* Franz */ {1.0 , 0 , 0 , 0 , 0 }, /* Lisa */ {0 , 1/3.0, 0 , 1/3.0, 1/3.0}, /* Anna */ {0 , 0 , 0 , 0 , 1 }, /* Sepp */ {0 , 0.5 , 0.5 , 0 , 0 } }; I wanted my functions to not be fixed to operate on 5-by-5 matrices so I always pass the number of rows and/or cols to the function. This forces me not to use the double [][X] syntax because it can not be completely "variable" and instead use a double* as function parameter. inline size_t matrix_get(int rows, int i, int j); inline void matrix_print(double* m, int rows, int cols); inline void matrix_copy(double* d, const double* s, int rows, int cols); void matrix_multiply( int m, int n, int l, const double* a, const double* b, double* d); But I always get this warning when calling a function that accepts double* when I passed double [5][5] instead. fuenf_freunde.c:138:17: warning: incompatible pointer types passing 'double [5][5]' to parameter of type 'double *' [-Wincompatible-pointer-types] matrix_print( R, 5, 5); ^ fuenf_freunde.c:54:27: note: passing argument to parameter 'm' here void matrix_print(double* m, int rows, int cols) ^ Casting using (double*) F resolves the warning. Now my questions are * *am I wrong casting a 2D double array to a double pointer? *why is it working if its illegal? *what is the right way to pass an n-dimensional arbitrary size array to a function? EDIT: This cleared a lot up for me: Accesing a 2D array using a single pointer So I should just use double[x*y] instead of double[x][y] I think. But is it legal to cast double[] to double*? A: I contend that there is nothing wrong with what you do. Your code just lacks an explicit cast which would get rid of the warning, indicating that your assignment is intentional. You can access a one dimensional array through a pointer to its elements, and recursively applied, it follows that n-dimensional matrices can be accessed through pointers to the atomic elements. C guarantees a contiguous memory layout for them. This pattern is common. In fact passing arrays is hard or impossible to do differently, given the little information C stores with types (as opposed to, say, C#). So the matrix decays to a pointer to its first element (in your case to the first one dimensional array), which can safely be cast to an address of its first element, a double. They all share the same numerical address. Typical concerns with pointer type casting are aliasing issues with modern optimizing compilers (a compiler can assume that you don't access memory through pointers of unrelated types except char*), but there is an explicit exemption in the standard draft 1570 which I have, par. 6.5.7, which I think is applicable here: An object [that would be a double in your matrix, -ps] shall have its stored value accessed only by an lvalue expression that has one of the following types: — a type compatible with the effective type of the object [that would be a dereferenced double pointer, -ps] [...] — an aggregate [e.g. array, -ps] [...] type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union) [that would be your matrix variable, containing, eventually, doubles, -ps] [...]
{ "language": "en", "url": "https://stackoverflow.com/questions/29666141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need help setup windows server 2008 SMTP server I am trying to setup windows server 2008 smtp server to relay emails to gmail smtp. Everything appears to be setup but it is not sending emails. Could you please help me figure out whats wrong. Below is the setup: * *Windows server 2008 with SMTP server feature installed. Need SMTP server to forward all messages to gmail smtp server to send. *I have google apps setup for my domain, also I can send emails throught my test app using gmail smtp. *SMTP Server Configuration: By default has default smtp server virtual directory. *In Properties of that virtual smtp server changed following. *Fully qualified domain name = mydomain.com *smart host = smtp.gmail.com *TCP Port = 587 *Out Bound Security = Basic Authentication(my username password for google apps email account) *In domains list under virtual smtp server. I have one default domain that's server dns. I added another one for my domain name. With above setup i am trying to redirect all email to gmail smtp. I tested connection to smtp.gmail.com from server on port 587 through telnet and it works. I am trying to use above server from my web application also by just dropping emails in pickup directory. It get's picked up and also accepts request form web application but never sends an email. I can see that it adds those emails in queue folder but it stays there forever. When i try to send emails from web app to above server it rejects if To address is other than my domain.(Am i missing something in list of domains) A: Thanks for all answers, finally found solution there is a property for maximum sessions which value was 0 by default. Changed it to 100 and it send all pending emails immediately. A: This souds like a DNS issue. Check your /badmail directory. It will have .bad and .bdp files in there. You can open these in notepad (there will be some binary in there). However, it may point to the possible problem. You may also want to try and enable logging on the SMTP service. There may be something in there. A: Possible reasons are that some SMTP servers block the outgoing messages if there domain name mismatch, possible to prevent spam mails from being sent. So for example, I will not be able to send my email with an address abc@mydomain.com from my domain yourdomain.com. Hope that helps. A: Ensure your sending domain is the same as the google apps domain Ensure your sending address is a real address and not just an alias IIRC you need to use STARTTLS (SSL) not basic authentication
{ "language": "en", "url": "https://stackoverflow.com/questions/669754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: why can't I pass the return twice? I'm practicing python and I don't understand why I am getting this error. I tried searching it but I can't find put why. I tried to put pass_two = two(x) but it didn't work. it kept saying it was undefined. can any one correct and explain why? thanks def one(): x = 'blue' return x def two(x): y = 'red' xy = x+y return xy def three(z): w = 'black' print('all three passes ' + z+w) def main(): pass_one = one() two(pass_one) pass_two = two() three(pass_two) if __name__ == '__main__': main() A: You defined the function two to work with an argument so if you try to type two(), Python will output TypeError: two() missing 1 required positional argument: 'x'. Now, if you try to type two(x)without having defined x before, you will get a NameError. Maybe you wanted to write pass_two = two(pass_one)
{ "language": "en", "url": "https://stackoverflow.com/questions/56534893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Insert multipe rows after specific row in Excel 2003 For example, my table is like this : AAA bb cc AAA dd... How can I insert 3 empty rows just below AAA row? So that, my table becomes : AAA first empty row second empty row third empty row bb cc AAA first empty row second empty row third empty row dd.. A: If you are in Excel, right click on the row numbers on the left to show a context menu, then click on "Insert". This will add a new row.
{ "language": "en", "url": "https://stackoverflow.com/questions/10931538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java project can display a new scene pretty easily, but only for certain JavaFXML files, how to fix this? Here's my code I'm struggling with (I marked the line that's giving me errors): package sample.controller; import java.io.IOException; import java.net.URL; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.stage.Stage; import sample.database.DBConnection; import sample.model.User; public class LoginController { @FXML private ResourceBundle resources; @FXML private URL location; @FXML private Button loginButton; @FXML private TextField loginEmail; @FXML private Button createAccountSwitchButton; @FXML private PasswordField loginPassword; private DBConnection dbConnection; @FXML void initialize() { dbConnection = new DBConnection(); loginButton.setOnAction(event-> { String loginEmailText = loginEmail.getText().trim(); String loginPasswordText = loginPassword.getText().trim(); User user = new User(); user.setEmail(loginEmailText); user.setPassword(loginPasswordText); ResultSet userRow = dbConnection.checkForUser(user); int counter = 0; try{ while (userRow.next()){ counter++; } if (counter==1){ loginButton.getScene().getWindow().hide(); FXMLLoader loader = new FXMLLoader(); //THE LINE BELOW THIS LINE------------------------------------------------------------------- loader.setLocation(getClass().getResource("/sample/view/CreateAccount.fxml")); //THIS LINE //THE LINE ABOVE THIS LINE------------------------------------------------------------------- try { loader.load(); } catch (IOException e) { e.printStackTrace(); } Parent root = loader.getRoot(); Stage stage = new Stage(); stage.setScene(new Scene(root)); stage.showAndWait(); } }catch(SQLException e){ e.printStackTrace(); } }); // Takes user to Create Account page createAccountSwitchButton.setOnAction(event -> { createAccountSwitchButton.getScene().getWindow().hide(); FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/sample/view/CreateAccount.fxml")); try { loader.load(); } catch (IOException e) { e.printStackTrace(); } Parent root = loader.getRoot(); Stage stage = new Stage(); stage.setScene(new Scene(root)); stage.showAndWait(); }); } // private void loginUser(String email, String password) { // //Checks if fields are empty, if so, bring them to user dashboard. // if(!email.equals("") || !password.equals("")){ // // }else{ // // } // } } At this point, it does exactly what I want it to do, it loads a new scene of "CreateAccount.fxml" file whenever I click the login button. But I want it to load a different FXML file, so I change the name to "Dashboard.fxml" which is my dashboard file name, but all of a sudden it no longer works and it's giving me errors that don't make any sense since my path is right and my name is right as well. This is what I changed that line to to throw the error below: loader.setLocation(getClass().getResource("/sample/view/Dashboard.fxml")); Lastly, to make sure, I created a completely new and blank FXML file and it won't load either. Here are the full errors: javafx.fxml.LoadException: /C:/Users/andre/IdeaProjects/Covix/out/production/Covix/sample/view/Dashboard.fxml:12 at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601) at javafx.fxml.FXMLLoader.access$700(FXMLLoader.java:103) at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:922) at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971) at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220) at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744) at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707) at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527) at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441) at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409) at sample.controller.LoginController.lambda$initialize$0(LoginController.java:68) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49) at javafx.event.Event.fireEvent(Event.java:198) at javafx.scene.Node.fireEvent(Node.java:8411) at javafx.scene.control.Button.fire(Button.java:185) at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182) at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96) at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89) at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49) at javafx.event.Event.fireEvent(Event.java:198) at javafx.scene.Scene$MouseHandler.process(Scene.java:3757) at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485) at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762) at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494) at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394) at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:432) at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410) at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431) at com.sun.glass.ui.View.handleMouseEvent(View.java:555) at com.sun.glass.ui.View.notifyMouse(View.java:937) at com.sun.glass.ui.win.WinApplication._enterNestedEventLoopImpl(Native Method) at com.sun.glass.ui.win.WinApplication._enterNestedEventLoop(WinApplication.java:215) at com.sun.glass.ui.Application.enterNestedEventLoop(Application.java:511) at com.sun.glass.ui.EventLoop.enter(EventLoop.java:107) at com.sun.javafx.tk.quantum.QuantumToolkit.enterNestedEventLoop(QuantumToolkit.java:633) at javafx.stage.Stage.showAndWait(Stage.java:474) at sample.controller.CreateAccountController.lambda$initialize$0(CreateAccountController.java:59) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49) at javafx.event.Event.fireEvent(Event.java:198) at javafx.scene.Node.fireEvent(Node.java:8411) at javafx.scene.control.Button.fire(Button.java:185) at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182) at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96) at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89) at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54) at javafx.event.Event.fireEvent(Event.java:198) at javafx.scene.Scene$MouseHandler.process(Scene.java:3757) at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485) at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762) at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494) at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394) at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:432) at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410) at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431) at com.sun.glass.ui.View.handleMouseEvent(View.java:555) at com.sun.glass.ui.View.notifyMouse(View.java:937) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186) at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.ClassNotFoundException: sample.view.Dashboard at java.net.URLClassLoader.findClass(URLClassLoader.java:382) at java.lang.ClassLoader.loadClass(ClassLoader.java:418) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355) at java.lang.ClassLoader.loadClass(ClassLoader.java:351) at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:920) ... 106 more Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Root cannot be null at javafx.scene.Scene.<init>(Scene.java:336) at javafx.scene.Scene.<init>(Scene.java:194) at sample.controller.LoginController.lambda$initialize$0(LoginController.java:75) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49) at javafx.event.Event.fireEvent(Event.java:198) at javafx.scene.Node.fireEvent(Node.java:8411) at javafx.scene.control.Button.fire(Button.java:185) at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182) at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96) at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89) at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49) at javafx.event.Event.fireEvent(Event.java:198) at javafx.scene.Scene$MouseHandler.process(Scene.java:3757) at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485) at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762) at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494) at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394) at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:432) at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410) at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431) at com.sun.glass.ui.View.handleMouseEvent(View.java:555) at com.sun.glass.ui.View.notifyMouse(View.java:937) at com.sun.glass.ui.win.WinApplication._enterNestedEventLoopImpl(Native Method) at com.sun.glass.ui.win.WinApplication._enterNestedEventLoop(WinApplication.java:215) at com.sun.glass.ui.Application.enterNestedEventLoop(Application.java:511) at com.sun.glass.ui.EventLoop.enter(EventLoop.java:107) at com.sun.javafx.tk.quantum.QuantumToolkit.enterNestedEventLoop(QuantumToolkit.java:633) at javafx.stage.Stage.showAndWait(Stage.java:474) at sample.controller.CreateAccountController.lambda$initialize$0(CreateAccountController.java:59) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49) at javafx.event.Event.fireEvent(Event.java:198) at javafx.scene.Node.fireEvent(Node.java:8411) at javafx.scene.control.Button.fire(Button.java:185) at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182) at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96) at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89) at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) Here's my Dashboard.fxml: <?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.control.Label?> <?import javafx.scene.control.TableColumn?> <?import javafx.scene.control.TableView?> <?import javafx.scene.image.Image?> <?import javafx.scene.image.ImageView?> <?import javafx.scene.layout.AnchorPane?> <?import javafx.scene.shape.Rectangle?> <?import javafx.scene.text.Font?> <AnchorPane prefHeight="800.0" prefWidth="1400.0" xmlns="http://javafx.com/javafx/15.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.view.Dashboard"> <children> <AnchorPane layoutX="-6.0" layoutY="-12.0" prefHeight="816.0" prefWidth="325.0" style="-fx-background-color: #001E8A;"> <children> <ImageView fitHeight="46.0" fitWidth="46.0" layoutX="64.0" layoutY="60.0" pickOnBounds="true" preserveRatio="true"> <image> <Image url="@../assets/whiteLogo.png" /> </image> </ImageView> <Label layoutX="132.0" layoutY="55.0" text="Covix" textFill="WHITE"> <font> <Font size="43.0" /> </font> </Label> <Rectangle arcHeight="5.0" arcWidth="5.0" fill="WHITE" height="5.0" layoutX="51.0" layoutY="155.0" stroke="BLACK" strokeType="INSIDE" width="222.0" /> </children> </AnchorPane> <TableView layoutX="379.0" layoutY="342.0" prefHeight="402.0" prefWidth="397.0"> <columns> <TableColumn prefWidth="75.0" text="C1" /> <TableColumn prefWidth="75.0" text="C2" /> </columns> </TableView> <Label layoutX="371.0" layoutY="30.0" text="Dashboard"> <font> <Font name="System Bold" size="44.0" /> </font> </Label> </children> </AnchorPane> Here's my CreateAccount.fxml: <?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.control.Button?> <?import javafx.scene.control.CheckBox?> <?import javafx.scene.control.Label?> <?import javafx.scene.control.PasswordField?> <?import javafx.scene.control.TextField?> <?import javafx.scene.image.Image?> <?import javafx.scene.image.ImageView?> <?import javafx.scene.layout.AnchorPane?> <?import javafx.scene.text.Font?> <AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="600.0" prefWidth="1050.0" xmlns="http://javafx.com/javafx/15.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.controller.CreateAccountController"> <children> <AnchorPane layoutX="417.0" layoutY="-8.0" prefHeight="610.0" prefWidth="634.0" style="-fx-background-color: #001F8E;"> <children> <ImageView fitHeight="378.0" fitWidth="534.0" layoutX="46.0" layoutY="118.0" pickOnBounds="true" preserveRatio="true"> <image> <Image url="@../assets/loginart.png" /> </image> </ImageView> <Label layoutX="247.0" layoutY="514.0" text="Stay Safe With Covix" textFill="WHITE"> <font> <Font name="System Bold" size="16.0" /> </font> </Label> <Label layoutX="160.0" layoutY="542.0" text="Update your scores and see other user's scores to keep yourself" textFill="WHITE" /> <Label layoutX="160.0" layoutY="564.0" text=" and others around you as healthy and safe as possible." textFill="WHITE" /> </children></AnchorPane> <AnchorPane layoutY="-2.0" prefHeight="606.0" prefWidth="417.0" style="-fx-background-color: white;"> <children> <ImageView fitHeight="44.0" fitWidth="44.0" layoutX="38.0" layoutY="39.0" pickOnBounds="true" preserveRatio="true"> <image> <Image url="@../assets/covixapplogo.png" /> </image> </ImageView> <Label layoutX="94.0" layoutY="40.0" text="Covix" textFill="#111111"> <font> <Font size="32.0" /> </font> </Label> <Label layoutX="40.0" layoutY="111.0" text="Create Account"> <font> <Font name="System Bold" size="27.0" /> </font> </Label> <Label layoutX="42.0" layoutY="155.0" text="Get safer with your score. Create an account today!" textFill="#6c6c6c" /> <Button fx:id="createAccountButton" layoutX="49.0" layoutY="480.0" mnemonicParsing="false" prefHeight="30.0" prefWidth="313.0" style="-fx-background-color: #001F8E; -fx-border-radius: 10; -fx-border-color: none; text: white;" text="Create Account" textFill="WHITE" /> <TextField fx:id="createAccountEmail" layoutX="44.0" layoutY="294.0" prefHeight="35.0" prefWidth="324.0" promptText="Email" /> <Label layoutX="43.0" layoutY="265.0" prefHeight="18.0" prefWidth="235.0" text="Your email:" textFill="#191919"> <font> <Font size="15.0" /> </font> </Label> <Label layoutX="47.0" layoutY="337.0" prefHeight="18.0" prefWidth="235.0" text="Password:" textFill="#191919"> <font> <Font size="15.0" /> </font> </Label> <CheckBox layoutX="55.0" layoutY="421.0" mnemonicParsing="false" text="By creating an account you agree to the terms and conditions."> <font> <Font size="10.0" /> </font> </CheckBox> <Label layoutX="134.0" layoutY="531.0" text="Already have an account?" textFill="#6c6c6c" /> <Button fx:id="loginButtonSwitch" layoutX="176.0" layoutY="549.0" mnemonicParsing="false" style="-fx-background-color: none;" text="Log In" textFill="#041cf2"> <font> <Font name="System Bold" size="12.0" /> </font> </Button> <PasswordField fx:id="createAccountPassword" layoutX="44.0" layoutY="369.0" prefHeight="35.0" prefWidth="324.0" promptText="Password" /> <TextField fx:id="createAccountFullName" layoutX="42.0" layoutY="218.0" prefHeight="35.0" prefWidth="324.0" promptText="e.g. John Doe" /> <Label layoutX="42.0" layoutY="189.0" prefHeight="18.0" prefWidth="235.0" text="Your Full Name" textFill="#191919"> <font> <Font size="15.0" /> </font> </Label> </children> </AnchorPane> </children> </AnchorPane> So for some reason, my CreateAccount.fxml file loads, but not a completely new FXML file that's blank or my Dashboard.fxml file. I'm not sure what the problem could be. Thanks in advance! A: The problem is this line of the stack trace: Caused by: java.lang.ClassNotFoundException: sample.view.Dashboard This means that the FXML loader could not find a class named Dashboard in package sample.view. The FXML loader looked for this class because that is what was written in file Dashboard.fxml, namely: <AnchorPane prefHeight="800.0" prefWidth="1400.0" xmlns="http://javafx.com/javafx/15.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.view.Dashboard"> Notice the part at the end of the line: fx:controller="sample.view.Dashboard" If you don't need a controller class then simply remove that part.
{ "language": "en", "url": "https://stackoverflow.com/questions/66613696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error building react native app on Android Hi I´m trying to run my react native app on android but when i build it shows me this error: info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag. Jetifier found 952 file(s) to forward-jetify. Using 8 workers... info JS server already running. info Installing the app... > Task :react-native-safe-area-context:compileDebugJavaWithJavac FAILED Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0. Use '--warning-mode all' to show the individual deprecation warnings. See https://docs.gradle.org/6.9/userguide/command_line_interface.html#sec:command_line_warnings 48 actionable tasks: 2 executed, 46 up-to-date FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':react-native-safe-area-context:compileDebugJavaWithJavac'. > Could not find tools.jar. Please check that /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home contains a valid JDK installation. * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 5s error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081 FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':react-native-safe-area-context:compileDebugJavaWithJavac'. > Could not find tools.jar. Please check that /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home contains a valid JDK installation. * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 5s at makeError (/Users/calebgarcia/Dev/Auth/node_modules/@react-native-community/cli-platform-android/node_modules/execa/index.js:174:9) at /Users/calebgarcia/Dev/Auth/node_modules/@react-native-community/cli-platform-android/node_modules/execa/index.js:278:16 at processTicksAndRejections (node:internal/process/task_queues:96:5) at async runOnAllDevices (/Users/calebgarcia/Dev/Auth/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:106:5) at async Command.handleAction (/Users/calebgarcia/Dev/Auth/node_modules/@react-native-community/cli/build/index.js:192:9) info Run CLI with --verbose flag for more details. It´s a bit puzzling since when i build the app on the ios simulator it runs perfectly. Do you guys have any idea how i can solve the issue? Thanks. A: npm install react-native-safe-area-context Try this and build. If not, Please check your computer's environment variables and set JAVA_HOME if it has not already been setup.
{ "language": "en", "url": "https://stackoverflow.com/questions/70489427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS column bug fix or alternative Due to Chrome (and other Blink browsers) having a bug where only the first 500 columns are painted i need either a fix/hack, or an alternative solution. See bug here (there is 509 pages - not 500): https://codepen.io/anon/pen/pLxozK /* codepen link must be accompanied by code */ column-width: 400px; I parse EPUB html to a single file. The EPUB's styling must be preserved, so i can't change the html structure. CSS columns does a good job of rendering such a flat document horizontally. But the 500 limit in Blink means blank pages in Android Webviews. Is there any workaround for this bug? Users can adjust font size etc meaning amount of columns can change. So an alternative solution must be able to adjust. A: What a cool little bug, I've never seen that before! By the looks of things you'll need to add display:none to some of your divs. You'll need to use Javascript to see what's in view and see what's not. You'll get the added bonus of not using any system resources unnecessarily as you won't be painting any of the pages that aren't in view.
{ "language": "en", "url": "https://stackoverflow.com/questions/49734376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP preg_replace exclude < and > I need to change this code: $output = preg_replace("#&lt;a ([^&gt;]*)&gt;([^&lt;]*)&lt;\/a&gt;#", "<a href=\"$1\">$2</a>", $output) to make from &lt;a some.url&gt;description&lt;/a&gt; to HTML code <a href="some.url">description</a>, but after i changed < and > to &lt; and &gt; it doesn't make what I wanted. Thank you for your help. EDIT: I wouldn't use html_entity_decode(), because I want this for enabling slightly simplified HTML tags, but the most of HTML i would have disabled. Input for my function is a variable, obtained from a form: Firstly the code replaces all < and > with &lt; and &gt;. Than it changes back some text-modifying static HTML tags, for example <b> and </b>. But in the end, i want to change every link inputed as <a some.url>link</a> (and than by code changed to &lt;a some.url&gt;link&lt;/a&gt;) to be changed by preg_replace() into standard HTML code <a href="some.url">link</a> A: http://php.net/manual/en/function.html-entity-decode.php $str = "this 'quote' is &lt;b&gt;bold&lt;/b&gt;" html_entity_decode($output) // output This 'quote' is <b>bold</b> http://php.net/manual/en/function.htmlentities.php $str = "This 'quote' is <b>bold</b>"; htmlentities($output); // output this 'quote' is &lt;b&gt;bold&lt;/b&gt;
{ "language": "en", "url": "https://stackoverflow.com/questions/16208905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Open a PDF file from C#.NET using Impersonate I have a folder on the server containing pdf files(Windows Server 2008 R2 Enterprise). I have to open the folder with the authorized user account and display the pdf file in the browser. The user has full control permissions on the folder and is a member of the Administrator group. Bellow code works from my local as it opens the pdf file from the folder located in the server in Adobe Reader. But on the server the process does not start(Adobe Reader does not open) and no exception occurs. Most of the forums say that turning off UAC will help, but I don't want to do it, because of security reasons. How can I deal that issue? Please help. try { WindowsIdentity wi = new WindowsIdentity(@"user_name@DOMAIN"); WindowsImpersonationContext ctx = null; try { ctx = wi.Impersonate(); // Thread is now impersonating you can call the backend operations here... Process p = new Process(); p.StartInfo = new ProcessStartInfo() { CreateNoWindow = true, Verb = "open", FileName = ConfigurationManager.AppSettings["mobil"] + "\\" + prmSicilNo + "_" + prmPeriod.ToString("yyyyMM") + ".pdf", }; p.Start(); } catch (Exception ex) { msj = ex.Message; } finally { ctx.Undo(); } return msj; } catch (Exception ex) { return msj + "Error: " + ex.Message; } A: Try to execute your .exe with Run as Adminstrator on the server.If it works properly then add the below code: p.StartInfo.Verb = "runas"; A: @Chintan Udeshi Thank you for you quick answer. I can run the AcroRd32.exe by Run as Administrator but when I tried with runas I got the error which says; "No application is associated with the specified file for this operation". I also tried to place absolute Acrobat Reader Path, but it still didn't work. Any idea? p.StartInfo = new ProcessStartInfo(@"C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe") { CreateNoWindow = true, Verb = "runas", FileName = ConfigurationManager.AppSettings["mobil"] + "\\" + prmSicilNo + "_" + prmPeriod.ToString("yyyyMM") + ".pdf", // "c:\\pdf\\", };
{ "language": "en", "url": "https://stackoverflow.com/questions/42018301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: setAttribute a href in Selenium Java I got href of an element. After that, I subString,...to make a new href and want to set it back to element. But Selenium doesn't have setAttribute method nextListByNumber = driver.findElement(By.xpath("//*[@id='paginater']//*[text()='"+2+"']")); String href = nextListByNumber.getAttribute("href"); int manualcode1 = href.lastIndexOf("MANUAL"); int manualcode2 = href.lastIndexOf("/sort"); String manualcode = href.substring(manualcode1, manualcode2); String hrefNew = "http://localhost/jp/courseassign/course_assign_search_result/"+manualcode+"/sort:User.login_id/direction:asc/page:"+i+"?limit=20"; A: You can use JavaScript for this JavascriptExecutor executor = (JavascriptExecutor)driver; executor.executeScript("arguments[0].setAttribute(arguments[1], arguments[2]);", nextListByNumber, "href", hrefNew);
{ "language": "en", "url": "https://stackoverflow.com/questions/53318832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DELETE function is deleting the logo, but I don't want it to delete the logo I have a GUI in Matlab, where I have a DELETE BUTTON, after I click on it, it as well deletes the logo in it. The code for the DELETE function: clc figure('Name', 'Vektorkardiogram'); %Return handle to figure named 'Vectorcardiogram'. h = findobj('Name', 'Vektorkardiogram'); close(h); figure('Name', 'Roviny'); %Return handle to figure named 'Vectorcardiogram'. r = findobj('Name', 'Roviny'); close(r); figure('Name', 'P vlna'); %Return handle to figure named 'Vectorcardiogram'. p = findobj('Name', 'P vlna'); close(p); figure('Name', 'QRS komplex'); %Return handle to figure named 'Vectorcardiogram'. q = findobj('Name', 'QRS komplex'); close(q); figure('Name', 'T vlna'); %Return handle to figure named 'Vectorcardiogram'. t = findobj('Name', 'T vlna'); close(t); arrayfun(@cla,findall(0,'type','axes')); delete(findall(findall(gcf,'Type','axe'),'Type','text')); The code for uploading the logo (I have made a GUI in Matlab using the guide command, so this code below is inserted inside the GUI code): logo4 = imread('logo4.png','BackgroundColor',[1 1 1]); imshow(logo4) Pusghing the DELETE BUTTON, I just want to close certain figure windwos, not to delete the logo. Could you please help me out? A: You are clearing all axes using cla which includes the logo that you don't want to delete. arrayfun(@cla,findall(0,'type','axes')); Instead of clearing everything, it's better to delete and clear specific objects. cla(handles.axes10) cla(handles.axes11) Alternately, if you keep the handle to the image object, you can ignore the axes that contains it when clearing axes himg = imshow(data); allaxes = findall(0, 'type', 'axes'); allaxes = allaxes(~ismember(allaxes, ancestor(himg, 'axes'))); cla(allaxes) Also, you shouldn't ever do findall(0, ... in your GUI because if I open a figure before opening my GUI you will alter the state of my other figure. Instead, use findall(gcbf, ... which will only alter children of your own GUI. Either that, or use a 'Tag' specific to your GUI and then use findall to filter for that specific tag. figure('Tag', 'mygui') findall(0, 'Tag', 'mygui') Update You should use findall combined with the 'Name' parameter to figure out which of your figures actually exists figs = findall(0, 'Name', 'Vektorkardiogram', ... '-or', 'Name', 'Roviny', ... '-or', 'Name', 'P vlna', ... '-or', 'Name', 'QRS komplex', ... '-or', 'Name', 'T vlna'); delete(figs); And for clearing the axes, you can ensure that they exist ax = findall(0, 'tag', 'axes10', '-or', 'tag', 'axes11', '-or', 'tag', 'axes12'); cla(ax)
{ "language": "en", "url": "https://stackoverflow.com/questions/43212901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to retrieve array in php sent from iOS Following is my iOS code that sends NSmutable Array to PHP webservice: // Getting Server Address AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSString *serverAddress = [appDelegate getServerAddress]; serverAddress = [serverAddress stringByAppendingString:@"ABC.php"]; NSLog(@"Server Address: %@",serverAddress); NSData *post = [NSJSONSerialization dataWithJSONObject:UsersArray options:NSJSONWritingPrettyPrinted error:nil]; NSString *postLength = [NSString stringWithFormat:@"%d", [post length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:serverAddress]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:post]; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; [request setTimeoutInterval:30]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse* theResponse, NSData* theData, NSError* error){ //Do whatever with return data NSString *result = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding]; NSLog(@"Result : %@",result); }]; I want to retrive that array in PHP. How can I do that? Here is the php which I tried but returns null: $handle = fopen('php://input','r'); $jsonInput = fgets($handle); // Decoding JSON into an Array $decoded = json_decode($jsonInput,true); echo json_encode($decoded); A: I use a slightly different Content-Type (which shouldn't matter): [request addValue:@"text/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; And I use a slightly different PHP, too: <?php $handle = fopen("php://input", "rb"); $http_raw_post_data = ''; while (!feof($handle)) { $http_raw_post_data .= fread($handle, 8192); } fclose($handle); $json_data = json_decode($http_raw_post_data, true); echo json_encode($json_data); ?> If you're getting a blank response, I'd wager you have some PHP error. I'd you check out your server's error log, or temporarily changing the display_errors setting in your php.ini as follows: display_errors = On
{ "language": "en", "url": "https://stackoverflow.com/questions/17023131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WCF un-domain system I have developed WCF windows service using net tcp binding. Its working fine when wcf client and wcf service both on the same system. Getting error when both system are in work group not - Client and Service are on different machines please suggest what configuration i need to change . SocketId:61017335 to remote address :8005 had a connection reset error. Error :System.ServiceModel.CommunicationException: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:58.9879193'. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host I am using Certificate authentication - I know without a domain I lack the necessary Kerberos infrastuture to authenticate UPNs and SPNs but shouldn't that be resolved because I am using certificates. Client’s Config File <?xml version="1.0" encoding="utf-8"?> <configuration> <system.serviceModel> <client> <endpoint kind="discoveryEndpoint" address="net.tcp://localhost:8005/Probe" binding="netTcpBinding" bindingConfiguration="RequestReplyNetTcpBinding"> </endpoint> <endpoint binding="netTcpBinding" bindingConfiguration="RequestReplyNetTcpBinding" contract="Test2ServLib.IService1" behaviorConfiguration="LargeEndpointBehavior"> <identity> <dns value="WCFServer" /> </identity> <!--The behaviorConfiguration is required to enable WCF deserialization of large data sets --> </endpoint> </client> <behaviors> <endpointBehaviors> <behavior name="disableEndpointDiscovery"> <endpointDiscovery enabled="false" /> <!--The behavior is required to enable WCF deserialization of large data sets --> <dataContractSerializer maxItemsInObjectGraph="2147483647" /> <clientCredentials> <clientCertificate findValue="WCFClient" storeLocation="LocalMachine" storeName="TrustedPeople" x509FindType="FindBySubjectName" /> <serviceCertificate > <authentication certificateValidationMode="PeerTrust" revocationMode="NoCheck"/> </serviceCertificate> </clientCredentials> </behavior> <behavior name="LargeEndpointBehavior"> <!--The behavior is required to enable WCF deserialization of large data sets --> <dataContractSerializer maxItemsInObjectGraph="2147483647" /> <clientCredentials> <clientCertificate findValue="WCFClient" storeLocation="LocalMachine" storeName="TrustedPeople" x509FindType="FindBySubjectName" /> <serviceCertificate > <authentication certificateValidationMode="PeerTrust" revocationMode="NoCheck"/> </serviceCertificate> </clientCredentials> </behavior> </endpointBehaviors> </behaviors> <bindings> <netTcpBinding> <binding name="RequestReplyNetTcpBinding" receiveTimeout="05:00:00" openTimeout="00:00:59" closeTimeout="00:00:59" maxBufferPoolSize="524288" maxBufferSize="25000000" maxConnections="50" maxReceivedMessageSize="25000000" sendTimeout="00:05:00" listenBacklog="1500"> <reliableSession ordered="false" inactivityTimeout="00:01:00" enabled="true" /> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> <security> <message clientCredentialType="Certificate"/> </security> </binding> </netTcpBinding> </bindings> </system.serviceModel> </configuration> Service Config <?xml version="1.0" encoding="utf-8"?> <configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="announcementBehavior"> <!--The following behavior attribute is required to enable WCF serialization of large data sets --> <dataContractSerializer maxItemsInObjectGraph="2147483647"/> <serviceDiscovery> <announcementEndpoints> <endpoint kind="announcementEndpoint" address="net.tcp://localhost:8005/Announcement" binding="netTcpBinding" bindingConfiguration="RequestReplyNetTcpBinding"/> </announcementEndpoints> </serviceDiscovery> <serviceThrottling maxConcurrentCalls="1500" maxConcurrentSessions="1500" maxConcurrentInstances="1500"/> <serviceCredentials> <serviceCertificate findValue="WCFServer" storeLocation="LocalMachine" storeName="TrustedPeople" x509FindType="FindBySubjectName" /> <clientCertificate> <authentication certificateValidationMode="PeerTrust" trustedStoreLocation="LocalMachine" revocationMode="NoCheck"/> </clientCertificate> </serviceCredentials> </behavior> </serviceBehaviors> </behaviors> <service name="Test2ServLib.IService1" behaviorConfiguration="announcementBehavior"> <host> <baseAddresses> <add baseAddress="net.tcp://localhost:8006/Service1"/> </baseAddresses> </host> <endpoint binding="netTcpBinding" bindingConfiguration="RequestReplyNetTcpBinding" contract="Test2ServLib.IService1" behaviorConfiguration="LargeEndpointBehavior" /> <bindings> <netTcpBinding> <binding name = "RequestReplyNetTcpBinding"> <security> <message clientCredentialType="Certificate" /> </security> </binding> </netTcpBinding> </bindings> </system.serviceModel> </configuration>
{ "language": "en", "url": "https://stackoverflow.com/questions/63694431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android build failed and error message is "More than one file was found with OS independent path 'org/apache/pdfbox/debugger/real.png'" In my Android App I used pdfbox to generate PDF file. I was able to compile but when I build and try to deploy to a simulator. I got the following error message: "More than one file was found with OS independent path 'org/apache/pdfbox/debugger/real.png'". In my build.gradle file I include a libs path and all the jar were copy to libs path compile fileTree(include: ['*.jar'], dir: 'libs') // implementation 'libs/*.jar' implementation files('libs/jfreechart-1.0.19.jar') All the jars were included in the app/libs path The following jars were included in the app/libs path jfreechart-1.0.0.19 jar pdfbox-2.0.13.jar pdfbox-app-2.0.13.jar pdfbox-debugger-2.0.13.jar pdfbox-tools-2.0.13.jar
{ "language": "en", "url": "https://stackoverflow.com/questions/59318132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MongoDb: Match value on foreign collection I have the collection USER: { "_id" : ObjectId("5d64d2bf48dd17387d77d27a"), "name" : "John", "notifications" : { "email" : false, "sms" : true } }, { "_id" : ObjectId("5da9586911e192081ee1c6be"), "name" : "Mary", "notifications" : { "email" : false, "sms" : false } } And this other collection ALERT: { "_id" : ObjectId("5d54f04dbe5e6275e53a551e"), "active" : true, "user_id" : ObjectId("5d64d2bf48dd17387d77d27a") }, { "_id" : ObjectId("5d54f04dbe5e6275e53a551f"), "active" : false, "user_id" : ObjectId("5d64d2bf48dd17387d77d27a") }, { "_id" : ObjectId("5d54f04dbe5e6275e53a552e"), "active" : true, "user_id" : ObjectId("5da9586911e192081ee1c6be") }, { "_id" : ObjectId("5d54f04dbe5e6275e53a552f"), "active" : true, "user_id" : ObjectId("5da9586911e192081ee1c6be") } I want a MongoDB query that lists the documents on collection ALERT that have property "active" as TRUE and whose matching USER has element "sms" on property "notifications" as TRUE too. A: You can use Uncorelated sub queries in $lookup * *$match to get the "notifications.sms": true *$lookupto join two collections. We are assigning uId = _id from USER collection. Inside the pipeline, we use $match to find the active :true, and _id=uId here is the script db.USER.aggregate([ { "$match": { "notifications.sms": true } }, { "$lookup": { "from": "ALERT", "let": { uId: "$_id" }, "pipeline": [ { $match: { $and: [ { active: true }, { $expr: { $eq: [ "$user_id", "$$uId" ] } } ] } } ], "as": "joinAlert" } } ]) Working Mongo playground
{ "language": "en", "url": "https://stackoverflow.com/questions/64978968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: xml extension type and user defined I've a xml document that according to its schema definition for a certain node "level" only allows a predefined list of values (aka enumeration if not wrong). This predefined values are ok for a country, but if we change country the values might change. For this the "level" node allows ( and here starts my doubts) attribute "userDefined" and sub nodes such as <extension> and I believe is through this <extension> node or maybe userdefined attr that I will be able to specify other value and thus get the doc validated. The xsd file is here: http://utdanning.no/schemas/CDM/2.1/CDM.xsd and the xml sample file here <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <CDM xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://utdanning.no/schemas/CDM/2.1/CDM.xsd"> <orgUnit> <orgUnitID>217</orgUnitID> <orgUnitName>Contoso Inc [TEST PURPOSES ONLY]</orgUnitName> <webLink> <href>http://www.google.com</href> </webLink> <course> <courseID>341</courseID> <courseCode>FWTEST2222222</courseCode> <courseName>Another field course test imported</courseName> <courseDescription>Testing purposes only test teste teste</courseDescription> <level level="other_value"/><!--This is where i want to add a diff value other than the allowed list: vgs, folkehogskole, bachelor, master, phd, fagskole, evu, aarsstudium --> <credits ECTScredits="45"/> <admissionInfo/> <teachingPlace> <adr> <country>NORWAY</country> </adr> </teachingPlace> <formOfTeaching>Field course</formOfTeaching> <instructionLanguage>Norske</instructionLanguage> </course> </orgUnit> </CDM> A: This schema does not allow arbitrary values in the "level" attribute. There is no way to extend the set of valid values.
{ "language": "en", "url": "https://stackoverflow.com/questions/5409076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Differentiating Between an AJAX Call / Browser Request Is there anything in the header of an HTTP request that would allow me to differentiate between an AJAX call and a direct browser request from a given client? Are the user agent strings usually the same regardless? A: If you use Prototype, jQuery, Mootools or YUI you should find a X-Requested-With:XMLHttpRequest header which will do the trick for you. It should be possible to insert whatever header you like with other libraries. At the lowest level, given a XMLHttpRequest or XMLHTTP object, you can set this header with the setRequestHeader method as follows: xmlHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); A: After some research, it looks like the best approach would be to simply specify a custom user agent string when making AJAX calls and then checking for this custom user agent string on the server.
{ "language": "en", "url": "https://stackoverflow.com/questions/216173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Log4j properties | Create new log file with timestamp for every run I'm quite new to log4j and have managed to create the logs for my code. But what I need is, a new file to be created for each run, rather than appending the logs to the same file. Below are the properties I'm setting (found somewhere on google). Please suggest changes, so that new file will be created with the timestamp after each run. // Here we have defined root logger log4j.rootLogger=INFO,R,HTML // Here we define the appender log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.HTML=org.apache.log4j.FileAppender // Here we define log file location log4j.appender.R.File=./Logs/LastRunLog.log log4j.appender.HTML.File=./Logs/LastRunLog.html // Here we define the layout and pattern log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%d - %c -%p - %m%n log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout log4j.appender.HTML.layout.Title=Application log log4j.appender.HTML.layout.LocationInfo=true A: You can use a system property to set the log4j file names with it's value and give that property an unique value for each run. Something like this on your starter class (timeInMillis and a random to avoid name clashes): static { long millis = System.currentTimeMillis(); System.setProperty("log4jFileName", millis+"-"+Math.round(Math.random()*1000)); } And then you refer to the system property on log4j conf properties: log4j.appender.R.File=./Logs/${log4jFileName}.log log4j.appender.HTML.File=./Logs/${log4jFileName}.log Hope it helps! A: You need to write (or find) a custom appender which will create the file with a timestamp in the name. The 3 defaults implementation for file logging in log4j are : * *FileAppender : One file logging, without size limit. *RollingFileAppender : Multiple files and rolling file when current file hits the size limit *DailyRollingFileAppender : A file per day The simpliest way is to extend FileAppender and overwrite the setFile and getFile methods. A: i think this answer would be helpful for you click here i have ran code as the page said, and i got a new log file each time i start my application. result like that : and all code in my Test.java is :` private static final Logger log = Logger.getLogger(Test.class); public static void main(String[] args) { log.info("Hello World"); } `
{ "language": "en", "url": "https://stackoverflow.com/questions/44753863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to select checkbox button and NavigationLink to another view independently in SwiftUI List row I hope to make a list just like to-do list, the cell has a checkbox and Text. And I want when list cell selected, the view could be translate to detailView. Meanwhile I also could select the checkbox, but don't trigger the view translate to the detailView. I removed the List{}, the code run ok, but the List property and method can't use any more. So I plan to code a customer list view. But I don't think it will be the good method. So if I still can't find a good way to make it, I may implement in this way at last. NavigationView { VStack { List { ForEach(todayDietModel.todayDietItems) { item in NavigationLink(destination: DietItemDetailView()) { TodayDietRow(todayDietItem: item) .animation(.spring()) } } } } .frame(width: 352, height: 400) .background(Color.white) .cornerRadius(16) } struct TodayDietRow: View { @State var isFinished: Bool = false var body: some View { HStack(spacing: 20.0) { Button(action: {self.isFinished.toggle()}) { if self.isFinished { Image("icon_checked_s001") .resizable() .renderingMode(.original) .aspectRatio(contentMode: .fit) .frame(width: 24, height: 24) } else { Image("icon_unchecked_s001") .resizable() .frame(width: 24, height: 24) } } .padding(.leading, 10) Text("DietName") .font(.system(size:13)) .fontWeight(.medium) .foregroundColor(Color.black) } .frame(width: 327, height: 48) } } A: This works quite well with a gesture on the checkbox image. Two Buttons didn't work since every tap went to both buttons. struct TodayTodoView2: View { @ObservedObject var todayDietModel = TodayDietModel() func image(for state: Bool) -> Image { return state ? Image(systemName: "checkmark.circle") : Image(systemName: "circle") } var body: some View { NavigationView { VStack { List { ForEach($todayDietModel.todayDietItems) { (item: Binding<TodayDietItem>) in HStack{ self.image(for: item.value.isFinished).onTapGesture { item.value.isFinished.toggle() } NavigationLink(destination: DietItemDetailView2(item: item)) { Text("DietNamee \(item.value.dietName)") .font(.system(size:13)) .fontWeight(.medium) .foregroundColor(Color.black) } } } } .background(Color.white) } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/57558874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }