text
stringlengths
15
59.8k
meta
dict
Q: Query: table name specified more than once i'm trying to fix a vue filter. I have to change a query, but i can't find it in the laravel directory. SELECT count(*) AS aggregate FROM ( SELECT ST_asGeoJSON(elements.geom) AS geometry FROM "elements" LEFT JOIN subsidies ON elements.subsidy_id = subsidies.id LEFT JOIN owners ON elements.owner_id = owners.id LEFT JOIN locations ON elements.location_id = locations.id LEFT JOIN element_type ON elements.element_type_id = element_type.id LEFT JOIN shapes ON elements.shape_id = shapes.id LEFT JOIN objectives ON elements.objective_id = objectives.id LEFT JOIN diameters ON elements.diameter_id = diameters.id LEFT JOIN maintenances ON maintenances.element_id = elements.id LEFT JOIN maintenances ON elements.id = maintenances.element_id WHERE elements.organisation_id = 14 and(elements.deleted_at) IS NULL GROUP BY elements.id, maintenances.element_id, subsidies.id, owners.id, locations.id, element_type.id, shapes.id, objectives.id, diameters.id, maintenances.id HAVING COUNT(element_id) < 1) count_row_table above is the query that is executed when then checkbox is checked: SQLSTATE[42712]: Duplicate alias: 7 ERROR: table name "maintenances" specified more that once (SQL: select count(*) as... ['parent_table' => 'elements', 'join_table' => 'element_type', 'filter_column' => 'element_type_id', 'filter_value' => 'element_type_' . \Config::get('app.locale')], ['parent_table' => 'elements', 'join_table' => 'shapes', 'filter_column' => 'shape_id', 'filter_value' => 'shape_' . \Config::get('app.locale')], ['parent_table' => 'elements', 'join_table' => 'objectives', 'filter_column' => 'objective_id', 'filter_value' => 'objective_' . \Config::get('app.locale')], ['parent_table' => 'elements', 'join_table' => 'diameters', 'filter_column' => 'diameter_id', 'filter_value' => 'diameter', 'order_by' => 'diameters.id'], ['parent_table' => 'element_flora', 'join_table' => 'flora', 'filter_column' => 'flora_id', 'filter_value' => 'flora_' . \Config::get('app.locale'), 'additional_wheres' => ['element_flora.deleted_at is null']], ['parent_table' => 'element_fauna', 'join_table' => 'fauna', 'filter_column' => 'fauna_id', 'filter_value' => 'fauna_' . \Config::get('app.locale'), 'additional_wheres' => ['element_fauna.approval_pending is not TRUE', 'element_fauna.deleted_at is null']], ['parent_table' => 'elements', 'join_table' => 'owners', 'filter_column' => 'owner_id', 'filter_value' => 'owner'], ['parent_table' => 'maintenances', 'join_table' => 'elements', 'filter_column' => 'id', 'filter_value' => 'id', 'havingRaw' => 'COUNT(maintenances.element_id) < 1', 'join_type' => 'left', 'filter_null' => true], ['parent_table' => 'elements', 'join_table' => 'projects', 'filter_column' => 'project_id', 'filter_value' => 'project', 'order_by' => 'projects.id'],
{ "language": "en", "url": "https://stackoverflow.com/questions/57002131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xamarin IOS file picker : unable to get selected file from icloud drive I've installed filepicker control from Nuget and added tried adding reference from MonoTouch10 folder and later from github to my xamarin.ios project. FileData file = await CrossFilePicker.Current.PickFile(); if (file != null) { } this is the code i added to my browse button, after selecting a file from iCloud drive, control never comes to "if condition". and again when i click on browse button for second time, app crashes saying "only one operation can be active at a time". A: Modifying the source code of the FilePickerImplementation plugin for the iOS platform worked, in this way: using Foundation; using MobileCoreServices; using Plugin.FilePicker.Abstractions; using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using UIKit; using System.Diagnostics; namespace Plugin.FilePicker { /// <summary> /// Implementation for FilePicker /// </summary> public class FilePickerImplementation : NSObject, IUIDocumentMenuDelegate, IFilePicker { private int _requestId; private TaskCompletionSource<FileData> _completionSource; /// <summary> /// Event which is invoked when a file was picked /// </summary> public EventHandler<FilePickerEventArgs> Handler { get; set; } private void OnFilePicked(FilePickerEventArgs e) { Handler?.Invoke(null, e); } public void DidPickDocumentPicker(UIDocumentMenuViewController documentMenu, UIDocumentPickerViewController documentPicker) { documentPicker.DidPickDocument += DocumentPicker_DidPickDocument; documentPicker.WasCancelled += DocumentPicker_WasCancelled; documentPicker.DidPickDocumentAtUrls += DocumentPicker_DidPickDocumentAtUrls; UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(documentPicker, true, null); } private void DocumentPicker_DidPickDocumentAtUrls(object sender, UIDocumentPickedAtUrlsEventArgs e) { var control = (UIDocumentPickerViewController)sender; foreach (var url in e.Urls) DocumentPicker_DidPickDocument(control, new UIDocumentPickedEventArgs(url)); control.Dispose(); } private void DocumentPicker_DidPickDocument(object sender, UIDocumentPickedEventArgs e) { var securityEnabled = e.Url.StartAccessingSecurityScopedResource(); var doc = new UIDocument(e.Url); var data = NSData.FromUrl(e.Url); var dataBytes = new byte[data.Length]; System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length)); string filename = doc.LocalizedName; string pathname = doc.FileUrl?.ToString(); // iCloud drive can return null for LocalizedName. if (filename == null) { // Retrieve actual filename by taking the last entry after / in FileURL. // e.g. /path/to/file.ext -> file.ext // filesplit is either: // 0 (pathname is null, or last / is at position 0) // -1 (no / in pathname) // positive int (last occurence of / in string) var filesplit = pathname?.LastIndexOf('/') ?? 0; filename = pathname?.Substring(filesplit + 1); } OnFilePicked(new FilePickerEventArgs(dataBytes, filename, pathname)); } /// <summary> /// Handles when the file picker was cancelled. Either in the /// popup menu or later on. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void DocumentPicker_WasCancelled(object sender, EventArgs e) { { var tcs = Interlocked.Exchange(ref _completionSource, null); tcs.SetResult(null); } } /// <summary> /// Lets the user pick a file with the systems default file picker /// For iOS iCloud drive needs to be configured /// </summary> /// <returns></returns> public async Task<FileData> PickFile() { var media = await TakeMediaAsync(); return media; } private Task<FileData> TakeMediaAsync() { var id = GetRequestId(); var ntcs = new TaskCompletionSource<FileData>(id); if (Interlocked.CompareExchange(ref _completionSource, ntcs, null) != null) throw new InvalidOperationException("Only one operation can be active at a time"); var allowedUtis = new string[] { UTType.UTF8PlainText, UTType.PlainText, UTType.RTF, UTType.PNG, UTType.Text, UTType.PDF, UTType.Image, UTType.UTF16PlainText, UTType.FileURL }; var importMenu = new UIDocumentMenuViewController(allowedUtis, UIDocumentPickerMode.Import) { Delegate = this, ModalPresentationStyle = UIModalPresentationStyle.Popover }; UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(importMenu, true, null); var presPopover = importMenu.PopoverPresentationController; if (presPopover != null) { presPopover.SourceView = UIApplication.SharedApplication.KeyWindow.RootViewController.View; presPopover.PermittedArrowDirections = UIPopoverArrowDirection.Down; } Handler = null; Handler = (s, e) => { var tcs = Interlocked.Exchange(ref _completionSource, null); tcs?.SetResult(new FileData(e.FilePath, e.FileName, () => { var url = new Foundation.NSUrl(e.FilePath); return new FileStream(url.Path, FileMode.Open, FileAccess.Read); })); }; return _completionSource.Task; } public void WasCancelled(UIDocumentMenuViewController documentMenu) { var tcs = Interlocked.Exchange(ref _completionSource, null); tcs?.SetResult(null); } private int GetRequestId() { var id = _requestId; if (_requestId == int.MaxValue) _requestId = 0; else _requestId++; return id; } public async Task<bool> SaveFile(FileData fileToSave) { try { var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var fileName = Path.Combine(documents, fileToSave.FileName); File.WriteAllBytes(fileName, fileToSave.DataArray); return true; } catch (Exception ex) { Debug.WriteLine(ex.Message); return false; } } public void OpenFile(NSUrl fileUrl) { var docControl = UIDocumentInteractionController.FromUrl(fileUrl); var window = UIApplication.SharedApplication.KeyWindow; var subViews = window.Subviews; var lastView = subViews.Last(); var frame = lastView.Frame; docControl.PresentOpenInMenu(frame, lastView, true); } public void OpenFile(string fileToOpen) { var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var fileName = Path.Combine(documents, fileToOpen); if (NSFileManager.DefaultManager.FileExists(fileName)) { var url = new NSUrl(fileName, true); OpenFile(url); } } public async void OpenFile(FileData fileToOpen) { var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var fileName = Path.Combine(documents, fileToOpen.FileName); if (NSFileManager.DefaultManager.FileExists(fileName)) { var url = new NSUrl(fileName, true); OpenFile(url); } else { await SaveFile(fileToOpen); OpenFile(fileToOpen); } } } } A: To answer my own question, i customized in plugin, like * *Used DocumentPicker_DidPickDocumentAtUrls event instead of DocumentPicker_DidPickDocument. *while returning selected file used new FileData(e.FilePath, e.FileName, () => { var url = new Foundation.NSUrl(e.FilePath); return new FileStream(url.Path, FileMode.Open, FileAccess.Read); }) This solved my issue. Thanks. A: There are several forks of the FilePicker Xamarin plugin. I recommend the following project, since it's the most actively maintained one: https://github.com/jfversluis/FilePicker-Plugin-for-Xamarin-and-Windows (note: I'm one of the contributors to the project). With this version of the plugin file picking should work. The example code from sandeep's answer was already incorporated into the latest version of the plugin. Be sure to read the README.md's Troubleshooting page in case you're getting problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/46946482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating a .jar in Android I have a Android project with some classes that I would like to compress to a JAR. I create the JAR by right clicking my project - export - JAR - and the JAR gets created without any warnings. I can access all classes from the JAR in my code but when I try to build the project get this exception : java.lang.NoClassDefFoundError: name.of.class.in.package Does anyone know what resources should be exported with the JAR? The options you get is .class path .prject AndroidManifest.xml proguard.cfg project.properties Right now I have included all of the above. Making the JAR into a library project is not an option. And just to make it clear I don't have anything in the RES folder of my JAR project. A: Just add your JAR to classpath or build your project with Maven and include dependencies A: Open the project properties -> Java Build Path -> Order and Export and check item Android Dependencies are checked to be exported to the result APK. And if .jar exist in Library tab under Android Dependencies item. If you have .jar in the "libs" folder it should be included by default. A: Try generating the jar in a different way. Basically jar is a zipped file of all class files with an extension of .jar. * *Select all your class files that needs to be included in a jar file. *Right click and send to compressed (Zip File). *you will have a zipped file which will contain all the class files. *Rename this zipped file with having an extension .jar Now include this jar file into your project whichever you want to use. Or if you want to zip all the files by a different method then make sure all the files are zipped together without a folder. So when you unzip the files you should get all the files without contained in a folder. A: It looks similar with this topic. Follow the very clear instructions written by Russ Bateman.
{ "language": "en", "url": "https://stackoverflow.com/questions/10720885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing focus from one input to the next with a barcode scanner I am using a barcode scanner to enter data into input fields on a webpage. I set up the form and autofocus on the first input field. When the first barcode is entered into the first input field I would like focus to jump to the next input field. However, as soon as I enter the first barcode the form 'submits'. Here is the html I am using: <form id="barcode1" name="barcode" method="Post" action="#"> <div> <label for="S1">Barcode 1 </label> <input id="S1" class="bcode" type="text" name="S1" autofocus/> <label for="S2">Barcode 2 </label> <input id="S2" class="bcode" type="text" name="S2" /> <label for="S3">Barcode 3 </label> <input id="S3" class="bcode" type="text" name="S3" /> </div> <p><input type="submit" name="Submit" value="Submit"></p> </form> I have tried solutions from similar SO questions here and [here] (http://jsfiddle.net/davidThomas/ZmAEG/), but they don't seem to work. Ideally I would like to have a solution something like this (the second link above), so please let me know where or why this is not working and what I can do to fix it. $('form').on('keypress','input',function(e){ var eClassName = this.className, index = $(this).index('.' + eClassName) + 1; if (e.which === 13){ e.preventDefault(); $('input.' + eClassName) .eq(index) .focus(); } }); A: If your barcode scanner is a keyboard wedge, you should be able to configure the trailing character to a TAB. It seems like, by default, your scanner is trailing with an ENTER (carriage return). Another option would be to also check for a LF (decimal 10) in your javascript code. A: You need to return false in order to prevent the enter key from submitting the form. The answer to this question will help you: Prevent form submission with enter key //Press Enter in INPUT moves cursor to next INPUT $('#form').find('.input').keypress(function(e){ if ( e.which == 13 ) // Enter key = keycode 13 { $(this).next().focus(); //Use whatever selector necessary to focus the 'next' input return false; } }); No need to make any changes to your bar scanner. A: Looks like your function will never get called because browser submits the form on Enter. You may have to suppress submit until all fields are filled (or some other condition) by intercepting submit event first. $( "form" ).submit(function( event ) { if(/*all req. fields are filled -> submit the form*/) $(this).submit(); event.preventDefault(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/35614951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Struts 2 token is not working with display tag pagination I have a Struts 2 application, I have created some reports with display tag pagination, it works fine but when I apply CSRF token to that page, only first page displays properly and when I try to navigate other paginated pages application shows invalid.token error. Can anyone please suggest how to apply CSRF token with display tag ?
{ "language": "en", "url": "https://stackoverflow.com/questions/38091526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook php ads sdk CurlLogger.php Warning: fwrite() expects parameter 1 to be resource, string given in /var/www/myapp/vendor/facebook/php-ads-sdk/src/FacebookAds/Logger/CurlLogger.php on line 182 I have this error... how fix that ? and this code is in on that line fwrite($this->handle, $buffer.PHP_EOL.PHP_EOL); I tried to debug and return this: curl -G \ -d 'level=account' \ -d 'filtering=[]' \ -d 'breakdowns=["age","gender"]' \ -d 'time_range={"since":"2017-09-06","until":"2017-10-06"}' \ -d 'fields=results,result_rate,reach,frequency,impressions,delivery,social_reach,social_impressions,total_actions,total_unique_actions,relevance_score:score,relevance_score:positive_feedback,relevance_score:negative_feedback,spend,today_spend,cost_per_result,cpp,cpm,cost_per_total_action,actions:page_engagement,actions:like,actions:mention,actions:tab_view,actions:comment,actions:post_engagement,actions:post_reaction,actions:post,actions:photo_view,actions:rsvp,actions:receive_offer,actions:checkin,cost_per_action_type:page_engagement,cost_per_action_type:like,cost_per_action_type:mention,cost_per_action_type:tab_view,cost_per_action_type:comment,cost_per_action_type:post_engagement,cost_per_action_type:post_reaction,cost_per_action_type:post,cost_per_action_type:photo_view,cost_per_action_type:rsvp,cost_per_action_type:receive_offer,cost_per_action_type:checkin,actions:video_view,video_10_sec_watched_actions:video_view,video_30_sec_watched_actions:video_view,video_p25_watched_actions:video_view,video_p50_watched_actions:video_view,video_p75_watched_actions:video_view,video_p95_watched_actions:video_view,video_p100_watched_actions:video_view,video_avg_time_watched_actions:video_view,video_avg_percent_watched_actions:video_view,canvas_avg_view_time,canvas_avg_view_percent,canvas_component_avg_pct_view:canvas_view,cost_per_action_type:video_view,cost_per_10_sec_video_view:video_view,actions:link_click,unique_actions:link_click,outbound_clicks:outbound_click,website_ctr:link_click,unique_link_clicks_ctr,call_to_action_clicks,clicks,unique_clicks,ctr,unique_ctr,social_clicks,unique_social_clicks,cost_per_action_type:link_click,cost_per_unique_action_type:link_click,cpc,cost_per_unique_click,estimated_ad_recallers,estimated_ad_recall_rate,cost_per_estimated_ad_recallers' \ -d 'access_token=aaaaaaaaa' \ -d 'appsecret_proof=aaaaaa' \ https://graph.facebook.com/v2.8/act_aaaaaaa/insights Code of my file: <?php require __DIR__ . '/vendor/autoload.php'; use FacebookAds\Object\AdAccount; use FacebookAds\Object\AdsInsights; use FacebookAds\Api; use FacebookAds\Logger\CurlLogger; $access_token = 'hidden'; $ad_account_id = 'hidden'; $app_secret = 'hidden'; $api = Api::init($app_id, $app_secret, $access_token); $api->setLogger(new CurlLogger()); $fields = array( 'actions:link_click', 'unique_actions:link_click', 'clicks', ); $params = array( 'level' => 'account', 'filtering' => array(), 'breakdowns' => array('age','gender'), 'time_range' => array('since' => '2017-09-06','until' => '2017-10-06'), ); echo json_encode((new AdAccount($ad_account_id))->getInsights($fields,$params)->getResponse()->getContent(), JSON_PRETTY_PRINT); This code is generated by facebook marketing api Screenshot here https://prnt.sc/gtqbf5 and use php php 5.6.3
{ "language": "en", "url": "https://stackoverflow.com/questions/46588934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you convert between polar coordinates and cartesian coordinates assuming north is zero radians? I've been trying to make a simple physics engine for games. I am well aware that this is re-inventing the wheel but it's more of a learning exercise than anything else. I never expect it to be as complete as box2d for instance. I'm having issues with my implementation of 2d Vectors. The issue is related to the fact that in the game world I want to represent north as being zero radians and east as being 1/2 PI Radians, or 0 and 90 degrees respectively. However in mathematics (or maybe more specifically the Math class of Java), I believe trigonometry functions like sine and cosine assume that "east" is zero radians and I think north is 1/2 PI Radians? Anyway I've written a small version of my vector class that only demonstrates the faulty code. public class Vector { private final double x; private final double y; public Vector(double xIn, double yIn) { x = xIn; y = yIn; } public double getX() { return x; } public double getY() { return y; } public double getR() { return Math.sqrt((x * x) + (y * y)); } public double getTheta() { return Math.atan(y / x); } public double bearingTo(Vector target) { return (Math.atan2(target.getY() - y, target.getX() - x)); } public static Vector fromPolar(double magnitude, double angle) { return new Vector(magnitude * Math.cos(angle), magnitude * Math.sin(angle)); } } And here is the test code to demonstrate the issue: public class SOQuestion { public static void main(String[] args) { //This works just fine Vector origin = new Vector(0, 0); Vector target = new Vector(10, 10); double expected = Math.PI * 0.25; double actual = origin.bearingTo(target); System.out.println("Expected: " + expected); System.out.println("Actual: " + actual); //This doesn't work origin = new Vector(0, 0); target = new Vector(10, 0); expected = Math.PI * 0.5; //90 degrees, or east. actual = origin.bearingTo(target); //Of course this is going to be zero, because in mathematics right is zero System.out.println("Expected: " + expected); System.out.println("Actual: " + actual); //This doesn't work either Vector secondTest = Vector.fromPolar(100, Math.PI * 0.5); // set the vector to the cartesian coordinates of (100,0) System.out.println("X: " + secondTest.getX()); //X ends up being basically zero System.out.println("Y: " + secondTest.getY()); //Y ends up being 100 } } The requirements are: * *fromPolar(magnitude,angle) should return a vector with x and y initialized to the appropriate values assuming north is at zero radians and east is at 1/2 PI radians. for example fromPolar(10,PI) should construct a vector with x: 0 and y: -1 *getTheta() should return a value greater than or equal to zero and less than 2 PI. Theta is the angular component of the vector it's called on. For example a vector with x:10 and y:10 would return a value of 1/4 PI when getTheta() is called. *bearingTo(target) should return a value that is greater than or equal to zero and less than 2 PI. The value represents the bearing to another vector. The test code demonstrates that when you try to get the bearing of one point at (0,0) to another point at (10,0), it doesn't produce the intended result, it should be 90 degrees or 1/2 PI Radians. Likewise, trying to initialize a vector from polar coordinates sets the x and y coordinate to unexpected values. I'm trying to avoid saying "incorrect values" since it' not incorrect, it just doesn't meet the requirements. I've messed around with the code a lot, adding fractions of PI here or taking it away there, switching sine and cosine, but all of these things only fix parts of the problem and never the whole problem. Finally I made a version of this code that can be executed online http://tpcg.io/OYVB5Q A: Typical polar coordinates 0 points to the East and they go counter-clockwise. Your coordinates start at the North and probably go clockwise. The simplest way to fix you code is to first to the conversion between angles using this formula: flippedAngle = π/2 - originalAngle This formula is symmetrical in that it converts both ways between "your" and "standard" coordinates. So if you change your code to: public double bearingTo(Vector target) { return Math.PI/2 - (Math.atan2(target.getY() - y, target.getX() - x)); } public static Vector fromPolar(double magnitude, double angle) { double flippedAngle = Math.PI/2 - angle; return new Vector(magnitude * Math.cos(flippedAngle), magnitude * Math.sin(flippedAngle)); } It starts to work as your tests suggest. You can also apply some trigonometry knowledge to not do this Math.PI/2 - angle calculation but I'm not sure if this really makes the code clearer. If you want your "bearing" to be in the [0, 2*π] range (i.e. always non-negative), you can use this version of bearingTo (also fixed theta): public class Vector { private final double x; private final double y; public Vector(double xIn, double yIn) { x = xIn; y = yIn; } public double getX() { return x; } public double getY() { return y; } public double getR() { return Math.sqrt((x * x) + (y * y)); } public double getTheta() { return flippedAtan2(y, x); } public double bearingTo(Vector target) { return flippedAtan2(target.getY() - y, target.getX() - x); } public static Vector fromPolar(double magnitude, double angle) { double flippedAngle = flipAngle(angle); return new Vector(magnitude * Math.cos(flippedAngle), magnitude * Math.sin(flippedAngle)); } // flip the angle between 0 is the East + counter-clockwise and 0 is the North + clockwise // and vice versa private static double flipAngle(double angle) { return Math.PI / 2 - angle; } private static double flippedAtan2(double y, double x) { double angle = Math.atan2(y, x); double flippedAngle = flipAngle(angle); // additionally put the angle into [0; 2*Pi) range from its [-pi; +pi] range return (flippedAngle >= 0) ? flippedAngle : flippedAngle + 2 * Math.PI; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/49576502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use pair correctly in C++ I am trying to insert an object into a map. You can ignore most of the code here, but I'll include it to help. It's the line mymap.insert(pair(name, myobj(num1, num2))); That is giving me the error. struct ap_pair { ap_pair(float tp, float tm) : total_price(tp), total_amount(tm) {}; ap_pair & operator+=(const ap_pair &); float total_price; float total_amount; }; void APC :: compute_total () { string name; map<string, ap_pair> :: iterator my_it; float num1, num2, num3; while (!fs.eof() ) { fs >> name >> num1 >> num2; //read in file ap_pair myobj(num1, num2); //send the weight/count and per unit price ap_pair my_it = mymap.find(name); //returns iterator if (fs.eof()) break; //makes it so the last line is not repeated mymap.insert(pair<string,ap_pair>(name, myobj(num1, num2))); //ERROR IS HERE num3= num1*num2; total_amount+=num1; total_price+= num3; } } I am getting an error when compiling saying " error: no match for call to '(ap_pair) (float&, float&)". Why is that? What is wrong with doing what I did? I've been working on this for over an hour with no solution in sight. Any ideas? I can give some more ideas of what I am trying to do if needed. I think this might be a simple syntax issue I am looking over though. A: myobj(num1, num2) This attempts to call your myobj object like a functor. Instead you just want to pass myobj: mymap.insert(pair<string,ap_pair>(name, myobj));
{ "language": "en", "url": "https://stackoverflow.com/questions/21191698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Thread Pool of workers in a Window service? I'm creating a Windows service with 2 separate components: 1 component creates jobs and inserts them to the database (1 thread) The 2nd component processes these jobs (multiple FIXED # of threads in a thread pool) These 2 components will always run as long as the service is running. What I'm stuck on is determining how to implement this thread pool. I've done some research, and there seems to be many ways of doing this such as creating a class that overriddes the method "ThreadPoolCallback", and using ThreadPool.QueueUserWorkItem to queue a work item. http://msdn.microsoft.com/en-us/library/3dasc8as.aspx However in the example given, it doesn't seem to fit my scenario. I want to create a FIXED number of threads in a thread pool initially. Then feed it jobs to process. How do I do this? // Wrapper method for use with thread pool. public void ThreadPoolCallback(Object threadContext) { int threadIndex = (int)threadContext; Console.WriteLine("thread {0} started...", threadIndex); _fibOfN = Calculate(_n); Console.WriteLine("thread {0} result calculated...", threadIndex); _doneEvent.Set(); } Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations]; const int FibonacciCalculations = 10; for (int i = 0; i < FibonacciCalculations; i++) { ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i); } A: Create a BlockingCollection of work items. The thread that creates jobs adds them to this collection. Create a fixed number of persistent threads that read items from that BlockingCollection and process them. Something like: BlockingCollection<WorkItem> WorkItems = new BlockingCollection<WorkItem>(); void WorkerThreadProc() { foreach (var item in WorkItems.GetConsumingEnumerable()) { // process item } } Multiple worker threads can be doing that concurrently. BlockingCollection supports multiple readers and writers, so there's no concurrency problems that you have to deal with. See my blog post Simple Multithreading, part 2 for an example that uses one consumer and one producer. Adding multiple consumers is a very simple matter of spinning up a new task for each consumer. Another way to do it is to use a semaphore that controls how many jobs are currently being processed. I show how to do that in this answer. However, I think the shared BlockingCollection is in general a better solution. A: The .NET thread pool isn't really designed for a fixed number of threads. It's designed to use the resources of the machine in the best way possible to perform multiple relatively small jobs. Maybe a better solution for you would be to instantiate a fixed number of BackgroundWorkers instead? There are some reasonable BW examples.
{ "language": "en", "url": "https://stackoverflow.com/questions/20429716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to edit NavItem of Navbar component in Bootstrap Studio? Problem: I am using Stylish Portfolio template to design a quick website in Bootstrap Studio. I am unable to edit the default NavItem (Home, About, Services and so on) from the Navbar component as shown in image below. Other components can be easily edited by double clicking on that component. But, the NavBar is hidden by default and shows only when we click on a hamburger icon. So, I am unable to edit the default fields of NavBar. Here is the screenshot of the Bootstrap Studio editor. What I have tried: By converting the component into HTML by Convert to HTML option, Bootstrap Studio gives the corresponding raw HTML file to edit and I was able to change the values from there. But, I think there must be a better way to edit the elements directly in Bootstrap studio instead. What am I missing? Please help! A: I couldn't find a way to make the NavBar visible for editing. But, a way around is to double click on the NavItem component and type the text you want for NavItem can change the NavItem. A: Click on "Show Toolbar" then "Open", this will show the items.
{ "language": "en", "url": "https://stackoverflow.com/questions/70202630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: SQL How to find average of many sums of groups only if the groups follow certain rules Here is my current code: SELECT AVG(famTotal) FROM `OmniHealth.new2015Data`, ( SELECT SUM( TOTEXP15 ) as famTotal FROM `OmniHealth.new2015Data` GROUP BY DUID ) WHERE BMINDX53 BETWEEN 0 AND 25 AND ADSMOK42 = -1 AND FCSZ1231 = 7 What I want to do is find the average cost per family where the family has all members with BMI between 0 and 25, don't smoke, and the family is an arbitrary size. The spending data is on a per person basis in the table, so I'm trying to sum it based on the "dwelling unit ID" (DUID) being the same for all of the people, and then averaging the total per family as long as the family only has the properties I stated in the last paragraph. Thank you for the replies! I'm new at SQL. A: Below is for BigQuery Standard SQL #standardSQL SELECT DUID, AVG(TOTEXP15) AS famAverage FROM `OmniHealth.new2015Data` GROUP BY DUID HAVING MIN(BMINDX53) >=0 AND MAX(BMINDX53) <=25 AND MIN(ADSMOK42) = -1 AND MAX(ADSMOK42) = -1 AND MIN(FCSZ1231) = 7 AND MAX(FCSZ1231) = 7 A: Consider joining two aggregate query derived tables that matches on count to align all household members to all household members with specific conditions. SELECT AVG(t1.famTotal) as famTotal FROM (SELECT DUID, Count(*) As GrpCount, SUM(TOTEXP15) as famTotal FROM `OmniHealth.new2015Data` GROUP BY DUID) As t1 INNER JOIN (SELECT DUID, Count(*) As GrpCount FROM `OmniHealth.new2015Data` WHERE BMINDX53 BETWEEN 0 AND 25 AND ADSMOK42 = -1 AND FCSZ1231 = 7 GROUP BY DUID) As t2 ON t1.DUID = t2.DUID AND t1.GrpCount = t2.GrpCount
{ "language": "en", "url": "https://stackoverflow.com/questions/48039288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to restrict the acess to a few users in pyTelegramBotAPI? I'm using telebot (https://github.com/eternnoir/pyTelegramBotAPI) to create a bot to send photos to its users. The point is I didn't see a way to restrict the access to this bot as I intend to share private images through this bot. I read in this forum that through python-telegram-bot there is a way to limit the access from the sender's message (How To Limit Access To A Telegram Bot), but I didn't know if via pyTelegramBotAPI it is possible. Do you know how can I solve it? A: A bit late tot the party - perhaps for future post readers. You can wrap the function to disallow access. An example below: from functools import wraps def is_known_username(username): ''' Returns a boolean if the username is known in the user-list. ''' known_usernames = ['username1', 'username2'] return username in known_usernames def private_access(): """ Restrict access to the command to users allowed by the is_known_username function. """ def deco_restrict(f): @wraps(f) def f_restrict(message, *args, **kwargs): username = message.from_user.username if is_known_username(username): return f(message, *args, **kwargs) else: bot.reply_to(message, text='Who are you? Keep on walking...') return f_restrict # true decorator return deco_restrict Then where you are handling commands you can restrict access to the command like this: @bot.message_handler(commands=['start']) @private_access() def send_welcome(message): bot.reply_to(message, "Hi and welcome") Keep in mind, order matters. First the message-handler and then your custom decorator - or it will not work. A: The easiest way is probably a hard coded check on the user id. # The allowed user id my_user_id = '12345678' # Handle command @bot.message_handler(commands=['picture']) def send_picture(message): # Get user id from message to_check_id = message.message_id if my_user_id = to_check_id: response_message = 'Pretty picture' else: response_message = 'Sorry, this is a private bot!' # Send response message bot.reply_to(message, response_message)
{ "language": "en", "url": "https://stackoverflow.com/questions/55437732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Compiling 32-bit programs and calling 64-bit programs on 64-bit systems My system is 64 bit. I have a program calls a command "bcdedit.exe" c++ code: ShellExecuteA(NULL, "open", "cmd.exe", "/c bcdedit.exe /?", NULL, SW_SHOWNORMAL); I compiled to 32 bit When I run it back "file not find" When I compiled to 64 bit, run passed The same problem exists in go go code: cmd := exec.Command("cmd.exe","/c","bcdedit.exe /?") out, err := cmd.CombinedOutput() if err != nil { fmt.Println(err) } fmt.Println(string(out)) I found "bcdedit.exe" in another directory: C:\\Windows\\WinSxS\\amd64_microsoft-windows-b..iondata-cmdlinetool_31bf3856ad364e35_10.0.17134.471_none_69b0e05efb5a4702\\bcdedit.exe When I call the command in this directory, all passed This directory is different on every PC How do I run the 32-bit compiled program for this command on each PC A: So your code attempts to launch "bcdedit.exe". From the command line, the only location of bcdedit.exe in your PATH environment is the Windows System directory, c:\Windows\System32. When you compile your code as 32-bit and run it on a 64-bit system, your process's view of the file system will change. Namely, the process view of the C:\Windows\System32 is replaced by the contents of C:\Windows\SysWOW64 - where only 32-bit DLLs and EXEs are located. However.... There is no 32-bit version bcdedit.exe located in this folder. (If you want to simulate this, go run c:\windows\syswow64\cmd.exe - you won't be able to find bcdedit.exe in the c:\windows\system32 folder anymore). You probably need something like this: How to retrieve correct path of either system32 or SysWOW64? Format your ShellExecute function to directly specificy the SysWow64 path for both bcdedit.exe and cmd.exe. Or as others have suggested, just compile for 64-bit.
{ "language": "en", "url": "https://stackoverflow.com/questions/55896402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generic class instantiation using a bounded wildcard Based on the code snippet listed in my previous question (copied from a Java tutorial on generics by Gilad Bracha), I wrote the following code which tries to populate a custom generic list called history with objects of different types conforming to the bound ? extends Shape. However, my program doesn't compile. Why? How is it different from the code snippet in my other question? import java.util.ArrayList; class Shape {} class Circle extends Shape {} class Rectangle extends Shape {} class MyArrayList<T> { private ArrayList<T> items = new ArrayList<>(); public T get(int idx) { return items.get(idx); } public void add(T item) { items.add(item); } @Override public String toString() { String str = "A box of ["; for (T item : items) { str += item; } str += ']'; return str; } } public class Shapes { private static MyArrayList<? extends Shape> history = new MyArrayList<>(); public static void main(String[] args) { history.add(new Circle()); history.add(new Rectangle()); System.out.println(history); } } A: In your previous example, you had a List<List<? extends Shape>>. Here you have a List<? extends Shape>. Completely different things. Given a MyArrayList<? extends Shape>, that is a REFERENCE (like a page in an address book, not like a house), and the 'page in the address book' (that'd be your variable) promises that the house you get to will be guaranteed to be one of a few different style. Specifically, it'll be a List<Shape>. Or it could be a List<Rectangle>. Or perhaps a List<Circle>. But it'll be either a list of all sorts of shapes, or a list of some sort of specific shape. This is different from just 'it's a list of all sorts of shapes' - that would be a List<Shape>, not a List<? extends Shape>. Given that it could be a list of circles, and it could also be a list of squares, everything you do with history needs to be a thing you could do to either one. .add(new Circle()) is not something that is valid for a List<Rectangle>. Hence, you can't do that, and history.add(new Circle()) is a compilation error. So why did the previous snippet work? Because that was about List<List<? extends Shape>> which is a completely different thing to a List<? extends Shape>. One stores shapes. One stores a list of shapes.
{ "language": "en", "url": "https://stackoverflow.com/questions/75501494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: custom inputAccessoryView as UIView from nib giving error: returned 0 width, assuming UIViewNoIntrinsicMetric I am using an inputAccessoryView which is loaded from a nib using the following UIView subclass: class CustomInputAccessoryView: UIView { @IBOutlet var containerView: UIView! @IBOutlet var contentView: UIView! @IBOutlet weak var button1: UIButton! @IBOutlet weak var button2: UIButton! @IBOutlet weak var textView: UITextView! override var intrinsicContentSize: CGSize { return CGSize.zero } override init(frame: CGRect) { super.init(frame: frame) setupInputAccessoryView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupInputAccessoryView() } func setupInputAccessoryView() { self.translatesAutoresizingMaskIntoConstraints = false Bundle.main.loadNibNamed("CustomInputAccessoryView", owner: self, options: nil) addSubview(containerView) containerView.frame = self.bounds } } I assign the view to the inputAccessoryView and set it up just by the following: var customInputAccessoryView = CustomInputAccessoryView() The inputAccessoryView loads properly and displays correctly. The problem is when I press inside the textView of the inputAccessoryView and the keyboard displays, I get the following error: <_UIKBCompatInputView: ...; frame = (0 0; 0 0); layer = <CALayer: ...>> returned 0 width, assuming UIViewNoIntrinsicMetric I have two files, a .swift file which is the subclass of UIView displayed above and the nib file by the same name. In the file owner of the nib I select the sub class (CustomInputAccessoryView) and wire up the outlets. I don't really know what is happening other than maybe the input accessory view automatically resizing to zero frame whenever the keyboard is displayed before going to the correct size. If so I'm assuming I need to change some AutoLayout priorities but what I have tried is not working. The only hard width constraints are the buttons which have fixed widths. The inputAccessoryView width should always be the width of the window it is displayed in.
{ "language": "en", "url": "https://stackoverflow.com/questions/50581092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: SwiftUI List color background I can't change background color of a view if i List static items. this my code: NavigationView { ZStack { Color("AppBackgroundColor").edgesIgnoringSafeArea(.all) List { Section(header: Text("Now in theaters")) { ScrollMovies(type: .currentMoviesInTheater) } Section(header: Text("Popular movies")) { ScrollMovies(type: .popularMovies) } }.listStyle(.grouped) } } A: List cannot be "painted". Please use the following instead: List of items: ForEach(items) { item in HStack { Text(item) } }.background(Color.red) Scrollable list of items: ScrollView { ForEach(items) { item in HStack { Text(item) } }.background(Color.red) } In your case: VStack { // or HStack for horizontal alignment Section(header: Text("Now in theaters")) { ScrollMovies(type: .currentMoviesInTheater) } Section(header: Text("Popular movies")) { ScrollMovies(type: .popularMovies) } }.background(Color.red) A: Using UITableView.appearance().backgroundColor can affect the background colour of all List controls in the app. If you only want one particular view to be affected, as a workaround, you can set it onAppear and set it back to the default onDisappear. import SwiftUI import PlaygroundSupport struct PlaygroundRootView: View { @State var users: [String] = ["User 1", "User 2", "User 3", "User 4"] var body: some View { Text("List") List(users, id: \.self){ user in Text(user) } .onAppear(perform: { // cache the current background color UITableView.appearance().backgroundColor = UIColor.red }) .onDisappear(perform: { // reset the background color to the cached value UITableView.appearance().backgroundColor = UIColor.systemBackground }) } } PlaygroundPage.current.setLiveView(PlaygroundRootView()) A: You can provide a modifier for the items in the list NavigationView { ZStack { Color("AppBackgroundColor").edgesIgnoringSafeArea(.all) List { Section(header: Text("Now in theaters")) { ScrollMovies(type: .currentMoviesInTheater) .listRowBackground(Color.blue) // << Here } Section(header: Text("Popular movies")) { ScrollMovies(type: .popularMovies) .listRowBackground(Color.green) // << And here } }.listStyle(.grouped) } } A: For SwiftUI on macOS this works : extension NSTableView { open override func viewDidMoveToWindow() { super.viewDidMoveToWindow() // set the background color of every list to red backgroundColor = .red } } It will set the background color of every list to red (in that example). A: iOS 16 Since Xcode 14 beta 3, You can change the background of all lists and scrollable contents using this modifier: .scrollContentBackground(.hidden) You can pass in .hidden to make it transparent. So you can see the color or image underneath. iOS 15 and below All SwiftUI's Lists are backed by a UITableView (until iOS 16). so you need to change the background color of the tableView. You make it clear so other views will be visible underneath it: struct ContentView: View { init(){ UITableView.appearance().backgroundColor = .clear } var body: some View { Form { Section(header: Text("First Section")) { Text("First cell") } Section(header: Text("Second Section")) { Text("First cell") } } .background(Color.yellow) } } Now you can use Any background (including all Colors) you want Note that those top and bottom white areas are the safe areas and you can use the .edgesIgnoringSafeArea() modifier to get rid of them. Also note that List with the .listStyle(GroupedListStyle()) modifier can be replaced by a simple Form. But keep in mind that SwiftUI controls behave differently depending on their enclosing view. Also you may want to set the UITableViewCell's background color to clear as well for plain tableviews A: Easiest way to do this for now is just to use UIAppearance proxy. SwiftUI is young so there's a couple of features not fully implemented correctly by Apple yet. UITableView.appearance().backgroundColor = .red A: @State var users: [String] = ["User 1", "User 2", "User 3", "User 4"] init(){ UITableView.appearance().backgroundColor = .red UITableViewCell.appearance().backgroundColor = .red UITableView.appearance().tableFooterView = UIView() } var body: some View { List(users, id: \.self){ user in Text(user) } .background(Color.red) } PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView()) A: A bit late to the party, but this may help. I use a combination of: * *Setting the UITableView.appearance appearance *Setting the UITableViewCell.appearance appearance *Settings the List listRowBackground modifier. Setting the appearance affects the entire app, so you may want to reset it to other values where applicable. Sample code: struct ContentView: View { var body: some View { let items = ["Donald", "Daffy", "Mickey", "Minnie", "Goofy"] UITableView.appearance().backgroundColor = .clear UITableViewCell.appearance().backgroundColor = .clear return ZStack { Color.yellow .edgesIgnoringSafeArea(.all) List { Section(header: Text("Header"), footer: Text("Footer")) { ForEach(items, id: \.self) { item in HStack { Image(systemName: "shield.checkerboard") .font(.system(size: 40)) Text(item) .foregroundColor(.white) } .padding([.top, .bottom]) } .listRowBackground(Color.orange)) } .foregroundColor(.white) .font(.title3) } .listStyle(InsetGroupedListStyle()) } } } A: since, you are asking for changing the background color of view, you can use .colorMultiply() for that. Code: var body: some View { VStack { ZStack { List { Section(header: Text("Now in theaters")) { Text("Row1") } Section(header: Text("Popular movies")) { Text("Row2") } /*Section(header: Text("Now in theaters")) { ScrollMovies(type: .currentMoviesInTheater) } Section(header: Text("Popular movies")) { ScrollMovies(type: .popularMovies) } */ }.listStyle(.grouped) }.colorMultiply(Color.yellow) } } Output:
{ "language": "en", "url": "https://stackoverflow.com/questions/57128547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Error in my c++ code using linkedlist "Stop working" my code stop working in that test case, i think that the error in function Checktables but i'm not sure and i can't fix the error please help me to tun this code correctly. image of a test case and the error this is a cpp file with main .cpp #include"Header.h" string Name; string namess; customer::customer() { name = ""; gsize = status = 0; next = NULL; } customer::customer(string name1, int gsize1, int status1) { name = name1; gsize = gsize1; status = status1; next = NULL; } waitinglist::waitinglist() { chairnum =50 ; totalcustomers = tables = 0; head = tail = NULL; } waitinglist::waitinglist(int val) { chairnum = 50; totalcustomers = 0; tables = 0; head = tail = NULL; } void waitinglist::change() { customer*temp ; temp = head; cout << "enter the name: "; cin >> namess; while (temp != NULL) { if (namess == temp->name) { if (temp->status==2) { temp->status=1; cout << "done! " << endl ; break ; } } else if (namess != temp->name) { temp = temp->next; } } if (temp == NULL) { cout << "can't found! " << endl; } } void waitinglist::newcustomer() { customer*tmp = new customer; cout << "enter the name: "; cin >> tmp->name; customer*tmpo=new customer; tmpo=head ; while (tmpo != NULL) { if (tmp->name != tmpo->name) { tmpo = tmpo->next; } else if (tmp->name == tmpo->name) { cout<<"The Name already exist! " << endl ; cout << "enter the name: "; cin >> tmp->name; tmpo=head; } } cout << "enter the group number: "; cin >> tmp->gsize; cout << "enter the status: "; cin >> tmp->status; if (head == NULL) // linkedlist is empty { head = tail = tmp; totalcustomers++; } else { tail->next = tmp; tail=tail->next; totalcustomers++; } } void waitinglist::checktables() { float c=5.00; customer*temp=head; customer*found; cout<<"enter number of tables: "; cin >> tables ; while (tables>=1 && temp!=NULL) { int x; float y; y=((temp->gsize)/c); x=(temp->gsize)/c; if (tables<y) { temp=temp->next; } else if (tables>=y) { if (x==y) { tables=tables-x ; // Correct Table! cout<<temp->name<<endl; } else if (x!=y) { tables=tables-(x+1); cout<<temp->name<<endl; } found=temp ; delete found; // Discard break ; } } } void waitinglist::displayall() { customer *tmp; tmp = head; if (tmp == NULL) { cout << "Empty!"; } while (tmp != NULL) { cout << "Name: " << tmp->name <<endl; cout << "group number: " << tmp->gsize << endl; tmp = tmp->next; } cout << endl; } void waitinglist::diplaycustomer() { customer*tmp; tmp = head; cout << "enter the name: "; cin >> Name; while (tmp != NULL) { if (Name == tmp->name) { cout << "the name : " << tmp->name << endl; cout << "the group size = " << tmp->gsize << endl; cout << "the status = " << tmp->status << endl; break; } else if (Name != tmp->name) { tmp = tmp->next; } } if (tmp == NULL) { cout << "can't found!" << endl; } } int main() { int choice; string name1 = ""; int gsize1 = 0; int status1 = 0; waitinglist mylist; cout << "Note: 1 in status means the customer not here and 2 means the customer is here.\n"; cout << "Select your option.\n\n"; cout << "(1) Add a new Customer.\n"; cout << "(2) Display information based on Name.\n"; cout << "(3) List all Names.\n"; cout << "(4) to change the status. \n" ; cout << "(5) Check tables by name. \n"; cout << "(6) quit. \n"; do { cout << "\n"; cout << "Enter your choice: --> "; cin >> choice; if (1 <= choice && choice <= 5) { switch (choice) { case 1: mylist.newcustomer(); break; case 2: mylist.diplaycustomer(); break; case 3: mylist.displayall(); break; case 4: mylist.change() ; break; case 5 : mylist.checktables(); break; default: cout << "Invalid choice. Enter again.\n\n"; break; } } else if (choice>6) { cout << "Invalid choice. Enter again.\n\n"; break; } } while (choice != 6); return 0; } and this is the header file .h #include<iostream> #include<string> using namespace std; class customer { public: string name; int gsize; int status; customer* next; customer(); customer(string,int,int); }; class waitinglist { public: int tables; //number of occupied tables int chairnum; int totalcustomers; customer*head,*tail; waitinglist(); waitinglist(int); void newcustomer(); void diplaycustomer(); void displayall(); void change () ; void checktables(); }; A: One error is that your checktables function corrupts your linked list structure by calling delete on one of the nodes: found = temp; delete found; // Discard What you've just done in those lines above is to have a linked list with a broken (invalid) link in it. Any functions that now traverses the list (like displaytables) will now hit the broken link, and things start to go haywire. To delete a node from a linked list, you have to not just call delete, but adjust the link in waitinglist that used to point to that deleted node and have it point to the next node after the deleted one. Think of it like a real chain -- if one of the links in the chain needs to be removed, you have to physically remove it, and hook the link before it to the next good link. You didn't do this step. I won't write the code for that, but this is what you should have seen much earlier in the development of your program. Better yet would have been to write a singly-linked list class that adds and removes nodes correctly first. Test it, and then once it can add and remove nodes successfully without error, then use it in your larger program.
{ "language": "en", "url": "https://stackoverflow.com/questions/34503439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: How to mock other class functions in testing controller in Laravel I am trying to test a controller in Laravel that uses another class as a helper which calls an API and returns the result. To avoid external API calls, I need to mock this helper. I tried to mock the class inside the controller and run the test but I didn't get what I expected in mock class. this is my controller method: public function A(Request $request){ $helper = new TheHelper(); $result = $helper->getResult($request->email); if($result){ return response()->json([ 'success' => true, 'message' => "result found", ], 200); }else{ return response()->json([ 'success' => false, 'message' => "no result", ], 500); } } My helper method simply calls an API and returns the result. class TheHelper { public function getResult($email){ // some api calls return $result; } } Here is my test: public function testExample() { $helperMock = Mockery::mock(TheHelper::class); // Set expectations $helperMock ->shouldReceive('getResult') ->once() ->with('[email protected]') ->andReturn([ 'id' => '100' ]); $this->app->instance(TheHelper::class, $helperMock); $this->json( 'POST', '/api/test_method', ['email' => '[email protected]']) ->assertStatus(200); } My mock function never called. it only checks with the real API inside TheHelper method A: Your test is creating a mock object and binding that mock object into the Laravel service container. However, your controller is not pulling a TheHelper instance from the Laravel service container; it is manually instantiating it with the new keyword. Using the new keyword is core PHP, and does not involve Laravel at all. Your test is showing you an issue in your code. TheHelper is a dependency of your method, and should therefore be passed into the method instead of being created inside the method. You either need to update your controller method to use dependency injection, so that Laravel can automatically resolve the TheHelper dependency from its container, or you need to replace your new keyword with a call into the Laravel container. Using dependency injection: public function A(Request $request, TheHelper $helper) { $result = $helper->getResult($request->email); // rest of function... } Manually pull from the container: public function A(Request $request) { $helper = app(TheHelper::class); $result = $helper->getResult($request->email); // rest of function... }
{ "language": "en", "url": "https://stackoverflow.com/questions/57097454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changes in the fxml file are not visible Basically when i update my .fxml file, i can't see the new stuff...it's like showing the old version of the .fxml...with the old stuff... and yes i save the file... This is my Main.java package Library.Assistant.Ui.Main; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class MainLoader extends Application { public static void main(String arg[]) { launch(arg); } @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("Main.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } } This is my Main.fxml <?xml version="1.0" encoding="UTF-8"?> <?import com.jfoenix.controls.JFXButton?> <?import com.jfoenix.controls.JFXTextField?> <?import javafx.geometry.Insets?> <?import javafx.scene.control.Button?> <?import javafx.scene.control.Label?> <?import javafx.scene.control.ListView?> <?import javafx.scene.control.Menu?> <?import javafx.scene.control.MenuBar?> <?import javafx.scene.control.MenuItem?> <?import javafx.scene.control.Tab?> <?import javafx.scene.control.TabPane?> <?import javafx.scene.control.TextField?> <?import javafx.scene.image.Image?> <?import javafx.scene.image.ImageView?> <?import javafx.scene.layout.BorderPane?> <?import javafx.scene.layout.ColumnConstraints?> <?import javafx.scene.layout.GridPane?> <?import javafx.scene.layout.HBox?> <?import javafx.scene.layout.RowConstraints?> <?import javafx.scene.layout.VBox?> <VBox maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" minHeight="-Infinity" minWidth="-Infinity" prefHeight="548.0" prefWidth="617.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Library.Assistant.Ui.Main.MainController"> <children> <MenuBar maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308"> <menus> <Menu mnemonicParsing="false" text="File"> <items> <MenuItem mnemonicParsing="false" text="Close" /> </items> </Menu> <Menu mnemonicParsing="false" text="Edit"> <items> <MenuItem mnemonicParsing="false" text="Delete" /> </items> </Menu> <Menu mnemonicParsing="false" text="Help"> <items> <MenuItem mnemonicParsing="false" text="About" /> </items> </Menu> </menus> </MenuBar> <GridPane fx:id="grid" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" VBox.vgrow="ALWAYS"> <columnConstraints> <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" /> <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" /> </columnConstraints> <rowConstraints> <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" /> <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" /> <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" /> <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" /> <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" /> </rowConstraints> <children> <TabPane maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" tabClosingPolicy="UNAVAILABLE" GridPane.rowSpan="2147483647"> <tabs> <Tab text="Book Issue"> <content> <VBox alignment="CENTER" prefHeight="200.0" prefWidth="100.0"> <children> <HBox alignment="CENTER" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" VBox.vgrow="ALWAYS"> <children> <TextField fx:id="enterBookID" promptText="Enter Book ID" /> <VBox alignment="CENTER" prefHeight="200.0" prefWidth="100.0" HBox.hgrow="ALWAYS"> <children> <Label text="Book Name" /> <Label text="Author" /> </children> </VBox> </children> </HBox> <HBox alignment="CENTER" layoutX="10.0" layoutY="10.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" VBox.vgrow="ALWAYS"> <children> <TextField promptText="Enter Member ID" /> <VBox alignment="CENTER" prefHeight="200.0" prefWidth="100.0" HBox.hgrow="ALWAYS"> <children> <Label text="Member Name" /> <Label text="Contact" /> </children> </VBox> </children> </HBox> <HBox alignment="CENTER" layoutX="10.0" layoutY="404.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" VBox.vgrow="ALWAYS"> <children> <JFXButton maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" text="Issue" HBox.hgrow="ALWAYS" /> </children> </HBox> </children> </VBox> </content> </Tab> <Tab text="Renew / Submission"> <content> <VBox maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308"> <children> <BorderPane maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" VBox.vgrow="ALWAYS"> <top> <JFXTextField alignment="CENTER" promptText="Enter Book ID" BorderPane.alignment="CENTER"> <BorderPane.margin> <Insets bottom="20.0" left="10.0" right="10.0" top="10.0" /> </BorderPane.margin> </JFXTextField> </top> <center> <ListView maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" BorderPane.alignment="CENTER" /> </center> <bottom> <HBox maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" BorderPane.alignment="CENTER"> <children> <JFXButton maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" text="Renew" HBox.hgrow="ALWAYS" /> <JFXButton maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" text="Submission" HBox.hgrow="ALWAYS" /> </children> <BorderPane.margin> <Insets /> </BorderPane.margin> </HBox> </bottom> </BorderPane> </children> </VBox> </content> </Tab> </tabs> </TabPane> <Button contentDisplay="TOP" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Add Member" GridPane.columnIndex="1"> <graphic> <ImageView fitHeight="50.0" fitWidth="50.0" pickOnBounds="true" preserveRatio="true"> <image> <Image url="@add_mem.png" /> </image> </ImageView> </graphic> </Button> <Button contentDisplay="TOP" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Add Book" GridPane.columnIndex="1" GridPane.rowIndex="1"> <graphic> <ImageView fitHeight="50.0" fitWidth="50.0" pickOnBounds="true" preserveRatio="true"> <image> <Image url="@add_book.png" /> </image> </ImageView> </graphic> </Button> <Button contentDisplay="TOP" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="View Members" GridPane.columnIndex="1" GridPane.rowIndex="2"> <graphic> <ImageView fitHeight="50.0" fitWidth="50.0" pickOnBounds="true" preserveRatio="true"> <image> <Image url="@list_mem.png" /> </image> </ImageView> </graphic> </Button> <Button contentDisplay="TOP" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="View Books" GridPane.columnIndex="1" GridPane.rowIndex="3"> <graphic> <ImageView fitHeight="50.0" fitWidth="50.0" pickOnBounds="true" preserveRatio="true"> <image> <Image url="@list_book.png" /> </image> </ImageView> </graphic> </Button> <Button contentDisplay="TOP" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Settings" GridPane.columnIndex="1" GridPane.rowIndex="4"> <graphic> <ImageView fitHeight="50.0" fitWidth="50.0" pickOnBounds="true" preserveRatio="true"> <image> <Image url="@settings.png" /> </image> </ImageView> </graphic> </Button> </children> </GridPane> </children> </VBox> I just can't understand why it's showing the old version of the file...yesterday everything was working fine.I was adding new stuff and it was showing them properly, but today it keeps showing the version from yesterday...no matter how many stuff i change..
{ "language": "en", "url": "https://stackoverflow.com/questions/65508895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: POST method in Flask app = Flask(__name__) @app.route('/') def home(): return render_template("home.html") @app.route('/login_page', methods=["GET","POST"]) def login_page(): if request.method == "POST": user=request.form["login"] return redirect(url_for("user",usr=user)) else: return render_template("login_page.html") @app.route('/register_page') def register_page(): return render_template("register_page.html") @app.route('/home', methods=["GET","POST"]) @app.route("/<usr>") def user(usr): return f"<h1>{usr}</h1>" if __name__ == '__main__': app.run(debug=True) here is my error TypeError: user() missing 1 required positional argument: 'usr', i dont understand where user function is missing argument here is my folder tree https://i.stack.imgur.com/5pvkT.png A: You've defined your user function like this: def user(usr) This says that it requires a single positional argument. You have two routes pointing at this function: - @app.route('/home', methods=["GET","POST"]) - @app.route("/<usr>") Only the second route provides the necessary usr variable. When you visit the route /home, you'll get the TypeError you've shown in your question. Depending on how you want the function to behave when no user is specified, it may make more sense to have a second function handling /home. Maybe that was supposed to be an alternate route for the home function instead?
{ "language": "en", "url": "https://stackoverflow.com/questions/67712557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VBA Excel code to save picture as PNG to file location I tried different codes but I cant go with the correct output. I want to have a code that I can choose a file location. All working, I just need to save the PNG to file location selected when saving. I only got the following: FName = "C:\Users\Desktop\Nutrifacts and Analysis-Save\1.png" Sub picsave_Click() Dim pic_rng As Range Dim ShTemp As Worksheet Dim ChTemp As Chart Dim PicTemp As Picture Dim FName As String FName = "C:\Users\Desktop\Nutrifacts and Analysis-Save\1.png" Application.ScreenUpdating = False ThisWorkbook.Windows(1).DisplayGridlines = False Set pic_rng = Worksheets(1).Range("A1:R31") Set ShTemp = Worksheets.Add Charts.Add ActiveChart.Location Where:=xlLocationAsObject, Name:=ShTemp.Name Set ChTemp = ActiveChart pic_rng.CopyPicture Appearance:=xlScreen, Format:=xlPicture With ThisWorkbook.Sheets(1) ActiveSheet.Shapes.Item(1).Line.Visible = msoFalse ActiveSheet.Shapes.Item(1).Width = .Range("A1:R31").Width ActiveSheet.Shapes.Item(1).Height = .Range("A1:R31").Height End With ChTemp.Paste ChTemp.Export fileName:=FName, Filtername:="png" Application.DisplayAlerts = False ShTemp.Delete Application.DisplayAlerts = True ThisWorkbook.Windows(1).DisplayGridlines = True Application.ScreenUpdating = True Set ShTemp = Nothing Set ChTemp = Nothing Set PicTemp = Nothing MsgBox ("Done.") End Sub A: Try below. Added varResult variable to get the filename. You may change it as you want. Used Application.GetSaveAsFilename to get the file name. Sub test() Dim pic_rng As Range Dim ShTemp As Worksheet Dim ChTemp As Chart Dim PicTemp As Picture Dim FName As String Dim varResult As Variant On Error Resume Next FName = "C:\Users\Desktop\Nutrifacts and Analysis-Save\1.png" 'displays the save file dialog varResult = Application.GetSaveAsFilename(FileFilter:="PNG (*.png), *.png") If varResult = False Then Exit Sub ' do what you want Else FName = varResult End If Application.ScreenUpdating = False ThisWorkbook.Windows(1).DisplayGridlines = False Set pic_rng = Worksheets(1).Range("A1:R31") Set ShTemp = Worksheets.Add Charts.Add ActiveChart.Location Where:=xlLocationAsObject, Name:=ShTemp.Name Set ChTemp = ActiveChart pic_rng.CopyPicture Appearance:=xlScreen, Format:=xlPicture With ThisWorkbook.Sheets(1) ActiveSheet.Shapes.Item(1).Line.Visible = msoFalse ActiveSheet.Shapes.Item(1).Width = .Range("A1:R31").Width ActiveSheet.Shapes.Item(1).Height = .Range("A1:R31").Height End With ChTemp.Paste ChTemp.Export Filename:=FName, Filtername:="png" Application.DisplayAlerts = False ShTemp.Delete Application.DisplayAlerts = True ThisWorkbook.Windows(1).DisplayGridlines = True Application.ScreenUpdating = True Set ShTemp = Nothing Set ChTemp = Nothing Set PicTemp = Nothing MsgBox ("Done.") End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/41604629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Memory leak reported by instrument. Can't understand why Instruments is telling that the following method is leaking memory when creating the mutable string. Can anybody tell me why? I am using ARC on iOS 8 XCode 6.2. - (NSString *)capitalizeFirstLetter { if (self.length == 0) { return self; } NSMutableString * string = [NSMutableString stringWithString:self.lowercaseString]; [string replaceCharactersInRange:NSMakeRange(0, 1) withString:[self substringToIndex:1].capitalizedString]; return string; } A: I am not sure what caused the leak, but if you want to only avoid it you can change your method to: - (NSString *)capitalizeFirstLetter { if (self.length == 0) { return self; } return [NSString stringWithFormat:@"%@%@", [self substringToIndex:1].capitalizedString, [self substringFromIndex:1]]; } also you could review the answeres here Need help fixing memory leak - NSMutableString
{ "language": "en", "url": "https://stackoverflow.com/questions/29326481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Load data in a webpart lifecycle works first time, but in a popup reload it doesnt refresh So, here is the scenarion I have a webpart that loads some data. I have in another place of the page a button, that opens a popup, when the user does something in that page (create action), the popup is closed and the calling page is reloaded. When this happen, I can see in the browser that the page is reloaded, but my new data is not shown on the webpart. I am binding the data in the create child controls, I tried to do it in the page load but then it doesnt work. If I put my cursor on the address bar then it shows me the new data, but if I press F5 it doesnt. public class LastCreatedJobs : WebPart { private GridView _lastCreatedJobsGrid; protected override void CreateChildControls() { base.CreateChildControls(); CreateGridControl(); } private void CreateGridControl() { try { _lastCreatedJobsGrid = new GridView(); _lastCreatedJobsGrid.RowDataBound += _lastCreatedJobsGrid_RowDataBound; var bJobCode = new BoundField { DataField = "JobCode", HeaderText = "Job Code" }; bJobCode.ItemStyle.CssClass = "ms-cellstyle ms-vb2"; bJobCode.HeaderStyle.CssClass = "ms-vh2"; _lastCreatedJobsGrid.Columns.Add(bJobCode); var jobName = new HyperLinkField { DataNavigateUrlFields = new[] { "JobWebsite" }, HeaderText = "Job Name", DataTextField = "JobName" }; jobName.ItemStyle.CssClass = "la"; jobName.HeaderStyle.CssClass = "ms-vh2"; jobName.ControlStyle.CssClass = "ms-listlink"; _lastCreatedJobsGrid.Columns.Add(jobName); var biPowerLink = new HyperLinkField { Target = "_blank", DataNavigateUrlFields = new[] { "IPowerLink" }, HeaderText = "iP Link", Text = @"<img src='" + ResolveUrl("/_layouts/15/PWC/DMS/Images/iclient.gif") + "' /> " }; biPowerLink.ItemStyle.CssClass = "ms-cellstyle ms-vb-icon"; biPowerLink.HeaderStyle.CssClass = "ms-vh2"; _lastCreatedJobsGrid.Columns.Add(biPowerLink); _lastCreatedJobsGrid.CssClass = "ms-listviewtable"; //Table tag? _lastCreatedJobsGrid.HeaderStyle.CssClass = "ms-viewheadertr ms-vhlt"; _lastCreatedJobsGrid.RowStyle.CssClass = "ms-itmHoverEnabled ms-itmhover"; _lastCreatedJobsGrid.AutoGenerateColumns = false; _lastCreatedJobsGrid.EmptyDataText = Constants.Messages.NoJobsFound; Controls.Add(_lastCreatedJobsGrid); LoadGridData(); } catch (Exception ex) { LoggingService.LogError(LoggingCategory.Job, ex); } } private void _lastCreatedJobsGrid_RowDataBound(object sender, GridViewRowEventArgs e) { try { if (e.Row.RowType == DataControlRowType.DataRow) { JobInfo jobInfo = (JobInfo)e.Row.DataItem; if (jobInfo.IsConfidential) { var newHyperLink = new HyperLink { Text = @"<img src='" + ResolveUrl("/_layouts/15/PWC/DMS/Images/spy-icon.gif") + "' /> ", NavigateUrl = jobInfo.xlink }; e.Row.Cells[2].Controls.RemoveAt(0); e.Row.Cells[2].Controls.Add(newHyperLink); } } } catch (Exception ex) { LoggingService.LogError(LoggingCategory.Job, ex); } } #region Private methods private void LoadGridData() { try { String currentUrl = SPContext.Current.Site.Url; var jobInfoList = new List<JobInfo>(); SPSecurity.RunWithElevatedPrivileges(delegate { using (var clientSiteCollection = new SPSite(currentUrl)) { foreach ( SPWeb web in clientSiteCollection.AllWebs.Where( c => c.AllProperties[Constants.WebProperties.General.WebTemplate] != null && c.AllProperties[Constants.WebProperties.General.WebTemplate].ToString() == Constants.WebTemplates.JobWebPropertyName).OrderByDescending(d => d.Created).Take(5) ) { SPList jobInfoListSp = web.Lists.TryGetList(Constants.Lists.JobInfoName); if (jobInfoListSp != null) { if (jobInfoListSp.Items.Count > 0) { var value = new SPFieldUrlValue( jobInfoListSp.Items[0][Constants.FieldNames.Job.iPowerLink].ToString()); jobInfoList.Add(new JobInfo { JobName = jobInfoListSp.Items[0][Constants.FieldNames.Job.JobName].ToString(), JobCode = jobInfoListSp.Items[0][Constants.FieldNames.Job.JobCode].ToString(), xlink= value.Url, JobWebsite = web.Url, IsConfidential = HelperFunctions.ConvertToBoolean(jobInfoListSp.Items[0][Constants.FieldNames.Job.Confidential].ToString()) }); } } web.Dispose(); } } }); _lastCreatedJobsGrid.DataSource = jobInfoList; _lastCreatedJobsGrid.DataBind(); } catch (Exception ex) { LoggingService.LogError(LoggingCategory.Job, ex); } } #endregion } and the page that opens the popup: <asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server"> <SharePoint:ScriptLink ID="ScriptLink1" runat="server" Name="sp.js" OnDemand="false" Localizable="false" LoadAfterUI="true"/> <script type="text/javascript"> //Just an override from the ClientField.js - Nothing Special to do here function DisableClientValidateButton() { } function waitMessage() { window.parent.eval("window.waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Creating Job','Working on the Job site. Please wait.',90,450);"); } </script> </asp:Content> and the code behind of that page, in a button click, just the important part, after the button is clicked. ClientScript.RegisterStartupScript(GetType(), "CloseWaitDialog", @"<script language='javascript'> if (window.frameElement != null) { if (window.parent.waitDialog != null) { window.parent.waitDialog.close(); window.frameElement.commonModalDialogClose(1, 'New call was successfully logged.'); } } </script>"); A: The trick here is that the loadgrid data has to be executed in the OnPreRender.
{ "language": "en", "url": "https://stackoverflow.com/questions/17608604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Confused about readlink /usr/lib/libpcre.so I am following http://www.linuxfromscratch.org/blfs/view/svn/general/pcre.html to install pcrc (OS: CentOS 6.6). I am confused about this line ln -sfv ../../lib/$(readlink /usr/lib/libpcre.so) /usr/lib/libpcre.so I know it is creating a soft link but not sure why it needs readlink and why it is ../../lib instead of /lib? Hope it is clear. Any help appreciated. A: Be careful with that. These are generic instructions and they assume a non-CentOS/fedora distro. In CentOS/fedora, /lib is a symlink to /usr/lib (and /lib64 is a symlink to /usr/lib64). So, the instructions won't work. On other distros, /lib and /usr/lib are distinct directories. The command is trying to create a symlink from /usr/lib to /lib, such that: /usr/lib/libpcre.so --> /lib/libpcre.so And, /lib/libcpre.so is the real file. On CentOS/fedora, this would create a symlink cycle: /usr/lib/libpcre.so --> /usr/lib/libpcre.so Unless you have a specific reason not to, just do "yum install pcre" and let the distro install handle it. You may also want the development package: "yum install pcre-devel" Also, note that the instructions are for a 32 bit system. If yours is 64 bit, then we're talking about /lib64 and /usr/lib64. If your system is 64 bit, but you want to create 32 bit apps, you'll need "yum install pcre.i686" IMO, in the instructions, using "&&" is "getting cute" and makes me distrust them a bit (e.g. ./configure -blah && make) is technically correct, but it's usually better to do these as separate steps: - ./configure -blah - check for errors - make - check for errors The reason that it's relative (using ../..) is so that you could install under /usr/local or other (e.g /usr/local/lib and /usr/local/usr/lib)
{ "language": "en", "url": "https://stackoverflow.com/questions/33044239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Right full approach to convert a Website Theme to an React components I am facing issues in converting AdminLTE theme in React component. As the theme uses third parties js libraries and some custom js function, i am really finding it difficult to implementing. Don't know where to put and how to put. This all works well in the static demo HTML pages, as the custom.js is loaded towards the end of the HTML page and after all the third parties libraries, all nodes are presented at the moment and ready for selectors to select. A: It is really a slow and painfull process to convert a a existing theme to a react theme. CSS are not a issue, the issue are all the javascripts that pretends to manipulate the DOM directly. My advice is to search components that are replicas of the functionality already in the theme and then style it according to the css (adjustment will be necessary) of the original theme. If you want a reference on HOW wrap standard libraries in a react component, take a look at the official docs about the topic: https://reactjs.org/docs/integrating-with-other-libraries.html
{ "language": "en", "url": "https://stackoverflow.com/questions/52327600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++: How can I allow user to retry if they accidentally enter more than one character in char variable? Question: In C++, ow do I make a program throw out an error when a user enters multiple characters for an input requesting a single character? I'd like to have the program re-prompt for a single character, but it just keeps going and entering the multiple characters on later lines. This is a very simple program I wrote to test out character inputs and their properties to help me with another assignment. I wanted to see how it would react to multi-character inputs. //Include statements #include <iostream> #include <string> using namespace std; //main statement int main () { //name variables int numChar; char letterEntry; string finalWord = ""; //begin entry cout << "This program will let you enter characters and combine them into a string." << endl; cout << "First tell us how many characters you want to enter." << endl; cin >> numChar; //convert characters to string and add to string variable int counter = 0; while (counter<numChar) { cout << "Enter a character!" << endl; cin >> letterEntry; finalWord = finalWord + string(1, letterEntry); counter++; } //Display final word cout << "Your word is " << finalWord << endl; return(0); } This is an output that demonstrates my issue. This program will let you enter characters and combine them into a string. First tell us how many characters you want to enter. 3 Enter a character! DOGS Enter a character! Enter a character! Your word is DOG I want the program to not save anything if the user types in more than one character. I want it to print an error message that says "You entered more than one character, please retry," and lets them try again. Is there a way to do this with type char? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/32787653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: wxPython print string with formatting so I have the following class which prints the text and header you call with it. I also provided the code I am using to call the Print function. I have a string 'outputstring' which contains the text I want to print. My expected output is below and my actual output is below. It seems to be removing spaces which are needed for proper legibility. How can I print while keeping the spaces? Class: #Printer Class class Printer(HtmlEasyPrinting): def __init__(self): HtmlEasyPrinting.__init__(self) def GetHtmlText(self,text): "Simple conversion of text. Use a more powerful version" html_text = text.replace('\n\n','<P>') html_text = text.replace('\n', '<BR>') return html_text def Print(self, text, doc_name): self.SetHeader(doc_name) self.PrintText(self.GetHtmlText(text),doc_name) def PreviewText(self, text, doc_name): self.SetHeader(doc_name) HtmlEasyPrinting.PreviewText(self, self.GetHtmlText(text)) Expected Print: +-------------------+---------------------------------+------+-----------------+-----------+ | Domain: | Mail Server: | TLS: | # of Employees: | Verified: | +-------------------+---------------------------------+------+-----------------+-----------+ | bankofamerica.com | ltwemail.bankofamerica.com | Y | 239000 | Y | | | rdnemail.bankofamerica.com | Y | | Y | | | kcmemail.bankofamerica.com | Y | | Y | | | rchemail.bankofamerica.com | Y | | Y | | citigroup.com | mx-b.mail.citi.com | Y | 248000 | N | | | mx-a.mail.citi.com | Y | | N | | bnymellon.com | cluster9bny.us.messagelabs.com | ? | 51400 | N | | | cluster9bnya.us.messagelabs.com | Y | | N | | usbank.com | mail1.usbank.com | Y | 65565 | Y | | | mail2.usbank.com | Y | | Y | | | mail3.usbank.com | Y | | Y | | | mail4.usbank.com | Y | | Y | | us.hsbc.com | vhiron1.us.hsbc.com | Y | 255200 | Y | | | vhiron2.us.hsbc.com | Y | | Y | | | njiron1.us.hsbc.com | Y | | Y | | | njiron2.us.hsbc.com | Y | | Y | | | nyiron1.us.hsbc.com | Y | | Y | | | nyiron2.us.hsbc.com | Y | | Y | | pnc.com | cluster5a.us.messagelabs.com | Y | 49921 | N | | | cluster5.us.messagelabs.com | ? | | N | | tdbank.com | cluster5.us.messagelabs.com | ? | 0 | N | | | cluster5a.us.messagelabs.com | Y | | N | +-------------------+---------------------------------+------+-----------------+-----------+ Actual Print: The same thing as expected but the spaces are removed making it very hard to read. Function call: def printFile(): outputstring = txt_tableout.get(1.0, 'end') print(outputstring) app = wx.PySimpleApp() p = Printer() p.Print(outputstring, "Data Results") A: For anyone else struggling, this is the modified class function I used to generate a nice table with all rows and columns. def GetHtmlText(self,text): html_text = '<h3>Data Results:</h3><p><table border="2">' html_text += "<tr><td>Domain:</td><td>Mail Server:</td><td>TLS:</td><td># of Employees:</td><td>Verified</td></tr>" for row in root.ptglobal.to_csv(): html_text += "<tr>" for x in range(len(row)): html_text += "<td>"+str(row[x])+"</td>" html_text += "</tr>" return html_text + "</table></p>" A: maybe try `html_text = text.replace(' ','&nbsp;').replace('\n','<br/>')` that would replace your spaces with html space characters ... but it would still not look right since it is not a monospace font ... this will be hard to automate ... you really want to probably put it in a table structure ... but that would require some work you probably want to invest a little more time in your html conversion ... perhaps something like (making assumptions based on what you have shown) def GetHtmlText(self,text): "Simple conversion of text. Use a more powerful version" text_lines = text.splitlines() html_text = "<table>" html_text += "<tr><th> + "</th><th>".join(text_lines[0].split(":")) + "</th></tr> for line in text_lines[1:]: html_text += "<tr><td>"+"</td><td>".join(line.split()) +"</td></tr> return html_text + "</table>"
{ "language": "en", "url": "https://stackoverflow.com/questions/24148387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android app with static content/data I am making an android app and trying to figure out the best way to store the data. The data is fully static and will basically be several items with a name, logo and phone number for each. The data will then be shown using a listview. So my question, what is the best way to store the data? Xml, json, SQLite or something else? I want something that makes it easy to write down the data using Eclipse (like XML) but also easy to retrieve the data without the need to use a bunch of extra code. A: If the data must last as long as the application session lasts, then caching them as JSON objects would be suitable. You could use GSON to quickly convert them to your JAVA model, but the objects also sound simple enough to parse using Android's out of the box JSONObject class. If the data must persist beyond the application's session, you can still store them in the SharedPreferences as JSON objects. I wouldn't use SQLite, because the data doesn't sound heavy & complex. The data sounds small & light enough for caching or SharedPreferences based on the data's persistence.
{ "language": "en", "url": "https://stackoverflow.com/questions/23771171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there an alternative to CGPath which allows to compute points on a path for a given location? For an animation timing algorithm I need to supply a path as the curve. Probably a bezier curve with control points on both ends. The problem is that it seems not possible to calculate points on a CGPath because CGPathRef is opaque. Also Apple provides no mechanism to compute points on a path. Is there a library or utility class which can compute points on a bezier curve or path, for a given location like 0.5 for the middle along the path? Or let me rephrase it: If CGPath / CGPathRef makes this impossible because it is opaque, and if you only care about bezier curves, is there a way to compute points for locations along the path? A: The math behind a Bézier path is actually "just": start⋅(1-t)3 + 3⋅c1⋅t(1-t)2 + 3⋅c2⋅t2(1-t) + end⋅t3 This means that if you know, the start, the end and both control points (c1 and c2), then you can calculate the value for any t (from 0 to 1). It the values are points (like in the image below) then you can do these calculations separately for x and y. This is form my explanation of Bézier paths here and the code to update the orange circle as the slider changes (in Javascript) is simply this (it shouldn't be too hard to translate into Objective-C or simply C but I was too lazy): var sx = 190; var sy = 80; // start var ex = 420; var ey = 250; // end var c1x = -30; var c1y = 350; // control point 1 var c2x = 450; var c2y = -20; // control point 2 var t = (x-minSliderX)/(maxSliderX-minSliderX); // t from 0 to 1 var px = sx*Math.pow(1-t, 3) + 3*c1x*t*Math.pow(1-t, 2) + 3*c2x*Math.pow(t,2)*(1-t) + ex*Math.pow(t, 3); var py = sy*Math.pow(1-t, 3) + 3*c1y*t*Math.pow(1-t, 2) + 3*c2y*Math.pow(t,2)*(1-t) + ey*Math.pow(t, 3); // new point is at (px, py) A: If you already have the control points to the bezier curve you would like to use for the timing function (of what I presume to be CAAnimation), then you should use the following function to get the appropriate timing function: [CAMediaTimingFunction functionWithControlPoints:(float)c1x :(float)c1y :(float)c2x :(float)c2y] However, if what you are trying to do is calculate the Y-locaiton of a bezier curve for a given X-location, you will have to calculate that yourself. Here is a reference for how to do so: Bezier Curves A: Point location calculation from CGPath (Swift 4). extension Math { // Inspired by ObjC version of this code: https://github.com/ImJCabus/UIBezierPath-Length/blob/master/UIBezierPath%2BLength.m public class BezierPath { public let cgPath: CGPath public let approximationIterations: Int private (set) lazy var subpaths = processSubpaths(iterations: approximationIterations) public private (set) lazy var length = subpaths.reduce(CGFloat(0)) { $0 + $1.length } public init(cgPath: CGPath, approximationIterations: Int = 100) { self.cgPath = cgPath self.approximationIterations = approximationIterations } } } extension Math.BezierPath { public func point(atPercentOfLength: CGFloat) -> CGPoint { var percent = atPercentOfLength if percent < 0 { percent = 0 } else if percent > 1 { percent = 1 } let pointLocationInPath = length * percent var currentLength: CGFloat = 0 var subpathContainingPoint = Subpath(type: .moveToPoint) for element in subpaths { if currentLength + element.length >= pointLocationInPath { subpathContainingPoint = element break } else { currentLength += element.length } } let lengthInSubpath = pointLocationInPath - currentLength if subpathContainingPoint.length == 0 { return subpathContainingPoint.endPoint } else { let t = lengthInSubpath / subpathContainingPoint.length return point(atPercent: t, of: subpathContainingPoint) } } } extension Math.BezierPath { struct Subpath { var startPoint: CGPoint = .zero var controlPoint1: CGPoint = .zero var controlPoint2: CGPoint = .zero var endPoint: CGPoint = .zero var length: CGFloat = 0 let type: CGPathElementType init(type: CGPathElementType) { self.type = type } } private typealias SubpathEnumerator = @convention(block) (CGPathElement) -> Void private func enumerateSubpaths(body: @escaping SubpathEnumerator) { func applier(info: UnsafeMutableRawPointer?, element: UnsafePointer<CGPathElement>) { if let info = info { let callback = unsafeBitCast(info, to: SubpathEnumerator.self) callback(element.pointee) } } let unsafeBody = unsafeBitCast(body, to: UnsafeMutableRawPointer.self) cgPath.apply(info: unsafeBody, function: applier) } func processSubpaths(iterations: Int) -> [Subpath] { var subpathArray: [Subpath] = [] var currentPoint = CGPoint.zero var moveToPointSubpath: Subpath? enumerateSubpaths { element in let elType = element.type let points = element.points var subLength: CGFloat = 0 var endPoint = CGPoint.zero var subpath = Subpath(type: elType) subpath.startPoint = currentPoint switch elType { case .moveToPoint: endPoint = points[0] case .addLineToPoint: endPoint = points[0] subLength = type(of: self).linearLineLength(from: currentPoint, to: endPoint) case .addQuadCurveToPoint: endPoint = points[1] let controlPoint = points[0] subLength = type(of: self).quadCurveLength(from: currentPoint, to: endPoint, controlPoint: controlPoint, iterations: iterations) subpath.controlPoint1 = controlPoint case .addCurveToPoint: endPoint = points[2] let controlPoint1 = points[0] let controlPoint2 = points[1] subLength = type(of: self).cubicCurveLength(from: currentPoint, to: endPoint, controlPoint1: controlPoint1, controlPoint2: controlPoint2, iterations: iterations) subpath.controlPoint1 = controlPoint1 subpath.controlPoint2 = controlPoint2 case .closeSubpath: break } subpath.length = subLength subpath.endPoint = endPoint if elType != .moveToPoint { subpathArray.append(subpath) } else { moveToPointSubpath = subpath } currentPoint = endPoint } if subpathArray.isEmpty, let subpath = moveToPointSubpath { subpathArray.append(subpath) } return subpathArray } private func point(atPercent t: CGFloat, of subpath: Subpath) -> CGPoint { var p = CGPoint.zero switch subpath.type { case .addLineToPoint: p = type(of: self).linearBezierPoint(t: t, start: subpath.startPoint, end: subpath.endPoint) case .addQuadCurveToPoint: p = type(of: self).quadBezierPoint(t: t, start: subpath.startPoint, c1: subpath.controlPoint1, end: subpath.endPoint) case .addCurveToPoint: p = type(of: self).cubicBezierPoint(t: t, start: subpath.startPoint, c1: subpath.controlPoint1, c2: subpath.controlPoint2, end: subpath.endPoint) default: break } return p } } extension Math.BezierPath { @inline(__always) public static func linearLineLength(from: CGPoint, to: CGPoint) -> CGFloat { return sqrt(pow(to.x - from.x, 2) + pow(to.y - from.y, 2)) } public static func quadCurveLength(from: CGPoint, to: CGPoint, controlPoint: CGPoint, iterations: Int) -> CGFloat { var length: CGFloat = 0 let divisor = 1.0 / CGFloat(iterations) for idx in 0 ..< iterations { let t = CGFloat(idx) * divisor let tt = t + divisor let p = quadBezierPoint(t: t, start: from, c1: controlPoint, end: to) let pp = quadBezierPoint(t: tt, start: from, c1: controlPoint, end: to) length += linearLineLength(from: p, to: pp) } return length } public static func cubicCurveLength(from: CGPoint, to: CGPoint, controlPoint1: CGPoint, controlPoint2: CGPoint, iterations: Int) -> CGFloat { let iterations = 100 var length: CGFloat = 0 let divisor = 1.0 / CGFloat(iterations) for idx in 0 ..< iterations { let t = CGFloat(idx) * divisor let tt = t + divisor let p = cubicBezierPoint(t: t, start: from, c1: controlPoint1, c2: controlPoint2, end: to) let pp = cubicBezierPoint(t: tt, start: from, c1: controlPoint1, c2: controlPoint2, end: to) length += linearLineLength(from: p, to: pp) } return length } @inline(__always) public static func linearBezierPoint(t: CGFloat, start: CGPoint, end: CGPoint) -> CGPoint{ let dx = end.x - start.x let dy = end.y - start.y let px = start.x + (t * dx) let py = start.y + (t * dy) return CGPoint(x: px, y: py) } @inline(__always) public static func quadBezierPoint(t: CGFloat, start: CGPoint, c1: CGPoint, end: CGPoint) -> CGPoint { let x = QuadBezier(t: t, start: start.x, c1: c1.x, end: end.x) let y = QuadBezier(t: t, start: start.y, c1: c1.y, end: end.y) return CGPoint(x: x, y: y) } @inline(__always) public static func cubicBezierPoint(t: CGFloat, start: CGPoint, c1: CGPoint, c2: CGPoint, end: CGPoint) -> CGPoint { let x = CubicBezier(t: t, start: start.x, c1: c1.x, c2: c2.x, end: end.x) let y = CubicBezier(t: t, start: start.y, c1: c1.y, c2: c2.y, end: end.y) return CGPoint(x: x, y: y) } /* * http://ericasadun.com/2013/03/25/calculating-bezier-points/ */ @inline(__always) public static func CubicBezier(t: CGFloat, start: CGFloat, c1: CGFloat, c2: CGFloat, end: CGFloat) -> CGFloat { let t_ = (1.0 - t) let tt_ = t_ * t_ let ttt_ = t_ * t_ * t_ let tt = t * t let ttt = t * t * t return start * ttt_ + 3.0 * c1 * tt_ * t + 3.0 * c2 * t_ * tt + end * ttt } /* * http://ericasadun.com/2013/03/25/calculating-bezier-points/ */ @inline(__always) public static func QuadBezier(t: CGFloat, start: CGFloat, c1: CGFloat, end: CGFloat) -> CGFloat { let t_ = (1.0 - t) let tt_ = t_ * t_ let tt = t * t return start * tt_ + 2.0 * c1 * t_ * t + end * tt } } Usage: let path = CGMutablePath() path.move(to: CGPoint(x: 10, y: 10)) path.addQuadCurve(to: CGPoint(x: 100, y: 100), control: CGPoint(x: 50, y: 50)) let pathCalc = Math.BezierPath(cgPath: path) let pointAtTheMiddleOfThePath = pathCalc.point(atPercentOfLength: 0.5)
{ "language": "en", "url": "https://stackoverflow.com/questions/20521296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: iphone - Programmatically set (System-wide) proxy settings? I am new to iPhone development, so I'm sorry if this is a stupid question. I am developing an application whose purpose will be to route all iPhone activity through my company's proxy. Is there a way to programmatically set system-wide proxy settings in the iPhone (which will also take effect on the 3G connection)? I know there is a way to manually set proxy settings for each wifi connection. Detecting new networks and setting the proxy on them would be acceptable. However, I need to also be able to set the proxy on the 3G connection. Also, bonus: Is there a way to programmatically change the "Restrictions" settings? If anyone has any tips or can point me in the right direction, I would appreciate it. Thanks. EDIT: Please understand that this is for a legitimate purpose. Apple has to approve app store additions, so it's not like I'm trying to spread a virus. Please, constructive answers only. A: If you're configuring iPhones in a commercial environment, you should look at the Enterprise Deployment Guide. Specifically, you should look at using the iPhone Configuration Utility to create a *.mobileconfig configuration file that can be distributed to all the phones in your network. The *.mobileconfig plist supports changing the following proxy configuration settings on the phone: PropNetProxiesHTTPEnable (Integer, 1 = Proxy enabled) PropNetProxiesHTTPProxy (String, Proxy server address) PropNetProxiesHTTPPort (Integer, Proxy port number) HTTPProxyUsername (String, optional username) HTTPProxyPassword (String, optional password) PropNetProxiesProxyAutoConfigEnable (Integer, 1 = Auto proxy enabled) PropNetProxiesProxyAutoConfigURLString (String, URL that points to a PAC file where the configuration information is stored) The iPhone Configuration Utility does not currently support adding or editing those settings, so you may need to get your hands dirty with the Property List Editor application. Also, it looks like the latest version of the Enterprise Deployment Guide does not include the settings I've included above, but you should be able to find it in the previous version of the document. A: Pretty sure this is outside the Apple provided SDK sandbox. Probably possible with a jailbreak though.
{ "language": "en", "url": "https://stackoverflow.com/questions/543111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: PHP: class.object does not show print_r()? I'm trying to print class object using print_r. This is my index.php code <?php if (isset($_POST['btnLogin'])){ if (isset($_POST['username']) && !empty($_POST['username'])){ $username=$_POST['username']; }else{ $errusername="Enter Username"; } if (isset($_POST['password']) && !empty($_POST['password'])){ $username=$_POST['password']; }else{ $errpassword="Enter Password"; } if (isset($email) && isset($password)) { $user = new User(); print_r($user); } } ?> This is user.class.php <?php class User{ public $id,$name,$username,$password; public function login() { echo "this is function"; } } ?> I want to print class object for eg: OBJECT([username=>this,password=>this]) It does not show any errors and does not show the print_r result. A: Change: $username=$_POST['password']; With: $password=$_POST['password']; As the $password var is not set the print_r is not executed. A: You are validating $email but declaring $username and other error assigning $password if (isset($_POST['btnLogin'])){ if (isset($_POST['username']) && !empty($_POST['username'])){ $username=$_POST['username']; }else{ $errusername="Enter Username"; } if (isset($_POST['password']) && !empty($_POST['password'])){ $password=$_POST['password']; }else{ $errpassword="Enter Password"; } if (isset($username) && isset($password)) { $user = new User(); print_r($user); } } A: you can use echo "<pre>"; var_export( $user )
{ "language": "en", "url": "https://stackoverflow.com/questions/47736042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Vim python3 integration on mac I'm trying to work out to integrate Python3 into Vim, I know I need to do it when compiling vim but I cant seem to get it right. I'm using homebrew to install with the following script: brew install vim --override-system-vim --with-python3 It installs vim however when i check the version, python3 is still not supported. A: Finally found the solution - $ brew install vim --with-python3 A: I thought I had the same issue but realised I needed to re-start the shell. If the problem still persists, it may be that you have older versions that homebrew is still trying to install. brew cleanup would remove older bottles and perhaps allow you to install the latest. If this is still giving you trouble, I found removing vim with brew uninstall --force vim and then reinstalling with brew install vim --override-system-vim --with-python3 worked for me. EDIT 2018-08-22 Python 3 is now default when compiling vim. Therefore the command below should integrate vim with Python 3 automatically. brew install vim --override-system-vim A: This worked for me with the latest OS for mac at this date. Hope it works for you. brew install vim python3
{ "language": "en", "url": "https://stackoverflow.com/questions/35086949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: QT C++ QRegularExpression multiple matches I want to extract Information from a QString (.html) by using Regular Expressions. I explicitly want to use Regex (no Parser Solutions) and the class QRegularExpression (for several reasons e.g.: Reasons). For simplification aspects here is an problem equivalent task. Constructed source string: <foo><bar s>INFO1.1</bar> </ qux> <peter></peter><bar e>INFO1.2 </bar><fred></ senseless></fred></ xx><lol></lol></foo><bar s>INFO2.1</bar> </ nothing><endlessSenselessTags></endlessSenselessTags><rofl> <bar e>INFO2.2</bar></rofl> *Note:*There could be more or less INFOs and additional sensless tags. (6 Infos e.g.) Wanted: Info1.1 and Info1.2 and Info2.1 and Info2.2 (e.g. in List) Attempt 1. QRegularExpression reA(".*<bar [es]>(.*)</bar>.*", QRegularExpression::DotMatchesEverythingOption); -> INFOa</bar> </ qux> <peter></peter><bar e>INFOb </bar><fred></ senseless></fred></ xx><lol></lol></foo><bar s>INFOc</bar> </ nothing><endlessSenselessTags></endlessSenselessTags><rofl> <bar e>INFOd 2. QRegularExpression reA("(.*<bar [es]>(.*)</bar>.*)*", QRegularExpression::DotMatchesEverythingOption); ->senseless Problem: The Regex is always related to the whole String. <bar s>INFO</bar><bar s>INFO</bar> would select the first <bar s> and the last and </bar>. Wanted is first With QRegExp there seems to be a solution, but i want to do this with QRegularExpression. A: I'm adding a new similar answer due to the vexing lack of QRegularExpression answers that handle all capture groups specified, and not by name. I just wanted to be able to specify capture groups and get only those results, not the whole kitchen sink. That becomes a problem when blindly grabbing capture group 0, which is what almost all answers on SO do for QRegularExpressions with multiple results. This answer gets back all specified capture groups' in a list, and if no capture groups were specified, it returns capture-group 0 for a whole-regex match. I made this simplified code-snippet on Gist that doesn't directly address this question. The sample app below if a diff that does address this specific question. #include <QCoreApplication> #include <QRegularExpressionMatch> #include <QStringList> #include <iostream> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QStringList results; QRegularExpression this_regex("<bar \\w>(.*?)</bar>"); QString test_string = "<foo><bar s>INFO1.1</bar> </ qux> <peter></peter><bar e>INFO1.2\n\ </bar><fred></ senseless></fred></ xx><lol></lol></foo><bar s>INFO2.1</bar>\n\ </ nothing><endlessSenselessTags></endlessSenselessTags><rofl>\n\ <bar e>INFO2.2</bar></rofl>\n"; if(!this_regex.isValid()) { std::cerr << "Invalid regex pattern: " << this_regex.pattern().toStdString() << std::endl; return -2; } for (int i = 0; i < this_regex.captureCount()+1; ++i) { // This skips storing capture-group 0 if any capture-groups were actually specified. // If they weren't, capture-group 0 will be the only thing returned. if((i!=0) || this_regex.captureCount() < 1) { QRegularExpressionMatchIterator iterator = this_regex.globalMatch(test_string); while (iterator.hasNext()) { QRegularExpressionMatch match = iterator.next(); QString matched = match.captured(i); // Remove this if-check if you want to keep zero-length results if(matched.length() > 0){results << matched;} } } } if(results.length()==0){return -1;} for(int i = 0; i < results.length(); i++) { std::cout << results.at(i).toStdString() << std::endl; } return 0; } Output in console: INFO1.1 INFO2.1 INFO2.2 To me, dealing with Regular Expressions using QRegularExpression is less painful than the std::regex's, but they're both pretty general and robust, requiring more fine-tuned result-handling. I always use a wrapper I made for QRegularExpressions to quickly make the kind of regexes and results that I typically want to leverage. A: Maybe you can try with this QRegularExpression reA("(<bar [se]>[^<]+</bar>)"); QRegularExpressionMatchIterator i = reA.globalMatch(input); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); if (match.hasMatch()) { qDebug() << match.captured(0); } } that gives me this output "<bar s>INFO1.1</bar>" "<bar e>INFO1.2 </bar>" "<bar s>INFO2.1</bar>" "<bar e>INFO2.2</bar>" while this expression QRegularExpression reA("((?<=<bar [se]>)((?!</bar>).)+(?=</bar>))", QRegularExpression::DotMatchesEverythingOption); with this input <foo><bar s>INFO1</lol>.1</bar> </ qux> <peter></peter><bar e>INFO1.2 </bar><fred></ senseless></fred></ xx><lol></lol></foo><bar s>INFO2.1</bar> </ nothing><endlessSenselessTags></endlessSenselessTags><rofl> <bar e>INFO2.2</bar></rofl> gives me as output "INFO1</lol>.1" "INFO1.2 " "INFO2.1" "INFO2.2"
{ "language": "en", "url": "https://stackoverflow.com/questions/22489723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: alertDialog from xml layout im tryin to retrieve radio button value and checkbox value from alertdialog. this alert is created from xml layout here my xml file (ard.xml) <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" > <RadioGroup android:id="@+id/rardEtat" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_marginTop="10dp" > <RadioButton android:id="@+id/rd_bien" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Bien" android:checked="true" android:textSize="10pt" /> <RadioButton android:id="@+id/rd_casse" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Casse" android:layout_below="@+id/rd_bien" android:textSize="10pt" /> <RadioButton android:id="@+id/rd_abs" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_below="@+id/rd_casse" android:text="Absente" android:textSize="10pt" /> </RadioGroup> <CheckBox android:id="@+id/checked" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/rardEtat" android:textSize="10pt" android:text="Brule" /> <RadioGroup android:id="@+id/etatProprete" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/checked" > <RadioButton android:id="@+id/rd_propre" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_below="@+id/checked" android:checked="true" android:text="Propre" android:textSize="10pt" /> <RadioButton android:id="@+id/rd_sale" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_below="@+id/rd_propre" android:text="Sale" android:textSize="10pt" /> <RadioButton android:id="@+id/rd_tsale" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_below="@+id/rd_sale" android:text="Trop sale" android:textSize="10pt" /> </RadioGroup> </RelativeLayout> here is my activity (button listner) AlertDialog.Builder customDialog = new AlertDialog.Builder(this); LayoutInflater layoutInflater = (LayoutInflater)getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE); View view2=layoutInflater.inflate(R.layout.ard,null); RadioGroup radioGroupEtat=(RadioGroup) findViewById(R.id.rardEtat); int radioetat = radioGroupEtat.getCheckedRadioButtonId(); RadioButton etatbut = (RadioButton) findViewById(radioetat); String etatBac= etatbut.getText(); RadioGroup radioGroupProprete=(RadioGroup) findViewById(R.id.etatProprete); int radiopropre = radioGroupProprete.getCheckedRadioButtonId(); RadioButton propre = (RadioButton) findViewById(radiopropre); String etatPropre=propre.getText(); CheckBox checkBrule=(CheckBox) findViewById(R.id.checked); customDialog.setPositiveButton("OK", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface arg0, int arg1) { // TODO Auto-generated method stub // show what i've checked ! }}); customDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface arg0, int arg1) { // TODO Auto-generated method stub }}); customDialog.setView(view); customDialog.show(); } }); but im getting error in groupradio instanciation RadioGroup radioGroupEtat=(RadioGroup) findViewById(R.id.rardEtat); /* error here */ int radioetat = radioGroupEtat.getCheckedRadioButtonId(); Any help please A: I guess you must replace: RadioGroup radioGroupEtat=(RadioGroup) findViewById(R.id.rardEtat); to RadioGroup radioGroupEtat=(RadioGroup) view2.findViewById(R.id.rardEtat); because you have to find your children views inside your inflated parent view, and your parent view for alert dialog is view2
{ "language": "en", "url": "https://stackoverflow.com/questions/23484598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Json Schema example for oneOf objects I am trying to figure out how oneOf works by building a schema which validates two different object types. For example a person (firstname, lastname, sport) and vehicles (type, cost). Here are some sample objects: {"firstName":"John", "lastName":"Doe", "sport": "football"} {"vehicle":"car", "price":20000} The question is what have I done wrongly and how can I fix it. Here is the schema: { "description": "schema validating people and vehicles", "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "required": [ "oneOf" ], "properties": { "oneOf": [ { "firstName": {"type": "string"}, "lastName": {"type": "string"}, "sport": {"type": "string"} }, { "vehicle": {"type": "string"}, "price":{"type": "integer"} } ] } } When I try to validate it in this parser: https://json-schema-validator.herokuapp.com/ I get the following error: [ { "level" : "fatal", "message" : "invalid JSON Schema, cannot continue\nSyntax errors:\n[ {\n \"level\" : \"error\",\n \"schema\" : {\n \"loadingURI\" : \"#\",\n \"pointer\" : \"/properties/oneOf\"\n },\n \"domain\" : \"syntax\",\n \"message\" : \"JSON value is of type array, not a JSON Schema (expected an object)\",\n \"found\" : \"array\"\n} ]", "info" : "other messages follow (if any)" }, { "level" : "error", "schema" : { "loadingURI" : "#", "pointer" : "/properties/oneOf" }, "domain" : "syntax", "message" : "JSON value is of type array, not a JSON Schema (expected an object)", "found" : "array" } ] A: Try this: { "description" : "schema validating people and vehicles", "type" : "object", "oneOf" : [ { "type" : "object", "properties" : { "firstName" : { "type" : "string" }, "lastName" : { "type" : "string" }, "sport" : { "type" : "string" } } }, { "type" : "object", "properties" : { "vehicle" : { "type" : "string" }, "price" : { "type" : "integer" } }, "additionalProperties":false } ] } A: oneOf need to be used inside a schema to work. Inside properties, it's like another property called "oneOf" without the effect you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/25014650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "54" }
Q: Android ExoPlayer Playback speed very fast on Android 4.2 version It looks like on Android 4.2 (Jelly bean) has an issue using ExoPlayer Library. When used for Audio purpose to stream live music, the Playback is played at double the speed. I have raised an issue at the Github for ExoPlayer but no positive reply till yet. Anyone with any suggestion will be highly appreciated. Thanks A: this symptom will happen when any given player (not specific to Exo) cannot resolve from the source media either/or the input's sample-rate or bit-depth - If you start with one song using known values, say sample-rate 44100 Hertz and a bit-depth of 16 bits which are typical audio defaults, play this then convert it into permutations, say bit-depth of 8 bits to see if this makes a difference
{ "language": "en", "url": "https://stackoverflow.com/questions/25909954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Marshall an array of structs I am calling a C++ function from C#. As arguments it receives a pointer to an array of structs. struct A { int data; } int CFunction (A* pointerToFirstElementOfArray, int NumberOfArrayElements) In C# I have created the same struct (as a class) and I marshall it correctly (the first element in the array is received correctly). Here is my C# definition of the C++ struct: [StructLayout(LayoutKind.Sequential), Serializable] class A { int data; } The first element is read correctly so I know all the fields in the struct are marshalled correctly. The problem occurs when I try to send over an array of elements. How do I create an array of classes that will be in a single memory block (chunk), so the C++ function can increment the pointer to the array? I guess I would need something similar to stackalloc, however I belive that only works for primitive types? Thank you for your help. A: This is not intended to be a definitive answer, but merely an example of you could accomplish this using stackalloc and unsafe code. public unsafe class Example { [DllImport("library.dll")] private static extern int CFunction(A* pointerToFirstElementOfArray, int NumberOfArrayElements); public void DoSomething() { A* a = stackalloc A[LENGTH]; CFunction(a, LENGTH); } } Also, pay attention to the packing of the struct that the API accepts. You may have to play around with the Pack property of the StructLayout attribute. I believe the default is 4, but some APIs expect 1. Edit: For this to work you will have to change the declaration of A from a class to a struct. public struct A { public int data; }
{ "language": "en", "url": "https://stackoverflow.com/questions/4044345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I determine if a char* is a windows line ending? In my C program, I am looking through a file character by character for info. For some reason my data is getting windows line ending characters even though my code looks like it does below. I have tried a couple of things like temp[0]=='\r\n' while((temp = fgetc(file)) != EOF) { if((temp>=65 && temp<=90) || (temp>=97 && temp<=122) || (temp>=48 && temp<=57) || temp==39){ c[count]=temp; count++; } else break; A: Windows line endings consist of two separate characters, a carriage return ('\r') immediately followed by a newline ('\n'). Because they are a combination of two characters, you cannot detect them by looking at only one character at a time. If your code is running on Windows and the file is supposed to be interpreted as text, then open it in text mode (for instance, "r" instead of "rb"), and the line terminators should be automatically translated to single newlines. If you're running on a system that uses single newlines as line terminators (most anything but Windows these days) then no such translation will be performed. In that case, to detect Windows-style line terminators you need to keep track of whether the immediately previous character was a '\r'. When that is so, and the next character read is a '\n', then you've detected a line terminator. But if it should be considered erroneous for Windows-style terminators to be in the file, then consider instead just fixing the file via dos2unix or a similar utility.
{ "language": "en", "url": "https://stackoverflow.com/questions/56050349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generic way to initialize a JPA 2 lazy association So, the question at hand is about initializing the lazy collections of an "unknown" entity, as long as these are known at least by name. This is part of a more wide effort of mine to build a generic DataTable -> RecordDetails miniframework in JSF + Primefaces. So, the associations are usually lazy, and the only moment i need them loaded is when someone accesses one record of the many in the datatable in order to view/edit it. The issues here is that the controllers are generic, and for this I also use just one service class backing the whole LazyLoading for the datatable and loading/saving the record from the details section. What I have with come so far is the following piece of code: public <T> T loadWithDetails(T record, String... associationsToInitialize) { final PersistenceUnitUtil pu = em.getEntityManagerFactory().getPersistenceUnitUtil(); record = (T) em.find(record.getClass(), pu.getIdentifier(record)); for (String association : associationsToInitialize) { try { if (!pu.isLoaded(record, association)) { loadAssociation(record, association); } } catch (..... non significant) { e.printStackTrace(); // Nothing else to do } } return record; } private <T> void loadAssociation(T record, String associationName) throws IntrospectionException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { BeanInfo info = Introspector.getBeanInfo(record.getClass(), Object.class); PropertyDescriptor[] props = info.getPropertyDescriptors(); for (PropertyDescriptor pd : props) { if (pd.getName().equals(associationName)) { Method getter = pd.getReadMethod(); ((Collection) getter.invoke(record)).size(); } } throw new NoSuchFieldException(associationName); } And the question is, did anyone start any similar endeavor, or does anyone know of a more pleasant way to initialize collections in a JPA way (not Hibernate / Eclipselink specific) without involving reflection? Another alternative I could think of is forcing all entities to implement some interface with Object getId(); void loadAssociations(); but I don't like the idea of forcing my pojos to implement some interface just for this. A: With the reflection solution you would suffer the N+1 effect detailed here: Solve Hibernate Lazy-Init issue with hibernate.enable_lazy_load_no_trans You could use the OpenSessionInView instead, you will be affected by the N+1 but you will not need to use reflection. If you use this pattern your transaction will remain opened until the end of the transaction and all the LAZY relationships will be loaded without a problem. For this pattern you will need to do a WebFilter that will open and close the transaction.
{ "language": "en", "url": "https://stackoverflow.com/questions/25382072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby on Rails - how require is executed in application.js I am reading a book for "Ruby on Rails". In the "application.js", we are including other JavaScript libraries in the following way and more specific - jQuery UI: //= require jquery //= require jquery_ujs //= require jquery-ui As this is ordinary JavaScript file (not ruby extensions here like "html.erb" for exmaple) how the application knows to execute the require command? What kind of JavaScript syntax is this: //= and as this is ordinary JavaScript file, why we are not using "script" tags to include JavaScript files? Also, I have read here that "require" method will check for this library in define by $LOAD_PATH variable folders. How can I see where the "jquery-ui" is stored? I am asking because in other applications in order to use jQuery UI I should add not only JavaScript file, but css file and images used by the library - in this case, we are doing this only with single line? A: What kind of JavaScript syntax is this. Anything starting with a // is a Javascript comment. How is it able to process it ? Sprockets on the server side scans the JS file for directives. //= is a special Sprocket directive. When it encounters that directive it asks the Directive Processor to process the command, require in this example. In the absence of Sprockets the //= require .. line would be a simple JS comment. Ruby require vs Sprockets require These are two completely different things. The one you link to is Ruby's require. Why not use script tags to load JS files. Usually, you want to concatenate all your app JS files and then minify them into 1 master JS file and then include that. I recommend reading the YSlow best practices on this. I also recommend watching the Railscasts on Asset Pipline - http://railscasts.com/episodes/279-understanding-the-asset-pipeline Cheers!
{ "language": "en", "url": "https://stackoverflow.com/questions/13218006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to obtain only ALL Undocumented Stored Procs in SQL SERVER 2005 If I write SELECT * FROM sys.all_objects WHERE ([type] = 'P'); I will get all the SQL Stored Procedure. But how to obtain only the Undocumented ones? Thanks A: There isn't any way to query this list, but you can find it here List of Undocumented Stored Procedures in SQL Server
{ "language": "en", "url": "https://stackoverflow.com/questions/3191947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to calculate two data in one array? I'm a beginner in php, I want to calculate two data from one array, but I still don't understand how. For example, I have one data array $array = (1,2,3,4); and I want the output like this 1x2 = 2 1x3 = 3 1x4 = 4 2x3 = 6 2x4 = 8 3x4 = 12 I try some code but didn't help, and now I got stuck. sorry my language is not good. A: Just use two loops to iterate over the data: <?php $input = [1, 2, 3, 4]; foreach ($input as $left) { foreach ($input as $right) { if ($left < $right) { echo sprintf("%dx%d = %d\n", $left, $right, $left*$right); } } } For bigger data sets you might want to optimize it. Faster but harder to read: <?php $input = [1, 2, 3, 4]; foreach ($input as $key => $left) { foreach (array_slice($input, $key+1) as $right) { echo sprintf("%dx%d = %d\n", $left, $right, $left*$right); } } The output obviously is: 1x2 = 2 1x3 = 3 1x4 = 4 2x3 = 6 2x4 = 8 3x4 = 12
{ "language": "en", "url": "https://stackoverflow.com/questions/58668869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Old-school SQL DB access versus ORM (NHibernate, EF, et al). Who wins? I've been successful with writing my own SQL access code with a combination of stored procedures and parameterized queries and a little wrapper library I've written to minimize the ADO.NET grunge. This has all worked very well for me in the past and I've been pretty productive with it. I'm heading into a new project--should I put my old school stuff behind me and dig into an ORM-based solution? (I know there are vast high-concepts differences between NHibernate and EF--I don't want to get into that here. For the sake of argument, let's even lump LINQ with the old-school alternatives.) I'm looking for advice on the real-world application of ORM type stuff against what I know (and know pretty well). Old-school ADO.NET code or ORM? I'm sure there is a curve--does the curve have an ROI that makes things worthwhile? I'm anxious and willing to learn, but do have a deadline. A: I find that LINQ to SQL is much, much faster when I'm prototyping code. It just blows away any other method when I need something now. But there is a cost. Compared to hand-rolled stored procs, LINQ is slow. Especially if you aren't very careful as seemingly minor changes can suddenly make a single turn into 1+N queries. My recommendation. Use LINQ to SQL at first, then swtich to procs if you aren't getting the performance you need. A: A good question but a very controversial topic. This blog post from Frans Bouma from a few years back citing the pros of dynamic SQL (implying ORMs) over stored procedures sparked quite the fiery flame war. A: There was a great discussion on this topic at DevTeach in Montreal. If you go to this URL: http://www.dotnetrocks.com/default.aspx?showNum=240 you will be able to hear two experts in the field (Ted Neward and Oren Eini) discuss the pros and cons of each approach. Probably the best answer you will find on a subject that has no real definite answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/59972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to restrict Google places api autocomplete for some city names and all state names? <form> <input id="pac-input" value="" class="controls" type="text" placeholder="Search Box"> <input type="button" id="find" value="find" /> </form> <script> function initAutocomplete() { var options = { componentRestrictions: { country: "IN" } }; // Create the search box and link it to the UI element. var input = document.getElementById('pac-input'); var searchBox = new google.maps.places.Autocomplete(input, options); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD9CiSrNomU7HPw5PLIpFZYP6NXXOq0dlE&libraries=places&callback=initAutocomplete" async defer></script> I want that in searchbox text like "Maharashtra,india", "mumbai", "india" should not come.Basically I need only regions and localities and not state names or city names to appear in suggestion. Can anybody help ? A: Please refer : https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete If you look at the sample code in the 'JavaScript + HTML' section, the API allows you to set filters, for example, establishments. So, just set the types to your criteria and you should be good to go. Cheers, Mrugesh A: How to limit google autocomplete results to City and Country only You can refer this answer. function initialize() { var options = { types: ['(regions)'], componentRestrictions: {country: "us"} }; var input = document.getElementById('searchTextField'); var autocomplete = new google.maps.places.Autocomplete(input, options); }
{ "language": "en", "url": "https://stackoverflow.com/questions/33853186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Csv to PDF PDFBOX? I'm new to java, and I'm learning how to create PDF, I was using Itext to create PDF, but because it handles a license I stopped using it, and started using PDFbox. I've searched the internet for how to convert from CSV to PDF, but I can't find an example of how to use margins, or how to align the content. Using Itext, this is my code using Itext7, it works perfectly but i want to migrate it to PDFbox public static boolean isEmpty(File rutaCSV) { if(rutaCSV.isDirectory()){ String[] csvFiles = rutaCSV.list(); if (csvFiles.length > 0) { for (String cadena : csvFiles){ readCSV("path"); try{ File csvFile = new File("path"); if (csvFile.exists()){ csvFile.delete(); return false; } System.out.println(csvFile.delete()); }catch(Exception ex){ System.out.println(ex); } } return true; }else{ System.out.println("There's not files"); return true; } } return true; } public static void readCSV(String file, String cadena){ try{ FileReader filereader = new FileReader(file); // Configuración para leer el archivo con ; CSVParser parser = new CSVParserBuilder().withSeparator(';').build(); CSVReader csvReader = new CSVReaderBuilder(filereader) .withCSVParser(parser) .build(); Document pdfDocument = new Document(); pdfDocument.addTitle("Some"); pdfDocument.setMargins(0, 0,25,25); String fileName = cadena.replaceFirst("[.][^.]+$", ""); PdfWriter.getInstance(pdfDocument, new FileOutputStream("path"+fileName+".pdf")); pdfDocument.open(); PdfPTable tableData = new PdfPTable(5); PdfPCell cells; // Lista para guardar los datos leídos List<String[]> allData = csvReader.readAll(); for (String[] row : allData) { for (String cell : row) { cells =new PdfPCell(new Phrase(cell)); tableData.addCell(cells); } } pdfDocument.addTitle("Some"); pdfDocument.add(tableData); pdfDocument.close(); }catch(Exception ex){ ex.printStackTrace(); System.out.println("error"); } } Using PDFBox public static void main(String[] args) throws IOException, CsvException { PDDocument document = new PDDocument(); PDPage page = new PDPage(PDRectangle.A4); document.addPage(page); PDPageContentStream content = new PDPageContentStream(document, page); try{ String file = "C:\\Users\\brayan.milian\\Desktop\\pruebaFTP\\prueba.csv"; FileReader filereader = new FileReader(file); CSVParser parser = new CSVParserBuilder().withSeparator(';').build(); CSVReader csvReader = new CSVReaderBuilder(filereader) .withCSVParser(parser) .build(); List<String[]> allData = csvReader.readAll(); for (String row[] : allData) { for (String cell : row){ content.beginText(); content.setFont(PDType1Font.TIMES_BOLD, 12); content.showText(cell); content.endText(); } } content.close(); }catch(Exception ex){ System.out.println("dja"); } Can anyone help me?
{ "language": "en", "url": "https://stackoverflow.com/questions/70435706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check as CRAN, but do not skip any tests Is there any easy way with devtools::check() to run the extended CRAN checks but also run testhat tests that are marked as skip_on_cran()? Basically, I want to run the most comprehensive tests I can: all of the CRAN checks, plus all of my unit tests A: The current version of testhat::skip_on_cran just check a system variable: testthat::skip_on_cran function () { if (identical(Sys.getenv("NOT_CRAN"), "true")) { return(invisible(TRUE)) } skip("On CRAN") } On my site, the devtools::check does not set this environment variable even with cran = TRUE so all tests are run. That is, the question does not seem to make sense with the present version of testthat.
{ "language": "en", "url": "https://stackoverflow.com/questions/27557150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how to make on click once and then toggle and make sure the CSS of the toggle comes after the table being loaded? Hi i would like to ask how to draw the table once and then toggle the table. Besides that, the toggleSetting's css will only load after the table is done drawn/loaded. PS: i'm quite new to javascript and please be forgiving, thank you and also please ignore my terrible english. here is my toggle function function toggleSetting(setting, ctrl) { var stt = document.getElementById(setting); if (stt.style.display == 'none') { stt.style.display = ''; ctrl.className = "accordion2"; } else { stt.style.display = 'none'; ctrl.className = "accordion"; } } here is my code for the javascript function $("#tableAOnce").one("click", (function () { $.ajax({ type: "POST", url: "AccInfo.ashx", success: function (output) { try { output = JSON.parse(output); DrawTable(output); toggleSetting('toggleSBook', this); //alert(output); } catch (ex) { alert("error"); $('#tableA').empty(); } } , complete: function (data) { } }); the table in the DrawTable function is a table drawn using stringbuilder and append. function DrawTable(output){ var general = output; var sb = new StringBuilder(); sb.append("<table>"); sb.append("<tr>"); sb.append("<td>"); sb.append("</td>"); sb.append("</tr >"); sb.append("</table>"); $('#tableA').empty().html(sb.toString()); } this is my code for the main table <table> <tr> <td> <table id="tableAOnce" class="accordion" onclick="toggleSetting('toggleTab',this)" > <tr> <td align="left">Table1</td> </tr> </table> </td> </tr> <tr style="display:none;" id="toggleTab" > <td> <table id="tableA"></table> </td> </tr> </table> I've tried to using the toggleSetting function in complete:function(data) but it wont work. A: First, you did seem to leave out the web method directive on your general function. And your ajax call should thus include the web method. eg: [WebMethod] Public static function toggleSetting(setting, ctrl) { But a ajax call means your code behind will run just fine, but you can't update any control attributes because the web page has not been posted/sent to the server. So the web page and controls remains sitting on users desktop. You can call your server code, but it can't modify controls since the whole web page has not been sent up to the server (it is still sitting in the browser). Your current code setup thus needs a post back of the page. Or at the VERY least the part of the page with the controls you are setting. This suggest you might as well use a update panel, and your button code is not ajax or JS anymore. So, you could place regular asp button that posts back the pack. And update panel means a partial post back - so both the button and table have to be inside of that up-date panel for this to work. That means the page and a post back occurs, but ONLY what is inside the update panel goes up to the server. The other way? Don't call the server. Do this client side as js, and then you don't need or have to call server side code. And thus you not need any post back (full or partial with a update panel). So, I would consider writing the function in js, and not call the code behind (server side). However, I unfortunately find js somewhat hard to work with, but 100% client side code would be best. Eventually, if you going to run any code behind after a hide/show of the given control (client side), then eventually if ANY code is to run server side and set or work with those controls, then a post-back will be required. And your ajax post needs to include the web method in the url eg: $.ajax({ type: "POST", url: "AccInfo.ashx/toggleSetting", data: {setting: "some value", ctrl: "some value"} note VERY VERY careful in above how in the above json string the names are to be the SAME as the parameters you have for the server side function. But, without a post back? The settings will occur server side, but any post back from the client side will send up the whole web page in its current state, and the changed values of the controls server side will be over-written. So best to think that you have a copy of the web page sitting client side, and then one sitting server side. Changes on the server side copy of the web page will get over written by any post back. And changes server side will NOT appear until such time that the server side copy of the web page is sent back down to the client. You have: Client side web page. Change things, controls etc. client side. post-back. The web page is sent to server. Code behind runs (maybe update web page), and then the WHOLE page is sent back down to the browser. So, you can't run server side code that updates controls unless te web page is sent up to the server. If you break this rule, then you have changes being made client side and server side - but the two pages are out of sync now. Change the style attributes 100% client side. So in js, you can do the same as your c# server side code with something like this: function ShowUpload() { var JUpload = document.getElementById('<%=UploadFiles.ClientID%>') JUpload.style.display = "inline"; return false; } With jquery, then you can go: function mysetter(ctrl, setting, value) { $('#' + ctrl).css(setting, value); } And thus now set any style setting, say like: mysetter('Button1', 'display', 'none'); And, because hide and show is oh so very common? You can use this: $('#MyControl').hide(); or $('#MyControl').hide(); Note that hide() and show() actually sets the style display to "none" or "normal". So, I would would not do a ajax call to set/hide the controls UNLESS you using a full asp.net button and a full postback. Or put the buttons/controls and the asp.net button inside of a update panel, and you also not get a full page post back. Given that you just hiding and showing a button or control? I think this can with relative ease be handled with 100% client side browser code.
{ "language": "en", "url": "https://stackoverflow.com/questions/62893728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JNA / WinAPI. Simulate mouse click without moving the cursor doesn't work correctly EDIT: Sorry, but I am not sure that my questions was closed correcltly. I was suggested this thread but it doesn't answer on my question. I am able to simulate mouse click but it doesn't work correctly as I described in my question. I am still learning JNA and using it in my Java application (JNA 5.6.0 and jna-platform 5.6.0) but I hope people who familiar with C languages can understand me too because JNA is using WinAPI functions. My OS is Windows 10. What I have: * *Swing application that launches the Warcraft III game, runs the exe file of the game. *Low level keyboard hook that intercepts keystrokes LowLevelKeyboardProc() and calls click() method, which is described below. *Logic that should simulate mouse clicks on the coordinates of the game window (where the Inventory, Skills and Control are located), after pressing certain keys (as shown in the picture below). The problem is that I cannot achieve the correct execution of a mouse click on the coordinates of the game window. I want to say in advance that I do not violate the rules of the game's license agreement and I want to use it only for personal purposes for the old version of the game, 1.26. Also, I've seen a similar implementation in other programming languages, but I want to implement it in Java. Below I am attaching the 3 options that I tried, with a description of the problem: 1. Using User32.INSTANCE.SendMessage() public void click(KeyBindComponent keyBindComponent) { final int WM_LBUTTONDOWN = 513; final int WM_LBUTTONUP = 514; final int MK_LBUTTON = 0x0001; Map<String, Integer> cords = getCords(keyBindComponent); if (!cords.isEmpty()) { int xCord = cords.get("width"); int yCord = cords.get("height"); LPARAM lParam = makeLParam(xCord, yCord); user32Library.SendMessage(warcraft3hWnd, WM_LBUTTONDOWN, new WPARAM(MK_LBUTTON), lParam); user32Library.SendMessage(warcraft3hWnd, WM_LBUTTONUP, new WPARAM(MK_LBUTTON), lParam); System.out.println("x = " + xCord + " y = " + yCord); } } public static LPARAM makeLParam(int l, int h) { // note the high word bitmask must include L return new LPARAM((l & 0xffff) | (h & 0xffffL) << 16); } It was expected that an invisible click would be made on the test coordinate point (on the building). But the problem is that the area was allocated instead. I assume that the following sequence was performed: clicking the mouse down in the Сurrent mouse position and moving the cursor to the Сoordinate point for click. But I have no idea why this happened. 2. Using User32.INSTANCE.PostMessage() public void click(KeyBindComponent keyBindComponent) { final int WM_LBUTTONDOWN = 513; final int WM_LBUTTONUP = 514; Map<String, Integer> cords = getCords(keyBindComponent); if (!cords.isEmpty()) { int xCord = cords.get("width"); int yCord = cords.get("height"); LPARAM lParam = makeLParam(xCord, yCord); user32Library.PostMessage(warcraft3hWnd, WM_LBUTTONDOWN, new WPARAM(0), lParam); user32Library.PostMessage(warcraft3hWnd, WM_LBUTTONUP, new WPARAM(0), lParam); System.out.println("x = " + xCord + " y = " + yCord); } } public static LPARAM makeLParam(int l, int h) { // note the high word bitmask must include L return new LPARAM((l & 0xffff) | (h & 0xffffL) << 16); } The same situation happened,instead of clicking on the coordinates, the area was selected, as well as in the case of SendMessage(), probably I will not re-attach the picture twice. 3. Using User32.INSTANCE.SendInput() public void click(KeyBindComponent keyBindComponent) { Map<String, Integer> cords = getCords(keyBindComponent); if (!cords.isEmpty()) { int xCord = cords.get("width"); int yCord = cords.get("height"); mouseMove(xCord, yCord); mouseClick(); System.out.println("x = " + xCord + " y = " + yCord); } } void mouseMove(int x, int y) { final int MOUSEEVENTF_LEFTUP = 0x0004; final int MOUSEEVENTF_ABSOLUTE = 0x8000; INPUT input = new INPUT(); INPUT[] move = (INPUT[]) input.toArray(2); // Release the mouse before moving it move[0].type = new DWORD(INPUT.INPUT_MOUSE); move[0].input.setType("mi"); move[0].input.mi.dwFlags = new DWORD(MOUSEEVENTF_LEFTUP); move[0].input.mi.dwExtraInfo = new BaseTSD.ULONG_PTR(0); move[0].input.mi.time = new DWORD(0); move[0].input.mi.mouseData = new DWORD(0); move[1].type = new DWORD(INPUT.INPUT_MOUSE); move[1].input.mi.dx = new LONG(x); move[1].input.mi.dy = new LONG(y); move[1].input.mi.mouseData = new DWORD(0); move[1].input.mi.dwFlags = new DWORD(MOUSEEVENTF_LEFTUP + MOUSEEVENTF_ABSOLUTE); user32Library.SendInput(new DWORD(2), move, move[0].size()); } void mouseClick() { final int MOUSEEVENTF_LEFTUP = 0x0004; final int MOUSEEVENTF_LEFTDOWN = 0x0002; INPUT input = new INPUT(); INPUT[] click = (INPUT[]) input.toArray(2); click[0].type = new DWORD(INPUT.INPUT_MOUSE); click[0].input.setType("mi"); click[0].input.mi.dwFlags = new DWORD(MOUSEEVENTF_LEFTDOWN); click[0].input.mi.dwExtraInfo = new BaseTSD.ULONG_PTR(0); click[0].input.mi.time = new DWORD(0); click[0].input.mi.mouseData = new DWORD(0); click[1].type = new DWORD(INPUT.INPUT_MOUSE); click[1].input.setType("mi"); click[1].input.mi.dwFlags = new DWORD(MOUSEEVENTF_LEFTUP); click[1].input.mi.dwExtraInfo = new BaseTSD.ULONG_PTR(0); click[1].input.mi.time = new DWORD(0); click[1].input.mi.mouseData = new DWORD(0); user32Library.SendInput(new DWORD(2), click, click[0].size()); } In this case, there is no click at all on the coordinate point. Instead, when certain keys are pressed, the mouse is clicked in Current mouse position. By the way, I also tried using Java Robot, but it didn't work for me. Unfortunately the mouse cursor moved (disappeared) by about a milliseconds from the starting position to the point where you need to click and back to the starting position. Thank you for reading this to the end, I apologize for such a cumbersome explanation. Can anyone tell me what and where I made a mistake in the code? Since in all 3 options, I did not achieve the expected behavior. A: For the 3rd case, you did not use the MOUSEEVENTF_MOVE flag to move the mouse, so the mouse did not actually move. And also according to the document: If MOUSEEVENTF_ABSOLUTE value is specified, dx and dy contain normalized absolute coordinates between 0 and 65,535 void mouseMove(int x, int y) { INPUT move[2] = {}; DWORD fScreenWidth = ::GetSystemMetrics(SM_CXSCREEN); DWORD fScreenHeight = ::GetSystemMetrics(SM_CYSCREEN); move[0].type = move[1].type = INPUT_MOUSE; move[0].mi.dwFlags = MOUSEEVENTF_LEFTUP;// Release the mouse before moving it move[1].mi.dx = MulDiv(x, 65535, fScreenWidth); move[1].mi.dy = MulDiv(y, 65535, fScreenHeight); move[1].mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE; SendInput(2, move, sizeof(INPUT)); } Then use the MOUSEEVENTF_LEFTDOWN and MOUSEEVENTF_LEFTUP to click the current postion. Or you can directly merge the mouse move into the click event: void mouseMoveClick(int x, int y) { INPUT click[3] = {}; click[0].type = INPUT_MOUSE; click[0].mi.dwFlags = MOUSEEVENTF_LEFTUP;// Release the mouse before moving it DWORD fScreenWidth = ::GetSystemMetrics(SM_CXSCREEN); DWORD fScreenHeight = ::GetSystemMetrics(SM_CYSCREEN); click[1].type = INPUT_MOUSE; click[1].mi.dx = click[2].mi.dx= MulDiv(x, 65535, fScreenWidth); click[1].mi.dy = click[2].mi.dy= MulDiv(y, 65535, fScreenHeight); click[1].mi.dwFlags = MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE; click[2].type = INPUT_MOUSE; click[2].mi.dwFlags = MOUSEEVENTF_LEFTUP | MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE; SendInput(3, click, sizeof(INPUT)); } If you want to move back to the original position after the mouse click, you can use GetCursorPos to record the current position before moving. Then use mouseMove event or simpler SetCursorPos to return to the position. void click(int xCord, int yCord) { //mouseMove(xCord, yCord); POINT p = {}; GetCursorPos(&p); mouseMoveClick(xCord, yCord); SetCursorPos(p.x, p.y); }
{ "language": "en", "url": "https://stackoverflow.com/questions/65316317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google Cloud Loadbalancer HTTPS only (or forward http to https) We are running our infrastructure with different content servers in the Google cloud. We are using HTTP load balancing and forward traffic to our instance groups. At the moment we are struggling to accept HTTP but force/forward to HTTPS? What is the best practice to do that? Thank you in advance. :) Leo PS: we tried to use .htaccess rewrite on our loadbalanced (Apache) instances, but this does not work.
{ "language": "en", "url": "https://stackoverflow.com/questions/33242310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Chaining 4 unix commands together and breaking the command to additional lines I used to run a simple line in my .sh file, such as: python myFileA.py && python myFileB.py but i wanted to do it with 4 files. At first, i was thinking yea this is easy. python myFileA.py && python myFileB.py && python myFileC.py && python myFileD.py but in actuality, the commands are way more complex than this. I wanted to know if for cleanliness sake i can continue it to the next line with the _ character. python myFileA.py && _ python myFileB.py && _ python myFileC.py && _ python myFileD.py Is this the right character/design i should be using? You might be thinking, Why dont you just put them sequentially on seperate lines, but the answer to that is that the files are async, so when B starts, it will fail because A is not complete. I dont know if this adds much complexity, but it seems when i was doing the simple 2 command way, it was working as intended. A: Instead of underscore you need to use \ here for continuation: python myFileA.py && \ python myFileB.py && \ python myFileC.py && \ python myFileD.py However since you have && you don't really need to use \ and can just skip it: python myFileA.py && python myFileB.py && python myFileC.py && python myFileD.py A: With bash you don't need any continuation character following &&, ||, | python myFileA.py && python myFileB.py && python myFileC.py && python myFileD.py
{ "language": "en", "url": "https://stackoverflow.com/questions/26510569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: responsive Navbar issue, with the toggle menu I have been working on a responsive website design with React and react styled components, and I have an issue with the navigation bar responsiveness, it works well for the desktop and tablet and when I made a UseState hook that shows a toggle menu instead of a navigation bar for the mobile view everything still works good, but when implementing the Hook in the code, it Shows a white screen with no details on desktop, tablet and mobile view, even that I have set the toggle menu display to none if the width is more that 375px. import React from "react"; import { useState } from "react"; import { MenuIcon, CloseIcon } from "../assets/shared"; import { StyledNavLink } from "./StyledNavLink"; import { StyledNav } from "./StyledNav"; import { NavLink } from "react-router-dom"; const NavbarLinksList = () => ( <> <StyledNavLink to="/home"> <p>00 HOME</p> </StyledNavLink> <StyledNavLink to="/destination-a"> <p>01 DESTINATION</p> </StyledNavLink> <StyledNavLink to="/crew-a"> <p>02 CREW</p> </StyledNavLink> <StyledNavLink to="/technology-a"> <p>03 TECHNOLOGY</p> </StyledNavLink> </> ); const NavBar = () => { const [toggleMenu, setToggleMenu] = useState(false); return ( <div> <StyledNav> <div className="logo"> <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48"> <g fill="none" fill-rule="evenodd"> <circle cx="24" cy="24" r="24" fill="#FFF" /> <path fill="#0B0D17" d="M24 0c0 16-8 24-24 24 15.718.114 23.718 8.114 24 24 0-16 8-24 24-24-16 0-24-8-24-24z" /> </g> </svg> </div> <div className="line"></div> <div className="nav-links-container"> <StyledNavLink to="/home"> <p>00 HOME</p> </StyledNavLink> <StyledNavLink to="/destination-a"> <p>01 DESTINATION</p> </StyledNavLink> <StyledNavLink to="/crew-a"> <p>02 CREW</p> </StyledNavLink> <StyledNavLink to="/technology-a"> <p>03 TECHNOLOGY</p> </StyledNavLink> </div> <div className="toggle_menu"> {toggleMenu ? ( <CloseIcon onClick={() => setToggleMenu(false)} /> ) : ( <MenuIcon onClick={() => setToggleMenu(true)} /> )} {toggleMenu && ( <div className="menu_links"> <NavLink to="/" className="link"> Home </NavLink> <NavbarLinksList /> </div> )} </div> </StyledNav> </div> ); }; export default NavBar; import styled from "styled-components"; export const StyledNav = styled.div` display: flex; justify-content: space-between; position: fixed; width: 1672px; height: 96px; left: 55px; top: 40px; .nav-links-container { display: flex; justify-content: space-around; align-items: center; width: 830px; height: 96px; left: 842px; background: rgba(255, 255, 255, 0.04); backdrop-filter: blur(40.7742px); } .line { position: absolute; z-index: 10; width: 473px; height: 1px; left: 23.5%; top: 50%; background: #FFFFFF; mix-blend-mode: normal; opacity: 0.25; } .logo { padding-top: 1.2%; } .toggle_menu { display: none; } .active {text-decoration: solid underline rgba(255,255,255, 1) 5px; text-underline-offset: 2.3em;} @media screen and (max-width: 768px){ width: 710px; top: 0; .nav-links-container { width: 470px; p { height: 17px; left: 19.94%; right: 56.18%; top: calc(50% - 17px/2 + 0.5px); font-style: normal; font-weight: 400; font-size: 11px; line-height: 17px; /* identical to box height */ letter-spacing: 2.3625px; } } .line { display: none;} .logo {margin-top: 2.5%;} } @media screen and (max-width: 375px){ .toggle_menu { display: flex; align-items: flex-end; justify-content: flex-end;} } A: const [toggleMenu, setToggleMenu] = useState(false); should be... const [toggleMenu, setToggleMenu] = React.useState(false); Worked for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/73916490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: apache kafka partition,java Im very new to apache kafka, and i am trying to do kafka partitions while sending my string to kafka, doing exactly same as here public class Producer { public static void main(String[] argv)throws Exception { String topicName = "test"; //Configure the Producer Properties configProperties = new Properties(); configProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.4.226:9092"); configProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.ByteArraySerializer"); configProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer"); configProperties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG,CountryPartitioner.class.getCanonicalName()); configProperties.put("partitions.0","USA"); configProperties.put("partitions.1","India"); org.apache.kafka.clients.producer.Producer producer = new KafkaProducer(configProperties); ProducerRecord<String, String> rec = new ProducerRecord<String, String>(topicName,"message111"); producer.send(rec, new Callback() { public void onCompletion(RecordMetadata metadata, Exception exception) { System.out.println("Message sent to topic ->" + metadata.topic() +" stored at offset->" + metadata.offset()); } }); producer.close(); } } Now i'm getting an exception like this 2018-07-03 17:52:12 ERROR RecordBatch:102 - Error executing user-provided callback on message for topic-partition test-2: java.lang.NullPointerException at com.spnotes.kafka.partition.Producer$1.onCompletion(Producer.java:29) at org.apache.kafka.clients.producer.internals.RecordBatch.done(RecordBatch.java:99) at org.apache.kafka.clients.producer.internals.RecordBatch.maybeExpire(RecordBatch.java:136) at org.apache.kafka.clients.producer.internals.RecordAccumulator.abortExpiredBatches(RecordAccumulator.java:220) at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:192) at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:141) at java.lang.Thread.run(Thread.java:748) what i'm doing wrong? Thanks in advance. A: EDIT 3: Only thing is you have to create multiple partitions, see these steps.First we make a config file for each of the brokers (on Windows use the copy command instead) > cp config/server.properties config/server-1.properties > cp config/server.properties config/server-2.properties Now edit these new files and set the following properties: config/server-1.properties: broker.id=1 listeners=PLAINTEXT://:9093 log.dir=/tmp/kafka-logs-1 config/server-2.properties: broker.id=2 listeners=PLAINTEXT://:9094 log.dir=/tmp/kafka-logs-2 We already have Zookeeper and our single node started, so we just need to start the two new nodes: > bin/kafka-server-start.sh config/server-1.properties & > bin/kafka-server-start.sh config/server-2.properties & Now create a new topic with a replication factor of three along with 3 partitions it would solve the issue: > bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 3 --partitions 3 --topic my-replicated-topic
{ "language": "en", "url": "https://stackoverflow.com/questions/51154710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: input time value when step is 1 My prob is when I choose 00:05:00 for instance, the seconds part is not displayed, only 00:05 is displayed $('#compute').click(function(){ alert($('#inputTime').val()) }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <input id="inputTime" type="time" step="1" value="00:00:00"> <br> <input type="button" id="compute" value="compute">
{ "language": "en", "url": "https://stackoverflow.com/questions/48150279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to bring the answer of this binary multiplication code in binary? int product = 0; String num1 = "11100001"; String num2 = "10110001"; int multiplicand = Integer.parseInt(num1); int multiplier = Integer.parseInt(num2); for(int i=7; i>=0; i--) { if((multiplier & 01) != 0) { product=product+multiplicand; } multiplicand <<=1; multiplier >>=1; } System.out.println((product)); This is the code for binary multiplication. It has been asked about many times but I still have following confusion about this question: * *After the shifting operation,the binary result does not remain binary anymore. At the end the product variable is not binary. How do I don't let shifting affect the final result, so that the product is in binary? (In this specific example, the answer is 2115700113 which is clearly not a binary number. *What does 01 mean in (multiplier & 01)? Thanks for answer in advance. A: Try Integer.parseInt("100101", 2); This will parse the integer as a binary number. A: Just add this as a last statement: System.out.println(Integer.toBinaryString(product)); To see the binary version of your product. Java prints out the numbers using decimal base numbers, since human is the master. Internally in the memory, or CPU registry everything is binary.
{ "language": "en", "url": "https://stackoverflow.com/questions/35509049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to set pom.xml to run main class in maven project in netbeans May I ask what I should do to run main class in a maven project created in Netbeans IDE? I set the pom.xml like the following, but it doesn't work.Is there any other configuration in Netbeans I should modify? <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mycompany</groupId> <artifactId>mavenproject2</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>mavenproject2</name> <url>http://maven.apache.org</url> <build> <plugins> <!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <configuration> <mainClass>com.mycompany.mavenproject2.App</mainClass> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> </dependencies> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> </project> A: You can do the same in multiple ways. * *Using command line. mvn exec:java -Dexec.mainClass="com.example.Main" -Dexec.args="arg0 arg1" * *Using exec-maven-plugin. A: You have not configured your pom.xml to run the main class .Also , you can configure more than one main class to execute from the main class. The question is already been answered in stackoverflow by Mr Kai Sternad. i am sharing the link you can let me know if you are satisfied or not How to Configure pom.xml to run 2 java mains in 1 Maven project
{ "language": "en", "url": "https://stackoverflow.com/questions/35026857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java: have integer, need it in byte in 0x00 format I have an integer used to seed my for loop: for(int i = 0; i < value; i++) Within my for loop I am seeding a byte array with byte content values that increment +1. For instance new byte[]{0x00}; But the 0x00 needs to be 0x01 on the next iteration, how can I convert my value of integer i into a value of byte in the 0x00 format? I tried things like Byte.valueOf(Integer.toHexString(i)) but this just gives me a value that looks like 0 instead of 0x00. A: I think the real problem is that you are confused about number representations and text renderings of numbers. Here are some key facts that you need to understand: * *The byte type is the set of integral values from -128 to +127. *All integral types use the same representation (2's complement). The difference between the different types is their ranges. *When you "see" a number, what you are seeing is a rendering of the number into a sequence of characters. There are MANY possible renderings; e.g. the number represented in memory as 00101010 (42) can be rendered as "42" or "+42" or "0x2a" or ... "forty two". *The default format for rendering a byte, short, int and long is the same; i.e. an optional minus sign followed by 1 or more decimal digits (with no zero padding). If you want to see your numbers formatted differently, then you need to do the formatting explicitly; e.g. using String.format(...). So to pull this together, if you want the bytes to look like 0x00 and 0x01 when you output or display them, you need to format them appropriately as you output / display them. In your example code, I doubt that there is anything wrong with the numbers themselves, or with the loop you are using to populate the array. A: You are confusing the string representation of the value with the value itself. A value can be represented as binary, decimal, or hex, but it is still the same value. If you want to use your integer to initialise a byte array, you just need to cast your integer value to a byte value as follows: arr[i] = (byte) i; A: new byte[]{0x00} is actually equivalent to new byte[]{0} The 0x00 notation is just an alternative way to write integer constants, and if the integer constant is in the range -128 to 127, then it can be used as a byte. If you have an existing integer variable that you want to use, and its value is in the range -128 to 127, then you just have to cast it: int i = 1; new byte[]{(byte)i}; A: You want new byte[]{(byte)i} How you print this array is another matter. Look up printf in the API reference. A: I would just like to note that 0 is NOT the same thing as 0x00. If i were to use: ColorChooserOutputText.append(Integer.toHexString(list[i].getRed())); ColorChooserOutputText.append(Integer.toHexString(list[i].getGreen())); ColorChooserOutputText.append(Integer.toHexString(list[i].getBlue())); and wanted to return the color, Purple it would return: ff0cc Which would be fine if I were just using Java. But if you are going between Java and something that had format specific needs ff0cc would not produce purple.. ff00cc is actually purple. //Declare some variables. Color HexColor = JButton1.getBackground(); String MyRValue = null; String MyGValue = null; String MyBValue = null; //Get Hex Value MyRValue = Integer.toHexString(HexColor.getRed()); MyGValue = Integer.toHexString(HexColor.getGreen()); MyBValue = Integer.toHexString(HexColor.getBlue()); //Make sure to keep both 0's MyRValue = ("00"+MyRValue).substring(MyRValue.length()); MyGValue = ("00"+MyGValue).substring(MyGValue.length()); MyBValue = ("00"+MyBValue).substring(MyBValue.length()); //Format your HexColor to #00ff00, #000000, #ff00ee JTextArea1.append("#"); JTextArea1.append(MyRValue+MyGValue+MyBValue); JTextArea1.append(", "); A: String.Format ("%02x") is your friend :) http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html http://www.xinotes.org/notes/note/1195/
{ "language": "en", "url": "https://stackoverflow.com/questions/7781461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Create IDs for each * (including nestings) in a jQuery sortable list I have a sortable list with nested LI items. I'm looking for create an ID for each LI in the group. Example. If I have this: <li class="main"> Cat 0 <ul class="subCat"> <li>Subcat 0 <ul class="subCat"> <li>Sub-Subcat 0 <ul class="subCat"></ul> </li> </ul> </li> <li>Subcat 1</li> </ul> </li> Ok, those ul.subCat are there to nest other li items. I want to make a function to add IDs to li elements and its li child elements. This function will be called by every order change. The result should be something like this: <li class="main" id="cat_0"> Cat 0 <ul class="subCat"> <li id="cat_0_0">Subcat 0 <ul class="subCat"> <li id="cat_0_0_0">Sub-Subcat 0 <ul class="subCat"></ul> </li> </ul> </li> <li id="cat_0_1">Subcat 1</li> </ul> </li> And, for each li.main element repeat the story to reach 4 levels (0 to 3). My actual code is this one: // level 0 target = $('#ulMenu >li'); for( i=0; i<=target.length-1; i++ ){ target.eq(i).attr('id', 'cat_' + i).addClass('main'); } // level 1 //------------------------------------------------------------------ $('#ulMenu >li.main').each(function(){ target = $(this).children('ul').children('li'); for( i=0; i<=target.length-1; i++ ){ father = target.eq(i).parent('ul').parent('li').attr('id').split('_')[1]; target.eq(i).attr('id', 'cat_' + padre + '_' + i); } I have to know how to add IDs to the rest of elements. I was trying but I can't found with the solution. A: Something like this should do it... $('#ulMenu').children('li').each(function(cat) { $(this).attr('id', 'cat_' + cat).children('ul').children('li').each(function(sCat) { $(this).attr('id', 'cat_' + cat + '_' + sCat).children('ul').children('li').each(function(ssCat) { $(this).attr('id', 'cat_' + cat + '_' + sCat + '_' + ssCat); }); }); });​ Example: http://jsfiddle.net/6YR5p/2/ A: Here's a recursive solution that'll work to any depth you want: function menuID(el, base) { base = base || 'cat'; $(el).filter('li').each(function(i) { this.id = base + '_' + i; menuID($(this).children('ul').children('li'), this.id); }); }; menuID('.main');​ See http://jsfiddle.net/alnitak/XhnYa/ Alternatively, here's a version as a jQuery plugin: (function($) { $.fn.menuID = function(base) { base = base || 'cat'; this.filter('li').each(function(i) { this.id = base + '_' + i; $(this).children('ul').children('li').menuID(this.id); }); }; })(jQuery); $('.main').menuID(); See http://jsfiddle.net/alnitak/5hkQU/
{ "language": "en", "url": "https://stackoverflow.com/questions/12727064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Printing MySQL table rows matching variable input The query in the following returns the data I want when I provide value I want to find a match for, however, I seem to be having difficulty when returning the data using the echo statements at the end: $conn = mysqli_connect($host,$username,$password, $database) or die (mysql_error ()); $searched=$_POST['searched']; $sound = soundex($searched); $sql = "SELECT * FROM word_list WHERE sound = '$sound';"; $result = mysql_query($conn,$sql); while($row = mysql_fetch_array($result)) { echo $row['word'] . ':' . $row['sound'] . '<br />'; } mysqli_close($conn); ?> The output in a browser is a blank page (no errors logged, etc.). When I var_dump the input, I get the correct soundex value; I am not sure where I've overlooked something, as seen above, tried a few things I saw in another thread. 'string(4) "A000"' is the result of the var_dump. As I explained, when I use 'A000' in place of my $sound variable, the query is successful in MySQL, and returns a list of words with matching soundex values (stored in a column called 'sound'), but I can't seem to get it to readout as such in the browser. A: Try using mysqli_query instead of mysql_query. I think mysqli_connect returns an object and mysql_query needs a string.
{ "language": "en", "url": "https://stackoverflow.com/questions/16877776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to specify multiple relationships between models in rails using ActiveRecord associations Say there're two models : User and Post, i want to keep track of who has read which post, and who writes which post, which user favorites which posts etc. Then i come up with the following solution: class User < ActiveRecord::Base has_many :writings has_many :posts, :through => :writings has_many :readings has_many :posts, :through => :readings #.. end class Post < ActiveRecord::Base has_many :writings has_many :posts, :through => :writings #... end and setting up the intermediate models - Writing, Reading. this works, but finally i find out that when i writing this @user.posts #... the returned array contains housekeeping information both for writings and readings. How can i solve this problem. A: You want something like this: class User < ActiveRecord::Base has_many :writings has_many :posts, :through => :writings has_many :readings has_many :read_posts, :through => :readings, :class_name => "Post" #.. end By giving the association name something other than just :posts you can refer to each one individually. Now... @user.posts # => posts that a user has written via writings @user.read_posts # => posts that a user has read via readings
{ "language": "en", "url": "https://stackoverflow.com/questions/1927986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: list single attribute of single post then I'll repeat in loop I am writing a very simple react app that will list the posts in my WordPress site. 1) Fetch the posts and set them to a state variable. 2) Successfully access the posts from render(). 3) Loop through the posts rendering the title and other information about each post. 1 and 2 are finished, so now I need to do 3. When I try to print the title of a post it tells me that it cannot access 'title' of undefined. . I know what you are thinking and I am able to print the post if I write a loop that prints out every key of the post (loop commented out), but if I try to print out the value of just one key I get an error saying the post is undefined. import React, { Component } from 'react'; import PropTypes from 'prop-types'; export default class Widget extends React.Component { constructor(props) { super(props); this.state = { posts: [] }; } componentWillMount() { const theUrl = "http://localhost:8888/test-site/wp-json/wp/v2/posts"; fetch(theUrl) .then(response => response.json()) .then(response => this.setState({ posts: response, }) ) } render() { let post = this.state.posts[0]; // for (var key in post) { // console.log(key + ': ' + post[key]); // } let title = post['title'].rendered; let stringbuilder = ''; try { stringbuilder += title + ', '; } catch {} return ( <div> <h1>React Widget</h1> {stringbuilder} </div> ); } } Widget.propTypes = { wpObject: PropTypes.object }; This question is probably easy for some of the more advanced react devs, but how can I print just the title attribute of post? A: The problem is that React is trying to render the posts before the asynchronous fetch returns a result and updates the state. In your render, just check if posts has more than 0 values: //... render() { const { posts } = this.state; if (posts && posts.length) { let post = posts[0]; // for (var key in post) { // console.log(key + ': ' + post[key]); // } let title = post['title'].rendered; let stringbuilder = ''; try { stringbuilder += title + ', '; } catch {} return ( <div> <h1>React Widget</h1> {stringbuilder} </div> ); } // Return null while loading // Or, return useful info like <p>Loading Posts...</p> return null; } //... Also, you should use componentDidMount as componentWillMount has been deprecated.
{ "language": "en", "url": "https://stackoverflow.com/questions/56944138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: After changing all font-family, font awesome icons show up as squares After applying the below codes, the font awesome icons show up as squares. If I apply it to body tag. It doens't overwrite all font-family, so I had to apply it to *. How can I fix this error? <style> * { font-family: "Open Sans", sans-serif !important; } </style> A: This is because font awesome requires the FontAwesome font-family to be applied to icon elements, in order to source and render the icons correctly. Your styles are likely overwriting this FontAwesome behaviour. One way to fix this would be to ensure font awesome's .fas class still correctly applies the required FontAwesome font to .fas elements. You could do this by updating your CSS: <style> * { font-family: "Open Sans", sans-serif; } .fas { font-family:FontAwesome; } </style> Or, if your browser supports the :not CSS3 selector: <style> *:not(.fas) { font-family: "Open Sans", sans-serif; } </style> A: If you are using Font Awesome 5 You can use this .fab { font-family: 'Font Awesome 5 Brands' !important; } .fas, .far, .fa { font-family: 'Font Awesome 5 Free' !important; }
{ "language": "en", "url": "https://stackoverflow.com/questions/53074655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Renaming files in folder c# I have over 1000 files in a folder with names like abc_1, abc_2 ... abc_n I want to delete this prefix 'abc_' from all the files. Any chance to not doing this manually because there are over 1000, and it will be a pain. How can do this with c# ? A: You can enumerate the file. using System.IO; string[] filePaths = Directory.GetFiles(@"c:\MyDir\"); Then, ForEach the string[] and create a new instance of the IO.File object. Once you get a handle on a File, just call the Move method and pass in String.Replace("abc_", String.Empty). I said Move because there is no direct Rename method in IO.File. File.Move(oldFileName, newFileName); Be mindful of the extension. A: You should have a look at the DirectoryInfo class and GetFiles() Method. And have a look at the File class which provides the Move() Method. File.Move(oldFileName, newFileName); A: Following code will work, not tested though, public class FileNameFixer { public FileNameFixer() { StringToRemove = "_"; StringReplacement = ""; } public void FixAll(string directory) { IEnumerable<string> files = Directory.EnumerateFiles(directory); foreach (string file in files) { try { FileInfo info = new FileInfo(file); if (!info.IsReadOnly && !info.Attributes.HasFlag(FileAttributes.System)) { string destFileName = GetNewFile(file); info.MoveTo(destFileName); } } catch (Exception ex) { Debug.Write(ex.Message); } } } private string GetNewFile(string file) { string nameWithoutExtension = Path.GetFileNameWithoutExtension(file); if (nameWithoutExtension != null && nameWithoutExtension.Length > 1) { return Path.Combine(Path.GetDirectoryName(file), file.Replace(StringToRemove, StringReplacement) + Path.GetExtension(file)); } return file; } public string StringToRemove { get; set; } public string StringReplacement { get; set; } } you can use this class as, FileNameFixer fixer=new FileNameFixer(); fixer.StringReplacement = String.Empty; fixer.StringToRemove = "@@"; fixer.FixAll("C:\\temp"); A: You can use File.Move and String.Substring(index): var prefix = "abc_"; var rootDir = @"C:\Temp"; var fileNames = Directory.EnumerateFiles(rootDir, prefix + "*", SearchOption.AllDirectories); foreach(String path in fileNames) { var dir = Path.GetDirectoryName(path); var fileName = Path.GetFileName(path); var newPath = Path.Combine(dir, fileName.Substring(prefix.Length)); File.Move(path, newPath); } Note: Directory.EnumerateFiles(rootDir, prefix + "*", SearchOption.AllDirectories); will search also subfolders from your root directory. If this is not intended use SearchOption.TopDirectoryOnly. A: You can try with this code DirectoryInfo d = new DirectoryInfo(@"C:\DirectoryToAccess"); FileInfo[] infos = d.GetFiles(); foreach(FileInfo f in infos) { File.Move(f.FullName, f.FullName.Replace("abc_","")); // Careful!! This will replaces the text "abc_" anywhere in the path, including directory names. } A: you can use a foreach iteration along with the File class from the System.IO namespace. All its methods are provided for you at no cost here: http://msdn.microsoft.com/en-us/library/system.io.file%28v=vs.100%29.aspx A: Total Commander has the possibility to rename multiple files (You don't need to program a tool on your own for each little task). A: string path = @"C:\NewFolder\"; string[] filesInDirectpry = Directory.GetFiles(path, "abc*"); forearch(string file in filesInDirectory) { FileInfo fileInfo = new FileInfo(file); fileInfo.MoveTo(path + "NewUniqueFileNamHere"); } A: I like the simplicity of the answer with the most up-votes, but I didn't want the file path to get modified so I changed the code slightly ... string searchString = "_abc_"; string replaceString = "_123_"; string searchDirectory = @"\\unc\path\with\slashes\"; int counter = 0; DirectoryInfo d = new DirectoryInfo(searchDirectory); FileInfo[] infos = d.GetFiles(); foreach(FileInfo f in infos) { if (f.Name.Contains(searchString)) { File.Move(searchDirectory+f.Name, searchDirectory+ f.Name.Replace(searchString, replaceString)); counter++; } } Debug.Print("Files renamed" + counter); A: This code enables user to replace a part of file name. Useful if there are many files in a directory that have same part. using System; using System.IO; // ... static void Main(string[] args) { FileRenamer(@"D:\C++ Beginner's Guide", "Module", "PDF"); Console.Write("Press any key to quit . . . "); Console.ReadKey(true); } static void FileRenamer(string source, string search, string replace) { string[] files = Directory.GetFiles(source); foreach (string filepath in files) { int fileindex = filepath.LastIndexOf('\\'); string filename = filepath.Substring(fileindex); int startIndex = filename.IndexOf(search); if (startIndex == -1) continue; int endIndex = startIndex + search.Length; string newName = filename.Substring(0, startIndex); newName += replace; newName += filename.Substring(endIndex); string fileAddress = filepath.Substring(0, fileindex); fileAddress += newName; File.Move(filepath, fileAddress); } string[] subdirectories = Directory.GetDirectories(source); foreach (string subdirectory in subdirectories) FileRenamer(subdirectory, search, replace); } A: Use this if you want all directories recursively: using System; using System.IO; namespace ConsoleApp1 { class Program { static void Main(string[] args) { foreach (String filePath in Directory.GetFiles(@"C:\folderName\", "*.*", SearchOption.AllDirectories)) { File.Move(filePath, filePath.Replace("abc_", "")); } } } } A: This command would do the trick, using renamer: $ renamer --find "abc_" *
{ "language": "en", "url": "https://stackoverflow.com/questions/12347881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: Why cronjob execute multiple time My cronjob execute multiple time. Is my setting wrong?? Please help me this is the script #!/bin/bash source /home/obe/env/bin/activate cd /home/obe/env/crawl/pjt/pjt scrapy crawl gets this is the crontab I set,I use centos7 * 23 * * * /home/obe/env/crawl/cron_set.sh And I use ps aux | grep cron I found my cronjob execute many time root 1202 0.0 0.0 126336 288 ? Ss 17:16 0:02 /usr/sbin/crond -n root 9870 0.0 0.0 113116 8 ? Ss 23:00 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 9908 0.0 0.0 113116 8 ? Ss 23:01 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 10203 0.0 0.0 113116 8 ? Ss 23:09 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 10238 0.0 0.0 113116 8 ? Ss 23:10 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 10269 0.0 0.0 113116 8 ? Ss 23:11 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 10328 0.0 0.0 113116 8 ? Ss 23:13 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 10370 0.0 0.0 113116 8 ? Ss 23:14 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 10412 0.0 0.0 113116 8 ? Ss 23:15 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 10455 0.0 0.0 113116 8 ? Ss 23:16 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 10594 0.0 0.0 113116 8 ? Ss 23:17 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 10631 0.0 0.0 113116 8 ? Ss 23:18 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 10660 0.0 0.0 113116 8 ? Ss 23:19 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 10699 0.0 0.0 113116 8 ? Ss 23:20 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 10731 0.0 0.0 113116 8 ? Ss 23:21 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 10753 0.0 0.0 113116 4 ? Ss 23:22 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 10779 0.0 0.0 113116 36 ? Ss 23:23 0:00 /bin/bash /home/obe/env/clawer/cron_set.sh root 10802 0.5 0.0 112644 216 pts/2 S+ 23:23 0:00 grep --color=auto cron Why would this happen??? A: Your crontab * 23 * * * /home/obe/env/crawl/cron_set.sh means : The command /home/obe/env/crawl/cron_set.sh will execute every minute of 11pm every day. If you want it to run once in a day , it should be : 0 23 * * * /home/obe/env/crawl/cron_set.sh which means The command /home/obe/env/crawl/cron_set.sh will execute at 11:00pm every day. Next time refer to : http://www.cronchecker.net/ Happy crons
{ "language": "en", "url": "https://stackoverflow.com/questions/33084996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I launch a new form and return to it after the new form is closed? If my user clicks a button, I would like to launch a new Form. Then when the user closes the second form, I would like to return back to the initial form. var appLaunch = new App(); appLaunch.Show(); this.Hide(); Could anyone please help me? My code doesn't allow me to return back to where I left off when I close the second form A: To create a new form appLaunch you can use: var appLaunch = new App(); appLaunch.Show(this); this.Hide(); Then add this code on FormClosed event of appLaunch private void appLaunch_FormClosed(Object sender, FormClosedEventArgs e) { this.Owner.Show(); } A: The hide() function just temporarily removes the form from the display. The close() function removed the form from memory. So if you want to go back to form1 after showing form2, just don't close form1. You could hide it, but you wouldn't have to. Just hide form2 when you're wanting to return to form1.
{ "language": "en", "url": "https://stackoverflow.com/questions/41108467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a replacement for Attribute.IsDefined in UWP apps? It seems that the static method Attribute.IsDefined is missing for UWP apps, I can navigate to the metadata for the Attribute class alright and the method is there, but the project won't compile stating that 'Attribute' does not contain a definition for 'IsDefined' - weird (matter of fact, there are no static methods on that type at all according to IntelliSense). I was going to query for types with a certain attribute like var types = this.GetType().GetTypeInfo().Assembly.GetTypes() .Where(t => Attribute.IsDefined(t, typeof (MyAttribute))); and am wondering if there is a workaround. A: This should work: var types = this.GetType().GetTypeInfo().Assembly.GetTypes() .Where(t => t.GetTypeInfo().GetCustomAttribute<MyAttribute>() != null);
{ "language": "en", "url": "https://stackoverflow.com/questions/32414954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: React HOC that takes argument instead of component and returns component How do I create a React HOC that takes argument instead of component (let's say the argument is from useParams() of react router dom) and returns a component with the given argument (with hooks) I tried import React from 'react' const ResultsContent = searchValue => { const Content = props => { return ( <h1>{searchValue}</h1> ) } return Content } export default ResultsContent then let { value } = useParams() const Content = ResultsContent(value) return ( <div> <Content></Content> </div> ) and I got _results__WEBPACK_IMPORTED_MODULE_5___default(...) is not a function A: You could do something like this: import React from "react"; import ReactDOM from "react-dom"; const resultsContent = (searchValue) => { const Content = (props) => <h1>{searchValue}</h1>; return Content; }; const Content = resultsContent("a"); const rootElement = document.getElementById("root"); ReactDOM.render(<Content />, rootElement); **Also check if you import your ResultsContent with a default import not named import: import ResultsContent from './your-path-to-the-file';**
{ "language": "en", "url": "https://stackoverflow.com/questions/68771102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting header values, Status code etc from Jax-Rs Response class in Junit I am using Restful web Service using Dropwizard. And generating response as: Response response = resources.client().resource("/url") .header("CONTENT-TYPE","value") .post(Response.class, jsonRequestString); Now I want to write unit test to ensure the returned content type is corrected in Response Object. how to do that? A: You can use the ClientResponse type in Jackson. For example, using a GET operation: ClientResponse response = Client.create() .resource(url) .get(ClientResponse.class); String contentType = response.getHeaders() .getFirst("Content-Type"); System.out.println(contentType);
{ "language": "en", "url": "https://stackoverflow.com/questions/27395114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Finding all object indices satisfying testing function, like array.findIndex() but more than first index I have an array of objects: var data = [{"district":"201","date":"Wed Apr 01 2020","paper":671.24,"mgp":36.5}, {"district":"202","date":"Wed Apr 01 2020","paper":421.89,"mgp":44.2}, {"district":"203","date":"Wed Apr 01 2020","paper":607.85,"mgp":67.36}, {"district":"201","date":"Sun Mar 01 2020","paper":571.24,"mgp":38.8}, {"district":"202","date":"Sun Mar 01 2020","paper":421.89,"mgp":36.6}, {"district":"203","date":"Sun Mar 01 2020","paper":607.85,"mgp":69.36}, {"district":"201","date":"Sat Feb 01 2020","paper":571.24,"mgp":38.8}, {"district":"202","date":"Sat Feb 01 2020","paper":421.89,"mgp":22.2}, {"district":"203","date":"Sat Feb 01 2020","paper":607.85,"mgp":59.66}, {"district":"201","date":"Wed Jan 01 2020","paper":571.24,"mgp":38.8}, {"district":"202","date":"Wed Jan 01 2020","paper":421.89,"mgp":22.2}, {"district":"203","date":"Wed Jan 01 2020","paper":607.85,"mgp":89.26}] For each district I would like to take the values of paper and mgp for February, March, and April and divide each month's values by their January values to measure % change. Using Array.findIndex() and reduce() (like here) I can match the districts and return the correct value, but that only returns the first index of the match, and there are repeat indices because there are subsequent months. I've tried wrapping a loop of months around the findIndex() to no avail: console.log(result) returns nothing var result = data.reduce((a, b) => { var months = [...new Set(a.map(m => a.date))]; for (var month of months){ var idx = a.findIndex(e => e.district == b.district && e.date == month) if (~idx && b.date === "Wed Jan 01 2020") { a[idx].paper = a[idx].paper/b.paper; a[idx].mgp = a[idx].mgp/b.mgp} else { a.push(JSON.parse(JSON.stringify(b))); } return a }, []); Result should look like this: [{"district":"201","date":"Wed Apr 01 2020","paper":1.17,"mgp":0.94}, {"district":"202","date":"Wed Apr 01 2020","paper":1,"mgp":1.99}, {"district":"203","date":"Wed Apr 01 2020","paper":1,"mgp":0.75}, {"district":"201","date":"Sun Mar 01 2020","paper":1,"mgp":1}, {"district":"202","date":"Sun Mar 01 2020","paper":1,"mgp":1.64}, {"district":"203","date":"Sun Mar 01 2020","paper":1,"mgp":0.77}, {"district":"201","date":"Sat Feb 01 2020","paper":1.17,"mgp":1}, {"district":"202","date":"Sat Feb 01 2020","paper":1,"mgp":1}, {"district":"203","date":"Sat Feb 01 2020","paper":1,"mgp":0.67] A: var data = [{"district":"201","date":"Wed Apr 01 2020","paper":671.24,"mgp":36.5}, {"district":"202","date":"Wed Apr 01 2020","paper":421.89,"mgp":44.2}, {"district":"203","date":"Wed Apr 01 2020","paper":607.85,"mgp":67.36}, {"district":"201","date":"Sun Mar 01 2020","paper":571.24,"mgp":38.8}, {"district":"202","date":"Sun Mar 01 2020","paper":421.89,"mgp":36.6}, {"district":"203","date":"Sun Mar 01 2020","paper":607.85,"mgp":69.36}, {"district":"201","date":"Sat Feb 01 2020","paper":571.24,"mgp":38.8}, {"district":"202","date":"Sat Feb 01 2020","paper":421.89,"mgp":22.2}, {"district":"203","date":"Sat Feb 01 2020","paper":607.85,"mgp":59.66}, {"district":"201","date":"Wed Jan 01 2020","paper":571.24,"mgp":38.8}, {"district":"202","date":"Wed Jan 01 2020","paper":421.89,"mgp":22.2}, {"district":"203","date":"Wed Jan 01 2020","paper":607.85,"mgp":89.26}]; const byDistrict = {}; for (const item of data) { const month = item.date.split(' ')[1]; // eg Apr if (!byDistrict[item.district]) byDistrict[item.district] = { }; byDistrict[item.district][month] = { paper: item.paper, mgp: item.mgp, date: item.date }; } for (const district of Object.keys(byDistrict)) { const District = byDistrict[district]; District.all = { district, paper: (District.Feb.paper + District.Mar.paper + District.Apr.paper) / District.Jan.paper, mgp: (District.Feb.mgp + District.Mar.mgp + District.Apr.mgp) / District.Jan.mgp } } const result = Object.keys(byDistrict).map(it => byDistrict[it].all); console.log(result); A: You could collect the january values first and then omit january in the result set. var data = [{ district: "201", date: "Wed Apr 01 2020", paper: 671.24, mgp: 36.5 }, { district: "202", date: "Wed Apr 01 2020", paper: 421.89, mgp: 44.2 }, { district: "203", date: "Wed Apr 01 2020", paper: 607.85, mgp: 67.36 }, { district: "201", date: "Sun Mar 01 2020", paper: 571.24, mgp: 38.8 }, { district: "202", date: "Sun Mar 01 2020", paper: 421.89, mgp: 36.6 }, { district: "203", date: "Sun Mar 01 2020", paper: 607.85, mgp: 69.36 }, { district: "201", date: "Sat Feb 01 2020", paper: 571.24, mgp: 38.8 }, { district: "202", date: "Sat Feb 01 2020", paper: 421.89, mgp: 22.2 }, { district: "203", date: "Sat Feb 01 2020", paper: 607.85, mgp: 59.66 }, { district: "201", date: "Wed Jan 01 2020", paper: 571.24, mgp: 38.8 }, { district: "202", date: "Wed Jan 01 2020", paper: 421.89, mgp: 22.2 }, { district: "203", date: "Wed Jan 01 2020", paper: 607.85, mgp: 89.26 }], january = data.reduce((r, o) => { if (o.date.includes('Jan')) r[o.district] = o; return r; }, {}), result = data.reduce((r, o) => { if (o.date.includes('Jan')) return r; r.push({ ...o, paper: +(o.paper / january[o.district].paper).toFixed(2), mgp: +(o.mgp / january[o.district].mgp).toFixed(2) }) return r; }, []); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; } A: var data = [{"district":"201","date":"Wed Apr 01 2020","paper":671.24,"mgp":36.5}, {"district":"202","date":"Wed Apr 01 2020","paper":421.89,"mgp":44.2}, {"district":"203","date":"Wed Apr 01 2020","paper":607.85,"mgp":67.36}, {"district":"201","date":"Sun Mar 01 2020","paper":571.24,"mgp":38.8}, {"district":"202","date":"Sun Mar 01 2020","paper":421.89,"mgp":36.6}, {"district":"203","date":"Sun Mar 01 2020","paper":607.85,"mgp":69.36}, {"district":"201","date":"Sat Feb 01 2020","paper":571.24,"mgp":38.8}, {"district":"202","date":"Sat Feb 01 2020","paper":421.89,"mgp":22.2}, {"district":"203","date":"Sat Feb 01 2020","paper":607.85,"mgp":59.66}, {"district":"201","date":"Wed Jan 01 2020","paper":571.24,"mgp":38.8}, {"district":"202","date":"Wed Jan 01 2020","paper":421.89,"mgp":22.2}, {"district":"203","date":"Wed Jan 01 2020","paper":607.85,"mgp":89.26}] let res = data.filter(it => !it.date.includes('Jan')) .reduce ((acc, rec) => [...acc, {district: rec.district, date: rec.date, paper: +(rec.paper/data.filter(it => (it.district === rec.district && it.date.includes('Jan')))[0].paper).toFixed(2), mgp: +(rec.mgp/data.filter(it => (it.district === rec.district && it.date.includes('Jan')))[0].mgp).toFixed(2)}] ,[]) console.log(JSON.stringify(res))
{ "language": "en", "url": "https://stackoverflow.com/questions/61510275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to view project logs after merging a repository into a monorepo? Suppose I have a monorepo whose directory is named monorepo. In the multirepo, each project has its own directory. Also suppose I have another existing repository named project-a that I wish to place into the monorepo. To place project-a into the existing multirepo, I did this (taken from this question): # Prepare project-a. cd ~/project-a/ mkdir project-a/ mv * project-a/ git add --all git commit -am 'Move all files into a directory in preparation for conversion to monorepo' # Place project-a into the monorepo. cd ~/monorepo/ git remote add origin ~/project-a/ git fetch origin git merge origin/master --allow-unrelated-histories git remote rm origin At this point, the history (i.e. the output of git log) of project-a has been merged seamlessly with the existing history in the monorepo. But how do I view the history of project-a only? i.e. How can I view the history of project-a as if it had not been merged into the monorepo? I tried git log -- project-a/, but that only shows one commit (i.e. 'Move all files into a directory in preparation for conversion to monorepo'), whereas I had intended to see all the commits I made for the files in project-a.
{ "language": "en", "url": "https://stackoverflow.com/questions/53393014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to read more than 20 byte using pygatt I'm using python's pygatt in order to subscribe to a device's charasteristic. The problem I have is that in the callback, I'm only receiving 20 bytes each time and I need the full 70-100byte answer. Is there a workaround to be able to read more than 20 bytes using python and pygatt? Changing the default mtu size for example. (I don't know if this can be done) A: It would appear that this is a known issue. Here is a link to the comment thread on github.
{ "language": "en", "url": "https://stackoverflow.com/questions/53378884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Excel VBA Error "user-defined type not defined" with Outlook I am using Office 2016 in my computer and I have a VBA code that sends Email to so mail lists in the file. Every time I want to send the Emails automatically with my CommandButton, I get the error massage: "user-defined type not defined". I made some research in the web and I found out that there is a solution: VB Editor ----> Tools ----> Referenced ----> Microsoft Outlook 16.0 Object Library But the next time I open the file the same error runs again and again and again. Can someone find me solution that will be permanent? I Don't know what to do more then I already did. Public Sub sendMail() Call ini_set If mail_msg.Cells(200, 200) = 1 Then lr = main_dist.Cells(main_dist.Rows.Count, "A").End(xlUp).row On Error Resume Next For i = 2 To lr Application.DisplayAlerts = False Dim applOL As Outlook.Application Dim miOL As Outlook.MailItem Dim recptOL As Outlook.Recipient mail_msg.Visible = True mailSub = mail_msg.Range("B1") mailBody = mail_msg.Range("B2") mail_msg.Visible = False Set applOL = New Outlook.Application Set miOL = applOL.CreateItem(olMailItem) Set recptOL = miOL.Recipients.Add(main_dist.Cells(i, 5)) recptOL.Type = olTo tempPath = ActiveWorkbook.Path & "\" & main_dist.Cells(i, 4) & ".xlsm" With miOL .Subject = mailSub .Body = mailBody .Attachments.Add tempPath .send End With Set applOL = Nothing Set miOL = Nothing Set recptOL = Nothing Application.DisplayAlerts = True Next i End Sub Here is the problem based on the VB Editor: Dim applOL As Outlook.Application A: As I suggested in the comment, you can edit your code like below (see three commented lines) and should be able to run without references. I am assuming that the code is correct otherwise and it is providing intended results Public Sub sendMail() Call ini_set If mail_msg.Cells(200, 200) = 1 Then lr = main_dist.Cells(main_dist.Rows.Count, "A").End(xlUp).Row On Error Resume Next For i = 2 To lr Application.DisplayAlerts = False Dim applOL As Object '\\Outlook.Application Dim miOL As Object '\\Outlook.MailItem Dim recptOL As Object '\\Outlook.Recipient mail_msg.Visible = True mailSub = mail_msg.Range("B1") mailBody = mail_msg.Range("B2") mail_msg.Visible = False Set applOL = New Outlook.Application Set miOL = applOL.CreateItem(olMailItem) Set recptOL = miOL.Recipients.Add(main_dist.Cells(i, 5)) recptOL.Type = olTo tempPath = ActiveWorkbook.Path & "\" & main_dist.Cells(i, 4) & ".xlsm" With miOL .Subject = mailSub .Body = mailBody .Attachments.Add tempPath .send End With Set applOL = Nothing Set miOL = Nothing Set recptOL = Nothing Application.DisplayAlerts = True Next i End Sub Late binding can help in some other cases as well especially if there are several users and they are having different setups with respect to software versions!
{ "language": "en", "url": "https://stackoverflow.com/questions/47376978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: StructureMap Constructor Injection without Interface? I'm setting up a MVC project. It looks like this EfDbContext : IDbContext { ... } MyStuff : IMyStuff { ... } MyService : IMyService { List<things> GetSomething(IDbContext context, IMyStuff stuff) { ... } } MyController : Controller { ActionResult MyAction(IMyService service) { ... } } I use StructureMap.MVC to resolve all the constructor dependencies, plus setter injection for auditing and logging in custom ActionFilters. The only thing I have to manually specify in the IoC is the connection string for IDbContext, everything else just automagically worked! Until I read some articles that says, it smells to have 1:1 ratio between class and interface. My application is quite simple, there will never be different implementation of IMyStuff or IMyService. The only reason I have them is so that they can be injected and unit tested (I used Rhino but start to like NSubstitue). Is there way I can get rid of the interface and inject the concrete class directly? So it looks like GetSomething(IDbContext context, MyStuff stuff) {} MyAction(MyService service) {} Of course, I still want all the convention based auto wiring with StructureMap, so I don't have to specify them one by one. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/15314968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Profile model is deleted when I fail to validate on Devise Edit form So, I'm a beginner in RoR4 and I thought I'd go on a practice project. I am using Devise for a User model and I went on to add a Profile model to it like so: class User < ActiveRecord::Base has_one :profile, dependent: :destroy before_create :build_profile # Creates profile at user creation accepts_nested_attributes_for :profile ... end and class Profile < ActiveRecord::Base belongs_to :user validates :user_id, presence: true end config/routes.rb: devise_for :users, controllers: { sessions: 'users/sessions', registrations: 'users/registrations' } resources :users, only: [:index, :show, :destroy] resources :profiles, only: [:update] namespace :admin do root "base#index" resources :users end authenticated do root to: 'pages#menu', as: :authenticated end I basically want to allow editing the profile in the same Edit form that Devise generated. So I added this to application_controller: def configure_permitted_parameters ... devise_parameter_sanitizer.for(:account_update) do |u| u.permit( :email, :password, :password_confirmation, :current_password, :name, profile_attributes: [:birthday, :phone, :address, :about, :restrictions, :avatar] ) end end and I followed the instructions on this page on Devise's wiki to restrict requiring the password only on email and password change, as follows: def update @user = User.find(current_user.id) successfully_updated = if needs_password?(@user, params) @user.update_with_password(devise_parameter_sanitizer.sanitize(:account_update)) else # remove the virtual current_password attribute # update_without_password doesn't know how to ignore it params[:user].delete(:current_password) @user.update_without_password(devise_parameter_sanitizer.sanitize(:account_update)) end if successfully_updated set_flash_message :notice, :updated # Sign in the user bypassing validation in case his password changed sign_in @user, :bypass => true redirect_to after_update_path_for(@user) else render "edit" end end private # check if we need password to update user data # ie if password or email was changed # extend this as needed def needs_password?(user, params) user.email != params[:user][:email] || params[:user][:password].present? end I then updated the nested form and everything went as expected with until I tried NOT to provide my old password when changing the email or password. I got the notice message but then the Profile associated with the User just turned to nil, and poof, it's gone. Here is the server log message: Processing by Users::RegistrationsController#update as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"L1i+uV0LFvyVs3xLOMYUJyqeZLnFSWV6R0igyG4+W7E=", "user"=>{"name"=>"Foo Bar1", "profile_attributes"=>{"birthday"=>"", "phone"=>"", "address"=>"", "about"=>"Lorem ipsum dolor", "restrictions"=>"", "avatar"=>"", "id"=>"13"}, "email"=>"[email protected]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "current_password"=>"[FILTERED]"}, "commit"=>"Update"} User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY "users"."id" ASC LIMIT 1 User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 2]] Unpermitted parameters: id Profile Load (0.2ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."user_id" = ? ORDER BY "profiles"."id" ASC LIMIT 1 [["user_id", 2]] (0.1ms) begin transaction SQL (0.4ms) DELETE FROM "profiles" WHERE "profiles"."id" = ? [["id", 13]] (13.4ms) commit transaction User Exists (0.5ms) SELECT 1 AS one FROM "users" WHERE ("users"."email" = '[email protected]' AND "users"."id" != 2) LIMIT 1 User Exists (0.6ms) SELECT 1 AS one FROM "users" WHERE (LOWER("users"."username") = LOWER('user1') AND "users"."id" != 2) LIMIT 1 Any suggestion on what could have gone wrong? how to fix it? UPDATE Rereading the whole discussion with @RichPeck and @KirtiThorat here, and specifically the server log, I managed to solve the issue of recreating the profile object and deleting the old one by adding the profile ID as one of the permitted parameters in Devise's :account_update sanitizer, like so: devise_parameter_sanitizer.for(:account_update) do |u| u.permit( :email, :password, :password_confirmation, :current_password, :name, profile_attributes: [:id, :birthday, :phone, :address, :about, :restrictions, :avatar] ) end I don't know what's the impact of that on security, so I would still appreciate a feedback. A: First of all, if you have setup Devise to allow users to edit their account without providing a password then you need to remove current_password field from the view as well as configure_permitted_parameters method. def configure_permitted_parameters ... devise_parameter_sanitizer.for(:account_update) do |u| u.permit( :email, :password, :password_confirmation, ## :current_password, ## REMOVE THIS LINE :name, profile_attributes: [:birthday, :phone, :address, :about, :restrictions, :avatar] ) end end By specifying current_password you are permitting it for mass-assignment on account_update. UPDATE class User < ActiveRecord::Base has_one :profile, dependent: :destroy, inverse_of :user before_create :build_profile # Creates profile at user creation accepts_nested_attributes_for :profile ... end class Profile < ActiveRecord::Base belongs_to :user, inverse_of :profile validates :user_id, presence: true end
{ "language": "en", "url": "https://stackoverflow.com/questions/22435124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using node as api and static I'm extremely new to web development. I've bought a domain name (let say 'domain.com' and what I want is to have two links: one 'api.domain.com' with MySql database and Node server for API; and second is: 'domain.com' with some client-side app which will call to 'api.domain.com' for data. Same for native mobile apps which will call 'api.domain.com'. What NodeJS frameworks will you suggest to best serve this needs. And how are those "domain tricks" called, so I can read about how to organise it. A: * *For bare web framework and middleware abstraction, please see express *For Extensive API development and integration, please see loopback *For enterprise features to manage your deployments, please see strongloop
{ "language": "en", "url": "https://stackoverflow.com/questions/41174784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reusing parent context with context.WithTimeout in go? Reusing parent context with context.WithTimeout with a new timeout Hi there, I'm new to go. I was wondering if it's possible to reuse a parent context to create multiple context.withTimeout(). The rationale would be where I have to call multiple network requests in sequence and would like to set a timeout for each request at the same time using the parent's context. Rationale When the parent's context is cancelled, all the requests made would be cancelled too. Problem In the code below, it shows an example whereby LongProcess is the network request. However, the context is closed before the second LongProcess call can be made with a context deadline exceeded. The documentation withDeadline states The returned context's Done channel is closed when the deadline expires, when the returned cancel function is called, or when the parent context's Done channel isclosed, whichever happens first. So if that's the case, is there a way where I can reset the timer for withTimeout? Or do I have to create a new context context.Background() for every request? That would mean the parent context will not be passed. :( // LongProcess refers to a long network request func LongProcess(ctx context.Context, duration time.Duration, msg string) error { c1 := make(chan string, 1) go func() { // Simulate processing time.Sleep(duration) c1 <- msg }() select { case m := <-c1: fmt.Println(m) return nil case <-ctx.Done(): return ctx.Err() } } func main() { ctx := context.Background() t := 2 * time.Second ctx, cancel := context.WithTimeout(ctx, t) defer cancel() // Simulate a 2 second process time err := LongProcess(ctx, 2*time.Second, "first process") fmt.Println(err) // Reusing the context. s, cancel := context.WithTimeout(ctx, t) defer cancel() // Simulate a 1 second process time err = LongProcess(s, 1*time.Second, "second process") fmt.Println(err) // context deadline exceeded } A: It looks like the first call to context.WithTimeout shadow the parent context ctx. The later process re-use this already canceled context hence the error. You have to re-use the parent one. Here is the example updated: func main() { // Avoid to shadow child contexts parent := context.Background() t := 2 * time.Second // Use the parent context. ctx1, cancel := context.WithTimeout(parent, t) defer cancel() err := LongProcess(ctx1, 2*time.Second, "first process") fmt.Println(err) // Use the parent context not the canceled one. ctx2, cancel := context.WithTimeout(parent, t) defer cancel() err = LongProcess(ctx2, 1*time.Second, "second process") fmt.Println(err) }
{ "language": "en", "url": "https://stackoverflow.com/questions/61269264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Are there any performance drawbacks to using 'do nothing' default event handlers? Let's say I have a collection of thousands of objects, all of which implement the following: public event EventHandler StatusChanged = (s,e) => {}; private void ChangeStatus() { StatusChanged(this, new EventArgs()); } If no handlers are subscribed to that event for each object, does using the no-op event handler provide any performance drawbacks? Or is the CLR smart enough to ignore it? Or am I better off checking for a StatusChanged handler before firing the event? A: Yes, the CLR is not really smart enough to ignore it but the difference should be negligible in most cases. A method call is not a big deal and is unlikely to have a meaningful impact on the performance of your application. A: If your application calls ChangeStatus thousand times per second, maybe it would be a problem. But only profiler can prove this.
{ "language": "en", "url": "https://stackoverflow.com/questions/2183871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google Genomics API - Internal Server Error + ReferenceIDs I'm pretty new to Google genomics APIs. I'm trying to create an annotation. I used both web version and Python API call: service.annotations().create(body={ 'annotationSetId': '101', 'name': 'TestAnnotation', 'referenceName': 'chrM', 'start': '1', 'end': '1'}, fields='id') Here is a sample annotation: { "annotationSetId": "101", "name": "TestAnnotation", "referenceName": "chrM", "start": "1", "end": "1", } I get the following error for both cases: 500 Internal Server Error { "error": { "code": 500, "message": "Unknown Error.", "status": "UNKNOWN" } } Any Suggestion? One more observation. We can add a variant set by only submitting datasetId and name; no need to specify referenceId, but we cannot create an annotation set w/o referenceId. Why? 400 HTTP/2.0 400 - SHOW HEADERS - { "error": { "code": 400, "message": "Invalid value for field \"annotationSet.referenceSetId\": empty or not specified", "status": "INVALID_ARGUMENT" } } BTW, how can I set the WRITE permission for the caller? Caller must have WRITE permission for the associated annotation set. Thank you in advance! A: So to have an annotationset associated to a dataset, you would need write permission to that dataset. If you created the dataset then you would have write permission, which would be associated with your account. If it is a public dataset, then you might need to ask for permission from the person who loaded that dataset to add you with write permissions to it, or you could reload it under you account. Now assuming you created a dataset, then you can create an AnnotationSet via curl directly - you will need to use your API key from the console (please don't post your API key publicly here). Below is the command and what you would fill in: curl -v -X POST -H "Content-Type: application/json" -d '{"datasetId":"YourActualDatasetID", "referenceSetId":"YourActualReferencesetID"}' https://genomics.googleapis.com/v1/annotationsets?fields=asdf&key=YOUR_API_KEY Let me know if this worked for you, and if there is anything else that I can help you with. Thanks, Paul A: to add to Paul's answer: annotationSetId must be the id to a real annotation set. We will work on improving the error message. We would like to require referenceId for all our APIs. We don't for our Variant API because the Reference API didn't exist when we created the Variant API. To give a user WRITE permission, add the user as a Project Editor. See https://cloud.google.com/iam/docs/quickstart-roles-members#add_a_project_member_and_grant_them_an_iam_role A: My previous comment didn't get formatted properly, so I'm writing it as an answer instead. For this specific test I would need to enable billing for my account, so my guide is the raw information in the Genomics REST API via the Discovery service: https://www.googleapis.com/discovery/v1/apis/genomics/v1/rest Based on the REST API, the scopes for creating a AnnotationSet are the following: "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/genomics" Since you are getting an authentication error, it would be good to first check on the console (https://console.cloud.google.com) for your project that is tied to your API (server) key that you used, if it is enabled for the Genomics and Cloud APIs? ~p A: Here is the public references: https://console.cloud.google.com/storage/browser/genomics-public-data/references/ And here we can get ReferenceIDs: https://developers.google.com/apis-explorer/#p/genomics/v1/genomics.referencesets.search A: Glad to hear you got everything to work Amir! It was a fun team effort by the three of us, and I'm always happy to help out as I've used and seen the evolution of the API over the past two years :) Regarding ReferenceIds I see you already found some of the same links I am posting here. These are basically the id that point to a reference which is a sequence such as a chromosome. A collection of reference IDs belong to a ReferenceSet which represents a reference assembly, and references.bases belong to a ReferenceID. I have not seen in the REST API a way to create load a new reference genome - those are probably populated and made available by Google manually via the backend. Maybe Melissa might have more information regarding that. Below are a collection of links that may be helpful regarding References - some of which you also discovered - and am listing them as a collection in case others might find them useful in the future: http://googlegenomics.readthedocs.io/en/latest/use_cases/discover_public_data/reference_genomes.html https://cloud.google.com/genomics/v1/users-guide#references https://cloud.google.com/genomics/v1/reference-sets#finding-references https://cloud.google.com/genomics/reference/rest/v1/referencesets https://cloud.google.com/genomics/reference/rest/v1/references https://cloud.google.com/genomics/reference/rest/v1/references.bases Each of the above of the REST APIs will have their own specific methods for searching and associating to data. Hope it helps, ~p A: To use the REST API for annotation: gcloud auth login TOKEN=$(gcloud auth print-access-token) curl -v -X POST -H "Authorization: Bearer $TOKEN" -d '{"datasetId": "YOUR_DATA_SET" , "referenceSetId": "EMWV_ZfLxrDY-wE" }' --header "Content-Type: application/json" https://genomics.googleapis.com/v1/annotationsets
{ "language": "en", "url": "https://stackoverflow.com/questions/37712872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the use of "psycopg2" in Django while connecting to PostgreSQL What is the use of the psycopg2 PostgreSQL database adapter; or what is the difference between using postgresql vs postgresql_psycopg2 while establishing connection in the settings.py file in a Django project? Because either one works fine for me. 'ENGINE': 'django.db.backends.postgresql' 'ENGINE': 'django.db.backends.postgresql_psycopg2' A: According to the documentation: The PostgreSQL backend (django.db.backends.postgresql_psycopg2) is also available as django.db.backends.postgresql. The old name will continue to be available for backwards compatibility. Actually, this question is already solved here.
{ "language": "en", "url": "https://stackoverflow.com/questions/54164283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Snowflake COPY INTO Export Producing Unreadable File Testing export functionality in Snowflake and having a hard time getting a readable file back. Using the below command on: COPY INTO 'azure://my_account.blob.core.windows.net/test-folder/test_file_8.csv' FROM (SELECT * FROM DEMO_DB.INFORMATION_SCHEMA.DATABASES) credentials = (azure_sas_token='my_sas_token') FILE_FORMAT = (TYPE = CSV RECORD_DELIMITER = ',') HEADER = TRUE SINGLE = TRUE I'm getting the following back: See Exported Data What am I doing wrong? A: From COPY INTO docs: If SINGLE = TRUE, then COPY ignores the FILE_EXTENSION file format option and outputs a file simply named data. To specify a file extension, provide a filename and extension in the internal or external location path COPY INTO @mystage/data.csv ... and: COMPRESSION = AUTO | GZIP | BZ2 | BROTLI | ZSTD | DEFLATE | RAW_DEFLATE | NONE String (constant) that specifies to compresses the unloaded data files using the specified compression algorithm. Supported Values AUTO Unloaded files are automatically compressed using the default, which is gzip. **Default: AUTO** Either do not compress file(compression method NONE) or provide a proper file name with gz extension: COPY INTO 'azure://my_account.blob.core.windows.net/test-folder/test_file_8.csv.gz'
{ "language": "en", "url": "https://stackoverflow.com/questions/65939852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Codeigniter Sessions Third Variable Gets Lost I'm trying to save checkbox data using PHP sessions in CodeIgniter. After submitting the form the data is saved in the session variables and can be called upon on the next page. The problem is however that when I then continue to another page the last session variable is empty when called upon, while the first two are still available. I also tried using the standard PHP $_SESSION which gives me the exact same result. The processing file contains: $price_low = $this->input->post('price_low'); $price_high = $this->input->post('price_high'); $stock_only = $this->input->post('stock_only'); $session = array('price_low' => $price_low, 'price_high' => $price_high, 'stock_only' => $stock_only); $this->session->set_userdata($session);` Retrieving the data: $this->session->userdata('price_low'); $this->session->userdata('price_high'); $this->session->userdata('stock_only');
{ "language": "en", "url": "https://stackoverflow.com/questions/44785558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSON creation in android I want to create a json like this in java. { "contacts": [ { "id": "c200", "name": "Ravi Tamada", "email": "[email protected]", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c201", "name": "Johnny Depp", "email": "[email protected]", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c202", "name": "Leonardo Dicaprio", "email": "[email protected]", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c203", "name": "John Wayne", "email": "[email protected]", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c204", "name": "Angelina Jolie", "email": "[email protected]", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "female", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c205", "name": "Dido", "email": "[email protected]", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "female", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c206", "name": "Adele", "email": "[email protected]", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "female", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c207", "name": "Hugh Jackman", "email": "[email protected]", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c208", "name": "Will Smith", "email": "[email protected]", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c209", "name": "Clint Eastwood", "email": "[email protected]", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c2010", "name": "Barack Obama", "email": "[email protected]", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c2011", "name": "Kate Winslet", "email": "[email protected]", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "female", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c2012", "name": "Eminem", "email": "[email protected]", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } } ] } I am using the library org.json. But when i convert the json into string there comes a lot of slashes. Like this: { \"id\": \"c200\", \"name\": \"Ravi Tamada\", \"email\": \"[email protected]\", \"address\": \"xx-xx-xxxx,x - street, x - country\", \"gender\" : \"male\", \"phone\": { \"mobile\": \"+91 0000000000\", \"home\": \"00 000000\", \"office\": \"00 000000\" } } How to get rid of the slashes. thanks in advance A: As I recall, the \ character is escaping the ". It's supposed to be there. How do you want to use the JSON data? It would be nice if you could provide sample code for what you are doing with it. In my application I do the following, BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); JSONTokener tokener = new JSONTokener(json); JSONObject JSONParams = new JSONObject(tokener); String param1 = eventParams.getString("param1"); ... If you use these objects they should take care of removing the escape characters for you. A: Flexjson is also a very convenient way if you are have POJOs to be converted to JSON representations. JSONSerializer will serialize and JSONDeserializer will do the reverse. I have used it by myself. Link to Flexjson Website - http://flexjson.sourceforge.net/ public String doSomething( Object arg1, ... ) { Person p = ...load a person...; JSONSerializer serializer = new JSONSerializer(); return serializer.serialize( p ); } { "class": "Person", "name": "William Shakespeare", "birthday": -12802392000000, "nickname": "Bill" }
{ "language": "en", "url": "https://stackoverflow.com/questions/11856329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Nginx apply sub_filter directive based on response status code I have an Nginx server in which I use the sub_filter directive to inject a script in the HTML response by replacing the </head> closing tag: sub_filter '</head>' '<script src="some-custom-script.js"></script> </head>'; The problem is that I want to conditionally apply the sub_filter directive: I want it active only if the response status code is 2xx (e.g. success), and not for error status codes such as 404. The reason is that I do not want the script injected into error page HTMLs. Is that any way to achieve this "if else" branching in Nginx config? A: The first idea was using if statement and $status variable but sub_filter can't be used in if only in http, server, location. The same functionality can be implemented with body_filter_by_lua body_filter_by_lua ' if ngx.status == ngx.HTTP_OK then ngx.arg[1] = ngx.re.sub(ngx.arg[1], "</head>", "<script src=\"some-custom-script.js\"></script> </head>") end ';
{ "language": "en", "url": "https://stackoverflow.com/questions/63626470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angular 13 routing: Static with Resolved Data does not work After migration to angular 13, I get this routing errors: error TS2339: Property 'myParam' does not exist on type 'Data'. this.activatedRoute.data.subscribe(({ myParam, operation }) => { const myVariable = myParam; // this does not work }) { path: ':id/delete', component: MyComponentDeletePopupComponent, resolve: { myParam: MyComponentResolve }, data: { authorities: ['...'], pageTitle: 'home.title', operation: 'DELETE' }, canActivate: [UserRouteAccessService], outlet: 'popup' } Any idea ? A: The solution is to use res['myParam'] and res['operation'] It should look like this: this.activatedRoute.data.subscribe(res => { const myAttribute = res['myParam']; });
{ "language": "en", "url": "https://stackoverflow.com/questions/75483383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AWS Cognito - How to set first user as admin, every next as user. Like title, how can I set first registred user as admin and every next as normal user? A: Are you trying to simply identify if a certain user is the first to register? If so, you can use the Post Confirmation lambda trigger. Use a DynamoDB table to maintain a flag (this could be a count)and check this flag to identify if that is the first user to successfully confirm. Change the value of the flag to record that the first user has registered.
{ "language": "en", "url": "https://stackoverflow.com/questions/42365687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stop session from expiring when browser closes in MVC I am facing a session issue After I close my browser my session expires, and after re-open browser, I have to log in again. I don't want to expire my session on browser close. I am using this in my web.config file: <authentication> <forms loginUrl="~/account/login" name="astroswamig" slidingExpiration="true" timeout="1000"></forms> </authentication> <sessionState mode="StateServer" cookieless="false" timeout="1000" /> and this in my controller: string str = JsonConvert.SerializeObject(user); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.CustEmail, DateTime.Now, DateTime.Now.AddDays(120), true, str); string enctryptTicket = FormsAuthentication.Encrypt(ticket); HttpCookie authCustCookie = new HttpCookie(FormsAuthentication.FormsCookieName, enctryptTicket); authCustCookie.Domain = "xyz.com"; Response.Cookies.Add(authCustCookie); A: The web.config sample in the question is using StateServer mode, so the out-of-process ASP.NET State Service is storing state information. You will need to configure the State Service; see an example of how to do that in the "STATESERVER MODE(OUTPROC MODE)" section here: https://www.c-sharpcorner.com/UploadFile/484ad3/session-state-in-Asp-Net/ Also be sure to read the disadvantages section of the above linked article to make sure this approach is acceptable for your needs. Another way to manage user session is using the InProc mode to manage sessions via a worker process. You can then get and set HttpSessionState properties as shown here: https://www.c-sharpcorner.com/UploadFile/3d39b4/inproc-session-state-mode-in-Asp-Net/ and also here: https://learn.microsoft.com/en-us/dotnet/api/system.web.sessionstate.httpsessionstate?view=netframework-4.8#examples Again be sure to note the pros and cons of InProc mode in the above linked article to determine what approach best fits your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/59500802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Expression must have pointer-to-object type - What do I do? This problem keeps on bugging me for a very long time, yet I can't quite understand the problem or how to solve it. It says that Expression must have pointer-to-object type for i whenever I am in the for loop. Everything else seems to be fine. int number, number0, digit, numberLength = 1, dementor, i; cout << "Enter a number: "; cin >> number; number0 = number; while (number0 != 1) { number0 /= 10; numberLength++; } number0 = number; for(int i = numberLength; i >= 0; i--) { digit[i] = number0 % 10; number0 = number0 / 10; cout << digit << endl; }
{ "language": "en", "url": "https://stackoverflow.com/questions/54816313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python IF Else and For loop workflow I am trying to write a function that returns the number of prime numbers that exist up to and including a given number. Initially this was my code: def count_primes(num): prime = [2] x = 3 if num < 2: return 0 while x <= num: for y in prime: if x%y == 0: print('not prime') x+=2 break else: prime.append(x) x += 2 return len(prime) How ever I realise this code will run forever because of the following line of code: for y in prime: if x%y == 0: print('not prime') x+=2 break else: prime.append(x) x += 2 Can anyone help to explain to me why will this end up with an infinite loop compared to the following code? for y in prime: if x%y == 0: print('not prime') x+=2 break else: prime.append(x) x += 2
{ "language": "en", "url": "https://stackoverflow.com/questions/52124602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: selecting records from hive table where there are duplicates with a given criteria Table 1 has duplicate entries in column A with same frequency values. I need to select one random record out of those .If the duplicate entry contain 'unknown' as a column B value ( like in record "d") select one from other rows . I need a select statement which satisfy the above . Thanks . A: These conditions can be prioritized using a case expression in order by with a function like row_number. select A,B,frequency,timekey from (select t.* ,row_number() over(partition by A order by cast((B = 'unknown') as int), B) as rnum from tbl t ) t where rnum = 1 Here for each group of A rows, we prioritize rows other than B = 'unknown' first, and then in the order of B values. A: Use row_number analytic function. If you want to select not unknown record first, then use the query below: select A, B, Frequency, timekey from (select A, B, Frequency, timekey, row_number() over(partition by A,Frequency order by case when B='unknown' then 1 else 0 end) rn )s where rn=1 And if you want to select unknown if they exist, use this row_number in the query above: row_number() over(partition by A,Frequency order by case when B='unknown' then 0 else 1 end) rn
{ "language": "en", "url": "https://stackoverflow.com/questions/54169685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does it matter where the ret instruction is called in a procedure in x86 assembly I am currently learning x86 assembly. Something is not clear to me still however when using the stack for function calls. I understand that the call instruction will involve pushing the return address on the stack and then load the program counter with the address of the function to call. The ret instruction will load this address back to the program counter. My confusion is, does it matter when the ret instruction is called within the procedure/function? Will it always find the correct return address stored on the stack, or must the stack pointer be currently pointing to where the return address was stored? If that's the case, can't we just use push and pop instead of call and ret? For example, the code below could be the first on entering the function , if we push different registers on the stack, must the ret instruction only be called after the registers are popped in the reverse order so that after the pop %ebp instruction , the stack pointer will point to the correct place on the stack where the return address is, or will it still find it regardless where it is called? Thanks in advance push %ebp mov %ebp, %esp //push other registers ... //pop other registers mov %esp, %ebp (could ret instruction go here for example and still pop the correct return address?) pop %ebp ret A: You must leave the stack and non-volatile registers as you found them. The calling function has no clue what you might have done with them otherwise - the calling function will simply continue to its next instruction after ret. Only ret after you're done cleaning up. ret will always look to the top of the stack for its return address and will pop it into EIP. If the ret is a "far" return then it will also pop the code segment into the CS register (which would also have been pushed by call for a "far" call). Since these are the first things pushed by call, they must be the last things popped by ret. Otherwise you'll end up reting somewhere undefined. A: The CPU has no idea what is function/etc... The ret instruction will fetch value from memory pointed to by esp a jump there. For example you can do things like (to illustrate the CPU is not interested into how you structurally organize your source code): ; slow alternative to "jmp continue_there_address" push continue_there_address ret continue_there_address: ... Also you don't need to restore the registers from stack, (not even restore them to the original registers), as long as esp points to the return address when ret is executed, it will be used: call SomeFunction ... SomeFunction: push eax push ebx push ecx add esp,8 ; forget about last 2 push pop ecx ; ecx = original eax ret ; returns back after call If your function should be interoperable from other parts of code, you may still want to store/restore the registers as required by the calling convention of the platform you are programming for, so from the caller point of view you will not modify some register value which should be preserved, etc... but none of that bothers CPU and executing instruction ret, the CPU just loads value from stack ([esp]), and jumps there. Also when the return address is stored to stack, it does not differ from other values pushed to stack in any way, all of them are just values written in memory, so the ret has no chance to somehow find "return address" in stack and skip "values", for CPU the values in memory look the same, each 32 bit value is that, 32 bit value. Whether it was stored by call, push, mov, or something else, doesn't matter, that information (origin of value) is not stored, only value. If that's the case, can't we just use push and pop instead of call and ret? You can certainly push preferred return address into stack (my first example). But you can't do pop eip, there's no such instruction. Actually that's what ret does, so pop eip is effectively the same thing, but no x86 assembly programmer use such mnemonics, and the opcode differs from other pop instructions. You can of course pop the return address into different register, like eax, and then do jmp eax, to have slow ret alternative (modifying also eax). That said, the complex modern x86 CPUs do keep some track of call/ret pairings (to predict where the next ret will return, so it can prefetch the code ahead quickly), so if you will use one of those alternative non-standard ways, at some point the CPU will realize it's prediction system for return address is off the real state, and it will have to drop all those caches/preloads and re-fetch everything from real eip value, so you may pay performance penalty for confusing it. A: In the example code, if the return was done before pop %ebp, it would attempt to return to the "address" that was in ebp at the start of the function, which would be the wrong address to return to.
{ "language": "en", "url": "https://stackoverflow.com/questions/46714626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Module commons.math3 not found using jdeps I'm using JDEPS to list the dependencies of libraries to ensure they are satisfied. I've recently upgraded from Apache POI v4.1.1 to v5.0.0, where JigSaw modules were added. Previously, the following command would output the dependencies: jdeps --multi-release 11 poi-scratchpad-4.1.1.jar But now using v5.0.0, I'm getting: jdeps.exe --multi-release 11 poi-scratchpad-5.0.0.jar Exception in thread "main" java.lang.module.FindException: Module commons.math3 not found, required by org.apache.poi.scratchpad at java.base/java.lang.module.Resolver.findFail(Resolver.java:894) at java.base/java.lang.module.Resolver.resolve(Resolver.java:191) at java.base/java.lang.module.Resolver.resolve(Resolver.java:140) at java.base/java.lang.module.Configuration.resolve(Configuration.java:422) at java.base/java.lang.module.Configuration.resolve(Configuration.java:256) at jdk.jdeps/com.sun.tools.jdeps.JdepsConfiguration$Builder.build(JdepsConfiguration.java:564) at jdk.jdeps/com.sun.tools.jdeps.JdepsTask.buildConfig(JdepsTask.java:603) at jdk.jdeps/com.sun.tools.jdeps.JdepsTask.run(JdepsTask.java:557) at jdk.jdeps/com.sun.tools.jdeps.JdepsTask.run(JdepsTask.java:533) at jdk.jdeps/com.sun.tools.jdeps.Main.main(Main.java:49) I have the commons-math3 library, but even when I include it via the -classpath argument, I'm still getting the same issue. A: Using --module-path instead of the -classpath option for the module to be resolved for commons-math3-3.6.1.jar should work for you. In practice, you can detail all the dependencies into a single folder for simplicity and then treat that as modulepath such as following: In the above image, I have created a dependencies folder that includes the .jars for all dependent libraries for poi-scratchpad. Further executing the following command from the same directory works: jdeps --module-path dependencies poi-scratchpad-5.0.0.jar
{ "language": "en", "url": "https://stackoverflow.com/questions/65831117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Compilation errors with 12c Trigger statements? First post and it's a biggie. I've been stuck on this for a while and it's holding up the rest of my project - it's been a long time since I've done much in the way of database development. The last time I used Oracle it was on 11g but the syntax I'm trying to reuse from an old project doesn't seem to work now and I'm left scratching my head. I'd be incredibly grateful if anyone can point out the (probably) obvious thing I'm missing? Not sure if I've posted too much here so just say if so. Here's the table CREATE, and TRIGGER statements 1. CREATE 2. TABLE employees 3. ( 4. Employee_id NUMBER (4) NOT NULL , 5. firstname VARCHAR2 (64) NOT NULL , 6. surname VARCHAR2 (64) NOT NULL , 7. email VARCHAR2 (256) NOT NULL , 8. telephone VARCHAR2 (20) , 9. emp_password VARCHAR2 (32) NOT NULL , 10. startdate DATE NOT NULL , 11. organisation_id NUMBER (3) NOT NULL , 12. department_id NUMBER (2) NOT NULL , 13. jobtitle_id NUMBER (3) NOT NULL , 14. user_level NUMBER (1) NOT NULL , 15. Emp_added_by NUMBER (4) NOT NULL , 16. Emp_added_on TIMESTAMP NOT NULL , 17. Emp_updated_by NUMBER (4) NOT NULL , 18. Emp_updated_on TIMESTAMP NOT NULL 19. ) ; 20. ALTER TABLE employees ADD CONSTRAINT employees_PK 21. PRIMARY KEY ( employee_id ) ; And the Sequence and statement; 22. CREATE SEQUENCE "seq_employee_id" MINVALUE 1 MAXVALUE 9999 INCREMENT BY 1 23. START WITH 1 NOCACHE ORDER NOCYCLE ; And finally the trigger that's giving me shit; 24. create or replace 25. trigger trg_employees 26. BEFORE 27. INSERT OR 28. UPDATE OF employee_id 29. ON employees FOR EACH ROW 30. BEGIN 31. IF INSERTING THEN IF 32. :NEW.employee_id = NULL THEN 33. SELECT seq_employee_id.NEXTVAL 34. INTO :NEW.employee_id 35. FROM sys.dual; 36. END IF; 37. END IF; 38. /*format firstname to have initial capital letter*/ 39. :NEW.firstname := INITCAP(:NEW.firstname); 40. /*format surname to have initial capital letter*/ 41. :NEW.surname := INITCAP(:NEW.surname); 42. /*replace any characters other than digits with an empty string*/ 43. :NEW.telephone := REGEXP_REPLACE(:NEW.telephone, '[^[:digit:]]', ''); 44. /*adjust to (99999) 999999 format */ 45. :NEW.telephone := REGEXP_REPLACE(:NEW.telephone, 46. '([[:digit:]]{5})([[:digit:]](6)', '(\1) \2'); 47. END; 48. ELSIF UPDATING THEN 49. SELECT SYSDATE INTO :NEW.employee_updated_on FROM sys.dual; 50. END IF; 51. END; /*This trigger automatically inserts a timestamp into updated rows to show audit details.*/ 52. CREATE OR REPLACE TRIGGER trg_employee_update 53. BEFORE UPDATE ON employees FOR EACH ROW 54. BEGIN /* Update "employee_updated_on" to current system date*/ 55. :NEW.employee_updated_on := sysdate; 56. END; I can create the table, constraints, and sequence with no trouble; but when I run the trigger statement it compiles with the following errors 4,7 PL/SQL: SQL Statement ignored 4,14 PL/SQL: ORA-02289: sequence does not exist Now obviously the sequence does exist, but I have no idea at all why it can't recognise it as I can view the sequence fine in my database. I don't know if I've got a syntax error at line 10, SELECT seq_employee_id.NEXTVAL, perhaps? A: The sequence you're referencing in your trigger doesn't exist. If you use double-quotes around the identifier in your CREATE SEQUENCE statement CREATE SEQUENCE "seq_employee_id" MINVALUE 1 MAXVALUE 9999 INCREMENT BY 1 START WITH 1 NOCACHE ORDER NOCYCLE ; then you are creating a case-sensitive identifier. If you do that, you would need to refer to the identifier using double quotes and with the correct case every time you refer to it. That's generally rather annoying which is why I'd never suggest creating case-sensitive identifiers. SELECT "seq_employee_id".NEXTVAL INTO :NEW.employee_id FROM sys.dual; Starting with 11g, you can simplify the statement by doing a direct assignment of the sequence :new.employee_id := "seq_employee_id".nextval; Realistically, I'd suggest recreating the sequence without the double-quotes and using the direct assignment to the :new.employee_id.
{ "language": "en", "url": "https://stackoverflow.com/questions/23049952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to point to a number that correspond value of this number is selected by user? Suppose i have two table as person and OfficeAccess. In person i'll save the staffs of office and in OfficeAccess i save access of this staffs to office's building. "person" has this field: "IdKnown, name, family, phone, IdAccess and OfficeAccess has this field: IdAccess, AccessDeccription. IdAccess foreign key in person have a reference to OfficeAccess and IdAccess column. Suppose i make a windows in WPF to add a new staff and in this window i put TextBoxfor name and family and phone and i put a ComboBox to add IdAccess. but combo bind to OfficeAccess and AccessDeccription values are shown in this combo. Now, how can i add IdAccess to person when user select a value of combo? I have already said that i use of EF6. private void btnSave_Click(object sender, RoutedEventArgs e) { FaceDBEntities.FaceDBEntities FaceDB = new FaceDBEntities.FaceDBEntities(); try { tblOfficeAccess OffAcs = new tblOfficeAccess(); tblperson PerTbl = new tblperson() { Name = txtName.Text.ToString(), Family = txtFamily.Text.ToString(), Phone = txtPhone.Text.ToString(), IdAccess=OffAcs.IdAccess (????) }; FaceDB.tblperson.Add(PerTbl); FaceDB.SaveChanges(); } catch { } A: try this IdAccess = from x in OffAcs where x.AccessDeccription == Combobox.SelectedText select x.IdAccess; or this: IdAccess = OffAcs.First(x=>x.AccessDeccription == Combobox.SelectedText).IdAccess;
{ "language": "en", "url": "https://stackoverflow.com/questions/38010260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-8" }
Q: Find the centroid of Clusters generated by the hclust function I need to get the centroid for each cluster computed by the hierarchical method. First, this is a part of my dataset to get reproductible example: > dput(DATABASE[1:20,]) structure(list(TYPE_PEAU = c(2L, 2L, 3L, 2L, 2L, 2L, 2L, 4L, 3L, 2L, 2L, 2L, 2L, 1L, 4L, 2L, 2L, 2L, 4L, 2L), SENSIBILITE = c(3L, 2L, 3L, 3L, 3L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 3L, 3L, 3L, 1L, 3L, 3L), IMPERFECTIONS = c(2L, 2L, 3L, 3L, 1L, 2L, 2L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 3L, 1L, 2L, 1L, 2L, 2L), BRILLANCE = c(3L, 3L, 1L, 3L, 1L, 3L, 3L, 1L, 1L, 3L, 3L, 3L, 3L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), GRAIN_PEAU = c(3L, 3L, 3L, 1L, 3L, 3L, 3L, 2L, 3L, 2L, 1L, 3L, 1L, 1L, 3L, 1L, 3L, 3L, 1L, 3L), RIDES_VISAGE = c(3L, 1L, 1L, 3L, 1L, 3L, 3L, 3L, 3L, 3L, 2L, 1L, 3L, 1L, 3L, 3L, 3L, 3L, 3L, 3L), MAINS = c(2L, 2L, 3L, 3L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 2L), PEAU_CORPS = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 2L, 2L, 3L, 2L, 3L, 2L, 3L, 2L, 2L, 1L), INTERET_ALIM_NATURELLE = c(1L, 1L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 1L, 3L, 1L, 3L, 1L, 3L, 1L, 1L, 1L, 1L), INTERET_ORIGINE_GEO = c(1L, 1L, 2L, 3L, 1L, 1L, 1L, 1L, 1L, 3L, 1L, 3L, 1L, 1L, 3L, 3L, 1L, 1L, 1L, 1L), INTERET_VACANCES = c(1L, 2L, 3L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 3L, 1L, 2L), INTERET_ENVIRONNEMENT = c(1L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), AGE_INTERVAL = c(3L, 3L, 4L, 2L, 2L, 3L, 3L, 4L, 4L, 3L, 4L, 2L, 1L, 3L, 3L, 2L, 2L, 2L, 2L, 3L), ATTENTE_BEAUTE_1 = c(1L, 6L, 4L, 4L, 6L, 6L, 3L, 1L, 1L, 4L, 3L, 6L, 2L, 5L, 5L, 6L, 7L, 4L, 6L, 3L), ATTENTE_BEAUTE_2 = c(2L, 2L, 3L, 6L, 4L, 1L, 4L, 7L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 2L, 6L, 2L, 2L, 2L), MILIEU_VIE = c(1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), PROFIL_SELECTIONNE = c(1L, 32L, 21L, 23L, 34L, 31L, 15L, 6L, 1L, 20L, 14L, 34L, 9L, 28L, 28L, 32L, 42L, 20L, 32L, 14L), NOMBRE_ACHAT = c(14L, 6L, 3L, 9L, 8L, 13L, 10L, 14L, 4L, 3L, 10L, 8L, 12L, 3L, 7L, 6L, 4L, 13L, 3L, 3L), NOMBRE_CADEAU = c(2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L)), .Names = c("TYPE_PEAU", "SENSIBILITE", "IMPERFECTIONS", "BRILLANCE", "GRAIN_PEAU", "RIDES_VISAGE", "MAINS", "PEAU_CORPS", "INTERET_ALIM_NATURELLE", "INTERET_ORIGINE_GEO", "INTERET_VACANCES", "INTERET_ENVIRONNEMENT", "AGE_INTERVAL", "ATTENTE_BEAUTE_1", "ATTENTE_BEAUTE_2", "MILIEU_VIE", "PROFIL_SELECTIONNE", "NOMBRE_ACHAT", "NOMBRE_CADEAU"), row.names = c(NA, 20L), class = "data.frame") then I used as follow : mydist = dist(DATABASE) clusters = cutree(hclust(mydist),k=3) > clusters [1] 1 2 3 3 2 2 3 1 1 3 1 2 1 3 2 2 2 3 2 1 3 2 1 1 1 1 2 1 2 1 3 3 2 3 2 2 1 1 1 1 3 2 1 1 3 2 1 2 2 1 2 2 3 1 3 1 3 [58] 1 3 2 2 1 1 2 1 2 2 2 3 2 3 1 2 2 1 1 3 3 2 1 2 2 1 2 3 3 3 1 2 1 2 1 1 1 1 1 3 2 2 2 1 1 3 2 2 1 1 1 2 1 1 1 1 3 [115] 1 2 2 1 2 3 1 1 2 3 1 1 1 2 1 3 1 2 3 2 2 1 2 1 1 3 3 2 1 2 2 1 1 1 1 2 1 2 2 3 3 1 1 3 1 3 3 3 3 2 3 1 2 3 3 3 1 [172] 1 2 2 1 1 2 1 2 2 1 3 3 1 2 2 1 1 1 2 2 1 1 1 1 3 2 3 3 1 1 2 2 2 3 1 1 1 2 2 1 2 1 3 1 2 1 3 3 1 1 1 1 2 1 2 2 2 [229] 3 3 1 1 2 1 3 2 2 2 1 1 2 1 3 1 2 1 3 1 3 1 3 1 1 1 1 2 2 1 3 3 3 2 1 2 3 2 2 1 1 3 1 2 3 1 1 2 1 1 1 1 2 2 2 3 2 [286] 1 2 1 1 2 1 2 1 2 2 1 2 3 1 3 1 3 1 1 3 1 1 2 2 1 3 3 2 2 1 2 1 1 2 2 1 3 3 2 2 1 3 3 3 1 1 1 1 3 3 2 1 3 1 2 1 2 [343] 1 2 3 3 2 3 1 3 2 3 3 1 2 2 1 2 2 3 2 1 3 2 2 1 2 3 2 3 3 3 2 2 3 2 1 1 1 2 3 2 2 1 2 2 2 1 2 1 1 1 3 1 2 2 1 1 2 [400] 1 1 1 1 1 2 2 2 Please Note that the objectif is to compute the inter and intra inertia: So i need to compute the distance between each centroid and all points that are included in its cluster. So I need to compute the distance between each centroid and its concerned cluster to used then for computing the inter and intra inertia. A: You can define the centroids as the means of variables, per cluster, in DATABASE. mydist <- dist(DATABASE) clusters <- cutree(hclust(mydist), k = 3) ## Col means in each cluster apply(DATABASE, 2, function (x) tapply(x, clusters, mean)) ## or DATABASE$cluster <- clusters # add cluster to DATABASE # Now take means per group library(dplyr) centroids <- DATABASE %>% group_by(cluster) %>% summarise_all(funs(mean)) ## Distance between centroids dist(centroids[, -1], method = "euclidean") ## Example for distance in cluster 1 (distance between all observations of cluster 1) DATABASE %>% filter(cluster == 1) %>% select(-cluster) %>% dist() A: you might want to specify your k value into 1:3 not just 3 here is the code and how to find the center (mean)
{ "language": "en", "url": "https://stackoverflow.com/questions/51376552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to move jquery ui in to the footer to wordperss? I am able to move jquery ui in the footer but i want to move it between the footer scripts (above all js scripts). here is the code i used to load jquery in the footer. if (!is_admin()) add_action("wp_enqueue_scripts", "wpf_CybarMagazine_scripts", 11); function wpf_CybarMagazine_scripts() { wp_deregister_script('jquery'); wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js", false, '1.11.1', true); wp_enqueue_script('jquery'); } html output is.... <script type='text/javascript' src='http://localhost/demo/CybarMagazine/wp-includes/js/admin-bar.min.js?ver=4.0.1'></script> <script type='text/javascript' src='http://localhost/demo/CybarMagazinehttp//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script> <script type='text/javascript' src='http://localhost/demo/CybarMagazine/wp-content/themes/CybarMagazine/js/bootstrap.min.js'></script> I want to load the jquery library in top, but i can't find any solution for moving the jquery between footer scripts. Any suggestions will be appreciated. Thanks A: Quickfix. Try this: wp_register_script('jquery', "//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js", false, '1.11.1', true); Update: Let's split this string into 3 parts: * *"http" *($_SERVER['SERVER_PORT'] == 443 ? "s" : "") *"//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js", false, '1.11.1', true); * *"http" - We don't need beucase jQuery starts with // *This is if/else statemnt which was causing the problem, it was adding localhost/demo/CybarMagazinehttp to your output results *This what link to jQuery DNS which we want to leave without changes
{ "language": "en", "url": "https://stackoverflow.com/questions/27123472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Attach API: How to set agent properties? The Java Attach API for JDK6 provides a method getAgentProperties() on VirtualMachine: public abstract Properties getAgentProperties() throws IOException Returns the current agent properties in the target virtual machine. The target virtual machine can maintain a list of properties on behalf of agents. The manner in which this is done, the names of the properties, and the types of values that are allowed, is implementation specific. Agent properties are typically used to store communication end-points and other agent configuration details. For example, a debugger agent might create an agent property for its transport address. This method returns the agent properties whose key and value is a String. Properties whose key or value is not a String are omitted. If there are no agent properties maintained in the target virtual machine then an empty property list is returned. (from the Java Attach API) My question is, how to set these properties on the other side (i.e. within the JVM where the agent is running) ? The documentation for the instrument API doesn't talk about this either. A: On Hot Spot VM you can set agent properties using sun.misc.VMSupport.getAgentProperties().
{ "language": "en", "url": "https://stackoverflow.com/questions/6894920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Set XML values in jTable I've got a jTable and now I want to add the content of a XML-File into it. I dont know how I should browse through the XML-File, I was currently only able to manipulate the data (rewrite, deleting) and to get the Values of a Single tag and not of all. I'm using JDOM my XML-File looks like this: <?xml version="1.0" encoding="UTF-8"?> <app> <!-- Pfad für Templates und speicher ort für die Entity.java--> <Entity> <Name>Aposting</Name> <Art>0</Art> <Datum>Wed Nov 19 10:51:10 CET 2014</Datum> </Entity> <Entity> <Name>Aposting</Name> <Art>1</Art> <Datum>Wed Nov 19 11:30:34 CET 2014</Datum> </Entity> <Entity> <Name>Aposting</Name> <Art>1</Art> <Datum>Wed Nov 19 15:21:12 CET 2014</Datum> </Entity> <Entity> <Name>Aposting</Name> <Art>2</Art> <Datum>Thu Nov 20 8:01:10 CET 2014</Datum> </Entity> </app> And i want to display it in a Table like this: Thank you for your help Edit: i've made a Custom model package TableTest; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.swing.event.TableModelListener; import javax.swing.table.TableModel; /** * * @author Administrator */ public class ModelData implements TableModel { List<TableData> data = new ArrayList<>(); String colNames[] = {"Name", "Type", "Date"}; Class<?> colClasses[] = {String.class, String.class, Date.class}; ModelData() { data.add(new TableData("Aposting", "Created", new Date())); data.add(new TableData("Aposting", "Edited", new Date())); data.add(new TableData("Aposting", "Edited", new Date())); data.add(new TableData("Aposting", "Deleted", new Date())); } @Override public int getRowCount() { return data.size(); } @Override public int getColumnCount() { return colNames.length; } @Override public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) { return data.get(rowIndex).getName(); } if (columnIndex == 1) { return data.get(rowIndex).getType(); } if (columnIndex == 2) { return data.get(rowIndex).getDate(); } return null; } @Override public String getColumnName(int columnIndex) { return colNames[columnIndex]; } @Override public Class<?> getColumnClass(int columnIndex) { return colClasses[columnIndex]; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return true; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (columnIndex == 0) { data.get(rowIndex).setName((String) aValue); } if (columnIndex == 1) { data.get(rowIndex).setType((String) aValue); } if (columnIndex == 2) { data.get(rowIndex).setDate((Date) aValue); } } @Override public void addTableModelListener(TableModelListener l) { } @Override public void removeTableModelListener(TableModelListener l) { } } and a TableData class which is to access: package TableTest; import java.util.Date; public class TableData { String name; String type; Date date; public TableData(String name, String type, Date date) { super(); this.name = name; this.type = type; this.date = date; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } } and it works with the added values in "ModelData" but i still got no clue how i could extract all Entities out of my XML-File A: You'll need two things for this: * *A suitable XML parser. *A custom table model, illustrated here. Depending on the chosen parser, you can either * *Construct a Java data structure, e.g. List<Entity>, that can be accessed in the TableModel. *Access the document object model directly to meet the TableModel contract for getValueAt(), getRowCount(), etc. Addendum: Based on your edit, * *While you evaluate other parsing options, start with a simple SAXParser, illustrated here. The example builds a List<School>; you'll build a List<TableData>. *In your custom table model, extend AbstractTableModel to get the event handling illustrated here.
{ "language": "en", "url": "https://stackoverflow.com/questions/27014038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Objective-C - NSTimer: unrecognized selector sent to class - call method from another class addCloudOne is a method within the Food class. The following code produces a crash with the following error: +[Food addCloudOne]: unrecognized selector sent to class 0x1000ad760 SEL selector = @selector(addCloudOne); [NSTimer scheduledTimerWithTimeInterval:k1 target:[Food class] selector:selector userInfo:nil repeats:YES]; Do you have ideas? A: You need to specify an instance of the Food class, so this argument is incorrect: target:[Food class] So what you are passing to NSTimer is a Class object, not a Food object. Instead you probably need an instance variable of the Food instance and specify that: @interface MyClass () { Food *_food; } @implementation MyClass ... - (void)whatever { _food = [Food new]; // This might need to be elsewhere SEL selector = @selector(addCloudOne); [NSTimer scheduledTimerWithTimeInterval:k1 target:_food selector:selector userInfo:nil repeats:YES]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/25424354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirect to profile url after login I am new in backend Node.js and till now I am able to complete registration and login with authentication. When login I am getting token in response by using jwt token Now I want to have the registration details to be shown to users after login. After login the details must of be of particular user's only whos is logging in. And if admin is logging in, then he will get the entire database user's fields. This is my index.route:- const express = require ('express'); const router = express.Router(); const mongoose = require ('mongoose'); const User = mongoose.model('User'); const ctrlUser = require ('../controllers/user.controller.js'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const passport = require('passport'); // routing functions //registartion user signup router.post('/register' , ctrlUser.register); //login user router.post('/login' , (req, res, next) => { User.find({email: req.body.email}) .exec() .then(user => { if(user.length < 1) { return res.status(401).json({ message: "Auth failed. User not found." }) } bcrypt.compare(req.body.password, user[0].password, (err, result) =>{ if (err) { return res.status(401).json({ message: "Auth failed. Check email and password" }); } if (result){ const adminEmail = "[email protected]"; const role = user[0].email===adminEmail? "admin" : "user"; //check user id as admin or user const token = jwt.sign( { email: user[0].email, userId: user[0]._id, role }, process.env.JWT_KEY, { expiresIn : "1h" }); return res.status(200).json({ message: "Auth Successful", token : token }); res.redirect('/profile'); } }); }) .catch(err =>{ if (err.code == 500) res.status(500).send(["Something went wrong in login"]); else return next(err); }); }); router.get('/profile', function(req, res, next){ //something todo here ... }); //delete user router.delete('/:userId' , (req, res, next) =>{ User.deleteMany({_id: req.params.userId}) .exec() .then(result => { res.status(200).send(["Deleted"]); }) .catch(err =>{ if (err.code == 500) res.status(500).send(["Didn't get deleted"]); else return next(err); }); }); module.exports = router; How can I access user's details in profile url API? A: Get JWT from request header then decode jwt.verify(token, getKey, options, function(err, decoded) { console.log(decoded.email) }); jwt.verify - jwt doc A: Create new middleware ( above other routes) // route middleware to verify a token router.use(function(req, res, next) { // check header or url parameters or post parameters for token var token = req.body.token || req.query.token || req.headers['x-access-token']; // decode token if (token) { // verifies secret and checks exp jwt.verify(token, app.get('superSecret'), function(err, decoded) { if (err) { return res.json({ success: false, message: 'Failed to authenticate token.' }); } else { // if everything is good, save to request for use in other routes req.decoded = decoded; next(); } }); } else { // if there is no token // return an error return res.status(403).send({ success: false, message: 'No token provided.' }); } }); Help : jwt - decode and save in req A: In the code, After return your redirect never work. so There're 2 options: * *You don't need to return a token to client, just use res.redirect('/profile') after your verification. (in this way, your server and client are in one) *You just return the token to client (Don't use res.redirect('/profile') anymore) then client will use that token to redirect to the profile. (in this way, your server and client are separate each other).
{ "language": "en", "url": "https://stackoverflow.com/questions/54070157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Posting a tweet on the Twitter timeline using "TwitterOAuth" I am trying to post a feed on Twitter using TwitterOAuth. I have two PHP scripts, redirect.php, and callback.php that work as follows. redirect.php -> twitter auth -> callback.php Whatever session key/values stored upon calling redirect.php are lost when callback.php is called for some reason. The both PHP files reside in the same domain and HTTPS is used all the way through. session_start() is used in the both scripts right before storing and fetching session data. What could be the cause of this problem? A: It turns out that Apache was not able write session files to a directory(in my case, /var/lib/php/session) specified in the php.ini. Granting the write permission for this directory to Apache has solved the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/35446756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Serialization of ArrayList containing multiple objects, doesn't save object state I can't seem to figure out why serialization saves and restores the list of objects, but not the their state. The list is displayed, but not the title which is contained in the object. The object class implements Serializable. Serialization of objects ("c"): arrayList.add ( c ); String fileName = "testFile"; try { FileOutputStream fos = this.openFileOutput ( fileName, Context.MODE_PRIVATE ); ObjectOutputStream os = new ObjectOutputStream ( fos ); os.writeObject ( arrayList ); fos.close (); os.close (); } catch ( Exception ex ) { ex.printStackTrace (); } } Deserialization: FileInputStream fis = this.openFileInput ( fileName ); ObjectInputStream ois = new ObjectInputStream ( fis ); arrayList = ( ArrayList<TestObject> ) ois.readObject (); ois.close (); return arrayList; Adding objects to adapter: for ( TestObject c : arrayList ) { adapter.add ( c ); } Edit: part of the TestObject class: public class TestObject implements Serializable { private String mName; @Override public String toString () { return mName; } public String getName () { return mName; } public void setName ( String name ) { mName = name; } A: yes, It is also working for me check public class SerializationIssue { private static final String fileName = "testFile"; public static void main(String[] args) { TestObject object1= new TestObject(); TestObject object2=new TestObject(); object1.setName("object1"); object2.setName("object2"); List<TestObject> list=new ArrayList<TestObject>(); list.add(object1); list.add(object2); serializeList(list); ArrayList<TestObject> deserializedList=desializeDemo(); System.out.println(deserializedList.get(0).getName()); } private static ArrayList desializeDemo() { ArrayList<TestObject> deserializedList; try { FileInputStream fileIn = new FileInputStream(fileName); ObjectInputStream in = new ObjectInputStream(fileIn); deserializedList= (ArrayList<TestObject>) in.readObject(); in.close(); fileIn.close(); }catch(IOException i) { i.printStackTrace(); return null; }catch(ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); return null; } return deserializedList; } private static void serializeList(List<TestObject> list) { // TODO Auto-generated method stub try { FileOutputStream fos = new FileOutputStream(fileName); ObjectOutputStream os = new ObjectOutputStream ( fos ); os.writeObject ( list ); fos.close (); os.close (); } catch ( Exception ex ) { ex.printStackTrace (); } } } TestObject bean public class TestObject implements Serializable{ /** * serial version. */ private static final long serialVersionUID = 1L; String name; public TestObject(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Output:object1
{ "language": "en", "url": "https://stackoverflow.com/questions/19741376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }