text
stringlengths
15
59.8k
meta
dict
Q: Converting object to Integer equals null I am trying to convert an object from an object to an integer in java. These are the results I get with the following methods: Object intObject = 50; intObject: 50 intObject.toString(): 50 Integer.getInteger(intObject.toString()): null I have no idea why I would get a null when converting the string of the object to an integer. Here is the code that I am using: final Object temp = mCloudEntity.get(SaveAndLoadManager.TAG_TEST_INT); Log.i(TAG, "intObject: " + temp ); Log.i(TAG, "intObject.toString(): " + temp.toString()); Log.i(TAG, "Integer.getInteger(intObject.toString()): " + Integer.getInteger(temp.toString())); A: You should use // Parses the string argument as a signed decimal integer Integer.parseInt(intObject.toString()); instead of // Determines the integer value of the system property with the specified name. // (Hint: Not what you want) Integer.getInteger(...)
{ "language": "en", "url": "https://stackoverflow.com/questions/17560994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to SELECT with several conditions? (WHERE ... AND ... IN (...)) For example: in my database I have 3 tables: COMPANY, COUPON and COMPANY_COUPON. COMPANY table has fields: ID and NAME, COUPON table has: ID, TITLE and TYPE, COMPANY_COUPON table has: ID of the COMPANies and ID of the COUPONs that they own. So, in java to get all coupons of the company I use command: SELECT coupon_id FROM company_coupon WHERE company_id = ? And put it into Collection. But I need something to get all coupons of the company by the type, something like: SELECT * FROM company_coupon WHERE company_id = 1 AND coupon_id = (SELECT * FROM coupon WHERE type = camping) of course this one is not working, but I'm looking for something like that. I know that i can get all coupons of the company and put them into Collection and then just delete all coupons that not equals to the specified type, but is there any way to do this process in database by SQL commands? A: Use only one column with an IN operator SELECT * FROM COMPANY_COUPON WHERE COMPANY_ID = 1 AND COUPON_ID IN (SELECT COUPON_ID FROM COUPON WHERE TYPE = CAMPING) A: I think you just want a join: SELECT cc.COUPON_ID FROM COMPANY_COUPON cc JOIN COUPON c ON cc.COUPON_ID = c.ID WHERE cc.COMPANY_ID = ? AND c.TYPE = ?; A: You might want to use WHERE IN here: SELECT * FROM COMPANY_COUPON WHERE COMPANY_ID = 1 AND COUPON_ID IN (SELECT ID FROM COUPON WHERE TYPE = 'CAMPING'); You could also use EXISTS, which is probably the best way to write your logic: SELECT cc.* FROM COMPANY_COUPON cc WHERE cc.COMPANY_ID = 1 AND EXISTS (SELECT 1 FROM COUPON c WHERE c.TYPE = 'CAMPING' AND c.ID = cc.COUPON_ID); Using EXISTS might outperform doing a join between the two tables, because the database can stop as soon as it finds the very first match.
{ "language": "en", "url": "https://stackoverflow.com/questions/54062794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem showing image from a database with JSF via a Servlet EDIT: The reason for this issue was due to bug unrelated to the servlet. I'm working on a JSF2/JPA/EJB3 project that enables users to upload photos of themselves and stores them in a database. Loading images from the database is made possible with a servlet. There is however a problem; when changing the picture and posting the page, the image goes blank. The servlet doesn't seem to be called. Web page: <h:form> <h:graphicImage value="image?fileId=#{bean.currentUser.photo.id}"/> <3rd party file upload component (primeFaces)/> <h:commandButton value="post"/> </h:form> Servlet mapping: <servlet> <servlet-name>imageServlet</servlet-name> <servlet-class>com.xdin.competence.jsf.util.ImageServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>imageServlet</servlet-name> <url-pattern>/image/*</url-pattern> </servlet-mapping> Servlet: @ManagedBean public class ImageServlet extends HttpServlet { private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB. @EJB private UserBean userBean; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Long fileId = Long.parseLong(request.getParameter("fileId")); if (fileId == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404. return; } UserFile photo = userBean.findUserFile(fileId); // Init servlet response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setContentType("image/png"); response.setHeader("Content-Length", String.valueOf(photo.getFileData().length)); response.setHeader("Content-Disposition", "inline; filename=\"" + photo.getFilename() + "\""); // Prepare streams. BufferedInputStream input = null; BufferedOutputStream output = null; try { // Open streams. input = new BufferedInputStream(new ByteArrayInputStream(photo.getFileData()), DEFAULT_BUFFER_SIZE); output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE); // Write file contents to response. byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int length; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } } finally { // Gently close streams. close(output); close(input); } } private static void close(Closeable resource) { if (resource != null) { try { resource.close(); } catch (IOException e) { // Do your thing with the exception. Print it, log it or mail it. e.printStackTrace(); } } } My guess is that doGet in ImageServlet is only called on Get. Forcing a new GET with faces-redirect=true works, but is it possible to make the servlet work on POST aswell? A: You seem to think that images are downloaded as part of the HTTP response containing the HTML page containing the <img> elements. This is not true. The browser obtains the HTML page, parses the HTML structure, encounters the <img> element and fires separate HTTP requests for each of them. It is always GET. The same applies to CSS/JS and other resources. Install a HTTP request debugger tool like Firebug and check the Net panel. The actual problem is likely that the URL as definied in src attribute is wrong. You're using a context-relative path (i.e. no leading slash and no domain in the src attribute, it's fully dependent on the current request URL -the one in browser address bar). Probably the HTML page get posted to a different context/folder which caused that the image becomes unreachable from that point. Try using an absolute path or a domain-relative path. <h:graphicImage value="#{request.contextPath}/image?fileId=#{bean.currentUser.photo.id}" /> If still in vain, then have a closer look at Firebug's analysis.
{ "language": "en", "url": "https://stackoverflow.com/questions/4644789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I want to make an Script in python which will calculate Beneish M Score in python Table 1 – Financials (standalone) Year 2014 2013 2012 2011 2010 Net Sales 8,020.35 9,754.50 8,433.48 6,447.24 4,827.47 Cost of Goods 5,524.76 7,416.64 6,299.72 4,494.74 3,176.16 Net Receivables 2,045.70 2,807.26 1,689.88 1,109.29 693.33 Current Assets 4,000.61 4,894.15 4,228.61 2,747.23 2,236.16 Property, Plant and Equipment 1,848.27 2,177.22 1,948.19 1,834.23 1,552.22 Depreciation 199.02 219.18 203.06 194.05 180.10 Total Assets 13,994.40 13,215.16 12,186.17 10,201.72 8,480.00 SGA Expense 588.25 495.77 451.73 347.35 338.63 Net Income 673.95 423.05 345.39 379.69 283.40 Cash Flow from Operations 988.18 1.17 406.65 340.06 1,069.19 Current Liabilities 4,301.49 4,697.45 4,868.32 3,087.15 889.03 Long-term Debt 1,492.06 1,503.40 1,475.46 1,534.03 3,640.02 Table 2 – Financials (consolidated) Year 2014 2013 2012 2011 2010 Net Sales 26,111.94 26,003.67 21,840.29 18,187.77 15,523.34 Cost of Goods 10,323.87 11,543.19 9,156.12 6,872.80 5,519.23 Net Receivables 2,642.69 3,358.56 2,220.68 1,530.03 1,083.42 Current Assets 17,581.22 17,393.72 13,317.96 10,932.59 5,528.21 Property, Plant and Equipment 17,998.98 15,444.53 12,490.63 8,847.56 6,544.69 Depreciation 1,608.86 1,295.49 1,092.33 940.90 866.48 Total Assets 63,034.10 57,105.27 45,157.00 39,600.52 28,988.86 SGA Expense 1,730.27 1,625.98 1,347.43 1,231.69 1,640.42 Net Income 1,221.80 1,183.89 1,010.15 907.97 154.56 Cash Flow from Operations 47.62 -993.70 153.47 1,263.04 4,235.99 Current Liabilities 14,515.48 15,660.07 11,881.23 9,106.74 3,206.53 Long-term Debt 12,460.74 9,392.73 5,641.57 4,680.65 7,432.40 Here from the above table I need to calculate different Indexes: Index 1: Days Sales in Receivables Index (DSRI) = Net Receivable [CY]/ Net Sales [CY] Divided by Net Receivable [CY-1]/ Net Sales [CY-1] So I thought storing all the Table 1 data in dictionary like this: Net_Sales = {2014: 8020.35, 2013:9754.50, 2012:8433.48, 2011:6447.24, 2010:4827.47} Cost_Goods = {2014: 5524.76, 2013:7416.64, 2012:6299.72, 2011:4494.74, 2010:3176.16} Net_Receivables = {2014:2045.70, 2013:2807.26, 2012:1689.88, 2011:1109.29, 2010:693.33} Current_Assets = {2014:4000.61, 2013:4894.15, 2012:4228.61, 2011:2747.23, 2010:2236.16} Property_Plant_Equipment = {2014:1848.27, 2013:2177.22, 2012:1948.19, 2011:1834.23, 2010:1552.22} Depreciation = {2014:199.02, 2013:219.18, 2012:203.06, 2011:194.05, 2010:180.10} Total_Assets = {2014:13994.40, 2013:13215.16, 2012:12186.17, 2011:10201.72, 2010:8480.00} SGA_Expense = {2014:588.25, 2013:495.77, 2012:451.73, 2011:347.35, 2010:338.63} Net_Income = {2014:673.95, 2013:423.05, 2012:345.39, 2011:379.69, 2010:283.40} Cash_Flow_Operations = {2014:988.18, 2013:1.17, 2012:406.65, 2011:340.06, 2010:1069.19} Current_Liabilities = {2014:4301.49, 2013:4697.45, 2012:4868.32, 2011:3087.15, 2010:889.03} Long_Deb = {2014:1492.06, 2013:1503.40, 2012:1475.46, 2011:1534.03, 2010:3640.02} But then again I need to make lots of dictionary for Table 2 also. And again I need to display the output in a table like this: #Index 1 using the formula 1. Net Receivable [CY-1]/ Sales [CY-1] Year 2014 2013 2012 2011 As per Standalone Financials 0.886 1.436 1.165 1.198 As per Consolidated Financials 0.784 1.270 1.209 1.205 I calculated the 1st value using the following formula: DSRI = (Net_Receivables[2014]/Net_Sales[2014]) / (Net_Receivables[2013]/Net_Sales[2013]) And I got the only one value. So it would be very hectic and unplanned way to do the above calculation. As I need to do lots of calculation on the above data. So can someone help me how to store these data if not in dictionary then where. And how should I plan to calculate all the required values. As I need to calculate 8 indexes and maybe in the future I can reuse it for different set of years. Thanks. Please tell me if you need more information.
{ "language": "en", "url": "https://stackoverflow.com/questions/33646537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to schedule a MySQL database backup in a remote Ubuntu server to a Dropbox folder in Windows PC? I have a MySQL database that I want to daily backup to my Dropbox folder on my Windows PC. How can I do that automatically from Windows 7? A: One of the simplest ways to backup a mysql database is by creating a dump file. And that is what mysqldump is for. Please read the documentation for mysqldump. In its simplest syntax, you can create a dump with the following command: mysqldump [connection parameters] database_name > dump_file.sql where the [connection parameters] are those you need to connect your local client to the MySQL server where the database resides. mysqldump will create a dump file: a plain text file which contains the SQL instructions needed to create and populate the tables of a database. The > character will redirect the output of mysqldump to a file (in this example, dump_file.sql). You can, of course, compress this file to make it more easy to handle. You can move that file wherever you want. To restore a dump file: * *Create an empty database (let's say restore) in the destination server *Load the dump: mysql [connection parameters] restore < dump_file.sql There are, of course, some other "switches" you can use with mysqldump. I frequently use these: * *-d: this wil tell mysqldump to create an "empty" backup: the tables and views will be exported, but without data (useful if all you want is a database "template") *-R: include the stored routines (procedures and functions) in the dump file *--delayed-insert: uses insert delayed instead of insert for populating tables *--disable-keys: Encloses the insert statements for each table between alter table ... disable keys and alter table ... enable keys; this can make inserts faster You can include the mysqldump command and any other compression and copy / move command in a batch file. A: My solution to extract a backup and push it onto Dropbox is as below. A sample of Ubuntu batch file can be downloaded here. In brief * *Prepare a batch script backup.sh *Run backup.sh to create a backup version e.g. backup.sql *Copy backup.sql to Dropbox folder *Schedule Ubuntu/Windows task to run backup.sh task e.g. every day at night Detail steps * *All about backing up and restoring an MySQL database can be found here. Back up to compressed file mysqldump -u [uname] -p [dbname] | gzip -9 > [backupfile.sql.gz] *How to remote from Windows to execute the 'backup' command can be found here. plink.exe -ssh -pw -i "Path\to\private-key\key.ppk" -noagent username@server-ip *How to bring the file to Dropbox can be found here Create a app https://www2.dropbox.com/developers/apps Add an app and choose Dropbox API App. Note the created app key and app secret Install Dropbox API in Ubuntu; use app key and app secret above $ wget https://raw.github.com/andreafabrizi/Dropbox-Uploader/master/dropbox_uploader.sh $ chmod +x dropbox_uploader.sh Follow the instruction to authorize access for the app e.g. http://www2.dropbox.com/1/oauth/authorize?oauth_token=XXXXXXX Test the app if it is working right - should be ok $ ./dropbox_uploader.sh info The app is created and a folder associating with it is YourDropbox\Apps\<app name> Commands to use List files $ ./dropbox_uploader.sh list Upload file $ ./dropbox_uploader.sh upload <filename> <dropbox location> e.g. $ ./dropbox_uploader.sh upload backup.sql . This will store file backup.sql to YourDropbox\Apps\<app name>\backup.sql Done *How to schedule a Ubuntu can be view here using crontab Call command sudo crontab -e Insert a line to run backup.sh script everyday as below 0 0 * * * /home/userName/pathTo/backup.sh Explaination: minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday), command Or simply we can use @daily /home/userName/pathTo/backup.sh Note: * *To mornitor crontab tasks, here is a very good guide.
{ "language": "en", "url": "https://stackoverflow.com/questions/25961016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can i modulo a big integer value #include <string> #include <iostream> using namespace std; #include "md5.h" int main() { MD5 md5; string message = "secretU"; char arr[message.size()]; strcpy(arr, message.c_str()); //encrypting the message "secretU", it will return a string of hexadecimals string result = md5.digestString(arr); //print the result of the encrypted message. cout << result; return 0; } Result of the output in hexadecimals 1853c517b0e1095a341210f1a4b422e6 Once i tried to convert to Decimal, it needs 125 bit size? However, unsigned long long can only contain up to 64 bits, is there a way to store this long integer so that i can modulo it with the value i want? Convert hexadecimals to decimal 32336430049777443053240099092194140902 A: You can do it by hand or use a library that provides big integers like https://mattmccutchen.net/bigint/ A: Take the modulo by breaking them into pieces.. say for example you want to take modulo of 37^11 mod 77 in which 37^11 gives answer 1.77917621779460E17 so to get this .. take some small number in place of 11 which gives an integer value.. break it into pieces... 37^11 mod 77 can be written as (37^4 x 37^4 x 37^3 mod 77) so solve it as.. {(37^4 mod 77)(37^4 mod 77)(37^3 mod 77)} mod 77. So, in general xy mod n = {(x mod n)(y mod n)} mod n
{ "language": "en", "url": "https://stackoverflow.com/questions/47114016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jhipster - production build failure I cannot generate my JHipster application war by running mvnw -Pprod. Here's the error I get in a console: https://pastebin.com/3wLwy2x4 And my package.json dependencies: https://pastebin.com/txnATG6M The solution from: Webpack failure during JHipster Prod Package doesn't work for me, only the error changes to: [INFO] ERROR in ./src/main/webapp/app/app.main.ts [INFO] Module not found: Error: Can't resolve './app.module.ngfactory' in 'D:\Programy\Web\softdog2\src\main\webapp\app' [INFO] @ ./src/main/webapp/app/app.main.ts 2:0-62 [INFO] MergetJsonsWebpackPlugin emit starts... [INFO] MergetJsonsWebpackPlugin emit completed... [ERROR] error Command failed with exit code 2. [INFO] info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. [ERROR] error Command failed with exit code 1. [INFO] info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. [ERROR] error Command failed with exit code 1. [INFO] info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 01:48 min [INFO] Finished at: 2018-06-13T23:29:58+02:00 [INFO] Final Memory: 50M/532M Also, I get following warnings from yarn: [ERROR] warning " > [email protected]" has incorrect peer dependency "@angular/core@^4.0.0". [ERROR] warning " > [email protected]" has incorrect peer dependency "@angular/core@>=4.2.6 <5.0.0". [ERROR] warning " > [email protected]" has incorrect peer dependency "@angular/common@>=4.2.6 <5.0.0". [ERROR] warning " > [email protected]" has incorrect peer dependency "@angular/platform-browser@>=4.2.6 <5.0.0". [ERROR] warning " > [email protected]" has incorrect peer dependency "@angular/router@>=4.2.6 <5.0.0". A: The answer to this problem is to update Angular libraries versions (in my case from 5.1.0 to 5.1.1).
{ "language": "en", "url": "https://stackoverflow.com/questions/50846582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Image request from URL fails I have the following code: func getImage(urlString: String, completionHandler: UIImage -> Void) -> NSURLSessionTask { let request = NSMutableURLRequest(URL: NSURL(fileURLWithPath: urlString)!) println("Executing image request: \(urlString)") return session.dataTaskWithRequest(request) { data, response, error in if error != nil { println("\tGET request failed: \(error!)") } else { println("\tGET request succeeded!") let response = response as NSHTTPURLResponse if response.statusCode == 200 { let image = UIImage(data: data) dispatch_async(dispatch_get_main_queue()) { // dispatch naar main thread (main_queue is thread# van main thread van app) completionHandler(image!) } } } } } But when I execute it, I get the following output: Executing image request: http://i.imgur.com/rfw7jrU.gif GET request failed: Error Domain=NSURLErrorDomain Code=-1100 "The operation couldn’t be completed. (NSURLErrorDomain error -1100.)" UserInfo=0x14e9b200 {NSErrorFailingURLKey=file:///http:/i.imgur.com/rfw7jrU.gif, NSErrorFailingURLStringKey=file:///http:/i.imgur.com/rfw7jrU.gif, NSUnderlyingError=0x14d8d600 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1100.)"} I have no idea why this happens, as my nearly identical code that gets a .json file does work. I have tested this on both my device and the simulator. This fails on all urls, not only imgur links. It also crashes before I put it into a UIImage, so that is also not the problem. A: From the error message one can see that your URL is a file URL: file:///http:/i.imgur.com/rfw7jrU.gif and error -1100 is kCFURLErrorFileDoesNotExist (see CFNetwork Error Codes Reference). You should replace NSURL(fileURLWithPath: urlString) by NSURL(string: urlString) // Swift 3+: URL(string: urlString)
{ "language": "en", "url": "https://stackoverflow.com/questions/27003861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to fix update error i want to update all row's alternativegroups with $id value. the action getting error: coldchain can not be null. when i search the db for pk = $a, It's coldchain value is boolen(false). and db is postgresql how can i set $q->attributes without posting other values? public function actionUpdate($id){ if (isset($_POST['forms'])){ $arr = explode(',', $_POST['forms']); foreach ($arr as $a){ $q = MedicineDrugform::model()->findbypk($a); $q->alternativegroup = $id; if ($q->save()){ echo $q->id."q saved <br />"; } else { echo "<pre>"; print_r($q->getErrors()); } die(); $qu = MedicineDrugformUpdate::model()->findbyattributes(array('drug_form_id'=>$a)); $quu = MedicineDrugformUpdate::model()->findbypk($qu->id); $quu->alternativegroup = $id; if ($quu->save()){ echo $quu->id."qu saved <br />"; } } die(); $this->render('/site/messages', array('message'=>'formsaved')); } $this->render('add', array('id'=>$id)); } A: maybe it cant find the corresponding record for $q = MedicineDrugform::model()->findbypk($a);
{ "language": "en", "url": "https://stackoverflow.com/questions/14381732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .Net MVC4 updating database I am struggling to update a database. All i need to do is update a column called balance In my controller i have this public void updateBalance(int account, double amount) { var accounnt = db.Accounts.FirstOrDefault(u => u.AccountNumber == account); if (accounnt == null) { } else { // update the balance column in account table } } can some one please assist? A: Once you have loaded your entity, you simply need to update its properties and call SaveChanges on your DbContext. if (accounnt == null) { } else { account.balance = 1000; } db.SaveChanges();
{ "language": "en", "url": "https://stackoverflow.com/questions/19027575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Render Flash (SWF) frame as image (PDF,PNG,JPG) I would like to write a python script that takes a bunch of swf files and renders them to individual image files. Each swf file has just one frame (text, pictures etc.) and no animations at all. I have already tried the render command from the swftools toolset (The windows version), but the resolution of the resulting image is too low. So what I need is: A command line tool (Windows/Linux) or a python library which renders one frame from a swf to a bitmap or better to something like a PDF (It would be cool if the text data could be retained). It would be great if the target resolution/size could be set manually. Thanks in advance! A: Sometimes SWFRender is stuck at very heavy files, especially when producing 300dpi+ images. In this case Gnash may help: gnash -s<scale-image-factor> --screenshot last --screenshot-file output.png -1 -r1 input.swf here we dump a last frame of a movie to file output.png disabling sound processing and exiting after the frame is rendered. Also we can specify the scale factor here or use -j width -k height to specify the exact size of resulting image. A: You could for example build an AIR app that loads each SWF, takes the screenshot and writes it to a file. The thing is you'll need to kick off something to do the render and, as far as i know, you can't do that without the player or some of its Open Source implementation. I think your best bet is going AIR, the SDK is free and cross-platform. If you are used to python, the AS3 necessary should be easy enough to pick up. HTH, J A: I'm sorry to answer my own question, but I found an undocumented feature of swfrender (part of the swftools) by browsing through the sources. swfrender path/to/my.swf -X<width of output> -Y<height of output> -o<filename of output png> As you might have guessed the X option lets you determine the width (in pixels) of the output and Y does the same for the height. If you just set one parameter, then the other one is chosen in relation to the original height-width-ratio (pretty useful) That does the trick for me but as Zarate offered a solution that might be even better (I'm thinking of swf to PDF conversion) he deserves the credits. Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/2988823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: sum of table with join on joined table gives wrong total I have three tables: * *users_timings_log *projects_tasks *projects_modules I want to calculate the total hours spent on a task with module_ id 2 for example I use the following query for it: SELECT SEC_TO_TIME(SUM(TIMESTAMPDIFF(SECOND, `start_date`, `end_date`))) AS `total_hours` FROM `users_timings_log` INNER JOIN `projects_tasks` ON users_timings_log.type_id = projects_tasks.id LEFT JOIN `projects_modules` ON projects_tasks.module_id = '2' WHERE `type` = '0' This is the structure of my users_timings_log table +-------+---------------------+---------------------+------+---------+ | ID | start_date | end_date | type | type_id | +-------+---------------------+---------------------+------+---------+ | 1 | 2015-09-17 09:00:00 | 2015-09-17 19:00:00 | 1 | 28 | | 2 | 2015-09-17 07:00:00 | 2015-09-17 12:00:00 | 1 | 24 | | 3 | 2015-09-17 08:00:00 | 2015-09-17 16:15:00 | 1 | 18 | | 4 | 2015-09-17 10:00:00 | 2015-09-17 17:00:00 | 1 | 24 | +-------+---------------------+---------------------+------+---------+ Here's the structure of my projects_tasks table +-------+---------------+-----------------------------+-----------+ | ID | name | description | module_id | +-------+---------------+-----------------------------+-----------+ | 18 | First task | Some useless description | 1 | | 24 | Second task | Another useless description | 2 | | 28 | Third task | NULL | 3 | +-------+---------------+-----------------------------+-----------+ Structure of projects_modules table +-------+---------------+ | ID | name | +-------+---------------+ | 1 | Module 1 | | 2 | Module 2 | | 3 | Module 3 | +-------+---------------+ What I need is the total of hours of a specific module, but for some reason It is giving me for each module the same amount of time. I'm stuck on it. What am I doing wrong? Thanks in advance A: You need a GROUP BY and proper JOIN: SELECT pt.module_id, SEC_TO_TIME(SUM(TIMESTAMPDIFF(SECOND, ul.`start_date`, ul.`end_date`))) AS `total_hours` FROM `users_timings_log` ul INNER JOIN `projects_tasks` pt ON ul.type_id = pt.id WHERE `type` = '0' GROUP BY pt.module_id; If you only want one module, then add a WHERE clause for that purpose. I also added table aliases, so the query is easier to write and to read. I should add, the problem with your query is that it did not have proper JOIN conditions for projects_modules. You don't seem to need that table, so removing the table is fine. If you need columns from that table, add the appropriate JOIN conditions.
{ "language": "en", "url": "https://stackoverflow.com/questions/32949015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: With a user specified by IP address, why I can't connect to mysql server remotely? I am trying to set mysql server on an office computer to allow only for my computer at home to be able to connect to the mysql server. I created a user on the mysql server. The user is specified by IP address(XXX.XXX.XXX.XXX) of my home computer. Login name: myname Limit to Hosts Matching: XXX.XXX.XXX.XXX and also, in Administrative Roles tab, I added DBManager to this user. and then, I tested this connection from my home computer using mysql workbench, and I got this error: Failed to Connect to MySQL at ---.---.---.---:3306 with user myname Host '???-???-???-???-???.abc.defg.hi.jk' is not allowed to connect to this MySQL server ---.---.---.---: IP address of the computer that has mysql server. ???-???-???-???-???.abc.defg.hi.jk: I am not sure about this. Looks like some gate way name.
{ "language": "en", "url": "https://stackoverflow.com/questions/63517968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JMeter Network distribution in load testing How can i distribute networks while load testing in JMeter? Suppose my load test is of 1 hr. and i have 100 users. I want to distribute network like- 20% users - 2G speed 40% users - 3G speed rest - 4G speed. OR, other scenario like throughout the whole test of 1hr. 20% traffic will on 2G speed, 40% traffic on 3G and rest on 4G speed. Can anyone tell me that how to mimic this network behavior in JMeter? A: * *You will need to kick off 3 JMeter instances in Distributed Mode *For 1st JMeter instance add the next lines to user.properties file to mimic 2G network: httpclient.socket.http.cps=6400 httpclient.socket.https.cps=6400 *For 2nd JMeter instance add the next lines to user.properties file to mimic 3G network httpclient.socket.http.cps=2688000 httpclient.socket.https.cps=2688000 *For 3rd JMeter instance add the next lines to user.properties file to mimic 4G network: httpclient.socket.http.cps=19200000 httpclient.socket.https.cps=19200000 More information: How to Simulate Different Network Speeds in Your JMeter Load Test
{ "language": "en", "url": "https://stackoverflow.com/questions/48982829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: URL rewrite in IIS6 - Third party tools I have collected the following api/sdk/whatever which provide modules for doing url rewriting in IIS 5/6/7. Some are free-open source and some require $. I haven't tried any of them. I would like to know if anyone is currently using or used or have any kind of experience with these tools (website listed). UrlRewritingNet.UrlRewrite - http://www.urlrewriting.net/159/en/downloads.html IIS Mod-Rewrite Pro ($) -http://www.iis.net/downloads/default.aspx?tabid=34&g=6&i=1469 Open Source - http://urlrewriter.net/ Helicon Tech (Full $)- http://www.isapirewrite.com/ ISAPI_ Rewrite 3.0 ($) - http://www.seoconsultants.com/windows/isapi/3/ Open Source Ionics Isapi Rewrite Filter - http://iirf.codeplex.com/ Any help would be greatly appreciated. Thanks. Murali A: I have personal experience with IIRF from the codeplex site, and I liked it and found it good. A: I use UrlRewrite from UrlRewriting.Net Very easy to use for the simple thing I'm doing: send .pdf requests to an aspx page to generate the pdf.
{ "language": "en", "url": "https://stackoverflow.com/questions/1765988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: googleVis datatype conversion in R does not seems to work I have been working with 'googleVis' and R in order to produce a Line chart using Google charts APIs. On Google API's tutorial I found that data conversion in Javascript is used to determine if the axes will be "continuous"(using Numeric Javascript type) and "discrete" (using String). I believe with googleVis is the same, since datatypes are derived from R. Problem is, in the following example (which I modified after taking it from the R demo function), the X axis values are equally spaced (hence, still discrete), despite they seem to be "Numeric" library(googleVis) df=data.frame(val1=c(10,13,100), val2=c(23,12,32)) Line <- gvisLineChart(df) plot(Line) Could someone please me help to understand this? Thank you very much! A: Full disclosure: I love the googleVis package. I see the same behavior you do, even after updating to the latest version of googleVis (not yet on CRAN). I don't know if this is a bug or not; the googleVis documentation for gvisLineChart mentions continuous data, but nothing I tried allows me to plot the X axis as numerical. You can get clues as to what's happening when you change aspects of your code in generating googleVis charts and graphs if you right-click on the web page that gets displayed with the plot, and choose "View Page Source." This page is where the magic happens, and is the HTML output from the googleVis package. The problematic line in this case is the one that reads "data.addColumn('string','val1'); In this line, the word 'string' should be 'number', and the val1 values should not be in quotes in the data section. You can get the results you want, though, by using gvisScatterChart instead: library(googleVis) df=data.frame(val1=c(10,13,100), val2=c(23,12,32)) Line <- gvisScatterChart(df, options=list(lineWidth=2, pointSize=0)) plot(Line)
{ "language": "en", "url": "https://stackoverflow.com/questions/15392774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android NetworkOnMainThreadException when calling Url.OpenStream I get this exception when running my code on emulator (Android 4.0.3 / API 15). While opening a stream it will throw an exception. Error-message is null. try { String adress = "xxx"; URL url = new URL(adress); InputSource source = new InputSource(url.openStream()); } catch (Exception e) { (new TextView).setText("Error: "+e.getMessage()); } URL is still working with the emulator (in browser). I have cleaned the project. Also Internet connection is allowed: <uses-permission android:name="android.permission.INTERNET" /> Exception : android.os.NetworkOnMainThreadException A: Please never run a networking operation on the main (UI) thread . Main thread is used to: * *interact with user. *render UI components. any long operation on it may risk your app to be closed with ANR message. Take a look at the following : * *Keeping your application Responsive *NetworkOnMainThreadException you can easily use an AsyncTask or a Thread to perform your network operations. Here is a great tutorial about threads and background work in android: Link A: Works for me: Manifest.xml: <uses-permission android:name="android.permission.INTERNET" /> .java: private static boolean DEVELOPER_MODE = true; ... protected void onCreate(Bundle savedInstanceState) { if (DEVELOPER_MODE) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()); } ... hope it helps. see also : http://developer.android.com/reference/android/os/StrictMode.html
{ "language": "en", "url": "https://stackoverflow.com/questions/15685153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reply Kafka Template - Exception handling I am using ReplyingKafkaTemplate to establish a synchronous call between two microservices. The receiver of the event is annotated with SendTo as below: @KafkaListener(topics = "${kafka.topic.prefix}" + "${kafka.topic.name}", containerFactory = "customEventKafkaListenerFactory") @SendTo public CustomResponseEvent onMessage( @Payload @Valid CustomRequestEvent event, @Header(KafkaHeaders.CORRELATION_ID) String correlationId, @Header(KafkaHeaders.REPLY_TOPIC) String replyTopic) { //Making some REST API calls to another external system here using RestTemplate } The REST API call can throw a 4xx or 5xx. There are multiple such calls, some to internal systems, and some to external systems. It may be a bad design, but let's not get into that. I would like to have a global exception handler for the RestTemplate where I can catch all the exceptions, and then return a response to the original sender of the event. I am using the same replyTopic and correlationId as received in the consumer to publish the event. But still the receiver of the response throws No pending reply exception. * *Whatever approach I have above, is it possible to achieve such a central error response event publisher? *Is there any other alternative that is best suited for this exception handling? A: The @KafkaListener comes with the: /** * Set an {@link org.springframework.kafka.listener.KafkaListenerErrorHandler} bean * name to invoke if the listener method throws an exception. * @return the error handler. * @since 1.3 */ String errorHandler() default ""; That one is used to catch and process all the downstream exceptions and if it returns a result, it is sent back to the replyTopic: public void onMessage(ConsumerRecord<K, V> record, Acknowledgment acknowledgment, Consumer<?, ?> consumer) { Message<?> message = toMessagingMessage(record, acknowledgment, consumer); logger.debug(() -> "Processing [" + message + "]"); try { Object result = invokeHandler(record, acknowledgment, message, consumer); if (result != null) { handleResult(result, record, message); } } catch (ListenerExecutionFailedException e) { // NOSONAR ex flow control if (this.errorHandler != null) { try { Object result = this.errorHandler.handleError(message, e, consumer); if (result != null) { handleResult(result, record, message); } } catch (Exception ex) { throw new ListenerExecutionFailedException(createMessagingErrorMessage(// NOSONAR stack trace loss "Listener error handler threw an exception for the incoming message", message.getPayload()), ex); } } else { throw e; } } See RecordMessagingMessageListenerAdapter source code for more info.
{ "language": "en", "url": "https://stackoverflow.com/questions/57791556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL Auto increment skipping number which is deleted I want to generate Bill No From mySQL Auto Increment. I have column ID (Primary Key & Auto Increment). Now From This column ID I am generating Bill No As requested by user. Problem is If I delete some record in between then It should not skip the deleted ID when new record gets entered. e.g. 1001,1002,1003,1004 etc In this if I delete record Id 1002 & next time If I enter any new record then How can I assign 1002 back to the new record. A: It should not skip the deleted ID when new record gets entered Yes it should. You're just relying on the system to do something that it was never designed to do and never claimed to do. AUTOINCREMENT is not designed to generate your "Bill No". It's designed to generate an ever-incrementing identifier and guarantee uniqueness by never re-using a value. And it's doing exactly that. You can manually generate your "Bill No" using whatever logic you like and store it in another column. It would be strange to re-use values though. Imagine if you issue a bill to someone, later delete the record, and then issue another bill to someone else with the same number. Uniqueness is important with identifiers. A: From a financial control point of view being able to delete and reuse invoice numbers damages your audit trail and leaves you open to risk. Also from a database integrity point of view, reusing primary keys is not allowed as it would lead to unexpected results,such as records in other tables appearing wrongly in a join. There are consequences to naturalising your primary keys (excellent discussion of natural and surrogate primary keys). The database is protecting its referential integrity by not allowing the reuse of the primary key. Indeed, as @David says in his response, part of the function of autoincrement on a primary key is to maintain the uniqueness of the key. Now to solutions, from a financial aspect invoices should never be deleted so there is an audit trail, an incorrect invoice should have a contra through a credit note. On the database side if you must 'delete' a record and reuse the invoice number, I would suggest having a different field for the invoice number, not actually deleting, but using a field to flag active or deleted, and maintaining a separate incrementing invoice number. Although not advised, this will at least help maintain the integrity of your records.
{ "language": "en", "url": "https://stackoverflow.com/questions/45711993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Which credentials and tooling do I use to authenticate to the HERE geofencing/fleet APIs? I have been trying to apply some geofencing to my Here map, but continually get 401 and 403 responses from the geofencing endpoints no matter what I do. I was originally using the node module '@here/maps-api-for-javascript' but I saw indicators that it was not possible to do geofencing with that tool, and so I have switched to pulling down scripts (v3.1) from CDN and making direct REST calls to fill in any gaps as outlined in this SO post, I have created a test project using the exact code provided at that SO post with my api key, and the map does not render at all, let alone the geofencing (but the triangle and marker are rendered). In the console I see 403s for all calls to the APIs. I have tried: * *JS API key from developer account *REST API key from developer account *platform API key from platform account *oauth API token from platform account *app_id and app_code params with my JS app id and JS API key *app_id and app_code params with my REST app id and REST app key My keys work to render my map, calculate routes, and update routehandles in my app, so I'm not sure why they are not working for these two calls - one to upload the fences, and one to check position against them. Additionally in my app I had tried to do geofencing as outlined in this tutorial from here but when I try to access the platform.ext.getGeoFencingService (line 163 in view source at that link) I get an error that platform.ext is undefined. Adding to my confusion, one part of the docs says that apikeys are read only, and another part of the docs says that starting with JS api v3.1 that you no longer need app_id and app_code.
{ "language": "en", "url": "https://stackoverflow.com/questions/69124772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to position a view in Android constraint layout outside the screen at the beginning I have a View in a Constraint Layout and I would like that at the very beginning it should be outside of the screen (and then later slowly move into the scree from right to left). Now, I kind of need something like negative bias or margins. I had a look at this question How to achieve overlap/negative margin on Constraint Layout?. The accepted answer using android:layout_marginTop="-25dp" does not have any effect (altough the top of the view is constrained and I use"androidx.constraintlayout:constraintlayout:2.1.3"). I tried the second most upvoted answer and used the code: view.setTranslationX(view.getWidth() - 20); This actually works. However, the problem is that when the Fragment is created you first see that the view is not on the left for a short period of time. This is not what I want. I would like to have the view beyond the right rim of the layout at the very very beginning such that it can later move into the layout. Do you have any idea how I can do that? Ideally I would like to do this programmatically. Update: Here is the code of the XML layout where a negative margin does not have any effect: <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/game_test_background" tools:context=".MainActivity" android:id="@+id/constraintLayout"> <ImageView android:id="@+id/imageView_RedRectange_Test" android:layout_width="0dp" android:layout_height="30dp" android:layout_marginTop="-1250dp" app:layout_constraintWidth_percent="0.25" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="1.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.048" app:srcCompat="@drawable/red_rectangle" /> <Button android:id="@+id/button" android:layout_width="0dp" android:layout_height="0dp" android:text="Button" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHeight_percent="0.102" app:layout_constraintHorizontal_bias="0.373" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.745" app:layout_constraintWidth_percent="0.12" /> </androidx.constraintlayout.widget.ConstraintLayout> A: Okay so to have a negative margin you can use translateX, translateY or TranslationZ. in xml like so: <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello World!" android:translationX="-60dp" android:translationY="-90dp" android:translationZ="-420dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> or programmatically like so: View view = ...; view.setTranslationX(-60); view.setTranslationY(-90); view.setTranslationZ(-420); Then in order to slowly bring it in from right to left you can use the animate() method like so: View view = ...; view.animate().setDuration(1000).translationX(-600).start(); A: There is a problem with setting the width of the button using app:layout_constraintWidth_percent when the ImageView has a negative margin. The problem should go away if you can set a definite width to the button (instead of 0dp). The problem should also resolve if you set app:layout_constraintWidth_percent to a value such that the text of the button shows completely on one line. Here is a simplified layout to demonstrate this issue. The ConstraintLayout has two views that are simply constrained to the parent to appear in vertical center of the layout. These two views have no dependencies on each other. In addition, the ImageView has a top margin of -250dp, so it should appear above the layout's vertical center. <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/holo_green_light"> <ImageView android:id="@+id/redRectangle" android:layout_width="100dp" android:layout_height="30dp" android:layout_marginTop="-250dp" android:layout_marginEnd="16dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="@drawable/red_rectangle" /> <Button android:id="@+id/button" android:layout_width="0dp" android:layout_height="wrap_content" android:text="Button" android:textSize="18sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintWidth_default="percent" app:layout_constraintWidth_percent="0.12" /> </androidx.constraintlayout.widget.ConstraintLayout> Here is what happens then the width of the ImageView is changed from 0dp to a non-zero value of 1dp. When the width is set to 0dp, the negative margin seems to be ignored. It is only when the width is set to a non-zero value that the ImageView is correctly placed. Changing the width of the button should have no effect on the placement of the ImageView; however, the button only appears in the proper position when the button has a non-zero width. Here is what happens when the app:layout_constraintWidth_percent is increased so that the word "Button" is not cutoff. Again, the placement of the ImageView should be independent of the width of the button. Instead, the button only appears in the correct position when the app:layout_constraintWidth_percent is set such that the word "Button" is not cutoff. This is only an issue with negative margins. Positive margins work as expected. This is a strange problem, so you may want to use one of the other solutions mentioned. (ConstraintLayout version 2.1.3)
{ "language": "en", "url": "https://stackoverflow.com/questions/71241995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Layout PrimeFaces I have a layout file as follows <p:layout fullPage="true"> <p:layoutUnit position="center"> <p:layoutUnit position="north"> <ui:insert name="Middle top"> <h3>This is a Center</h3> </ui:insert> </p:layoutUnit> <p:layoutUnit position="center"> <ui:insert name="Middle center"> <h3>This is a Center</h3> </ui:insert> </p:layoutUnit> </p:layoutUnit> </p:layout> But when I run the layout file, nothing is displayed! I use primefaces 3.5, jsf 2.1. A: Except center layoutUnit, other layout units must have dimensions defined via size option. Like this: <p:layout fullPage="true"> <p:layoutUnit position="north" size="50"> <h:outputText value="Top content." /> </p:layoutUnit> <p:layoutUnit position="south" size="100"> <h:outputText value="Bottom content." /> </p:layoutUnit> <p:layoutUnit position="west" size="300"> <h:outputText value="Left content" /> </p:layoutUnit> <p:layoutUnit position="east" size="200"> <h:outputText value="Right Content" /> </p:layoutUnit> <p:layoutUnit position="center"> <h:outputText value="Center Content" /> </p:layoutUnit> </p:layout> A: If you are going with a layout concept in your project, it should handle like this. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui" xmlns:f="http://java.sun.com/jsf/core"> <f:view contentType="text/html" id="fview"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <f:metadata> <ui:insert name="metadata" /> </f:metadata> <meta name="selectedLanguage" content="Lang" lang="#{menuBean.selectedLanguage}"/> <h:head> </head> <h:body behavior: url(PIE/PIE.htc);"> <p:layout fullPage="true" widgetVar="layoutWdgtMain"> <p:layoutUnit id="north" position="north" cellpadding="0" cellspacing="0"> //enter your code </p:layoutUnit> <p:layoutUnit id="east" position="east" cellpadding="0" cellspacing="0"> //enter your code </p:layoutUnit> <p:layoutUnit id="west" position="west" cellpadding="0" cellspacing="0"> //enter your code </p:layoutUnit> <p:layoutUnit id="south" position="south" cellpadding="0" cellspacing="0"> //enter your code </p:layoutUnit> </p:layout> </h:body> </f:view> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/17666949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to generate HTML code using Javascript and JSON? I need to create a quiz by parsing a JSON file. The checked answers must be stored in the local storage. The JSON code: { "quiz": { "q1": { "question": "Which one is correct team name in NBA?", "options": [ "New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket" ], "answer": "Huston Rocket" }, "q2": { "question": "'Namaste' is a traditional greeting in which Asian language?", "options": [ "Hindi", "Mandarin", "Nepalese", "Thai" ], "answer": "Hindi" }, "q3": { "question": "The Spree river flows through which major European capital city?", "options": [ "Berlin", "Paris", "Rome", "London" ], "answer": "Berlin" }, "q4": { "question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": [ "Pablo Picasso", "Vincent van Gogh", "Salvador Dalí", "Edgar Degas" ], "answer": "Pablo Picasso" } } } The code is below: <div id="container"></div> <input type ="submit" name ="submit" value = "Submit answers" onclick = "results()"> <script> let data = {"quiz": {"q1": {"question": "Which one is correct team name in NBA?", "options": ["New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket"], "answer": "Huston Rocket"}, "q2": {"question": "'Namaste' is a traditional greeting in which Asian language?", "options": ["Hindi", "Mandarin", "Nepalese", "Thai"], "answer": "Hindi"}, "q3": {"question": "The Spree river flows through which major European capital city?", "options": ["Berlin", "Paris", "Rome", "London"], "answer": "Berlin"}, "q4": {"question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": ["Pablo Picasso", "Vincent van Gogh", "Salvador Daly", "Edgar Degas"], "answer": "Pablo Picasso"}}}; let list = document.createElement("ul"); for (let questionId in data["quiz"]) { let item = document.createElement("node"); let question = document.createElement("strong"); question.innerHTML = questionId + ": " + data["quiz"][questionId]["question"]; item.appendChild(question); list.appendChild(item); let sublist = document.createElement("ul"); item.appendChild(sublist); for (let option of data["quiz"][questionId]["options"]) { item = document.createElement("input"); item.type = "radio"; item.name = data["quiz"][questionId]; var label = document.createElement("label"); label.htmlFor = "options"; label.appendChild(document.createTextNode(data["quiz"][questionId]["options"])); var br = document.createElement('br'); sublist.appendChild(item); document.getElementById("container").appendChild(label); document.getElementById("container").appendChild(br); } } document.getElementById("container").appendChild(list); function results () { var score = 0; if (data["quiz"][questionId]["answer"].checked) { score++; } } localStorage.setItem("answers","score"); </script> I should get this: enter image description here Instead I got this, no matter how many times I rewrite the code: enter image description here Whay am I doing wrong? Thank you very much for your help, Mary. A: You have a small error with document.createElement("node") - there is no tag node so appending other elements to that is also incorrect. The code could be simplified though as below ( the add to local storage will throw an error in the snippet though ) let data = { "quiz": { "q1": { "question": "Which one is correct team name in NBA?", "options": ["New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket"], "answer": "Huston Rocket" }, "q2": { "question": "'Namaste' is a traditional greeting in which Asian language?", "options": ["Hindi", "Mandarin", "Nepalese", "Thai"], "answer": "Hindi" }, "q3": { "question": "The Spree river flows through which major European capital city?", "options": ["Berlin", "Paris", "Rome", "London"], "answer": "Berlin" }, "q4": { "question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": ["Pablo Picasso", "Vincent van Gogh", "Salvador Daly", "Edgar Degas"], "answer": "Pablo Picasso" } } }; // utility prototype to shuffle an array Array.prototype.shuffle=()=>{ let i = this.length; while (i > 0) { let n = Math.floor(Math.random() * i); i--; let t = this[i]; this[i] = this[n]; this[n] = t; } return this; }; let list = document.createElement("ul"); Object.keys(data.quiz).forEach((q, index) => { // the individual record let obj = data.quiz[q]; // add the `li` item & set the question number as data-attribute let question = document.createElement("li"); question.textContent = obj.question; question.dataset.question = index + 1; question.id = q; // randomise the answers obj.options.shuffle(); // Process all the answers - add new radio & label Object.keys(obj.options).forEach(key => { let option = obj.options[key]; let label = document.createElement('label'); label.dataset.text = option; let cbox = document.createElement('input'); cbox.type = 'radio'; cbox.name = q; cbox.value = option; // add the new items label.appendChild(cbox); question.appendChild(label); }); // add the question list.appendChild(question); }); // add the list to the DOM document.getElementById('container').appendChild(list); // Process the checked radio buttons to determine score. document.querySelector('input[type="button"]').addEventListener('click', e => { let score = 0; let keys = Object.keys(data.quiz); document.querySelectorAll('[type="radio"]:checked').forEach((radio, index) => { if( radio.value === data.quiz[ keys[index] ].answer ) score++; }); console.log('%d/%d', score, keys.length); localStorage.setItem("answers", score); }) #container>ul>li { font-weight: bold } #container>ul>li>label { display: block; padding: 0.1rem; font-weight: normal; } #container>ul>li>label:after { content: attr(data-text); } #container>ul>li:before { content: 'Question 'attr(data-question)': '; color: blue } <div id="container"></div> <input type="button" value="Submit answers" /> A: You need to make minor changes to your nest loop so that the option labels are inserted in the correct location. See the code snippet where it is marked "remove" and "add" for the changes you need to make. As @ProfessorAbronsius noted, there isn't an html tag called "node", though that won't stop your code from working. let data = {"quiz": {"q1": {"question": "Which one is correct team name in NBA?", "options": ["New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket"], "answer": "Huston Rocket"}, "q2": {"question": "'Namaste' is a traditional greeting in which Asian language?", "options": ["Hindi", "Mandarin", "Nepalese", "Thai"], "answer": "Hindi"}, "q3": {"question": "The Spree river flows through which major European capital city?", "options": ["Berlin", "Paris", "Rome", "London"], "answer": "Berlin"}, "q4": {"question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": ["Pablo Picasso", "Vincent van Gogh", "Salvador Daly", "Edgar Degas"], "answer": "Pablo Picasso"}}}; let list = document.createElement("ul"); for (let questionId in data["quiz"]) { let item = document.createElement("node"); let question = document.createElement("strong"); question.innerHTML = questionId + ": " + data["quiz"][questionId]["question"]; item.appendChild(question); list.appendChild(item); let sublist = document.createElement("ul"); item.appendChild(sublist); // The problem is here in this nested loop for (let option of data["quiz"][questionId]["options"]) { item = document.createElement("input"); item.type = "radio"; item.name = data["quiz"][questionId]; var label = document.createElement("label"); label.htmlFor = "options"; // remove 1 // label.appendChild(document.createTextNode(data["quiz"][questionId]["options"])); // add 1 label.appendChild(document.createTextNode(option)); var br = document.createElement('br'); sublist.appendChild(item); // remove 2 //document.getElementById("container").appendChild(label); //document.getElementById("container").appendChild(br); // add 2 sublist.appendChild(label); sublist.appendChild(br); } } document.getElementById("container").appendChild(list); function results() { var score = 0; if (data["quiz"][questionId]["answer"].checked) { score++; } } // Removed because snippets don't allow localStorage // localStorage.setItem("answers", "score"); <div id="container"></div> <input type="submit" name="submit" value="Submit answers" onclick="results()"> A: Here's the answer to your question. Please let me know if you have any issues. <div id="container"></div> <input type="submit" name="submit" value="Submit answers" onclick="results()"> <script> let data = { "quiz": { "q1": { "question": "Which one is correct team name in NBA?", "options": ["New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket"], "answer": "Huston Rocket" }, "q2": { "question": "'Namaste' is a traditional greeting in which Asian language?", "options": ["Hindi", "Mandarin", "Nepalese", "Thai"], "answer": "Hindi" }, "q3": { "question": "The Spree river flows through which major European capital city?", "options": ["Berlin", "Paris", "Rome", "London"], "answer": "Berlin" }, "q4": { "question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": ["Pablo Picasso", "Vincent van Gogh", "Salvador Daly", "Edgar Degas"], "answer": "Pablo Picasso" } } }; data = data.quiz; let list = document.createElement("ul"); for (let questionId in data) { let item = document.createElement("node"); let question = document.createElement("strong"); let i = Object.keys(data).indexOf(questionId) + 1; question.innerHTML = "Question" + i + ": " + questionId["question"]; item.appendChild(question); list.appendChild(item); let sublist = document.createElement("ul"); item.appendChild(sublist); for (let option of data[questionId]["options"]) { item = document.createElement("input"); item.type = "radio"; item.name = questionId; var label = document.createElement("label"); label.htmlFor = option; label.appendChild(document.createTextNode(option)); var br = document.createElement('br'); sublist.appendChild(item); sublist.appendChild(label); sublist.appendChild(br); } } document.getElementById("container").appendChild(list); function results() { var score = 0; if (data[questionId]["answer"].checked) { score++; } } //localStorage.setItem("answers", "score"); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/74598312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Three.JS - AudioAnalyser() not working with audio source as Stream type in Safari I'm developing a streaming radio in 3D using Three.JS, I'm sending music as a PeerConnection to my clients attaching a THREE.AudioAnalyser() to display 3D bars that move according to frequencies. Sound is working great in all platforms, but THREE.AudioAnalyser() with an input source of stream type only works on Chrome, Safari is not working at all :frowning: var listener = new THREE.AudioListener(); var audio = new THREE.Audio( listener ); audio.setMediaStreamSource( stream ); audioAnalyser = new THREE.AudioAnalyser( audio, 128 ); function loop(){ console.log(audioAnalyser.getFrequencyData()); } The console.log() of the loop() function should contain an Array of Integers, on Chrome is all good, Safari logs [0,0,0,0,0,0,0,0] What could be causing this issue? It seems to work everywhere but not on Safari, and also it only seems to fail when the source is a stream. A: Not 100% sure, but you might want to connect the output of the AnalyserNode to the destination node. You may want to stick a GainNode with a gain of 0 in between, just in case you don't really want the audio from the AnalyserNode to be played out.
{ "language": "en", "url": "https://stackoverflow.com/questions/64019947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove unused source code files using eclipse/ Flash builder 4.6 i have a project having lots of file, around 4500 file in all Project. i separated it in 40 library project.Now my problem is that it taking too much time to Compile. so i increase a memory of Flash builder. This gives me little improvement to compile. i am sure that i have too much file which is not used in my project. so now i want to remove it by plug of Flash Builder / Eclipse. Because it is too much headache process to see that "xyz.as/mxml" file is used in any other file or if it is used in Other file say "abx.as/mxml" then again i have a question that "abx.as/mxml" is useful file or used in any other file. so you have any idea or hint please give me. Thanks in advance... A: One thing you can try is to use the size-report of your flex compilation : flex compiler options This way you will have an idea of which classes are really used in your libraries and therefore wich ones aren't because the flex compiler only link to classes you really need in your compiled swf. This not ideal but it can avoid a lot of manual process pain. A: Add this param to your compiler: -link-report output.xml this information will help you. A: I'm not sure if it would work for flash-builder, but for Java there is the UCDetector.
{ "language": "en", "url": "https://stackoverflow.com/questions/15087983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: 1d numpy array with enough elements not resizing as expected I just started working with numpy arrays in conjunction with panda dataframes, and I am working on a practice project, but have hit a bit of a problem. I have a panda dataframe which I pass the rows of to a function to do some work on it. The function takes in two different arrays one labeled best and worst and then creates a new vector to compare sums against. From there it will return either the current array that the pandas.apply has passed or it will return the new vector based on which sum() is the lowest. This creates a new python array which needs to be a matrix of 20x5 at the end. The function works fine, but the returned dataframe needs to be converted to a python array of size (20 x 5) for further work, which when np.array() is called, it converts it into an array of size (20,). I figured just using .reshape(20,5) would work since it has enough elements to work with, but it does not, it just fails on run. Any help is appreciated as I can't find anything that's helping me understand why this is happening. (the error, as many could guess by reading above, is: "cannot reshape array of size 20 into shape (20,5)" ) code except from my program that shows it (can run on it's own): import numpy as np import pandas as pd rng = np.random.default_rng(seed=22) df = pd.DataFrame(rng.random((20,5))) def new_vectors(current, best, worst): #convert current to numpy array current = current.to_numpy() #construct a new vector to check new = np.add(current, np.subtract((rng.random()*(np.subtract(best, np.absolute(current)))), ((rng.random()*(np.subtract(worst, np.absolute(current))))))) #get the new sum for the new and old vectors summed = current.sum() newsummed = new.sum() #return the smallest one return np.add(((newsummed < summed)*(new)), ((newsummed > summed)*(current))).flatten() z = np.array(df.apply(new_vectors, args=(df.iloc[0].to_numpy(), df.iloc[11].to_numpy()), axis=1)) z.reshape(20,5) #I know reshape() creates a copy, just here to show it doesn't work regardless A: You can do the reshape manually. * *Delete z.reshape(20,5). This is not going to work with an array of arrays. *After applying the function, use this instead: # Create a empty matrix with desired size matrix = np.zeros(shape=(20,5)) # Iterate over z and assign each array to a row in the numpy matrix. for i,arr in enumerate(z): matrix[i] = arr If you don't know the desired size for the matrix. Create the matrix as matrix = np.zeros(shape=df.shape). All the code used: import numpy as np import pandas as pd rng = np.random.default_rng(seed=22) df = pd.DataFrame(rng.random((20,5))) def new_vectors(current, best, worst): #convert current to numpy array current = current.to_numpy() #construct a new vector to check new = np.add(current, np.subtract((rng.random()*(np.subtract(best, np.absolute(current)))), ((rng.random()*(np.subtract(worst, np.absolute(current))))))) #get the new sum for the new and old vectors summed = current.sum() newsummed = new.sum() #return the smallest one return np.add(((newsummed < summed)*(new)), ((newsummed > summed)*(current))).flatten() z = np.array(df.apply(new_vectors, args=(df.iloc[0].to_numpy(), df.iloc[11].to_numpy()), axis=1)) matrix = np.zeros(shape=df.shape) for i,arr in enumerate(z): matrix[i] = arr A: Your original dataframe - with reduced length for display purposes: In [628]: df = pd.DataFrame(rng.random((4,5))) In [629]: df Out[629]: 0 1 2 3 4 0 0.891169 0.134904 0.515261 0.975586 0.150426 1 0.834185 0.671914 0.072134 0.170696 0.923737 2 0.065445 0.356001 0.034787 0.257711 0.213964 3 0.790341 0.080620 0.111369 0.542423 0.199517 The next frame: In [631]: df1=df.apply(new_vectors, args=(df.iloc[0].to_numpy(), df.iloc[3].to_numpy()), axis=1) In [632]: df1 Out[632]: 0 [0.891168725430691, 0.13490384333565053, 0.515... 1 [0.834184861872087, 0.6719141503303373, 0.0721... 2 [0.065444520313796, 0.35600115939269394, 0.034... 3 [0.7903408924058509, 0.08061955595765169, 0.11... dtype: object Note that it has 1 column, that contains arrays. Make an array from it: In [633]: df1.to_numpy() Out[633]: array([array([0.89116873, 0.13490384, 0.51526113, 0.97558562, 0.15042584]), array([0.83418486, 0.67191415, 0.07213404, 0.17069617, 0.92373724]), array([0.06544452, 0.35600116, 0.03478695, 0.25771129, 0.21396367]), array([0.79034089, 0.08061956, 0.1113691 , 0.54242262, 0.19951741])], dtype=object) That is (4,) object dtype. That dtype is important. Even though the elements all have 5 elements themselves, reshape does not work across that "object" boundary. We can't reshape it to (4,5). But we can concatenate those arrays: In [636]: np.vstack(df1.to_numpy()) Out[636]: array([[0.89116873, 0.13490384, 0.51526113, 0.97558562, 0.15042584], [0.83418486, 0.67191415, 0.07213404, 0.17069617, 0.92373724], [0.06544452, 0.35600116, 0.03478695, 0.25771129, 0.21396367], [0.79034089, 0.08061956, 0.1113691 , 0.54242262, 0.19951741]])
{ "language": "en", "url": "https://stackoverflow.com/questions/70160495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sort a string property that is in a List(of class) In my database project, the user should have a search function. The search results are saved in a List(of Class_Post). This list should now be sorted alphabetically. I would like to add that I could already have used: sorted.Sort(Function(x, y) x.compareto(y)) But the FxCopAnalyzer complained that the sorting could differ due to regional settings, so I now want to use String.Compare (x, y, StringComparison.Ordinal). The property to be sorted is Class_Post.Ueberschrift. The error is at line 11 (sorted.sort(comparison)): Overload resolution failed because no accessible "Sort" can be called with these arguments: "Public Overloads Sub Sort (comparer As IComparer (Of Class_Post))": "Option Strict On" does not allow implicit conversions from "Comparison (Of String)" to "IComparer (Of Class_Post)". Dim sorted As List(Of Class_Post) = Ergebnisse.ToList() Select Case Suchmoeglichkeit Case Sortiermoeglichkeiten.Alphabetisch ' alphabetical (a String) Dim comparison As Comparison(Of String) = Function(x, y) Dim rslt As Integer = x.Length.CompareTo(y.Length) Return rslt End Function sorted.Sort(comparison) Case Sortiermoeglichkeiten.Erstellzeit 'Creation Time (a Date) sorted.Sort(Function(x, y) x.Erstelldatum_dieses_Posts.CompareTo(y.Erstelldatum_dieses_Posts)) Case Else Exit Select End Select Return sorted A: You don't want a Comparison(Of String) but a Comparison(Of Class_Post) and you want to compare the Ueberschrift. Case Sortiermoeglichkeiten.Alphabetisch ' alphabetical (a String) Dim comparison As Comparison(Of Class_Post) = Function(x, y) Dim rslt As Integer = StringComparer.Ordinal.Compare(x.Ueberschrift, y.Ueberschrift) Return rslt End Function sorted.Sort(comparison) A ListOf(Of Class_Post) can just be sorted with a Comparison(Of Class_Post). Another approach which is easier to read and to maintain is LINQ: Select Case Suchmoeglichkeit Case Sortiermoeglichkeiten.Alphabetisch ' alphabetical (a String) Return Ergebnisse.OrderBy(Function(x) x.Ueberschrift).ToList() Case Sortiermoeglichkeiten.Erstellzeit 'Creation Time (a Date) Return Ergebnisse.OrderBy(Function(x) x.Erstelldatum_dieses_Posts).ToList() Case Else Exit Select End Select
{ "language": "en", "url": "https://stackoverflow.com/questions/67374564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Algorithm for Background subtraction I am trying to implement a simple background subtraction method for the detection of moving objects in a particular scene. The objective is to kind of segment out a particular motion out of a video to use it in another video. The algorithm i am following is: 1. Take the first 25frames from the video and average them to get a background model. 2. Find the standard deviation of those 25frames and store the values in another image. 3. Now i am calculating the absolute difference between each frame and average background model pixel wise. The output i am getting is kind of a transparent motion being highlighted in white (the absolute differencing is resulting in the transparency i think). I want to know whether my approach is right or not considering that i will be doing a segmentation upon this output as next step? And also i am getting no idea as to how to use the standard deviation image. Any help will be appreciated. Please let me know if this is not the type of question that i should post in stack overflow. In that case any reference or links to other sites will be helpful. A: You should take a look at that blog. http://mateuszstankiewicz.eu/?p=189 You will find a start of Answer. Moreover I think there is a specific module for video analysis in Opencv. A: You said it looks like transparent. This is what you saw right?→ See YouTube Video - Background Subtraction (approximate median) The reason is you use the median value of all frames to create the background. What you saw in white in your video is the difference of your foreground(average image) and your background. Actually, median filtered background subtraction method is simple, but it's not a robust method. You can try another background subtraction method like Gaussian Mixture Models(GMMs), Codebook, SOBS-Self-organization background subtraction and ViBe background subtraction method. See YouTube Video - Background Subtraction using Gaussian Mixture Models (GMMs) A: Try these papers: * *Improved adaptive Gaussian mixture model for background subtraction *Efficient Adaptive Density Estimapion per Image Pixel for the Task of Background Subtraction
{ "language": "en", "url": "https://stackoverflow.com/questions/17315981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Configure all Devise controllers to use a different layout? I have a Rails app which application layout is used to render an AngularJS app. However, I would like that all the Devise controllers use another layout. I don't need Angular in there. How can I tell Devise to use a different layout for all its controllers? A: You probably should review this entry: How To: Create custom layouts. More or less, you can set it via ApplicationController: class ApplicationController < ActionController::Base layout :layout_by_resource protected def layout_by_resource if devise_controller? "layout_name_for_devise" else "application" end end end Or via configuration (config/application.rb): config.to_prepare do Devise::SessionsController.layout "devise" Devise::RegistrationsController.layout proc{ |controller| user_signed_in? ? "application" : "devise" } Devise::ConfirmationsController.layout "devise" Devise::UnlocksController.layout "devise" Devise::PasswordsController.layout "devise" end
{ "language": "en", "url": "https://stackoverflow.com/questions/22943915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Image data transfer on drag and draw on canvas I am uploading an image from PC. Then I read the file with file reader and display image by creating an img tag. Then I drag the image from the img tag into the canvas and draw it onto canvas. I'm using dragstart and onDrop events. I use datatransfer.setdata() and datatransfer.getdata() for the functionality. But on drop, the image drawn on canvas is not as original. It is a zoomed version. I don't know why is this happening! Here is my code: <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Drag Demo</title> <link href="copy.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="container"> <div style = "border:2px solid black;"> <canvas id = "canvas" style = "position:relative;width:1000px;height:1000px;top:0px;left:200px; border:2px solid black;" ondrop="dropIt(event);" ondragover="event.preventDefault();"> </canvas> </div> <div> <input type="file" id="fileElem" accept="image/*" style="display:none" > <div id="fileSelect" class="drop-area">Select some files</div> </div> <div id="thumbnail"></div> </div> <script type="text/javascript"> function dragIt(event) { event.dataTransfer.setData("URL", event.target.id) }; function dropIt(event) { var theData = event.dataTransfer.getData("URL"); dt = document.getElementById(theData); alert(dt.width); alert(dt.height); event.preventDefault(); var c = document.getElementById("canvas"); var ctx = c.getContext('2d'); ctx.drawImage(dt, 0, 0); }; var count = 0; var fileSelect = document.getElementById("fileSelect"), fileElem = document.getElementById("fileElem"); fileElem.addEventListener("change",function(e){ var files = this.files handleFiles(files) },false) fileSelect.addEventListener("click", function (e) { fileElem.click(); e.preventDefault(); }, false); function handleFiles(files) { for (var i = 0; i < files.length; i++) { var file = files[i]; var imageType = /image.*/; if(!file.type.match(imageType)){ console.log("Not an Image"); continue; } var image = document.createElement("img"); var thumbnail = document.getElementById("thumbnail"); image.file = file; function handlefilereader(evt){ var target = evt.target || evt.srcElement; image.src = evt.target.result; } if(document.all) { image.src = document.getElementById('fileElem').value; } else { var reader = new FileReader() reader.onload = handlefilereader; reader.readAsDataURL(file); } image.id = count; count++; thumbnail.appendChild(image); alert(image.width); image.draggable = true; image.ondragstart = dragIt; } } </script> </body> </html> A: With canvas there are 2 'size' settings: Through CSS you'll set the DISPLAY size, so to set the PHYSICAL size of the canvas, you MUST use its attributes. So NO CSS/Style. Think about it this way: you create a IMAGE with physical size: (let's say) 400px*400px. Then just as a normal image (jpg,png,gif) that has a physical size, you can still choose to change the DISPLAYED size and thus aspect-ratio: like 800px*600px. Even % is normally supported. Hope this explains clearly WHY this happened and why your solution in your comment is also the correct solution!!
{ "language": "en", "url": "https://stackoverflow.com/questions/11578480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Argument 2 passed to Controller method must be in instance of Request, none given I'm trying to pass 2 dates from one view to another, in my controller, but I get the following error: Argument 2 passed to App\Http\Controllers\GuestController::reservationToGuest() must be an instance of Illuminate\Http\Request, none given This is my first view (the view having the date): <form action="{{ route('create_guest') }}"> {{ csrf_field() }} <input type="hidden" value="2016-08-26" name="dateOne"> <input type="hidden" value="2016-08-28" name="dateTwo"> <button class="btn btn-block btn-success">Proceed To Check In</button> </form> (dateOne and dateTwo are the dates which I want in the second view) routes.php Route::get('/guest_page/create/{idreservation?}',[ 'uses' => 'GuestController@reservationToGuest', 'as' => 'create_guest' ]); reservationToGuest in GuestController public function reservationToGuest($idreservation = null, Request $request){ if($idreservation === null){ return view('guest_page_create', ['idreservation' => 0, 'page_title' => 'Guest Check In', 'check_in_date' => $request['dateOne']]); } else{ //else clause works just fine and the dates from the database are inserted into the view $details = DB::table('reservation') ->where('idreservation', $idreservation) ->get(); return view('guest_page_create', ['idreservation' => $idreservation, 'details' => $details, 'page_title' => 'Guest Check In']); } } And in view 'guest_page_create' <label for="datemask">Check In Date</label> <input type="date" class="form-control" id="datemask" name="datemask" value="{{ $check_in_date }}"> A: You shouldn't pass optional parameters before required ones. Try this: public function reservationToGuest(Request $request, $idreservation = null) { // ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/39160398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: iOS 14 large titles not working properly when navigating between views Large titles disappear after navigating back and forth within the app. The large title is enabled but when navigating back, it becomes small again. This only happened when updating to iOS 14.
{ "language": "en", "url": "https://stackoverflow.com/questions/64000578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Controlled database insert I have created a script that uses PDO database functions to pull in data from an external feed and insert it into a database, which some days could amount to hundreds of entries.. the page hangs until it's done and there is no real control over it, if there is an error I don't know about it until the page has loaded. Is there a way to have a controlled insert, so that it will insert X amount, then pause a few seconds and then continue on until it is complete? During its insert it also executes other queries so it can get quite heavy. I'm not quite sure what I am looking so have struggled to find help on Google. A: I would recommend you to use background tasks for that. Pausing your PHP script will not help you in speeding up page loading. Apache (or nginx or any other web-server) sends whole HTTP packet back to browser only when PHP script is completed. You can use some functions related to output stream and if web-server supports chunked transfer then you can see progress while your page is loading. But for this purpose many developers use AJAX-queries. One query for one chunk of data. And store position of chunk in a session. But as I wrote at first the better way would be using background tasks and workers. There are many ways of implementation this approach. You can use some specialized services like RabbitMQ, Gearman or something like that. And you can just write your own console application that you will start and check by cron-task.
{ "language": "en", "url": "https://stackoverflow.com/questions/30502305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Node.js get actual memory usage as a percent I have used "os" http://nodejs.org/api/os.html#os_os To attempt to calculate some system stats for use in an app. However I notice that it cannot actually calculate the memory properly, because it leaves out the cache and buffers witch is needed to properly calculate a single readable percentage. Without it the memory will almost always be 90%+ with most high performance servers (based on my testing). I would need to calculate it like so: (CURRENT_MEMORY-CACHED_MEMORY-BUFFER_MEMORY)*100/TOTAL_MEMORY This should get me a more accurate % of memory being used by the system. But the os module and most other node.js modules I have seen only get me total and current memory. Is there any way to do this in node.js? I can use Linux but I do not know the ins and outs of the system to know where to look to figure this out on my own (file to read to get this information, like top/htop). A: Based on Determining free memory on Linux, Free memory = free + buffers + cache. Following example includes values derived from node os methods for comparison (which are useless) var spawn = require("child_process").spawn; var prc = spawn("free", []); var os = require("os"); prc.stdout.setEncoding("utf8"); prc.stdout.on("data", function (data) { var lines = data.toString().split(/\n/g), line = lines[1].split(/\s+/), total = parseInt(line[1], 10), free = parseInt(line[3], 10), buffers = parseInt(line[5], 10), cached = parseInt(line[6], 10), actualFree = free + buffers + cached, memory = { total: total, used: parseInt(line[2], 10), free: free, shared: parseInt(line[4], 10), buffers: buffers, cached: cached, actualFree: actualFree, percentUsed: parseFloat(((1 - (actualFree / total)) * 100).toFixed(2)), comparePercentUsed: ((1 - (os.freemem() / os.totalmem())) * 100).toFixed(2) }; console.log("memory", memory); }); prc.on("error", function (error) { console.log("[ERROR] Free memory process", error); }); Thanks to leorex. Check for process.platform === "linux" A: From reading the documentation, I am afraid that you do not have any native solution. However, you can always call 'free' from command line directly. I put together the following code based on Is it possible to execute an external program from within node.js? var spawn = require('child_process').spawn; var prc = spawn('free', []); prc.stdout.setEncoding('utf8'); prc.stdout.on('data', function (data) { var str = data.toString() var lines = str.split(/\n/g); for(var i = 0; i < lines.length; i++) { lines[i] = lines[i].split(/\s+/); } console.log('your real memory usage is', lines[2][3]); }); prc.on('close', function (code) { console.log('process exit code ' + code); });
{ "language": "en", "url": "https://stackoverflow.com/questions/20578095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Serving express static files not working with bundle from webpack :( so I have a node/express app that serves back a bundle.js bundled by webpack. I've been banging my head at this issue for close to 4 nights and I don't know anymore. I'm getting the Uncaught SyntaxError: Unexpected token < error as the express static middleware is not catching the request and treating it. webpack.config.js: output: { path: BUILD_DIR, filename: 'bundle.js', // https://github.com/webpack/webpack-dev-middleware/issues/205 // DO NOT leave publicPath out -- it'll cause errors if we do publicPath: '/', }, express middleware: var serveStatic = require('serve-static') app.use(serveStatic( path.join(__dirname, 'statics'), )) app.use('/dist', express.static('dist')); app.use('/statics', express.static('statics'));\ index.html: <script src="bundle.js" type="text/javascript"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/48656905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: javascript -I can't understand, why are the first two functions returning 'undefined' but the third one returns the desired value? Addy(int c) : function to add all the digits of the number and repeat the sum only if it is a single digit. Else, repeat the process till it is a single number. first function : function addy(c) { c = parseInt(c); console.log('Recieved Number '+c); var sum; var nas = c.toString().split(''); // nas --> Number As String. console.log('Digits present in Number: '+nas); for (var i = 0; i < nas.length; i++) { sum = sum + parseInt(nas[i]); } console.log('Sum is: '+sum); if(sum < 9) { console.log(typeof sum); console.log('value of sum is: '+ sum); return sum; } console.log('Value Still not single digit.'); addy(sum); } Algorithm(that I used in the first function.): * *Convert the given number to string. *Get all the digits present in the numbers by using the split method on the string that has just been created from the number. *Loop through all the digits, and add to sum. *If the sum is single digit, then return and if it is not then repeat the process till the sum is single digit. Second function : function addy(c){ var s=0; while(c!==0) { s = s + parseInt(c%10); c = parseInt(c/10); } if(s>9) { s = addy(s); } else if(s<9) { return s; } } Third function : (which actually works and is identical to the second function) function addy(num) { var sum = 0; while (num > 0) { sum += parseInt(num % 10); num = parseInt(num / 10); } if (sum > 9) { sum = addy(sum); } return sum; } I want to know the reason why the first two functions are returning "undefined" instead of returning a single digit number. A: First of all, your third function is not identical to your second function. First function Fixed code: function addy(c) { c = parseInt(c); var sum = 0; // <------- THIS LINE var nas = c.toString().split(''); for (var i = 0; i < nas.length; i++) { sum = sum + parseInt(nas[i]); } if(sum < 9) { return sum; } addy(sum); } console.log(addy(123)); Your original code has a line: var sum; // sum is undefined Therefore, when the execution reaches this line: sum = sum + parseInt(nas[i]); sum will become NaN because that translate to: undefined = undefined + parseInt(nas[i]); To make it work, you simply need to initialise the value of sum: var sum = 0; // Give sum a default value; Second function Fixed code: function addy(c){ var s=0; while(c!==0) { s = s + parseInt(c%10); c = parseInt(c/10); } if(s>9) { s = addy(s); return s; // <----- THIS LINE } else { return s; } } console.log(addy(1234)); In original code: if(s>9) { s = addy(s); } else { return s; } Nothing is being returned if s > 9. Therefore you get undefined. To make it work, you simply need to add a return line: if (s > 9){ s = addy(s); return s; // <--- THIS LINE } else { return s; }
{ "language": "en", "url": "https://stackoverflow.com/questions/47846088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: JavaScript regular expression to remove comma in number comma number "12,56,7abc,fgh" ===> "12567abc,fgh" "1,245abc,1a" ===> "1245abc,1a" "1,2,3,4,5abc" ===> "12345abc" How to remove comma in (number),(number) format? For the test const array = ["12,56,7abc,fgh", "1,245abc,1a", "1,2,3,4,5abc"] const answer = ["12567abc,fgh", "1245abc,1a", "12345abc"] function formatter(string){ // here return // string.replace('', '') ?? } array.map((el, i) => { const formatted = formatter(el) if(answer[i] === formatted){ console.log('Success. formatted: ', formatted) } else { console.log('Failed. formatted: ', formatted) } }) A: str.replace(/(?<=\d),(?=\d)/g, '') (?<=\d): lookbehind - a digit (?=\d) : lookahead - a digit
{ "language": "en", "url": "https://stackoverflow.com/questions/62314932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Initialize multiple jQuery sliders programatically, each with a different onChange function I'll try and keep this straightforward. I am using jQuery sliders and trying to initialize them all at once using an array: sliders.push(new slider('paletteControl','pSlider',0,255,100,sliderChange())); function slider (context, id, min, max, defaultvalue, changeFunc) { this.context = context; this.id = id; this.min = min; this.max = max; this.defaultvalue = defaultvalue; this.changeFunc = changeFunc; } Where context is the ID of its intended parent div and changeFunc is the function I want it to call on change. My Init function loops through this array and appends the markup according to the context, and then tries to init each jquery slider like so: $(id).slider({ range: "min", min: sliders[i].min, max: sliders[i].max, value: sliders[i].defaultvalue, create: function() { handle.text( $( this ).slider( "value" ) ); }, change: function() { sliders[i].changeFunc(); } }); The min, max, and value inits work fine, presumably since they happen exactly once, during the init, but the change function fails pretty miserably, again presumably because it's simply trying to look up sliders[i] on each change (i being a long dead iterator by that point). My question is - how can I programatically init a bunch of jquery sliders, each with a different onChange function? Without doing them manually, that is. EDIT: Got some great help from Ramon de Paula Marques below, though in the end I had to do it a different way altogether because I was unable to pass a value to the function. What I ended up doing, for better or worse, was creating a wrapper function that simply looked up the proper change function once called based on the id of the slider that called it. function parcelSliderFunction(caller, value) { for (var x = 0; x < sliders.length; x++) { if(sliders[x].id == caller) { sliders[x].callback(value); return; } } console.log("id " + caller + " not found, you done screwed up."); return; } I should probably use a dictionary for this. A: First you have to remove parentheses of the function as parameter, in this line sliders.push(new slider('paletteControl','pSlider',0,255,100,sliderChange())); It becomes sliders.push(new slider('paletteControl','pSlider',0,255,100,sliderChange)); Then you get the change function like this (without parentheses) $(id).slider({ range: "min", min: sliders[i].min, max: sliders[i].max, value: sliders[i].defaultvalue, create: function() { handle.text( $( this ).slider( "value" ) ); }, change: sliders[i].changeFunc }); OR $(id).slider({ range: "min", min: sliders[i].min, max: sliders[i].max, value: sliders[i].defaultvalue, create: function() { handle.text( $( this ).slider( "value" ) ); } }); $( id ).on( "slidechange", function( event, ui ) {} ); A: You may call the changeFunc using window[value.changeFunc] as shown below function newSlider(context, id, min, max, defaultvalue, changeFunc) { this.context = context; this.id = id; this.min = min; this.max = max; this.defaultvalue = defaultvalue; this.changeFunc = changeFunc; } function func1() { $('#output').append("func1<br>"); } function func2() { $('#output').append("func2<br>"); } function func3() { $('#output').append("func3<br>"); } var sliders = []; sliders.push(new newSlider('paletteControl', 'pSlider1', 0, 255, 100, "func1")); sliders.push(new newSlider('paletteControl', 'pSlider2', 0, 255, 200, "func2")); sliders.push(new newSlider('paletteControl', 'pSlider3', 0, 255, 70, "func3")); $.each(sliders, function(index, value) { $("#" + value.id).slider({ range: "min", min: value.min, max: value.max, value: value.defaultvalue, change: window[value.changeFunc] }); }); Working code: https://plnkr.co/edit/nwjOrnwoI7NU3MY8jXYl?p=preview
{ "language": "en", "url": "https://stackoverflow.com/questions/44116834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to fit multiline text inside a TextView using a custom font? I'm using API 10. I am stuck with this for days. I searched stackoverflow and tried a ton of classes. I wanted to fit a multiline text inside my TextView bounds with the default font. I used the class below and it worked wonders, and not only one one device, but on all devices. Exactly the same. The code is this, I found it in stackoverflow: /** * This class builds a new android Widget named AutoFitText which can be used instead of a TextView * to have the text font size in it automatically fit to match the screen width. Credits go largely * to Dunni, gjpc, gregm and speedplane from Stackoverflow, method has been (style-) optimized and * rewritten to match android coding standards and our MBC. This version upgrades the original * "AutoFitTextView" to now also be adaptable to height and to accept the different TextView types * (Button, TextClock etc.) * * @author pheuschk * @createDate: 18.04.2013 */ @SuppressWarnings("unused") public class AutoFitText extends TextView { /** Global min and max for text size. Remember: values are in pixels! */ private final int MIN_TEXT_SIZE = 10; private final int MAX_TEXT_SIZE = 400; /** Flag for singleLine */ private boolean mSingleLine = false; /** * A dummy {@link TextView} to test the text size without actually showing anything to the user */ private TextView mTestView; /** * A dummy {@link Paint} to test the text size without actually showing anything to the user */ private Paint mTestPaint; /** * Scaling factor for fonts. It's a method of calculating independently (!) from the actual * density of the screen that is used so users have the same experience on different devices. We * will use DisplayMetrics in the Constructor to get the value of the factor and then calculate * SP from pixel values */ private final float mScaledDensityFactor; /** * Defines how close we want to be to the factual size of the Text-field. Lower values mean * higher precision but also exponentially higher computing cost (more loop runs) */ private final float mThreshold = 0.5f; /** * Constructor for call without attributes --> invoke constructor with AttributeSet null * * @param context */ public AutoFitText(Context context) { this(context, null); } public AutoFitText(Context context, AttributeSet attrs) { super(context, attrs); mScaledDensityFactor = context.getResources().getDisplayMetrics().scaledDensity; mTestView = new TextView(context); mTestPaint = new Paint(); mTestPaint.set(this.getPaint()); this.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @SuppressWarnings("deprecation") @Override public void onGlobalLayout() { // make an initial call to onSizeChanged to make sure that refitText is triggered onSizeChanged(AutoFitText.this.getWidth(), AutoFitText.this.getHeight(), 0, 0); // Remove the LayoutListener immediately so we don't run into an infinite loop AutoFitText.this.getViewTreeObserver().removeGlobalOnLayoutListener(this); } }); } /** * Main method of this widget. Resizes the font so the specified text fits in the text box * assuming the text box has the specified width. This is done via a dummy text view that is * refit until it matches the real target width and height up to a certain threshold factor * * @param targetFieldWidth * The width that the TextView currently has and wants filled * @param targetFieldHeight * The width that the TextView currently has and wants filled */ private void refitText(String text, int targetFieldWidth, int targetFieldHeight) { // Variables need to be visible outside the loops for later use. Remember size is in pixels float lowerTextSize = MIN_TEXT_SIZE; float upperTextSize = MAX_TEXT_SIZE; // Force the text to wrap. In principle this is not necessary since the dummy TextView // already does this for us but in rare cases adding this line can prevent flickering this.setMaxWidth(targetFieldWidth); // Padding should not be an issue since we never define it programmatically in this app // but just to to be sure we cut it off here targetFieldWidth = targetFieldWidth - this.getPaddingLeft() - this.getPaddingRight(); targetFieldHeight = targetFieldHeight - this.getPaddingTop() - this.getPaddingBottom(); // Initialize the dummy with some params (that are largely ignored anyway, but this is // mandatory to not get a NullPointerException) mTestView.setLayoutParams(new LayoutParams(targetFieldWidth, targetFieldHeight)); // maxWidth is crucial! Otherwise the text would never line wrap but blow up the width mTestView.setMaxWidth(targetFieldWidth); if (mSingleLine) { // the user requested a single line. This is very easy to do since we primarily need to // respect the width, don't have to break, don't have to measure... /*************************** Converging algorithm 1 ***********************************/ for (float testSize; (upperTextSize - lowerTextSize) > mThreshold;) { // Go to the mean value... testSize = (upperTextSize + lowerTextSize) / 2; mTestView.setTextSize(TypedValue.COMPLEX_UNIT_SP, testSize / mScaledDensityFactor); mTestView.setText(text); mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); if (mTestView.getMeasuredWidth() >= targetFieldWidth) { upperTextSize = testSize; // Font is too big, decrease upperSize } else { lowerTextSize = testSize; // Font is too small, increase lowerSize } } /**************************************************************************************/ // In rare cases with very little letters and width > height we have vertical overlap! mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); if (mTestView.getMeasuredHeight() > targetFieldHeight) { upperTextSize = lowerTextSize; lowerTextSize = MIN_TEXT_SIZE; /*************************** Converging algorithm 1.5 *****************************/ for (float testSize; (upperTextSize - lowerTextSize) > mThreshold;) { // Go to the mean value... testSize = (upperTextSize + lowerTextSize) / 2; mTestView.setTextSize(TypedValue.COMPLEX_UNIT_SP, testSize / mScaledDensityFactor); mTestView.setText(text); mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); if (mTestView.getMeasuredHeight() >= targetFieldHeight) { upperTextSize = testSize; // Font is too big, decrease upperSize } else { lowerTextSize = testSize; // Font is too small, increase lowerSize } } /**********************************************************************************/ } } else { /*********************** Converging algorithm 2 ***************************************/ // Upper and lower size converge over time. As soon as they're close enough the loop // stops // TODO probe the algorithm for cost (ATM possibly O(n^2)) and optimize if possible for (float testSize; (upperTextSize - lowerTextSize) > mThreshold;) { // Go to the mean value... testSize = (upperTextSize + lowerTextSize) / 2; // ... inflate the dummy TextView by setting a scaled textSize and the text... mTestView.setTextSize(TypedValue.COMPLEX_UNIT_SP, testSize / mScaledDensityFactor); mTestView.setText(text); // ... call measure to find the current values that the text WANTS to occupy mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); int tempHeight = mTestView.getMeasuredHeight(); // int tempWidth = mTestView.getMeasuredWidth(); // LOG.debug("Measured: " + tempWidth + "x" + tempHeight); // LOG.debug("TextSize: " + testSize / mScaledDensityFactor); // ... decide whether those values are appropriate. if (tempHeight >= targetFieldHeight) { upperTextSize = testSize; // Font is too big, decrease upperSize } else { lowerTextSize = testSize; // Font is too small, increase lowerSize } } /**************************************************************************************/ // It is possible that a single word is wider than the box. The Android system would // wrap this for us. But if you want to decide fo yourself where exactly to break or to // add a hyphen or something than you're going to want to implement something like this: mTestPaint.setTextSize(lowerTextSize); List<String> words = new ArrayList<String>(); for (String s : text.split(" ")) { Log.i("tag", "Word: " + s); words.add(s); } for (String word : words) { if (mTestPaint.measureText(word) >= targetFieldWidth) { List<String> pieces = new ArrayList<String>(); // pieces = breakWord(word, mTestPaint.measureText(word), targetFieldWidth); // Add code to handle the pieces here... } } } /** * We are now at most the value of threshold away from the actual size. To rather undershoot * than overshoot use the lower value. To match different screens convert to SP first. See * {@link http://developer.android.com/guide/topics/resources/more-resources.html#Dimension} * for more details */ this.setTextSize(TypedValue.COMPLEX_UNIT_SP, lowerTextSize / mScaledDensityFactor); return; } /** * This method receives a call upon a change in text content of the TextView. Unfortunately it * is also called - among others - upon text size change which means that we MUST NEVER CALL * {@link #refitText(String)} from this method! Doing so would result in an endless loop that * would ultimately result in a stack overflow and termination of the application * * So for the time being this method does absolutely nothing. If you want to notify the view of * a changed text call {@link #setText(CharSequence)} */ @Override protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { // Super implementation is also intentionally empty so for now we do absolutely nothing here super.onTextChanged(text, start, lengthBefore, lengthAfter); } @Override protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) { if (width != oldWidth && height != oldHeight) { refitText(this.getText().toString(), width, height); } } /** * This method is guaranteed to be called by {@link TextView#setText(CharSequence)} immediately. * Therefore we can safely add our modifications here and then have the parent class resume its * work. So if text has changed you should always call {@link TextView#setText(CharSequence)} or * {@link TextView#setText(CharSequence, BufferType)} if you know whether the {@link BufferType} * is normal, editable or spannable. Note: the method will default to {@link BufferType#NORMAL} * if you don't pass an argument. */ @Override public void setText(CharSequence text, BufferType type) { int targetFieldWidth = this.getWidth(); int targetFieldHeight = this.getHeight(); if (targetFieldWidth <= 0 || targetFieldHeight <= 0 || text.equals("")) { // Log.v("tag", "Some values are empty, AutoFitText was not able to construct properly"); } else { refitText(text.toString(), targetFieldWidth, targetFieldHeight); } super.setText(text, type); } /** * TODO add sensibility for {@link #setMaxLines(int)} invocations */ @Override public void setMaxLines(int maxLines) { // TODO Implement support for this. This could be relatively easy. The idea would probably // be to manipulate the targetHeight in the refitText-method and then have the algorithm do // its job business as usual. Nonetheless, remember the height will have to be lowered // dynamically as the font size shrinks so it won't be a walk in the park still if (maxLines == 1) { this.setSingleLine(true); } else { throw new UnsupportedOperationException( "MaxLines != 1 are not implemented in AutoFitText yet, use TextView instead"); } } @Override public void setSingleLine(boolean singleLine) { // save the requested value in an instance variable to be able to decide later mSingleLine = singleLine; super.setSingleLine(singleLine); } } The text shrunk as needed so that it fit the TextView bounds. But now I want to use a custom font. I imported my custom font and everything went wrong. As you can see in the image below it doesn't fit anymore. The text doesn't shrink to fit. So, does anyone have an idea how to handle this? Have you faced a similar problem with custom fonts? Please someone with enough reputation, enable my image. A: You need also to set the current fontface to the testTextView. This solved my problem. private void refitText(String text, int targetFieldWidth, int targetFieldHeight) { // // Bla bla bla codes // // // THIS IS THE FIX // Put the current typeface of textview to the test-textview mTestView.setTypeface(getTypeface()); // Initialize the dummy with some params (that are largely ignored anyway, but this is // mandatory to not get a NullPointerException) mTestView.setLayoutParams(new LayoutParams(targetFieldWidth, targetFieldHeight)); // maxWidth is crucial! Otherwise the text would never line wrap but blow up the width mTestView.setMaxWidth(targetFieldWidth); if (mSingleLine) {
{ "language": "en", "url": "https://stackoverflow.com/questions/16641182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ggplot2 polygon world map centred with limits gives funny edges Using the below code I generate a map centred on Washington DC. solution based on kohske's solution here. I have changed geom_path to geom_polygon as I want to colour the countries. All is well and good until I want add the scale_x_continuous (commented so you can see that there's no problem when it is left out), this makes Antarctica and China look very strange, i guess because the polygons have been trimmed? Is there a known workaround for this? Help is appreciated. library(maps) library(maptools) library(ggplot2) home_country_longitude <- -77.03 mp1 <- fortify(map(fill=TRUE, plot=FALSE)) mp2 <- mp1 mp2$long <- mp2$long + 360 mp2$group <- mp2$group + max(mp2$group) + 1 mp <- rbind(mp1, mp2) if(home_country_longitude < 0){ mp$long <- mp$long - (360 + home_country_longitude) } else { mp$long <- mp$long + home_country_longitude } ggplot() + geom_polygon(aes(x = long, y = lat, group = group), data = mp) + #scale_x_continuous(limits = c(-180, 180)) + theme(panel.background = element_rect(fill = "#090D2A"), panel.grid.major = element_blank(), panel.grid.minor = element_blank()) A: Use coord_map, like this. Full explanation here. ggplot() + geom_polygon(aes(x = long, y = lat, group = group), data = mp) + coord_map(xlim = c(-180, 180)) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())
{ "language": "en", "url": "https://stackoverflow.com/questions/47021117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to check the variables of an Object are Empty or NULL in JAVA? How to check variables of Objects are empty or NULL in JAVA? Employee employee = repository.getEmployee(id).orElseGet(null); if (employee == null) { employee = new Employee(); employee.id(1); employee.name("Thirumal"); employee.mobile("+91-8973-697-871"); repository.save(employee); } Instead of NULL, I am trying to create an object new Employee() Employee employee = repository.getEmployee(id).orElseGet(new Employee()); if (employee.isEmpty()) { //--------- How to do ???????? employee = new Employee(); employee.id(1); employee.name("Thirumal"); employee.mobile("+91-8973-697-871"); repository.save(employee); } How to check the member of objects are empty/NULL? A: Just add that isEmpty method to Employee class and implement it there, or use a null object pattern instead of doing new Employee(). As to what you are actually trying to do in your code, I suggest to do it like that instead: Employee employee = repository.getEmployee(id).orElseGet(() -> { Employee emp = new Employee(); emp.id(1); emp.name("Thirumal"); emp.mobile("+91-8973-697-871"); return repository.save(emp); });
{ "language": "en", "url": "https://stackoverflow.com/questions/63391784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How can I open the Install Voices settings page in Objective C (iOS) I would like my custom made app to be able to open the iOS native settings page, specifically the settings for installing new voices to your device. How can I do this in Objective C? I saw you can use UIApplicationOpenSettingsURLString to open the settings, but I need to go to the specific install voices settings page for the current language of the user which looks like this: This page is found under: Settings -> Accessibility -> Spoken Content -> Voices -> (Your Language) Getting to the Voices page, where the user has to select the language is fine too. I guess I could try using the open() objective C function in order to open a custom URI scheme, but I need to know which URI scheme I need exactly... EDIT: This is what I'm currently trying to do: NSString *voiceSettings = @"prefs:root=ACCESSIBILITY&path=SPEECH_TITLE#QuickSpeakAccents"; NSString *cleanQuery = [voiceSettings stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString: [NSString stringWithFormat:cleanQuery]] options:@{} completionHandler:nil]; However it fails with: Failed to open URL prefs:root=ACCESSIBILITY&path=SPEECH_TITLE#QuickSpeakAccents: Error Domain=NSOSStatusErrorDomain Code=-10814 "(null)" UserInfo={_LSLine=229, _LSFunction=-[_LSDOpenClient openURL:options:completionHandler:]} am I missing something here? A: UIApplicationOpenSettingsURLString is the only supported way of opening the built-in Settings.app. Any other method is a hack and runs the risk of review rejection because of private API usage. See e.g. Is it considered a private API to use App-prefs:root?
{ "language": "en", "url": "https://stackoverflow.com/questions/66919691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot implicity convert type object to system.data.datatable Hi I'm trying to do the following but it throws the error title. As I can fix? Thanks!!! public static object conectar(string query) { DataTable Tabla = new DataTable(); SqlConnection connection = BaseDatos1.getConexion(); SqlDataAdapter Da = new SqlDataAdapter(); DataSet Ds = new DataSet(); Da = new SqlDataAdapter(query, connection); Da.FillSchema(Tabla, SchemaType.Source); Da.FillLoadOption = LoadOption.PreserveChanges; Da.Fill(Tabla); BaseDatos1.closeConnection(); return Tabla; } public static string Verificar() { bool functionReturnValue ; DataTable Dt1; DataTable Dt2; DataTable Dt3; int j; int k; int DigitoVerificador; int Acum; string A; string tablas = ""; string[] table = new string[6]; string registro = ""; bool errorEnTablaActual; int reg = 0; try { functionReturnValue = true; //Verifico en Base Seguridad **Dt1 = conectar("select Tabla from DigitoVerificador");** A: You get the error because the conectar method returns an object, which you then assign to Dt1, which is a DataTable, and so you get the message that the value cannot be implicitly converted.. You can explicitly cast the return value to a DataTable, as the conectar method never returns null: Dt1 = (DataTable)conectar("select Tabla from DigitoVerificador"); Alternatively, and probably better, you would change the return type of conectar to DataTable.
{ "language": "en", "url": "https://stackoverflow.com/questions/40382828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Series from highcharts not showing up This is my first time using Highcharts and I'm struggling with a little problem that doesn't let me go further in my work. I have a database in MySQL and I'm trying to show some infomation on a graph using Highcharts. The problem is that even after several try, I'm still not being able to show my series and I can't see why. Here's my code : data.php <?php try { $bdd = new PDO('mysql:host=localhost;dbname=name', 'root', ''); } catch (Exception $e) { die('Erreur : ' . $e->getMessage()); } $sql=<<<SQL SELECT DATE, Traf_BH_TCH_Erl, Trafic_HR_BH, Block_BH_TCH FROM 182_d_all WHERE BCF='TIMNAY' SQL; $reponse = $bdd->query($sql); $bln = array(); $rows = array(); $bln['name'] = 'Date'; $rows['name'] = 'Traf_BH_TCH_Erl'; while($donnee=$reponse->fetch()){ $bln['data'][] = $donnee['DATE']; $rows['data'][] = $donnee['Traf_BH_TCH_Erl']; } $rslt = array(); array_push($rslt, $bln); array_push($rslt, $rows); print json_encode($rslt, JSON_NUMERIC_CHECK); $reponse->closeCursor(); ?> line.php <?php $cakeDescription = "Highcharts Pie Chart"; ?> <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title><?php echo $cakeDescription ?></title> <link href="webroot/css/cake.generic.css" type="text/css" rel="stylesheet"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var options = { chart: { renderTo: 'container', type: 'line' }, title: { text: 'Random title', x: -20 //center }, subtitle: { text: 'Random subtitle', x: -20 }, xAxis: { categories: [], title: { text: 'Date' } }, yAxis: { title: { text: 'Traf_BH_TCH_Erl' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, tooltip: { valueSuffix: 'Hz' }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle', borderWidth: 0 }, series: [] }; $.getJSON("data.php", function(json) { options.xAxis.categories = json[0]['data']; //xAxis: {categories: []} options.series[0] = json[1]; chart = new Highcharts.Chart(options); }); }); </script> <script src="http://code.highcharts.com/highcharts.js"></script> <script src="http://code.highcharts.com/modules/exporting.js"></script> </head> <body> <!-- <a class="link_header" href="/highcharts/">&lt;&lt; Back to index</a> --> <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div> </body> </html> The problem is that all the values of the series are equal to zero. I don't understand why it's all blank instead of showing values? Thank you for your answers! EDIT : The JSON looks something like : [{"name":"Date","data":["\n5/6/2015 00:00:00","\n17/6/2015 00:00:0","\n15/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n26/6/2015 00:00:0","\n18/6/2015 00:00:0","\n18/6/2015 00:00:0","\n16/6/2015 00:00:0","\n7/6/2015 00:00:00","\n9/6/2015 00:00:00","\n3/6/2015 00:00:00","\n11/6/2015 00:00:0","\n9/6/2015 00:00:00","\n11/6/2015 00:00:0","\n20/6/2015 00:00:0","\n7/6/2015 00:00:00","\n24/6/2015 00:00:0","\n9/6/2015 00:00:00","\n22/6/2015 00:00:0","\n26/6/2015 00:00:0","\n26/6/2015 00:00:0","\n17/6/2015 00:00:0","\n17/6/2015 00:00:0","\n16/6/2015 00:00:0","\n16/6/2015 00:00:0","\n24/6/2015 00:00:0","\n22/6/2015 00:00:0","\n24/6/2015 00:00:0","\n22/6/2015 00:00:0","\n3/6/2015 00:00:00","\n20/6/2015 00:00:0","\n20/6/2015 00:00:0","\n3/6/2015 00:00:00","\n7/6/2015 00:00:00","\n28/6/2015 00:00:0","\n25/6/2015 00:00:0","\n25/6/2015 00:00:0","\n25/6/2015 00:00:0","\n5/6/2015 00:00:00","\n5/6/2015 00:00:00","\n28/6/2015 00:00:0","\n28/6/2015 00:00:0","\n15/6/2015 00:00:0","\n15/6/2015 00:00:0","\n23/6/2015 00:00:0","\n21/6/2015 00:00:0","\n19/6/2015 00:00:0","\n19/6/2015 00:00:0","\n19/6/2015 00:00:0","\n30/6/2015 00:00:0","\n30/6/2015 00:00:0","\n28/5/2015 00:00:0","\n18/6/2015 00:00:0","\n1/7/2015 00:00:00","\n1/7/2015 00:00:00","\n1/7/2015 00:00:00","\n8/6/2015 00:00:00","\n8/6/2015 00:00:00","\n8/6/2015 00:00:00","\n4/6/2015 00:00:00","\n4/6/2015 00:00:00","\n4/6/2015 00:00:00","\n28/5/2015 00:00:0","\n28/5/2015 00:00:0","\n29/5/2015 00:00:0","\n29/5/2015 00:00:0","\n29/5/2015 00:00:0","\n31/5/2015 00:00:0","\n6/6/2015 00:00:00","\n6/6/2015 00:00:00","\n6/6/2015 00:00:00","\n30/5/2015 00:00:0","\n30/5/2015 00:00:0","\n21/6/2015 00:00:0","\n21/6/2015 00:00:0","\n10/6/2015 00:00:0","\n10/6/2015 00:00:0","\n10/6/2015 00:00:0","\n23/6/2015 00:00:0","\n23/6/2015 00:00:0","\n29/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n27/6/2015 00:00:0","\n29/6/2015 00:00:0","\n29/6/2015 00:00:0","\n27/6/2015 00:00:0","\n27/6/2015 00:00:0","\n30/5/2015 00:00:0","\n30/6/2015 00:00:0","\n1/6/2015 00:00:00","\n1/6/2015 00:00:00","\n1/6/2015 00:00:00","\n31/5/2015 00:00:0","\n31/5/2015 00:00:0","\n2/6/2015 00:00:00","\n2/6/2015 00:00:00","\n2/6/2015 00:00:00","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n12/6/2015 00:00:0","\n12/6/2015 00:00:0","\n12/6/2015 00:00:0","\n12/6/2015 00:00:0","\n12/6/2015 00:00:0","\n12/6/2015 00:00:0"]},{"name":"Traf_BH_TCH_Erl","data":["14,49","17,47","12,96","13,10","13,10","12,03","5,59","10,33","3,68","10,42","14,92","12,82","14,49","11,93","12,03","11,47","5,59","11,09","12,29","10,31","5,63","10,15","9,82","4,56","15,58","8,52","12,77","7,56","10,18","11,23","3,36","4,08","11,96","9,97","3,98","5,69","4,97","13,49","8,55","7,88","4,17","12,25","5,81","8,69","4,72","12,01","5,59","11,58","9,77","9,69","8,47","2,89","9,61","3,24","12,71","8,27","12,36","10,42","3,67","14,21","13,59","4,92","15,37","13,56","4,44","11,41","7,39","14,90","11,77","6,63","11,02","12,68","11,48","5,19","12,37","5,84","8,26","3,87","12,71","11,79","5,37","8,94","3,27","9,82","13,10","12,03","5,59","11,31","9,06","3,65","10,13","4,06","9,11","9,79","11,71","11,57","5,46","9,37","4,59","13,62","13,33","5,34","13,10","12,03","5,59","13,10","12,03","5,59","13,10","12,03","5,59","10,59","10,00","4,77","10,59","10,00","4,77"]}] A: There is a lot going on here... A few changes I did to get a functional example from your data: * *You must create a 'data' field inside 'series': series: [{ data: [] }] *You must set the 'data' attribute from 'series[0]' and pass the data field from your JSON: options.series[0].data = text[1].data; *You must use numbers as y coordinate data, so you should use dot as decimal separator and do not use quotes: {"name":"Traf_BH_TCH_Erl","data":[11.23,3.36,4.08,11.96,9.97]} *You are not using X axis with date format properly, but you can search for that after you get your first Highcharts working. ;) Functional example: JSFiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/31405965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generating a PHP array tree structure from dynamic data set I have a history with having tree issues and I've done a lot of research on the topic. I think maybe I'm using the wrong hammer on this nail. I am trying to create a tree hierarchy data set from an array, but not just one that has defined parent-child relationships. It's pretty much comparing one array in the data set to another, and then combining what is the same, and branching the differences into a new array. The reasoning behind this is for searching against the data sets later (such as ACL) which are expected to be large, and to return this format through API calls. Coming from a PHP and MySQL query, I return an array that looks like this (the key value pairs could be anything, this is just a generalization): $testArray = array( array('group' => 'Group1','group_id' => '1','portal' => 'Portal1','portal_id' => '1','role' => 'Role1','role_id' => '1','permission' => 'Permission1','permission_id' => '1'), array('group' => 'Group1','group_id' => '1','portal' => 'Portal1','portal_id' => '1','role' => 'Role1','role_id' => '1','permission' => 'Permission2','permission_id' => '2'), array('group' => 'Group1','group_id' => '1','portal' => 'Portal2','portal_id' => '2','role' => 'Role1','role_id' => '1','permission' => 'Permission3','permission_id' => '3'), array('group' => 'Group1','group_id' => '1','portal' => 'Portal2','portal_id' => '2','role' => 'Role2','role_id' => '2','permission' => 'Permission1','permission_id' => '1'), array('group' => 'Group2','group_id' => '2','portal' => 'Portal1','portal_id' => '1','role' => 'Role3','role_id' => '3','permission' => 'Permission1','permission_id' => '1'), array('group' => 'Group2','group_id' => '2','portal' => 'Portal1','portal_id' => '1','role' => 'Role3','role_id' => '3','permission' => 'Permission2','permission_id' => '2') ); Pseudo Output After: (Group_Name = Group1, Group_ID = 1) (Portal_Name = Portal1, Portal_id = 1) (Portal_Name = Portal2, Portal_id = 2) (Role,RoleID) (Role,RoleID) (Permission,Permission_id) (Permission,Permission_id) Here's the WIP function. It's a little all over the place ATM, but this is where my head is at: //List of keyList to compare against if(is_array($testArray[0])) { $keyList = array_keys($testArray[0]); } function buildTree(&$data, $keyList) { $branch = array(); $tree = array(); foreach($keyList as $k => &$keyName) { //Each row in the data set is an array foreach($data as $rowKey => &$rowArraySet) { //If the branch key exists, and matches if(isset($rowArraySet[$keyName]) && isset($keyList[$keyName]) && isset($branch[$keyList[$keyName]][$rowArraySet[$keyName]])) { if(isset($data[1+$rowKey]) && $rowArraySet[$keyName] == $data[1+$rowKey][$keyName]) { $branch[$keyName][$rowArraySet[$keyName]] = array_diff($rowArraySet, $rowArraySet[$keyName]); unset($data[$rowKey]); } } //If the branch does not exist, and matches next array record else if(isset($data[1+$rowKey]) && $rowArraySet[$keyName] == $data[1+$rowKey][$keyName]) { $branch[$keyName] = array(); $branch[$keyName][$rowArraySet[$keyName]] = array_diff($rowArraySet, array($keyName => $rowArraySet[$keyName])); unset($data[$rowKey]); } //Create new branch key (no match) else if(isset($rowArraySet[$keyName])) { $branch[$keyName] = array(); $branch[$keyName][$rowArraySet[$keyName]] = array_diff($rowArraySet, array($keyName => $rowArraySet[$keyName])); unset($data[$rowKey]); } echo $rowKey; } //Remove keyName from checking unset($keyList[$k]); //Compare branch //$tree[] = buildTree($branch, &$keyList); //echo '<pre>'; //var_dump($branch); //die; } return $tree; } Yes, I know there's a little place in hell for programmers and undocumented code. My thinking goes like this: * *Capture Keys from the first array in the set (this is the parent - child like relationship, at least the order to check against) *Use the keys to compare each array to eachother in the set (if exists/set etc) *Matching values create a new branch and move the array over, combining them *Check the next set, and check to see if the keys exist in the branch *Recursively sort the branch once complete *Return branch to tree array and output tree As always, any guidance is appreciated. I feel like I'm close to figuring this out, I just can't wrap my head around it. Thank you. Edit per recommendations.
{ "language": "en", "url": "https://stackoverflow.com/questions/22868871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get return code from spark-submit? I am trying to execute a spark job using an ssh connection on a remote location. There have been instances where the job failed but the scheduler marked it as "success" so i want to check the return code of spark-submit so i could forcefully fail it. Below is the code I'm using def execute_XXXX(): f = open('linux.pem','r') s = f.read() keyfile = StringIO.StringIO(s) mykey = paramiko.RSAKey.from_private_key(keyfile) sshcon = paramiko.SSHClient() sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) sshcon.connect('XXX.XXX.XXX.XXX', username='XXX', pkey=mykey) stdin, stderr, stdout= sshcon.exec_command('spark-submit XXX.py') logger.info("XXX ------>"+str(stdout.readlines())) logger.info("Error--------->"+str(stderr.readlines())) How do I get the return code for the spark-submit job so I can forcefully fail the task. Or could you suggest an alternate solution. Thanks, Chetan A: So this is how I solved the issue i was facing. A simple 1 line code was enough. def execute_XXXX(): f = open('linux.pem','r') s = f.read() keyfile = StringIO.StringIO(s) mykey = paramiko.RSAKey.from_private_key(keyfile) sshcon = paramiko.SSHClient() sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) sshcon.connect('XXX.XXX.XXX.XXX', username='XXX', pkey=mykey) stdin, stderr, stdout= sshcon.exec_command('spark-submit XXX.py') if (stdout.channel.recv_exit_status())!= 0: logger.info("XXX ------>"+str(stdout.readlines())) logger.info("Error--------->"+str(stderr.readlines())) sys.exit(1) A: You need to implement a sparkListener. More information to which can be found on the below link. How to implement custom job listener/tracker in Spark?
{ "language": "en", "url": "https://stackoverflow.com/questions/43321182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Excel SUMIF variations I'm trying to make a SUMIF function like this one =SUMIF(OUT!$G$22:$G$70;'2018'!$B4;OUT!$J$22:$J$70) But i would like instead of giving the name of the sheet OUT, i want the excel to read de name of the sheet from an other cell like i show on the img. I tried =SUMIF(CELL("contents";E2)!$G$22:$G$70;'2018'!$B4;CELL("contents";E2)!$J$22:$J$70) but still not working. Anyone knows how to do it? Excel image A: You need INDIRECT: =SUMIF(INDIRECT("'"&E2&"'!G22:G70");'2018'!$B4;INDIRECT("'"&E2&"'!J22:J70")) Note that since the ranges are literal text strings, you don't need to make them absolute since they won't adjust if you copy/fill anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/53518717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What determines if a scrollbar has color in Firefox? TLDR; I've encountered interesting behaviour in Firefox. For example, it automatically styles the scrollbar limegreen, but not lightgreen. Why does it render one, but not the other? While answering another question I found that this renders a limegreen colored scroll bar in Firefox 72 latest on Windows 10: div { background-color: limegreen; max-height: 5em; overflow-y: scroll; } <div>Hi!<br>Hi!<br>Hi!<br>Hi!<br>Hi!<br>Hi!<br>Hi!<br>Hi!<br>Hi!<br>Hi!<br></div> Like this: But that Firefox refuses to render a lightgreen colored scroll bar: div { background-color: lightgreen; max-height: 5em; overflow-y: scroll; } <div>Hi!<br>Hi!<br>Hi!<br>Hi!<br>Hi!<br>Hi!<br>Hi!<br>Hi!<br>Hi!<br>Hi!<br></div> See this: What causes this behavior, and how can I predict it? PS. Chrome 80 shows both scrollbars in the default style. PS. There are questions on how to actively change scrollbar color in Firefox, but I'm not (right now) interested in pragmatic advice on "how to change scrollbar color", but instead I'm asking and trying to understand when and why it happens automatically, and only for some background colors. A: div { background-color: lightgreen; max-height: 5em; overflow-y: scroll; scrollbar-color: lightgreen lightgreen; } <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div> Using scrollbar-color works (more info here). I think color detection is just really buggy - sometimes one color works with scrollbar-color and applies to both parts of the scrollbar and sometimes you need to repeat it twice. I just think it's a poorly implemented part of the HTML spec. Doesn't have great browser support though so make sure it's not required as part of your interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/60296538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: checkbox select submit post call I need to make a post call when a checkbox is selected in table. The row information should need to be passed when I select the checkbox of the particular row which I am selecting. Right now I am bale to get the selected table row information, only thing is I am not able to submit information to backend. Note: I dont want to make a ajax call.I need the page get reload once again. Code: <script type="text/javascript"> $(function() { $(".chcktbl").change(function() { if(this.checked) { alert("ddd"); var chk = $(this).closest('tr').find('input:checkbox'); var data = $(this).parents('tr:eq(0)'); alert( $(data).find('td:eq(1)').text()); alert( $(data).find('td:eq(2)').text()); } }); }); </script> <div id="searchContainer"> <span class="addmessage">${flashMessage}</span> <form method="post" action="/InformationManagement/mrps/getDepositSearch" class="searchCriteria"> <div class="searchform"> Select the Search Column Name <select class="dropmenu" name="searchCondition"> <option value="NONE">--- Select ---</option> <c:forEach items="${searchAllContents.searchContent}" var="record"> <%-- <c:if test="${searchAllContents.searchContent} ==''"> <option value="${record.key}" selected>${record.value}</option> </c:if> --%> <c:choose> <c:when test="${record.key=='DPST_NUM'}"> <option value="${record.key}" selected>${record.value}</option> <option value="DPST_DTE">Deposit Date</option> </c:when> <c:when test="${record.key=='DPST_DTE'}"> <option value="DPST_NUM">Deposit Number</option> <option value="${record.key}" selected>${record.value}</option> </c:when> <c:otherwise> <option value="DPST_NUM">Deposit Number</option> <option value="DPST_DTE">Deposit Date</option> </c:otherwise> </c:choose> </c:forEach> </select> Search <input type="text" id="searchText" name="searchText" value="${searchText}" /> <!-- <button class = "refreshButton">Refresh</button> --> <input type="submit" class="submit" /> </div> </form> </div> <div> <form name="test" id= "testid" action="Controller" method="post"> <table style="width:100%"> <tr> <th></th> <th>Deposit Date</th> <th>Deposit Number</th> <th>Deposit Status</th> </tr> <c:forEach items="${depositDetails}" var="depositDetails"> <tr> <td><input type="checkbox" class = "chcktbl" /></td> <td>${depositDetails.DPST_DTE}</td> <td>${depositDetails.DPST_NUM}</td> <td>${depositDetails.PMT_STS}</td> </tr> </c:forEach> </table> </form> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/39618893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why do we extend JpaRepository Interface and not implements it TestRepository ***extends*** JpaRespotiroy<Test,Long> JpaRepository is an interface. Why do we extend it and not implement it as we know in Java? As far as I know, interfaces are implemented, not extended. Can somebody explain to me please? A: I assume your code looks like interface TestRepository extends JpaRepository<Test, Long> So TestRepository is an interface and interfaces can extend other interfaces not implement interfaces. The TestRepository will be implemented from Spring Data JPA during runtime based on the SimpleJpaRepository https://github.com/spring-projects/spring-data-jpa/blob/master/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java A: In Java * *Class extends Class class Test Extends Thread *interface Extend interface public interface TestI extends Runtime *class implements interface public class Test implements Runnable
{ "language": "en", "url": "https://stackoverflow.com/questions/58881221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to handle API requests with Record Limits using R I do not have any code to share, but am looking for advice on the best way to handle API record limits. I am pulling data for a restful api service and the record limit is 1000 records. The data goes back about three years. I am using HTTR package in R to use a GET request with multiple parameters. I want to be able to pull as much data into memory that R can handle which in my experience is around 2 million records. Loops do not seem ideal. I managed to create a list of date ranges (about 30 day range) which when created into a dataframe leaves me with about 40 dataframes where about half are still reaching a record limit of 1000 rows. The date ranges do not overlap. The only thing I can think of is to make the query small enough so that the data pulled back is not reaching or exceeding the record limit and to then do a rbind on all the data. Is there any workarounds for querying restful api's that have these record limits. If not, then my approach may be to query small enough date ranges and loop the GET request until it has queried all date ranges in my list and cache the files. Then perhaps query from the cached files. Is there a better approach?
{ "language": "en", "url": "https://stackoverflow.com/questions/66123340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Illegal State Exception in mediaplayer.prepare android I am using a method in asynctask in the class VideoSurfaceView. But I am getting crash. I tried other ways too but didn't worked. Below is the code: ...... public class VideoSurfaceView extends SurfaceView implements SurfaceHolder.Callback { private static final String TAG = "VideoSurfaceView"; private MediaPlayer mMediaPlayer; private String mVideoPath = ""; private ScreenSaverView.OnVideoPrepareListener onVideoPrepareListener; private Bitmap mPreviewBitmap; private boolean locking = false; private boolean lockResult = false; private boolean reading = false; public VideoSurfaceView(Context context) { super(context); init(); } private void init() { LogD.i(TAG, "init"); SurfaceHolder mSurfaceHolder = getHolder(); mSurfaceHolder.addCallback(this); } @Override public void surfaceCreated(SurfaceHolder holder) { LogD.i(TAG, "surfaceCreated"); if (!getVideoPath().isEmpty()) { initVideoPlayer(); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { LogD.i(TAG, "surfaceChanged"); } @Override public void surfaceDestroyed(SurfaceHolder holder) { LogD.i(TAG, "surfaceDestroyed"); if (mMediaPlayer != null) { if (mMediaPlayer.isPlaying()) { mMediaPlayer.stop(); } mMediaPlayer.release(); mMediaPlayer = null; } } private void initVideoPlayer() { Canvas canvas = getHolder().lockCanvas(); if (mPreviewBitmap != null && canvas != null) { int w = getWidth(); int h = getHeight(); Rect src = new Rect(0, 0, mPreviewBitmap.getWidth(), mPreviewBitmap.getHeight()); Rect dst = new Rect(0, 0, w, h); LogD.d(TAG, "drawFirstFrame:view w: " + getWidth() + " h:" + getHeight()); canvas.drawBitmap(mPreviewBitmap, src, dst, null); getHolder().unlockCanvasAndPost(canvas); } else if (canvas != null){ canvas.drawColor(Color.WHITE); getHolder().unlockCanvasAndPost(canvas); } boolean needClose = onVideoPrepareListener.onPrepare(); if (needClose) { LogD.d(TAG, "initVideoPlayer needClose return: "); return; } LogD.i(TAG, "initFirstPlayer()"); mMediaPlayer = new MediaPlayer(); mMediaPlayer.setVolume(0, 0); mMediaPlayer.setDisplay(getHolder()); startPlayFirstVideo(); } private void startPlayFirstVideo() { new AsyncTask<Void, Void, FileCacheMediaDataSource>() { @Override protected FileCacheMediaDataSource doInBackground(Void... voids) { locking = true; lockResult = false; reading = true; new Thread(new Runnable() { @Override public void run() { LockResult result = LockManager.getInstance().lock(LockReason.DISK_SCREENSAVER_READ_ACCESS); lockResult = result.isLockSuccess(); if (!reading && lockResult) { LockManager.getInstance().unlock(LockReason.DISK_SCREENSAVER_READ_ACCESS); } locking = false; } }).start(); String path = AppConst.SCREEN_SAVER_MEDIA_PATH + mVideoPath; FileCacheMediaDataSource dataSource = new FileCacheMediaDataSource(path); if (!locking && lockResult) { LockManager.getInstance().unlock(LockReason.DISK_SCREENSAVER_READ_ACCESS); } reading = false; return dataSource; } @Override protected void onPostExecute(FileCacheMediaDataSource dataSource) { super.onPostExecute(dataSource); if (mMediaPlayer == null) { return; } if (dataSource.getSize() == -1) { LogD.d(TAG, "showErrorScreenSaver"); screenSaverError(); return; } try { // stop and reset media player mMediaPlayer.stop(); mMediaPlayer.reset(); mMediaPlayer.setDataSource(dataSource); mMediaPlayer.setLooping(true); mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mMediaPlayer.start(); } }); mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mediaPlayer, int i, int i1) { return false; } }); mMediaPlayer.prepare(); } catch (IOException e) { LogD.i(TAG, "startPlayFirstVideo = " + e.toString()); } } }; } private void screenSaverError() { if (videoSurfaceCallBack != null) { videoSurfaceCallBack.onError(); } } public String getVideoPath() { return mVideoPath; } public void setOnVideoPrepareListener(ScreenSaverView.OnVideoPrepareListener onVideoPrepareListener) { this.onVideoPrepareListener = onVideoPrepareListener; } public void setPreviewBitmap(Bitmap bitmap){ mPreviewBitmap = bitmap; } public void setVideoPath(String videoPath) { mVideoPath = videoPath; Bitmap bitmap = mPreviewBitmap; if (bitmap != null) { int videoWidth = bitmap.getWidth(); int videoHeight = bitmap.getHeight(); float max = Math.max((float) videoWidth / (float) 1024,(float) videoHeight / (float) 520); videoWidth = (int) Math.ceil((float) videoWidth / max); videoHeight = (int) Math.ceil((float) videoHeight / max); LogD.d(TAG, "setVideoPath LayoutParams videoWidth:"+videoWidth+" videoHeight:"+videoHeight); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(videoWidth, videoHeight); layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT); setLayoutParams(layoutParams); } } private VideoSurfaceCallBack videoSurfaceCallBack; public void setVideoSurfaceCallBack(VideoSurfaceCallBack videoSurfaceCallBack) { this.videoSurfaceCallBack = videoSurfaceCallBack; } interface VideoSurfaceCallBack { void onError(); } } I am getting error as, 12-23 08:28:11.108 7759 7759 E AndroidRuntime: Process: com.example.custom, PID: 7759 12-23 08:28:11.108 7759 7759 E AndroidRuntime: java.lang.IllegalStateException 12-23 08:28:11.108 7759 7759 E AndroidRuntime: at android.media.MediaPlayer._prepare(Native Method) 12-23 08:28:11.108 7759 7759 E AndroidRuntime: at android.media.MediaPlayer.prepare(MediaPlayer.java:1274) 12-23 08:28:11.108 7759 7759 E AndroidRuntime: at com.example.custom.view.VideoSurfaceView$1.onPostExecute(VideoSurfaceView.java:155) 12-23 08:28:11.108 7759 7759 E AndroidRuntime: at com.example.custom.view.VideoSurfaceView$1.onPostExecute(VideoSurfaceView.java:106) 12-23 08:28:11.108 7759 7759 E AndroidRuntime: at android.os.AsyncTask.finish(AsyncTask.java:755) 12-23 08:28:11.108 7759 7759 E AndroidRuntime: at android.os.AsyncTask.access$900(AsyncTask.java:192) 12-23 08:28:11.108 7759 7759 E AndroidRuntime: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772) 12-23 08:28:11.108 7759 7759 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:107) 12-23 08:28:11.108 7759 7759 E AndroidRuntime: at android.os.Looper.loop(Looper.java:214) 12-23 08:28:11.108 7759 7759 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:7356) 12-23 08:28:11.108 7759 7759 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method) 12-23 08:28:11.108 7759 7759 E AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 12-23 08:28:11.108 7759 7759 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) I am getting error in mMediaPlayer.prepare();. Kindly let me know where exactly I need to fix this issue. I tried using mMeiaPlayer.perpareAsync too but didn't worked. A: You are probably trying to prepare the MediaPlayer when the MediaPlayer is in a wrong state. Check the MediaPlayer State Diagram. The prepare or prepareAsync methods can be called only if the MediaPlayer is in Initialized or Stopped state. Since the MediaPlayer state is not accessible, you could use this extension to check what's wrong with your MediaPlayer (remember to remove the external player listeners from your code before trying this) import android.content.Context import android.media.MediaPlayer import android.net.Uri import android.util.Log class AudioPlayer : MediaPlayer(), MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener, MediaPlayer.OnPreparedListener { enum class AudioPlayerState { IDLE, INITIALIZED, PREPARING, PREPARED, STARTED, STOPPED, PAUSED, PLAYBACK_COMPLETED, ERROR, END } var playerState: AudioPlayerState? = null set(value) { Log.d(javaClass.name, "Setting new player state $value") field = value } init { playerState = AudioPlayerState.IDLE setOnPreparedListener(this) setOnBufferingUpdateListener(this) setOnCompletionListener(this) setOnErrorListener(this) setOnInfoListener(this) } override fun setDataSource(context: Context, uri: Uri) { if (playerState != AudioPlayerState.IDLE) Log.e(javaClass.name, "Trying to set data source on player state $playerState") super.setDataSource(context, uri) playerState = AudioPlayerState.INITIALIZED } override fun prepare() { if (playerState != AudioPlayerState.INITIALIZED && playerState != AudioPlayerState.STOPPED) Log.e(javaClass.name, "Trying to prepare on player state $playerState") playerState = try { super.prepare() AudioPlayerState.PREPARED } catch (e: Exception) { e.printStackTrace() Log.e(javaClass.name, "Exception on audio player prepare ${e.message} with state $playerState") AudioPlayerState.ERROR } } override fun prepareAsync() { playerState = try { super.prepareAsync() AudioPlayerState.PREPARING } catch (e: Exception) { e.printStackTrace() Log.e(javaClass.name, "Exception on audio player prepare async ${e.message} with state $playerState") AudioPlayerState.ERROR } } override fun start() { if (playerState != AudioPlayerState.PREPARED && playerState != AudioPlayerState.STARTED && playerState != AudioPlayerState.PAUSED && playerState != AudioPlayerState.PLAYBACK_COMPLETED ) Log.e(javaClass.name, "Trying to start on player state $playerState") playerState = try { super.start() AudioPlayerState.STARTED } catch (e: Exception) { e.printStackTrace() Log.e(javaClass.name, "Exception on audio player start ${e.message} with state $playerState") AudioPlayerState.ERROR } } override fun stop() { if (playerState != AudioPlayerState.PREPARED && playerState != AudioPlayerState.STARTED && playerState != AudioPlayerState.STOPPED && playerState != AudioPlayerState.PAUSED && playerState != AudioPlayerState.PLAYBACK_COMPLETED ) Log.e(javaClass.name, "Trying to stop on player state $playerState") playerState = try { super.stop() AudioPlayerState.STOPPED } catch (e: Exception) { e.printStackTrace() Log.e(javaClass.name, "Exception on audio player stop ${e.message} with state $playerState") AudioPlayerState.ERROR } } override fun pause() { if (playerState != AudioPlayerState.STARTED && playerState != AudioPlayerState.PAUSED && playerState != AudioPlayerState.PLAYBACK_COMPLETED ) Log.e(javaClass.name, "Trying to pause on player state $playerState") playerState = try { super.pause() AudioPlayerState.PAUSED } catch (e: Exception) { e.printStackTrace() Log.e(javaClass.name, "Exception on audio player pause ${e.message} with state $playerState") AudioPlayerState.ERROR } } override fun seekTo(msec: Int) { if (playerState != AudioPlayerState.PREPARED && playerState != AudioPlayerState.STARTED && playerState != AudioPlayerState.PAUSED && playerState != AudioPlayerState.PLAYBACK_COMPLETED ) Log.e(javaClass.name, "Trying to seek to on player state $playerState") try { super.seekTo(msec) } catch (e: Exception) { e.printStackTrace() Log.e(javaClass.name, "Exception on audio player seek to ${e.message} with state $playerState") playerState = AudioPlayerState.ERROR } } override fun seekTo(msec: Long, mode: Int) { if (playerState != AudioPlayerState.PREPARED && playerState != AudioPlayerState.STARTED && playerState != AudioPlayerState.PAUSED && playerState != AudioPlayerState.PLAYBACK_COMPLETED ) Log.e(javaClass.name, "Trying to seek to with mode on player state $playerState") try { super.seekTo(msec, mode) } catch (e: Exception) { e.printStackTrace() Log.e(javaClass.name, "Exception on audio player seek to with mode ${e.message} with state $playerState") playerState = AudioPlayerState.ERROR } } override fun getCurrentPosition(): Int { if (playerState == null) return 0 if (playerState != AudioPlayerState.IDLE && playerState != AudioPlayerState.INITIALIZED && playerState != AudioPlayerState.PREPARED && playerState != AudioPlayerState.STARTED && playerState != AudioPlayerState.PAUSED && playerState != AudioPlayerState.STOPPED && playerState != AudioPlayerState.PLAYBACK_COMPLETED ) Log.e(javaClass.name, "Trying to get current position on player state $playerState") try { return super.getCurrentPosition() } catch (e: Exception) { e.printStackTrace() Log.e(javaClass.name, "Exception on audio player current position ${e.message} with state $playerState") playerState = AudioPlayerState.ERROR } return 0 } override fun isPlaying(): Boolean { if (playerState == null) return false if (playerState != AudioPlayerState.IDLE && playerState != AudioPlayerState.INITIALIZED && playerState != AudioPlayerState.PREPARED && playerState != AudioPlayerState.STARTED && playerState != AudioPlayerState.PAUSED && playerState != AudioPlayerState.STOPPED && playerState != AudioPlayerState.PLAYBACK_COMPLETED ) Log.e(javaClass.name, "Trying to get is playing on player state $playerState") try { return super.isPlaying() } catch (e: Exception) { e.printStackTrace() Log.e(javaClass.name, "Exception on audio player is playing ${e.message} with state $playerState") playerState = AudioPlayerState.ERROR } return false } override fun reset() { playerState = try { super.reset() AudioPlayerState.IDLE } catch (e: Exception) { e.printStackTrace() Log.e(javaClass.name, "Exception on audio player reset ${e.message} with state $playerState") AudioPlayerState.ERROR } } override fun release() { playerState = try { super.release() AudioPlayerState.END } catch (e: Exception) { e.printStackTrace() Log.e(javaClass.name, "Exception on audio player release ${e.message} with state $playerState") AudioPlayerState.ERROR } } override fun onPrepared(mp: MediaPlayer?) { if (playerState != AudioPlayerState.STARTED) { playerState = AudioPlayerState.PREPARED } } override fun onInfo(mp: MediaPlayer?, what: Int, extra: Int): Boolean { return false } override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean { playerState = AudioPlayerState.ERROR return false } override fun onCompletion(mp: MediaPlayer?) { playerState = AudioPlayerState.PLAYBACK_COMPLETED seekTo(0) } override fun onBufferingUpdate(mp: MediaPlayer?, percent: Int) { } } A: According to exception, mediaPlayer in wrong state. Since i cannot see how you have defined the mediaPlayer, i assume you reuse the mediaPlayer. If so, make sure to stop and reset mediaPlayer before set a new dataSource like following in onPostExecute; Read more on here: mediaPlayer @Override protected void onPostExecute(FileCacheMediaDataSource dataSource) { super.onPostExecute(dataSource); if (mMediaPlayer == null) { return; } if (dataSource.getSize() == -1) { LogD.d(TAG, "showErrorScreenSaver"); screenSaverError(); return; } try { // stop and reset media player mMediaPlayer.stop(); mMediaPlayer.reset(); // set datasource mMediaPlayer.setDataSource(dataSource); mMediaPlayer.setLooping(true); mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.start(); } }); mMediaPlayer.prepareAsync(); } catch (IOException e) { LogD.i(TAG, "startPlayFirstVideo = " + e.toString()); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/70938608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to reset to a specific commit? I have the following recent commits when I do "git log --oneline"...I want to reset to "8ec2027",I tried some rebase commands that didnot work..what is the exact command to do this? 2503013 code: cs release 1.2.3.47 269ed14 code: Fixed below issues due to which 2nd client is not associating to GO dca02a3 code: Donot allow the scan during WPS/EAPOL exchange. b2fee57 code: MCC Adaptive Scheduler 6af29c4 code: Not able to connect more then 10 STA 150aacd code: Fix the Max Tx power value in 5G band and .ini support for 11h 8ec2027 Merge "code: cs release 1.2.3.46" 9015b60 Merge "code: Quarky Support on Prima" ...... A: You want to reset not rebase. Rebasing is the act of replaying commits. Resetting is making the current commit some other one. you will need to save any work that you may have in your work directory first: git stash -u then you will make you current commit the one you want with git reset --hard 8ec2027 Optionally, after you can save where you were before doing this with: git branch -b temp HEAD@{1} see reflog documentation to see how this works. A: Probably this could also work out for you * *Create a new branch at 2503013 (this saves the changes after 8ec202) *git reset --hard 8ec2027
{ "language": "en", "url": "https://stackoverflow.com/questions/14314596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Instantiate const pointer to derived class I have an abstract base class Base that contains a pointer to another abstract base class BaseDataClass. I have derived classes for both classes, I'll call them Derived and DerivedDataClass. The Base does not know that DerivedDataClass exists, and in any case, I intend to later have multiple combinations of Base and BaseDataClass subclasses . In the derived class, I want the pointer to be set to an instance of the derived data class, but I don't want to accidentally be able to assign the pointer later on so I made it const. This obviously keeps me from assigning the pointer using new in the derived class's constructor. Is there a neat way to accomplish this while keeping the pointer const? class BaseDataClass { public: BaseDataClass(){} //some pure virtual methods }; class Base { public: Base(){} //some pure virtual methods protected: BaseDataClass * const data; //compiler complains if this isn't set }; //// elsewhere class DerivedDataClass : public BaseDataClass { public: DerivedDataClass(){} }; class Derived : public Base { public: Derived(){ data = new DerivedDataClass(); //also does not compile obviously } }; A: Const objects cannot be assigned to. You must set the value of the const member upon initialisation. If you initialise to null, then it will always be null. So, don't initialise to null. In order to let the derived class choose what to initialise it to, use a constructor argument: Base::Base(BaseDataClass *); You can use that argument to initialise the member. That said: * *If you use new in constructor, you should make sure that you eventually delete it or else you will leak memory. *You cannot delete through the pointer to base, because the destructor of the base is not virtual. *Bare owning pointers are a bad design. You should use smart pointers instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/57063133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Limit objects in Realm Results by condition in order to observe result I want to limit the objects in a realm results by some predicate in order to observe this results and update my UI based on its changes. I have seen several solutions arguing that because objects in realm are lazy-loaded there is no need to limit the query. However I would like the query to constrain results by the limit in order for change notifications to fire when the objects constrained by the limit changes. Let me give you an example: Suppose I have a package object: class Package: Object { @objc enum State: Int { case scheduled case delivered } @objc dynamic var state = State.scheduled @objc dynamic var deliveryDate = Date() } and I want to create a results of all packages that are scheduled AND ONLY the newest package that is delivered. How would I go about doing that? Is this even possible with a single Results that I could then observe for changes? UPDATE: Trying to be more clear about what I am looking for. Lets say I have the following packages in my realm: Package1 state: delivered deliveryDate: March 1st Package2 state: delivered deliveryDate: March 2nd Package3 state: delivered deliveryDate: March 3rd Package4 state: scheduled deliveryDate: March 4th Package5 state: scheduled deliveryDate: March 5th Package6 state: scheduled deliveryDate: March 6th and let's say that these packages change state on a daily basis. So on March 3rd the data would look as above, but on March 4th Package4 would have changed state to 'delivered'. I then want a results that would reflect the following on those two days: March 3rd: - Package3 (delivered) - Package4 (scheduled) - Package5 (scheduled) - Package6 (scheduled) March 4th: - Package4 (delivered) - Package5 (scheduled) - Package6 (scheduled) A: I going to attempt an answer but it may be off base. The objective is to have a single realm result that can be observed for changes and also know what the newest delivery is. Here's the code self.packageResults = realm.objects(Package.self).sorted(byKeyPath: "delivered", ascending: false) Then observe self.packageResults. Whenever there's a change the observe closure will fire and deliver the results, sorted descending so the most current delivery will be 'at the top' i.e. index 0. EDIT Based on a comment and update to the question there was a question whether this answer provides a solution. Now there is a bit more data, just a slight modification produces the desired result (almost, keep reading) self.packageResults = realm.objects(Package.self) .filter("deliveryDate => 20190303") .sorted(byKeyPath: "state", ascending: false) then add an observer to self.packageResults. (note that I am using an Int for the timestamp to keep it simple) To test, we use the data provided in the question with our observer code. The code prints the initial state of the data, and then prints the state after any delete, insert or modify. func doObserve() { self.notificationToken = self.packageResults!.observe { (changes: RealmCollectionChange) in switch changes { case .initial: print("initial load complete") if let results = self.packageResults { for p in results { print(p.deliveryDate, p.state.rawValue) } } break case .update(_, let deletions, let insertions, let modifications): if let results = self.packageResults { for p in results { print(p.deliveryDate, p.state.rawValue) } } then we run the code and add the observer. This is the output initial load complete 20190303 1 20190304 0 20190305 0 20190306 0 if we then change the package 20190304 to 'delivered' we get the following output 20190303 1 20190304 1 20190305 0 20190306 0 So we are getting the desired result. HOWEVER, according to the question, the conditions of the query change as the next query would be for dates 20190304 and after. If the conditions of the output change, the conditions of the query would have to change as well. In this case the desired result is to display the most currently delivered package each day, so the query would need to be updated each day to reflect that date. As a possible solution, change the Package object to include a watched property class Package: Object { @objc enum State: Int { case scheduled case delivered } @objc dynamic var state = State.scheduled @objc dynamic var deliveryDate = 0 @objc dynamic var watched = false } and update the query to only observe packages being watched, ignore ones not being watched (where watched = false) self.packageResults = realm.objects(Package.self) .filter("deliveryDate => 20190303 and watched == true") .sorted(byKeyPath: "state", ascending: false) Then, when you no longer need to know about an object, set it's watched property to false, and it will not be included in the results. Using the same process as above with this query, when changing 20190304 to delivered, we also change 20190303 watched property to false and the results are handle item delete, insert or mod 20190304 1 20190305 0 20190306 0 which appears to answer the question.
{ "language": "en", "url": "https://stackoverflow.com/questions/55046898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to Capture screen using DirectX AM trying to take screenshot with DirectX in VS 2008. But always i used to get black image . Can someone point me out, whats wrong happening with my code.. my snippet code looks like this: void CaptureScreen() { IDirect3DDevice9* pDirect3DDevice; IDirect3DSurface9* pRenderTarget=NULL; IDirect3DSurface9* pDestTarget=NULL; D3DDISPLAYMODE d3ddisplaymode; D3DPRESENT_PARAMETERS PresentParams; memset(&PresentParams, 0, sizeof(D3DPRESENT_PARAMETERS)); PresentParams.Windowed = TRUE; PresentParams.SwapEffect = D3DSWAPEFFECT_DISCARD; HWND h = ::FindWindow(0,"EIML"); IDirect3D9* direct=Direct3DCreate9(D3D9b_SDK_VERSION); direct->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, h, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &PresentParams,&pDirect3DDevice); if (pDirect3DDevice == NULL) return; HRESULT hr = pDirect3DDevice->GetRenderTarget(0, &pRenderTarget); hr = direct->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,&d3ddisplaymode); hr = pDirect3DDevice->CreateOffscreenPlainSurface(d3ddisplaymode.Width,d3ddisplaymode.Height,D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &pDestTarget, NULL); pDirect3DDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &pDestTarget ) ; hr = pDirect3DDevice->GetRenderTargetData(pRenderTarget,pDestTarget); hr = D3DXSaveSurfaceToFile("C:\\Image1.bmp", D3DXIFF_BMP, pDestTarget, NULL, NULL); pRenderTarget->Release(); pDestTarget->Release(); } Thank you.. A: Here's how I take a screenshot: IDirect3DSurface9 *offscreenSurface; d3dDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &offscreenSurface); D3DXSaveSurfaceToFile( filename, D3DXIFF_BMP, offscreenSurface, 0, 0 )
{ "language": "en", "url": "https://stackoverflow.com/questions/14851511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Advantages and Understanding of using Currying Function pattern in onClick Event handler in React I need some help in understanding the following working code for onClick EventHandler. A detailed explanation will be really appreciated in understanding why a function is returning another function here. const MyComponent = (props) => { const onClickHandler = (somearg) => (e) => { console.log(`somearg passed successfully is ${somearg}`) }; return ( <div onClick={onClickHandler(somearg)}> </div> ); }; export default MyComponent; A: simply this is whats happening when the code first run const MyComponent = (props) => { const onClickHandler = (somearg) => (e) => { console.log(`somearg passed successfully is ${somearg}`) }; return ( <div onClick={onClickHandler('some args')}> </div> ); }; * *When it sees onClick={onClickHandler(1)} it will run the code inside the onClick *Then onClickHandler is a function and we pass an argument as 1 and execute it, now it will return a another function with replaced values as below. (e) => { console.log(`somearg passed successfully is 1`); // see args gets replaced with the value. } *so now when we click on the div above function will be called. to make sure this is what exactly happening see the below Demo const MyComponent = (props) => { const onClickHandler = (somearg) => (e) => { console.log(`somearg passed successfully is ${somearg}`, new Date().getTime()) }; return ( <div onClick={onClickHandler(new Date().getTime())}> div </div> ); }; and you will see the times are different, which means clicked time and function created time is different. So if you are put a one function inside onClick as it will gets executed with the code executing, and will not respond to you clicks const MyComponent = (props) => { const onClickHandler = (e) => { console.log(`somearg passed successfully is`, new Date().getTime()) }; return ( <div onClick={onClickHandler(new Date().getTime())}> div </div> ); }; A: The pattern you're referring to is called "currying". I'll explain why that pattern can be useful later in the answer, but first let's try to understand exactly what's happening. As you've already identified, the onClickHandler function returns a new function, it doesn't actually add much outside of that. Now what this means is that when the component renders, onClickHandler will be called immediately. So writing this: <div onClick={onClickHandler('test')}> Will end up returning this: <div onClick={(e) => {console.log(`somearg passed successfully is ${somearg}`)}}> This is why here you're allowed to call the function in the JSX, even though (like you pointed out) you can't do that most other times. The reason is because it's the returned function that will actually handle the click. Now lets talk more about why this pattern is useful. somearg is vague, but we'll stick with it for now until we get to the other benefits. "currying" uses a closure to sort of "freeze" the value of somearg for use by the returned function. Looking at the above example of the returned function, somearg would appear to not exist. However, with a closure, somearg will not only be available, but will also retain the value of 'test'. So why use this pattern? This pattern allows you to reuse functions in ways otherwise not possible. Consider a usecase where we have 2 div's that should be clickable. They should both do the same thing, but it may be helpful to be able to distinguish which div was clicked in order to complete that operation. For simplicity, lets just say we have two div's, and when clicked we want each to log their order. Here's how you might do that without currying: const Example = () => { const onClickHandler1 = (e) => { console.log("I am the 1 div."); }; const onClickHandler2 = (e) => { console.log("I am the 2 div."); }; return ( <div> <div onClick={onClickHandler1}>1</div> <div onClick={onClickHandler2}>2</div> </div> ); } ReactDOM.render(<Example />, document.getElementById('root')); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div> The above works just fine, but our two functions have a lot of shared functionality. It seems unnecessary to have both. So one solution would be to use currying: const Example = () => { // Converted to longer form so its possible to console.log in the first function // It still operates identically to the short-hand form. const onClickHandler = (order) => { console.log("called with " + order); return (e) => console.log("I am the " + order + " div."); }; return ( <div> <div onClick={onClickHandler(1)}>1</div> <div onClick={onClickHandler(2)}>2</div> </div> ); } ReactDOM.render(<Example />, document.getElementById('root')); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div> As you can see in the above example, onClickHandler gets called twice as soon as the component renders. But the first time, order is "frozen" or "closed over" with the value of 1, and the second has the value of 2. This was a very simple example, but imagine you are looping over a dynamic set of data that should each return a clickable element. You could then pass an index or and id or some other variable to identify the element. Ultimately, this is just a pattern for function reuse. There are other ways to accomplish the same level of abstraction like using inline functions, but this is just for the sake of explaining currying and how it may be used.
{ "language": "en", "url": "https://stackoverflow.com/questions/62514396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: inline namespace technique for managing platform specific code in c++ I have seen usage of #ifdef macros ( example Eigen library ) to manage platform specific, but haven't seen any one use "inline namespace"s to manage platform specific code. The github repo belows gives specific code and example usage. https://github.com/dchichkov/curious-namespace-trick/wiki/Curious-Namespace-Trick I am wondering if it is a viable technique to use or if there are any gotchas that I am not able to see. Below is the code snippet : #include <stdio.h> namespace project { // arm/math.h namespace arm { inline void add_() {printf("arm add\n");} // try comment out } // math.h inline void add_() { // printf("common add\n"); // } inline namespace platform {inline void add() {add_();}} inline void dot_() { // add(); // } inline namespace platform {inline void dot() {dot_();}} } int main() { project::dot(); return 1; } Output : $g++ func.cpp -Dplatform=common ; ./a.out common add $ g++ func.cpp -Dplatform=arm ; ./a.out arm add A: There are at least two ways to achieve same results. First one with namespaces. Second one - with static functions in classes. With namespaces: #include <stdio.h> namespace GenericMath { void add(); void dot(); } namespace ArmMath { void add(); using GenericMath::dot; } namespace GenericMath { void add() { printf("generic add"); } void dot() { Math::add(); printf("generic dot"); } } namespace ArmMath { void add() { printf("arm add"); } using GenericMath::dot; } int main() { Math::dot(); return 1; } With classes: #include <stdio.h> class GenericMath { public: static void add(); static void dot(); }; class ArmMath : public GenericMath { public: static void add(); }; void GenericMath::add() { printf("generic add"); } void GenericMath::dot() { printf("generic dot"); Math::add(); } void ArmMath::add() { printf("arm add"); } int main() { Math::add(); Math::dot(); return 1; } IMO inline namespaces make code less readable and too verbose. A: Once issue is that unlike #ifdef, the compiler still compiles all the code that isn't for the current platform. So you can't use it for dealing with platform-specific APIs.
{ "language": "en", "url": "https://stackoverflow.com/questions/34937200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Python Regex Match sub-string I have the following string: spf=pass (sender IP is 198.71.245.6) smtp.mailfrom=bounces.em.godaddy.com; domainname.com.au; dkim=pass (signature was verified) header.d=godaddy.com;domainname.com.au; dmarc=pass action=none header.from=godaddy.com; With the following code: if "Authentication-Results" in n: auth_results = n['Authentication-Results'] print(auth_results) spf = re.match(r"spf=(\w+)", auth_results) if spf: spf_result = spf.group(1) dkim = re.match(r"^.*dkim=(\w+)", auth_results) print(dkim) if dkim: dkim_result = dkim.group(1) The SPF always matches but the DKIM doesn't: print(dkim) = None According to the regex testers online it should: https://regex101.com/r/ZkVg74/1 any ideas why it's not i also tried these: dkim = re.match(r"dkim=(\w+)", auth_results) dkim = re.match(r"^.*dkim=(\w+)", auth_results, re.MULTILINE) A: . does not match a newline character by default. Since the dkim in your test string is on the second line and your regex pattern tries to match any non-newline character from the beginning of the string with ^.*, it would not find dkim on the second line. You should either use the re.DOTALL flag to allow . to match a newline character: dkim = re.match(r"^.*dkim=(\w+)", auth_results, flags=re.DOTALL) or remove the unnecessary match from the beginning of the string altogether: dkim = re.search(r"dkim=(\w+)", auth_results) A: First, re.match works from the beginning. so your r"dkim=(\w+)" trial doesn't work. Second, the . symbol matches characters except the new line character. If you want it to, you should explictly force it using re.S or re.DOTALL flag. Also, you can use [\s\S] or [\w\W] to match any characters. Try this: re.match(r"^[\s\S]*dkim=(\w+)", auth_results).group(1) or this: re.match(r"^.*dkim=(\w+)", auth_results, re.DOTALL).group(1)
{ "language": "en", "url": "https://stackoverflow.com/questions/52694599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to verify Azure AD token with NestJS application I'm trying to verify Azure AD token with my NestJS backend application. I'm logging to Azure AD using React frontend application and, for now, grab access_token from the response manually. Then I have this guard in NestJS: @Injectable() export class AzureADStrategy extends PassportStrategy( BearerStrategy, 'azure-ad', ) { constructor() { super({ identityMetadata: `https://login.microsoftonline.com/${tenantID}/v2.0/.well-known/openid-configuration`, clientID, clientSecret, loggingLevel: 'debug', loggingNoPII: false }); } async validate(response: any) { console.log(response); } } export const AzureGuard = AuthGuard('azure-ad'); When i apply it on some endpoint i'm trying to fetch this URL, like: curl localhost:9000/test --header 'Authorization: Bearer xyz' But i'm not able to authenticate and i get this error log: {"name":"AzureAD: Bearer Strategy","hostname":"<hostname>","pid":1713974,"level":30,"msg":"authentication failed due to: invalid signature","time":"2022-11-03T13:00:51.213Z","v":0} How should i configure it to make it work? A: I'm assuming you've been able to login ok and then pass the details to the API and you're user/s are registered under the APP. On validate, this is what i have and works fine. async validate(data) { return data; } This is the example i followed to get it working - https://medium.com/adidoescode/azure-ad-for-user-authentication-with-vue-and-nestjs-4dab3e96d240
{ "language": "en", "url": "https://stackoverflow.com/questions/74303571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: monitor process for failure I am working on a simple fuzzing tool that involves generating valid instances of some file type and monitoring the program under test for failure. A key component to this tool is a process monitor module: This module should provide functions that, given a strings representing a program path and arguments (e.g., corrupt.py and random_file.wav) indicates if calling currupt.py random_file.wav triggers some error. What's the simplest way to define a function that monitors such a process for hanging or throwing an error in OCaml? I plan to run such a function on loop, so diverting side effects (e.g., content printed to std.out) is critical. The type signature of such a function should be something along the lines of bytes -> int, where int has some associated meaning (e.g., 0 -> healthy exit). Additionally, I understand that the halting problem makes it impossible to tell if halting is unexpected behavior or not, so I'm fine with drawing the line at an arbitrary wait time. A: You may start with the Unix "High-level process and redirection management" functions, e.g., create_process prog args new_stdin new_stdout new_stderr is a generic function that will create a process that runs a program, and it allows you to redirect the channels. The created process will run asynchronously, so you can either peek it with waitpid's WNOHANG flag, or just block until it ends (probably the latter shouldn't work for you). Probably, the following interface should suffice your needs: module Monitor : sig val start : string -> t val terminate : t -> unit val on_finish : t -> (int -> unit) -> unit ... end or you can just simplify it to val monitor : string -> (int -> 'a) -> 'a if you don't want to have to manage monitor instances. Alternatively, you can take a look at the Lwt high-level process management library. It might save you quite a few keystrokes. There is also an alternative async unix library from Janestreet, that you may try.
{ "language": "en", "url": "https://stackoverflow.com/questions/41703970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Currency translation -- changing an elements place with angularjs I am using angular-translate in my project and I have 2 languages in it(Turkish&English). In Turkish, price of an item is written like this: 36₺, but in the US, it's like: $9. I don't want to use ng-if for every price in my project(there are lots of them) to change money sign's place. So is there a shorter way to accomplish that? A: Consider creating a custom filter that uses Number.prototype.toLocaleString() console.log(Number(8).toLocaleString('en',{style: 'currency', currency: 'USD'})) console.log(Number(8).toLocaleString('de',{style: 'currency', currency: 'EUR'})) A: Something like this: {{ lang == 'tr' ? '₺' + item.price : item.price + '$' }} Or write your own Custom Filter that parses your currency.
{ "language": "en", "url": "https://stackoverflow.com/questions/45660834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Code to logging ratio? What is the ideal code to logging ratio? I'm not used to writing logs as most of the applications I've developed have not had much logging. Recently though I've changed job, and I've noticed that you can't see the application code for the calls to log4net. I appreciate that this is useful but surely having too many debug statements is just as bad as not having any at all? There are logging statements that tell you when every method starts and finishes and what they are returning. and when pretty much anything is done. Would it not be easier to have some addon that used reflection to add the logging statements in at compile time so they didn't get in the way as you were trying to look at the code? Also in these days of powerful IDEs and remote debugging is that much logging really nescisary? A: That much logging is not necessary. There's no reason (in production) to know when each method starts and ends. Maybe you need that on certain methods, but having that much noise in the log files makes them nearly impossible to analyze effectively. You should log when important things happen such as errors, user logins (audit log), transactions started, important data updated... so on and so forth. If you have a problem that you can't figure out from the logs, then you can add more to it if necessary... but only if necessary. Also, just for your information, the adding logging in at compile time would be an example of what is called Aspect Oriented Programming. Logging would be the "cross cutting concern". A: I think "logs to code ratio" is a misunderstanding of the problem. In my job I once in a while have a situation where a bug in a Java program cannot be reproduced outside the production environment and where the customer does NOT want it to happen again. Then ALL you have available to you to fix the bug, is the information you yourself have put in the log files. No debugging sessions (that is forbidden in production environments anyway) - no poking at input data - nothing! So the logs are your time machine back to when the bug happened, and since you cannot predict ahead of time what information you will need to fix a bug yet unknown - otherwise you could just fix the bug in the first place - you need to log lots of stuff... Exactly WHAT stuff depends on the scenario, but basically enough to ensure that you are never in doubt what happens where :) Naturally this means that a LOT of logging will happen. You will then create two logs - one with everything which is only kept around for long enough to ensure that you will not need it, and the other one with non-trivial information which can be kept for a lot longer. Dismissing logging as excessive, is usually done by those who have not had to fix a bug with nothing else to go by :) A: Since log4net does a great job at not clogging up the resources, I tend to be a little verbose on logging because when you have to change to debug mode, the more info you have, the better. Here's what I typically log: DEBUG Level * *Any parameters passed into the method *Any row counts from result sets I retrieve *Any datarows that may contain suspicious data when being passed down to the method *Any "generated" file paths, connection strings, or other values that could get mungled up when being "pieced together" by the environment. INFO Level * *The start and end of the method *The start and end of any major loops *The start of any major case/switch statements ERROR Level * *Handled exceptions *Invalid login attempts (if security is an issue) *Bad data that I have intercepted forreporting FATAL Level * *Unhandled exceptions. Also having a lot of logging details prevents me from asking the user what they were doing when they got the error message. I can easily piece it together. A: When you come across a bug during the beta release of your application and can't reproduce it, you know that you should have done excessive logging. Same way if a client reports a bug but you can't reproduce it an excessive logging feature can save the day. A: When you have a customer scenario (i.e., someone whose machine you don't get physical access to), the only things that are "too much logging" are repainting functions and nearly anything called by them (which should be nearly nothing). Or other functions that are called 100's of times per second during operation (program startup is ok, though, to have 100's of calls to get/set routines logged because, in my experience, that's where most of the problems originate). Otherwise, you'll just be kicking yourself when you're missing some key log point that would definitively tell you what the problem is on the user's machine. (Note: here I'm referring to the logging that happens when trace mode is enabled for developer-oriented logs, not user-oriented normal operation logs.) A: I personally believe that first of all there is no hard and fast rule. I have some applications that log a LOT, in and out of methods, and status updates through the middle. These applications though are scheduled processes, run hands off, and the logs are parsed by another application that stores success/failure. I have found that in all reality, many user applications don't need large amounts of logging, as really if issues come up you will be debugging to trace the values there. Additionally you typically don't need the expense of logging. However, it really depends on the project. A: How many of those lines are logging by default? I've worked on a system very much like what you describe - just booting it up would cause over 20MB of logs to be written if logging was cranked way up, but even debugging we didn't turn it all the way up for all modules. By default it would log when a module of code was entered, and major system events. It was great for debugging since QA could just attach a log to a ticket, and even if it wasn't reproducible you could see what was going on when the problem happened. If you have serious multithreading going on then logging is still better than any IDE or debugger I've worked with. A: In my line of work, I write a lot of Windows services. For me, logging isn't a luxury; it's actually my only UI. When we deploy to production, we lose access to debugging and even the databases to which our services write and without logging we would have no way of knowing any specifics of issues that arise. Having said that, I do believe that a concise logging style is the best approach. Log messages tend to be limited to the business logic of the application such as "received message from account xxx" than "entered function yyy". We do log exceptions, thread starts, echoing of environment settings and timings. Beyond that, we look to the debugger to identify logical errors in the development and QA phases. A: I find that logging is much less necessary since I've started using TDD. It makes it much easier to determine where bugs lie. However, I find that logging statements can help understand what's going on in code. Sure, debuggers help give you a low-level idea of what's happening. But I find it easier when I can match a line of output to a line of code if I want to get a high level view of what's happening.. However, one thing that I should add is this: make sure your log statements include the module that the log statement is in! I can't count the number of times I've had to go back through and find where a log statement actually lies. A: Complete log files are amazingly useful. Consider a situation where your application is deployed somewhere like a bank. You can't go in there and debug it by hand and they sure aren't going to send you their data. What you can get is a complete log which can point you to where the problem occured. Having a number of log levels is very helpful. Normally the application would run in a mode such that it only reports on fatal errors or serious errors. When you need to debug it a user can switch on the debug or trace output and get far more information. The sort of logging you're seeing does seem excessive but I can't really say it is for certain without knowing more about the application and where it might be deployed. A: Also in these days of powerful IDEs and remote debugging is that much logging really nescisary? Yes, absolutely, although the mistake that many unskilled developers make is to try to fix bugs using the wrong method, usually tending towards logging when they should be debugging. There is a place for each, but there are at least a few areas where logging will almost always be necessary: * *For examining problems in realtime code, where pausing with the debugger would effect the result of the calculation (granted, logging will have a slight impact on timing in a realtime process like this, but how much depends greatly on the software) *For builds sent to beta testers or other colleagues who may not have access to a debugger *For dumping data to disk that may not be easy to view within a debugger. For instance, certain IDE's which cannot correctly parse STL structures. *For getting a "feel" of the normal flow of your program *For making code more readable in addition to commenting, like so: // Now open the data file fp = fopen("data.bin", "rb"); The above comment could just as easily be placed in a logging call: const char *kDataFile = "data.bin"; log("Now opening the data file %s", kDataFile); fp = fopen(kDataFile, "rb"); That said, you are in some ways correct. Using the logging mechanism as a glorified stack-trace logger will generate very poor quality logfiles, as it doesn't provide a useful enough failure point for the developer to examine. So the key here is obviously the correct and prudent use of logging calls, which I think boils down to the developer's discretion. You need to consider that you're essentially making the logfiles for yourself; your users don't care about them and will usually grossly misinterpret their contents anyways, but you can use them to at least determine why your program misbehaved. Also, it's quite rare that a logfile will point you to the direct source of a certain bug. In my experience, it usually provides some insight into how you can replicate a bug, and then either by the process of replicating it or debugging it, find the cause of the problem. A: There is actually a nice library for adding in logging after the fact as you say, PostSharp. It lets you do it via attribute-based programming, among many other very useful things beyond just logging. I agree that what you say is a little excessive for logging. Some others bring up some good points, especially the banking scenario and other mission critical apps. It may be necessary for extreme logging, or at least be able to turn it on and off if needed, or have various levels set. A: I must confess that when started programming I more or less logged all details as described by "Dillie-O". Believe me... It helped a lot during initial days of production deployment where we heavily relied on log files to solve hundreds of problems. Once the system becomes stable, I slowly started removing log entries as their value add started diminishing. (No Log4j at those point in time.) I think, the ratio of code-to-log entries depends on the project and environment, and it need not be a constant ratio. Nowadays we've lot of flexibility in logging with packages like Log4j, dynamic enabling of log level, etc. But if programmers doesn't use it appropriately, such as when to use, when NOT to use INFO, DEBUG, ERROR etc. as well as details in log messages (I've seen log message like, "Hello X, Hello XX, Hello XXX, etc." which only the programmer can understand) the ratio will continue to be high with less ROI. A: I think another factor is the toolset/platform being used and the conventions that come with it. For example, logging seems to be quite pervasive in the J(2)EE world, whereas I can't remember ever writing a log statement in a Ruby on Rails application.
{ "language": "en", "url": "https://stackoverflow.com/questions/153524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "49" }
Q: Unit test 'success' and 'error' observable response in component for Angular 2 I'm writing a unit test for a component that makes a call to a service OnInit. If the response is a 'success' one action taken and another for an 'error'. What is the best way to test both cases? I've created a simplified version of the component and unit test. Something that I could easily test against in both cases. I've attempted to implement the solution here but I must be off on the implementation. I've also attempted to throw an error as you will see in the spec and comments. Component @Component({ selector: 'app-observer-throw-unit-test', template: '<p>{{ data }}</p>' }) export class ObserverThrowUnitTestComponent implements OnInit { public data: string; constructor(private _observerThrowService: ObserverThrowService) { } ngOnInit() { this._observerThrowService.getData().subscribe( (data) => { this.data = data; }, (error) => { this.redirect() } ) } redirect() { this.data = "Redirecting..."; } } Spec const data: string = "Lorem ipsum dolor sit amet."; const ObserverThrowServiceStub = { error: false, getData() { return Observable.create((observer) => { if(this.error) { observer.error(new Error()); } else { observer.next(data); } observer.complete(); }) } } describe('ObserverThrowUnitTestComponent', () => { let component: ObserverThrowUnitTestComponent; let fixture: ComponentFixture<ObserverThrowUnitTestComponent>; let _observerThrowService: ObserverThrowService; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ObserverThrowUnitTestComponent ], providers: [ { provide: ObserverThrowService, useValue: ObserverThrowServiceStub }, ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ObserverThrowUnitTestComponent); component = fixture.componentInstance; fixture.detectChanges(); _observerThrowService = TestBed.get(ObserverThrowService); }); it('should set "data" to "Lorem ipsum dolor sit amet." on success', () => { expect(component.data).toEqual("Lorem ipsum dolor sit amet."); }); it('should set "data" on "Redirecting..." on error',() => { ObserverThrowServiceStub.error = true; // spyOn(_observerThrowService, "getData").and.returnValue(Observable.throw("error")); // This did not work and returned : TypeError: undefined is not a constructor (evaluating 'Observable_1.Observable.throw("error")') in src/test.ts spyOn(_observerThrowService, "getData") expect(component.data).toEqual("Redirecting..."); }); it('should set "data" on "Redirecting..." on error',() => { // This works after setting error to true in the previous test spyOn(_observerThrowService, "getData") expect(component.data).toEqual("Redirecting..."); }); }); A: someObj.ObservableReturninFunction().subscribe( (obj)=> { conosle.log(obj.message); }, (err)=>{ console.log(err.message); } }); when success; SpyOn(someObj,"ObservableReturninFunction").and.returnValue( Observable.of({message: "something"})); when erro: SpyOn(someObj,"ObservableReturninFunction").and.returnValue( Observable.throw({message: "some-error"})); A: I would create two mocks - one that throws an error: class ObserverThrowServiceStub { getData() { return Observable.throw(new Error('Test error')); } } and one that returns successfully. class ObserverSuccessServiceStub { getData() { return Observable.from(data); } } Then, instead of providing the same mock service to all tests, you provide the failing/successful mock service appropriately depending on the test in question (obviously you'll need to move your module configuration into a configurable method that you call from within each test rather than in the .beforeEach() code. There is a really nice article on testing Angular services using Observables here (which uses exactly this model): http://www.zackarychapple.guru/angular2/2016/11/25/angular2-testing-services.html A: You can use Jasmine Spy to spyOn your mock service class's method which returns an Observable. More detail is here: Jasmine - how to spyOn instance methods A: I would add a public error flag in the stub. Then I can create the stub once in beforeEach() and just update the error flag in each test case to decide which version of getData I want to use. class ObserverServiceStub { public error = false; getData() { if (this.error) { return Observable.throw(new Error('Test error')); } else { return Observable.from(data); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/45084568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: what is matplotlib's retina display mode? What is retina display mode in matplotlib? I searched a lot and only thing I get is how to use it in jupyter notebook. How is it different? Does it have something to do with apple's retina display? EDIT: In jupyter notebook, this is how the code is written: import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_format='retina' My doubt is what does this retina mode does? How is it different from other modes? A: It's just that the definition of the displayed plot is a bit better: retina quality. Any display with retina resolution will make the figures look better - if your monitor's resolution is sub-retina than the improvement will be less noticeable.
{ "language": "en", "url": "https://stackoverflow.com/questions/54312924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Store Values generated in a while loop on a list in python Just a simple example of what i want to do: numberOfcalculations = 3 count = 1 while contador <= numberOfcalculations: num = int(input(' number:')) num2 = int(input(' other number:')) calculate = num * num2 print(calculate) count = count + 1 How do i store the 3 different values that "calculate" will be worth in a list []? A: When you initialize calculate as list type you can append values with + operator: numberOfcalculations = 3 count = 1 calculate = [] while count <= numberOfcalculations: num = int(input(' number:')) num2 = int(input(' other number:')) calculate += [ num * num2 ] print(calculate) count = count + 1 Also you have to change contador somehow or you will end up in an infinite loop maybe. I used count here instead to give the user the ability to input 3 different calculations.
{ "language": "en", "url": "https://stackoverflow.com/questions/74650866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: flutter markdown extension I want to detect and do something when there is a message that starts with the @ sign. How do I do this with the extension set feature? I added a new class and extended it return Bubble( style: BubbleStyle( radius: const Radius.circular(4), elevation: 1, color: Theme.of(context).scaffoldBackgroundColor, margin: const BubbleEdges.only(bottom: 4.0, top: 4.0), ), child: Container( constraints: const BoxConstraints(minWidth: 0.0, maxWidth: 240), child: MarkdownBody( extensionSet: md.ExtensionSet( md.ExtensionSet.gitHubFlavored.blockSyntaxes, [X(), ...md.ExtensionSet.gitHubFlavored.inlineSyntaxes], ), onTapLink: (text, href, title) { launchUrlString(href ?? text); print(text); print(href); print(title); }, data: body, ), ), ); } } class X extends md.InlineSyntax { X() : super("/(^|\s)@\w+/g"); @override bool onMatch(md.InlineParser parser, Match match) { print("eşleşti"); return true; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/74985456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generator in threading I have a generator that returns me a certain string, how can I use it together with this code? from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(4) results = pool.map(my_function, my_array) Instead of the array that is passed above, I use a generator, since the number of values does not fit in the array, and I do not need to store them. Additional question: In this case, the transition to the next iteration should be carried out inside the function? A: Essentially the same question that was posed here. The essence is that multiprocessing will convert any iterable without a __len__ method into a list. There is an open issue to add support for generators but for now, you're SOL. If your array is too big to fit into memory, consider reading it in in chunks, processing it, and dumping the results to disk in chunks. Without more context, I can't really provide a more concrete solution. UPDATE: Thanks for posting your code. My first question, is it absolutely necessary to use multiprocessing? Depending on what my_function does, you may see no benefit to using a ThreadPool as python is famously limited by the GIL so any CPU bound worker function wouldn't speed up. In this case, maybe a ProcessPool would be better. Otherwise, you are probably better off just running results = map(my_function, generator). Of course, if you don't have the memory to load the input data, it is unlikely you will have the memory to store the results. Secondly, you can improve your generator by using itertools Try: import itertools import string letters = string.ascii_lowercase cod = itertools.permutations(letters, 6) def my_function(x): return x def dump_results_to_disk(results, outfile): with open(outfile, 'w') as fp: for result in results: fp.write(str(result) + '\n') def process_in_chunks(generator, chunk_size=50): accumulator = [] chunk_number = 1 for item in generator: if len(accumulator) < chunk_size: accumulator.append(item) else: results = list(map(my_function, accumulator)) dump_results_to_disk(results, "results" + str(chunk_number) + '.txt') chunk_number += 1 accumulator = [] dump_results_to_disk(results, "results" + str(chunk_number)) process_in_chunks(cod) Obviously, change my_function() to whatever your worker function is and maybe you want to do something instead of dumping to disk. You can scale chunk_size to however many entries can fit in memory. If you don't have the disk space or the memory for the results, then there's really no way for you process the data in aggregate
{ "language": "en", "url": "https://stackoverflow.com/questions/67814650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MQ | Channel RETRYING status I have started exploring MQ series and I noticed Sender channel in RETRYING status after SHORTRTR are exhausted. I have also noticed client applications couldn't connect to MQ when Sender channel was in RETRYING status. * *Is my understanding correct that client applications can't connect to MQ if Sender channel is in RETRYING status? *What happens client start connection with MQ and Sender channel is not RUNNING? *Does Sender channel status matter when client is initializing MQ connection? A: * *The ability for a client application to connect is almost entirely unrelated to the state of a sender channel. (I say almost because theoretically you could use up all the resources in your queue manager by having loads of retrying senders and then maybe they could affect clients). *When a client application makes a connection to a queue manager, the network connection is first caught by the listener, and then a running channel of type SVRCONN is started. This is a different type from a SENDER channel, and so there is no requirement to have a SENDER channel running for the client connection to be successful. *Sender channel status does not matter for the client to be able to connect. Lets' try to diagnose your two problems. Look in the queue manager AMQERR01.LOG (found in the data directory under \Qmgrs\<qm-name>\errors) and edit your question to add the errors you see in there. There should be errors that explain why the sender channel is retrying, and some to explain why the client cannot connect. It is possible that the problem with the client not being able to connect is because it is not even reaching the queue manager machine - in which case there will be nothing about that in the queue manager error log. In this case, you should also look in the AMQERR01.LOG on the client machine, this time in the data directory just under the errors folder (as no queue manager name there). You should also have seen some sort of error message or MQRC Reason code from the client application - you should tell us that too.
{ "language": "en", "url": "https://stackoverflow.com/questions/62509953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Robot: Backslash in EXECDIR, Windows path Underlying problem: I want to enable running robot tests using selenium 2 in a portable Firefox that's stored within EXECDIR. ${firefox_binary}= Evaluate sys.modules['selenium.webdriver.firefox.firefox_binary'].FirefoxBinary('${EXECDIR}${/}Firefox${/}App${/}Firefox${/}Firefox.exe') sys, selenium.webdriver ${firefox_profile}= Evaluate sys.modules['selenium.webdriver.firefox.firefox_profile'].FirefoxProfile('${EXECDIR}${/}Lib${/}SeleniumFirefoxProfile') sys, selenium.webdriver Create Webdriver Firefox firefox_binary=${firefox_binary} firefox_profile=${firefox_profile} That works fine if, instead of ${EXECDIR}, I use the actual path. EXECDIR is something like C:\Users\bart.simpson\workspace\projectname here. The issue is that a backslash, when followed by the b, is converted to the ASCII backslash character. The test log then says: Evaluating expression 'sys.modules['selenium.webdriver.firefox.firefox_profile'].FirefoxProfile('C:\Users\bart.simpson\workspace\projectname\Lib\SeleniumFirefoxProfile')' failed: OSError: [Errno 20047] Unknown error: 20047: 'C:\\Users\x08art.simpson\\workspace\\projectname\\Lib\\SeleniumFirefoxProfile' Of course I've tried using ${fixedExecDir}= Replace String ${EXECDIR} '\' '/' and such, but nothing ever changes the outcome. Ideas? Thanks. A: Try treating the path as a raw string literal, by putting an "r" before the quote immediately before ${EXECDIR}: ${firefox_binary}= Evaluate ....FirefoxBinary(r'${EXECDIR}${/}Firefox...') This should work because the robot variables are substituted before the string is passed to python, so the python interpreter only ever sees the complete string. If you are unfamiliar with python raw string literals, see this question: What exactly do “u” and “r” string flags do in Python, and what are raw string literals?
{ "language": "en", "url": "https://stackoverflow.com/questions/26918520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Select SVG element by inkskape:label attribute I have an external SVG loaded with the SVG Jquery plugin http://keith-wood.name/svg.html. One line of the SVG is: <g groupmode="layer" id="layer1" inkscape:label="myLabel"></g> I'm able to get the value of the label of that element by this line $('#layer1', svg.root()).attr("inkscape:label"); this will return the value "myLabel". How do I select the same element using that value? Tryed with var myElement = $('g[inkscape:label="myLabel"]', svg.root()); with no luck. Any suggestion? TIA! A: according to this SO post referencing the jquery docs, your best bet would be var myElement = $('g[inkscape\\:label="myLabel"]', svg.root());. A: It's been impossible for me to make it work as you request. The solution I have arrived, is duplicating the tag, but using an underscode instead of two dots, like this: $('path').each(function() { $(this).attr({ "inkscape_label" : $(this).attr('inkscape:label') }); }); Then I can select by the label I want like this: $('[inkscape_label = ... A: For me the only solution that worked was this one: const t = document.querySelectorAll('g') const layer = Array.from(t) .filter(t => t.getAttribute('inkscape:label') === 'myLabel')[0] A: The title isn't very descriptive so I ended up here when trying to figure out how to select it via CSS. In case it helps anyone else: <style> [inkscape\:label="MyNamedLayer"] { /*green*/ filter: invert(42%) sepia(93%) saturate(1352%) hue-rotate(87deg) brightness(119%) contrast(119%); filter: invert(48%) sepia(79%) saturate(2476%) hue-rotate(86deg) brightness(118%) contrast(119%); } </style>
{ "language": "en", "url": "https://stackoverflow.com/questions/15110866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pandas groupby cumulative sum ignore current row I know there's some questions about this topic (like Pandas: Cumulative sum of one column based on value of another) however, none of them fuull fill my requirements. Let's say I have a dataframe like this one . I want to compute the cumulative sum of Cost grouping by month, avoiding taking into account the current value, in order to get the Desired column.By using groupby and cumsum I obtain colum CumSum . The DDL to generate the dataframe is df = pd.DataFrame({'Month': [1,1,1,2,2,1,3], 'Cost': [5,8,10,1,3,4,1]}) A: IIUC you can use groupby.cumsum and then just subtract cost; df['cumsum_'] = df.groupby('Month').Cost.cumsum().sub(df.Cost) print(df) Month Cost cumsum_ 0 1 5 0 1 1 8 5 2 1 10 13 3 2 1 0 4 2 3 1 5 1 4 23 6 3 1 0 A: You can do the following: df['agg']=df.groupby('Month')['Cost'].shift().fillna(0) df['Cumsum']=df['Cost']+df['agg']
{ "language": "en", "url": "https://stackoverflow.com/questions/60709083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display Image with data using GridLayout or ListFragment Which one of the following method is best to fetch image and data from local database and display on a fragment. Model 1 : <ListFragment> <ListItem>Image+Data(below image)</ListItem> <ListItem>Image+Data(below image)</ListItem> <ListItem>Image+Data(below image)</ListItem> <ListItem>Image+Data(below image)</ListItem> <ListItem>Image+Data(below image)</ListItem> <ListItem>Image+Data(below image)</ListItem> <ListItem>Image+Data(below image)</ListItem> <ListItem>Image+Data(below image)</ListItem> </ListFragment> Model 2 : <Fragment> <GridLayout> <RelativeLayout>Image+Data(below image)</RelativeLayout> <RelativeLayout>Image+Data(below image)</RelativeLayout> <RelativeLayout>Image+Data(below image)</RelativeLayout> <RelativeLayout>Image+Data(below image)</RelativeLayout> <RelativeLayout>Image+Data(below image)</RelativeLayout> <RelativeLayout>Image+Data(below image)</RelativeLayout> <RelativeLayout>Image+Data(below image)</RelativeLayout> <RelativeLayout>Image+Data(below image)</RelativeLayout> </GridLayout> <Fragment> Note : I tried to use GridLayout for following reasons, * *Because display multiple columns on tablet landscape mode But the Gridlayout doesn't have adapter,so I think it may be complex to add child view dynamically. A: You should use GridView for this purpose. It has adapter. See an example here: http://developer.android.com/guide/topics/ui/layout/gridview.html For dealing with images, i would also take a look at https://github.com/nostra13/Android-Universal-Image-Loader it just makes my life so easy.
{ "language": "en", "url": "https://stackoverflow.com/questions/19451034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why doesn't belongs_to have a restrict_with_exception option for dependent? I have a model like: class ImportedReceipt < ApplicationModel # dependent: :restrict_with_exception is not allowed on belongs_to belongs_to: :payment before_destroy :allow_destroy def allow_destroy return false if payment true end end I want to disallow destroying an ImportedReceipt if it is linked to a Payment. I can do this by returning false from a before_destroy action. Is there a reason Rails doesn't allow :restrict_with_exception on belongs_to associations?
{ "language": "en", "url": "https://stackoverflow.com/questions/60105161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jenkins: Schedule Particular Stage with single pipeline I have a single pipeline where it' declarative and I've several stages such as below triggers via webhook. I would like to execute and scheduled Stage B at a certain time which can also run without trigger via webhook. Clearly it needs to run when triggers via webhook and also run when it will be schedule. Can I handle this without creating seperate job or pipeline in Jenkins ? stage('A'){ when{ beforeAgent true expression{return env.GIT_BRANCH == "origin/development"} } steps{ script{ //Do something } stage ('B'){ when { beforeAgent true expression{return env.GIT_BRANCH == "origin/development"} steps { script { //Run Tests } } } stage('C'){ when{ beforeAgent true expression{return env.GIT_BRANCH == "origin/development"} } steps{ script{ //Do something } A: You can discover what caused your pipeline to run. This may be cron trigger, manual trigger, code commit trigger, webhook trigger, comment on GitHub, upstream job, etc. (depending on plugins installed, the list may be long.) Here's and example of code to understand what the trigger was. This example sets the environment variable TRIGGERED_BY. def checkForTrigger() { def timerCause = currentBuild.rawBuild.getCause(hudson.triggers.TimerTrigger.TimerTriggerCause) if (timerCause) { echo "Build reason: Build was started by timer" env.TRIGGERED_BY = 'timer' return } def userCause = currentBuild.rawBuild.getCause(hudson.model.Cause$UserIdCause) if (userCause) { echo "Build reason: Build was started by user" env.TRIGGERED_BY = 'user' return } def remoteCause = currentBuild.rawBuild.getCause(hudson.model.Cause$RemoteCause) if (remoteCause) { echo "Build reason: Build was started by remote script" env.TRIGGERED_BY = 'webhook' return } // etc. println "We haven't caught any of triggers, might be a new one, here is the dump" def causes = currentBuild.rawBuild.getCauses() println causes.dump() } I think that a build might have more than one trigger, if so the order of your clauses is important. Once you have this figured out, you can run your stages only when the trigger fits your definition. stage ('B'){ when { beforeAgent true anyOf { expression{return env.GIT_BRANCH == "origin/development"} environment name: 'TRIGGERED_BY', value: 'timer' environment name: 'TRIGGERED_BY', value: 'webhook' } A: Not in a clean or first-class manner, but yes you can do it effectively. For any job which has been run at least once, you can click "replay" for the previous run. You will then be presented with the Jenkinsfile in a text edit box. At this point you can perform any edit you want to the Jenkinsfile (including pasting in a completely unrelated Jenkinsfile if you wanted) and Jenkins will execute the modified version. For your specific case, you can delete all the stages you don't want to re-run and just leave behind the one (or two, etc) you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/61930192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SocialTest - com.adobe.ane.social SocialUI could not be found I'm trying to run the sample SocialTest, but this error always appears: VerifyError: Error # 1014: Class :: com.adobe.ane.social SocialUI could not be found. The same applies to any other sample ANE, from gaming sdk... FlashBuilder 4.7 Adobe AIR 3.6 Gaming SDK 1.0.2 iPhone 3gs 6.1.3 Simulator sdk 6.0 A: You forgot to add the ANE to your package. Project > Properties > Flex Build Packaging > (Your OS) > Native Extentions... Add...
{ "language": "en", "url": "https://stackoverflow.com/questions/15639313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SSIS: What are rules to import date fields from text files to SQL table I have created a package in |SSIS 2012. The package basically connect to a text files in a predefined location and load data from the text files to the SQL database table. I have one DOB field which is DATE TYPE in the destination SQL table and it was returning error: conversion failed and date out-of-range. I did not have any luck converting DOB column using the CAST or CONVERT funtion: CONVERT(date, DOB, 103) What am I doing wrong? A: You should use CAST() or CONVERT() functions, when you want convert varchar value to datetime https://msdn.microsoft.com/ru-ru/library/ms187928.aspx A: I had some bad data in my input files for the DOB column. For example, DOB: 100-01-01, 29999-05-24; I tried to convert these dates using CONVERT function and it was returning error. So, I was just selecting records only with valid DOB dates using the query as below and after that I could convert the DOB without any error in this case: SELECT * FROM MyTableTest WHERE ISDATE(dob) <> 1
{ "language": "en", "url": "https://stackoverflow.com/questions/30664902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ClassNotFoundException Symfony UserBundle I'm developping a website on Symfony2, I want to intergrate FOSUserBundle. I am using Doctrine ORM User class. I've followed the installation steps but I got this error: ClassNotFoundException in AppKernel.php line 21: Attempted to load class "FOSUserBundle" from namespace "FOS\UserBundle". Did you forget a "use" statement for another namespace? AppKernel.php: public function registerBundles() { $bundles = array( ... new FOS\UserBundle\FOSUserBundle(), ); It looks correctly placed: FOSUserBundle.php is located in \vendor\friendsofsymfony\userbundle And the namespace is correct I think: namespace FOS\UserBundle; Other files: #config.yml fos_user: db_driver: orm firewall_name: main user_class: REMERA\PlatformBundle\Entity\User #routing.yml fos_user: resource: "@FOSUserBundle/Resources/config/routing/all.xml" #security.yml security: encoders: FOS\UserBundle\Model\UserInterface: bcrypt role_hierarchy: ROLE_ADMIN: ROLE_USER ROLE_SUPER_ADMIN: ROLE_ADMIN providers: fos_userbundle: id: fos_user.user_provider.username firewalls: main: pattern: ^/ form_login: provider: fos_userbundle csrf_provider: security.csrf.token_manager # Use form.csrf_provider instead for Symfony <2.4 logout: true anonymous: true access_control: - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/admin/, role: ROLE_ADMIN } I've been trying to solve this for hours, answers on other similar questions don't resolve my error. Am I missing something? Thanks in advance. A: How this was solved: try to clear the cache first. Then if it is still not working, composer remove, composer require and composer update again. – Brewal A: When you try to clear cache but its not getting cleared you should use --no-warmup option, this will make sure that you cache is re-generated and cache is not warmed up only. I think this can help you: php app/console cache:clear --env=prod --no-warmup or php app/console cache:clear --env=dev --no-warmup
{ "language": "en", "url": "https://stackoverflow.com/questions/30863601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scala cake pattern and multiproject In common-project I have this: trait DBProvider trait DBTableNamesProvider trait DefaultDBProvider extends DBProvider trait DefaultTableNames extends DBTableNamesProvider trait MyService extends DBProvider with DBTableNamesProvider object MyService { def apply() = new MyService with DefaultDBProvider with DefaultTableNames {} } In projectA which has a reference to common-project as a jar I wish to construct MyService projectA (has dependency on common-project): object MyOtherApp { trait MyOtherTableName extends DBTableNamesProvider val MyCustomService = MyService() with MyOtherTableName // will not compile how to reuse the module's MyService() with another implementation of one of the traits? } The above will not compile I cannot just call MyService() construction and override some of the dependencies. The above is what I wish to do, I wish to override from a different project the factory construction of MyService() apply with my own implementation of MyProjectATableNames is that possible in scala? if not what is the recommended way without code repetition? A: val MyCustomService = new MyService() with MyOtherTableName should work If you want to also inherit from the DefaultDBProvider and DefaultTableNames, you would have to either list them explicitly as well: val MyCustomService = new MyService() with MyOtherTableName with DefaultDBProvider with DefaultTableNames or create an intermediate trait in the common library: trait DefaultService extends MyService with DefaultDBProvider with DefaultTableNames A: You cannot override constructed type like that because MyService() is an object not a type anymore. So to reuse your code you might create a class like class ConfiguredMyService extends DefaultDBProvider with DefaultTableNames in the first app you can declare object MyService { def apply() = new ConfiguredMyService } and in the second val MyCustomService = new ConfiguredMyService with MyOtherTableName Note: Nowadays, Cake pattern is considered an anti-pattern, so I recommend you checkout Dependency Injection.
{ "language": "en", "url": "https://stackoverflow.com/questions/47657979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: URLClassLoader and Multi-release jar I use the URLClassLoader to dynamically load JDBC drivers into my application. My application is compiled under OpenJDK15. I cannot upgrade since some drivers would get issues under higher versions. One of the drivers is using truffle-api-22.2.0.jar, which has support for two Java versions: truffle-api-22.2.0.jar\META-INF\versions\11 and 17 When the jar is loaded, I get this exception: java.lang.UnsupportedClassVersionError: META-INF/versions/17/module-info has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 59.0 java.lang.UnsupportedClassVersionError: META-INF/versions/17/module-info has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 59.0 at java.base/java.lang.ClassLoader.defineClass1(Native Method) at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016) at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151) at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:825) at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:723) at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:646) at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:604) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:576) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522) at com.wisecoders.dbs.dbms.driver.model.a.a(DriverClassLoader.java:132) at com.wisecoders.dbs.dbms.driver.model.a.b(DriverClassLoader.java:110) at com.wisecoders.dbs.dbms.driver.model.a.a(DriverClassLoader.java:88) at com.wisecoders.dbs.dbms.driver.model.a.a(DriverClassLoader.java:66) at com.wisecoders.dbs.dbms.driver.model.a.<init>(DriverClassLoader.java:34) I used: urlClassLoader = new URLClassLoader( urlsArray, OneClassFromMyCode.class.getClassLoader() ); urlClassLoader.loadClass( className ); The URLClassLoader documentation states that this should work with multi-version jars. Which could be the issue?
{ "language": "en", "url": "https://stackoverflow.com/questions/73557790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Node not being removed from parent (spritekit) Create enemy touchesBegan and didBegin contact function My enemy node is not being removed from the scene every time my sword node touches it. I'm just wondering if anyone could explain to me what I'm doing wrong? (UPDATE BELOW) import SpriteKit import GameplayKit import AVFoundation class LevelTwo: SKScene, SKPhysicsContactDelegate{ var levelBg = SKSpriteNode(imageNamed: "level2") var hero = SKSpriteNode() var enemy = SKSpriteNode() var sword = SKSpriteNode() var health1 = SKSpriteNode(imageNamed: "playerhplv2") var health2 = SKSpriteNode(imageNamed: "playerhplv2") var health3 = SKSpriteNode(imageNamed: "playerhplv2") var musicPath = URL(fileURLWithPath: Bundle.main.path(forResource: "gameMusic", ofType: "mp3")!) var musicGamePlayer = AVAudioPlayer() var runMonster = SKAction() var waitMonster = SKAction() var sequenceMonster = SKAction() var repeatMonster = SKAction() enum CollisionNum: UInt32{ case swordNum = 1 case enemyNum = 2 case playerNum = 4 } override func didMove(to view: SKView) { self.physicsWorld.contactDelegate = self ///music do{ musicGamePlayer = try AVAudioPlayer(contentsOf: musicPath) musicGamePlayer.prepareToPlay() musicGamePlayer.numberOfLoops = -1 musicGamePlayer.play() } catch{ print(error) } //bg levelBg.position = CGPoint(x: 0, y: 0) levelBg.zPosition = 1 levelBg.size = levelBg.texture!.size() levelBg.setScale(1.25) self.addChild(levelBg) //hero let playerTexture = SKTexture(imageNamed: "main") hero = SKSpriteNode(texture: playerTexture) hero.position = CGPoint(x: 0, y: 0) hero.zPosition = 2 hero.setScale(0.6) hero.physicsBody = SKPhysicsBody(texture: playerTexture, size: CGSize(width: hero.size.width, height: hero.size.height)) hero.physicsBody!.categoryBitMask = CollisionNum.playerNum.rawValue hero.physicsBody!.collisionBitMask = CollisionNum.enemyNum.rawValue //player is allowed to bump into rocks and skulls hero.physicsBody!.contactTestBitMask = CollisionNum.enemyNum.rawValue // same as collisions hero.physicsBody!.isDynamic = false self.addChild(hero) //health1 health1.position = CGPoint(x: 130, y: 150) health1.zPosition = 3 health1.setScale(0.75) self.addChild(health1) //health2 health2.position = CGPoint(x: 230, y: 150) health2.zPosition = 3 health2.setScale(0.75) self.addChild(health2) //health3 health3.position = CGPoint(x: 320, y: 150) health3.zPosition = 3 health3.setScale(0.75) self.addChild(health3) runMonster = SKAction.run(addMonster) waitMonster = SKAction.wait(forDuration: 0.3) sequenceMonster = SKAction.sequence([runMonster,waitMonster]) repeatMonster = SKAction.repeatForever(sequenceMonster) run(repeatMonster) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches{ let locale = touch.location(in: self) hero.position.x = locale.x hero.position.y = locale.y } } func addMonster(){ //random position based off the bg size let monsterHigherX = Int(levelBg.size.width) let monsterHigherY = Int(levelBg.size.height) let monsterLowerX = monsterHigherX * -1 let monsterLowerY = monsterHigherY * -1 let randomLocaleX = Int(arc4random_uniform(UInt32(monsterHigherX - monsterLowerX))) + monsterLowerX let randomLocaleY = Int(arc4random_uniform(UInt32(monsterHigherY - monsterLowerY))) + monsterLowerY let movementEnemy = SKAction.moveBy(x: -5, y: -5, duration: 0.2) let movementForever = SKAction.repeatForever(movementEnemy) let enemyTexture = SKTexture(imageNamed: "boss0") enemy = SKSpriteNode(texture: enemyTexture) enemy.zPosition = 2 enemy.setScale(0.5) enemy.position = CGPoint(x: randomLocaleX, y: randomLocaleY) enemy.physicsBody = SKPhysicsBody(texture: enemyTexture, size: CGSize(width: enemy.size.width, height: enemy.size.height)) enemy.physicsBody!.isDynamic = true enemy.physicsBody!.affectedByGravity = false enemy.physicsBody!.categoryBitMask = CollisionNum.enemyNum.rawValue enemy.physicsBody!.collisionBitMask = CollisionNum.swordNum.rawValue enemy.physicsBody!.contactTestBitMask = CollisionNum.swordNum.rawValue enemy.run(movementForever) self.addChild(enemy) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let swordTexture = SKTexture(imageNamed: "blade-0") sword = SKSpriteNode(texture: swordTexture) sword.setScale(0.50) sword.zPosition = 2 sword.position = hero.position sword.physicsBody = SKPhysicsBody(texture: swordTexture, size: CGSize(width: sword.size.width, height: sword.size.height)) sword.physicsBody!.velocity = CGVector(dx: 1200, dy:0) sword.physicsBody!.isDynamic = true sword.physicsBody!.affectedByGravity = true sword.physicsBody!.usesPreciseCollisionDetection = true sword.physicsBody!.categoryBitMask = CollisionNum.swordNum.rawValue sword.physicsBody!.collisionBitMask = CollisionNum.enemyNum.rawValue sword.physicsBody!.contactTestBitMask = CollisionNum.enemyNum.rawValue self.addChild(sword) } func didBegin(_ contact: SKPhysicsContact) { let collision: UInt32 = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask if collision == CollisionNum.swordNum.rawValue | CollisionNum.enemyNum.rawValue { enemy.removeFromParent() } } override func update(_ currentTime: TimeInterval) { } } (Ive attached my whole level2 class) Thank you so much for the suggestion; however, when I tried implementing this I still run into the same problem (im running this on the iphone simulator) Im wondering whether the error is with my enum or my implementation of my physics with my nodes A: Try this: func didBegin(_ contact: SKPhysicsContact) { let collision: UInt32 = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask if collision == CollisionNum.swordNum.rawValue | CollisionNum.enemyNum.rawValue { enemy.removeFromParent() } } You were only testing if bodyA is equal to the enemy, however, bodyA may be equal to the sword instead. A: You do not want to remove "enemy" because "enemy" is always the last monster you added. You need to check which contactBody is the enemy so you can remove it. You can do that by guaranteeing which node you want to associate as A, and which you want to associate as B by looking at the categoryBitMask value: func didBegin(_ contact: SKPhysicsContact) { //This guarantees the lower categoryBitMask (Providing you are only using one) is in A let bodyA = contact.bodyA.categoryBitMask <= contact.bodyB.categoryBitMask ? contact.bodyA : contact.bodyB let bodyB = contact.bodyA.categoryBitMask <= contact.bodyB.categoryBitMask ? contact.bodyB : contact.bodyA if bodyA.categoryBitMask == CollisionNum.swordNum.rawValue && bodyB.categoryBitMask == CollisionNum.enemyNum.rawValue { bodyB.node.removeFromParent() } } Of course this will lead to problems with multiple collisions, so instead you may want to do: var removeNodes = SKNode() func didBegin(_ contact: SKPhysicsContact) { //This guarantees the lower categoryBitMask (Providing you are only using one) is in A let bodyA = contact.bodyA.categoryBitMask <= contact.bodyB.categoryBitMask ? contact.bodyA : contact.bodyB let bodyB = contact.bodyA.categoryBitMask > contact.bodyB.categoryBitMask ? contact.bodyB : contact.bodyA if bodyA.categoryBitMask == CollisionNum.swordNum.rawValue && bodyB.categoryBitMask == CollisionNum.enemyNum.rawValue { bodyB.node.moveToParent(removeNodes) } } func didFinishUpdate(){ removeNodes.removeAllChildren() }
{ "language": "en", "url": "https://stackoverflow.com/questions/51340820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NVBLAS with Intel Fortran compilers I seem to be missing something when attempting to use NVBLAS with the Intel Fortran compilers. I appear to be linking and using nvblas.conf correctly as I see feedback from the initialization of NVBLAS at runtime. However, NVBLAS does not seem to be intercepting the calls to DGEMM as only the CPU implementation is executed. This is despite using: NVBLAS_CPU_RATIO_CGEMM 0.0 in nvblas.conf (or removing it entirely). If I disable access to the CPU BLAS implementation by removing: NVBLAS_CPU_BLAS_LIB /ccc/home/wilkinson/EMPIRE-2064/src/dynamiclibs/libmkl_rt.so the program crashes at runtime, as I would expect. The compiler options I am currently using are shown below, I have also tried manually linking MKL, but with the same results. # Compiler options FFLAGS=-O3 -axAVX,SSE4.2 -msse3 -align array32byte -fpe1 -fno-alias -openmp -mkl=parallel -heap-arrays 32 # Linker options LDFLAGS= -L/ccc/home/wilkinson/EMPIRE-2064/src/dynamiclibs -lnvblas # List of libraries used LIBS= -L/ccc/home/wilkinson/EMPIRE-2064/src/dynamiclibs -lnvblas An example of a call to DGEMM is as follows: call dgemm('N','T',nCols2,nCols1,nOcc(s),2.0d0/dble(nSpins),C2,nRowsP,C(:,:,s),nRowsP,0.0d0,P(i21,i11,s),nOrbsP) Unfortunately I am currently limited to using the Intel compilers but that restriction will be lifted shortly (at which point I will use CUDA Fortran to optimize data movement). A: I am not sure what is going on here. If I take a very simple DGEMM example (cribbed directly from the MKL fortran guide): PROGRAM MAIN IMPLICIT NONE DOUBLE PRECISION ALPHA, BETA INTEGER M, K, N, I, J PARAMETER (M=8000, K=8000, N=8000) DOUBLE PRECISION A(M,K), B(K,N), C(M,N) PRINT *, "Initializing data for matrix multiplication C=A*B for " PRINT 10, " matrix A(",M," x",K, ") and matrix B(", K," x", N, ")" 10 FORMAT(a,I5,a,I5,a,I5,a,I5,a) PRINT *, "" ALPHA = 1.0 BETA = 0.0 PRINT *, "Intializing matrix data" PRINT *, "" DO I = 1, M DO J = 1, K A(I,J) = (I-1) * K + J END DO END DO DO I = 1, K DO J = 1, N B(I,J) = -((I-1) * N + J) END DO END DO DO I = 1, M DO J = 1, N C(I,J) = 0.0 END DO END DO PRINT *, "Computing matrix product using DGEMM subroutine" CALL DGEMM('N','N',M,N,K,ALPHA,A,M,B,K,BETA,C,M) PRINT *, "Computations completed." PRINT *, "" PRINT *, "Top left corner of matrix A:" PRINT 20, ((A(I,J), J = 1,MIN(K,6)), I = 1,MIN(M,6)) PRINT *, "" PRINT *, "Top left corner of matrix B:" PRINT 20, ((B(I,J),J = 1,MIN(N,6)), I = 1,MIN(K,6)) PRINT *, "" 20 FORMAT(6(F12.0,1x)) PRINT *, "Top left corner of matrix C:" PRINT 30, ((C(I,J), J = 1,MIN(N,6)), I = 1,MIN(M,6)) PRINT *, "" 30 FORMAT(6(ES12.4,1x)) PRINT *, "Example completed." STOP END If I build the code with the Intel compiler (12.1) and run it under nvprof (note I don't have access to MKL at the moment so I am using OpenBLAS built with ifort): $ ifort -o nvblas_test nvblas_test.f -L/opt/cuda-7.5/lib64 -lnvblas $ echo -e "NVBLAS_CPU_BLAS_LIB /opt/openblas/lib/libopenblas.so\nNVBLAS_AUTOPIN_MEM_ENABLED\n" > nvblas.conf $ nvprof --print-gpu-summary ./nvblas_test ==23978== NVPROF is profiling process 23978, command: ./nvblas_test [NVBLAS] Config parsed Initializing data for matrix multiplication C=A*B for matrix A( 8000 x 8000) and matrix B( 8000 x 8000) Intializing matrix data Computing matrix product using DGEMM subroutine Computations completed. Top left corner of matrix A: 1. 2. 3. 4. 5. 6. 8001. 8002. 8003. 8004. 8005. 8006. 16001. 16002. 16003. 16004. 16005. 16006. 24001. 24002. 24003. 24004. 24005. 24006. 32001. 32002. 32003. 32004. 32005. 32006. 40001. 40002. 40003. 40004. 40005. 40006. Top left corner of matrix B: -1. -2. -3. -4. -5. -6. -8001. -8002. -8003. -8004. -8005. -8006. -16001. -16002. -16003. -16004. -16005. -16006. -24001. -24002. -24003. -24004. -24005. -24006. -32001. -32002. -32003. -32004. -32005. -32006. -40001. -40002. -40003. -40004. -40005. -40006. Top left corner of matrix C: -1.3653E+15 -1.3653E+15 -1.3653E+15 -1.3653E+15 -1.3653E+15 -1.3653E+15 -3.4131E+15 -3.4131E+15 -3.4131E+15 -3.4131E+15 -3.4131E+15 -3.4131E+15 -5.4608E+15 -5.4608E+15 -5.4608E+15 -5.4608E+15 -5.4608E+15 -5.4608E+15 -7.5086E+15 -7.5086E+15 -7.5086E+15 -7.5086E+15 -7.5086E+15 -7.5086E+15 -9.5563E+15 -9.5563E+15 -9.5563E+15 -9.5563E+15 -9.5563E+15 -9.5563E+15 -1.1604E+16 -1.1604E+16 -1.1604E+16 -1.1604E+16 -1.1604E+16 -1.1604E+16 Example completed. ==23978== Profiling application: ./nvblas_test ==23978== Profiling result: Time(%) Time Calls Avg Min Max Name 92.15% 8.56855s 512 16.736ms 9.6488ms 21.520ms void magma_lds128_dgemm_kernel<bool=0, bool=0, int=5, int=5, int=3, int=3, int=3>(int, int, int, double const *, int, double const *, int, double*, int, int, int, double const *, double const *, double, double, int) 7.38% 685.77ms 1025 669.04us 896ns 820.55us [CUDA memcpy HtoD] 0.47% 44.017ms 64 687.77us 504.56us 763.05us [CUDA memcpy DtoH] I get what I expect - offload of the DGEMM call to the GPU. When I do this: $ echo "NVBLAS_GPU_DISABLED_DGEMM" >> nvblas.conf $ nvprof --print-gpu-summary ./nvblas_test ==23991== NVPROF is profiling process 23991, command: ./nvblas_test [NVBLAS] Config parsed Initializing data for matrix multiplication C=A*B for matrix A( 8000 x 8000) and matrix B( 8000 x 8000) Intializing matrix data Computing matrix product using DGEMM subroutine Computations completed. Top left corner of matrix A: 1. 2. 3. 4. 5. 6. 8001. 8002. 8003. 8004. 8005. 8006. 16001. 16002. 16003. 16004. 16005. 16006. 24001. 24002. 24003. 24004. 24005. 24006. 32001. 32002. 32003. 32004. 32005. 32006. 40001. 40002. 40003. 40004. 40005. 40006. Top left corner of matrix B: -1. -2. -3. -4. -5. -6. -8001. -8002. -8003. -8004. -8005. -8006. -16001. -16002. -16003. -16004. -16005. -16006. -24001. -24002. -24003. -24004. -24005. -24006. -32001. -32002. -32003. -32004. -32005. -32006. -40001. -40002. -40003. -40004. -40005. -40006. Top left corner of matrix C: -1.3653E+15 -1.3653E+15 -1.3653E+15 -1.3653E+15 -1.3653E+15 -1.3653E+15 -3.4131E+15 -3.4131E+15 -3.4131E+15 -3.4131E+15 -3.4131E+15 -3.4131E+15 -5.4608E+15 -5.4608E+15 -5.4608E+15 -5.4608E+15 -5.4608E+15 -5.4608E+15 -7.5086E+15 -7.5086E+15 -7.5086E+15 -7.5086E+15 -7.5086E+15 -7.5086E+15 -9.5563E+15 -9.5563E+15 -9.5563E+15 -9.5563E+15 -9.5563E+15 -9.5563E+15 -1.1604E+16 -1.1604E+16 -1.1604E+16 -1.1604E+16 -1.1604E+16 -1.1604E+16 Example completed. ==23991== Profiling application: ./nvblas_test ==23991== Profiling result: Time(%) Time Calls Avg Min Max Name 100.00% 768ns 1 768ns 768ns 768ns [CUDA memcpy HtoD] I get no offload to the GPU. If you can't reproduce this, then the problem is either with your compiler version (you haven't said which one you are using), if you can, then perhaps the somewhat fancier build options you are using are interacting with NVBLAS in an unexpected way
{ "language": "en", "url": "https://stackoverflow.com/questions/34896171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python-doit dependecy on a dataset in an h5 file I have a doit task which depends on one of several datasets contained in an h5 file. Does anyone have any idea how I could (1) check the dependency to determine whether or not to execute the task and (2) save the dependency's signature for checking next time the task is executed? A: In doit you can write custom rules to check if a task is up-to-date or not. Check uptodate http://pydoit.org/dependencies.html#uptodate
{ "language": "en", "url": "https://stackoverflow.com/questions/37670445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handling the usual errors: If-Then-Throw blocks vs. Code Contracts vs. an Assert class When I start writing a method, I usually check for exceptional conditions first in the method, using If-Then-Throw blocks. public void ReadFile(string filePath) { if (string.IsNullOrEmpty(filePath) { throw new ArgumentException(... This style seems to be very clear and easy to understand, but it takes up more space than I think is necessary. I want to be able to handle errors and exceptional conditions in a smart way that enables whoever's reading these errors to easy take care of them while also keeping the code itself clean. I've looked a bit at Code Contracts, which seems to me a requirement for certain conditions before and after a method's execution. That seems to be a tad bit overkill for just a null string, and I'm not sure if you can have contract clauses within the method itself, for instance, if the path is not null but no file exists at that path. The solution I'm thinking of using is rolling my own Assert class. This class will basically turn the above If-Then-Throw into a simple one liner. Assert.IsFalse<ArgumentException>(string.IsNullOrEmpty(filePath), "The path cannot be null or empty."); All Assert methods would throw an exception using the exception type and the message in the last argument. The thing is that I'm not sure if this is good practice. Does it confuse what exceptions are truly for, or what Assert actually means? Would it make error-handling easier or harder? A: I would say this is not good practice. As you pointed out, this would confuse the roles of Assertions and Exceptions. The topic is somewhat common, this link has a lot of nice ideas. By combining exceptions and assertions, you end up with a conundrum... is the class an exception helper, or is it an assertion helper? Since assertions are compiled out of the Release build, would your assertion class even work in Release mode? It would be non-conventional to expect an Assertion class to work in release mode. So, would your Assertion class throw the exceptions in Release mode? There lies the confusion. By convention, I would say the exception should not be thrown when using an Assert Class (in Release mode) because it is understood that assertions are not part of a Release build. The code above should not make 'Exception Handling' easier nor harder, it should be the same since the exception handling depends on what is catching the exception in the stack. I think you are really asking if it makes throwing Exceptions easier or harder. I think it could make dealing with your exceptions easier. I also think it is probably unnecessary. What is most important is that you are consistent with this... if you are going to use an ExceptionHelper class, then embrace it and be consistent... otherwise it is all done for naught. Debug.Assert: * *Use liberally *Use whenever there is a chance that an assumption could be wrong *Used to help other programmers, not necessarily the end user *Should never affect the flow of the program *Not compiled in Release builds *Always yells 'BLOODY MURDER' when something unexpected happens, this is a good thing *many other reasons, I'm not aiming for a complete list Exceptions: * *Can be caused for any reason, it is not always known why *Always in debug or release builds *Pertains to how the application flows *Some exception handlers may silently swallow an exception and you would never know it *many other reasons, I'm not aiming for a complete list A: To be honest, I'm not sure a custom Assert class would help clarify anything, and I'm not sure you should be worried about two lines need to check and throw an exception vs one line. Your current way of checking parameters is the way we do things as well. In fact, a majority of public methods around our code look something like this: public void PerformStringOperation(string str1, string str2) { if(string.IsNullOrEmpty(string1)) throw new ArgumentNullException(...); if(string.IsNullOrEmpty(string2)) throw new ArgumentNullException(...); // perform string operation(s) here } We have never found it too encumbering, and I'm sure it is the exact solution used by many teams.
{ "language": "en", "url": "https://stackoverflow.com/questions/23298011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Change size of element in SegmentedPicker Let's say I have this simple Picker in a SegmentedPickerStyle. struct ContentView: View { @State private var favoriteColor = 0 var body: some View { VStack { Picker(selection: $favoriteColor, label: Text("bla bla...")) { Text("This is a very long string").tag(0) Text("B").tag(1) Text("C").tag(2) } .pickerStyle(SegmentedPickerStyle()) } } } the result will be something like this: Is there a way to make the size of the segments dynamic? So that the first segment will be bigger and "B" and "C" are adjusted to it?
{ "language": "en", "url": "https://stackoverflow.com/questions/66745445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get an 100vw item to be centred when inside a container that is not centred and not full width? I have a full width element inside a container that is not full width (715px). This container is not centred as it's got a side bar next to it (245px). I cannot absolutely position the item as it's dynamic / a block in a matrix. How can I ensure that it is always centre no matter what screen size? margin: auto margin-left: 50% don't work, using a percentage and doing it visually doesn't work because as soon as the screen size changes the full width element is no longer centred HTML <section class="grid"> <div class="grid__item one-quarter"> <ul> <li>List Item</li> <li>List Item</li> <li>List Item</li> </ul> </div> <div class="grid__item three-quarters"> <div class="page-builder-item"> <h1>Some content in an element</h1> </div> <div class="page-builder-item"> <h1>Some content in an element</h1> </div> <div class="page-builder-item full-width"> <h1>Some content in an FULL WIDTH element</h1> </div> </div> </section> CSS .grid { width: 960px; display: flex; margin: auto; } .grid-item { display: inline-block; } .one-quarter { width: 25%; border: 1px solid red; } .three-quarters { width: 75%; border: 1px solid blue; } .page-builder-item { background: pink; height: 100px; width: 100%; } .page-builder-item.full-width { width: 100vw; background: magenta; margin-left: -25%; } Link to codepen example https://codepen.io/hellojessicagraham/pen/pxedav A: Generally I think it's best to keep children elements within the bounds of their parents because of how tricky this can get. However if you need to use this layout you can try something like: margin-left: calc((-1 * 960px * .25) - (50vw - (.5 * 960px))); I'm sure that can be shortened, but I wanted to leave the full calculation in place for clarity's sake. The first part, -1 * 960px *.25 moves the magenta box to align its left edge with the grid's left edge. The second part 50vw - (.5 * 960px) then moves the magenta box further so that its left edge aligns with the browser's left edge. The problem with this is it's somewhat brittle. It depends very heavily on the exact width of both the 'grid' element and the percent width of the left column. CSS Tricks has a good post about centering items that are wider than their parents. It's solutions don't directly apply to this case, but it's a good resource to better understand your options and I used it to develop the calc statement I used
{ "language": "en", "url": "https://stackoverflow.com/questions/52731422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Turn a JSON array of arrays into * and * elements I'm creating a custom visual in Microsoft Power BI. The creation api uses typescript and the d3 library. I'm also using jquery I'm trying to create a hierarchical tree that represents the fields that are dragged into the visual. So the depth of the tree is decided during run-time so It doesn't know how many layers it will have. I've managed to arrange my dummy data into a nested JSON array. This is a screenshot from the console when I do console.log(finalViewModel) [{ "text": "France","id": 591, "parent": 0, "identity": {long text}, "nodes" [{"text": "Bread", "id", 478, "parent": 591, "identity: {long text}, "nodes" []}, {"text": "Nocco", "id", 498, "parent": 591, "identity: {long text}, "nodes" []}, {"text": "Red Wine", "id", 718, "parent": 591, "identity: {long text}, "nodes" []}]}, {"text: "Germany", "id" .....so on and so forth This is how my data looks when I JSON.stringify it in the console, also I used only 2 fields so It wouldn't be too cluttered. "identity": {long text}, does not display like that. The identity field is for the Power BI selection manager so when something from the tree is clicked it will render into other visuals. long text Is a replacement for a very long array that holds the information for that certain item identity. Now to the problem, I want to convert my JSON data into ul and li elements. Like this: <ul> <li>France</li> <ul> <li>Baguette</li> <li>Nocco</li> <li>Red Wine</li> </ul> <li>Germany</li> </ul> I've found many solutions to this kind of problem on the web but nothing seems to fit my needs. Can anyone help me with a working code snippet? Thanks in advance A: Here is a demo how it could be achieved with the pure javascript. var createSublist = function(container, args) { var ul = document.createElement('ul'); for(var j = 0; j < args.length; j++) { var row = args[j]; var li = document.createElement('li'); li.innerText = row.text; var nodes = row.nodes; if(nodes && nodes.length) { createSublist(li, nodes); } ul.appendChild(li); } container.appendChild(ul); }; var data =[ { "text":"France", "nodes":[ { "text":"Bread" }, { "text":"Nocco" } ], }, { "text":"Italy", "nodes":[ { "text":"Pizza" }, { "text":"Wine", "nodes": [ { "text": "Red" }, { "text":"White" } ] } ] } ]; var container = document.getElementsByClassName('container')[0]; if(container) { createSublist(container, data); } else { console.log('Container has not been found'); } <div class="container"> </div> A: JavaScript ES6 and a small recursive function /** * Convert Tree structure to UL>LI and append to Element * @syntax getTree(treeArray [, TargetElement [, onLICreatedCallback ]]) * * @param {Array} tree Tree array of nodes * @param {Element} el HTMLElement to insert into * @param {function} cb Callback function called on every LI creation */ const treeToHTML = (tree, el, cb) => el.append( tree.reduce((ul, n) => { const li = document.createElement("li"); if (cb) cb.call(li, n); if (n.nodes?.length) treeToHTML(n.nodes, li, cb); ul.append(li); return ul; }, document.createElement("ul")) ); // DEMO TIME: const myTree = [{ "id": 1, "parent_id": 0, "name": "Item1", "nodes": [{ "id": 2, "parent_id": 1, "name": "Item2" }] }, { "id": 4, "parent_id": 0, "name": "Item4", "nodes": [{ "id": 9, "parent_id": 4, "name": "Item9" }, { "id": 5, "parent_id": 4, "name": "Item5", "nodes": [{ "id": 3, "parent_id": 5, "name": "Item3" }] } ] }]; treeToHTML(myTree, document.querySelector("#demo"), function(node) { this.textContent = `${node.parent_id} ${node.id} ${node.name}` }); <div id="demo"></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/50966117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How can I make n*n buttons using an array at runtime in C#? It takes a number n from the user and makes n*n buttons for it on the form. When I run the code, only the first row appears on form, instead of all n rows. private void button1_Click(object sender, EventArgs e) { int n = Convert.ToInt32(textBox1.Text.ToString()); Button[,] v = new Button[n, n]; for (int i = 0; i < n; i++) { int top = 60; int left = 160; int width = 25; for (int j = 0; j < n; j++) { Button c= new Button(); c.Top =top ; c.Left= left; c.Width = width; v[i, j] = c; left += c.Width + 2; } top += 2; left = 160; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { this.Controls.Add(v[i, j]); } } } A: You are resetting the top variable at each loop, your buttons are all in the same top position. Move the initialization of the top variable outside the first loop private void button1_Click(object sender, EventArgs e) { int top = 60; int n = Convert.ToInt32(textBox1.Text.ToString()); Button[,] v = new Button[n, n]; for (int i = 0; i < n; i++) { // int top = 60; ...... However, you are incrementing the top only by 2 pixel. This is not enough to avoid covering one row of button with the next row. You need to increment top by at least 25 pixels at the end of the inner loop. .... top += 25; left = 160; } A: You can also use your for loops to set the top and left property values (more than one variable can be defined and incremented in a for loop). For each row, we increase the top value by the height + padding (padding is the gap between buttons), and for each col, we increase the left by width + padding. We can also add each button to the controls collection as we create it rather than adding it to an array and then iterating again over that array, and we can add some input validation to the textbox.Text that we're assuming is a positive number, presenting the user with a message box if they entered something invalid. Given this, we can simplify the code to something like: private void button1_Click(object sender, EventArgs e) { int count; // Validate input if (!int.TryParse(textBox1.Text, out count) || count < 0) { MessageBox.Show("Please enter a positive whole number"); return; } // remove old buttons (except this one) var otherButtons = Controls.OfType<Button>().Where(b => b != button1).ToList(); foreach (Button b in otherButtons) { Controls.Remove(b); } // Add button controls to form with these size and spacing values (modify as desired) var width = 25; var height = 25; var padding = 2; // For each row, increment the top by the height plus padding for (int row = 0, top = padding; row < count; row++, top += height + padding) { // For each column, increment the left by the width plus padding for (int col = 0, left = padding; col < count; col++, left += width + padding) { // Add our new button Controls.Add(new Button { Top = top, Left = left, Width = width, Height = height, }); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/55975082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Performing inference in Tensorflow with multiple graphs on same GPU parallely I created 2 tf.graph() (loaded the same frozen model) from different threads, which seem to happen based on the different tf.graph object address that I see in each thread. When I tried to run inference on these 2 graphs parallely using the same GPU, I feel it is running like a sequential pipeline. This is based on the GPU memory & utilization stats and also the time taken. ie, A single graph would consume 7GB of GPU memory and utilize ~15% of compute. With 2 graphs running parallely I would expect to use twice the GPU memory and increased compute, but that doesn't seem to happen.
{ "language": "en", "url": "https://stackoverflow.com/questions/49662266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Route Class Undefined I am using Laravel 5.7, and the following error ocurrs with this code:+ /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/welcome', function () { return view('welcome'); }); Fatal error: Uncaught Error: Class 'Route' not found in C:\wamp64\www\master-fullstack\api-rest-laravel\routes\web.php:14 Fatal error: Uncaught Error: Class 'Route' not found in C:\wamp64\www\master-fullstack\api-rest-laravel\routes\api.php on line 16
{ "language": "en", "url": "https://stackoverflow.com/questions/57872553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Css selector for exact class name I am trying to make a css selector query for exact class name . Consider this html <div class="My class1">Some long text</div> <div class="My class1 234">Some long text2</div> <div class="My class1">Some long text3</div> <div class="My class1 haha">Some long text2</div> Now i want to catch only class 'My class1' ...and ignore the 'My class1 234' or 'My class1 haha'.. The query $$('div.My class1') , gives me all the 4 above . Note : I am trying on firebug console.. How to specify the exact class name here so to get only that particular class ? Thanks A: Attribute Selector Syntax For straight CSS it is: [class='My class1'] For most javascript frameworks like jQuery, MooTools, etc., it is going to be the same selector string used as for the straight CSS. The key point is to use an attribute selector to do it, rather than selecting directly by the class name itself. The class= (with just the equals sign) will only select for an exact match of the string following. If you also have need of catching class1 My then you would need to select as well for [class='class1 My']. That would cover the two cases where only those two classes are applied (no matter the order in the html). A: Class definitions in elements are separated by spaces, as such your first element infact has both classes 'My' and 'class1'. If you're using Mootools, you can use the following: $$("div.My.class1:not(div.234):not(div.haha)") Example in Mootools: http://jsfiddle.net/vVZt8/2/ Reference: http://mootools.net/docs/core125/core/Utilities/Selectors#Selector:not If you're using jQuery, you can use the following: $("div.My.class1").not("div.234").not("div.haha"); Example in jQuery: http://jsfiddle.net/vVZt8/3/ Reference: http://api.jquery.com/not-selector/ These two examples basically retrieve all elements with the classes 'My' and 'class1', and then remove any elements that are a 'div' element which have the either of the '234' or 'haha' classes assigned to them. A: jQuery equals selector: http://api.jquery.com/attribute-equals-selector/ jQuery("[class='My class1']"). or $("[class='My class1']"). or $$("[class='My class1']").
{ "language": "en", "url": "https://stackoverflow.com/questions/17314060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Android self organiser with calendarView Hi I'm trying to create app that will respond to clicked date on CalendarView, will get the date chosen and will display it in textview, here is my code: public class MyOrganiser1Activity extends Activity { /** Called when the activity is first created. */ TextView dateView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); CalendarView calendas = (CalendarView)findViewById(R.id.calendarView1); dateView = (TextView)findViewById(R.id.dateView1); calendas.setOnDateChangeListener( new CalendarView.OnDateChangeListener() { private GregorianCalendar calendar; public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) { this.calendar = new GregorianCalendar(year, month, dayOfMonth); SimpleDateFormat ss = new SimpleDateFormat("yyyy-MM-dd"); String currentdate= ss.format(calendar); dateView.setText(currentdate); } }); } } And my question is: Once i run this code; my app crash. Debug info:"can't find android.java for DataSetObservable.class". However; i don't even know if this code above is correct.
{ "language": "en", "url": "https://stackoverflow.com/questions/10367118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: spring batch job stuck in loop even when ItemReader returns null I am converting xml to csv using spring batch and integration. I have a approach that job will start by reading files in from landing dir. while processing it will move files in inprocess dir. on error file will be moved to error dir. on successfully processing/writing file will be moved to output/completed. After searching a while i got to know that there must be problem with itemreader but it is also returning null. I am not getting where is the problem. Below is my batch configuration @Bean public Job commExportJob(Step parseStep) throws IOException { return jobs.get("commExportJob") .incrementer(new RunIdIncrementer()) .flow(parseStep) .end() .listener(listener()) .build(); } @Bean public Step streamStep() throws IOException { CommReader itemReader = itemReader(null); if (itemReader != null) { return steps.get("streamStep") .<Object, Object>chunk(env.getProperty(Const.INPUT_READ_CHUNK_SIZE, Integer.class)) .reader(itemReader) .processor(itemProcessor()) .writer(itemWriter(null)) .listener(getChunkListener()) .build(); } return null; } @Bean @StepScope public ItemWriter<Object> itemWriter(@Value("#{jobParameters['outputFilePath']}") String outputFilePath) { log.info("CommBatchConfiguration.itemWriter() : " + outputFilePath); CommItemWriter writer = new CommItemWriter(); return writer; } @Bean @StepScope public CommReader itemReader(@Value("#{jobParameters['inputFilePath']}") String inputFilePath) { log.info("CommBatchConfiguration.itemReader() : " + inputFilePath); CommReader reader = new CommReader(inputFilePath); // reader.setEncoding(env.getProperty("char.encoding","UTF-8")); return reader; } @Bean @StepScope public CommItemProcessor itemProcessor() { log.info("CommBatchConfiguration.itemProcessor() : Entry"); return new CommItemProcessor(ruleService); } CommReader.java File inputFile = null; private String jobName; public CommReader(String inputFilePath) { inputFile = new File(inputFilePath); } @Value("#{stepExecution}") private StepExecution stepExecution; public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } @Override public Object read() throws IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; if (inputFile.exists()) { try { builder = factory.newDocumentBuilder(); log.info("CommReader.read() :" + inputFile.getAbsolutePath()); Document document = builder.parse(inputFile); return document; } catch (ParserConfigurationException | SAXException | TransformerFactoryConfigurationError e) { log.error("Exception while reading ", e); } } return null; } @Override public void close() throws ItemStreamException { } @Override public void open(ExecutionContext arg0) throws ItemStreamException { } @Override public void update(ExecutionContext arg0) throws ItemStreamException { } @Override public void setResource(Resource arg0) { } CommItemProcessor.java @Autowired CommExportService ruleService; public CommItemProcessor(CommExportService ruleService) { this.ruleService = ruleService; } @Override public Object process(Object bean) throws Exception { log.info("CommItemProcessor.process() : Item Processor : " + bean); return bean; } CommItemWriter.java FlatFileItemWriter<byte[]> delegate; ExecutionContext execContext; FileOutputStream fileWrite; File stylesheet; StreamSource stylesource; Transformer transformer; List<List<?>> itemsTotal = null; int recordCount = 0; @Autowired FileUtil fileUtil; @Value("${input.completed.dir}") String completedDir; @Value("${input.inprocess.dir}") String inprocessDir; public void update(ExecutionContext arg0) throws ItemStreamException { this.delegate.update(arg0); } public void open(ExecutionContext arg0) throws ItemStreamException { this.execContext = arg0; this.delegate.open(arg0); } public void close() throws ItemStreamException { this.delegate.close(); } @Override public void write(List<? extends Object> items) throws Exception { log.info("CommItemWriter.write() : items.size() : " + items.size()); stylesheet = new File("./config/style.xsl"); stylesource = new StreamSource(stylesheet); String fileName = fileUtil.getFileName(); try { transformer = TransformerFactory.newInstance().newTransformer(stylesource); } catch (TransformerConfigurationException | TransformerFactoryConfigurationError e) { log.error("Exception while writing",e); } for (Object object : items) { log.info("CommItemWriter.write() : Object : " + object.getClass().getName()); log.info("CommItemWriter.write() : FileName : " + fileName); Source source = new DOMSource((Document) object); Result outputTarget = new StreamResult( new File(fileName)); transformer.transform(source, outputTarget); } } In chunkListener there is nothing much i am doing. Below is the job listener. @Override public void beforeJob(JobExecution jobExecution) { log.info("JK: CommJobListener.beforeJob()"); } @Override public void afterJob(JobExecution jobExecution) { log.info("JK: CommJobListener.afterJob()"); JobParameters jobParams = jobExecution.getJobParameters(); File inputFile = new File(jobParams.getString("inputFilePath")); File outputFile = new File(jobParams.getString("outputFilePath")); try { if (jobExecution.getStatus().isUnsuccessful()) { Files.move(inputFile.toPath(), Paths.get(inputErrorDir, inputFile.getName()), StandardCopyOption.REPLACE_EXISTING); Files.move(outputFile.toPath(), Paths.get(outputErrorDir, outputFile.getName()), StandardCopyOption.REPLACE_EXISTING); } else { String inputFileName = inputFile.getName(); Files.move(inputFile.toPath(), Paths.get(inputCompletedDir, inputFileName), StandardCopyOption.REPLACE_EXISTING); Files.move(outputFile.toPath(), Paths.get(outputCompletedDir, outputFile.getName()), StandardCopyOption.REPLACE_EXISTING); } } catch (IOException ioe) { log.error("IOException occured ",ioe); } } I am also using integration flow. @Bean public IntegrationFlow messagesFlow(JobLauncher jobLauncher) { try { Map<String, Object> headers = new HashMap<>(); headers.put("jobName", "commExportJob"); return IntegrationFlows .from(Files.inboundAdapter(new File(env.getProperty(Const.INPUT_LANDING_DIR))) , e -> e.poller(Pollers .fixedDelay(env.getProperty(Const.INPUT_POLLER_DELAY, Integer.class).intValue()) .maxMessagesPerPoll( env.getProperty(Const.INPUT_MAX_MESSAGES_PER_POLL, Integer.class).intValue()) .taskExecutor(getFileProcessExecutor()))) .handle("moveFile","moveFile") .enrichHeaders(headers) .transform(jobTransformer) .handle(jobLaunchingGw(jobLauncher)) .channel("nullChannel").get(); } catch (Exception e) { log.error("Exception in Integration flow",e); } return null; } @Autowired private Environment env; @Bean public MessageHandler jobLaunchingGw(JobLauncher jobLauncher) { return new JobLaunchingGateway(jobLauncher); } @MessagingGateway public interface IMoveFile { @Gateway(requestChannel = "moveFileChannel") Message<File> moveFile(Message<File> inputFileMessage); } @Bean(name = "fileProcessExecutor") public Executor getFileProcessExecutor() { ThreadPoolTaskExecutor fileProcessExecutor = new ThreadPoolTaskExecutor(); fileProcessExecutor.setCorePoolSize(env.getRequiredProperty(Const.INPUT_EXECUTOR_POOLSIZE, Integer.class)); fileProcessExecutor.setMaxPoolSize(env.getRequiredProperty(Const.INPUT_EXECUTOR_MAXPOOLSIZE, Integer.class)); fileProcessExecutor.setQueueCapacity(env.getRequiredProperty(Const.INPUT_EXECUTOR_QUEUECAPACITY, Integer.class)); fileProcessExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); fileProcessExecutor.initialize(); return fileProcessExecutor; } A: Try to return document itself instead of Object in read method of CommReader.java and then check whether its coming null or not in the writer to stop it.
{ "language": "en", "url": "https://stackoverflow.com/questions/48265296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Laravel login with another database At this moment I am working on a laravel 5.6 application, but the client has asked me to login in sqlserver, I have already created a custom class that connects to sqlserver, the problem is I occupy the laravel Auth class , someone could help me connect laravel auth with my sqlserver class or gift me any ideas? A: Laravel outof the box, comes with functionality to connect with SQL server. I don't think you need to create a custom class on your own. You might need to configure Laravel to connect to your SQL server though. Have a look at the link below for setting up Laravel for SQL server... https://laravel.com/docs/5.6/database
{ "language": "en", "url": "https://stackoverflow.com/questions/51364881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add information to the x-axis label of the plotted graph in Python? import pandas as pd import matplotlib.pyplot as plt my_funds = [10, 20, 50, 70, 90, 110] my_friends = ['Angela', 'Gabi', 'Joanna', 'Marina', 'Xenia', 'Zulu'] my_actions = ['sleep', 'work', 'play','party', 'enjoy', 'live'] df = pd.DataFrame({'Friends': my_friends, 'Funds':my_funds, 'Actions': my_actions}) produces: Then, I am plotting it like this: df.plot (kind='bar', x = "Friends" , y = 'Funds', color='red', figsize=(5,5)) getting the following: What is the goal? The same graph, but instead of "Angela" to have "Angela - sleep" written on the x-axis. The "sleep" comes from the "Action" column. Further [Gabi - work, Joanna - play, Marina - party, Xenia - enjoy, Zulu - live] A: A solution could be to create a new column in your DataFrame: df["Friend-Action"] = [f"{friend} -> {action}" for friend, action in zip(df["Friends"], df["Actions"])] Then, plot this column: df.plot (kind='bar', x = "Friend-Action" , y = 'Funds', color='red', figsize=(5,5)) A: For the sake of this question it is easier to create an extra column with the values you desire and then pass it to the df.plot(): df['Friends_actions'] = df['Friends'] + " " + df['Actions'] df.plot(kind='bar', x = "Friends_actions" , y = 'Funds', color='red', figsize=(5,5)) Output:
{ "language": "en", "url": "https://stackoverflow.com/questions/60115776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to export a list of pandas data frames to Excel using a nested generator expression? I'm trying to export a list of Pandas data frames to Excel files using a generator expression. However nothing is exported once the script has finished executing. It works if I use a for loop, but not using a generator expression. I'm really interested in knowing how it could work, but also why, thanks in advance. This doesn't work: def process_pandas_dfs(): (df.to_excel('df_name.xlsx') for df in list_of_dfs) However this does: def process_pandas_dfs(): for df in list_of_dfs: df.to_excel('df_name.xlsx') A: generator expressions are not evaluated during definition, they create a iterable generator object. Use a list comprehension instead: [df.to_excel('df_name.xlsx') for df in list_of_dfs] Though as Yatu pointed out, the for loop would be the appropriate method of executing this method
{ "language": "en", "url": "https://stackoverflow.com/questions/57689324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: google map like search on wordpress site I want this kind of search on my wordpress site. I m using wpestate wordpress theme. Anybody has any idea about this?? Exactly the same..Any plugin or custom code???Or js,jquery?? How do i embed this kind of search in my wordpress site??
{ "language": "en", "url": "https://stackoverflow.com/questions/25077606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: InfoPath Drop Down list, loses data after trying to submit I have a question about my InfoPath Form: When I select a value from the first Drop Down list, the second one appears (it has a hide rule) and it has the values I configured in the InfoPath. But when I select a value from the first Drop Down list and do not click on the second one, I get an error! After this, I submit the form and the forms needs a value from the second Drop Down. So, after this message, I clicked in the second Drop Box, but all the values are gone. If I exit the form, and open it again, the forms loads OK and if I repeat the same actions, the data of the second Drop Down list disappears again. A: Problem solved guys! I changed the button of Infopath, before it was reading the a rule for submit, now the button is a submit button! Hope this can help someone!
{ "language": "en", "url": "https://stackoverflow.com/questions/20201480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Padding in PCX decoder I've got a PCX decoder in C# (see below) that is meant to read in a Stream and output a Bitmap. It works when dealing with an image that has dimensions that are multiples of 8, and seems to work with most images that are less than 8bpp regardless of dimensions, but images with different dimensions become skewed in an unusal way (see this link ). The pixels are all there, just it seems to be almost moved left in a weird way. The image is a valid PCX and opens in IrfanView and Paint.net. Edit 1: Okay, here's the result of quite a bit of testing: images with a byte-per-line value that divides by 8 (e.g. 316x256) decode fine, but images with an odd value don't. This is not true for all PCX files; it would seem that some (most?) images created in IrfanView work fine, but those I've found elsewhere do not. I was working on this some time ago, so I can't recall where they came from, I do know that images saved with the paint.net plug-in (here) also reproduce this problem. I think it's likely due to a padding issue, either with them or my decoder, but the images to decode fine elsewhere so, it's likely I'm the one with the problem, I just can't see where :( End of Edit 1. My code for importing is here (there's a lot, but it's the whole decoding algorithm, minus the header, which is processed separately): public IntPtr ReadPixels(Int32 BytesPerScanline, Int32 ScanLines, Stream file) { //BytesPerScanLine is the taken from the header, ScanLines is the height and file is the filestream IntPtr pBits; Boolean bRepeat; Int32 RepeatCount; Byte ReadByte; Int32 Row = 0; Int32 Col = 0; Byte[] PCXData = new Byte[BytesPerScanline * ScanLines]; //BytesPerScanline * ScanLines); BinaryReader r = new BinaryReader(file); r.BaseStream.Seek(128, SeekOrigin.Begin); while (Row < ScanLines) { ReadByte = r.ReadByte(); bRepeat = (0xc0 == (ReadByte & 0xC0)); RepeatCount = (ReadByte & 0x3f); if (!(Col >= BytesPerScanline)) { if (bRepeat) { ReadByte = r.ReadByte(); while (RepeatCount > 0) { PCXData[(Row * BytesPerScanline) + Col] = ReadByte; RepeatCount -= 1; Col += 1; } } else { PCXData[(Row * BytesPerScanline) + Col] = ReadByte; Col += 1; } } if (Col >= BytesPerScanline) { Col = 0; Row += 1; } } pBits = System.Runtime.InteropServices.Marshal.AllocHGlobal(PCXData.Length); System.Runtime.InteropServices.Marshal.Copy(PCXData, 0, pBits, PCXData.Length); return pBits; } I've been advised that it might be an issue with padding, but I can't see where this may be in the code and I'm struggling to see how to understand where the padding is.
{ "language": "en", "url": "https://stackoverflow.com/questions/8376436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Batch replace serialized CDN subdomains We are moving an existing website to use CDN distribution of img resources. The project manager has mandated that on each page we have to distribute img src's to one of six different CDN subdomains -- the idea being that since download requests to different domains execute simultaneously instead of serially, we will get speed benefits. In other words, I need to turn this... <p>Argle bargle.</p> <img src="http://old-domain.com/_img/image-a.jpg"> <img src="http://old-domain.com/_img/image-b.jpg"> <img src="http://old-domain.com/_img/image-c.jpg"> <img src="http://old-domain.com/_img/image-d.jpg"> <img src="http://old-domain.com/_img/image-e.jpg"> <img src="http://old-domain.com/_img/image-f.jpg"> <img src="http://old-domain.com/_img/image-g.jpg"> <img src="http://old-domain.com/_img/image-h.jpg"> <p>Whiz bang.</p> Into this... <p>Argle bargle.</p> <img src="http://cdn1.cdn.com/_img/image-a.jpg"> <img src="http://cdn2.cdn.com/_img/image-b.jpg"> <img src="http://cdn3.cdn.com/_img/image-c.jpg"> <img src="http://cdn4.cdn.com/_img/image-d.jpg"> <img src="http://cdn5.cdn.com/_img/image-e.jpg"> <img src="http://cdn6.cdn.com/_img/image-f.jpg"> <img src="http://cdn1.cdn.com/_img/image-g.jpg"> <img src="http://cdn2.cdn.com/_img/image-h.jpg"> <p>Whiz bang.</p> I have hundreds of files to update and they are all much more complex than the above sample. If the CDN was just one domain, I would batch replace all the files in an instant using TextWrangler. But I need to somehow serialize (or even randomize?) the replacement strings. I use FileMaker Pro as a production front-end (to automate navigation construction, meta-tagging, etc.), and so I tried to craft a Calculation on my HTML Output field that would serialize every src, but I think it needs a for-each loop, which you can't do in a Calculation field (I have FM Pro, not FM Pro Advanced, so I can't use a Custom Function). Anybody ever do anything similar in AppleScript? Or maybe leverage a Terminal text-processor? Any recommendations would be appreciated. A: I suggest you to use a simple bash script like that: #!/bin/bash OLD="old-domain.com\/_img" NEW="cdn1.cdn.com\/_img" DPATH="/home/of/your/files/*.html" for f in $DPATH do sed "s/$OLD/$NEW/g" "$f" > temp; mv temp "$f"; done It replaces old-domain.com/_img with cdn1.cdn.com/_img on all your .html files on /home/of/your/files/. A: Are you actually writing HTML from FileMaker? If that's the case, and you want to manipulate the HTML using Perform AppleScript, then you can do something like the following. Best Practice: Always use "Native AppleScript" instead of "Calculated AppleScript". To get data in and out of AppleScript, create a pair of global fields for reading and writing between FileMaker and AppleScript. This helps you isolate AppleScript errors when talking to other applications so that they don't bleed into later script steps. (I prefer to create a Global table and create a table occurrence called @Global. In that Global table I create two fields: AppleScriptInput and AppleScriptOutput. Note that you must create a record in this table or you will get mysterious "object not found" errors in AppleScript.) Set Field [@Global::AppleScriptInput; $myHtml] Perform AppleScript [“ -- Read HTML from a global field in FileMaker set html to get data (table "@Global")'s (field "AppleScriptInput") -- Split html on old domain fragment set my text item delimiters to "<img src=\"http://old-domain.com/_img/" set html_fragments to text items of html -- Prefix resource with CDN domain fragment repeat with i from 2 to length of html_fragments set cdn_number to (i - 2) mod 6 + 1 set cdn_fragment to "<img src=\"http://cdn" & cdn_number & ".cdn.com/_img/" set item i of html_fragments to cdn_fragment & item i of html_fragments end repeat -- Re-join html fragments set my text item delimiters to "" set html to html_fragments as text -- Write html back to a global field in FileMaker set data (table "@Global")'s (cell "AppleScriptInput") to html ”] Set Variable [$revisedHtml; @Global::AppleScriptOutput] The above script steps will read the input you provided from the FileMaker variable $html and save the output you provided to $revisedHtml. You can do the same thing in pure FileMaker script of course: Set Variable [$html; "<p>Argle bargle.</p> <img src=\"http://old-domain.com/_img/image-a.jpg\"> <img src=\"http://old-domain.com/_img/image-b.jpg\"> <img src=\"http://old-domain.com/_img/image-c.jpg\"> <img src=\"http://old-domain.com/_img/image-d.jpg\"> <img src=\"http://old-domain.com/_img/image-e.jpg\"> <img src=\"http://old-domain.com/_img/image-f.jpg\"> <img src=\"http://old-domain.com/_img/image-g.jpg\"> <img src=\"http://old-domain.com/_img/image-h.jpg\"> <p>Whiz bang.</p>" ] Set Variable [$oldDomain; "http://old-domain.com/_img/"] Set Variable [$itemCount; PatternCount ( $html ; $oldDomain )] Loop Exit Loop If [Let ( $i = $i + 1 ; If ( $i > $itemCount ; Let ( $i = "" ; True ) ) )] Set Variable [$html; Let ( [ domainPosition = Position ( $html ; "http://old-domain.com/_img/" ; 1 ; 1 ); domainLength = Length ( "http://old-domain.com/_img/" ); cdnNumber = Mod ( $i - 1 ; 6 ) + 1 ] ; Replace ( $html ; domainPosition ; domainLength ; "http://cdn" & cdnNumber & ".cdn.com/_img/" ) ) ] End Loop Show Custom Dialog ["Result"; $html]
{ "language": "en", "url": "https://stackoverflow.com/questions/27050639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }