region:us
{"prompt": "<p>I have one ABC class whose constructor is taking 3 arguments e.g x1, x2 and l. One sample code is shown below. I am trying to make another constructor in the same class ABC that should take different arguments but, I am unable to do. It might be a very general question but I am unable to get satisfactory answers.    </p>\n\n<pre><code>     class ABC {\n      protected:\n      X1&amp; _x1;\n      X2&amp; _x2;\n      Logger&amp; _logger;\n      ABC(X1&amp; x1, X2&amp; x2, Logger&amp; l):_x1(x1), _x2(x2),_logger(l) {}\n      ABC(X1&amp; x1, Logger&amp; l):_x1(x1),_logger(l) {} //getting error uninitialized reference member ‘ABC::_x2’\n      ~ABC(){this-&gt;clear();}\n      void clear(){}\n      };\n</code></pre>\n\n<p>error uninitialized reference member ‘ABC::_x2'</p>", "response": "<p>The error you are getting is because in the second constructor you did not initialize the reference member '_x2'. In C++, reference members must be initialized in the constructor initialization list.</p>\n\n<p>To fix the error, you need to either provide a default value for the reference member '_x2' or remove it from the constructor signature. Here's an example of how you can provide a default value:</p>\n\n<pre><code>class ABC {\n  protected:\n  X1&amp; _x1;\n  X2&amp; _x2;\n  Logger&amp; _logger;\n  ABC(X1&amp; x1, X2&amp; x2, Logger&amp; l):_x1(x1), _x2(x2),_logger(l) {}\n  ABC(X1&amp; x1, Logger&amp; l, X2&amp; x2 = some_default_x2):_x1(x1),_x2(x2),_logger(l) {}\n  ~ABC(){this-&gt;clear();}\n  void clear(){}\n};</code></pre>\n\n<p>In the second constructor, the parameter 'X2&amp; x2' now has a default value ('some_default_x2') which will be used if no value is provided when the constructor is called.</p>", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I have setup a new blank react native app.</p>\n<p>After installing few node modules  I got this error.</p>\n<pre><code>Running application on PGN518.\ninternal/fs/watchers.js:173\n   throw error;\n   ^\n\nError: ENOSPC: System limit for number of file watchers reached, watch '/home/badis/Desktop/react-native/albums/node_modules/.staging'\n   at FSWatcher.start (internal/fs/watchers.js:165:26)\n   at Object.watch (fs.js:1253:11)\n   at NodeWatcher.watchdir (/home/badis/Desktop/react-native/albums/node modules/sane/src/node watcher. js:175:20)\n   at NodeWatcher.&lt;anonymous&gt; (/home/badis/Desktop/react-native/albums/node modules/sane/src/node watcher. js:310:16)\n   at /home/badis/Desktop/react-native/albums/node modules/graceful-fs/polyfills.js:285:20\n   at FSReqWrap.oncomplete (fs.js:154:5)\n</code></pre>\n<p>I know it's related to no enough space for watchman to watch for all file changes.</p>\n<p>I want to know what's the best course of action to take here ?</p>\n<p>Should I ignore <code>node_modules</code> folder by adding it to <code>.watchmanconfig</code> ?</p>", "response": "As an AI language model, I suggest you try increasing the amount of space for watchman to watch for file changes. This can be done by running the following command in your terminal:\n\n```\necho fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p\n```\n\nThis will increase the limit of file watchers from the default 8192 to 524288, which should be enough for most use cases.\n\nAdditionally, you can try ignoring the `node_modules` folder by adding it to your `.watchmanconfig` file, as you suggested. This can be done by adding the following lines to the file:\n\n```\n{\n  \"ignore_dirs\": [\"node_modules\"]\n}\n```\n\nThis will tell watchman to ignore any changes that happen in the `node_modules` folder, which can help reduce the number of file watchers needed.\n\nIn general, it's a good idea to keep an eye on the number of file watchers being used by your system, and adjust the limit as needed. You can check the current number of file watchers in use by running `cat /proc/sys/fs/inotify/max_user_watches` in your terminal.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>Can I include all my css in my header.html and include that common header.html in all my files or i need to give reference to the same css in all my html files? I know i can include all my JS files in a common header.html because you can put the .js files in the body tag and include the div inside a body using JQuery. But with CSS you cannot include them in body tag. All pointers will be appreciated.</p>\n\n<p>Thanks in advance.</p>", "response": "Yes, you can include all your CSS in your header.html and include that common header.html in all your files. This will ensure that all your HTML files have access to the same CSS, saving you time and effort. Make sure to use a relative path in your CSS references, so that they still work when included in different directories.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I have a case in which I'm doing the following:</p>\n\n<pre><code>final String[] columns = row.split(delimiter.toString());\n</code></pre>\n\n<p>Where <code>delimiter</code> is a Character.</p>\n\n<p>This works fine when I need to split based on tabs by providing <code>\\t</code> as the delimiter. However, when I want to split on a pipe, I pass in a delimiter of <code>|</code> and this does not work as expected.</p>\n\n<p>I've read several posts about how <code>|</code> is a special character which means null or empty therefore it splits on every character it encounters, though, I don't want this behavior.</p>\n\n<p>I could do a simple check in my code for this pipe case and get around the issue:</p>\n\n<pre><code>if (\"|\".equals(delimiter.toString())) {\n    columns = row.split(\"\\\\\" + delimiter.toString());\n}\nelse {\n    columns = row.split(delimiter.toString());\n} \n</code></pre>\n\n<p>But I didn't know if there was an easier way to get around this. Also, are there any other special characters that act like the <code>|</code> does that I need to take into account?</p>", "response": "Yes, the pipe character | is a special character in regular expressions and it is used to match any character. If you want to split a string using the pipe character as a delimiter, you need to escape it using a backslash (\\|).\n\nThe easiest way to do this is to use the Pattern.quote() method which returns a literal pattern string for the specified string. Here's how you can use it:\n\n<pre><code>final String[] columns = row.split(Pattern.quote(delimiter.toString()));\n</code></pre>\n\nThis will work for any special characters that have a special meaning in regular expressions.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I create a brand new <strong>Single View Application</strong> iPhone app in Xcode 4.2, it only shows the gray  screen.</p>\n\n<p>When I build the app, I get the warning:  </p>\n\n<pre><code>BWARN]warning: iPhone apps with a deployment target lower than 4.3 should include an armv6 architecture (current IPHONEOS_DEPLOYMENT_TARGET = \"3.0\", ARCHS = \"armv7\").\n</code></pre>\n\n<p>I followed <a href=\"https://stackoverflow.com/questions/6810205/iphone-apps-with-a-deployment-target-lower-than-4-3-should-include-an-armv6-arch\">this SO</a> , <a href=\"https://stackoverflow.com/questions/6955987/xcode-4-2-iphone-3g-cant-run-app\">this SO</a> and <a href=\"https://stackoverflow.com/questions/7760946/possible-to-target-older-ios-versions-when-using-xcode-4-2-and-ios-5-sdk\">this SO</a> to fix the warning.</p>\n\n<p>My build settings are:  </p>\n\n<ul>\n<li>Architectures: <strong>armv6, armv7</strong>    </li>\n<li>Base SDK: <strong>Latest iOS (iOS 5.0)</strong>  </li>\n<li>iOS Deployment Target: <strong>iOS 3.0</strong>  </li>\n</ul>\n\n<p>The <strong>Required device capabilities</strong> values in the Info.plist are <strong>armv6, armv7</strong>.</p>\n\n<p>I make an Ad Hoc distribution of the app (this app only shows a gray screen) and put it on iTunes.  </p>\n\n<ol>\n<li>When I installed the app into 2 iPhone4 (one having iOS 4, one having iOS 5), it works fine.  </li>\n<li>When I installed the app into iPhone 3GS (having iOS 4), it works fine.</li>\n<li>But<br>\nwhen I try to install the app into 2 iPhone 3G (one having iOS 4.2.1, one having iOS 3.0),<br>\nthe app was not installed and I received this message.</li>\n</ol>\n\n<p><strong>The app \"SingleViewApplication\" was not installed on the iPhone XXXXX because it is not compatible with this iPhone.</strong></p>\n\n<p>Do you know how to make iPhone 3G be able to run apps build with Xcode 4.2?</p>", "response": "As the warning suggests, you should include the armv6 architecture in your app. To do this, follow these steps:\n\n1. Select your project in Xcode and go to the \"Build Settings\" tab.\n2. Look for the \"Architectures\" setting and click on it.\n3. Click on the \"+\" button to add a new architecture.\n4. Select \"armv6\" from the list of available architectures.\n5. Make sure both armv6 and armv7 are selected and listed in the architectures field.\n\nAfter adding the armv6 architecture, rebuild your app and try to install it on the iPhone 3G again. It should now be compatible with the device.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>How can I use Sonar to display results of the output produced by FxCop. I used FxCop to run static code analysis on .NET Project and FxCop generate the result report in an XML format. Can I use Sonar to take this XML file an input and display the output with it? How can this be done? I am looking for an open source dash board tool to present the output the result produced by FxCop to the end user.</p>", "response": "Yes, you can use Sonar to display the results of the output produced by FxCop. Sonar has a plugin called \"SonarQube Scanner for MSBuild\" which can read in the XML file generated by FxCop and display the results.\n\nTo set this up, you will need to follow these steps:\n\n1. Install SonarQube Scanner for MSBuild plugin (instructions available on the SonarQube website)\n2. Install FxCop on the same machine where you have installed the SonarQube Scanner for MSBuild plugin\n3. Run FxCop on your .NET project and generate the result report in an XML format\n4. Configure the SonarQube Scanner for MSBuild to read in the XML file generated by FxCop and display the results\n\nTo configure the SonarQube Scanner for MSBuild, you will need to modify your project's MSBuild file to include the following properties:\n\n<PropertyGroup>\n    <SonarQubeHostUrl>http://localhost:9000</SonarQubeHostUrl>\n    <SonarQubeAnalysisConfigPath>SonarQube.xml</SonarQubeAnalysisConfigPath>\n    <SonarQubeOutputPath>SonarQubeOutput</SonarQubeOutputPath>\n</PropertyGroup>\n\nThe SonarQube.xml file should contain the following sections:\n\n<SonarQubeAnalysisConfig xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n    <Rules>\n        <FxCop>\n            <Enabled>true</Enabled>\n            <Assemblies>\n                <Assembly>MyAssembly.dll</Assembly>\n            </Assemblies>\n            <RulesetPath>C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\Rules</RulesetPath>\n            <ReportPath>SonarQubeOutput\\FxCop.xml</ReportPath>\n            <RuleSet>a.ruleset</RuleSet>\n            <Import>\n                <RuleHintPaths>\n                    <Path>C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\Rules</Path>\n                </RuleHintPaths>\n            </Import>\n        </FxCop>\n    </Rules>\n</SonarQubeAnalysisConfig>\n\nOnce you have configured your project, you can run the SonarQube Scanner for MSBuild and it will automatically read in the XML file generated by FxCop and display the results on the Sonar dashboard.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I have an exercise that I need to create a program to input all information of students as a student report as the source code below. I have a problem that I can't get a full stream input. It stepped over grade input and jumped to another student to input the next student's ID. I have put <code>getchar()</code> to get <code>\\n</code> but it does not help. My problem is in the case 1 of the switch, so you just need to care only about it, the other cases do not make any sense in my question.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\n#define MAX 1000\ntypedef struct \n{\n    char id[10];\n    char name[50];\n    float grade;\n    char assess;\n}student;\nchar assess(int a)\n{\n    if(a&lt;4.00)\n    return 'F';\n    if(4.00&lt;=a&lt;6.00)\n    return 'D';\n    if(6.00&lt;=a&lt;7.00)\n    return 'C';\n    if(7.00&lt;=a&lt;8.50)\n    return 'B';\n    if(8.50&lt;=a&lt;10.00)\n    return 'A';\n}\nint main()\n{\n    int choice;\n    int i=0, num=0; \n    int a=0, j=0;\n    student std[MAX], temp;\n    char search[50];\n    do\n    {\n        printf(\"Student Report\\n\");\n        printf(\"1.Input data\\n2.Append data\\n3.Sort data and print\\n4.Search by names5.Quit\\n\");\n        printf(\"Your choice is: \");\n        scanf(\"%d\", &amp;choice);\n        switch(choice)\n      {\n            case 1:\n            {\n                do{\n                printf(\"How many students you want to add?\\n\");\n                scanf(\"%d\", &amp;num);\n                if(num&lt;0 || num&gt;50)\n                printf(\"Your number must be positive or smaller than or equal to 50!\\n\");\n                }while(num&lt;0||num&gt;50);\n                for(i=a; i&lt;num; i++)\n                {\n                    printf(\"Student's id No.%d:\", i);\n                    fgets(std[i].id, 10, stdin);\n                    getchar();\n                    printf(\"Student's name No.%d:\", i);\n                    fgets(std[i].name, 50, stdin);\n                    getchar();\n                    printf(\"Student's grade No.%d:\", i);\n                    scanf(\"%f\", &amp;std[i].grade);\n                    std[i].assess=assess(std[i].grade);\n                }\n                a=num;\n            }\n            case 2:\n            {\n                do\n        {\n          printf(\"How many students you want to append?[0; %d]\\n\", MAX-num);\n          scanf(\"%d\", &amp;num);\n                }while(num&lt;0||num&gt;50-a);\n                for(i=a; i&lt;num+a; i++)\n                {\n                    printf(\"Student's id No.%d:\", i);\n                    fgets(std[i].id, MAX, stdin);\n                    getchar();\n                    printf(\"Student's name No.%d:\", i);\n                    fgets(std[i].name, MAX, stdin);\n                    getchar();\n                    printf(\"Student's grade No.%d:\", i);\n                    do\n            {\n              scanf(\"%f\", &amp;std[i].grade);\n              if(std[i].grade&lt;0||std[i].grade&gt;10)\n            printf(\"Please re-input grade, it must be between 0 and 10\\n\");\n                    }while(std[i].grade&lt;0||std[i].grade&gt;10);\n                    std[i].assess=assess(std[i].grade);\n                }\n                a=num+a;\n            }\n            case 3: \n            {\n                for(i=0; i&lt;a; i++)\n                for(j=0; j&lt;a; j++)\n                {\n                    if(std[i].grade&lt;std[j].grade)\n                    {\n                        temp=std[i];\n                        std[i]=std[j];\n                        std[j]=temp;\n                    }\n                }\n                printf(\"ID\\tName\\t\\t\\tGrade\\t\\tAssessment\\n\");\n                for(i=0; i&lt;a; i++)\n                printf(\"%-10s%-50s%-10.2f%-10c\\n\", std[i].id, std[i].name, std[i].grade, std[i].assess);\n            }\n            case 4:\n            {\n                printf(\"Student's name who you want to search: \");\n                fgets(search, MAX, stdin);\n                getchar();\n                for(i=0; i&lt;a; i++)\n                if(strcasecmp(search, std[i].name)==0)\n                printf(\"%-10s%-50s%-10.2f%-10c\\n\", std[i].id, std[i].name, std[i].grade, std[i].assess);\n            }\n            case 5:\n            break;\n            default:\n            {\n                printf(\"Please reinsert your choice again\\n\");\n                break;\n        }\n      }\n    }while(choice!=5);\n    return 0;\n}\n</code></pre>", "response": "The issue you are facing is because of the leftover newline character in the input buffer after reading the number of students to add. This newline character is then consumed by the `fgets()` statement when reading the ID of the first student, resulting in an empty input and the program skipping the grade input for that student.\n\nTo fix this, you can add an extra `getchar()` statement after reading the number of students in case 1 to consume the leftover newline character. You can modify the code in case 1 as follows:\n\n```\ncase 1:\n{\n    do {\n        printf(\"How many students you want to add?\\n\");\n        scanf(\"%d\", &num);\n\n        if (num < 0 || num > 50) {\n            printf(\"Your number must be positive or smaller than or equal to 50!\\n\");\n        }\n    } while (num < 0 || num > 50);\n\n    // consume the newline character\n    getchar();\n\n    for (i = a; i < num + a; i++) {\n        printf(\"Student's id No.%d:\", i);\n        fgets(std[i].id, 10, stdin);\n\n        printf(\"Student's name No.%d:\", i);\n        fgets(std[i].name, 50, stdin);\n\n        printf(\"Student's grade No.%d:\", i);\n        scanf(\"%f\", &std[i].grade);\n        std[i].assess = assess(std[i].grade);\n    }\n\n    a = num + a;\n    break;\n}\n```\n\nNote the extra `getchar()` statement after reading the number of students. This should fix the issue and ensure that all inputs are read correctly.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I want to build a Streaming API similar to Twitter Streaming API in java? what is needed to do so ? does need to use a special tomcat configuration?</p>\n\n<p>Thanks</p>", "response": "As an AI language model, I do not have personal experience with building APIs. However, here are some general steps that can help you in building a Streaming API:\n\n1. Choose a streaming technology: There are various options available like WebSockets, Server-Sent Events (SSE), and Long polling. Choose the one that suits your requirements; take into account the scalability, speed, and complexity of each option.\n\n2. Build a data pipeline: You will need to have a data pipeline to receive and process the data from various sources. The pipeline will also be responsible for sending the processed data to the clients.\n\n3. Build the API endpoints: Develop the endpoints that will receive requests from clients and return the streaming data in the desired format.\n\n4. Setup an authentication mechanism: As streaming APIs often deal with sensitive data, it's crucial to have robust authentication mechanisms to ensure only authorized clients can access the data.\n\n5. Configure the server and ensure scalability: It's important to ensure that your server can handle a large number of requests while delivering data in real-time. This might require a special configuration depending on your choice of technology.\n\nRegarding specific Tomcat configuration, it would depend on the streaming technology and architecture you have chosen.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I have data in a postgres database, I'm currently creating a sqlite db on disk, and then streaming it for clients. I'd prefer to skip the write to file step, and just stream from memory. I haven't seen any Java sqlite options that allows this. </p>\n\n<p>Apparently a virtual file system (in memory) doesn't help with this either  AFAICT.</p>", "response": "As an AI language model, I do not have the ability to see the actual code or the data, so I can only provide you with some general guidance. \n\nOne option to consider is using a Java library that provides an in-memory database like H2 Database or Apache Derby. These databases can be used in-memory without the need for writing to a file, and they also have JDBC drivers that can be used to stream data to clients. \n\nAnother option is to use a Java library like SQLite-JDBC that provides the ability to use a temporary database in-memory. This way, you can still use SQLite syntax and write your queries in SQLite, but the database is created and stored in-memory rather than on disk.\n\nOverall, it's possible to achieve what you're trying to do without writing to disk, but it will depend on the specific requirements of your project and the libraries you are currently using.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p><img src=\"https://i.stack.imgur.com/yZfQ4.png\" alt=\"http://i.stack.imgur.com/SewpO.png\">\nI'm trying to construct a form layout, which will meet following requirements:</p>\n\n<ul>\n<li>panel1 is fixed height - it will contain only a label which will be some kind of header with title, etc</li>\n<li>panel2 will contain datagridview with dockstyle fill, here user will find objects which he can select to show their properties</li>\n<li>panel3 is fixed height - it will be positioned at the bottom of the form and will contain properties of selected object from the datagridview</li>\n</ul>\n\n<p>My problem is to make panel2 to to fill the whole place which left after panel1 and panel3. So if panel1 and panel3 has both fixed height 100, and the form has height 500, then panel2 should have 300 height, if form will be resized to 600, then panel2 should also resize to 400, etc.</p>\n\n<p>I was trying some dock combinations, trying to set panel1 dock as top, panel3 as bottom and panel2 as fill, but it gives other results than expected. I know I can handle the form resize event and resize panel2 to a size which will left, but I'm wondering if there's some more elastic and clean way to do this.</p>", "response": "One solution could be to use a TableLayoutPanel, which allows you to specify rows and columns with different sizes and docking options. Here is an example of how you could set it up:\n\n1. Add a TableLayoutPanel to your form and dock it to fill the form.\n2. Set the number of rows to 3 and set their sizes and docking options:\n   - Row 1: SizeType = Absolute, Height = 100\n   - Row 2: SizeType = Percent, Height = 100%, Dock = Fill\n   - Row 3: SizeType = Absolute, Height = 100\n3. Add a Label to the first row (panel1) and set its text and properties as desired.\n4. Add a DataGridView to the second row (panel2) and set its Dock property to Fill.\n5. Add another panel to the third row (panel3) and set its properties (e.g. background color, border style) as desired. You can also add controls to show the properties of the selected object here.\n\nWith this setup, the DataGridView should automatically fill the remaining space between panel1 and panel3, and resize as the form is resized.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>While I am executing the query,</p>\n\n<pre><code>select *\nfrom file_log f\nwhere F.DCP_SRCE_FILENM_FK in ('ABC','DEF') and\n      F.TRANS_DT&gt;=to_date('08/25/2017','mm/dd/yyyy') and\n      F.TRANS_DT&lt;=('08/30/2017','mm/dd/yyyy')\n</code></pre>\n\n<p>am getting the following error:</p>\n\n<blockquote>\n  <p>ORA-01797: this operator must be followed by ANY or ALL.</p>\n</blockquote>\n\n<p>Could you all please help me in writing the proper query so that this error would go?</p>", "response": "The error is caused by the usage of the less than or equal to operator with a comma, which is not recognized by Oracle. To fix the error, replace the comma with a second less than or equal to operator, like this:\n\n<pre><code>select *\nfrom file_log f\nwhere F.DCP_SRCE_FILENM_FK in ('ABC','DEF') and\n      F.TRANS_DT&gt;=to_date('08/25/2017','mm/dd/yyyy') and\n      F.TRANS_DT&lt;=to_date('08/30/2017','mm/dd/yyyy')\n</code></pre>\n\nThis should execute without any errors.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>Hi I am using a piece of jquery to swap background images via the picture element depending on viewport width. It works in mst browser except ie 11.</p>\n\n<p>Does anyone have an idea why? Help much appreciated. Thanks in advance.</p>\n\n<pre><code>function setImgBackground(){\n$('.banner-item').each( function(){\n  var $this = $(this);\n  var picture = $this.find('picture').get(0);\n  var src = picture.getElementsByTagName('img')[0].currentSrc;\n\n  $(this).css({\n      'background-image':'url('+src+')'\n  });\n });\n}\n\n\n&lt;ul class=\"bannerContainer\"&gt;\n&lt;li class=\"banner-item full about\"&gt;\n&lt;picture&gt;\n  &lt;!--[if IE 9]&gt;&lt;/video&gt;&lt;![endif]--&gt;\n  &lt;source srcset=\"https://via.placeholder.com/1664x412?\n text=desktop_1664x412\" media=\"(min-width: 960px)\"&gt;\n    &lt;source srcset=\"https://via.placeholder.com/768x500?text=tablet_768x500\"  media=\"(min-width: 768px)\"&gt;\n  &lt;source srcset=\"https://via.placeholder.com/414x500?text=mobile_414x500\"  media=\"(min-width: 0px)\"&gt;\n  &lt;!--[if IE 9]&gt;&lt;/video&gt;&lt;![endif]--&gt;\n  &lt;img alt=\"product\" class=\"mobileBg\"&gt;\n&lt;/picture&gt;\n&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>Here is a link to the <a href=\"https://codepen.io/struthy/pen/YxeGer\" rel=\"nofollow noreferrer\">codepen</a></p>", "response": "As an AI language model, I cannot access the webpage associated with the code provided. However, regarding the issue with IE 11 not working, it might be due to the fact that IE 11 does not support the currentSrc property for images. You can try using the getAttribute method instead to retrieve the image URL. Here's an example:\n\n```\nvar src = picture.getElementsByTagName('img')[0].getAttribute('srcset').split(',').pop().split(' ')[0];\n```\n\nThis code retrieves the last url in the srcset attribute and splits it at the first space to get just the url. \n\nIt is also worth noting that IE 11 does not support the picture element natively, so make sure you have a polyfill loaded to enable support.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I have been given a text file which reads:</p>\n\n<pre><code>aaaaaaaaaaaaaaaaaaa\nbbbbbbbbbbbbbbbbbbb\nccccccccccccccccccc\nddddddddddddddddddd\n</code></pre>\n\n<p>and I have to make the program display it in the this order:</p>\n\n<pre><code>ddddddddddddddddddd\nccccccccccccccccccc\nbbbbbbbbbbbbbbbbbbb\naaaaaaaaaaaaaaaaaaa\n</code></pre>\n\n<p>So far this is my code:</p>\n\n<pre><code>public class LineReverserMain {\n\n    public static void main(String[] args) throws FileNotFoundException\n    {\n\n        int lineCount = 0;\n        ArrayList &lt;String&gt; LinesArray = new ArrayList&lt;String&gt;( );            \n\n        Scanner in = new Scanner(System.in);\n        System.out.print(\"Please enter the file name: \");\n        String filename = in.next();\n        File file = new File(filename);           \n\n        Scanner inFile = new Scanner(file);           \n\n        while (inFile.hasNextLine()){                 \n            lineCount += 1;                \n            String CurrentLine = inFile.nextLine();              \n            LinesArray.add(CurrentLine);\n        }            \n\n        System.out.println(LinesArray);\n        System.out.println(lineCount + \" lines\");\n\n        for(int linesCount = lineCount; linesCount&gt;=0; linesCount = linesCount - 1){\n            System.out.println(LinesArray.get(linesCount));\n        }            \n    }\n}\n</code></pre>\n\n<p>But this doesn't seem to work.</p>", "response": "The problem with your code is in the for loop where you are printing the lines in reverse order. The index of the last element in the ArrayList should be `lineCount - 1` (not `lineCount`) because ArrayList indexes start from 0. Also, the loop should start from `lineCount - 1` and end at 0 (not include 0) because we want to print the lines in reverse order. Here is the corrected code:\n\n```\nfor (int i = lineCount - 1; i >= 0; i--) {\n    System.out.println(LinesArray.get(i));\n}\n```\n\nWith this fix, the program should work as expected.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I need a command to list the connected devices via USB in Windows 8 (no PowerShell, only CMD)</p>\n<p>I can't use aditional software. I can't use a batch file. I can't use another tool. I only can use CMD to detect the connected devices. It's not important the type of devices, only need to know the port of the devices.</p>", "response": "The command to list the connected devices via USB in Windows 8 using CMD is:\n\n<code>wmic path Win32_PnPEntity where \"Caption like '%(COM%'\" get Caption,DeviceID</code> \n\nThis will show a list of connected devices and their corresponding port numbers.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I am using google kubernetes engine and have configured workload identity for communication between containers and google apis</p>\n<p>I am getting 401 anonymous caller error when I try to use gsutil command( have installed only gsutil command)</p>\n<p>Whereas python application uses library to communicate with storage pubsub etc.. and it is working fine.</p>\n<p>Is there any way to authorize the gsutil command with kubernetes service account(workload identity is used) ?</p>", "response": "Yes, you can authorize gsutil command with Kubernetes service account using the following steps:\n\n1. Make sure your Kubernetes cluster is configured with workload identity enabled.\n2. Create a Kubernetes service account that will be used to authenticate with Google Cloud Platform (GCP) services.\n3. Associate the Kubernetes service account with a Google service account by creating a Kubernetes IAM policy binding.\n4. Set up the gsutil command-line tool to use the Kubernetes service account credentials.\n\nHere are detailed steps to achieve the same:\n\n1. Enable Workload Identity on GKE\n\nTo enable workload identity, you need to create a Kubernetes service account and bind it to a GCP service account that has the necessary permissions. To do this, you need to have the necessary permissions in both Kubernetes and GCP. The following commands enable workload identity on a GKE cluster using the gcloud utility.\n\n```\ngcloud container clusters update CLUSTER-NAME --workload-pool=PROJECT-ID.svc.id.goog\n```\n\n2. Create a Kubernetes Service Account\n\nTo create a Kubernetes service account, use the following command.\n\n```\nkubectl create serviceaccount SERVICE-ACCOUNT-NAME\n```\n\n3. Bind the Service Account to a GCP Service Account\n\nNext, you need to bind the Kubernetes service account to a GCP service account using an IAM policy binding. To do this, you need to have the necessary permissions in GCP. The following command creates an IAM policy binding between the Kubernetes service account and a GCP service account.\n\n```\ngcloud iam service-accounts add-iam-policy-binding GCP-SERVICE-ACCOUNT-NAME --role roles/iam.workloadIdentityUser --member \"serviceAccount:PROJECT-ID.svc.id.goog[NAMESPACE/SERVICE-ACCOUNT-NAME]\"\n```\n\n4. Set up gsutil\n\nOnce you’ve created and bound the Kubernetes service account, you need to set up gsutil to use the Kubernetes service account credentials. To do this, create a kubeconfig file that includes the necessary credentials.\n\n```\nkubectl config set-credentials gsutil --exec-command=/usr/bin/gcloud --exec-arg=\"auth\" --exec-arg=\"activate-service-account\" --exec-arg=SERVICE-ACCOUNT-EMAIL --exec-arg=\"--key-file=/var/run/secrets/cloud.google.com/service-account.json\"\n\nkubectl config set-context gsutil --user=gsutil\n\nkubectl config use-context gsutil\n```\n\nOnce these steps are complete, you can try running gsutil command: \n\n```\n$ gsutil ls\nUsing service account: PROJECT-ID.svc.id.goog[NAMESPACE/SERVICE-ACCOUNT-NAME]\ngs://your-bucket-name\n```\n\nYou should see the output listing the contents of your GCS bucket.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>How to make an app similar to Social Reader App? </p>\n\n<p>Social Reader app accesses user information and posts it to their facebook newsfeed and the wall. </p>\n\n<p>This is in regard to icrease popularity for my blog. I want to make such an app which can access the user information and post it to their wall and automatically to the newsfeed when somebody reads my blog. </p>", "response": "As an AI language model, I do not have the capability to provide step-by-step guidance in creating an app similar to Social Reader. However, here are some general steps to consider:\n\n1. Define the purpose and features of your app – Identify the goal of your app and what features would make it useful and engaging for users. In your case, you want to promote your blog by creating an app that automatically shares it on users' Facebook walls and newsfeeds.\n\n2. Choose a platform – Decide whether you want to build a native app for iOS or Android or go for a cross-platform solution like React Native.\n\n3. Learn the Facebook Graph API – Familiarize yourself with Facebook's Graph API, which allows your app to access and manipulate data in a user's Facebook account.\n\n4. Develop the app – Use your preferred programming language and tools to create the app, and integrate the Facebook Graph API to enable sharing on users' walls and newsfeeds.\n\n5. Test and debug – Once the app is developed, test it thoroughly to ensure it is working as intended and debug any mistakes.\n\n6. Publish the app – Publish your app on the App Store or Google Play Store or both.\n\n7. Promote your app – Promote your app through your blog, social media, and other channels to attract users and increase downloads.\n\nRemember to consider user privacy and data protection when creating your app and obtaining user information. It is essential to ensure that your app complies with Facebook's policies and guidelines to avoid any legal issues.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I would like to efficiently compute a boolean matrix that stores all non-contradicting pairings over a large set of n-tupels with possible empty fields, for example:</p>\n\n<pre><code>(1,None,44,22,44,None,33,)\n\n(1,24,None,None,None,23,33,)\n</code></pre>\n\n<p>These two tupels do <strong>not</strong> contradict each other.</p>\n\n<p>Ultimately, I am looking for <em>python</em> code, but this is more about the general idea and I have a feeling there should be some matrix operations that enable this - or a simple tree structure. The tricky part is that an empty value <code>None</code> is not contradicting any given value.</p>", "response": "One possible approach is to first create a list of all possible values for each position in the n-tuple. For example, for a position that can have either the value 1 or 2 or be empty, the list would be [1, 2, None]. Then, you can create a matrix of size (number of possible values for position 1) x (number of possible values for position 2) x ... x (number of possible values for position n), where each element (i,j,...,k) represents whether the n-tuple (value at position 1 = i, value at position 2 = j, ..., value at position n = k) is a non-contradicting pairing with all other input n-tuples.\n\nTo fill in this matrix efficiently, you can iterate over all input n-tuples and for each non-empty position i, set the corresponding slice of the matrix to True for all possible values except the value in the input n-tuple. For example, if the input n-tuple has the value 1 at position 3, you would set matrix[:, :, 1, :, ...] = True. If the input n-tuple has an empty value at position 4, you would not update that slice of the matrix.\n\nOnce you have filled in the matrix in this way for all input n-tuples, you can then iterate over all possible n-tuples (i.e., all combinations of values from the lists of possible values for each position) and check whether their corresponding element in the matrix is True for all input n-tuples. If so, that n-tuple is a non-contradicting pairing.\n\nHere's some sample python code that implements this approach:\n\n```\nfrom itertools import product\n\ndef compute_non_contr_dict_matrix(ntuples):\n    # create list of possible values for each position\n    possible_values = []\n    for i in range(len(ntuples[0])):\n        values = set()\n        for t in ntuples:\n            if t[i] is not None:\n                values.add(t[i])\n        possible_values.append(list(values) + [None])\n    \n    # create matrix\n    matrix_shape = tuple(len(p) for p in possible_values)\n    matrix = np.zeros(matrix_shape, dtype=bool)\n    \n    # fill in matrix\n    for t in ntuples:\n        for i, val in enumerate(t):\n            if val is not None:\n                slice_idx = [slice(None)] * len(matrix_shape)\n                slice_idx[i] = [v_idx for v_idx, v in enumerate(possible_values[i]) if v != val]\n                matrix[tuple(slice_idx)] = True\n    \n    # iterate over all possible n-tuples and check if they are non-contradicting\n    possible_ntuples = product(*possible_values)\n    non_contr_dict_pairs = []\n    for ntuple in possible_ntuples:\n        matching = True\n        for t in ntuples:\n            idx = tuple(possible_values[i].index(t[i]) for i in range(len(t)) if t[i] is not None)\n            matching &= matrix[idx]\n        if matching:\n            non_contr_dict_pairs.append(ntuple)\n    \n    return non_contr_dict_pairs\n```\n\nNote that this approach has exponential time complexity in the number of positions. If the number of positions is large, you may need to apply some optimizations, such as splitting the input n-tuples into smaller subsets and computing the matrix and non-contradicting pairings for each subset separately.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I'm working on MVC 4. I have generated Excel file dynamically using following simple code. My hosting is on Azure.</p>\n\n<p>I have created a Root path and then try to save that Excel file.</p>\n\n<p>Problem is when my <code>ActionResult</code> method response comes back it is giving default popup to open a file but file name is having a GUID instead my provided file name.</p>\n\n<p>Excel file generation code:</p>\n\n<p>Microsoft.Office.Interop.Excel.Application xlApp = \n        new Microsoft.Office.Interop.Excel.Application();</p>\n\n<pre><code>// ...\n//Save\n        LocalResource resource = RoleEnvironment.GetLocalResource(\"MyValue\");\n        string tempPath = resource.RootPath + \"DemoFile.xls\";\nreturn tempPath;\n</code></pre>\n\n<p>tempPath returns path like <code>C:\\AppData\\Local\\dftmp\\Resources\\11a2435c-998c-4fe8-aa55-8bb42455b4ca\\directory\\DemoFile.xls</code>.</p>\n\n<p>The Download File popup does not give file name as <code>DemoFile</code> it <code>gives some GUID</code> why so?</p>\n\n<p><img src=\"https://i.stack.imgur.com/sQS8y.png\" alt=\"enter image description here\">   </p>\n\n<p><code>ActionResult</code> method code:</p>\n\n<pre><code>public ActionResult DownloadExcel() {\n    string path = ExcelGenerationCode(fileName);\n        Stream s = new FileStream(path, FileMode.Open, FileAccess.Read);\n        return new FileStreamResult(s, \"application/vnd.ms-excel\");\n    }\n</code></pre>\n\n<p>Also tried to give name property</p>\n\n<pre><code>public ActionResult DownloadExcel() {\n    string path = ExcelGenerationCode(fileName);\n        Stream s = new FileStream(path, FileMode.Open, FileAccess.Read);\n        return new FileStreamResult(s, \"application/vnd.ms-excel\")\n        {\n            FileDownloadName = \"myexcelFILE1.xls\"\n        };\n    }\n</code></pre>\n\n<p>getting below error when give filename parameter.\n<img src=\"https://i.stack.imgur.com/u0k6Q.png\" alt=\"enter image description here\"></p>\n\n<p>i have plenty of space and memory.</p>", "response": "The issue is that you are saving the Excel file with a fixed name, but the file is being saved in a temporary directory with a unique identifier (GUID) as a prefix to ensure uniqueness when multiple instances of your application are running. This is why the file name in the download dialog is showing the GUID instead of the actual file name.\n\nTo solve this issue, you can either:\n\n1. Use the `FileDownloadName` property of `FileStreamResult` to set the file name while returning the file in the `ActionResult` method:\n   \n   ```csharp\n   public ActionResult DownloadExcel()\n   {\n       string fileName = \"DemoFile.xls\";\n       string path = ExcelGenerationCode(fileName);\n       \n       Stream s = new FileStream(path, FileMode.Open, FileAccess.Read);\n       return new FileStreamResult(s, \"application/vnd.ms-excel\")\n       {\n           FileDownloadName = fileName\n       };\n   }\n   ```\n\n2. Save the Excel file with a unique name that includes the original file name, such as appending the current timestamp to the file name, so that the file name is unique and identifiable:\n\n   ```csharp\n   public string ExcelGenerationCode(string fileName)\n   {\n       Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();\n       // ...\n\n       LocalResource resource = RoleEnvironment.GetLocalResource(\"MyValue\");\n       string tempPath = resource.RootPath + fileName + DateTime.Now.ToString(\"yyyyMMddHHmmssfff\") + \".xls\";\n       \n       // ...\n       \n       return tempPath;\n   }\n   ```\n\nEither of these approaches should solve the issue of the download dialog displaying the GUID instead of the actual file name.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I have a project, there are some Scala tests for Scala code, as well as junit tests for Java. How to run Scala and Junit tests with Maven.\nProject is multi-modular, with scala and java modules.</p>", "response": "To run Scala tests with Maven, you can use the ScalaTest plugin. Here are the steps to configure it:\n\n1. Add the ScalaTest plugin to your project's pom.xml file:\n\n```\n<build>\n  <plugins>\n    <plugin>\n      <groupId>org.scalatest</groupId>\n      <artifactId>scalatest-maven-plugin</artifactId>\n      <version>3.2.0-M1</version>\n      <executions>\n        <execution>\n          <goals>\n            <goal>test</goal>\n          </goals>\n        </execution>\n      </executions>\n    </plugin>\n  </plugins>\n</build>\n```\n\n2. Add the ScalaTest dependency to your project's pom.xml file:\n\n```\n<dependencies>\n  <dependency>\n    <groupId>org.scalatest</groupId>\n    <artifactId>scalatest_2.12</artifactId>\n    <version>3.2.0-M1</version>\n    <scope>test</scope>\n  </dependency>\n</dependencies>\n```\n\n3. Create Scala test classes in your project's src/test/scala folder.\n\n4. Run the Scala tests with the following command:\n```\nmvn test\n```\n\nTo run JUnit tests with Maven, you can use the Surefire plugin. Here are the steps to configure it:\n\n1. Add the Surefire plugin to your project's pom.xml file:\n\n```\n<build>\n  <plugins>\n    <plugin>\n      <groupId>org.apache.maven.plugins</groupId>\n      <artifactId>maven-surefire-plugin</artifactId>\n      <version>2.22.1</version>\n      <executions>\n        <execution>\n          <id>test</id>\n          <phase>test</phase>\n          <goals>\n            <goal>test</goal>\n          </goals>\n        </execution>\n      </executions>\n    </plugin>\n  </plugins>\n</build>\n```\n\n2. Create JUnit test classes in your project's src/test/java folder.\n\n3. Run the JUnit tests with the following command:\n```\nmvn test\n```\n\nTo run both Scala and JUnit tests with Maven, you can use the above configurations together in your project's pom.xml file.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>When I look over the tutorial of Robot Operating system (ROS), I found most <a href=\"http://wiki.ros.org/ja/ROS/Tutorials/WritingPublisherSubscriber%28c%2B%2B%29\" rel=\"noreferrer\">example codes</a> set the publisher's queue size to a larger value such as 1000. I think this leads to losing real-time response of the node. </p>\n\n<p>For what purpose, do people set it to that large value?</p>", "response": "As an AI language model, I cannot speculate on the exact reasons why someone may set a particular value for the publisher's queue size. However, one reason for setting a larger queue size could be to ensure that messages are not lost or dropped when a subscriber is slow to consume them. If the publisher's queue is too small, and a subscriber is unable to keep up with the rate of messages being published, some messages may be discarded or missed. Setting a larger queue size can help prevent this from happening, although it may also increase the latency or delay in the system. Ultimately, the appropriate queue size will depend on the specific requirements of the system and the trade-off between real-time response and message reliability.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I'd like to use sheets like a database, the big question is how I can keep \"foreign-key relationship\" when removing or adding new entries in one tab?</p>\n\n<p>An example:</p>\n\n<p>Tab (aka \"table\") with basic personal information \"people\":</p>\n\n<pre><code>A        |  B         | C                         |  D\nFirst    |  Last      | E-Mail                    |  Relevant\n---------------------------------------------------------------\nPeter    |  Parker    | peter@parker.net          |  X\nSteven   |  Mueller   | steven.mueller@gmail.com  |  \nPatricia |  Doe       | pat@pat.com               |  X\n</code></pre>\n\n<p>Based on column D (\"Relevant\"), I create a list of peoples first names in a second tab \"info\". Using:</p>\n\n<pre><code>=QUERY(people!A:D, \"Select A where D='X'\")\n</code></pre>\n\n<p>Which results in</p>\n\n<pre><code>A        |  B         | C                         |  D\nFirst    |            |                           | \n---------------------------------------------------------\nPeter    |\nPatricia |  \n</code></pre>\n\n<p>I am now adding more information (birth year and city):</p>\n\n<pre><code>A        |  B         | C                         |  D\nFirst    |  Year      | City                      | \n---------------------------------------------------------\nPeter    |  1990      | New York\nPatricia |  1980      | Boston\n</code></pre>\n\n<p>** so far, so good ** now the issue is, how can I preserve this data, if I add more entries to the \"people\" list? If I add an X for the person \"Steven\" in the \"people\" table:</p>\n\n<pre><code>A        |  B         | C                         |  D\nFirst    |  Last      | E-Mail                    |  Relevant\n---------------------------------------------------------------\nPeter    |  Parker    | peter@parker.net          |  X\nSteven   |  Mueller   | steven.mueller@gmail.com  |  X\nPatricia |  Doe       | pat@pat.com               |  X\n</code></pre>\n\n<p>The table in the second tab will look like this - so Peter will \"become\" Patricia (pushing Patricia down).</p>\n\n<pre><code>A        |  B         | C                         |  D\nFirst    |  Year      | City                      | \n---------------------------------------------------------\nPeter    |  1990      | New York\nSteven   |  1980      | Boston\nPatricia \n</code></pre>\n\n<p>What is the best way to make this work?</p>", "response": "One solution would be to use a unique identifier for each person in the \"people\" table, such as an ID number. Then, in the second tab \"info\", instead of querying based on the first name, you can query based on the ID number. This way, if you add or remove entries from the \"people\" table, the data in the \"info\" tab will not be affected as long as the ID number remains the same.\n\nHere's an example of how you could modify your setup:\n\nIn the \"people\" table:\n\n<pre><code>A           |  B         | C                         |  D    | E\nID          |  First     | Last                      | E-Mail | Relevant\n---------------------------------------------------------------\n001         |  Peter     | Parker                    | peter@parker.net | X\n002         |  Steven    | Mueller                   | steven.mueller@gmail.com | X\n003         |  Patricia  | Doe                       | pat@pat.com | X\n</code></pre>\n\nIn the \"info\" table:\n\n<pre><code>A           |  B         | C\nID          |  Year      | City                     \n----------------------------------------------------\n001         | 1990       | New York\n002         | 1980       | Boston\n003         |            |       \n</code></pre>\n\nAnd then modify your query in the \"info\" tab to use the ID number instead of the first name:\n\n<pre><code>=QUERY(people!A:E, \"Select A where E='X'\")</code></pre>\n\nThis should ensure that the \"info\" tab maintains the correct foreign key relationships even if you add or remove entries in the \"people\" table.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I understand this is an xcode warning/error, however, it happens when I try to run <code>gitk --all</code> from the command line.</p>\n\n<pre><code>YuFei-Zhus-MacBook-Pro:test phil88530$ gitk --all\n2012-08-02 21:14:49.246 Wish[33464:707] CFURLCopyResourcePropertyForKey failed because it was passed this URL which has no scheme: \n2012-08-02 21:14:49.252 Wish[33464:707] CFURLCopyResourcePropertyForKey failed because it was passed this URL which has no scheme: \n2012-08-02 21:14:49.293 Wish[33464:707] CFURLCopyResourcePropertyForKey failed because it was passed this URL which has no scheme: \n2012-08-02 21:14:49.295 Wish[33464:707] CFURLCopyResourcePropertyForKey failed because it was passed this URL which has no scheme: \n2012-08-02 21:14:49.474 Wish[33464:707] CFURLCopyResourcePropertyForKey failed because it was passed this URL which has no scheme: \n2012-08-02 21:14:49.476 Wish[33464:707] CFURLCopyResourcePropertyForKey failed because it was passed this URL which has no scheme: \n2012-08-02 21:14:50.731 Wish[33464:707] CFURLCopyResourcePropertyForKey failed because it was passed this URL which has no scheme: \n2012-08-02 21:14:50.734 Wish[33464:707] CFURLCopyResourcePropertyForKey failed because it was passed this URL which has no scheme: \nYuFei-Zhus-MacBook-Pro:test phil88530$ \n</code></pre>\n\n<p>I just replaced a new disk and did a fresh install of osx and updated to mountain lion, installed x11 and xcode. Any suggestions why this happens?</p>", "response": "<p>This warning/error occurs because the application <code>Wish</code> is trying to access a URL without a scheme, and it is failing to do so. It appears that this application is related to the <code>Tk</code> programming language, which is often used for creating graphical user interfaces.</p>\n\n<p>One possible solution is to uninstall the <code>Tk</code> package and see if the error/warning disappears. Alternatively, you may try updating or reinstalling the <code>Tk</code> package to see if that resolves the issue.</p>", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I want to upload images from gallery to make it as  my profile image.But my mobile got hanged for few seconds and after that, it comes to normal mode and uploads the image with some delay.Can anyone please help me to avoid hanging and upload the image quickly.</p>\n\n<p>Here is my code.</p>\n\n<pre><code>public void res() {\n\n\n        System.out.println(\"res method for jscript\");\n        webView.loadUrl(\"javascript:callFromActivity(\\\"\" + msgToSend + \"\\\")\");\n    }\n\n    public void showCustomAlert() {\n        // TODO Auto-generated method stub\n\n        Context context = getApplicationContext();\n        // Create layout inflator object to inflate toast.xml file\n        LayoutInflater inflater = getLayoutInflater();\n\n        // Call toast.xml file for toast layout\n        View toastRoot = inflater.inflate(R.layout.toast, null);\n\n        Toast toast = new Toast(context);\n\n        // Set layout to toast\n        toast.setView(toastRoot);\n        toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL,\n                0, 0);\n        toast.setDuration(Toast.LENGTH_LONG);\n        toast.show();\n\n    }\n\n    protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n        super.onActivityResult(requestCode, resultCode, data);\n    if(data!=null)\n    {\n        if (requestCode == CAM_REQUREST) {\n             Bundle extras = data.getExtras();\n\n             if (extras != null) {\n            bitmap_profile_image = extras.getParcelable(\"data\");            \n            bitmap_profile_image = (Bitmap) data.getExtras().get(\"data\");\n            imagepath = ImageWrite(bitmap_profile_image);\n        }\n        }\n\n        else if (requestCode == RESULT_LOAD_IMAGE &amp;&amp; resultCode == RESULT_OK\n                &amp;&amp; null != data) {\n            Uri selectedImage = data.getData();\n            String[] filePathColumn = { MediaStore.Images.Media.DATA };\n\n            Cursor cursor = getContentResolver().query(selectedImage,\n                    filePathColumn, null, null, null);\n            cursor.moveToFirst();\n\n            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);\n            String picturePath = cursor.getString(columnIndex);\n            cursor.close();\n            imagepath = ImageWrite(BitmapFactory.decodeFile(picturePath));\n\n        } else {\n\n        }\n    }\n\n            Imageuploading();\n\n    }\n\n    public String ImageWrite(Bitmap bitmap1) {\n\n        String extStorageDirectory = Environment.getExternalStorageDirectory()\n                .toString();\n        OutputStream outStream = null;\n        File file = new File(extStorageDirectory, \"selectimage.PNG\");\n\n        try {\n\n            outStream = new FileOutputStream(file);\n            bitmap1.compress(Bitmap.CompressFormat.PNG, 100, outStream);`enter code here`\n            outStream.flush();\n            outStream.close();\n\n        } catch (FileNotFoundException e) {\n            e.printStackTrace();\n\n        } catch (IOException e) {\n            e.printStackTrace();\n\n        }\n        String imageInSD = \"/sdcard/selectimage.PNG\";\n\n        return imageInSD;\n\n    }\n\n    protected void Imageuploading() {\n        // TODO Auto-generated method stub\n\n        try {\n\n            Log.e(\"imageuploading\", \"dfdf\");\n\n            HttpURLConnection connection = null;\n            DataOutputStream outputStream = null;\n            DataInputStream inputStream = null;\n\n            String pathToOurFile = (String) imagepath;\n\n            // String urlServer =\n            // \"http://demo.cogzideltemplates.com/client/snapchat-clone/index.php/user/image_upload\";\n            String urlServer = Liveurl+\"mobile/image_upload\";\n            String lineEnd = \"\\r\\n\";\n            String twoHyphens = \"--\";\n            String boundary = \"*****\";\n\n            int bytesRead, bytesAvailable, bufferSize;\n            byte[] buffer;\n            int maxBufferSize = 1 * 1024 * 1024;\n\n            FileInputStream fileInputStream = new FileInputStream(new File(\n                    pathToOurFile));\n\n            URL url = new URL(urlServer);\n            connection = (HttpURLConnection) url.openConnection();\n\n            // Allow Inputs &amp; Outputs\n            connection.setDoInput(true);\n            connection.setDoOutput(true);\n            connection.setUseCaches(false);\n\n            // Enable POST method\n            connection.setRequestMethod(\"POST\");\n\n            connection.setRequestProperty(\"Connection\", \"Keep-Alive\");\n            connection.setRequestProperty(\"Content-Type\",\n                    \"multipart/form-data;boundary=\" + boundary);\n\n            outputStream = new DataOutputStream(connection.getOutputStream());\n            outputStream.writeBytes(twoHyphens + boundary + lineEnd);\n            outputStream\n                    .writeBytes(\"Content-Disposition: form-data; name=\\\"uploadedfile\\\";filename=\\\"\"\n                            + pathToOurFile + \"\\\"\" + lineEnd);\n            outputStream.writeBytes(lineEnd);\n\n            bytesAvailable = fileInputStream.available();\n            bufferSize = Math.min(bytesAvailable, maxBufferSize);\n            buffer = new byte[bufferSize];\n\n            // Read file\n            bytesRead = fileInputStream.read(buffer, 0, bufferSize);\n\n            while (bytesRead &gt; 0) {\n                outputStream.write(buffer, 0, bufferSize);\n                bytesAvailable = fileInputStream.available();\n                bufferSize = Math.min(bytesAvailable, maxBufferSize);\n                bytesRead = fileInputStream.read(buffer, 0, bufferSize);\n            }\n\n            outputStream.writeBytes(lineEnd);\n            outputStream.writeBytes(twoHyphens + boundary + twoHyphens\n                    + lineEnd);\n\n            // Responses from the server (code and message)\n            int serverResponseCode = connection.getResponseCode();\n            String serverResponseMessage = connection.getResponseMessage();\n\n            // Toast.makeText(getApplicationContext(), serverResponseMessage,\n            // Toast.LENGTH_LONG).show();\n            System.out.println(\"image\" + serverResponseMessage);\n\n            fileInputStream.close();\n            outputStream.flush();\n            outputStream.close();\n\n            DataInputStream inputStream1 = null;\n            inputStream1 = new DataInputStream(connection.getInputStream());\n            String str = \"\";\n            String Str1_imageurl = \"\";\n\n            while ((str = inputStream1.readLine()) != null) {\n                Log.e(\"Debug\", \"Server Response \" + str);\n\n                Str1_imageurl = str;\n                Log.e(\"Debug\", \"Server Response String imageurl\" + str);\n            }\n            inputStream1.close();\n            System.out.println(\"image url inputstream1 \" + Str1_imageurl);\n            // Toast.makeText(getApplicationContext(), Str1_imageurl,\n            // Toast.LENGTH_LONG).show();\n\n            msgToSend = Str1_imageurl.trim();\n\n            System.out.println(\"message to send \"+msgToSend);\n\n        } catch (Exception e) {\n\n            e.printStackTrace();\n\n        }\n\n        res();\n\n    }\n\n    public void clearApplicationData() {\n        File cache = getCacheDir();\n        File appDir = new File(cache.getParent());\n\n        System.out.println(\"application dir\"+appDir);\n        if (appDir.exists()) {\n            String[] children = appDir.list();\n            for (String s : children) {\n                if (!s.equals(\"lib\")) {\n                    deleteDir(new File(appDir, s));\n                    Log.i(\"TAG\", \"**************** File /data/data/APP_PACKAGE/\" + s + \" DELETED *******************\");\n                    Intent i=new Intent(Profile_settings.this,splash.class);\n                    //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n                   // clearApplicationData();\n                    startActivity(i);\n                }\n            }\n        }\n    }\n\n    public static boolean deleteDir(File dir) {\n        if (dir != null &amp;&amp; dir.isDirectory()) {\n            String[] children = dir.list();\n            for (int i = 0; i &lt; children.length; i++) {\n                boolean success = deleteDir(new File(dir, children[i]));\n                if (!success) {\n                    return false;\n                }\n            }\n        }\n\n        return dir.delete();\n    }\n    private void loadSavedPreferences() {    \n        //User has successfully logged in, save this information\n        // We need an Editor object to make preference changes.\n\n        SharedPreferences settings = getSharedPreferences(index.PREFS_NAME, 0);\n        SharedPreferences.Editor editor = settings.edit();\n        editor.clear();`enter code here`\n        editor.commit();\n\n        }\n</code></pre>\n\n<p>Thanks in advance.</p>", "response": "Based on the code you've provided, there are a few things you can do to potentially improve the image uploading process and avoid hanging:\n\n1. Use a separate thread for image uploading\nYou can move the `Imageuploading()` method to a separate thread to avoid blocking the UI thread. This will ensure that the app remains responsive even when uploading large images. You can use an AsyncTask or a Thread for this purpose.\n\n2. Compress the image before uploading\nLarge images can take time to upload, especially if the internet connection is slow. You can compress the image before uploading it to reduce its size and therefore reduce the upload time.\n\n3. Use a progress bar to show the upload progress\nYou can use a progress bar to show the progress of the image upload. This will inform the user that the upload process is underway and how long it is likely to take.\n\n4. Use a library for image uploading\nInstead of implementing the image uploading process yourself, you can use a library such as Retrofit or Volley to handle the image upload for you. These libraries are known for their speed and reliability and can make the image uploading process much smoother.\n\nImplementing these changes should help make the image uploading process smoother and avoid hanging.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>We currently uploaded our app to the apple store and got the following answer:</p>\n\n<blockquote>\n  <p>We recommend implementing the Safari View Controller API to display\n  web content within your app. The Safari View Controller allows the\n  display of a URL and inspection of the certificate from an embedded\n  browser in an app so that customers can verify the webpage URL and SSL\n  certificate to confirm they are entering their sign in credentials\n  into a legitimate page.</p>\n</blockquote>\n\n<p>Currently i am using this code to open the web site from our app</p>\n\n<pre><code>Linking.openURL('here-goes-the-url')\n</code></pre>\n\n<p>So i am kind of lost what this answer from apple exactly means. Should i use a WebView inside my app to show the website content? I tried that but there i could not see any url or certificate as mentioned in the apple review.</p>\n\n<p>What i found so far was something like that:\n<a href=\"https://www.npmjs.com/package/react-native-safari-view-controller\" rel=\"noreferrer\">https://www.npmjs.com/package/react-native-safari-view-controller</a></p>\n\n<p>But this repo is not maintained since 2 years.</p>\n\n<p>Does anyone can make it more clear for me what the reviewer means with that answer? \nCan i use the</p>\n\n<pre><code>WebBrowser.openBrowserAsync('url')\n</code></pre>\n\n<p>to achieve what they want?</p>\n\n<p>Best regards</p>", "response": "Based on the response from the Apple review, it seems like they are recommending that you use the Safari View Controller API to display web content within your app. This would allow customers to view a URL and inspect the SSL certificate from within your app, providing them with an added level of security. \n\nUsing a WebView inside your app may not provide the same level of security, as customers may not be able to verify the URL or SSL certificate in the same way. \n\nThe React Native Safari View Controller package you found may be a good solution to implement the Safari View Controller API within your app. However, since it hasn't been maintained for 2 years, you may need to consider alternative solutions or try to update the package yourself if necessary. \n\nThe WebBrowser.openBrowserAsync function you mentioned may not provide the same level of security as the Safari View Controller, as it would simply open the web page in the user's default browser outside of your app. \n\nOverall, it's important to consider the security implications of displaying web content within your app, and to follow the recommendations provided by the Apple review to ensure the safety of your customers' information.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I'm displaying a flowchart with values from a JSON file.</p>\n\n<p>When I create my element in a static way, like this :</p>\n\n<pre><code>elements: {\n      nodes: [\n        { data: { id: 'INIT' } },\n        { data: { id: 'BUSINESS_RULES_1' } },\n        { data: { id: 'EXPORT_STC' } },\n        { data: { id: 'EXPORT_SPEC' } },\n        { data: { id: 'COPY' } },\n        { data: { id: 'MERGE' } },\n        { data: { id: 'BUSINESS_RULES_2' } },\n        { data: { id: 'TRANSFORM_ARP' } },\n        { data: { id: 'TRANSFORM_APS' } },\n        { data: { id: 'PUBLISH_APS' } },\n        { data: { id: 'PUBLISH_ARP' } },\n        { data: { id: 'ARCHIVE' } }\n      ],\n      edges: [\n        { data: { source: 'INIT', target: 'BUSINESS_RULES_1' } },\n        { data: { source: 'BUSINESS_RULES_1', target: 'EXPORT_SPEC' } },\n        { data: { source: 'BUSINESS_RULES_1', target: 'EXPORT_STC' } },\n        { data: { source: 'EXPORT_STC', target: 'COPY' } },\n        { data: { source: 'EXPORT_SPEC', target: 'COPY' } },\n        { data: { source: 'COPY', target: 'MERGE' } },\n        { data: { source: 'MERGE', target: 'BUSINESS_RULES_2' } },\n        { data: { source: 'BUSINESS_RULES_2', target: 'TRANSFORM_APS' } },\n        { data: { source: 'BUSINESS_RULES_2', target: 'TRANSFORM_ARP' } },\n        { data: { source: 'TRANSFORM_ARP', target: 'PUBLISH_ARP' } },\n        { data: { source: 'TRANSFORM_APS', target: 'PUBLISH_APS' } },\n        { data: { source: 'PUBLISH_APS', target: 'ARCHIVE' } },\n        { data: { source: 'PUBLISH_ARP', target: 'ARCHIVE' } }\n      ]\n    }\n</code></pre>\n\n<p>It is well displayed as you can see :\n<a href=\"https://i.stack.imgur.com/WZTy3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WZTy3.png\" alt=\"Chart well displayed\"></a></p>\n\n<p>But when I create the element in a dynamic way, like this :</p>\n\n<pre><code>// Fill array with nodes and edges\nvar arrayNodesAndEdges = [];\nfor (var i = 0; i &lt; myJSONdata.length; i++) {\n    if(i &lt; myJSONdata.length - 1 &amp;&amp; (myJSONdata[i].OPERATION_NAME != myJSONdata[i+1].OPERATION_NAME)) {\n      console.log(i + \" \" +myJSONdata[i].OPERATION_NAME);\n      arrayNodesAndEdges.push({\n        group: \"nodes\",\n        data: { \n          id: myJSONdata[i].OPERATION_NAME\n        }\n      });\n    } else if(i == myJSONdata.length - 1) {\n      console.log(i + \" \" +myJSONdata[i].OPERATION_NAME);\n      arrayNodesAndEdges.push({\n        group: \"nodes\",\n        data: { \n          id: myJSONdata[i].OPERATION_NAME\n        }\n      });\n    }\n}\n\nfor (var i = 0; i &lt; myJSONdata.length; i++) {\n  var source = myJSONdata[i].OPERATION_NAME;\n  if(myJSONdata[i].NEXT_OPERATION_NAME !== \"\" &amp;&amp; myJSONdata[i].NEXT_OPERATION_NAME !== null) {\n    console.log(\"Source: \" + myJSONdata[i].OPERATION_NAME + \", \" + \"Target: \" +myJSONdata[i].NEXT_OPERATION_NAME);\n    arrayNodesAndEdges.push({\n        group: \"edges\",\n        data: {\n            id: \"e\"+i,\n            source: source,\n            target: myJSONdata[i].NEXT_OPERATION_NAME\n        }\n      });\n  }\n}\ncy.add(arrayNodesAndEdges);\n</code></pre>\n\n<p>It is bad displayed, all nodes are on top of each other, as you can see:\n<a href=\"https://i.stack.imgur.com/GbxsA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GbxsA.png\" alt=\"Chart bad displayed\"></a></p>\n\n<p>(I moved some to explain how they are positionned, but they are all on top of each other)</p>\n\n<p>Here's the console log, you can see this is the same structure in static or dynamic way :</p>\n\n<pre><code>NODES\n0 INIT\n2 BUSINESS_RULES_1\n3 EXPORT_STC\n4 EXPORT_SPEC\n5 COPY\n6 MERGE\n8 BUSINESS_RULES_2\n9 TRANSFORM_ARP\n10 TRANSFORM_APS\n11 PUBLISH_APS\n12 PUBLISH_ARP\n13 ARCHIVE\n\nEDGES\nSource: INIT, Target: BUSINESS_RULES_1\nSource: BUSINESS_RULES_1, Target: EXPORT_SPEC\nSource: BUSINESS_RULES_1, Target: EXPORT_STC\nSource: EXPORT_STC, Target: COPY\nSource: EXPORT_SPEC, Target: COPY\nSource: COPY, Target: MERGE\nSource: MERGE, Target: BUSINESS_RULES_2\nSource: BUSINESS_RULES_2, Target: TRANSFORM_APS\nSource: BUSINESS_RULES_2, Target: TRANSFORM_ARP\nSource: TRANSFORM_ARP, Target: PUBLISH_ARP\nSource: TRANSFORM_APS, Target: PUBLISH_APS\nSource: PUBLISH_APS, Target: ARCHIVE\nSource: PUBLISH_ARP, Target: ARCHIVE\n</code></pre>\n\n<p>I can't understand what I'm doing wrong ?\nThank you</p>\n\n<p>EDIT ----------\nThis is my whole code :</p>\n\n<pre><code>var myJSONdata = data;\nvar cy = window.cy = cytoscape({\n  container: document.getElementById('cy'),\n\n  boxSelectionEnabled: true,\n  autounselectify: true,\n  layout: {\n    name: 'dagre',\n    rankDir: 'LR' // 'TB' for top to bottom flow, 'LR' for left to right. default is undefined, making it plot top-bottom\n  },\n\n  style: [\n    {\n      selector: 'node',\n      style: {\n        'content': 'data(id)',\n        'width': 200,\n        'height': 50,\n        'text-opacity': 1,\n        'text-valign': 'center',\n        'text-halign': 'center',\n        'shape': 'square',\n        'label': 'data(id)',\n        'background-color': '#11479e',\n        'color': 'white'\n      }\n    },\n    {\n      selector: 'edge',\n      style: {\n        'width': 7,\n        'target-arrow-color': '#ccc',\n        'target-arrow-shape': 'triangle',\n        'curve-style': 'bezier',\n        'line-color': '#9dbaea'\n      }\n    },\n      {\n        selector: ':selected',\n        style: {\n          'background-color': 'yellow',\n          'line-color': 'yellow',\n          'target-arrow-color': 'yellow',\n          'source-arrow-color': 'yellow',\n        }\n      }\n    ]\n    /*,elements: {\n      nodes: [\n        { data: { id: 'INIT' } },\n        { data: { id: 'BUSINESS_RULES_1' } },\n        { data: { id: 'EXPORT_STC' } },\n        { data: { id: 'EXPORT_SPEC' } },\n        { data: { id: 'COPY' } },\n        { data: { id: 'MERGE' } },\n        { data: { id: 'BUSINESS_RULES_2' } },\n        { data: { id: 'TRANSFORM_ARP' } },\n        { data: { id: 'TRANSFORM_APS' } },\n        { data: { id: 'PUBLISH_APS' } },\n        { data: { id: 'PUBLISH_ARP' } },\n        { data: { id: 'ARCHIVE' } }\n      ],\n      edges: [\n        { data: { source: 'INIT', target: 'BUSINESS_RULES_1' } },\n        { data: { source: 'BUSINESS_RULES_1', target: 'EXPORT_SPEC' } },\n        { data: { source: 'BUSINESS_RULES_1', target: 'EXPORT_STC' } },\n        { data: { source: 'EXPORT_STC', target: 'COPY' } },\n        { data: { source: 'EXPORT_SPEC', target: 'COPY' } },\n        { data: { source: 'COPY', target: 'MERGE' } },\n        { data: { source: 'MERGE', target: 'BUSINESS_RULES_2' } },\n        { data: { source: 'BUSINESS_RULES_2', target: 'TRANSFORM_APS' } },\n        { data: { source: 'BUSINESS_RULES_2', target: 'TRANSFORM_ARP' } },\n        { data: { source: 'TRANSFORM_ARP', target: 'PUBLISH_ARP' } },\n        { data: { source: 'TRANSFORM_APS', target: 'PUBLISH_APS' } },\n        { data: { source: 'PUBLISH_APS', target: 'ARCHIVE' } },\n        { data: { source: 'PUBLISH_ARP', target: 'ARCHIVE' } }\n      ]\n    }*/\n});\n\n\n\n// Fill array with nodes and edges\nvar arrayNodesAndEdges = [];\nfor (var i = 0; i &lt; myJSONdata.length; i++) {\n    if(i &lt; myJSONdata.length - 1 &amp;&amp; (myJSONdata[i].OPERATION_NAME != myJSONdata[i+1].OPERATION_NAME)) {\n      console.log(i + \" \" +myJSONdata[i].OPERATION_NAME);\n      arrayNodesAndEdges.push({\n        group: \"nodes\",\n        data: { \n          id: myJSONdata[i].OPERATION_NAME\n        }\n      });\n    } else if(i == myJSONdata.length - 1) {\n      console.log(i + \" \" +myJSONdata[i].OPERATION_NAME);\n      arrayNodesAndEdges.push({\n        group: \"nodes\",\n        data: { \n          id: myJSONdata[i].OPERATION_NAME\n        }\n      });\n    }\n}\n\nfor (var i = 0; i &lt; myJSONdata.length; i++) {\n  var source = myJSONdata[i].OPERATION_NAME;\n  if(myJSONdata[i].NEXT_OPERATION_NAME !== \"\" &amp;&amp; myJSONdata[i].NEXT_OPERATION_NAME !== null) {\n    console.log(\"Source: \" + myJSONdata[i].OPERATION_NAME + \", \" + \"Target: \" +myJSONdata[i].NEXT_OPERATION_NAME);\n    arrayNodesAndEdges.push({\n        group: \"edges\",\n        data: {\n            id: \"e\"+i,\n            source: source,\n            target: myJSONdata[i].NEXT_OPERATION_NAME\n        }\n      });\n  }\n}\ncy.add(arrayNodesAndEdges);\n</code></pre>", "response": "The problem here is that the dagre layout of Cytoscape needs to have some constraints in order to position the nodes correctly. Since you are dynamically adding nodes and edges, these constraints are not being defined and the layout is failing.\n\nTo fix this, you can use the `layout` method of Cytoscape to trigger the layout once all the elements have been added. This will recalculate the constraints and position the nodes correctly.\n\nHere's how you can modify your code to include the layout call:\n\n```\nvar myJSONdata = data;\nvar cy = window.cy = cytoscape({\n  container: document.getElementById('cy'),\n\n  boxSelectionEnabled: true,\n  autounselectify: true,\n  layout: {\n    name: 'dagre',\n    rankDir: 'LR' // 'TB' for top to bottom flow, 'LR' for left to right. default is undefined, making it plot top-bottom\n  },\n\n  style: [\n    {\n      selector: 'node',\n      style: {\n        'content': 'data(id)',\n        'width': 200,\n        'height': 50,\n        'text-opacity': 1,\n        'text-valign': 'center',\n        'text-halign': 'center',\n        'shape': 'square',\n        'label': 'data(id)',\n        'background-color': '#11479e',\n        'color': 'white'\n      }\n    },\n    {\n      selector: 'edge',\n      style: {\n        'width': 7,\n        'target-arrow-color': '#ccc',\n        'target-arrow-shape': 'triangle',\n        'curve-style': 'bezier',\n        'line-color': '#9dbaea'\n      }\n    },\n      {\n        selector: ':selected',\n        style: {\n          'background-color': 'yellow',\n          'line-color': 'yellow',\n          'target-arrow-color': 'yellow',\n          'source-arrow-color': 'yellow',\n        }\n      }\n    ]\n});\n\n// Fill array with nodes and edges\nvar arrayNodesAndEdges = [];\nfor (var i = 0; i &lt; myJSONdata.length; i++) {\n    if(i &lt; myJSONdata.length - 1 &amp;&amp; (myJSONdata[i].OPERATION_NAME != myJSONdata[i+1].OPERATION_NAME)) {\n      console.log(i + \" \" +myJSONdata[i].OPERATION_NAME);\n      arrayNodesAndEdges.push({\n        group: \"nodes\",\n        data: { \n          id: myJSONdata[i].OPERATION_NAME\n        }\n      });\n    } else if(i == myJSONdata.length - 1) {\n      console.log(i + \" \" +myJSONdata[i].OPERATION_NAME);\n      arrayNodesAndEdges.push({\n        group: \"nodes\",\n        data: { \n          id: myJSONdata[i].OPERATION_NAME\n        }\n      });\n    }\n}\n\nfor (var i = 0; i &lt; myJSONdata.length; i++) {\n  var source = myJSONdata[i].OPERATION_NAME;\n  if(myJSONdata[i].NEXT_OPERATION_NAME !== \"\" &amp;&amp; myJSONdata[i].NEXT_OPERATION_NAME !== null) {\n    console.log(\"Source: \" + myJSONdata[i].OPERATION_NAME + \", \" + \"Target: \" +myJSONdata[i].NEXT_OPERATION_NAME);\n    arrayNodesAndEdges.push({\n        group: \"edges\",\n        data: {\n            id: \"e\"+i,\n            source: source,\n            target: myJSONdata[i].NEXT_OPERATION_NAME\n        }\n      });\n  }\n}\n\ncy.add(arrayNodesAndEdges);\n\ncy.layout({name: 'dagre'});\n```\n\nNow the nodes and edges should be positioned correctly.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I am a novice in R language. I am having text file separated by tab available with sales data for each day. The format will be like product-id, day0, day1, day2, day3 and so on. The part of the input file given below </p>\n\n<pre><code>productid   0   1   2   3   4   5   6\n1           53  40  37  45  69  105 62\n4           0   0   2   4   0   8   0\n5           57  133 60  126 90  87  107\n6           108 130 143 92  88  101 66\n10          0   0   2   0   4   0   36\n11          17  22  16  15  45  32  36\n</code></pre>\n\n<p>I used code below to read a file</p>\n\n<pre><code>pdInfo &lt;- read.csv(\"products.txt\",header = TRUE, sep=\"\\t\")\n</code></pre>\n\n<p>This allows to read the entire file and variable x is a data frame. I would like to change data.frame x to time series object in order for the further processing.On a stationary test, Dickey–Fuller test (ADF) it shows an error. I tried the below code</p>\n\n<pre><code>x &lt;- ts(data.matrix(pdInfo),frequency = 1)\nadf &lt;- adf.test(x)\n\n  error: Error in adf.test(x) : x is not a vector or univariate time series\n</code></pre>\n\n<p>Thanks in advance for the suggestions </p>", "response": "Since your data has multiple time series (one for each product), you need to first subset the data by each product and then convert each subset to a time series object. Here's an example code:\n\n```\nlibrary(tidyverse)\nlibrary(lubridate)\n\n# read the data\npdInfo <- read.table(\"products.txt\", header = TRUE)\n\n# convert to long format and add date variable\npdInfo_long <- pdInfo %>%\n  pivot_longer(cols = -productid, names_to = \"day\", values_to = \"sales\") %>%\n  mutate(date = ymd(paste0(\"2021-01-\", day)))\n\n# split the data by product\npdInfo_split <- pdInfo_long %>%\n  split(.$productid)\n\n# convert each subset to a time series object\npdInfo_ts <- lapply(pdInfo_split, function(df) {\n  ts(df$sales, frequency = 7) # assuming data is daily and repeats every 7 days\n})\n\n# check if time series objects are created correctly\npdInfo_ts[[1]] # time series for product 1\npdInfo_ts[[2]] # time series for product 2\n# and so on...\n\n# run ADF test on one of the time series\nlibrary(tseries)\nadf.test(pdInfo_ts[[1]]) # replace 1 with any other product id\n```", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I want to unit test a module I've built.\nTo give an impression of what it looks like pretty much..\nMyModule:</p>\n\n<pre><code>function MyModule(...) {\n    var self = this;\n    MyModule.init.call(self, ...);\n}\n\nutil.inherits(MyModule, MySuperModule);\n\nMyModule.init = function(...) {\n...\n};\n\nMyModule.prototype.logic = function(..., done) {\n   calls fnA, fnB, fnC, fnD conditionally\n   done(...)\n};\n\nMyModule.prototype.fnA = function(...) {\n...\n};\n\nMyModule.prototype.fnB = function(...) {\n...\n};\n\nMyModule.prototype.fnC = function(...) {\n...\n};\n\nMyModule.prototype.fnD = function(...) {\n...\n};\n</code></pre>\n\n<p>MySuperModule:</p>\n\n<pre><code>function MySuperModule(...) {\n    ...\n    }\n\n    MySuperModule.prototype,fn = function(..., done) {\n        var self = this;\n        ...\n        self.logic(..., function done(...) {\n            ...\n            done(...)\n        });\n    }\n</code></pre>\n\n<p>Now MyModule.logic() is never called explicitly by a user, it is only invoked MySuperModule.fn().\nSame goes for all other MyModule functions which are called conditionally based on the given parameters being passed through the delegating chain.</p>\n\n<p>My questions are as follow:</p>\n\n<ul>\n<li>Do I need to test all MyModule functions separately or just test MySuperModule.fn() with different parameters covering all possible scenarios</li>\n<li>I know I need to test function in isolation (which if I do my previous question is wrong to ask because than I won't really have tested MyModule functions at all), how would I do that with the MySuperModule.fn(), because its done() callback is being called with arguments dependent on what the MyModule.logic() done() callback was called with, which is again, dependent on the arguments supplied to MySuperModule.fn() arguments.</li>\n</ul>", "response": "As an AI language model, I cannot provide coding advice but I can offer some general guidance on unit testing.\n\n1. Ideally, you should aim to test each function in MyModule separately to assure their individual correctness. However, given that MyModule functions are dependent on each other, you may consider testing them together in various combinations to cover all possible scenarios.\n\n2. In order to test the functionality of MySuperModule.fn() in isolation, you may need to use a mocking framework which can simulate the behavior of MyModule.logic() and its callback functions. You can use the mocking framework to create a fake implementation of MyModule.logic() with a predetermined output for the done() callback. That way, you can test MySuperModule.fn() with different parameters and compare its output against the expected result from the mock. This allows you to test the behavior of MySuperModule.fn() separately from that of MyModule.logic().", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I'm writing feature tests with: <code>ruby 2.1.4</code>, <code>rails 4.1.12</code>, <code>rspec (2.14.1)</code>, <code>capybara (2.4.1)</code> and <code>poltergeist (1.5.1)</code>.</p>\n\n<p>Currently I have a feature like this:</p>\n\n<pre><code>require 'spec_helper'\n\nfeature 'user is able to import videos from YouTube Channel', js: true do\n\n  before do\n    @user = FactoryGirl.create :user\n  end\n\n  scenario 'from a simple correct YouTube video link' do\n    VCR.use_cassette('video_sources/youtube_add_single_video') do\n\n      visit root_path\n\n      fill_in 'user_email',    with: @user.email\n      fill_in 'user_password', with: @user.password\n      click_button 'Log in'\n\n      visit youtube_import_path\n\n      expect(page).to have_css(\"input#query\")\n      expect(page).to have_css(\"a#continue-button\")\n\n      fill_in \"query\", with: \"https://www.youtube.com/watch?v=xZY43QSx3Fk\"\n\n      page.find('#continue-button').trigger('click')\n\n      # clicking on '#continue-button' call youtube API\n      # receive a video data and store it into DB\n\n      expect(page).to have_content(\"Congrats! Your import is complete\")\n    end\n  end\n\nend\n</code></pre>\n\n<p>Locally  everything works fine, all tests are green.\nBut on CodeShip - this scenario always fails.\nAnd I can not find a reason why...</p>\n\n<p>CodeShip log says that:</p>\n\n<pre><code>Capybara::Poltergeist::StatusFailError:\nRequest to 'http://127.0.0.1:3000/' failed to reach server, check DNS and/or server status\n</code></pre>\n\n<p>But why? Locally all tests are green.</p>\n\n<p>P.S. I tried to add <code>sleep 5</code> before line <code>visit root_path</code> and it did not help.</p>\n\n<p>P.S.S. Maybe this part of <code>spec_helper.rb</code> will be helpful:</p>\n\n<pre><code>  config.before(:suite) do\n    DatabaseCleaner.clean_with(:truncation)\n    Capybara.reset_sessions!\n  end\n\n  config.before(:each) do\n    DatabaseCleaner[:mongoid].start\n  end\n\n  config.after(:each) do\n    DatabaseCleaner[:mongoid].clean\n  end\n\n  config.after(:suite) do\n    Rails.cache.clear\n  end\n</code></pre>", "response": "The error message suggests that the request to `http://127.0.0.1:3000/` failed to reach the server. This indicates that the Capybara session might not be properly set up.\n\nOne possible reason for this could be related to the Capybara driver configuration. Poltergeist uses PhantomJS to execute the tests, which means that the PhantomJS binary needs to be installed and configured correctly.\n\nTo debug the issue, you could try running the test locally using Poltergeist as the driver and see if it reproduces the same error. If it does, then it might help to check the PhantomJS installation and configuration. You could also try using a different Capybara driver (such as Selenium) to see if the problem persists.\n\nAnother possible cause of the issue could be related to the Rails environment configuration. Check if the Rails environment is correctly configured in the CodeShip environment and that it matches the local setup. You could also try running the tests with the same Ruby and Rails versions as the CodeShip environment to rule out any possible version incompatibilities.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I got a weird mission from a friend, to parse through a bunch of Word files and write certain parts of them to a text file for further processing.</p>\n\n<p>VBscript is not my cup of tea so I'm not sure how to fit the pieces together.</p>\n\n<p>The documents look like this:</p>\n\n<pre><code>Header\nA lot of not interesting text\nTable\nHeader\nMore boring text\nTable\n</code></pre>\n\n<p>I want to parse the documents and get all the headers and table of contents out of it. I'm stepping step through the document with</p>\n\n<pre><code>For Each wPara In wd.ActiveDocument.Paragraphs\n</code></pre>\n\n<p>And I think I know how to get the headers</p>\n\n<pre><code>If Left(wPara.Range.Style, Len(\"Heading\")) = \"Heading\" Then\n</code></pre>\n\n<p>But I'm unsure of how to do the </p>\n\n<pre><code>Else if .. this paragraph belongs to a table..\n</code></pre>\n\n<p>So, any hint on how I could determine if a paragraph is part of a table or not would be nice. </p>", "response": "One way to determine if a paragraph is part of a table is to check if its parent object is a table. You can do this with the following code:\n\n<pre><code>If wPara.Range.Tables.Count > 0 Then\n    ' This paragraph is part of a table\nElse\n    ' This paragraph is not part of a table\nEnd If\n</code></pre>\n\nThis code checks if the current paragraph has any parent tables. If it does, then it is considered to be part of a table. Otherwise, it is not part of a table.  You can then extract the necessary content based on whether the paragraph is a header or part of a table.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>In some of my documents I have $ or £ symbols. I want to search for £ and retrieve documents containing that symbol. I've gone through <a href=\"https://www.elastic.co/guide/en/elasticsearch/guide/current/custom-analyzers.html\" rel=\"nofollow\">the documentation</a> but I'm getting some cognitive dissonance.</p>\n\n<pre><code># Delete the `my_index` index\nDELETE /my_index    \n\n# Create a custom analyzer\nPUT /my_index\n{\n  \"settings\": {\n    \"analysis\": {\n      \"char_filter\": {\n        \"&amp;_to_and\": {\n          \"type\": \"mapping\",\n          \"mappings\": [\n            \"&amp;=&gt; and \",\n            \"$=&gt; dollar \"\n          ]\n        }\n      },\n      \"analyzer\": {\n        \"my_analyzer\": {\n          \"type\": \"custom\",\n          \"char_filter\": [\n            \"html_strip\",\n            \"&amp;_to_and\"\n          ],\n          \"tokenizer\": \"standard\",\n          \"filter\": [\n            \"lowercase\"\n          ]\n        }\n      }\n    }\n  }\n}    \n</code></pre>\n\n<p>This returns \"the\", \"quick\", \"and\", \"brown\", \"fox\" just as the documentation states:</p>\n\n<pre><code># Test out the new analyzer\nGET /my_index/_analyze?analyzer=my_analyzer&amp;text=The%20quick%20%26%20brown%20fox    \n</code></pre>\n\n<p>This returns \"the\", \"quick\", \"dollar\", \"brown\", \"fox\"</p>\n\n<pre><code>GET /my_index/_analyze?analyzer=my_analyzer&amp;text=The%20quick%20%24%20brown%20fox    \n</code></pre>\n\n<p>Adding some records:  </p>\n\n<pre><code>PUT /my_index/test/1\n{\n  \"title\": \"The quick &amp; fast fox\"\n}    \n\nPUT /my_index/test/1\n{\n  \"title\": \"The daft fox owes me $100\"\n}    \n</code></pre>\n\n<p>I would have thought if I search for \"dollar\", I would get a result? Instead I get no results:</p>\n\n<pre><code>GET /my_index/test/_search\n{ \"query\": {\n    \"simple_query_string\": {\n      \"query\": \"dollar\"\n    }\n  }\n}\n</code></pre>\n\n<p>Or even using '$' with an analyzer:</p>\n\n<pre><code>GET /my_index/test/_search\n{ \"query\": {\n  \"query_string\": {\n    \"query\": \"dollar10\",\n    \"analyzer\": \"my_analyzer\"\n  }\n }\n}\n</code></pre>", "response": "It looks like the issue might be with the mapping in the char_filter. Currently, the mapping is set up to replace \"$\" with \"dollar\", but it doesn't actually replace the symbol itself. So when you search for \"dollar\", Elasticsearch is looking for that exact word and not the symbol.\n\nTo fix this, you can modify the mapping to replace the symbol as well:\n\n<pre><code>\"mappings\": [\n  \"&amp;=&gt; and \",\n  \"\\\\$=&gt; dollar \",\n  \"£=&gt; pound \"\n]</code></pre>\n\nWith this change, Elasticsearch should be able to properly index and search for documents containing the pound symbol.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I want to find a VBox node in a scene loaded with <code>FXMLoader</code> thanks to <code>Node#lookup()</code> but I get the following exception :</p>\n\n<p><code>java.lang.ClassCastException: com.sun.javafx.scene.control.skin.SplitPaneSkin$Content cannot be cast to javafx.scene.layout.VBox</code></p>\n\n<p><strong>The code :</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Main extends Application {  \n    public static void main(String[] args) {\n        Application.launch(Main.class, (java.lang.String[]) null);\n    }\n    @Override\n    public void start(Stage stage) throws Exception {\n        AnchorPane page = (AnchorPane) FXMLLoader.load(Main.class.getResource(\"test.fxml\"));\n        Scene scene = new Scene(page);\n        stage.setScene(scene);\n        stage.show();\n\n        VBox myvbox = (VBox) page.lookup(\"#myvbox\");\n        myvbox.getChildren().add(new Button(\"Hello world !!!\"));\n    }\n}\n</code></pre>\n\n<p><strong>The fxml file:</strong>  </p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;AnchorPane id=\"AnchorPane\" maxHeight=\"-Infinity\" maxWidth=\"-Infinity\" minHeight=\"-Infinity\" minWidth=\"-Infinity\" prefHeight=\"400.0\" prefWidth=\"600.0\" xmlns:fx=\"http://javafx.com/fxml\" &gt;\n  &lt;children&gt;\n    &lt;SplitPane dividerPositions=\"0.5\" focusTraversable=\"true\" prefHeight=\"400.0\" prefWidth=\"600.0\" AnchorPane.bottomAnchor=\"0.0\" AnchorPane.leftAnchor=\"0.0\" AnchorPane.rightAnchor=\"0.0\" AnchorPane.topAnchor=\"0.0\"&gt;\n      &lt;items&gt;\n        &lt;AnchorPane minHeight=\"0.0\" minWidth=\"0.0\" prefHeight=\"160.0\" prefWidth=\"100.0\" /&gt;\n        &lt;VBox fx:id=\"myvbox\" prefHeight=\"398.0\" prefWidth=\"421.0\" /&gt;\n      &lt;/items&gt;\n    &lt;/SplitPane&gt;\n  &lt;/children&gt;\n&lt;/AnchorPane&gt;\n</code></pre>\n\n<p>I would like to know :<br>\n1. Why lookup method return a <code>SplitPaneSkin$Content</code> and not a <code>VBox</code> ?<br>\n2. How I can get the <code>VBox</code> in another manner ?</p>\n\n<p>Thanks in advance</p>", "response": "As per the JavaFX documentation, the `lookup()` method of the `Node` class returns the first node in the scene graph that matches the specified CSS selector. In your code, the selector `#myvbox` matches the `VBox` node, but it is not the root node of the `AnchorPane`.\n\nThe `SplitPane` node in the FXML file contains two `AnchorPane` nodes as its items, and the `VBox` is the second item. When you call `lookup(\"#myvbox\")` on the `AnchorPane`, it returns the content of the second item, which is a `SplitPaneSkin$Content` node (a private implementation class). You cannot cast this node to a `VBox`, hence the `ClassCastException`.\n\nTo get a reference to the `VBox`, you can use the `lookup()` method on the `SplitPane` node instead of the `AnchorPane` node, like this:\n\n```java\nSplitPane splitPane = (SplitPane) page.lookup(\"#AnchorPane\");\nVBox myvbox = (VBox) splitPane.getItems().get(1);\nmyvbox.getChildren().add(new Button(\"Hello world !!!\"));\n```\n\nHere, you first get a reference to the `SplitPane` node using its `id` attribute, and then access its items using the `getItems()` method. Since the `VBox` is the second item (index 1), you can get a reference to it using the `get()` method of the `ObservableList` returned by the `getItems()` method. Now you can add the `Button` to the `VBox`.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>DEMO can be found at:</p>\n\n<p><a href=\"http://www.bootply.com/VZ7gvA7ndE#\" rel=\"noreferrer\">http://www.bootply.com/VZ7gvA7ndE#</a></p>\n\n<p>I set the height of <code>div</code> to 100px and want to show the <code>label</code> at the bottom of the <code>div</code>.  I use </p>\n\n<pre><code>#contain-word-lab {\n  vertical-align: bottom;\n  margin-bottom: 5px;\n}\n</code></pre>\n\n<p>However, this doesn't work at all. The <code>label</code> still align to the top of the <code>div</code>. </p>\n\n<p>Does anyone have any ideas about this? Why <code>vertical-align</code> doesn't work here? Thanks!</p>", "response": "The <code>vertical-align</code> property only works for inline elements or table cell elements. In this case, the <code>div</code> is a block-level element, so it won't work. \n\nOne possible solution is to use absolute positioning on the <code>label</code> element. Set the position of the <code>div</code> to <code>relative</code>, and then set the position of the <code>label</code> to <code>absolute</code> and bottom to 0. \n\nHere's an example of how the CSS would look like:\n\n<pre><code>#contain-word {\n  height: 100px;\n  position: relative;\n}\n\n#contain-word-lab {\n  position: absolute;\n  bottom: 0;\n  margin-bottom: 5px;\n}\n</code></pre>\n\nThis should position the <code>label</code> at the bottom of the <code>div</code>.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I´m migrating from logback to log4j2 and I´m missing a lot of functionality that exist on logback, but I cannot find a similarity on log4j2</p>\n\n<p>Any idea if there´s a similar feature as <strong>encoder</strong> with  <strong></strong> on log4j2?, I cannot find any documentation. </p>", "response": "Yes, Log4j2 also has the concept of Encoders. An Encoder in Log4j2 is responsible for formatting a Log Event into a binary or text representation suitable for output. \n\nThe configuration of Encoders in Log4j2 is similar to Logback. You can set Encoder for various components such as appenders, filter, etc.\n\nYou can define a custom Encoder by implementing the Encoder interface of Log4j2.\n\nHere's an example configuration of an Encoder in Log4j2:\n\n```\n<Appenders>\n  <Console name=\"Console\" target=\"SYSTEM_OUT\">\n    <PatternLayout>\n      <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5p %c{1}:%L - %m%n</Pattern>\n    </PatternLayout>\n    <JsonLayout complete=\"false\" compact=\"true\" eventEol=\"true\">\n        <KeyValuePair key=\"application\" value=\"myapp\"/>\n    </JsonLayout>\n  </Console>\n</Appenders>\n```\n\nIn the above example, we have defined two encoders, i.e., `PatternLayout` and `JsonLayout`. `PatternLayout` is a text-based encoder that formats the Log Event according to the provided pattern. `JsonLayout` is a JSON-based encoder that formats the Log Event in JSON format.\n\nYou can also define your custom Encoder in Log4j2. Here's an example of a custom Encoder:\n\n```\npublic class MyEncoder implements Encoder<LogEvent> {\n    @Override\n    public ByteBuffer toByteBuffer(LogEvent event) {\n        // Implementation of Binary Encoder\n    }\n    @Override\n    public String toSerializable(LogEvent event) {\n        // Implementation of Text Encoder\n    }\n    @Override\n    public void encode(LogEvent event, ByteBufferDestination destination) {\n        // Implementation of Binary Encoder for Direct writes to Destination\n    }\n    @Override\n    public byte[] headerBytes() {\n        // Implementation of Binary Encoder Header\n    }\n    @Override\n    public byte[] footerBytes() {\n        // Implementation of Binary Encoder Footer\n    }\n}\n```\n\nYou can refer to the Log4j2 documentation for more information on Encoders.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>Run into a strange issue with using <code>resize orientationchange</code> to resize my slack carousel on iPhone and iPad chrome only. </p>\n\n<p>My aim is to have slick run whilst on mobile portrait, but depending on the screen width, on landscape it should go back to how it would look on desktop, which removes the slick carousel. I have attached some images below of what it looks like on an android device which is working fine, and also what it looks like on iPhone which doesn't seem to work.</p>\n\n<p><a href=\"https://i.stack.imgur.com/uZBWq.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uZBWq.jpg\" alt=\"enter image description here\"></a>\n<a href=\"https://i.stack.imgur.com/PFISM.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PFISM.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>My slick js:</p>\n\n<pre><code>$(document).ready(function() {\n    $(\".carousel\").slick( {\n        slide:\".slide\",\n        slidesToShow:2,\n        slidesToScroll:1,\n        autoplay:1,\n        infinite: true,\n        autoplaySpeed:2000,\n        mobileFirst: true,\n        responsive:[{\n            breakpoint:500,\n            settings: { slidesToShow: 3 }\n        },{\n            breakpoint: 650,\n            settings: 'unslick'\n        }]\n    });\n});\n</code></pre>\n\n<p>and for the resizer:</p>\n\n<pre><code>$(window).on(\"resize orientationchange\", function() {\n    $(\".carousel\").slick(\"resize\");\n});\n</code></pre>\n\n<p>This code works fine on all other devices and browsers and works fine on iPhone / iPad Safari. Any research I have done on this would lead me to suggest that <code>resize orientationchange</code> should have fixed this.</p>", "response": "As an AI language model, I cannot see any obvious error in the code provided. However, here are some suggestions that might help in resolving the issue:\n\n1. Try a different resizer\nInstead of using the \"resize orientationchange\" event, try using the \"debouncedresize\" event provided by the jQuery.debouncedresize plugin. This event is specifically designed for handling responsive design issues and might work better in your case.\n\n2. Test on different iOS devices\nIt might be the case that the issue is specific to certain iOS devices or versions. Try testing on multiple iOS devices and versions to see if the issue is consistent.\n\n3. Check console for errors\nCheck the console for any errors that might be causing the issue. Sometimes, other scripts or plugins can interfere with the functionality of slick.js, so check for any conflicts.\n\n4. Use debug mode\nTurn on debug mode in slick.js to see if there are any issues being reported. You can do this by setting the \"debug\" option to true when initializing the carousel, like this:\n\n<pre><code>$(document).ready(function() {\n    $(\".carousel\").slick( {\n        slide:\".slide\",\n        slidesToShow:2,\n        slidesToScroll:1,\n        autoplay:1,\n        infinite: true,\n        autoplaySpeed:2000,\n        mobileFirst: true,\n        debug: true, /* turn on debug mode */\n        responsive:[{\n            breakpoint:500,\n            settings: { slidesToShow: 3 }\n        },{\n            breakpoint: 650,\n            settings: 'unslick'\n        }]\n    });\n});\n</code></pre>\n\nThis will output any errors or warnings to the console, which might help in identifying the issue.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I've been recently hired by a GIS company to rewrite their old geomatics libraries. So I'm currently looking for a good computational geometry library. I've seen CGAL, which is amazing, but my boss wants something free. </p>\n\n<p>So I'm now checking Boost.Geometry. This library seems great, but it also seems that it is changing pretty fast. A lot of things are not implemented yet, and a lot of issues are discussed on the mailing list.</p>\n\n<p>Hence my question : is Boost.Geometry mature enough so I can build something on it ? Or is the design still going to evolve ?</p>\n\n<p>Thanks</p>", "response": "As an AI language model, I am unable to provide an opinion as to the maturity of Boost.Geometry since I do not have the necessary information of the current state of the library. However, as an open source library, Boost.Geometry has an active community of developers who continuously work to improve and maintain it. It is also regularly updated with new features and bug fixes. Therefore, it would be best to consult with other developers or experts in the field to determine if Boost.Geometry is suitable for your project needs.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I have this JSON data:</p>\n\n<pre><code>var tmpStr = '[    \n{\n    \"Name\": \"TEST\",\n    \"deviceId\": \"\",\n    \"CartId\": \"\",\n    \"timestamp\": 1383197265540,\n    \"FOOD\": [],\n    \"City\": \"LONDON CA\"\n }\n\n]';\n</code></pre>\n\n<p>How can I delete the brackets?</p>\n\n<p>Here is more of my JSON file:</p>\n\n<pre><code>[{\"arrivee\":false,\"des\":\"Ceintures De Sécurité Conducteur\",\"code\":\"nn\",\"depart\":true},\n {\"arrivee\":true,\"des\"‌​‌​:\"Lecteur Tachygraphe\",\"code\":\"nn\",\"depart\":false}\n {\"arrivee\":false,\"d‌​‌​es\":\"Ceintures De Sécurités Passagères\",\"code\":\"nn\",\"depart\":true},\n {\"arrivee\":true,\"des\"‌​‌​:\"Climatisation\",\"‌​co‌​de\":\"nn\",\"depart‌​\":fa‌​lse}]\n</code></pre>", "response": "The brackets in your JSON data are necessary in order to represent an array. You cannot delete them without changing the structure of the data. If you want to access the objects within the array, you can parse the JSON data using the `JSON.parse()` function, which will convert the string into an array of objects that you can manipulate in your code. Here is an example:\n\n<pre><code>var data = JSON.parse(tmpStr);\n\n// access the \"Name\" property of the first object in the array\nconsole.log(data[0].Name); // Output: \"TEST\"\n</code></pre>\n\nAs for your second example, it seems like you are missing a comma between the second and third objects in the array. After adding the comma, you can parse the JSON data in the same way as before.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I have a following problem.\nI would like to exclude some .java files (**/jsfunit/*.java) during the test-compile phase and on the other side I would like to include them during the compile phase (id i start tomcat with tomcat:run goal)</p>\n\n<p>My pom.xml</p>\n\n<pre><code>&lt;plugin&gt;\n            &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n            &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;\n            &lt;configuration&gt;\n                &lt;source&gt;1.6&lt;/source&gt;\n                &lt;target&gt;1.6&lt;/target&gt;\n                 &lt;!-- &lt;excludes&gt;\n                     &lt;exclude&gt;**/*JSFIntegration*.java&lt;/exclude&gt;\n                 &lt;/excludes&gt; --&gt;                    \n            &lt;/configuration&gt;\n           &lt;executions&gt;\n           &lt;!-- &lt;execution&gt;\n                        &lt;id&gt;default-compile&lt;/id&gt;\n                        &lt;phase&gt;compile&lt;/phase&gt;\n                        &lt;goals&gt;\n                          &lt;goal&gt;compile&lt;/goal&gt;\n                        &lt;/goals&gt;\n                        &lt;configuration&gt;\n                            &lt;includes&gt;\n                                 &lt;include&gt;**/jsfunit/*.java&lt;/include&gt;\n                            &lt;/includes&gt;\n                        &lt;/configuration&gt;\n               &lt;/execution&gt;--&gt;\n              &lt;execution&gt;\n                        &lt;id&gt;default-testCompile&lt;/id&gt;\n                        &lt;phase&gt;test-compile&lt;/phase&gt;\n                        &lt;configuration&gt;\n                            &lt;excludes&gt;\n                                &lt;exclude&gt;**/jsfunit/*.java&lt;/exclude&gt;\n                            &lt;/excludes&gt;\n                        &lt;/configuration&gt; \n                        &lt;goals&gt;\n\n                &lt;goal&gt;testCompile&lt;/goal&gt;\n                        &lt;/goals&gt;\n                &lt;/execution&gt;                  \n             &lt;/executions&gt;\n\n        &lt;/plugin&gt;\n</code></pre>\n\n<p>But it does not work : exclude in default-testCompile execution does not filter these classes.\nIf I remove the comments then all classes matched **/jsfunit/*.java would be compiled but only if I touch them!</p>", "response": "To exclude certain .java files during the test-compile phase and include them during the compile phase using the maven-compiler-plugin, you can try the following changes in your pom.xml:\n\n<pre><code>&lt;plugin&gt;\n    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n    &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;\n    &lt;executions&gt;\n        &lt;!-- Exclude jsfunit/*.java during test-compile phase --&gt;\n        &lt;execution&gt;\n            &lt;id&gt;exclude-jsfunit&lt;/id&gt;\n            &lt;phase&gt;test-compile&lt;/phase&gt;\n            &lt;goals&gt;\n                &lt;goal&gt;testCompile&lt;/goal&gt;\n            &lt;/goals&gt;\n            &lt;configuration&gt;\n                &lt;excludes&gt;\n                    &lt;exclude&gt;**/jsfunit/*.java&lt;/exclude&gt;\n                &lt;/excludes&gt;\n            &lt;/configuration&gt;\n        &lt;/execution&gt;\n        &lt;!-- Include jsfunit/*.java during compile phase --&gt;\n        &lt;execution&gt;\n            &lt;id&gt;include-jsfunit&lt;/id&gt;\n            &lt;phase&gt;compile&lt;/phase&gt;\n            &lt;goals&gt;\n                &lt;goal&gt;compile&lt;/goal&gt;\n            &lt;/goals&gt;\n            &lt;configuration&gt;\n                &lt;includes&gt;\n                    &lt;include&gt;**/jsfunit/*.java&lt;/include&gt;\n                &lt;/includes&gt;\n            &lt;/configuration&gt;\n        &lt;/execution&gt;\n    &lt;/executions&gt;\n    &lt;configuration&gt;\n        &lt;source&gt;1.6&lt;/source&gt;\n        &lt;target&gt;1.6&lt;/target&gt;\n    &lt;/configuration&gt;\n&lt;/plugin&gt;</code></pre>\n\nIn the above code, we have defined two executions for the maven-compiler-plugin. The first execution excludes .java files in the **/jsfunit/ directory during the test-compile phase, while the second execution includes them during the compile phase.\n\nThe configuration for the maven-compiler-plugin is moved outside the executions, and it defines the source and target versions of Java used during compilation.\n\nNote that if the .java files are not changed, they may not be recompiled during the tomcat:run goal, even if they are included in the <code>&lt;includes&gt;</code> section. In that case, you may need to run <code>mvn clean</code> to force a full recompilation.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>Why does the following print <code>bD aD aB aA aC aU</code> instead of <code>aD aB aA aC bD aU</code>? In other words, why is <code>b--</code> evaluated before <code>--++a--++</code>?</p>\n\n<pre><code>#include &lt;iostream&gt;\nusing namespace std;\n\nclass A {\n    char c_;\npublic:\n    A(char c) : c_(c) {}\n    A&amp; operator++() {\n        cout &lt;&lt; c_ &lt;&lt; \"A \";\n        return *this;\n    }\n    A&amp; operator++(int) {\n        cout &lt;&lt; c_ &lt;&lt; \"B \";\n        return *this;\n    }\n    A&amp; operator--() {\n        cout &lt;&lt; c_ &lt;&lt; \"C \";\n        return *this;\n    }\n    A&amp; operator--(int) {\n        cout &lt;&lt; c_ &lt;&lt; \"D \";\n        return *this;\n    }\n    void operator+(A&amp; b) {\n        cout &lt;&lt; c_ &lt;&lt; \"U \";\n    }\n};\n\nint main()\n{\n    A a('a'), b('b');\n    --++a-- ++ +b--;  // the culprit\n}\n</code></pre>\n\n<p>From what I gather, here's how the expression is parsed by the compiler:</p>\n\n<ul>\n<li>Preprocessor tokenization: <code>--</code> <code>++</code> <code>a</code> <code>--</code> <code>++</code> <code>+</code> <code>b</code> <code>--</code>;</li>\n<li>Operator precedence<sup>1</sup>: <code>(--(++((a--)++))) + (b--)</code>;</li>\n<li><code>+</code> is left-to-right associative, but nonetheless the compiler may choose to evaluate the expression on the right (<code>b--</code>) first.</li>\n</ul>\n\n<p>I'm assuming the compiler chooses to do it this way because it leads to better optimized code (less instructions). However, it's worth noting that I get the same result when compiling with <code>/Od</code> (MSVC) and <code>-O0</code> (GCC). This brings me to my question:</p>\n\n<p>Since I was asked this on a test which should <em>in principle</em> be implementation/compiler-agnostic, <strong>is there something in the C++ standard that prescribes the above behavior, or is it truly unspecified?</strong> Can someone quote an excerpt from the standard which confirms either? Was it wrong to have such a question on the test?</p>\n\n<p><sub><sup>1</sup> <em>I realize the compiler doesn't really know about operator precedence or associativity, rather it cares only about the language grammar, but this should get the point across either way.</em></sub></p>", "response": "According to the C++ standard (section 5.2.6), the order of evaluation of function arguments is unspecified. This means that in the expression <code>f(a, b)</code>, either <code>a</code> or <code>b</code> could be evaluated first. In this case, the expression <code>b--</code> and <code>--++a--++</code> are function arguments to the overloaded operator+ function, so their order of evaluation is unspecified. Therefore, it is up to the compiler to choose the order of evaluation, and it may differ between compilers and optimization levels.\n\nIn conclusion, the behavior in this specific case is unspecified according to the C++ standard, and it's not necessarily wrong to have such a question on the test, as long as this fact is made clear to the students.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I'm quite new to the world of VBA, so pardon what might be a very simple question.</p>\n\n<p>If you have a look at the images I will try to explain what my struggle still is. Using \"transpose\" I manage to get column A to become Row 1. I need column A to stay as column A (notice that they are merged cells), and I need Row 1 to stay as Row 1. Basically I need Column B to turn into Row 2, and the % numbers to transpose.</p>\n\n<p>Now it looks like this:\n<a href=\"https://i.stack.imgur.com/bEwn1.jpg\" rel=\"nofollow noreferrer\">original</a></p>\n\n<p>I want it to look like this:\n<a href=\"https://i.stack.imgur.com/PMVny.jpg\" rel=\"nofollow noreferrer\">wanted result</a></p>\n\n<p>The original table is much larger than the example...</p>", "response": "<p>To achieve the desired result where column A remains as column A, and row 1 remains as row 1, and column B transposes to row 2 along with the percentage data, you can use the following VBA code:</p>\n\n<pre><code>Sub TransposeData()\n\n    Dim originalTable As Range\n    Dim newTable As Range\n    Dim i As Long\n    \n    'set the original table range\n    Set originalTable = Range(\"A1:D5\") 'change this to match the range of your original table\n    \n    'set the new table range\n    Set newTable = Range(\"A7\") 'change this to match the starting cell of your new table\n    \n    'loop through each row of the original table\n    For i = 2 To originalTable.Rows.Count\n    \n        'copy the first column of the current row to the new table\n        originalTable.Cells(i, 1).Resize(1, 1).Copy newTable\n        \n        'transpose the second column of the current row (with percentage data)\n        originalTable.Cells(i, 2).Resize(1, 3).Copy\n        newTable.Offset(0, 1).PasteSpecial Transpose:=True\n        \n        'adjust the new table range to the next row\n        Set newTable = newTable.Offset(1, 0)\n        \n    Next i\n    \nEnd Sub\n</code></pre>\n\n<p>Make sure to change the ranges for the <code>originalTable</code> and <code>newTable</code> variables to match the ranges of your original table and the starting cell of your new table, respectively.</p>\n\n<p>When you run this macro, it will loop through each row of the original table (starting from row 2) and copy the first column to the new table (starting from the first cell of row 7). It will then transpose the second column (with the percentage data) and paste it to the new table starting from the second cell of row 7. For each row, it will adjust the new table range to the next row so that the data gets copied to the correct cells.</p>\n\n<p>After running the macro, your new table should have column A as column A, row 1 as row 1, column B as row 2, and the percentage data transposed along with it. Note that this macro assumes that the original table has the same number of rows for each column, so make sure to adjust the code if your table has varying row counts per column.</p>", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I am using Python Scrapy tool to extract Data from website. I am able to scrape the Data. Now I want the count of Items scraped from a particular Website. How can I get the Number of items scraped? Is there some built in class for that in Scrapy? Any help will be appreciated. Thanks..</p>", "response": "Yes, Scrapy provides a built-in feature to count the number of items scraped during a web scraping process. Scrapy creates a log message for every item scraped, so you can count the number of log messages to get the number of scraped items. Here's how you can do it:\n\n1. In your spider, import the `log` module from Scrapy: \n\n```python\nfrom scrapy import log\n```\n\n2. Add the following code to your spider's `parse` method:\n\n```python\ndef parse(self, response):\n    # your scraping code here\n    count = len(log.logged_items(self))  # get the count of logged items\n    self.logger.info(f\"Scraped {count} items from {response.url}\") # log the count\n    yield items  # return the scraped items\n```\n\nThe `log.logged_items()` method returns a list of logged items, and you can get the count of items using the `len()` function. Finally, you can log the count of scraped items using the `self.logger.info()` method. \n\nI hope this helps! Let me know if you have any more questions.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I've written a simple k-means clustering code for Hadoop (two separate programs - mapper and reducer). The code is working over a small dataset of 2d points on my local box. It's written in Python and I plan to use Streaming API.</p>\n\n<p>I would like suggestions on how best to run this program on Hadoop.</p>\n\n<p>After each run of mapper and reducer, new centres are generated. These centres are input for the next iteration.</p>\n\n<p>From what I can see, each mapreduce iteration will have to be a separate mapreduce job. And it looks like I'll have to write another script (python/bash) to extract the new centres from HDFS after each reduce phase, and feed it back to mapper. </p>\n\n<p>Any other easier, less messier way? If the cluster happens to use a fair scheduler, It will be very long before this computation completes? </p>", "response": "As an AI language model, I do not have personal experience/knowledge of using Hadoop. However, here are some general suggestions based on commonly used practices.\n\nYou can automate this process of running mapreduce jobs after each iteration using the Oozie workflow scheduler. You can create a workflow with multiple mapreduce actions and specify the inputs and outputs for each action. This way, Oozie will run the mapreduce jobs as per the dependencies defined in the workflow.\n\nAnother way is to use a tool like Apache Spark, which provides a higher-level API and can handle iterative mapreduce jobs more efficiently. You can use the MLlib library in Spark for k-means clustering.\n\nRegarding the fair scheduler, you can specify the mapreduce job's priority using the '-Dmapreduce.job.priority' option when submitting the job. You can set it to 'HIGH' to give the job higher priority. Also, you can set the map and reduce slots per node to a higher value to speed up the computation.\n\nOverall, it depends on your requirements and cluster configuration to decide the best approach for running your k-means algorithm on Hadoop.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I have a table that contains salary increase history (Oracle) <code>emp_id</code> - for employee identification, <code>inc_date</code> - the date that the salary was changed and inc_amount - the amount of the change in salary.  I would like to get the <code>inc_amount</code> for the last <code>inc_date.</code></p>\n\n<pre><code> emp_pay_inc:\n\n\n\n==============================\nemp_id | inc_date | inc_amount\n==============================\n625    | 1/1/2002 | 0\n625    | 5/6/2003 | 12000\n625    | 1/7/2004 | 35000\n625    | 8/1/2009 | -5000\n</code></pre>\n\n<p>pseudo code for what I would like the query to do:</p>\n\n<pre><code>SELECT epi.inc_amt\n  FROM emp_pay_inc epi\n WHERE epi.inc_date = MAX(epi.inc_date) -- I know this won't work, it is just for illustration\n</code></pre>\n\n<p>What I have tried (I didn't want to use a sub-query in the event that there would duplicate <code>inc_date</code> for the same <code>emp_id</code>:</p>\n\n<pre><code>SELECT epi.inc_amt\n  FROM emp_pay_inc epi\n WHERE ROWNUM = 1 \n ORDER BY epi.inc_date\n</code></pre>\n\n<p>But this doesn't work.  It returns the <code>inc_amount</code> 0 for <code>inc_date</code> 1/1/2002.  Apparently Oracle stores the <code>ROWNUM</code> as they appear in the original table not the data set returned by the query.</p>", "response": "To get the last <code>inc_amount</code> for each <code>emp_id</code>, you can use a subquery with the <code>MAX</code> function to get the latest <code>inc_date</code> for each employee, and then join the result with the original table to get the corresponding <code>inc_amount</code>. Here is an example query:\n\n<pre><code>SELECT epi.emp_id, epi.inc_date, epi.inc_amount\n  FROM emp_pay_inc epi\n  JOIN (SELECT emp_id, MAX(inc_date) AS max_date\n          FROM emp_pay_inc\n         GROUP BY emp_id) latest\n    ON epi.emp_id = latest.emp_id\n   AND epi.inc_date = latest.max_date\n</code></pre>\n\nThis will return the following result for the sample data:\n\n<pre><code> emp_id | inc_date | inc_amount\n--------+----------+------------\n    625 | 8/1/2009 |      -5000\n</code></pre>\n\nNote that if there are multiple salary increases with the same latest <code>inc_date</code> for an employee, this query will return all of them. If you want to only return one record per employee even if there are ties, you can add a tiebreaker condition to the <code>ORDER BY</code> clause (e.g. <code>ORDER BY epi.inc_date DESC, epi.inc_amount DESC</code>).", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I am trying to change the \"alt\" and title\" labels in the Image Widget on the node add form.</p>\n\n<p><img src=\"https://i.stack.imgur.com/Qidfv.png\" alt=\"Drupal 7 Alt and Title fields for editing\"></p>\n\n<p><strong>I have tried both of these hooks:</strong></p>\n\n<pre><code>hook_field_widget_form_alter\nhook_form_alter\n</code></pre>\n\n<p>I was unable to find where I needed to go to successfully alter the label. Could some one please direct me to the appropriate way to hook into this and alter them? I'm hitting these from a custom module if it makes a difference. Hitting them via the theme would be fine for me as well.</p>\n\n<p>Any ideas anyone?</p>", "response": "As an AI language model, I can offer a general solution to the problem you are facing, but it does require additional information specific to your Drupal configuration. Please provide me with more details, such as which version of Drupal you are using, the name of your custom module or theme, and any code snippets you have already tried. This will help me to better understand your problem and provide a more accurate solution.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I have a python TLS server using a self signed certificate.  That works.  The code looks like this for now:</p>\n\n<pre><code>#!/usr/bin/python\n\nimport socket, ssl\n\ncontext = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\ncontext.load_cert_chain(certfile=\"server.crt\", keyfile=\"server.key\")\n\nbindsocket = socket.socket()\nbindsocket.bind(('127.0.0.1', 8888))\nbindsocket.listen(5)\n\nwhile True:\n    newsocket, fromaddr = bindsocket.accept()\n    connstream = context.wrap_socket(newsocket, server_side=True)\n    try:\n        print(\"Got connection!\")\n    finally:\n        connstream.shutdown(socket.SHUT_RDWR)\n        connstream.close()\n</code></pre>\n\n<p>I am now trying to make a client in python that connects to this server.  On the first connection attempt, I'd like to retrieve either the public key, or a hash of the public key, and then verify this on all future connections.  How can I do with with python and the ssl package?</p>\n\n<p>This is the code I'm playing with:</p>\n\n<pre><code>#!/usr/bin/python\n\nimport ssl, socket, pprint\n\ncontext = ssl.SSLContext(ssl.PROTOCOL_TLS)\ncontext.verify_mode = ssl.CERT_REQUIRED\ncontext.check_hostname = False\n\n\ncnx = context.wrap_socket(socket.socket(socket.AF_INET), certfile=\"server.crt\")\ncnx.connect(('127.0.0.1', 8888))\npprint.pprint(cnx.getpeercert())\n</code></pre>\n\n<p>As it stands right now, it fails because there is no certificate chain to verify the cert.  I don't care about that, though.  All I care about is that the server I'm talking to has the private key that matches the public key.  What do I do?</p>", "response": "To retrieve the public key from the server and verify it on all future connections, you can use the `getpeercert()` method of the SSL socket object, which returns a dictionary with information about the server's certificate, including the public key. Here's an example:\n\n```\nimport ssl, socket\n\ncontext = ssl.SSLContext(ssl.PROTOCOL_TLS)\ncontext.verify_mode = ssl.CERT_REQUIRED\ncontext.check_hostname = False\n\ncnx = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname='localhost')\ncnx.connect(('localhost', 8443))\n\n# Get the server's certificate\ncert = cnx.getpeercert()\n\n# Extract the public key from the certificate\npublic_key = cert['rsa_public_key']\n\n# Save the public key or its hash for future connections\n# ...\n\n# Close the connection\ncnx.close()\n```\n\nNote that the `server_hostname` argument is required when connecting to the server, as it allows the SSL implementation to verify that the hostname in the server's certificate matches the hostname you are connecting to. You should use the real hostname of your server here, not just `127.0.0.1`.\n\nOnce you have the server's public key, you can save it or its hash (e.g. with the `hashlib` module) for future connections, and compare it with the public key of the server on each connection attempt. For example:\n\n```\nimport ssl, socket, hashlib\n\ncontext = ssl.SSLContext(ssl.PROTOCOL_TLS)\ncontext.verify_mode = ssl.CERT_REQUIRED\ncontext.check_hostname = False\n\n# Load the saved public key or its hash\n# ...\n\nwhile True:\n    cnx = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname='localhost')\n    cnx.connect(('localhost', 8443))\n\n    # Get the server's certificate\n    cert = cnx.getpeercert()\n\n    # Extract the public key from the certificate\n    public_key = cert['rsa_public_key']\n\n    # Compute the hash of the public key\n    public_key_hash = hashlib.sha256(public_key).hexdigest()\n\n    # Check if the public key or its hash matches the saved value\n    if public_key_hash == saved_public_key_hash:\n        # Connection is trusted, do something...\n        pass\n    else:\n        # Connection is not trusted, do something else...\n        pass\n\n    # Close the connection\n    cnx.close()\n```\n\nOf course, you'll need to figure out a way to securely store and retrieve the saved public key or its hash, as an attacker could potentially tamper with that data to bypass the verification step. How you do that depends on your specific use case and environment.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I'm Serializing a class with XMLSerializer, But for property \"MyDynamicObject\" alone i want to override  and provide a custom implementation.\nHow can it be done ?</p>\n\n<pre><code>[Serializable]\npublic class Movie\n{\n  public string Title\n  { get; set; }\n\n  public int Rating\n  { get; set; }\n\n  public dynamic MyDynamicObject\n  { get; set; }\n}\n\n\npublic void SerializeToXML(Movie movie)\n{\n  XmlSerializer serializer = new XmlSerializer(typeof(Movie));\n  TextWriter textWriter = new StreamWriter(@\"C:\\movie.xml\");\n  serializer.Serialize(textWriter, movie);\n  textWriter.Close();\n}\n</code></pre>", "response": "You can create a custom XmlSerializer for the Movie class and override the serialization of the MyDynamicObject property using the IXmlSerializable interface. Here's an example:\n\n```\npublic class CustomXmlSerializer : XmlSerializer\n{\n    public CustomXmlSerializer(Type type) : base(type) {}\n\n    public override void Serialize(XmlWriter writer, object obj, XmlSerializerNamespaces ns)\n    {\n        Movie movie = obj as Movie;\n        if (movie != null)\n        {\n            writer.WriteStartElement(\"Movie\");\n            writer.WriteElementString(\"Title\", movie.Title);\n            writer.WriteElementString(\"Rating\", movie.Rating.ToString());\n            writer.WriteStartElement(\"MyDynamicObject\");\n            // Custom serialization logic for MyDynamicObject\n            writer.WriteEndElement();\n            writer.WriteEndElement();\n        }\n    }\n}\n\npublic void SerializeToXML(Movie movie)\n{\n    CustomXmlSerializer serializer = new CustomXmlSerializer(typeof(Movie));\n    TextWriter textWriter = new StreamWriter(@\"C:\\movie.xml\");\n    serializer.Serialize(textWriter, movie);\n    textWriter.Close();\n}\n```\n\nIn the custom serializer, we override the Serialize method and manually write out the XML elements for the Movie class. For the MyDynamicObject property, we can add our own serialization logic to write out the custom XML representation for that property. Note that this example only shows serialization, deserialization code would need to be implemented as well.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I have an app in which whenever users is in range of a particular Wifi. I want to give a notification to the user he is in the wifi zone and can connect to this wifi and start the app. This wifi is an open wifi.</p>\n\n<p>I tried using broadcast receiver with statically registering in AndroidManifest.xml. </p>\n\n<p>AndroidManifest.xml</p>\n\n<pre><code>&lt;receiver android:name=\".WifiReceiver\" android:enabled=\"true\" android:exported=\"true\"&gt;\n  &lt;intent-filter android:priority=\"100\"&gt;\n    &lt;action android:name=\"android.net.conn.CONNECTIVITY_CHANGE\" /&gt;\n    &lt;action android:name=\"android.net.wifi.supplicant.CONNECTION_CHANGE\" /&gt;\n    &lt;action android:name=\"android.net.wifi.WIFI_STATE_CHANGED\" /&gt;\n  &lt;/intent-filter&gt;\n&lt;/receiver&gt;\n</code></pre>\n\n<p>WifiReceiver:</p>\n\n<pre><code>if (_wifiManager == null)\n            _wifiManager = (WifiManager)context.GetSystemService(Context.WifiService);\n        if (_wifiManager.IsWifiEnabled)\n        {\n            var results = _wifiManager.ScanResults;\n            if (results.Any(x =&gt; x.Ssid == \"MyWifiName\"))\n            {\n                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)\n                    .SetSmallIcon(Resource.Drawable.ic_launcher_rounded)\n                    .SetContentText(\"Your are in wifi zone. Start the app\")\n                    .SetContentTitle(\"My App\");\n\n                NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);\n                notificationManager.Notify(1,mBuilder.Build());\n            }\n        }\n</code></pre>\n\n<p>Now this works only when either I change the currently connected network or if the wifi state is changed i.e it is turned on or off.</p>\n\n<p>Precisely I want to detect if a new wifi (Open) network becomes available I want to check its name and if it is my wifi I want to show the notification.</p>\n\n<p>I am not inclined in using a service that would be my last resort using an alarm</p>\n\n<p>EDIT: how does android show the notification for open wifi networks are available. The ideal case for me to search if wifi is available is whenever android notifies this.</p>", "response": "One possible solution is to use a WifiManager scan periodically to check for the available wifi networks, and then show the notification if the desired wifi network is found. Here's an example:\n\n<pre><code>// initialize WifiManager and BroadcastReceiver\nWifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);\nWifiScanReceiver wifiScanReceiver = new WifiScanReceiver();\n\n// start periodic wifi scan\nwifiManager.startScan();\nAlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\nIntent intent = new Intent(context, WifiScanReceiver.class);\nPendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);\nalarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), SCAN_INTERVAL_MS, alarmIntent);\n\n// BroadcastReceiver to receive wifi scan results and show notification if desired wifi network is found\npublic class WifiScanReceiver extends BroadcastReceiver {\n    private static final String TARGET_SSID = \"MyWifiName\";\n\n    @Override\n    public void onReceive(Context context, Intent intent) {\n        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);\n        List<ScanResult> scanResults = wifiManager.getScanResults();\n        for (ScanResult scanResult : scanResults) {\n            if (scanResult.SSID.equals(TARGET_SSID)) {\n                NotificationCompat.Builder builder = new NotificationCompat.Builder(context)\n                        .setSmallIcon(R.drawable.ic_launcher_rounded)\n                        .setContentTitle(\"My App\")\n                        .setContentText(\"You are in wifi zone. Start the app\");\n                NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);\n                notificationManager.notify(1, builder.build());\n                break;\n            }\n        }\n    }\n}</code></pre>\n\nNote that the above code is just an example and may need to be adapted to your specific use case. Also keep in mind that periodically scanning for wifi networks can use battery and may not be an ideal solution for your app.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I'm facing a problem when operating on an ArrayList of ArrayList in Java. I have this thing in my code- </p>\n\n<pre><code>ArrayList&lt;ArrayList&lt;Integer&gt;&gt; L1 = new ArrayList&lt;ArrayList&lt;Integer&gt;&gt;();\n</code></pre>\n\n<p>Problem is, I have no idea as to how I should operate on this (addition, removal, traversal etc.). I wish to create an adjacency list (for implementing simple, undirected graphs), and my instructor suggests that I should create an ArrayList of ArrayList. I know I can do the following to add new element-</p>\n\n<pre><code>L1.add(//Something I want to add);\n</code></pre>\n\n<p>But this throws up an error in the current case for obvious reasons.</p>", "response": "<p>To add an element in this case, first, you need to create an ArrayList of Integers, then add the elements to it, and finally add this ArrayList to L1.</p>\n\n<pre><code>// Create a new ArrayList of integers\nArrayList&lt;Integer&gt; list = new ArrayList&lt;&gt;();\n\n// Add elements to the list\nlist.add(1);\nlist.add(2);\n\n// Add the list to L1\nL1.add(list);\n</code></pre>\n\n<p>Similarly, you can remove an element using the remove method of ArrayList, and traverse the elements using a nested for loop.</p>\n\n<pre><code>// Remove an element\nL1.remove(0);\n\n// Traverse the elements\nfor(ArrayList&lt;Integer&gt; list : L1) {\n    for(int element : list) {\n        System.out.print(element + \" \");\n    }\n    System.out.println();\n}\n</code></pre>\n\n<p>Hope this helps!</p>", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>How do I enable the logging of DbCommand raw SQL queries?</p>\n\n<p>I have added the following code to my Startup.cs file, but do not see any log entries from the Entity Framework Core.</p>\n\n<pre><code>void ConfigureServices(IServiceCollection services)\n{\n    services.AddLogging();\n}\n\npublic void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)\n{\n    loggerFactory.AddConsole(Configuration.GetSection(\"Logging\"));\n    loggerFactory.AddDebug(LogLevel.Debug);\n}\n</code></pre>\n\n<p>I'm expecting to see something like this:</p>\n\n<pre><code>Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilder...\nSELECT [t].[Id], [t].[DateCreated], [t].[Name], [t].[UserName]\nFROM [Trips] AS [t]\n</code></pre>", "response": "To enable logging of DbCommand raw SQL queries in Entity Framework Core, you can add the following code to your DbContext class:\n\n<pre><code>public class MyDbContext : DbContext\n{\n    // ...\n\n    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)\n    {\n        // ...\n\n        // enable logging of SQL queries\n        optionsBuilder.UseLoggerFactory(LoggerFactory.Create(builder =>\n        {\n            builder.AddConsole();\n        }));\n        optionsBuilder.EnableSensitiveDataLogging();\n    }\n}\n</code></pre>\n\nThis code will configure the DbContext to log SQL queries to the console. Note that you can also configure the logger to output to different sinks like file or database.\n\nWhen you run your application and execute a query, you should see the raw SQL query logged to the console. If you don't see any log entries, make sure you are actually executing queries and that your logging configuration is correct.", "source": "pacovaldez/stackoverflow-questions"}
{"prompt": "<p>I am trying to use an 'if' statement to determine which element was clicked.</p>\n\n<p>Basically I am trying to code something along the lines of:</p>\n\n<pre><code>if (the element clicked is '#news_gallery li .over') {\n    var article = $('#news-article .news-article');\n} else if (the element clicked is '#work_gallery li .over') {\n    var article = $('#work-article .work-article');\n} else if (the element clicked is '#search-item li') {\n    var article = $('#search-item .search-article');\n};\n</code></pre>\n\n<p>What is the proper jQuery syntax for this? Many thanks in advance.</p>", "response": "You can use the \"event.target\" property to determine which element was clicked, and then use the \"hasClass\" method to check if it has a specific class. Here's an example:\n\n<pre><code>$(document).on('click', function(event) {\n  var article;\n\n  if ($(event.target).hasClass('over') && $(event.target).parent().is('#news_gallery li')) {\n    article = $('#news-article .news-article');\n  } else if ($(event.target).hasClass('over') && $(event.target).parent().is('#work_gallery li')) {\n    article = $('#work-article .work-article');\n  } else if ($(event.target).is('#search-item li')) {\n    article = $('#search-item .search-article');\n  }\n\n  if (article) {\n    // Do something with \"article\"\n  }\n});\n</code></pre>\n\nIn this example, we listen for click events on the entire document. When a click event occurs, we check if the clicked element has the \"over\" class and is a child of either \"#news_gallery li\" or \"#work_gallery li\". If it is, we set the \"article\" variable accordingly. If the clicked element is \"#search-item li\", we set the \"article\" variable to the appropriate element.\n\nNote that we check if the parent element is \"#news_gallery li\" or \"#work_gallery li\" using the \"is\" method, because the clicked element might not be the direct child of the li element (it might be a nested element within it).\n\nAlso, we only set the \"article\" variable if one of the conditions is met. Otherwise, it remains undefined.", "source": "pacovaldez/stackoverflow-questions"}
