title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
Control.Invoke from same thread where the form is running
<p>In C#, is there any problem using Control.Invoke to change a property of a Control from the same thread where the form is running?</p> <p>I know it would be best using <code>Control.Property = value</code>, but I'd like to know which are the consequences of using Control.Invoke instead.</p> <p>Example:</p> <p>Using this:</p> <pre><code>public partial class FormMain : Form { private void Button1_Click(object sender, EventArgs e) { this.Invoke(new delegate {Label1.Text = "Hello"}); } } </code></pre> <p>Instead of this:</p> <pre><code>public partial class FormMain : Form { private void Button1_Click(object sender, EventArgs e) { Label1.Text = "Hello"; } } </code></pre>
2
In python 3 print() command to print chr with ascii directly under in a complete table
<p>I am very new to python and want to use it as retirement project. However I have a lot of trouble trying to print a table in the format below. I only will show the ascii table as below, in what I'm trying to achieve</p> <pre><code>chr: ! " # $ % &amp; ' ( ) * + , - . / asc: 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 chr: 0 1 2 3 4 5 6 7 8 9 : ; &lt; = &gt; ? asc: 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 </code></pre> <p>I tried <code>'\n'</code> in many variations and I cannot print the output as above. Here is the short code I tried to get the thing working at least;</p> <pre><code>for asc in range(32,64): print(chr(asc),end = ' ') print(ord(chr(asc)),end = ' ') </code></pre> <p>Putting a <code>'\n'</code> in anywhere, only confuses the issue further;</p> <pre><code>for asc in range(32,64): print(chr(asc),'\n',end = ' ') print(ord(chr(asc)),end = ' ') </code></pre> <p>Makes the output vertical again, so I'm stuck. I looked hard on Google and this site and I would prefer to stay away from class type commands as I'm still at the very beginning of programming. The long way at this point. Any help would be welcome.</p>
2
Cannot load bean in different package in Spring Boot application
<p>I'm trying to load beans from a different package on a Spring boot application. Here's my main class, that lives in <strong><em>com.xyz.app</em></strong> package:</p> <p><strong><em>Application.java</em></strong>:</p> <pre><code>@SpringBootApplication(scanBasePackages = { "com.xyz.app.repository" }) public class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(Application.class, args); context.getBean(MyInterfaceRepository.class).loadData(); } </code></pre> <p>The interface <strong><em>MyInterfaceRepository.java</em></strong> is inside the <strong><em>com.xyz.app.repository</em></strong> package, and is defined as follows:</p> <pre><code>@RepositoryRestResource(collectionResourceRel = "aas", path = "aas") public interface MyInterfaceRepository extends MongoRepository&lt;MyClass, Long&gt;, MyCustomInterface { ... } </code></pre> <p>Then, I also have a <strong><em>MyInterfaceRepositoryImpl.java</em></strong>, that lives in <strong><em>com.xyz.app.repository</em></strong>, that provides an implementation for <strong><em>MyCustomInterface.java</em></strong>, that also lives in <strong><em>com.xyz.app.repository</em></strong>.</p> <p>Starting my application I get the following:</p> <pre><code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xyz.app.repository.MyInterfaceRepository] is defined at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:372) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:332) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1066) at com.xyz.app.Application.main(Application.java:60) </code></pre> <p>I already checked, and indeed if I put <strong><em>MyInterfaceRepository.java</em></strong> and <strong><em>MyInterfaceRepositoryImpl.java</em></strong> in the same package as <strong><em>Application.java</em></strong>, <strong><em>com.xyz.app</em></strong>, than it works.</p> <p>It seems that Spring is not able to load the beans from a different package than the one where <strong><em>Application.java</em></strong> is. </p> <p>Also, I tried replacing the <strong><em>@SpringBootApplication</em></strong> with these:</p> <pre><code>@Configuration @EnableAutoConfiguration @ComponentScan({"com.xyz.app.repository"}) </code></pre> <p>Same issue.. Any idea?</p>
2
Centos7 :: Error unpacking rpm package httpd-2.4.6-40.el7.centos.1.x86_64
<p>I have to build an Image Docker for the solution of my company. This Image have to contains some dependencies and have to based on centos7. Among these dependencies, there is httpd.</p> <p>So, I built an image of CentOS 7 with systemd with this Dockerfile according to these explainations : <a href="https://hub.docker.com/_/centos/" rel="nofollow">https://hub.docker.com/_/centos/</a></p> <p>My centos7/Dockerfile</p> <blockquote> <pre><code>FROM centos:centos7 ENV container docker RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; \ do [ $i == systemd-tmpfiles-setup.service ] || rm -f $i; done); \ rm -f /lib/systemd/system/multi-user.target.wants/*;\ rm -f /etc/systemd/system/*.wants/*;\ rm -f /lib/systemd/system/local-fs.target.wants/*; \ rm -f /lib/systemd/system/sockets.target.wants/*udev*; \ rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \ rm -f /lib/systemd/system/basic.target.wants/*;\ rm -f /lib/systemd/system/anaconda.target.wants/*; RUN yum -y install deltarpm &amp;&amp; yum clean all RUN yum -y update &amp;&amp; yum clean all RUN yum -y install vim wget tar &amp;&amp; yum clean all VOLUME ["/sys/fs/cgroup"] CMD ["/usr/sbin/init"] </code></pre> </blockquote> <p>And I push this image on my repository "agilium/centos7" And I wrote an other Dockerfile for httpd according to the same explainations : My httpd/Dockerfile</p> <blockquote> <pre><code>FROM agilium/centos7 RUN yum -y update &amp;&amp; yum clean all RUN yum -y install httpd; yum clean all; systemctl enable httpd.service EXPOSE 80 CMD ["/usr/sbin/init"] </code></pre> </blockquote> <p>And I have this error when I built my image : <a href="http://i.stack.imgur.com/ECFt2.png" rel="nofollow">Error unpacking rpm package httpd-2.4.6-40.el7.centos.1.x86_64</a></p> <p>I also tried to localinstall the rpm package, but with the same error, like this :</p> <blockquote> <pre><code>COPY ./install/* ./install/ RUN yum -y localinstall ./install/httpd-2.4.6-40.el7.centos.1.x86_64.rpm </code></pre> </blockquote> <p>I search for solutions and I find an issue on github (issue #461) but it seems there was no solution found and the problem has solved itself. =/</p> <p>Thanks for help.</p>
2
Model/Form validation using Data Annotations and JavaScript
<p>I would like to implement Data Validations on my ASP MVC app. I am currently using Data Annotations like this: </p> <pre><code>[Required] public string UserName { get; set; } </code></pre> <p>Which would then turn into something like</p> <pre><code>&lt;input type='text' ... data-required&gt; </code></pre> <p>I can validate it fine using jquery unobtrusive validation, however, this project does not have jQuery. It is built straight from Javascript and we plan to keep it that way. </p> <p>Is there any way I can do this without jQuery?</p>
2
Laravel 5 composer update not working?
<p>I am using Laravel version 5.2 and Jenssegers MongoDB. I installed both and working fine but I have to use any other library and made changes in composer.json after that use command <strong>composer update</strong>. After using this command automatically Jenssegers MongoDB file removed. I don't know why this happen. After composer update why Jenssegers MongoDB file removed automatically? Please suggest me how to handel this?</p> <p>My composer.json file</p> <pre><code> { "name": "laravel/laravel", "description": "The Laravel Framework.", "keywords": ["framework", "laravel"], "license": "MIT", "type": "project", "require": { "php": "&gt;=5.5.9", "laravel/framework": "5.2.*", "acacha/admin-lte-template-laravel": "2.*" }, "require-dev": { "fzaninotto/faker": "~1.4", "mockery/mockery": "0.9.*", "phpunit/phpunit": "~4.0", "symfony/css-selector": "2.8.*|3.0.*", "symfony/dom-crawler": "2.8.*|3.0.*" }, "autoload": { "classmap": [ "database" ], "psr-4": { "App\\": "app/" }, "files": [ "app/common_helper.php" ] }, "autoload-dev": { "classmap": [ "tests/TestCase.php" ] }, "scripts": { "post-root-package-install": [ "php -r \"copy('.env.example', '.env');\"" ], "post-create-project-cmd": [ "php artisan key:generate" ], "post-install-cmd": [ "Illuminate\\Foundation\\ComposerScripts::postInstall", "php artisan optimize" ], "post-update-cmd": [ "Illuminate\\Foundation\\ComposerScripts::postUpdate", "php artisan optimize" ] }, "config": { "preferred-install": "dist" } } </code></pre>
2
Exception during list comprehension. Are intermediate results kept anywhere?
<p>When using try-except in a for loop context, the commands executed so far are obviously done with</p> <pre><code>a = [1, 2, 3, 'text', 5] b = [] try: for k in range(len(a)): b.append(a[k] + 4) except: print('Error!') print(b) </code></pre> <p>results with </p> <pre><code>Error! [5, 6, 7] </code></pre> <p>However the same is not true for list comprehensions</p> <pre><code>c=[] try: c = [a[k] + 4 for k in range(len(a))] except: print('Error!') print(c) </code></pre> <p>And the result is</p> <pre><code>Error! [] </code></pre> <p>Is the intermediate list, built before the exception occurred, kept anywhere? Is it accessible?</p>
2
Kendo Grid resizable is not working in IE
<p>I am using Kendo Grid to show the records.Below is my sample Html Page where i want to achieve the result for re-sizable in IE only. I have modified the code for Sample purpose only in Html. Resizable in Chrome is working.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;base href="http://demos.telerik.com/kendo-ui/grid/column-resizing"&gt; &lt;title&gt;&lt;/title&gt; &lt;link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.mobile.all.min.css" /&gt; &lt;link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.607/styles/kendo.common-material.min.css" /&gt; &lt;link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.607/styles/kendo.material.min.css" /&gt; &lt;link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.607/styles/kendo.default.mobile.min.css" /&gt; &lt;script src="//kendo.cdn.telerik.com/2016.2.607/js/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="//kendo.cdn.telerik.com/2016.2.607/js/kendo.all.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /&gt; &lt;link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"&gt; &lt;script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"&gt;&lt;/script&gt; &lt;style&gt; .wrap { width: 95%; margin: 0 auto; } .PageContentHeading { padding: 3% 0; } .PageContentHeading h3 { margin: 0; } .AddUser { margin-left: 10px; } .AddUser a { border-radius: 0; padding: 4px 12px; } .btn-group-sm &gt; .btn, .btn-sm { border-radius: 0; } .SupplierCompanyName { color: red; } .k-grid td { border-left: none; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;script type="text/x-kendo-template" id="toolBarTemplate"&gt; &lt;div class="toolbar"&gt; &lt;div class="row"&gt; &lt;div class="col-md-4" style="float:right;"&gt; &lt;div class="input-group"&gt; &lt;span class="input-group-addon"&gt;&lt;span class="glyphicon glyphicon-search" aria-hidden="true"&gt;&lt;/span&gt;&lt;/span&gt; &lt;input type="search" class="form-control" id='txtSearchString' placeholder="Search by User Details"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/script&gt; &lt;div class="wrap"&gt; &lt;div class="main"&gt; &lt;div class="PageContentHeading"&gt; &lt;h3 class="pull-left"&gt; Manage Users - &lt;span id="supplierPanel"&gt; &lt;span id="supplerCompany" class="SupplierCompanyName"&gt; ABC Aerospace Inc. &lt;/span&gt; &lt;span class="SupplierCompanyID"&gt; [ ID_0001 ] &lt;/span&gt; &lt;/span&gt; &lt;/h3&gt; &lt;div class="pull-right AddUser"&gt; &lt;a href="@Url.Action(" AddUser", "user" )" class="btn btn-success" style="color:#FFF;"&gt;Add User&lt;/a&gt; &lt;/div&gt; &lt;div class="pull-right ShowUsers"&gt; &lt;span class="labelname"&gt;Include Inactive Users:&lt;/span&gt; &lt;input type="checkbox" checked data-toggle="toggle" data-on="True" data-off="False" data-onstyle="success" data-offstyle="danger" data-size="small"&gt; &lt;/div&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="grid"&gt;&lt;/div&gt; &lt;script&gt; var apiUrl = "http://localhost:55020/"; var dynamicTemplate; var col = []; function switchChange(e) { //alert('E'); } function GetColumnsDetails() { var rowsTempldateStyle = "&lt;tr&gt; &lt;td style='word-wrap: break-word'&gt; &lt;span class='UserDesignation'&gt; #:FullName #&lt;/span&gt;&lt;span class='UserName'&gt;#:title #&lt;/span&gt; &lt;/td&gt; "; $.ajax({ url: apiUrl + "api/user/GetColumns/1", type: 'GET', async: false, success: function (result) { if (result.length &gt; 0) { for (var i = 0; i &lt; result.length; i++) { col.push({ field: result[i].colnameName, title: result[i].titleName, }); } col.push({ title: "Active", template: "&lt;input type='checkbox' disabled='disabled' /&gt;", width: "70px" }) col.push({ title: "Action", name: 'edit', width: "70px" }); } } }); } $(document).ready(function () { // GetColumnsDetails(); $("#grid").kendoGrid({ dataSource: { pageSize: 5, batch: false, // enable batch editing - changes will be saved when the user clicks the "Save changes" button transport: { read: "//demos.telerik.com/kendo-ui/service/Northwind.svc/Customers" }, pageSize: 20 }, height: 550, sortable: true, resizable: true, filterable: true, pageable: { refresh: true, pageSizes: true, buttonCount: 2 }, //resizable: true, columns: [{ template: "&lt;div class='customer-photo'" + "style='background-image: url(../content/web/Customers/#:data.CustomerID#.jpg);'&gt;&lt;/div&gt;" + "&lt;div class='customer-name'&gt;#: ContactName #&lt;/div&gt;", field: "ContactName", title: "Contact Name", width: 240 }, { field: "ContactTitle", title: "Contact Title" }, { field: "CompanyName", title: "Company Name" }, { field: "Country", width: 150 }] }); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I am using Latest version of Kendo but still it is not giving me the expected result. I have tried also to give the Width of each column but the same problem in IE. Can someone help me with this.</p>
2
Failed to list gulp tasks in WebStorm 2016.1
<p>I am using Gulp 3.9.1, node 5.7.1, npm 3.10.3, and WebStorm 2016.1. When I try to setup gulp for my project, I get the following error:</p> <pre><code>/usr/local/bin/node /Users/msbauer/Developer/workspaces/provider-data-management/node_modules/gulp/bin/gulp.js --color --gulpfile /Users/msbauer/Developer/workspaces/provider-data-management/gulpfile.js error: unknown option `--color' Process finished with exit code 1 </code></pre> <p>And when I force to rescan tasks:</p> <pre><code>Failed to list gulp tasks in provider-data-management/gulpfile.js: process finished with exit code 1 (a non-zero exit code means an error) * Edit settings $ /usr/local/bin/node /Users/msbauer/Developer/workspaces/provider-data-management/node_modules/gulp/bin/gulp.js --no-color --gulpfile /Users/msbauer/Developer/workspaces/provider-data-management/gulpfile.js --tasks error: unknown option `--no-color' Process finished with exit code 1 </code></pre> <p>When I execute <code>gulp --help</code> at CLI:</p> <pre><code>$ gulp --help Usage: gulp [options] [command] Commands: about display version information about availity-workflow project init initialize project metadata: package.json, bower.json, availity.json and README.md Options: -h, --help output usage information -V, --version output the version number </code></pre> <p>It's almost as if WebStorm is tacking on extra params, but the version of gulp I have doesn't support said params.</p> <p><strong>Updated:</strong></p> <p>I ran the following to installed gulp-cli (the second from my project root):</p> <pre><code>$ brew install gulp-cli $ npm install -g gulp-cli </code></pre> <p>If I do <code>gulp --help</code> I get the right options:</p> <pre><code>$ gulp --help Usage: gulp [options] tasks Options: --help, -h Show this help. [boolean] --version, -v Print the global and local gulp versions. [boolean] --require Will require a module before running the gulpfile. This is useful for transpilers but also has other applications. [string] --gulpfile Manually set path of gulpfile. Useful if you have multiple gulpfiles. This will set the CWD to the gulpfile directory as well. [string] --cwd Manually set the CWD. The search for the gulpfile, as well as the relativity of all requires will be from here. [string] --verify Will verify plugins referenced in project's package.json against the plugins blacklist. --tasks, -T Print the task dependency tree for the loaded gulpfile. [boolean] --depth Specify the depth of the task dependency tree. --tasks-simple Print a plaintext list of tasks for the loaded gulpfile. [boolean] --tasks-json Print the task dependency tree, in JSON format, for the loaded gulpfile. --color Will force gulp and gulp plugins to display colors, even when no color support is detected. [boolean] --no-color Will force gulp and gulp plugins to not display colors, even when color support is detected. [boolean] --silent, -S Suppress all gulp logging. [boolean] --continue Continue execution of tasks upon failure. [boolean] --log-level, -L Set the loglevel. -L for least verbose and -LLLL for most verbose. -LLL is default. [count] </code></pre> <p><code>which</code> returns the path <code>/Users/me/Developer/homebrew/bin/gulp</code>. But if I run <code>gulp --color</code> I still get the error <code>error: unknown option</code>--color'`</p> <p>If I do the same experiment using the gulp path of <code>~/Developer/workspace/project/node_modules/gulp-cli/bin/gulp.js --help</code>(again, from CLI) I get the exact same results: <code>--help</code> outputs the correct options, but <code>--color</code> and <code>--no-color</code> fails with the same error, despite being listed as valid options.</p>
2
Can't connect to TFS server from Intellij IDEA 2016.1.3: "Failed to load workspaces: Host contacted, but no TFS service found"
<p>I am having an issue where I am not able to connect to my TFS server from Intellij IDEA 2016.1.3. For the sake of this example, assume that the url to my TFS server is: <strong><a href="https://myurlsegment.visualstudio.com" rel="nofollow">https://myurlsegment.visualstudio.com</a>.</strong> Since I don't have enough reputation to post more than 2 urls, I am going to omit the "https" part from some of the urls in the description below, but rest assured that it is present in the actual url. Also assume that the name of my collection is <strong>"mycol"</strong>. Finally, note that I have enabled alternate authentication credentials for this server from TFS security.</p> <p>Here are the repro steps from Intellij IDEA:</p> <ol> <li><p>Go to: VCS->TFS-><strong>Edit Configuration</strong></p></li> <li><p>The "Manage TFS Servers and Workspaces" dialog opens, click "<strong>Add...</strong>"</p></li> </ol> <p>The "Add Team Foundation Server" dialog opens, fill out the details:</p> <p><strong>Address:</strong> <a href="https://myurlsegment.visualstudio.com" rel="nofollow">https://myurlsegment.visualstudio.com</a></p> <p>Here, I have also tried "://myurlsegment.visualstudio.com/mycol" and "://myurlsegment.visualstudio.com/DefaultCollection" (with https in front)</p> <p><strong>Auth:</strong> Alternate</p> <p><strong>User name:</strong> my microsoft (live) id</p> <p><strong>Password:</strong> password for alternate credentials as specified in Visual Studio Team Services.</p> <ol start="3"> <li>Click OK</li> <li>I get the error message:</li> </ol> <p><strong>"Failed to load workspaces: Host contacted, but no TFS service found"</strong></p> <p>After this, the server is still added, <strong><em>but with the wrong url</em></strong>. For some reason, Intellij IDEA appends <strong>"myurlsegment"</strong> to the original url, and I get the following for server name:</p> <p>://myurlsegment.visualstudio.com/<strong>myurlsegment</strong></p> <p>Instead of this: ://myurlsegment.visualstudio.com/<strong>mycol</strong> (or ://myurlsegment.visualstudio.com/<strong>DefaultCollection</strong>)</p> <p>Of course since I don't have anything under the url: ://myurlsegment.visualstudio.com/<strong>myurlsegment</strong>, I can't add any workspaces or do anything with this server added in such manner - it's useless.</p> <p>Any ideas what may be causing this error?</p> <p><strong>EDIT:</strong></p> <p>Btw I am able to connect just fine to my TFS server from Visual Studio 2015. I noticed that the url in Visual Studio is indeed shown as: <strong>myurlsegment</strong>.visualstudio.com/<strong>myurlsegment</strong>, so this may not be the problem. I also looked the the IntelliJ IDEA log, and found this:</p> <p>2016-07-07 08:29:01,021 [ ] DEBUG - httpclient.wire.header - >> "POST /myurlsegment/Services/v1.0/Registration.asmx HTTP/1.1[\r][\n]" </p> <p>2016-07-07 08:29:01,021 [ ] DEBUG - httpclient.wire.header - >> "Content-Type: application/soap+xml; charset=UTF-8; action="http://schemas.microsoft.com/TeamFoundation/2005/06/Services/Registration/03/GetRegistrationEntries"[\r][\n]" </p> <p>2016-07-07 08:29:01,021 [ ] DEBUG - httpclient.wire.header - >> "Authorization: Basic [\r][\n]" </p> <p>2016-07-07 08:29:01,021 [ ] DEBUG - httpclient.wire.header - >> "User-Agent: Axis2[\r][\n]" </p> <p>2016-07-07 08:29:01,021 [ ] DEBUG - httpclient.wire.header - >> "Accept-Encoding: gzip[\r][\n]" </p> <p>2016-07-07 08:29:01,021 [ ] DEBUG - httpclient.wire.header - >> "Host: myurlsegment.visualstudio.com[\r][\n]" </p> <p>2016-07-07 08:29:01,021 [ ] DEBUG - httpclient.wire.header - >> "Content-Length: 270[\r][\n]" </p> <p>2016-07-07 08:29:01,021 [ ] DEBUG - httpclient.wire.header - >> "[\r][\n]" </p> <p>2016-07-07 08:29:01,021 [ ] DEBUG - httpclient.wire.content - >> "" </p> <p>2016-07-07 08:29:01,721 [ ] DEBUG - httpclient.wire.header - &lt;&lt; "HTTP/1.1 404 Not Found[\r][\n]" </p> <p>2016-07-07 08:29:01,721 [ ] DEBUG - httpclient.wire.header - &lt;&lt; "HTTP/1.1 404 Not Found[\r][\n]" </p> <p>Hope this helps.</p>
2
SQL ERROR java.lang.ArrayIndexOutOfBoundsException: 0
<pre><code>private void jselectedhousecomboPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { String tmp = (String)jselectedhousecombo.getSelectedItem(); String sql = "SELECT H.HOUSE, H.TOTALROOMS, H.BEDSPERROOM, H.ROOMSOCCUPIED, H.ROOMSAVAILABLE, HM.HM_ID, HM.HM_NAME, HM.HM_DEPARTMENT, HM.HOUSE, HM.HM_PHONENUMBER, HM.HM_DATEIN, HM.HM_DATEOUT, HM.HM_RESIDENCE, CA.C_ID, CA.C_NAME, CA.HOUSE, CA.C_PHONENUMBER, CA.C_DATEIN, CA.C_DATEOUT, CA.C_RESIDENCE, HP.HP_REGNO,HP.HP_NAME, HP.HP_FORM, HP.HOUSE,HP.HP_ROOMNO,HP.HP_DATE, HP.HP_DATEOUT FROM HOUSES H JOIN Housemaster HM ON H.HOUSE = HM.HOUSE JOIN Caretaker CA ON H.HOUSE = CA.HOUSE JOIN Houseprefect HP ON H.HOUSE = HP.HOUSE"; try { pst=conn.prepareStatement(sql); pst.setString(1, tmp); rs=pst.executeQuery(); if(rs.next()) { String add=rs.getString("HOUSE"); jselectedhousename.setText(add); String add2=rs.getString("C_NAME"); jselectedhousecaretaker.setText(add2); String add3=rs.getString("HM_NAME"); jselectedhousemaster.setText(add3); String add4=rs.getString("HP_NAME"); jselectedhouseprefect.setText(add4); String add5=rs.getString("TOTALROOMS"); jselectedhousetr.setText(add5); String add6=rs.getString("BEDSPERROOM"); jselectedhousebpr.setText(add6); String add7=rs.getString("ROOMSOCCUPIED"); jselectedhousero.setText(add7); String add8=rs.getString("ROOMSAVAILABLE"); jselectedhousera.setText(add8); String add9=rs.getString("HM_ID"); jselectedhmid.setText(add9); String add10=rs.getString("HM_NAME"); jselectedhmname.setText(add10); String add11=rs.getString("HM_DEPARTMENT"); jselectedhmdept.setText(add11); String add12=rs.getString("HOUSE"); jselectedhmhouse.setText(add12); String add13=rs.getString("HM_PHONENUMBER"); jselectedhmphone.setText(add13); String add14=rs.getString("HM_DATEIN"); jselectedhmdatein.setText(add14); String add15=rs.getString("HM_DATEOUT"); jselectedhmdateout.setText(add15); String add16=rs.getString("HM_RESIDENCE"); jselectedhmresidence.setText(add16); String add17=rs.getString("HP_REGNO"); jselectedhpregno.setText(add17); String add18=rs.getString("HP_NAME"); jselectedhpname.setText(add18); String add19=rs.getString("HP_FORM"); jselectedhpform.setText(add19); String add20=rs.getString("HOUSE"); jselectedhphouse.setText(add20); String add21=rs.getString("HP_ROOMNO"); jselectedhproom.setText(add21); String add22=rs.getString("HP_DATEIN"); jselectedhpdatein.setText(add22); String add23=rs.getString("HP_DATEOUT"); jselectedhpdateout.setText(add23); String add24=rs.getString("C_ID"); jselectedcid.setText(add24); String add25=rs.getString("C_NAME"); jselectedcnames.setText(add25); String add26=rs.getString("HOUSE"); jselectedchouse.setText(add26); String add27=rs.getString("C_PHONENUMBER"); jselectedcphone.setText(add27); String add28=rs.getString("C_DATEIN"); jselectedcdatein.setText(add28); String add29=rs.getString("C_DATEOUT"); jselectedcdateout.setText(add29); String add30=rs.getString("C_RESIDENCE"); jselectedcresidence.setText(add30); } } catch (Exception e) { System.out.println(e); e.printStackTrace(); JOptionPane.showMessageDialog(null, e); } finally { try { rs.close(); pst.close(); } catch (Exception e) { } } // TODO add your handling code here: } </code></pre>
2
How to make open App v/s URL when sending a branch.io URL through onesignal generated notification
<p>On IOS - Notification opens browser v/s app.</p> <p>Using one-signal for notification. branch URL is set as additional data on the notification. Grabbing this back in OneSignalHandleNotificationBlock and direct your webview to it.</p> <p>Saw in the dev notes for Branch that one way to make this work is - </p> <p>You can use Branch links with push notifications. When creating a push notification, you should specify the Branch link in the userInfo dictionary. It should be an NSString, and the key in userInfo should be Branch. Example: @{ @"branch" : @"<a href="https://[branchsubdomain]/ALMc/e03OVEJLUq" rel="nofollow">https://[branchsubdomain]/ALMc/e03OVEJLUq</a>" }</p> <p>And then setting up didReceiveRemoteNotification - - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { [[Branch getInstance] handlePushNotification:userInfo];</p> <pre><code>// ... handle push notifications that do not include Branch links </code></pre> <p>}</p> <p>I have not been able to make this work. </p> <p>Anyone else faced something similar before - handing branch URL in one-signal notifications?</p> <p>For folks with experience in OneSignal - How to send this key:value pair in Apple Push Notification Payload as branch:"branch_link"?</p> <p>For folks with experience in Branch - How is branch expecting it in the Apple Push Notification Payload.</p>
2
Spotipy -- accessing tracks from a public playlist without authentication
<p>I want to search through public playlists and get the tracks. So far I have code which can get the names of the playlists but not the tracks:</p> <pre><code>import spotipy import sys sp = spotipy.Spotify() if len(sys.argv) &gt; 1: artist_name = ' '.join(sys.argv[1:]) results = sp.search(q=artist_name, limit=20, type='playlist') for i, t in enumerate(results['playlists']['items']): print(i,' ', t['name']) </code></pre> <p>This will print a list of the first 20 public playlists names given the search condition. What I want is to also print the tracks in each playlist! I thought this would be simple, but after searching it seems like the only way is to via authentication, which I do not want. These tracks are public, so why would I need to authenticate to list the tracks?! There are two reasons I think this. 1) if I add (in the loop):</p> <pre><code>print t['tracks'] </code></pre> <p>the request response says "This request requires authentication". Additionally, I found this example on the spotipy documentation which is exactly what I want, but only for authenticated users. <a href="https://github.com/plamere/spotipy/blob/dd021c4087981b583ef0f2b276cd43bbc6fd429f/examples/user_playlists_contents.py" rel="nofollow">https://github.com/plamere/spotipy/blob/dd021c4087981b583ef0f2b276cd43bbc6fd429f/examples/user_playlists_contents.py</a> So, is there any way to view the tracks without authenticating as the owner of that playlist? Opening the desktop Spotify app can quickly show anyone that public playlist tracks are completely searchable and viewable so it must be possible. I apologize if this is an extremely specific question -- but I'm not sure where else to ask seeing as this is my first time with this API or with an API like this at all. I have done quite a bit of research on this topic and now have resigned to asking for help.</p>
2
Cannot remove shaded background of carousel - CSS
<p>LINK TO WEBSITE TEST PAGE: </p> <p><a href="http://www.newventureactive.co.uk/test2.html" rel="nofollow noreferrer">WEBPAGE LINK</a></p> <p>I'm trying to have a carousel with no background. So the images and indicators are just displayed as is. </p> <p>Have tried this: </p> <pre><code>.carousel{ background:none; background-color: none; } </code></pre> <p>Which didn't make a difference, I also tried adding a placeholder as a background to see what it did: </p> <pre><code>.carousel{ background: url(http://placehold.it/620x420/); </code></pre> <p>}</p> <p>This added the placeholder background but behind the shading of the carousel. I've uploaded an image here: <a href="https://i.stack.imgur.com/V9eaj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V9eaj.jpg" alt="CAROUSEL SCREENSHOT"></a></p> <p>Hopefully someone knows what I've done wrong, thanks in advance.</p> <p>EDIT: Added HTML code for carousel: </p> <pre><code> &lt;!-- Image Gallery Start--&gt; &lt;br/&gt;&lt;br/&gt; &lt;div id="Carousel" class="carousel slide" data-ride="carousel" style="max-width: 400px; margin: 0 auto"&gt; &lt;!-- Indicators --&gt; &lt;ol class="carousel-indicators"&gt; &lt;li data-target="#suniceCarousel" data-slide-to="0" class="active"&gt;&lt;/li&gt; &lt;li data-target="#suniceCarousel" data-slide-to="1"&gt;&lt;/li&gt; &lt;li data-target="#suniceCarousel" data-slide-to="2"&gt;&lt;/li&gt; &lt;li data-target="#suniceCarousel" data-slide-to="3"&gt;&lt;/li&gt; &lt;/ol&gt; &lt;!-- Wrapper for slides --&gt; &lt;div class="carousel-inner" role="listbox"&gt; &lt;div class="item active"&gt; &lt;img class="img-responsive center-block" src="/images/sunice/sunice1.png" width="350" alt="Chania"&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img class="img-responsive center-block" src="/images/sunice/sunice2.png" width="350" alt="Chania"&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img class="img-responsive center-block" src="/images/sunice/sunice1.png" width="350" alt="Chania"&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img class="img-responsive center-block" src="/images/sunice/sunice2.png" width="350" alt="Chania"&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Left and right controls --&gt; &lt;a class="left carousel-control" href="#Carousel" role="button" data-slide="prev"&gt; &lt;span class="glyphicon glyphicon-chevron-left" aria-hidden="true"&gt;&lt;/span&gt; &lt;span class="sr-only"&gt;Previous&lt;/span&gt; &lt;/a&gt; &lt;a class="right carousel-control" href="#Carousel" role="button" data-slide="next"&gt; &lt;span class="glyphicon glyphicon-chevron-right" aria-hidden="true"&gt;&lt;/span&gt; &lt;span class="sr-only"&gt;Next&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/br&gt;&lt;/br&gt; &lt;!-- Image gallery end--&gt; </code></pre>
2
Any clue on how to protect my website's source code?
<p>So I have a website in html and I want to protect its source code from visitors.</p> <p>I was looking around for some time and everyone seem to agree that it was impossible to do, the only thing that could be done is to disable right click.</p> <p>And yet I found this website that is indeed protected. </p> <p><a href="http://tradesteamlatino.tk/" rel="nofollow">http://tradesteamlatino.tk/</a>,</p> <p>So, No matter where you go it will always display the same source code, I'm not sure if it is 100% secure but it will still protect the code from most users.</p> <p>How could this be done?</p>
2
How can I create instance variable based on OS version
<p>How can I define instance variable based on the iOS verison, for example <code>CNContactStore</code> is available since <code>iOS9.0</code> and <code>ABAddressBook</code> is deprecated in <code>9.0</code> but I want to create two variable depends upon iOS version. My Approach is</p> <pre><code>if #available(iOS 9.0, *) { var addressBookRef: ABAddressBook? = nil } else { var contactStore : CNContactStore? = nil } </code></pre> <p>If I do this inside a method body, works fine but I want it to be define globally and can be access throughout the class but giving me error if I do it like this</p> <pre><code>@available(iOS 9.0, *) var contactStore : CNContactStore? = nil </code></pre> <p>Need some suggestions. How do I achieve this. I've no idea if I release <code>@available(iOS 9.0, *)</code>, it will crash my app on iOS 8.x or below?</p>
2
Detecting the Asterisk Key on KeyDown Event
<p>Firstly I have seen the following answer <a href="https://stackoverflow.com/a/7731051/626442">https://stackoverflow.com/a/7731051/626442</a> and it is not quite sufficient for my needs. </p> <p>I have written an editor which has basic intellisense capabilities (see <a href="https://stackoverflow.com/questions/9556026/a-new-and-full-implementation-of-generic-intellisense">A New and Full Implementation of Generic Intellisense</a> for an insight). I have implemented some basic SQL Server completion using this editor, but I keep getting intellisense popping up when I type the <code>*</code> key. I want to prevent this. Currently I do the following:</p> <pre><code>private void TextArea_KeyDown(object sender, KeyEventArgs e) { if (!e.Control &amp;&amp; e.KeyCode == Keys.Space || e.Shift) return; IntellisenseEngine.DisplayCompletion(this, (char)e.KeyValue); } </code></pre> <p>I have recently redeveloped my control and I want to build on existing restrictions as to when and when not to show the insight window. A subset of what I want would be:</p> <pre><code>+------------------------------+-------------------+ ¦ ¦ Modifier ¦ Keys ¦ Show Completion ¦ ¦---+------------+-------------¦-------------------¦ ¦ 1 ¦ Shift ¦ None ¦ No ¦ ¦ 2 ¦ Shift ¦ * (see note)¦ No ¦ ¦ 3 ¦ None ¦ Space ¦ No ¦ ¦ 4 ¦ Any ¦ Arrow Keys ¦ No ¦ +------------------------------+-------------------+ </code></pre> <p>et al. Note, the "*" <code>e.KeyCode</code> is <code>D8</code>, this is obviously not keyboard invariant and dependent on locale, hence is not sufficient. </p> <p>Essentially I want my SQL intellisense to act like SQL Server Management Studio's (SQLMS), my questions are:</p> <ol> <li><p>How can I detect the asterisk char key being pressed independent of keyboard locale.</p></li> <li><p>What other key contions should I impose to make to suppress the pop-up of the intellisense window and to make it act like SQLMS?</p></li> </ol> <p>I have tried using </p> <pre><code>private void TextArea_KeyPress(object sender, KeyPressEventArgs e) { if ((Control.ModifierKeys &amp; Keys.Control) != Keys.Control &amp;&amp; &lt;Detect Space Bar&gt; || (Control.ModifierKeys &amp; Keys.Shift) == Keys.Shift &amp;&amp; e.KeyChar == '*') return; IntellisenseEngine.DisplayCompletion(this, (char)e.KeyValue); } </code></pre> <p>But then I have the problem of detecting the space bar.</p> <p>Thanks for your time.</p>
2
Call UWP AppService on winform/wpf client
<p>When i call AppService on UWP app, the AppServiceConnectionStatus returns Success. But, when i call AppService on winform or wpf client, the AppServiceConnectionStatus still return AppServiceUnavailable. UWP,Winform,WPF,the client code are the same:</p> <pre><code>private AppServiceConnection appService; private async void ConnectServer() { if (appService == null) { appService = new AppServiceConnection(); appService.AppServiceName = &quot;AserSecurityService&quot;; appService.PackageFamilyName = &quot;AserSecurityService_gfeg8w3smza92&quot;; var status = await this.appService.OpenAsync(); if (status != AppServiceConnectionStatus.Success) { appService = null; return; } } } </code></pre> <p>The service code below:</p> <pre><code>public sealed class AserSecurityComponentProviderTask : IBackgroundTask { private BackgroundTaskDeferral backgroundTaskDeferral; private AppServiceConnection appServiceconnection; public void Run(IBackgroundTaskInstance taskInstance) { this.backgroundTaskDeferral = taskInstance.GetDeferral(); taskInstance.Canceled += OnTaskCanceled; var details = taskInstance.TriggerDetails as AppServiceTriggerDetails; appServiceconnection = details.AppServiceConnection; appServiceconnection.RequestReceived += OnRequestReceived; } private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { var requestDeferral = args.GetDeferral(); try { var message = args.Request.Message; var result = new ValueSet(); if (message.ContainsKey(&quot;HardwareID&quot;)) { result.Add(&quot;HardwareID&quot;, GetHardwareID()); } await args.Request.SendResponseAsync(result); } catch (Exception ex) { var result = new ValueSet(); result.Add(&quot;exception&quot;, ex); await args.Request.SendResponseAsync(result); } finally { requestDeferral.Complete(); } } private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { if (this.backgroundTaskDeferral != null) { this.backgroundTaskDeferral.Complete(); } } private string GetHardwareID() { if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent(&quot;Windows.System.Profile.HardwareIdentification&quot;)) { var token = HardwareIdentification.GetPackageSpecificToken(null); var hardwareId = token.Id; var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId); byte[] bytes = new byte[hardwareId.Length]; dataReader.ReadBytes(bytes); return BitConverter.ToString(bytes).Replace(&quot;-&quot;, &quot;&quot;); } throw new Exception(&quot;NO API FOR DEVICE ID PRESENT!&quot;); } } </code></pre> <p>How can I solve this issue?</p> <p>or you can download my sample project code zip from <a href="http://pan.baidu.com/s/1slrcPrv" rel="nofollow noreferrer">here</a> or <a href="https://setup.aserweb.com/AppServiceSample.zip" rel="nofollow noreferrer">otherLink</a>.</p>
2
Bootstrap causes bullets to disappear from unordered lists
<p>I have the same code in a fiddle with bootstrap enabled and in a clean non-bootstrap fiddle.</p> <p>Why does one have list bullet points and the other does not?</p> <p>How would I make the bullets show on the unordered list for the Bootstrap fiddle?</p> <hr> <p>Here is the code:</p> <pre><code>&lt;ul&gt; &lt;li&gt;List Item&lt;/li&gt; &lt;li&gt;List Item2&lt;/li&gt; &lt;li&gt;List Item3&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Here are the two fiddles:</p> <p><a href="https://jsfiddle.net/dLsgtfzz/2/" rel="nofollow">Bootstrap</a></p> <p><a href="https://jsfiddle.net/kzum16fL/1/" rel="nofollow">Non-Bootstrap</a></p> <p>EDIT: The problem persists when I have an html file with bootstrap as such.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;!-- Bootstrap --&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;ul&gt;&lt;li&gt;List Element&lt;/li&gt;&lt;ul&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
2
invalid instruction suffix for `mov' (movw %ax, %ebx)
<p>When I try to compile the following program:</p> <pre><code>.globl _start .section .text _start: movw $-23, %ax movl $-1, %ebx # -1 = $0xffffffff movw %ax, %ebx movl $1, %eax movl $0, %ebx int $0x80 </code></pre> <p>I get this error message:</p> <pre><code>demo.s: Assembler messages: demo.s:7: Error: invalid instruction suffix for `mov' </code></pre> <p>So, the root of the proglem lies here:</p> <pre><code>movw %ax, %ebx </code></pre> <p>But the thing is that I don't think what I'm doing is totally wrong plus that's the example used in the book I'm currently reading: <a href="http://eu.wiley.com/WileyCDA/WileyTitle/productCd-0764579010.html" rel="nofollow">Professional Assembly Language by Richard Blum (2005)</a></p>
2
Finding second shortest path in a graph(With Backtracking)
<p>I found a problem in LightOJ where the problem was to find the second shortest path in a graph from node 1 to node n(There are n nodes in the graph marked from 1 to n). Now, the problem stated that I can backtrack to find a second shortest path. One of the sample cases is like this:</p> <ul> <li>Edge from node 1 to 2, cost 100. </li> <li>Edge from node 2 to 3, cost 300.</li> <li>Edge from node 1 to 3, cost 50.</li> </ul> <p>The answer for this test is 150, for this path 1->2->1->3. I am aware of Dijkstra algorithm. But I could not find anything on how to do this. I am sorry if this is and old topic but I when I googled it I could not find anything.</p> <p>Update: I read this question. <a href="https://stackoverflow.com/questions/4971850/which-algorithm-can-i-use-to-find-the-next-to-shortest-path-in-a-graph">Which algorithm can I use to find the next to shortest path in a graph?</a> My question is different from it because in this problem, I can use an edge twice. I am going from node 1 to 2 once, then coming back to 1. This using edge 1->2 twice. </p>
2
How to use Highcharts.Tooltip type in typescript
<p>I am following the example related with active the tooltip using the click event in Highchart from this url <a href="https://stackoverflow.com/questions/24204419/highcharts-show-tooltip-on-points-click-instead-mouseover">Highcharts - Show tooltip on points click instead mouseover</a>. The thing is that I am using typescript and I can' find a correct way to translate this line to typescript:</p> <pre><code> this.myTooltip = new Highcharts.Tooltip(this, this.options.tooltip); </code></pre> <p>The error what I am getting is: "Property Tooltip doesn' exist on type HighchartsStatic"</p> <p>I tried to add a new member to my controller like this:</p> <pre><code> public highchartTooltip : HighchartsTooltipOptions; </code></pre> <p>and after :</p> <pre><code>this.myTooltip = new self.highchartTooltip(this, this.options.tooltip); </code></pre> <p>But i am getting the error: "Cannot use 'new' with an expression whose type lacks a call or construct signature"... so i don't know how to create a object to initialize the tooltip according the js example.</p> <p>Also I can see the definition of tooltip in <a href="http://code.highcharts.com/highcharts.src.js" rel="nofollow noreferrer">http://code.highcharts.com/highcharts.src.js</a> </p> <pre><code> var Tooltip = Highcharts.Tooltip = function () { this.init.apply(this, arguments); }; Tooltip.prototype = {... </code></pre> <p>But I can't figure out how to find it in the Typescript definition file.</p> <p>The complete example in js is here: <a href="http://jsfiddle.net/2swEQ/2/" rel="nofollow noreferrer">http://jsfiddle.net/2swEQ/2/</a></p> <p>I have opened a ticket in github: <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/issues/9960" rel="nofollow noreferrer">https://github.com/DefinitelyTyped/DefinitelyTyped/issues/9960</a></p> <p>Any help? in some how there is a way to ignore this error? (thinking that object Highcharts.Tooltip exists when the app is runing)</p>
2
GreenDao query with distinct
<p>I`m new to GreenDao and want to load a list by stuffId.I need to use Distinct query to prevent duplicate! How can I use distinct in my query? below code does not work!!</p> <pre><code>@Override public ArrayList&lt;DbMaterial&gt; loadMaterialStuffList() { openReadableDb(); final List&lt;DbMaterial&gt; materials= mDaoSession.getDbMaterialDao().queryBuilder().distinct() .orderDesc(DbMaterialDao.Properties.StuffId).list(); mDaoSession.clear(); if (materials != null) { return new ArrayList&lt;&gt;(materials); } return null; } </code></pre>
2
Recycler View Scrolling messed up
<p>I am trying a heterogeneous Recycler view, following this tutorial. <a href="https://guides.codepath.com/android/Heterogenous-Layouts-inside-RecyclerView#overview" rel="nofollow">Heterogeneous Layouts </a> All is working fine expect for the part where i scroll the Recycler view, the layouts aren't displayed properly. I have 2 layouts, one has text and other has images, on scrolling I am left with alot of blank space in the text section,giving a feel to the viewer that there was some image previously here. I have checked links online but nothing solved the issue.Your help is needed and appreciated.<br> Here is my code</p> <p><strong>ComplexRecyclerViewAdapter</strong></p> <pre><code>public class ComplexRecyclerViewAdapter extends RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt; { private List&lt;Object&gt; items; private final int STATUS = 0, IMAGE_STATUS = 1; public ComplexRecyclerViewAdapter(List&lt;Object&gt; items) { this.items = items; } @Override public int getItemCount() { return this.items.size(); } @Override public int getItemViewType(int position) { if (items.get(position) instanceof ArrayFeedItem) { return STATUS; } else if (items.get(position) instanceof ArrayFeedItemWithImage) { return IMAGE_STATUS; } return -1; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { RecyclerView.ViewHolder viewHolder; LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); if (viewType == STATUS){ View v1 = inflater.inflate(R.layout.layout_viewholder1, viewGroup, false); viewHolder = new ViewHolder1(v1); } else if(viewType ==IMAGE_STATUS){ View v2 = inflater.inflate(R.layout.layout_viewholder2, viewGroup, false); viewHolder = new ViewHolder2(v2); } else viewHolder=null; return viewHolder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { if (viewHolder.getItemViewType() == STATUS ) { ViewHolder1 vh1 = (ViewHolder1) viewHolder; configureViewHolder1(vh1, position); vh1.setIsRecyclable(false); } else { ViewHolder2 vh2 = (ViewHolder2) viewHolder; configureViewHolder2(vh2, position); vh2.setIsRecyclable(false); } } private void configureViewHolder1(ViewHolder1 vh1, int position) { ArrayFeedItem item = (ArrayFeedItem) items.get(position); if (item != null) { vh1.getHolderImage().setImageResource(item.img); vh1.getHolderText().setText(item.txtname); vh1.getStatusMsg().setText(item.StatusMsg); vh1.getTimestamp().setText(item.Timestamp); vh1.getUrl().setText(item.URL); } } private void configureViewHolder2(ViewHolder2 vh2, int position) { ArrayFeedItemWithImage item = (ArrayFeedItemWithImage) items.get(position); if (item != null) { vh2.getHolderImage().setImageResource(item.img); vh2.getHolderText().setText(item.txtname); vh2.getStatusMsg().setText(item.StatusMsg); vh2.getTimestamp().setText(item.Timestamp); vh2.getUrl().setText(item.URL); vh2.getFeedImage().setImageResource(item.feedImage1); } } } </code></pre> <p>This is how I am binding the adapter to the recycle view.</p> <p><strong>Home Activity</strong></p> <pre><code>list=(RecyclerView) findViewById(R.id.list); adapter =new ComplexRecyclerViewAdapter(items); list.setNestedScrollingEnabled(false); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); list.setLayoutManager(mLayoutManager); list.setItemAnimator(new DefaultItemAnimator()); list.setAdapter(adapter); </code></pre> <p><strong>ViewHolder1</strong></p> <pre><code>public class ViewHolder1 extends RecyclerView.ViewHolder { private ImageView Image; private TextView Text,Timestamp,StatusMsg,Url; public ViewHolder1(View itemView) { super(itemView); Image=(ImageView) itemView.findViewById(R.id.img); Text=(TextView)itemView.findViewById(R.id.txt); Timestamp=(TextView)itemView.findViewById(R.id.timestamp); StatusMsg=(TextView)itemView.findViewById(R.id.txtStatusMsg); Url=(TextView)itemView.findViewById(R.id.txtUrl); } public ImageView getHolderImage() { return Image; } public void setHolderImage(ImageView image) { this.Image = image; } public TextView getHolderText() { return Text; } public void setHolderText(TextView text) { this.Text = text; } public TextView getTimestamp() { return Timestamp; } public void setTimestamp(TextView timestamp) { this.Timestamp = timestamp; } public TextView getStatusMsg() { return StatusMsg; } public void setStatusMsg(TextView statusmsg) { this.StatusMsg = statusmsg; } public TextView getUrl() { return Url; } public void setUrl(TextView url) { this.Url = url; } } </code></pre> <p><strong>layout_viewholder1</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/feed_bg" android:orientation="vertical" &gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_marginLeft="@dimen/feed_item_margin" android:layout_marginRight="@dimen/feed_item_margin" android:layout_marginTop="@dimen/feed_item_margin" android:background="@drawable/bg_parent_rounded_corner" android:orientation="vertical" android:paddingBottom="@dimen/feed_item_padding_top_bottom" android:paddingTop="@dimen/feed_item_padding_top_bottom" android:id="@+id/layout1" &gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:paddingLeft="@dimen/feed_item_padding_left_right" android:paddingRight="@dimen/feed_item_padding_left_right" &gt; &lt;ImageView android:id="@+id/img" android:layout_width="@dimen/feed_item_profile_pic" android:layout_height="@dimen/feed_item_profile_pic" android:scaleType="fitCenter" &gt; &lt;/ImageView&gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingLeft="@dimen/feed_item_profile_info_padd" &gt; &lt;TextView android:id="@+id/txt" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="@dimen/feed_item_profile_name" android:textStyle="bold" android:textColor="@color/black"/&gt; &lt;TextView android:id="@+id/timestamp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="@color/timestamp" android:textSize="@dimen/feed_item_timestamp" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;TextView android:id="@+id/txtStatusMsg" android:textColor="@color/black" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="5dp" android:paddingLeft="@dimen/feed_item_status_pad_left_right" android:paddingRight="@dimen/feed_item_status_pad_left_right" android:paddingTop="@dimen/feed_item_status_pad_top" /&gt; &lt;TextView android:id="@+id/txtUrl" android:textColor="@color/black" android:layout_width="fill_parent" android:layout_height="wrap_content" android:linksClickable="true" android:paddingBottom="10dp" android:paddingLeft="@dimen/feed_item_status_pad_left_right" android:paddingRight="@dimen/feed_item_status_pad_left_right" android:textColorLink="@color/link" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>Thanks in advance. </p>
2
non-blocking write in c
<p>I have read some materials about socket programming online. By default, <code>write()</code> is blocking. In some materials, <code>write()</code> only blocks when socket buffer is full. Some other materials say <code>write()</code> is blocked until all the data in the user buffer has been moved to the system buffer, which means <code>write()</code> will also block if there is not enough space for the data to place. I am wondering which statement is correct if <code>write()</code> is set to blocking.</p>
2
UIStackview horizontal alignment with 2 rows
<p>I've a horizontal stackview which has a stackview as a subview with 2 labels. Alignment &amp; Distribution are set to Fill in Xcode Attribute Inspector. I want to display 7 subview stacks inside the stack view with 4 in first row and 3 in second row using only one horizontal stackview. I have loaded first row. When I add 5th element, it is appearing in 1st row instead of 2nd row. Number of subviews changes dynamically. If there are 3 elements it should only display only one row. If more than 5, it should display in 2 rows.Below is the code.</p> <pre><code>if let viewInfos = TestViewController.viewInfos{ let dataNib = UINib(nibName: "InfoStackView", bundle: frameworkBundle) for viewInfo in viewInfos { let infoStackView = dataNib.instantiateWithOwner(nil, options: nil)[0] as! InfoStackView infoStackView.addInfoToStackView(viewInfo: viewInfo) self.InfoStackView.addArrangedSubview(infoStackView) } } Inside addInfoToStackView method, i add the label for each stackview </code></pre> <p>Above code adds stackview as subviews horizontally. I want to restrict 4 in first row and 3 in next row. Please help me how do this. </p>
2
Electron App: Turn off On-Screen Keyboard Windows 10 Tablet
<p>I've written an electron application and implemented my own input widgets to be used with my application - optimized for mobile touch input. Whether this is a good idea in general or not should be not part of this discussion.</p> <p>My problem now is that when i install my application on a Windows 10 Tablet the OS will open the on-screen keyboard whenever i focus an input-field.</p> <p>Of course the on-screen keyboard can be toggled off in windows itself - unfortunately it doesn't seem to work as expected... If i turn off the keyboard it will not show anymore anywhere - windows explorer, browser - nowhere. It works as intended. But the electron app STILL opens it even if i STOPPED the corresponding windows service.</p> <p>So my conclusion is that electron itself opens the keyboard and ignores whatever the system tells it about it. I didn't find any documentation or API to turn this feature off though.</p> <p>Does anyone have any idea how i can achieve my goal?</p> <p>Thank you in advance,</p> <p>Patrick</p>
2
AWS S3 GET request fallback to a different virtual folder
<p>Does anyone know if it is possible to set a rule or some kind of config to S3 server which will allow fallback to a different virtual folder if some resource is not found on given path?</p> <p>Here is an example:</p> <p>Url that is called is <code>https://bucket.s3.domain/virtual-folder/1/res.ext</code>. If <code>res.ext</code> can not be found in virtual folder <code>1</code> I would like it to redirect it to it's parent <code>https://bucket.s3.domain/virtual-folder/res.ext</code> Parent will contain default versions of resources. So the idea is if you can't find specific resource S3 should automatically return the default one.</p> <p>I have made some research but all I get is about website redirections. What I need here is a raw resources that devices will pull in a single request, and S3 will take care of everything. </p> <p>Is this stuff even possible?</p> <p>Thanks, Ante.</p>
2
Get every second post in WordPress loop
<p>I need to seperate loops in two colums and want to skip every second loop in each loop. At the end I need a view like this:</p> <p><strong>Loop 1</strong></p> <ul> <li>Post <strong>1</strong></li> <li>Post <strong>3</strong></li> <li>Post <strong>5</strong></li> </ul> <p><strong>Loop 2</strong></p> <ul> <li>Post <strong>2</strong></li> <li>Post <strong>4</strong></li> <li>Post <strong>6</strong></li> </ul> <p>Is that possible?</p> <p>My current loop:</p> <pre><code>&lt;?php $args = array ( 'nopaging' =&gt; true, 'posts_per_page' =&gt; '999', 'ignore_sticky_posts' =&gt; false, ); $query_row_1 = new WP_Query( $args ); if ( $query_row_1-&gt;have_posts() ) : ?&gt; &lt;?php while ( $query_row_1-&gt;have_posts() ) : $query_row_1-&gt;the_post(); ?&gt; &lt;?php the_title(); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php else : endif; wp_reset_postdata(); ?&gt; </code></pre>
2
Convert QStrings to other types
<p>I want to convert QStrings to different types. I would like to do this as generically and easy as possible without having to write an explicit method for each type.</p> <p>I thought of using a template function, something like this:</p> <pre><code>template&lt;typename T&gt; void getValueFromString(QString str, T&amp; returnVal) { returnVal = static_cast&lt;T&gt;(str); } </code></pre> <p>Obviously this doesn't work, but something like that I would like to have. </p> <p>Is there an easy way to do that?</p>
2
WPF StackPanel Size
<p>I have the following wpf Window. Why the StackPanel is not taking the size of the GroupBox ? How Can I force it to auto take the size of the GroupBox ?</p> <p>Thank you</p> <h2>XAML</h2> <pre><code> &lt;Window xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot; xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot; xmlns:local=&quot;clr-namespace:StyleTrigger&quot; xmlns:local2=&quot;clr-namespace:ComboBoxData&quot; xmlns:sys=&quot;clr-namespace:System;assembly=mscorlib&quot; xmlns:ig=&quot;http://schemas.infragistics.com/xaml&quot; x:Class=&quot;StyleTrigger.MainWindow&quot; mc:Ignorable=&quot;d&quot; Title=&quot;MainWindow&quot; Height=&quot;350&quot; Width=&quot;525&quot;&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width=&quot;50*&quot; /&gt; &lt;ColumnDefinition Width=&quot;50*&quot;/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height=&quot;1*&quot;/&gt; &lt;RowDefinition Height=&quot;1*&quot;/&gt; &lt;RowDefinition Height=&quot;1*&quot;/&gt; &lt;/Grid.RowDefinitions&gt; &lt;GroupBox x:Name=&quot;groupBox&quot; Header=&quot;GroupBox&quot; Grid.Row=&quot;1&quot; &gt; &lt;StackPanel HorizontalAlignment=&quot;Stretch&quot; VerticalAlignment=&quot;Stretch&quot;&gt; &lt;TextBox /&gt; &lt;TextBox /&gt; &lt;/StackPanel&gt; &lt;/GroupBox&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre>
2
Hbase byteArray to Long
<p>I have a row key which is being created like this </p> <pre><code>Put put = new Put(Bytes.toBytes(tweets.getContact_Unique_Id()+"^"+Bytes.toBytes(epoch))); </code></pre> <p>Where epoch is the long timestamp.</p> <p>Now when I scan I get a row as </p> <blockquote> <p>3857^[B@7c8f4424</p> </blockquote> <p>Now I wish to convert the part of rowkey ie to Long </p> <blockquote> <p>[B@7c8f4424</p> </blockquote> <p>How do I achieve this.</p> <p>EDIT -> If I use the put as </p> <blockquote> <p>Put put = new Put(Bytes.toBytes(tweets.getContact_Unique_Id() + "^" + epoch);</p> </blockquote> <p>Not all rows gets inserted , but when I use </p> <blockquote> <p>Put put = new Put(Bytes.toBytes(tweets.getContact_Unique_Id()+"^"+Bytes.toBytes(epoch)));</p> </blockquote> <p>All rows gets inserted , please note that all time values are different.</p> <p>Also note I have used "^" to seperate out the 1st and 2nd part of rowkey.</p> <p>Thanks</p>
2
Horizontal animation causes vertical scrollbar in css
<p>I am working on the website animation (a spinning cog and a text that infinitely moves left-right). Here is my body code</p> <pre><code>body { overflow:hidden; height:100%; margin:0; padding:0; font-family:Arial, Helvetica, sans-serif; //background attachments } </code></pre> <p>And here is a relevant animation code snippet from the same file</p> <pre><code>#cog { /* image on maintenance.html page */ display:block; margin:auto; margin-top:300px; animation:spin 5s ease infinite; } @keyframes spin { /* animation for image on maintenance.html page */ from { transform:rotate(-45deg); } 50% { transform:rotate(10deg); } 75% { transform:rotate(-10); } to { transform:rotate(-45deg); } } #maintenance { /* text image under cog graphic on maintenance.html page */ display:block; margin:auto; /* margin-top:30px; */ animation:maint 5s ease infinite; overflow: hidden; } @keyframes maint { /* animation for second image on maintenance.html page */ 50% { transform: translate(-200px, 0); } } </code></pre> <p>When the text reaches its final point to the right (or really close to it), it causes a vertical scrollbar to appear. And the closer the text gets to the right, the bigger the scrollbar becomes (the bar inside the scrollbar becomes smaller). And vice versa when text start moving from final right point to the left.</p> <p>I have already checked <a href="https://stackoverflow.com/questions/20973870/scrollbar-appears-through-css-animation-transition">SO post on the similar matter</a>, <a href="https://css-tricks.com/findingfixing-unintended-body-overflow/" rel="nofollow noreferrer">the article</a>, <a href="https://css-tricks.com/forums/topic/code-css3-flip-animation-gives-me-a-horizontal-scrollbar/" rel="nofollow noreferrer">and another article</a>. All of them are suggesting to do an overflow:hidden, but it did not work for me: I tried both body and the text animation itself.</p> <p>I also noticed that this scrollbar appears ONLY when the mouse is inside the animation container (not just idle mouse, but moving around).</p> <p>It occurs on both of my different-size monitors, and I am using Google Chrome to test it.</p> <h1>UPDATE</h1> <p>After trying suggested codepen and fiddle, it looks like a container with a navbar is at fault. I will play around with it and share the results.</p> <h1>UPDATE 2</h1> <p>Resolved my issue, see the answer.</p>
2
Moodle doesn't open files from one specific course
<p>the enterprise I work for owns a Moodle website with many courses. In all of them, we attach many files .doc or .pdf, so that users can download and read them. The problem is, in one of them - without apparent reason - users can't get the files. When clicking on a file, the website displays a message that goes more or less like this "You are already logged in as yourself. Exit and log as another user to see the file". Even if you do what the message is asking, nothing changes: you still get the same message and the files can't be downloaded or opened at all. <strong>And just in this specific course!</strong></p> <p><img src="https://i.stack.imgur.com/2wJ9J.png" alt="Message print"></p> <p>Note: I'm not trying to access the log in page while already logged, as some people in other forums suggested. I'm trying to <strong><em>OPEN/DOWNLOAD a file</em></strong>, just that! I have to be logged in order to see the links to the files, so there is no call for going to the login page again.</p>
2
EF Core custom results from stored procedure
<p>I'm using EF Core which I believe is also known as EF 7? Anyways, I have a stored procedure that returns custom results that will not identify with any specific table. How am I supposed to access those results and how should I call the sql command?</p> <p>Normally we have to use .FromSql but that is only available on entities, eg. _context.User.FromSql(). I don't have an entity for it.</p> <p>So I tried building a dbset/entity for the results, but again, there is no associated table, and there is also no "Key". How am I supposed to parse the data then of the custom results?</p>
2
How do you find percents of a variable in Python?
<p>I can't figure out how you find a percentage of a variable in Python. This is the example of the code:</p> <pre><code>money =546.97 week=0 for i in range(10): money=money+16 money=money+(5% money) print('you have',money,'dollars') week=week+4 print(week) i = i +1 </code></pre> <p>It always just adds 21 because it sees 5% and gives the equation (5% money) the value of 5.</p>
2
Proper way to move unique_ptr array into another
<p>I have an array contained in a std::unique_ptr and I want to move the contents into another array of the same type. Do I need to write a loop to move the elements one by one or can I use something like std::move?</p> <pre><code>const int length = 10; std::unique_ptr&lt;int[]&gt; data(new int[length]); //Initialize 'data' std::unique_ptr&lt;int[]&gt; newData(new int[length]); //Fill 'newData' with the contents of 'data' </code></pre> <p>EDIT: Also, what if the arrays are different sizes?</p>
2
Running Django app in a server
<p>I have created a simple hello world app in a server and would like to test it live. I'm using ssh to access the server, I have used the following commands to set it up: <code>django-admin startproject mysite</code>, and <code>python manage.py startapp site</code>. </p> <p>Changed urls.py in "wrong" folder to:</p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] </code></pre> <p>and changed urls.py in "mysite" folder to:</p> <pre><code>from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^wrong/', include('wrong.urls')), url(r'^admin/', admin.site.urls), ] </code></pre> <p>Now, when I test this in local server(my computer) through <code>python manage.py runserver</code> with "debug mode on", it works fine, but I'm clueless as to how this can be setup in a 'live' server?</p> <p>I've used the migrate command to migrate everything, and I expected the "hello world" message to be displayed in the index page of my domain, but it didn't.</p> <p>Can someone give me direction please, thanks in advance.</p>
2
How to change after postback URL in asp.net 4.5 web forms
<p>Here a button that does a postback</p> <pre><code> &lt;asp:LinkButton runat="server" ID="btnBestPrice" OnClick="btnSearchBestPrice_Click"&gt;Search Best Price&lt;/asp:LinkButton&gt; </code></pre> <p>Assume that this button is clicked on page</p> <pre><code>http://localhost:47207/Default?ClusterId=131 </code></pre> <p>Now after the postback is completed, the page is still</p> <pre><code>http://localhost:47207/Default?ClusterId=131 </code></pre> <p>However, after the postback, i want to make URL to be</p> <pre><code>http://localhost:47207/Default </code></pre> <p>Is that possible?</p> <p>If i make a redirect, the postback event would be loss. I still want to process the postback event perfectly fine. So if somehow i can set the postback url to be raw url of the page on the client side or?</p> <p>asp.net 4.5 web forms c#</p>
2
Unable to build qt module qtx11extras
<p>The system configuration is as below, OS - RHEL 6 QT - Qt5.5.0 Platform - X86_64</p> <p>I have already asked this question <a href="https://stackoverflow.com/questions/38011530/xinternatom-and-xgetselectionowner-was-not-declared-in-this-scope">here</a> and I realised the problem associated with that based on the answer to the question.</p> <p>The actual problem is <code>qx11info_x11.cpp: In static member function ‘static bool QX11Info::isCompositingManagerRunning()’: **qx11info_x11.cpp:386:108: **error: ‘XInternAtom’ was not declared in this scope** if (XGetSelectionOwner(QX11Info::display(), XInternAtom(QX11Info::display(), "_NET_WM_CM_S0", false)))** ^ **qx11info_x11.cpp:386:109: error: **‘XGetSelectionOwner’ was not declared in this scope** if (XGetSelectionOwner(QX11Info::display(), XInternAtom(QX11Info::display(), "_NET_WM_CM_S0", false)))**.</code></p> <p>The actual problem is with the <code>qt</code> module <code>qtx11extras</code>, which does not recognize the <code>XGetSelectionOwner</code> and <code>XInternAtom</code>. But my Linux box has the X11/Xlib.h installed. Even providing the Xlib.h in the included path during compilation did not help. So updated the file <code>qtx11extras/src/x11extras/qx11info_x11.cpp</code> to include <code>#include &lt;X11/Xlib.h&gt;</code>, it compiles successfully now. Do we see any issues with this approach.</p>
2
Password decryption with known salt and dictionary
<p>We are migrating a company we acquired a lot of kiosk hardware assets from that are in the field. Since the company was suffering, we are stuck with some issues in migrating the locations fingerprints, usernames and passwords without any implementation docs. Luckily, most of the passwords used are numeric 4-6 PIN or a common used word. I'm stuck with trying to figure out what format the password is hashed in and hopefully can decipher it from there using a dictionary for the majority of the passwords. I have the following format:</p> <pre><code>"password": "ce62f0002776890507c4050a3b76c064d3d24328aea52a08633b726d352532dc", "salt": "JUQLSPOYGFURMGSDRYWIWBIWP", </code></pre> <p>The password above is "<strong>password</strong>". Hopefully this helps in finding the format.</p>
2
CMake only accepting `find_package(Qt5Widgets REQUIRED)` in add_subdirectory, not in root project
<p><strong>Context</strong></p> <p>Using the below <code>CMakeLists.txt</code>, it build the <code>Qt</code> test project without issues ONLY when included to a parent project like:</p> <pre><code>RootProject +--CMakeLists.txt // Parent CMake +--TestQt +--testwidget.cpp +--testwidget.hpp // Empty class, just extends QWidget +--CMakeLists.txt // My Test Project CMake </code></pre> <p>Parent Project just contain:</p> <pre><code>add_subdirectory( "TestQt" ) </code></pre> <p>As soon as I try to build the "TestQt" project standalone, it just return an error like:</p> <blockquote> <p>CMake Error at CMakeLists.txt:16 (find_package): By not providing "FindQt5Widgets.cmake" in CMAKE_MODULE_PATH this project has asked CMake to find a package configuration file provided by "Qt5Widgets", but CMake did not find one.</p> <p>Could not find a package configuration file provided by "Qt5Widgets" with any of the following names:</p> <p>Qt5WidgetsConfig.cmake / qt5widgets-config.cmake</p> <p>Add the installation prefix of "Qt5Widgets" to CMAKE_PREFIX_PATH or set "Qt5Widgets_DIR" to a directory containing one of the above files. If "Qt5Widgets" provides a separate development package or SDK, be sure it has been installed.</p> </blockquote> <p><code>CMAKE_PREFIX_PATH</code> is empty in both cases.</p> <p>Currently using Debian with a slightly old CMAKE 3.0.2</p> <p><strong>Question</strong></p> <p>What is wrong/ missing?</p> <p><strong>CMakeLists.txt</strong></p> <pre><code>cmake_minimum_required(VERSION 3.0) set(CMAKE_AUTOMOC ON) set(CMAKE_INCLUDE_CURRENT_DIR ON) find_package(Qt5Widgets REQUIRED) include_directories(${Qt5Widgets_INCLUDE_DIRS}) add_definitions(${Qt5Widgets_DEFINITIONS}) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${Qt5Widgets_EXECUTABLE_COMPILE_FLAGS}") # Project name project ( "TestQt" ) add_executable( UnitTest_TestQt UnitTest.cpp testwidget.cpp) target_link_libraries(UnitTest_TestQt Qt5::Widgets) </code></pre>
2
Doctrine is converting string to hex value
<p>I am converting one database to another database through a script. </p> <p>While running the script I am getting the following error:</p> <pre><code>SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xBFbangl...' for column 'country' at row 1 </code></pre> <p>An exception is thrown where it shows that it tries to set country as "\xcf\xbb\xbf\x62\x61\x6e\x67\x6c\x61\x64\x65\x73\x68". </p> <p>When I var_dump the value, it just shows as "Bangladesh". </p> <p>Is there something I have to adjust in my php code?</p> <p>I have tried <a href="https://stackoverflow.com/questions/10957238/incorrect-string-value-when-trying-to-insert-utf-8-into-mysql-via-jdbc">this</a>, but phpmyadmin is throwing an #1064 error stating a syntax error in the query. </p> <p><strong>UPDATE</strong></p> <p>The scripts is a command in Symfony3:</p> <pre><code>&lt;?php namespace My\Bundle\Command; use My\AccommodationBundle\Entity\Visit; use My\NewAccommodationBundleV2\Entity\Visit as Visit2; use My\OtherBundle\Entity\Person; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class VisitConvertToNewFormatCommand extends ContainerAwareCommand { private $em; protected function configure() { $this -&gt;setName('accommodation:visit:convert') -&gt;setDescription("Converting old structure to new structure'") ; } protected function getTimeStamp() { $currentTime = new \DateTime('now'); return '['.$currentTime-&gt;format('Y-m-d H:i:s').'] '; } protected function execute(InputInterface $input, OutputInterface $output) { $output-&gt;writeln($this-&gt;getTimeStamp().$this-&gt;getDescription()); $this-&gt;em = $this-&gt;getContainer()-&gt;get('doctrine')-&gt;getManager(); $visits = $this-&gt;em-&gt;getRepository('MyOldAccommodationBundle:Visit')-&gt;findAll(); foreach ($visits as $visit) { $visit2 = new Visit2(); $visit2-&gt;setArrivalDate($visit-&gt;getArrivalDate()); $visit2-&gt;setArrivalStatus($visit-&gt;getArrivalStatus()); $visit2-&gt;setArrivalTime($visit-&gt;getArrivalTime()); $visit2-&gt;setBookingType($visit-&gt;getBookingType()); $visit2-&gt;setCountry($visit-&gt;getCountry()); // &lt;---- ... $this-&gt;em-&gt;persist($visit2); $user = $visit-&gt;getUser(); if ($user != null) { $person = new Person(); ... $person-&gt;setFirstName(trim(ucfirst(strtolower($user-&gt;getFirstName())))); $person-&gt;setLastName(trim(ucfirst(strtolower($user-&gt;getLastName())))); $person-&gt;setEmail(preg_replace('/\s+/', '', $user-&gt;getEmail())); ... $this-&gt;em-&gt;persist($person); } } } } </code></pre>
2
Why not default constructors in Java 8?
<p>I read <a href="https://stackoverflow.com/questions/22810921/is-there-a-way-to-add-a-default-constructor-to-an-interface">this</a> question. The answer says that even in Java 8 (where we can have default methods in interfaces), we cannot have <strong>default constructors</strong>. And it says that it makes no sense.</p> <p>Can someone explain why it doesn't make any sense or whatever the reason there is no support for default constructors in Java 8?</p>
2
Model undefined when passing Model from View to Controller using AJAX
<p>When I tried to used debugger; in ajax to check if I'm able to serialize the form it say it is "undefined". I don't encounter an error but The value i input in the view does not pass to the controller. This is my reference <a href="https://stick2basic.wordpress.com/2013/04/14/how-to-pass-model-from-view-to-controller-using-jquery/" rel="nofollow">https://stick2basic.wordpress.com/2013/04/14/how-to-pass-model-from-view-to-controller-using-jquery/</a></p> <p><strong>VIEW</strong></p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function () { $('#btnsubmit').click(function (e) { e.preventDefault(); if ($("#OrderForm").valid()) { //if you use validation $.ajax({ url: $("#OrderForm").attr('action'), type: $("#OrderForm").attr('method'), data: $("#OrderForm").serialize(), success: function (data) { alert("success"); } }); } }); }); &lt;/script&gt; @using (Html.BeginForm("_Order", "Account", FormMethod.Post, new { id = "OrderForm" })) { &lt;div class="form-group"&gt; &lt;div class="col-md-3"&gt; @Html.LabelFor(model =&gt; model.MerchantEmail, htmlAttributes: new { @class = "control-label col-md-2" }) &lt;/div&gt; &lt;div class="col-md-9"&gt; @Html.TextBoxFor(model =&gt; model.MerchantEmail, new { @Value = "[email protected]",@class = "form-control" }) @Html.ValidationMessageFor(model =&gt; model.MerchantEmail, "", new { @class = "text-danger" }) &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;div class="col-md-offset-2 col-md-10"&gt; &lt;input type="button" value="Create" id="btnsubmit" class="btn btn-primary" /&gt; &lt;/div&gt; &lt;/div&gt; } </code></pre> <p><strong>Controller</strong></p> <pre><code>[AllowAnonymous] [HttpPost] public ActionResult _Order(OrderModel model) { List&lt;OrderModel&gt; orderlist = new List&lt;OrderModel&gt;(); if (Session["OrderList"] != null) { orderlist = Session["OrderList"] as List&lt;OrderModel&gt;; orderlist.Add(model); } Session["OrderList"] = orderlist; return PartialView(); } </code></pre> <p><strong>MODEL</strong></p> <pre><code>public class OrderModel { [DataType(DataType.EmailAddress)] public string Email { get; set; } [StringLength(35)] public string FirstName { get; set; } [StringLength(35)] public string MiddleName { get; set; } [StringLength(35)] public string LastName { get; set; } [StringLength(255)] public string Address { get; set; } [StringLength(40)] public string Province { get; set; } [StringLength(40)] public string Town { get; set; } [StringLength(13)] public string MobileNo { get; set; } [Required(ErrorMessage = "Please fill up Merchant Email.")] [DataType(DataType.EmailAddress)] public string MerchantEmail { get; set; } [Required(ErrorMessage = "Please enter the exact amount.")] [DataType(DataType.Currency)] public float OrderAmount { get; set; } public string OrderSkuCode { get; set; } [Required(ErrorMessage = "Please fill up order details.")] [StringLength(5000)] public string OrderDetails { get; set; } } </code></pre>
2
HTML: How do i center align an image inside an <li> tag
<p>I want to center an image inside a tag how do i do it? the image is placed on the extreme left on the screen but i want it to be in the center of the screen without sticking to the left. here is my html:</p> <pre><code>&lt;div class="sequence-slider"&gt; &lt;div id="sequence"&gt;&lt;i class="sequence-prev icon-angle-left"&gt;&lt;/i&gt; &lt;i class="sequence-next icon-angle-right"&gt;&lt;/i&gt; &lt;ul class="sequence-canvas"&gt; &lt;!-- Sequencejs Slider Single Item --&gt; &lt;li&gt; &lt;img class="main-image" src="photo/fac2.jpg" alt="Image" /&gt; &lt;/li&gt; &lt;!-- Sequencejs Slider Single Item --&gt; &lt;li&gt; &lt;img class="main-image" src="photo/fac1.jpg" alt="Image" /&gt; &lt;/li&gt; &lt;!THIS IMAGE STICK TO THE LEFT BUT I WANT IT IN THE CENTER&gt; &lt;li&gt; &lt;img class="main-image" src="photo/slide3.png" alt="Image" style ="width: auto; height : auto; " /&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p><a href="https://i.stack.imgur.com/21f2A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/21f2A.png" alt="enter image description here"></a></p>
2
What is the order of execution of Mason blocks in a component
<p>What will be the sequence of execution if these blocks are present in a Mason component?</p> <ul> <li><code>%args</code></li> <li><code>%init</code></li> <li><code>%once</code></li> <li><code>%shared</code></li> <li><code>%attr</code></li> <li><code>%flags</code></li> </ul>
2
Python list find elements with close value
<p><em>First off, this is not a duplicate post; my question is different than the ones I searched on this site, but please feel free to link if you find an already answered question</em></p> <hr> <p><strong>Description:</strong></p> <p>If you think how your own mind finds out 10 and 2.10 to be first element which is not close, in A and B below, that is what I am trying to do programmatically. A hard coded threshold value is not the best option. Of-course, we need a threshold here, but the function should find the threshold based on values provided, so in the case of A, threshold might be around 1.1, and 0.01 for B. How? Well, "it makes sense" right? We looked at the values and figured out. That is what I meant, "dynamic threshold" per se, if your answer includes using threshold.</p> <pre><code>A = [1.1, 1.02, 2.3, 10, 10.01, 10.1, 12, 16, 18, 18] B = [1.01, 1.02, 1.001, 1.03, 2.10, 2.94, 3.01, 8.99] </code></pre> <hr> <p><strong>Python Problem:</strong></p> <p>I have 2D list in Python which looks like below, now if want to narrow down the items which are closer, to each other starting only from top to bottom ( the list is already sorted as you can notice ), we can easily find out that first four are quite closer to each other than 4th and 5th are.</p> <pre><code>subSetScore = [ ['F', 'H', 0.12346022214809049], ['C', 'E', 0.24674283702138702], ['C', 'G', 0.24675055907681284], ['E', 'G', 0.3467125665641178], ['B', 'D', 0.4720531092083966], ['A', 'H', 0.9157739970594413], ['A', 'C', 0.9173801845880128], ['A', 'G', 0.9174496830868454], ['A', 'B', 0.918924595673178], ['A', 'F', 0.9403919097569715], ['A', 'E', 0.9419672090638398], ['A', 'D', 0.9436390340635308], ['B', 'H', 1.3237456293166292], ['D', 'H', 1.3237456293166292], ['D', 'F', 1.3238460160371646], ['B', 'C', 1.3253518168452008], ['D', 'E', 1.325421315344033], ['D', 'G', 1.325421315344033], ['B', 'F', 1.349344243053239], ['B', 'E', 1.350919542360107], ['B', 'G', 1.350919542360107], ['C', 'H', 1.7160260449485403], ['E', 'H', 1.7238716532611786], ['G', 'H', 1.7238716532611786], ['E', 'F', 1.7239720399817142], ['C', 'F', 1.7416246586851503], ['C', 'D', 1.769389308968704], ['F', 'G', 2.1501908892101267] ] </code></pre> <p>Result:</p> <pre><code>closest = [ ['F', 'H', 0.12346022214809049], ['C', 'E', 0.24674283702138702], ['C', 'G', 0.24675055907681284], ['E', 'G', 0.3467125665641178], ['B', 'D', 0.4720531092083966] ] </code></pre> <p>As opposite to other questions I have observed here, where the 1D or 2D list is given and an arbitrary value let’s say 0.9536795380033108, then the function has to find that 0.9436390340635308 is the closest from the list, and the mostly the solutions use absolute difference to calculate it, but it does not seem to be applicable here.</p> <p>One approach which seem to be partially reliable was to calculate cumulative difference, as following. </p> <pre><code>consecutiveDifferences = [] for index, item in enumerate(subSetScore): if index == 0: continue consecutiveDifferences.append([index, subSetScore[index][2] - subSetScore[index - 1][2]]) </code></pre> <p>This gives me following:</p> <pre><code>consecutiveDifferences = [ [1, 0.12328261487329653], [2, 7.722055425818386e-06], [3, 0.09996200748730497], [4, 0.1253405426442788], [5, 0.4437208878510447], [6, 0.0016061875285715566], [7, 6.949849883253201e-05], [8, 0.0014749125863325885], [9, 0.021467314083793543], [10, 0.001575299306868283], [11, 0.001671824999690985], [12, 0.3801065952530984], [13, 0.0], [14, 0.00010038672053536146], [15, 0.001505800808036195], [16, 6.949849883230996e-05], [17, 0.0], [18, 0.0239229277092059], [19, 0.001575299306868061], [20, 0.0], [21, 0.36510650258843325], [22, 0.007845608312638364], [23, 0.0], [24, 0.00010038672053558351], [25, 0.01765261870343604], [26, 0.027764650283553793], [27, 0.38080158024142263] ] </code></pre> <p>And now, the index of difference more than the difference on 0th index is my cutoff index as following:</p> <pre><code>cutoff = -1 for index, item in enumerate(consecutiveDifferences): if index == 0: continue if consecutiveDifferences[index][1] &gt; consecutiveDifferences[0][1]: cutoff = index break cutoff = cutoff+1 closest = subSetScore[:cutoff+1] </code></pre> <p>Which would leave my list (closest) as following:</p> <pre><code>consecutiveDifferences = [ ['F', 'H', 0.12346022214809049], ['C', 'E', 0.24674283702138702], ['C', 'G', 0.24675055907681284], ['E', 'G', 0.3467125665641178], ['B', 'D', 0.4720531092083966] ] </code></pre> <p>But clearly this logic is buggy and it won’t work for following scenario:</p> <pre><code>subSetScore = [ ['A', 'C', 0.143827143333704], ['A', 'G', 0.1438310043614169], ['D', 'F', 0.15684652878164498], ['B', 'H', 0.1568851390587741], ['A', 'H', 0.44111469414482873], ['A', 'F', 0.44121508086536443], ['A', 'E', 0.4441224347331875], ['A', 'B', 0.4465394380814708], ['A', 'D', 0.4465394380814708], ['D', 'H', 0.7595452327118624], ['B', 'F', 0.7596456194323981], ['B', 'E', 0.7625529733002212], ['D', 'E', 0.7625529733002212], ['B', 'C', 0.7635645625610041], ['B', 'G', 0.763661088253827], ['D', 'G', 0.763661088253827], ['B', 'D', 0.7649699766485044], ['C', 'G', 0.7891593152699012], ['G', 'H', 1.0785858136575361], ['C', 'H', 1.0909217972002916], ['C', 'F', 1.0910221839208274], ['C', 'E', 1.0939295377886504], ['C', 'D', 1.0963465411369335], ['E', 'H', 1.3717343427604187], ['E', 'F', 1.3718347294809543], ['E', 'G', 1.3758501983023834], ['F', 'H', 2.0468234552800326], ['F', 'G', 2.050939310821997] ] </code></pre> <p>As the cutoff would be 2, here is what closest would look like:</p> <pre><code>closest = [ ['A', 'C', 0.143827143333704], ['A', 'G', 0.1438310043614169], ['D', 'F', 0.15684652878164498] ] </code></pre> <p>But here is the expected result:</p> <pre><code>closest = [ ['A', 'C', 0.143827143333704], ['A', 'G', 0.1438310043614169], ['D', 'F', 0.15684652878164498], ['B', 'H', 0.1568851390587741] ] </code></pre> <p>More datasets:</p> <pre><code>subSetScore1 = [ ['A', 'C', 0.22406316023573888], ['A', 'G', 0.22407088229116476], ['D', 'F', 0.30378179942424355], ['B', 'H', 0.3127393837182006], ['A', 'F', 0.4947366470217576], ['A', 'H', 0.49582931786451195], ['A', 'E', 0.5249800770970015], ['A', 'B', 0.6132933639744492], ['A', 'D', 0.6164207964219085], ['D', 'H', 0.8856811470650012], ['B', 'F', 0.8870402288199465], ['D', 'E', 0.916716087821392], ['B', 'E', 0.929515394689697], ['B', 'C', 1.0224773589334915], ['D', 'G', 1.0252457158036496], ['B', 'G', 1.0815974152736079], ['B', 'D', 1.116948985013035], ['G', 'H', 1.1663971669323054], ['C', 'F', 1.1671269011700458], ['C', 'G', 1.202339473911808], ['C', 'H', 1.28446739439317], ['C', 'E', 1.4222597514115916], ['E', 'F', 1.537160075120155], ['E', 'H', 1.5428705351075527], ['C', 'D', 1.6198555666753154], ['E', 'G', 1.964274682777963], ['F', 'H', 2.3095586690883034], ['F', 'G', 2.6867154391687365] ] subSetScore2 = [ ['A', 'H', 0.22812496138972285], ['A', 'C', 0.23015200093900193], ['A', 'B', 0.2321751794605681], ['A', 'G', 0.23302074452969593], ['A', 'D', 0.23360762074205865], ['A', 'F', 0.24534900601702558], ['A', 'E', 0.24730268603975933], ['B', 'F', 0.24968107911091342], ['B', 'E', 0.2516347591336472], ['B', 'H', 0.2535228016852614], ['B', 'C', 0.25554984123454044], ['C', 'F', 0.2766387746024686], ['G', 'H', 0.2767739105724205], ['D', 'F', 0.2855654706747223], ['D', 'E', 0.28751915069745604], ['D', 'G', 0.30469686299220383], ['D', 'H', 0.30884360675587186], ['E', 'F', 0.31103280946909323], ['E', 'H', 0.33070474566638247], ['B', 'G', 0.7301435066780336], ['B', 'D', 0.7473019138342167], ['C', 'E', 0.749630113545103], ['C', 'H', 0.7515104340412913], ['F', 'H', 0.8092791306818884], ['E', 'G', 0.8506307374871814], ['C', 'G', 1.2281311390340637], ['C', 'D', 1.2454208211324858], ['F', 'G', 1.3292051225026873] ] subSetScore3 = [ ['A', 'F', 0.06947533266614773], ['B', 'F', 0.06947533266614773], ['C', 'F', 0.06947533266614773], ['D', 'F', 0.06947533266614773], ['E', 'F', 0.06947533266614773], ['A', 'H', 0.07006993093393628], ['B', 'H', 0.07006993093393628], ['D', 'H', 0.07006993093393628], ['E', 'H', 0.07006993093393628], ['G', 'H', 0.07006993093393628], ['A', 'E', 0.09015499709650715], ['B', 'E', 0.09015499709650715], ['D', 'E', 0.09015499709650715], ['A', 'C', 0.10039444259115113], ['A', 'G', 0.10039444259115113], ['B', 'C', 0.10039444259115113], ['D', 'G', 0.10039444259115113], ['A', 'D', 0.1104369756724366], ['A', 'B', 0.11063388808579513], ['B', 'G', 2.6511978452376543], ['B', 'D', 2.6612403783189396], ['C', 'H', 2.670889086573508], ['C', 'E', 2.690974152736078], ['C', 'G', 5.252017000877225], ['E', 'G', 5.252017000877225], ['C', 'D', 5.262059533958511], ['F', 'H', 5.322704696245228], ['F', 'G', 10.504651766188518] ] </code></pre> <p><strong>How should I fix it, without using any library, except NumPy and SciPy?</strong></p> <p>Please note: I am on Python 2.7, and any library which comes as a part of Python (e.g. itertools, operator, math etc.)could be used.</p> <p>Update: I can use SciPy, and not sure what would be effect of no of clusters, so I think 2 might suffice, but I am not an expert on cluster by any means, please feel free to advice, I appreciate it!</p>
2
Concatenation of unicode and byte strings
<p>From what I understand, when concatenating a string and Unicode string, Python will automatically decode the string based on the default encoding and convert to Unicode before concatenating.</p> <p>I'm assuming something like this if default is <code>'ascii'</code> (please correct if mistaken):</p> <p>string -> ASCII hexadecimal bytes -> Unicode hexadecimal bytes -> Unicode string</p> <p>Wouldn't it be easier and raise less <code>UnicodeDetectionError</code> if, for example, <code>u'a' + 'Ӹ'</code> is converted to <code>u'a' + u'Ӹ'</code> directly before concatenating? Why does the string need to be decoded first? Why does it matter if the string contains non-ASCII characters if it will be converted to Unicode anyway? </p>
2
Multiple "where clauses" in endpoint query string parameters
<p>Can I include multiple "where" clauses (or an AND operator) in an endpoint query string? I'd like to do something like this:</p> <pre><code>http://localhost:5000/regions?where=name=="El Salvador"&amp;where=lang=="es" </code></pre> <p>I've tried few different syntaxes, but I can't get it to work.</p> <p>Is this possible? I know I can do it using MongoDB syntax, but I would like to use Python syntax.</p> <p>Note: I'm not trying to concatenate an list of parameteres using python, I'm trying to use <a href="http://python-eve.org/features.html#filtering" rel="nofollow">Eve's filtering feature</a> using native python syntax.</p>
2
How to put a passing parameter into <p:confirm message="">?
<p>This is what I've got:</p> <pre><code> &lt;p:growl id="message" showDetail="true" /&gt; &lt;p:commandButton value="delete user" actionListener="#{bean.deleteUser(user)}" update="@form"&gt; &lt;p:confirm header="Confirm" message="Are you sure to delete #{user.username}?" icon="ui-icon-alert" /&gt; &lt;/p:commandButton&gt; &lt;p:confirmDialog global="true" showEffect="fade" hideEffect="fade"&gt; &lt;p:commandButton value="yes" type="button" styleClass="ui-confirmdialog-yes" icon="ui-icon-check" /&gt; &lt;p:commandButton value="No" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close" /&gt; &lt;/p:confirmDialog&gt; </code></pre> <p>The variable <code>#{user.username}</code> won't be shown at all. what am I doing wrong?</p>
2
Stream live video via iOS to facebook
<p>Is it possible to stream a live video on Facebook from iOS app ? I've searched the iOS SDK but didn't found anything related. After searching further I've found that I can POST cURL </p> <pre><code>curl -k -X POST https://graph.facebook.com/$your_userid_or_pageid/live_videos \ -F "access_token=$your_user_or_page_token" \ -F "published=true" </code></pre> <p>and a process should be followed after this. Dose this mean that I need a middle server between client App and Facebook to get the stream and stream it to Facebook ? </p>
2
Some Excel Files not moving from Shared Path to SQL Server
<p>We have an application where the data in Excel file (present in shared path) moves to Database. In case of any error, the files moves to error folder by writing the error in a log file.It uses a windows service for the operation.</p> <p>Sometimes the file doesn't have any error still moves to error folder by writing log <code>External table is not in the expected format.</code> But the same file uploading again for once or multiple times, its moving to Database without any errors. </p> <p>The windows service, DB and shared path are present in XP Server. Application was running fine all these years. But in the recent days, above mentioned problem is occurring for almost every file.</p> <p>We have installed Microsoft 2003, 2007,2012 office components and access engines too. But still the issue still persists.</p> <p>I am mentioning the Windows service code below. Pls help. Thanks in advance.</p> <pre><code>using System.IO; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Data.SqlClient; using System.Data.OleDb; using System.Data.Common; namespace Impexp_Service { public partial class Service1 : ServiceBase { System.Timers.Timer T1 = new System.Timers.Timer(); public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { ///start /// { SqlConnection strconnection = new SqlConnection(); strconnection.ConnectionString = @"Data Source=XXXXXX;Initial Catalog=XXXX;User ID=XX;Password=XXXXXX;"; strconnection.Open(); // To get the all files placed at the shared path DirectoryInfo directory = new DirectoryInfo(@"D:\Impexp\Data\"); FileInfo[] files = directory.GetFiles("*.xlsx"); foreach (var f in files) { string path = f.FullName; // TO establish connection to the excel sheet string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";"; //Create Connection to Excel work book OleDbConnection excelConnection = new OleDbConnection(excelConnectionString); excelConnection.Open(); //Create OleDbCommand to fetch data from Excel OleDbCommand cmd = new OleDbCommand("Select * from [Report$]", excelConnection); DbDataReader dr = cmd.ExecuteReader(); // OleDbDataReader dReader; // dReader = cmd.ExecuteReader(); SqlBulkCopy sqlBulk = new SqlBulkCopy(strconnection); //Give your Destination table name sqlBulk.DestinationTableName = "imp_master_test"; sqlBulk.WriteToServer(dr); excelConnection.Close(); File.Delete(path); // To move error files to the error folder /// end T1.Interval = 20000; T1.Enabled = true; T1.Start(); T1.Elapsed += new System.Timers.ElapsedEventHandler(T1_Elapsed); } } } void T1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { T1.Enabled = false; try { SqlConnection strconnection = new SqlConnection(); strconnection.ConnectionString = @"Data Source=10.91.XXXXXX;Initial Catalog=XXXXX;User ID=XXXXX;Password=XXXXX;"; strconnection.Open(); // To get the all files placed at the shared path DirectoryInfo directory = new DirectoryInfo(@"D:\Impexp\Data\"); FileInfo[] files = directory.GetFiles("*.xlsx"); foreach (var f in files) { string path = f.FullName; // TO establish connection to the excel sheet string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";"; //Create Connection to Excel work book OleDbConnection excelConnection = new OleDbConnection(excelConnectionString); try { excelConnection.Open(); //Create OleDbCommand to fetch data from Excel OleDbCommand cmd = new OleDbCommand("Select * from [Report$]", excelConnection); DbDataReader dr = cmd.ExecuteReader(); // OleDbDataReader dReader; // dReader = cmd.ExecuteReader(); SqlBulkCopy sqlBulk = new SqlBulkCopy(strconnection); //Give your Destination table name sqlBulk.DestinationTableName = "imp_master_prod"; sqlBulk.WriteToServer(dr); excelConnection.Close(); File.Delete(path); } // To move error files to the error folder catch (Exception exp) { excelConnection.Close(); File.Move(path, Path.Combine(@"D:\Impexp\error\", f.Name)); string path1 = @"D:\Impexp\error\error.txt"; if (File.Exists(path1)) { // Create a file to write to. using (StreamWriter sw = File.AppendText(path1)) { sw.WriteLine("File : " + path + " : " + exp.Message); sw.Flush(); } } T1.Enabled = true; T1.Start(); } } strconnection.Close(); // End of TRY 1 } catch (UnauthorizedAccessException UAEx) { string path1 = @"D:\Impexp\error\error.txt"; if (File.Exists(path1)) { // Create a file to write to. using (StreamWriter sw = File.AppendText(path1)) { sw.WriteLine(UAEx.Message); sw.Flush(); } } T1.Enabled = true; T1.Start(); } catch (PathTooLongException PathEx) { string path1 = @"D:\Impexp\error\error.txt"; if (File.Exists(path1)) { // Create a file to write to. using (StreamWriter sw = File.AppendText(path1)) { sw.WriteLine(PathEx.Message); sw.Flush(); } } T1.Enabled = true; T1.Start(); } T1.Enabled = true; T1.Start(); } protected override void OnStop() { } } } </code></pre>
2
Convert Unicode file to ANSI using Bat file
<p>I need to convert a unicode text file (19,000K) to an ANSI text file for use with Essbase. </p> <p>I currently have this written to convert the file but only the first 7800 lines are copying. </p> <p><strong>This is what I have in my .bat file</strong></p> <p>cmd /a /c TYPE PVTBHFM_20160708.dat > PVTBHFM_ANSI.dat</p> <p>What am I missing to fully convert this file? </p> <p>Is there a way to save the file in a different location? </p>
2
How to halt execution in Vuejs until get request is finished
<p>I have this code requesting data from an api endpoint:</p> <pre><code>fetchStudentMeta: function(){ var vm = this; this.$http.get('/api/1.0/students/metadata/ '+ this.selectedStudent.id) .then(function (response){ this.$set('meta', response.data); console.log(vm.meta); //line1 }); console.log(this.meta); //line2 }, </code></pre> <p>In my console and execution, line 2 is processed before line 1. Any way to halt execution until my variable is set from the get request data?</p>
2
How to restore database from a copied folder in mongodb?
<p>I have created a database called RateDifferenceDB in mongodb before some time.</p> <p>Then I copied the folder called RateDifferenceDB from the location where it was created.</p> <p>Then I format my computer, so all my data is gone.</p> <p>Then I installed a fresh copy of windows and then I installed mongodb.</p> <p>Now I want to restore that database called RateDifferenceDB. Is that possible?</p> <p><strong>Wait before negative marking this question:</strong></p> <p>I know there are commands called <code>mongodump</code> and <code>mongorestore</code>. But at the time before fomating windows, I didn't knew that.</p> <p><strong>update:</strong></p> <pre><code>D:\Program Files\mongodb\bin&gt;mongod --dbpath ${J:\Setup\Mongodb\Backup}/RateDiff erenceDB 2016-07-19T02:35:37.146-0700 I CONTROL [initandlisten] MongoDB starting : pid=5 012 port=27017 dbpath=${J:\Setup\Mongodb\Backup}/RateDifferenceDB 64-bit host=Vi shal-PC 2016-07-19T02:35:37.146-0700 I CONTROL [initandlisten] targetMinOS: Windows 7/W indows Server 2008 R2 2016-07-19T02:35:37.146-0700 I CONTROL [initandlisten] db version v3.2.7 2016-07-19T02:35:37.147-0700 I CONTROL [initandlisten] git version: 4249c1d2b59 99ebbf1fdf3bc0e0e3b3ff5c0aaf2 2016-07-19T02:35:37.147-0700 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.1p-fips 9 Jul 2015 2016-07-19T02:35:37.147-0700 I CONTROL [initandlisten] allocator: tcmalloc 2016-07-19T02:35:37.147-0700 I CONTROL [initandlisten] modules: none 2016-07-19T02:35:37.147-0700 I CONTROL [initandlisten] build environment: 2016-07-19T02:35:37.148-0700 I CONTROL [initandlisten] distmod: 2008plus-ss l 2016-07-19T02:35:37.148-0700 I CONTROL [initandlisten] distarch: x86_64 2016-07-19T02:35:37.149-0700 I CONTROL [initandlisten] target_arch: x86_64 2016-07-19T02:35:37.149-0700 I CONTROL [initandlisten] options: { storage: { db Path: "${J:\Setup\Mongodb\Backup}/RateDifferenceDB" } } 2016-07-19T02:35:37.150-0700 E NETWORK [initandlisten] listen(): bind() failed errno:10048 Only one usage of each socket address (protocol/network address/port ) is normally permitted. for socket: 0.0.0.0:27017 2016-07-19T02:35:37.151-0700 E STORAGE [initandlisten] Failed to set up sockets during startup. 2016-07-19T02:35:37.151-0700 I CONTROL [initandlisten] dbexit: rc: 48 </code></pre> <p><strong>Update2:</strong></p> <p>I get a not found exception. Look below for more details:</p> <pre><code>D:\Program Files\mongodb\bin&gt;mongod --dbpath ${J:\Setup\Mongodb\Backup}/RateDiff erenceDB 2016-07-19T04:37:45.927-0700 I CONTROL [initandlisten] MongoDB starting : pid=6 560 port=27017 dbpath=${J:\Setup\Mongodb\Backup}/RateDifferenceDB 64-bit host=Vi shal-PC 2016-07-19T04:37:45.927-0700 I CONTROL [initandlisten] targetMinOS: Windows 7/W indows Server 2008 R2 2016-07-19T04:37:45.928-0700 I CONTROL [initandlisten] db version v3.2.7 2016-07-19T04:37:45.928-0700 I CONTROL [initandlisten] git version: 4249c1d2b59 99ebbf1fdf3bc0e0e3b3ff5c0aaf2 2016-07-19T04:37:45.928-0700 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.1p-fips 9 Jul 2015 2016-07-19T04:37:45.928-0700 I CONTROL [initandlisten] allocator: tcmalloc 2016-07-19T04:37:45.928-0700 I CONTROL [initandlisten] modules: none 2016-07-19T04:37:45.929-0700 I CONTROL [initandlisten] build environment: 2016-07-19T04:37:45.930-0700 I CONTROL [initandlisten] distmod: 2008plus-ss l 2016-07-19T04:37:45.930-0700 I CONTROL [initandlisten] distarch: x86_64 2016-07-19T04:37:45.930-0700 I CONTROL [initandlisten] target_arch: x86_64 2016-07-19T04:37:45.931-0700 I CONTROL [initandlisten] options: { storage: { db Path: "${J:\Setup\Mongodb\Backup}/RateDifferenceDB" } } 2016-07-19T04:37:45.931-0700 I STORAGE [initandlisten] exception in initAndList en: 29 Data directory ${J:\Setup\Mongodb\Backup}/RateDifferenceDB not found., te rminating 2016-07-19T04:37:45.931-0700 I CONTROL [initandlisten] dbexit: rc: 100 </code></pre>
2
Undefined index error in php/mysql
<p>I have the following script which allows the user from my android app to rate the football players of a team.</p> <pre><code>&lt;?php require "init.php"; header('Content-type: application/json'); error_reporting(E_ALL); ini_set("display_errors", 1); $id = $_POST['id']; $user_id = $_POST['User_Id']; $best_player = $_POST['player']; $rate = $_POST['rate']; if($best_player){ $sql_query = "insert into ratingplayerstable values('$id','$bestplayer','$rate','$user_id');"; if(mysqli_query($con,$sql_query)){ $_SESSION['id'] = mysqli_insert_id($con); $don = array('result' =&gt;"success","message"=&gt;"Επιτυχής πρόσθεση παίχτη"); } }else if($best_player){ $don = array('result' =&gt;"fail","message"=&gt;"Παρακαλώ συμπλήρωσε τα πεδία"); } echo json_encode($don); ?&gt; </code></pre> <p>When I run it as it is from my server,I get the following the following message:</p> <pre><code>&lt;br /&gt; &lt;b&gt;Notice&lt;/b&gt;: Undefined index: id in &lt;b&gt;/var/www/vhosts/theo- android.co.uk/httpdocs/ael/cms/insert_best_players.php&lt;/b&gt; on line &lt;b&gt;7&lt;/b&gt; &lt;br /&gt; &lt;br /&gt; &lt;b&gt;Notice&lt;/b&gt;: Undefined index: User_Id in &lt;b&gt;/var/www/vhosts/theo- android.co.uk/httpdocs/ael/cms/insert_best_players.php&lt;/b&gt; on line &lt;b&gt;8&lt;/b&gt; &lt;br /&gt; &lt;br /&gt; &lt;b&gt;Notice&lt;/b&gt;: Undefined index: player in &lt;b&gt;/var/www/vhosts/theo- android.co.uk/httpdocs/ael/cms/insert_best_players.php&lt;/b&gt; on line &lt;b&gt;9&lt;/b&gt; &lt;br /&gt; &lt;br /&gt; &lt;b&gt;Notice&lt;/b&gt;: Undefined index: rate in &lt;b&gt;/var/www/vhosts/theo- android.co.uk/httpdocs/ael/cms/insert_best_players.php&lt;/b&gt; on line &lt;b&gt;10&lt;/b&gt; &lt;br /&gt; &lt;br /&gt; &lt;b&gt;Notice&lt;/b&gt;: Undefined variable: don in &lt;b&gt;/var/www/vhosts/theo- android.co.uk/httpdocs/ael/cms/insert_best_players.php&lt;/b&gt; on line &lt;b&gt;38&lt;/b&gt; &lt;br /&gt; null </code></pre> <p>Without sending any data I should had get</p> <pre><code>{"fail":"Παρακαλώ συμπλήρωσε τα πεδία"} </code></pre> <p>Why is this happening? All the values like id,players etc are defined in my table. This is how I created the table:</p> <pre><code>CREATE TABLE IF NOT EXISTS `ratingplayerstable ` ( `id` int(10) NOT NULL AUTO_INCREMENT, `player` text NOT NULL, `rating` text NOT NULL, `User_Id`int(10) NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (User_Id) REFERENCES user_info(User_Id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=30; </code></pre> <p>Thanks,</p> <p>Theo.</p> <p><strong>edit</strong></p> <p>This is how i do the post request from the Android.</p> <pre><code>private void ratingPlayer(final String player, final String rating,final String UserId) { // Tag used to cancel the request //HttpsTrustManager.sssMethod(); String tag_string_req = "req_register"; StringRequest strReq = new StringRequest(Request.Method.POST, URL.URL_BEST_PLAYERS, new Response.Listener&lt;String&gt;() { @Override public void onResponse(String response) { Log.d("Response", "Best player response: " + response.toString()); try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.getString("result").equals("success")) { Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show(); } else if (jsonObject.getString("result").equals("fail")) { Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("Error", "Registration Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map&lt;String, String&gt; getParams() { // Posting params to register url Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;(); params.put("id", ""); params.put("User_Id", UserId); params.put("player", player); params.put("rating", rating); return params; } }; // Adding request to request queue AppController.getInstance().addToRequestQueue(strReq, tag_string_req); } } </code></pre> <p><strong>login.php</strong></p> <pre><code>&lt;?php session_start(); require "init.php"; header('Content-type: application/json'); $user_name = $_POST['user_name']; $user_pass = $_POST['user_pass']; $passwordEncrypted = sha1($user_pass); if($user_name &amp;&amp; $user_pass){ $sql_query = "select * from user_info where user_name ='".mysqli_real_escape_string($con, $user_name)."' and user_pass='".mysqli_real_escape_string($con, $passwordEncrypted)."' LIMIT 1"; $result = mysqli_query($con,$sql_query); $row = mysqli_fetch_array($result); if($row){ $don = array('result' =&gt;'success','message'=&gt;'You are logged in'); $_SESSION['id'] = $row['id']; }else{ $don = array('result' =&gt;'fail','message'=&gt;'User could not be found'); } }else if(!user_name){ $don = array('result' =&gt;"fail","message"=&gt;"Please enter your name"); }else if(!$user_pass){ $don = array('result' =&gt;"fail","message"=&gt;"Please enter your password"); } echo json_encode($don); ?&gt; </code></pre>
2
Android - Multiple fragment stack in each tab ViewPager
<p>I've been trying to create an app that uses the FragmentStatePagerAdapter, TabLayout, and Fragments. My goal is to have an app that functions as described below.</p> <pre><code>[App]--&gt; --&gt;[Tab1 Default View]--&gt;ChildFragment--&gt;ChildFragment --&gt;[Tab2 Default View]--&gt;ChildFragment--&gt;ChildFragment --&gt;[Tab3 Default View]--&gt;ChildFragment--&gt;ChildFragment </code></pre> <p>So, when the app loads, it would show Tab1 by default. Tab 1 would have it's "Root" view, and when I load a new "screen" from within it, it would nest the screens inside the Tab1. So if Tab1's title was "Tab 1" it would show that by default, but then if I click a button to load a new screen in tab 1, it would show the title as "New screen" and the back arrow would appear, which on click would take me back one level to the root view.</p> <p>I've tried following the tutorial here...</p> <p><a href="https://tausiq.wordpress.com/2014/06/06/android-multiple-fragments-stack-in-each-viewpager-tab/" rel="nofollow">https://tausiq.wordpress.com/2014/06/06/android-multiple-fragments-stack-in-each-viewpager-tab/</a></p> <p>However, it's FULL of errors and will not even compile in Android Studio newest version. Can anyone provide a short and sweet example project or even a link to a working example that I can follow?</p> <p>My app has always worked fine using ActivityGroup class, but since it has been deprecated since Api 13 I feel I REALLY need to update my app so it continues working in future Android versions. </p> <p>Help please!?!?!</p>
2
Trying to read numpy array into opencv - cv2.imdecode returns empty argument
<p>Just getting back into coding after a few years out. Trying to write a piece of code that can go through a folder with .fits files, read out the image data, convert them to an array, read them into opencv, then perform edge detection on them. I can get it working fine with .png files as I don't have to play with arrays. I've done a lot of reading about, and that's enabled me to get to this point. Problem is, img is currently being returned empty, which causes everything else to freak. Any ideas please? Any help would be gratefully received!</p> <pre><code>#import packages import cv2 from matplotlim import pyplot as plt import os from astropy.io import fits from skimage import img_as_uint import numpy as np #create array with filenames data = [] for root, dirs, files in os.walk(r'/Users/hannah/Desktop/firefountain-testset'): for file in files: if file.endswith('.fits'): data.append(file) #start my loop through the folder for i in data: fn = i #read fits image data hdulist = fits.open(fn) img_data = hdulist[1].data #put fits data into array with dtype set as original imgraw=np.array(img_data, dtype = np.uint8) #convert to uint16 img = img_as_uint(imgraw) #crop to area of interest then add into array - possibly don't need second line imgcrop = img[210:255,227:277] imgcroparr = np.array(imgcrop) #attempt to read into cv2 - this is where it loses the data #all fine before this point I believe imgfinal = cv2.imdecode(imgcroparr, 0,) plt.imshow(imgfinal) #imgfinal returns blank. </code></pre> <p><a href="https://drive.google.com/open?id=0B5sX66D_9xkwb18tdGpwU1M3bTA" rel="nofollow noreferrer">google drive with .fits files I'm using, plus .png to show what they should look like</a></p> <h1>Updated my code</h1> <pre><code>for i in data: fn = i imgraw = fits.getdata(fn) imgcrop = imgraw[210:255,227:277] img = cv2.imdecode(imgcrop, 0,) plt.imshow(img) </code></pre> <p>This opens the fits files no issue and imgcrop works as expected. cv2.imdecode(imgcrop, 0), however, throws up the following:</p> <p>error: /Users/jhelmus/anaconda/conda-bld/work/opencv-2.4.8/modules/highgui/src/loadsave.cpp:307: error: (-215) buf.data &amp;&amp; buf.isContinuous() in function imdecode_</p> <p>Can't find anything on this error in this context online, getting more and more confused. It's probably something very silly and basic that I've forgotten to do, but I can't see it.</p>
2
VSTO Addin for Outlook won't work
<p>I've seen tons of posts and sites that address this issue. I've tried every solution I've found but none of them work (I've been trying to figure this out for days now). I have seen many posts with the same exact sounding issue, but either the solution didn't work for me or isn't applicable. With that said...</p> <p>I have an add-in for Outlook 2007 that is intended to add text to the an email's title and body. It is installed for all users using an .msi file. There is an older version that I deployed last year that works fine. The new version I created has only a few minor input/output changes, nothing major. This new version works perfectly on my development computer in both debug from Visual Studio and from an actual install. However, I can't get it to work on a non-development computer. Here are the details on the program and target computer (development computer and target computer details are the same other than the fact that the target computer doesn't have Visual Studio):</p> <pre><code>-Using Visual Studio Professional 2013 -Written in Visual Basic -Target Framework is .NET 4.0 -The add-in is only run once the "send" button on an email is clicked. -Outlook version is Outlook 2007 -Operating system is Windows 7 Enterprise SP1 32-bit </code></pre> <p>The problem is that the add-in won't load on the target computer(yes, I know, a bazillion other people have had the same issue). As I said previously, it works fine on my computer in both debug and installed versions. This made me think that the other computer is missing something, so I tried installing the .NET 4.0 framework onto the target computer but it told me that it was already installed. I ran through everything I could think of to get it to work with no avail. Here's how it behaves:</p> <pre><code>-Installs fine with no errors. -HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Office/Outlook/Addins/EmailMarkTool/LoadBehavior = 3 after installation. -VSTO_LOGALERTS = 1 -VSTO_SUPPRESSDISPLAYALERTS = 0 -Outlook opens with no apparent errors. -LoadBehavior = 0 immediately after Outlook is opened. -Shows up in the Add-ins under "Inactive Application Add-ins." -Never shows up under "Disabled Add-ins." -In the "COM Add-Ins" dialog where I can check which add-ins to use, it shows the correct directory and the Load Behavior is "Unloaded." -The add-in can be checked. When I click "OK" I don't get any errors. When I go back to the Add-ins, it is unchecked and "Unloaded" again. -Setting the LoadBehavior to 3 doesn't help because it goes back to 0 as soon as Outlook is started again. -I inserted a try-catch block into the New() function of the add-in that has a MsgBox pop-up and a Throw. -I get absolutely no errors anywhere. -No log file is generated. </code></pre> <p>I have tried uninstalling, rebuilding, and reinstalling multiple times all with the same result. I just can't figure out why it will work on my development computer but not the target computer. Thanks for reading all of this. I know it's a lot, but I needed to get the details out. Thanks in advance for any input!</p> <p>[UPDATE]: I just created a brand new minimal add-in just to test if it would work but got the same results.</p>
2
Gradle + Spring Boot + Jetty + JSP fails
<p>I'm trying to use <a href="/questions/tagged/spring-boot" class="post-tag" title="show questions tagged &#39;spring-boot&#39;" rel="tag">spring-boot</a> with the <a href="/questions/tagged/gradle" class="post-tag" title="show questions tagged &#39;gradle&#39;" rel="tag">gradle</a> build system and <a href="/questions/tagged/jetty" class="post-tag" title="show questions tagged &#39;jetty&#39;" rel="tag"><img src="//i.stack.imgur.com/Ly8wa.png" height="16" width="18" alt="" class="sponsor-tag-img">jetty</a>. Now the jsp doesn't render and i get this error msg</p> <pre><code>Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Sun Jul 17 00:31:05 CEST 2016 There was an unexpected error (type=Internal Server Error, status=500). org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoClassDefFoundError: org/apache/jasper/runtime/JspSourceImports </code></pre> <p>it seems to depend on the build.gradle file.</p> <pre><code> buildscript { repositories { mavenCentral() } dependencies { classpath "org.springframework.boot:spring-boot-gradle-plugin:1.3.6.RELEASE" classpath 'org.springframework:springloaded:1.2.5.RELEASE' } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'spring-boot' apply plugin: 'rebel' buildscript { repositories { mavenCentral() } dependencies { classpath group: 'org.zeroturnaround', name: 'gradle-jrebel-plugin', version: '1.1.3' } } jar { baseName = 'gs-spring-boot' version = '0.1.0' } repositories { mavenCentral() } sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { // tag::jetty[] compile("org.springframework.boot:spring-boot-starter-web") { exclude module: "spring-boot-starter-tomcat" } compile("org.springframework.boot:spring-boot-starter-jetty") // end::jetty[] // tag::actuator[] compile("org.springframework.boot:spring-boot-starter-actuator") compile("javax.servlet:javax.servlet-api") compile('org.eclipse.jetty:jetty-webapp') compile('org.eclipse.jetty:jetty-jsp') runtime 'javax.servlet:javax.servlet-api' runtime 'javax.servlet:jstl' testCompile("org.springframework.boot:spring-boot-starter-test") testCompile("junit:junit") } // change default IntelliJ output directory for compiling classes idea { module { inheritOutputDirs = false outputDir = file("$buildDir/classes/main/") } } task wrapper(type: Wrapper) { gradleVersion = '2.3' } </code></pre> <p>If I use maven then I can render jsp if I start it from the command line with <code>mvn jetty:run</code></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;!-- Your own application should inherit from spring-boot-starter-parent --&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-samples&lt;/artifactId&gt; &lt;version&gt;1.4.0.BUILD-SNAPSHOT&lt;/version&gt; &lt;/parent&gt; &lt;artifactId&gt;spring-boot-sample-jetty-jsp&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;name&gt;Spring Boot Jetty JSP Sample&lt;/name&gt; &lt;description&gt;Spring Boot Jetty JSP Sample&lt;/description&gt; &lt;url&gt;http://projects.spring.io/spring-boot/&lt;/url&gt; &lt;organization&gt; &lt;name&gt;Pivotal Software, Inc.&lt;/name&gt; &lt;url&gt;http://www.spring.io&lt;/url&gt; &lt;/organization&gt; &lt;properties&gt; &lt;main.basedir&gt;${basedir}/../..&lt;/main.basedir&gt; &lt;m2eclipse.wtp.contextRoot&gt;/&lt;/m2eclipse.wtp.contextRoot&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-validation&lt;/artifactId&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;org.apache.tomcat.embed&lt;/groupId&gt; &lt;artifactId&gt;tomcat-embed-el&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-jetty&lt;/artifactId&gt; &lt;!--&lt;scope&gt;provided&lt;/scope&gt;--&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;jstl&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.eclipse.jetty&lt;/groupId&gt; &lt;artifactId&gt;apache-jsp&lt;/artifactId&gt; &lt;!--&lt;scope&gt;provided&lt;/scope&gt;--&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;executable&gt;true&lt;/executable&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;useSystemClassLoader&gt;false&lt;/useSystemClassLoader&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>Why even mix the build system with the runtime and why must I manually put together a jetty server just to run some jsp and servlets? I don't understand why Java project must make the easy thing impossible. It used to be easy to use jsp and servlet, now if I want to use jsp then I get 2 problems for one for several days. </p> <p>Isn't there even a working example with gradle for this type of task? Do you know anything about what I'm trying to do at all?</p> <p>Viewing a JSP with Jetty should be the most basic thing, why would I want to achieve something else with a Java server? Nobody uses Jetty for static content only or for RestAPI only - Jetty's main function is viewing JSP so why make the easy task impossible?</p> <p>I also do web development with python and with python this type of problem is incomprenehsible - viewing a template just works and we couldn't achieve this type of problem even if we tried. Now Java has wasted my entire weekend with bad or no instructions, faulty build files and incomplete projects. I wished I stayed with C, assembly and python. At least we can debug things there and we have alternatives. Every time I try something with Java we get this problem, a puke of endless confusing stacktrace where you have to link to most obscure 4 gigabytes of jar and xml hell. I'm going back to assembly programming where can know what you're doing and you don't need 4 gigabytes of XML just to run a server which is only a source of confusion.</p> <pre><code>org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoClassDefFoundError: org/apache/jasper/runtime/JspSourceImports at org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1305) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:979) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) ~[javax.servlet-api-3.1.0.jar:3.1.0] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) ~[javax.servlet-api-3.1.0.jar:3.1.0] at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:812) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter.doFilter(WebSocketUpgradeFilter.java:224) ~[websocket-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:281) ~[spring-boot-actuator-1.3.6.RELEASE.jar:1.3.6.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:115) ~[spring-boot-actuator-1.3.6.RELEASE.jar:1.3.6.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:103) ~[spring-boot-actuator-1.3.6.RELEASE.jar:1.3.6.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585) [jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577) [jetty-security-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515) [jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.Server.handle(Server.java:499) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544) [jetty-io-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635) [jetty-util-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555) [jetty-util-9.2.17.v20160517.jar:9.2.17.v20160517] at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91] Caused by: java.lang.NoClassDefFoundError: org/apache/jasper/runtime/JspSourceImports at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_91] at java.lang.ClassLoader.defineClass(ClassLoader.java:763) ~[na:1.8.0_91] at java.lang.ClassLoader.defineClass(ClassLoader.java:642) ~[na:1.8.0_91] at org.apache.jasper.servlet.JasperLoader.findClass(JasperLoader.java:232) ~[javax.servlet.jsp-2.3.2.jar:2.3.2] at org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:193) ~[javax.servlet.jsp-2.3.2.jar:2.3.2] at org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:125) ~[javax.servlet.jsp-2.3.2.jar:2.3.2] at org.apache.jasper.JspCompilationContext.load(JspCompilationContext.java:656) ~[javax.servlet.jsp-2.3.2.jar:2.3.2] at org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:202) ~[javax.servlet.jsp-2.3.2.jar:2.3.2] at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388) ~[javax.servlet.jsp-2.3.2.jar:2.3.2] at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473) ~[javax.servlet.jsp-2.3.2.jar:2.3.2] at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377) ~[javax.servlet.jsp-2.3.2.jar:2.3.2] at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) ~[javax.servlet-api-3.1.0.jar:3.1.0] at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:812) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652) ~[jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585) [jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:595) [jetty-security-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515) [jetty-servlet-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) [jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:191) ~[jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:72) ~[jetty-server-9.2.17.v20160517.jar:9.2.17.v20160517] at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:168) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1246) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1029) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:973) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE] ... 48 common frames omitted Caused by: java.lang.ClassNotFoundException: org.apache.jasper.runtime.JspSourceImports at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_91] at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_91] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_91] at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_91] at org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:187) ~[javax.servlet.jsp-2.3.2.jar:2.3.2] at org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:125) ~[javax.servlet.jsp-2.3.2.jar:2.3.2] ... 92 common frames omitted </code></pre> <p>My file structure is</p> <pre><code>dac@dac-Latitude-E7450 ~/p/s/s/spring-boot-sample-jetty-jsp&gt; tree . ├── build │   ├── classes │   │   ├── main │   │   │   ├── application.properties │   │   │   ├── rebel.xml │   │   │   └── sample │   │   │   └── jetty │   │   │   └── jsp │   │   │   ├── MyException.class │   │   │   ├── MyRestResponse.class │   │   │   ├── SampleJettyJspApplication.class │   │   │   └── WelcomeController.class │   │   └── test │   ├── dependency-cache │   ├── libs │   │   ├── gs-spring-boot-0.1.0.jar │   │   └── gs-spring-boot-0.1.0.jar.original │   ├── resources │   │   └── main │   │   ├── application.properties │   │   └── rebel.xml │   └── tmp │   ├── compileJava │   │   └── emptySourcePathRef │   ├── compileTestJava │   │   └── emptySourcePathRef │   └── jar │   └── MANIFEST.MF ├── build.gradle ├── build.log ├── classes │   └── production │   └── spring-boot-sample-jetty-jsp │   ├── application.properties │   └── rebel.xml ├── gradle │   └── wrapper │   ├── gradle-wrapper.jar │   └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── pom.xml ├── spring │   ├── gradle │   │   └── wrapper │   │   ├── gradle-wrapper.jar │   │   └── gradle-wrapper.properties │   ├── gradlew │   ├── gradlew.bat │   ├── pom.xml │   └── src │   ├── main │   │   ├── java │   │   │   └── sample │   │   │   └── jetty │   │   │   └── jsp │   │   │   ├── MyException.java │   │   │   ├── MyRestResponse.java │   │   │   ├── SampleJettyJspApplication.java │   │   │   └── WelcomeController.java │   │   ├── resources │   │   │   ├── application.properties │   │   │   └── rebel.xml │   │   └── webapp │   │   └── WEB-INF │   │   └── jsp │   │   └── welcome.jsp │   └── test │   └── java │   └── sample │   └── jetty │   └── jsp │   └── SampleWebJspApplicationTests.java ├── spring-boot-sample-jetty-jsp.iml ├── spring-boot-sample-jetty-jsp.ipr ├── spring-boot-sample-jetty-jsp.iws ├── src │   ├── main │   │   ├── java │   │   │   └── sample │   │   │   └── jetty │   │   │   └── jsp │   │   │   ├── MyException.java │   │   │   ├── MyRestResponse.java │   │   │   ├── SampleJettyJspApplication.java │   │   │   └── WelcomeController.java │   │   ├── resources │   │   │   ├── application.properties │   │   │   └── rebel.xml │   │   └── webapp │   │   └── WEB-INF │   │   └── jsp │   │   └── welcome.jsp │   └── test │   └── java │   └── sample │   └── jetty │   └── jsp │   └── SampleWebJspApplicationTests.java └── target ├── classes │   ├── application.properties │   ├── rebel.xml │   └── sample │   └── jetty │   └── jsp │   ├── MyException.class │   ├── MyRestResponse.class │   ├── SampleJettyJspApplication.class │   └── WelcomeController.class ├── generated-sources │   └── annotations ├── generated-test-sources │   └── test-annotations ├── maven-archiver │   └── pom.properties ├── maven-status │   └── maven-compiler-plugin │   ├── compile │   │   └── default-compile │   │   ├── createdFiles.lst │   │   └── inputFiles.lst │   └── testCompile │   └── default-testCompile │   ├── createdFiles.lst │   └── inputFiles.lst ├── spring-boot-sample-jetty-jsp-1.4.0.BUILD-SNAPSHOT │   ├── META-INF │   └── WEB-INF │   ├── classes │   │   ├── application.properties │   │   ├── rebel.xml │   │   └── sample │   │   └── jetty │   │   └── jsp │   │   ├── MyException.class │   │   ├── MyRestResponse.class │   │   ├── SampleJettyJspApplication.class │   │   └── WelcomeController.class │   ├── jsp │   │   └── welcome.jsp │   └── lib │   ├── classmate-1.3.1.jar │   ├── hibernate-validator-5.2.4.Final.jar │   ├── jackson-annotations-2.8.0.jar │   ├── jackson-core-2.8.0.jar │   ├── jackson-databind-2.8.0.jar │   ├── jboss-logging-3.3.0.Final.jar │   ├── jcl-over-slf4j-1.7.21.jar │   ├── jstl-1.2.jar │   ├── jul-to-slf4j-1.7.21.jar │   ├── log4j-over-slf4j-1.7.21.jar │   ├── logback-classic-1.1.7.jar │   ├── logback-core-1.1.7.jar │   ├── slf4j-api-1.7.21.jar │   ├── snakeyaml-1.17.jar │   ├── spring-aop-4.3.2.BUILD-SNAPSHOT.jar │   ├── spring-beans-4.3.2.BUILD-SNAPSHOT.jar │   ├── spring-boot-1.4.0.BUILD-SNAPSHOT.jar │   ├── spring-boot-autoconfigure-1.4.0.BUILD-SNAPSHOT.jar │   ├── spring-boot-starter-1.4.0.BUILD-SNAPSHOT.jar │   ├── spring-boot-starter-logging-1.4.0.BUILD-SNAPSHOT.jar │   ├── spring-boot-starter-validation-1.4.0.BUILD-SNAPSHOT.jar │   ├── spring-boot-starter-web-1.4.0.BUILD-SNAPSHOT.jar │   ├── spring-context-4.3.2.BUILD-SNAPSHOT.jar │   ├── spring-core-4.3.2.BUILD-SNAPSHOT.jar │   ├── spring-expression-4.3.2.BUILD-SNAPSHOT.jar │   ├── spring-web-4.3.2.BUILD-SNAPSHOT.jar │   ├── spring-webmvc-4.3.2.BUILD-SNAPSHOT.jar │   └── validation-api-1.1.0.Final.jar ├── spring-boot-sample-jetty-jsp-1.4.0.BUILD-SNAPSHOT.war ├── spring-boot-sample-jetty-jsp-1.4.0.BUILD-SNAPSHOT.war.original ├── surefire-reports │   ├── sample.jetty.jsp.SampleWebJspApplicationTests.txt │   └── TEST-sample.jetty.jsp.SampleWebJspApplicationTests.xml └── test-classes └── sample └── jetty └── jsp └── SampleWebJspApplicationTests.class 85 directories, 95 files </code></pre>
2
Deep filter for values in JSON data
<p>I have some JSON data that I am trying to filter based on the checkbox selection of a user in javascript but I have run into a wall as to the multi-level filtering. I have two dimensions of data that need to be filtered from the JSON; first filter the JSON data based on the OS selection, then to filter that resulting OS selection data with a questions selected filter. For example, I am doing the following:</p> <pre><code>$('.os-checkbox input[type="checkbox"]:checked').each(function() { OSSelected.push(Number($(this).parents('.checkbox').index())); }); $('.question-checkbox input[type="checkbox"]:checked').each(function() { QuestionSelected.push(Number($(this).parents('.checkbox').index())); }); var array = $scope.data.responses; var osSelectionFilter = array.filter(function(elem, index) { return (JSON.stringify(elem.OSSelectedIndex) == JSON.stringify(OSSelected)); }); console.log(osSelectionFilter); // should return all 'data.response.OSSelectedIndex' objects with the selection made, ex. 0-PC so any selection with "OSSelectedIndex": [0] included var questionSelectionFilter = osSelectionFilter.filter(function(elem, index) { return (JSON.stringify(elem.questionSelectedIndex) == JSON.stringify(QuestionSelected)); }); console.log(questionSelectionFilter); // should filter the osSelectionFilter above and return all objects with the questions array included, ex. 0, 1, 2... </code></pre> <p>Once a selection is filtered the "result" data in the JSON will populate a div. Issue is now that the filter is trying to filter the whole array I am guessing, e.g. looking for [0, 1] instead of each value in the array individually; where value [0] and [1] are two different separate selections.</p> <p>JSON data coming from the CMS looks like this:</p> <pre><code>{ "id": "test1", "fields": { "OS": [ "PC", "Mac", "Android", "iOS" ], "questions": [{ "question": "Question 0" }, { "question": "Question 1" }, { "question": "Question 2" }, { "question": "Question 3" }, { "question": "Question 4" }, { "question": "Question 5" }, { "question": "Question 6" }], "responses": [{ "ID": 1, "OSSelectedIndex": [ 0 ], "questionSelectedIndex": [], "result": "&lt;h1&gt;Response 1 found&lt;/h1&gt;" }, { "ID": 2, "OSSelectedIndex": [ 0, 1 ], "questionSelectedIndex": [ 0, 1, 2 ], "result": "&lt;h1&gt;Response 2 found&lt;/h1&gt;" }, { "ID": 3, "OSSelectedIndex": [ 0, 2 ], "questionSelectedIndex": [ 0, 1, 2, 5 ], "result": "&lt;h1&gt;Response 3 found&lt;/h1&gt;" }, { "ID": 4, "OSSelectedIndex": [ 1, 2 ], "questionSelectedIndex": [ 1, 2, 3, 4 ], "result": "&lt;h1&gt;Response 4 found&lt;/h1&gt;" }] } } </code></pre> <p>Is such a setup possible?</p> <p>Plunker with the code above:</p> <p><a href="https://plnkr.co/edit/N1NJKDOgvVkB9gPmPooi?p=preview" rel="nofollow">https://plnkr.co/edit/N1NJKDOgvVkB9gPmPooi?p=preview</a></p> <p>Thanks so much</p>
2
Out of memory exception after a certain execution time but C# application private bytes aren't increasing
<p>We've an application which writes records in a SQL Server CE (version 3.5) / (MySQL 5.7.11 community) database table [depending on the configuration] through the use of NHibernate (version 3.1.0.4000).</p> <p>The method which performs the save to the database table has the following structure, so everything should be disposed correctly</p> <pre><code>using (ISession session = SessionHelper.GetSession()) using (ITransaction txn = session.BeginTransaction()) { session.Save(entity); txn.Commit(); } </code></pre> <p>After about a week of heavy work (where several hundred thousands records have been written) the application stops working and throws an out of memory error. </p> <p>Then:</p> <ul> <li>With SQL Server CE the database gets corrupted and needs to be manually repaired</li> <li>With MySQL the mysqld daemon is terminated and it needs to be restarted </li> </ul> <p>We've been monitoring the application memory usage through ANTS Memory Profiler (with SQL CE configuration), but, to our surprise, <strong>the application "private bytes" doesn't seem to increase at all - this is reported both by ANTS and by the RESOURCE MANAGER</strong>. </p> <p>Still, when the application is forced close (after such error shows up) the "physical memory usage" in the task manager falls from about 80% right down to 20-30%, and I'm again able to start other processes without getting another out of memory exception.</p> <p>Doing some research, I've found this:</p> <p><a href="https://stackoverflow.com/questions/1984186/what-is-private-bytes-virtual-bytes-working-set/1986486#1986486">What is private bytes, virtual bytes, working set?</a></p> <p>I quote the last part about private bytes:</p> <blockquote> <p>Private Bytes are a reasonable approximation of the amount of memory your executable is using and can be used to help narrow down a list of potential candidates for a memory leak; if you see the number growing and growing constantly and endlessly, you would want to check that process for a leak. This cannot, however, prove that there is or is not a leak.</p> </blockquote> <p>Considering the rest of the linked topic, for what I understand, "private bytes" may or may not contain the memory allocated by linked unmanaged dlls, so:</p> <p>I configured ANTS to also report information about unmanaged memory (<em>Unmanaged memory breakdown by module section</em>) and I've noticed that <em>one of the 2 following modules (depending on a specific sessionfactory setting) take up more and more space (with a ratio that's compatible with the computer running out of memory in about a week)</em>:</p> <ol> <li>sqlceqp35</li> <li>MSVCR120</li> </ol> <p>Given the current results, I'm planning the following tests:</p> <ol> <li>update nhibernate version</li> <li>trying to further analyze current nhibernate sessionhelper configuration</li> <li>creating an empty console application without WPF user interface (yes, this application uses WPF) where I put more and more code until I'm able to reproduce the issue</li> </ol> <p>Any suggestion?</p> <p>EDIT 30/06/2016:</p> <p>Here's the session factory initialization:</p> <p><strong>SESSION FACTORY: (the custom driver is to avoid trucation after 4000 chars)</strong></p> <pre><code>factory = Fluently.Configure() .Database(MsSqlCeConfiguration.Standard.ConnectionString(connString) .ShowSql() .MaxFetchDepth(3) .Driver&lt;MySqlServerCeDriver&gt;()) // FIX truncation 4000 chars .Mappings(m =&gt; m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())) .ProxyFactoryFactory&lt;NHibernate.ByteCode.LinFu.ProxyFactoryFactory&gt;() .ExposeConfiguration(c =&gt; { c.SetProperty("cache.provider_class", "NHibernate.Cache.HashtableCacheProvider"); c.SetProperty("cache.use_query_cache", "true"); c.SetProperty("command_timeout", "120"); }) .BuildSessionFactory(); public class MySqlServerCeDriver : SqlServerCeDriver { protected override void InitializeParameter( IDbDataParameter dbParam, string name, SqlType sqlType) { base.InitializeParameter(dbParam, name, sqlType); if (sqlType is StringClobSqlType) { var parameter = (SqlCeParameter)dbParam; parameter.SqlDbType = SqlDbType.NText; } } } </code></pre> <p>EDIT 07/07/2016</p> <p>As requested, the GetSession() does the following:</p> <pre><code>public static ISession GetSession() { ISession session = factory.OpenSession(); session.FlushMode = FlushMode.Commit; return session; } </code></pre>
2
How to define the sort order when implementing 'Comparable'?
<p>I know this seems to be a trivial question (and I have no doubt all the 'smart guys' would come and mark it as duplicate), but I havn't found <strong>any sufficient explanation to my question</strong>. Is it just me getting so much trouble to understand this simple subject?</p> <p>I understand the basics behind <code>Comparable</code>interface and how it works, but I have a truly difficulty to undestand <strong>HOW</strong> to determine the <strong>ORDER</strong> of the sort.</p> <p>For example - I have this very simple <code>Fruit</code> class:</p> <pre><code>public class Fruit implements Comparable&lt;Fruit&gt; { private String fruitName; private String fruitDesc; private int quantity; public Fruit(String fruitName, String fruitDesc, int quantity) { this.fruitName = fruitName; this.fruitDesc = fruitDesc; this.quantity = quantity; } public String getFruitName() { return fruitName; } public void setFruitName(String fruitName) { this.fruitName = fruitName; } public String getFruitDesc() { return fruitDesc; } public void setFruitDesc(String fruitDesc) { this.fruitDesc = fruitDesc; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int compareTo(Fruit compareFruit) { //ascending order return this.quantity - ((Fruit) compareFruit).getQuantity(); } </code></pre> <p>Why when declaring the <code>compareTo</code> like above it will sort by ascending order and when declaring it the opposite:</p> <pre><code>return ((Fruit) compareFruit).getQuantity() - this.quantity; </code></pre> <p>it will be by descending order?</p>
2
functools.partial: TypeError: got multiple values for keyword argument
<p>I am using the partial method from the functools module to map a function over a range of values:</p> <pre><code>def basic_rule(p,b,vx=1,**kwargs): return (p / b) if vx != 0 else 0 def rule5(func,**kwargs): vals = map(functools.partial(func,**kwargs), range(1,kwargs['b']+1)) return [x for i,x in enumerate(vals[:-1]) if x &gt;= vals[i+1]] == [] rule5(basic_rule,p=100,b=10000) </code></pre> <p>Here is the error I get on line 5:</p> <pre><code>----&gt; return map(functools.partial(func,**kwargs), range(1,kwargs['b']+1)) TypeError: basic_rule() got multiple values for keyword argument 'p' </code></pre> <p>It looks like functools.partial is trying to assign the range to the argument p, even though I have already assigned a value to it. I'm trying to assign the range to the value of vx. Any idea how I can make that happen?</p> <p>EDIT: Added a little bit of extra context to the code. Essentially what I'd like test 5 to do is ensure that the result of the function given to it increases as vt goes up, so that `func(vt=1) &lt; func(vt=2)... &lt; func(vt=n).</p>
2
linux linking to a .so , but still getting undefined reference
<p>I am trying to create an executable that uses code from both static libraries and a shared library:</p> <p>The static libs are several boost .a , <code>pthread</code> and <code>libbus.a</code>. The shared lib is a <code>libwrap.so</code>. </p> <p>Note that the libwrap , uses code from <code>libbus</code> and <code>libbus</code> uses code from <code>pthread</code>. Finally, the executable uses code from <code>libwrap</code> and from <code>boost</code>.</p> <p>Since the order of libraries included in the linker matters I am trying to find the "winning" sequence.</p> <p>The linking stage is the following (pasted in multiple lines for convenience):</p> <pre><code>$ /usr/bin/c++ -Wall -Wextra -fPIC -fvisibility=hidden -fno-strict-aliasing -Wno-long-long -m64 -rdynamic -D_UNICODE -DUNICODE CMakeFiles/Wrapper_Test.dir/test.cpp.o /usr/local/lib/libboost_log.a /usr/local/lib/libboost_system.a /usr/local/lib/libboost_filesystem.a /usr/local/lib/libboost_date_time.a /usr/local/lib/libboost_thread.a /usr/local/lib/libboost_log_setup.a /usr/local/lib/libboost_chrono.a -pthread /home/nass/dev/Data_Parser/trunk/external/lib/linux64_gcc_release/libbus.a -L/home/nass/dev/Data_Parser_build/lib #this is where the libwrap.so is located -Wl,-rpath,/home/nass/dev/Data_Parser_build/lib -lwrap #the shared lib -o ../../../bin/Wrapper_Test </code></pre> <p>The link error is </p> <pre><code>CMakeFiles/Wrapper_Test.dir/test.cpp.o: In function `main': test.cpp:(.text+0x2e): undefined reference to `wrapperNamespace::GetWrapper()' collect2: error: ld returned 1 exit status </code></pre> <p>The <code>GetWrapper()</code> is located in <code>libwrap.so</code> of course, and I can verify it is a symbol that can be found in there:</p> <pre><code>$ nm -Ca ../../../lib/libwrap.so | grep GetWrapper 00000000000423d6 t wrapperNamespace::GetWrapper() </code></pre> <p>However, the linker cannot find it. what am I doing wrong here?</p> <h2>EDIT:</h2> <p>The linking command above is generated by the following CMakeLists.txt file:</p> <pre><code>set(TARGET_NAME Wrapper_Test) #set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/bin) #set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}) #set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}) # INCLUDE INTERNAL FOLDER include_directories(${CMAKE_SOURCE_DIR}/include/Wrapper) add_executable(${TARGET_NAME} test.cpp) add_boost_lib(${TARGET_NAME} log system filesystem date_time thread log_setup chrono) setup_libbus(${TARGET_NAME}) #the libbus.a target_link_libraries(${TARGET_NAME} -L../../../lib -lwrap) set_property(TARGET ${TARGET_NAME} PROPERTY FOLDER test) </code></pre>
2
Filtering/Searching Nested Struct Array
<p>I'm trying to add a search bar to the top of a grouped table. However I'm unsure how to filter through my data. The data is stored in a nested array with objects held in this format;</p> <pre><code>struct Group { var id: String var type: String var desc: String var avatar: String var name: String init() { id = "" type = "" desc = "" avatar = "" name = "" } } </code></pre> <p>Because I get data from two sources, two arrays are nested together, this also makes it simpler to create the two sections of the grouped table. I'll note, they both use the same Group struct.</p> <pre><code>self.masterArray = [self.clientArray, self.departmentArray] </code></pre> <p>This "masterArray" is then used to populate the table. Filtering/searching a single array isn't too difficult, but how do I search through a nested array?</p> <pre><code>func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { } </code></pre> <p><strong>EDIT:</strong> I've finally got things working, courtesy of @appzYourLife.</p> <pre><code>func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { print("Searching for:" + searchText) if searchText.isEmpty { filterArray = masterArray } else { filterArray = [ clientArray.filter { $0.name.range(of: searchText) != nil }] + [ departmentArray.filter { $0.name.range(of: searchText) != nil } ] } tableView.reloadData() } </code></pre>
2
C# How to read embedded resource text file with File.ReadLines?
<p>How can I do that? My string for hello.txt is:</p> <pre><code>string hello = Properties.Resources.hello; </code></pre> <p>and I want it so:</p> <pre><code>Random rand = new Random(); IEnumerable&lt;string&gt; lines = File.ReadLines(hello); var lineToRead = rand.Next(1, lines.Count()); var line = lines.Skip(lineToRead - 1).First(); txtbx_output.Text = line.ToString(); </code></pre> <p>This here works for me with no problems:</p> <pre><code>IEnumerable&lt;string&gt; lines = File.ReadAllLines(@"my pathblabla\Text\hello.txt"); </code></pre> <p>but not as a resource !</p> <p>This makes me very angry </p>
2
How do I run a filter on pg_dump data during an import?
<p>Using a terminal on Mac OSX (iTerm2) with no external apps except for postgres, I want to run some regex find/replaces on a rather large (52 MB) pg_dump data file as it's being imported into a PostgreSQL database. I need to do this before the dump file hits PostgreSQL because I have to transform the incoming SQL queries that create and modify tables.</p> <p>The shell command I'm using to import the data is:</p> <pre><code>psql MyDatabase &lt; mydata.sql </code></pre> <p>Is there a way to pipe the data through a regex find/replace filter? Can I do something with native Linux command line utilities like grep?</p> <p>Alternatively, how would I batch my regex's and apply them to my dump file and then save the changes to a new file?</p>
2
Route is working from Postman, but it is not working from client
<p>I am trying to fix a 400: Bad Request error. I get a 200 success when I make a PUT request from Postman <a href="http://i.stack.imgur.com/2pQwN.png" rel="nofollow">see image</a> . However, when I try the route from the browser, it gives me that 400. </p> <blockquote> <p>angular.js:11881 PUT <a href="http://localhost:8000/api/users/addStock/578430b65bd7a5dca37bf2e5" rel="nofollow">http://localhost:8000/api/users/addStock/578430b65bd7a5dca37bf2e5</a> 400 (Bad Request)</p> <p>err: Object {data: Object, status: 400, config: Object, statusText: "Bad Request"}</p> </blockquote> <p>stock.html</p> <pre><code>&lt;form ng-submit='addStock()'&gt; &lt;input type="text" ng-model='addObj.symbol' placeholder="symbol" required&gt; &lt;button class="btn btn-success"&gt;Add&lt;/button&gt; &lt;/form&gt; </code></pre> <p>controller.js</p> <pre><code>app.controller('stockCtrl', function($scope,User){ $scope.addStock = () =&gt; { let userId = '578430b65bd7a5dca37bf2e5'; User.addStock(userId, $scope.addObj.symbol) .then(res =&gt; { console.log("res.data: ", res.data); }) .catch(err =&gt; { console.log("err: ", err); }) } </code></pre> <p>service.js</p> <pre><code>app.service('User', function($http) { this.addStock = (id, symbol) =&gt; { return $http.put(`/api/users/addStock/${id}`, symbol); } } </code></pre> <p>routes/api/users.js</p> <pre><code>router.put('/addStock/:userId',(req,res)=&gt;{ User.findById(req.params.userId, (err, user)=&gt;{ if(err || !user) return res.status(400).send(err || {error: 'user not found'}); let stock = { symbol : req.body.symbol } user.stocks.push(stock); user.save((err, savedStock)=&gt;{ res.status(err ? 400 : 200).send(err || savedStock); }) }) }) </code></pre> <p>If anybody can help me. I will be very greatful. Thank you so much.</p>
2
How do I execute my program without ./a.out command?
<p>I have written a c program. I want to pipe the program and I want to make it look meaningful. So instead of writing <code>./a.out</code> each time, I want to name it <code>changetext</code>. To achieve that, I compiled my program following way: <code>gcc -o changetext myprog.c</code>. To the best of my knowledge, this should replace the use of <code>./a.out</code> and <code>changetext</code> should do that instead. But I'm getting <code>command not found</code>. I am new to c and unix environment. Any suggestion appreciated.</p>
2
Check sender when listening to unix socket
<p>I've got process that listen to unix socket. However, before i read, i'd like to check some meta data about this incoming message such as it's source process (say i'd like to drop messages from non trusted senders). is there any syscall that retrieve this information. </p> <pre><code> if(listen(sock_fd, 10) != 0) { assert("listen failed"); } while((conn_fd = accept(sock_fd, (struct sockaddr *) &amp;address, &amp;address_length)) != -1) { int nbytes = 0; static char buffer[PAYLOAD_SZ]; nbytes = (int)read(conn_fd, buffer, PAYLOAD_SZ); </code></pre>
2
Transfer large file via SFTP in PHP
<p>I have a large file (200 MB upwards). I need to transfer it via PHP cron job. Using <code>Phpseclib</code> gives the following error:</p> <blockquote> <p>Allowed memory size of 134217728 bytes exhausted (tried to allocate 4133 bytes) in /app/vendor/phpseclib/phpseclib/phpseclib/Net/SSH2.php</p> </blockquote> <p>Is there a way I can do this with <code>PHP cron job</code>? </p> <p>The code is simple one line where $localFile is an already existing CSV file </p> <pre><code>$sftp-&gt;put('/Import/coupons/coupons_import_test.csv', $localFile, NET_SFTP_LOCAL_FILE); </code></pre> <p><strong>PS</strong>. This needs to be done after <code>PHP</code> generates that file in the <code>/tmp</code> folder so timing of the transfer script has to come into play.</p> <p>[Edit] I do not intend on increasing the memory limit as the files later could be of higher sizes. A solution where I can transfer the file in parts (append mode) or use some shell script with PHP cron could be worthwhile</p> <p>The file size on remote server is 111.4 MB while the actual file is much larger on local.</p> <p>[Edit after the fix] The issue disappeared after changing to version 2.0.2 from version 1.0 I had to modify the code for put </p> <pre><code>$sftp-&gt;put('/Import/coupons/coupons_import.csv', $localFile, $sftp::SOURCE_LOCAL_FILE); </code></pre>
2
jquery ajax is not returning back to success function from MVC Controller
<p>I'm hitting a method in controller from <code>jquery ajax</code>. I have an <code>html</code> page outside the application from where I'm calling this method.</p> <p>Below is the <code>ajax</code> code written on <code>html</code> page.</p> <pre><code>function SignIn() { var d = JSON.stringify({ Email: $('#email').val(), Password: $('#password').val() }); $.ajax({ url: "http://localhost:58954/Account/SignIn", type: "POST", contentType: "application/json; charset=utf-8", dataType: "JSON", data: d, success: function (e) { alert('success'); }, error: function (e) { alert(JSON.stringify(e)); } }); } </code></pre> <p>Below is the code written in <code>controller's</code> method. I'm returning <code>Json object</code> from here.</p> <pre><code>[AjaxOnly(), HttpPost(), AllowAnonymous()] public ActionResult SignIn(AuthenticationModel model) { // here code written for authentication dynamic jsonData = new { Message = errorMessage, HasError = HasError, RedirectUrl = redirectUrl }; return Json(jsonData); } </code></pre> <p>When ajax code run then it first goes to error function and shows me following details in alert.</p> <p><a href="https://i.stack.imgur.com/V5cNo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V5cNo.png" alt="enter image description here"></a></p> <p>After this it hits the method in <code>controller</code> and <code>code</code> runs perfectly as it should and after that it doesn't return back to ajax call's success function.</p> <p>It shows the <code>Json object</code> on page as below:</p> <p><a href="https://i.stack.imgur.com/Ee8dG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ee8dG.png" alt=""></a></p>
2
ASP.Net Cache busting approach not working
<p>I am trying to solve the problem of browser caching. Whenever there are any changes in any of the js and css files, the files are served from the browser cache rather than from server, I researched on internet and found <a href="http://madskristensen.net/post/cache-busting-in-aspnet" rel="nofollow noreferrer">this great post</a> from mads krinstinsen.</p> <p>I included the following class and method in a class in my <code>App_Code</code> folder.</p> <pre><code>using System; using System.IO; using System.Web; using System.Web.Caching; using System.Web.Hosting; public class Fingerprint { public static string Tag(string rootRelativePath) { if (HttpRuntime.Cache[rootRelativePath] == null) { string absolute = HostingEnvironment.MapPath("~" + rootRelativePath); DateTime date = File.GetLastWriteTime(absolute); int index = rootRelativePath.LastIndexOf('/'); string result = rootRelativePath.Insert(index, "/v-" + date.Ticks); HttpRuntime.Cache.Insert(rootRelativePath, result, new CacheDependency(absolute)); } return HttpRuntime.Cache[rootRelativePath] as string; } } </code></pre> <p>Later i changed the references in all my aspx pages(almost 500 locations) like below.</p> <pre><code>&lt;script type="text/javascript" src="&lt;%=Fingerprint.Tag("/Scripts/JQuery/jquery.color.js")%&gt;"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="&lt;%=Fingerprint.Tag("/Scripts/JQuery/jquery.glowbuttons.js?v=1.1")%&gt;"&gt;&lt;/script&gt; </code></pre> <p>As suggested i have also added the following rewrite rules and installed rewrite module in IIS.</p> <pre><code>&lt;rewrite&gt; &lt;rules&gt; &lt;rule name="fingerprint"&gt; &lt;match url="([\S]+)(/v-[0-9]+/)([\S]+)" /&gt; &lt;action type="Rewrite" url="{R:1}/{R:3}" /&gt; &lt;/rule&gt; &lt;/rules&gt; &lt;/rewrite&gt; </code></pre> <p><strong>Now the problem i am facing</strong></p> <p>This all worked a charm in my development environment. When i published the code to the iis (uat and my local iis) the same code did not work.</p> <p>The <code>Fingerprint.Tag()</code> method returns wrong URLs.</p> <p><strong>My development URL goes like below</strong> </p> <pre><code>http://localhost:54992/login.aspx </code></pre> <p><strong>My IIS website URL goes like below</strong></p> <pre><code>http://www.example.com/myClientName/login.aspx </code></pre> <p>You might have noticed an extra level of url segment <code>(\myClientName\)</code>on IIS, this is what causing the problem.</p> <p>I have also added the logic to add the <code>myClientName</code> part in URL unfortunately that also did not work.</p> <p>On IIS hosted website i gent plenty of 404 errors because the url path skips the <em>myClientName</em> part.</p> <p><strong>UPDATE 1</strong></p> <p>I also tried it with the following another version of same method, which checks if the code is running in iisexpress or on Full IIS and generate the paths accordingly</p> <pre><code> public static string Tag(string rootRelativePath) { if (rootRelativePath.Contains("~")) rootRelativePath = rootRelativePath.Replace("~", string.Empty); bool isRunningInIisExpress = Process.GetCurrentProcess() .ProcessName.ToLower().Contains("iisexpress"); if (HttpRuntime.Cache[rootRelativePath] == null) { string siteAlias = string.Empty; if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["SiteName"])) siteAlias = WebConfigurationManager.AppSettings["SiteName"].ToString(); string absolute = HostingEnvironment.MapPath("~" + rootRelativePath); DateTime date = File.GetLastWriteTime(absolute); int index = rootRelativePath.LastIndexOf('/'); string result = rootRelativePath.Insert(index, "/v-" + date.Ticks); if (!isRunningInIisExpress) { siteAlias = "/" + siteAlias; result = siteAlias + result; } if (File.Exists(absolute)) HttpRuntime.Cache.Insert(rootRelativePath, result, new CacheDependency(absolute)); } return HttpRuntime.Cache[rootRelativePath] as string; } </code></pre> <p>Please guide me to right direction.</p>
2
MongoDb Aggregation (SQL UNION style)
<p>I need some help/advice on how to replicate some SQL behaviour in MongoDB. Specifically, given this collection:</p> <pre><code>{ "_id" : ObjectId("577ebc0660084921141a7857"), "tournament" : "Wimbledon", "player1" : "Agassi", "player2" : "Lendl", "sets" : [{ "score1" : 6, "score2" : 4, "tiebreak" : false }, { "score1" : 7, "score2" : 6, "tiebreak" : true }, { "score1" : 7, "score2" : 6, "tiebreak" : true }] } { "_id" : ObjectId("577ebc3560084921141a7858"), "tournament" : "Wimbledon", "player1" : "Ivanisevic", "player2" : "McEnroe", "sets" : [{ "score1" : 4, "score2" : 6, "tiebreak" : false }, { "score1" : 3, "score2" : 6, "tiebreak" : false }, { "score1" : 6, "score2" : 4, "tiebreak" : false }] } { "_id" : ObjectId("577ebc7560084921141a7859"), "tournament" : "Roland Garros", "player1" : "Navratilova", "player2" : "Graf", "sets" : [{ "score1" : 5, "score2" : 7, "tiebreak" : false }, { "score1" : 6, "score2" : 3, "tiebreak" : false }, { "score1" : 7, "score2" : 7, "tiebreak" : true }, { "score1" : 7, "score2" : 5, "tiebreak" : false }] } </code></pre> <p>And these two distinct aggregations:</p> <p><strong>1) Aggregation ALFA</strong>: this aggregation is purposely strange, in the sense that it is designed to find all matches where <strong>at least 1 tiebreak is true</strong> but <strong>only show sets where tiebreak is false</strong>. Please don't consider the logic of it, it is crafted to allow full freedom to the user.</p> <pre><code>{ $match: { "tournament": "Wimbledon", "sets.tiebreak": true } }, { $project: { "tournament": 1, "player1": 1, "sets": { $filter: { input: "$sets", as: "set", cond: { $eq: ["$$set.tiebreak", false] } } } } } </code></pre> <p><strong>2) Aggregation BETA</strong>: this aggregation is purposely strange, in the sense that it is designed to find all matches where <strong>at least 1 tiebreak is false</strong> but <strong>only show sets where tiebreak is true</strong>. Please don't consider the logic of it, it is crafted to allow full freedom to the user. Please note that <strong>player1</strong> is hidden from the results.</p> <pre><code>{ $match: { "tournament": "Roland Garros", "sets.tiebreak": false } }, { $project: { "tournament": 1, "sets": { $filter: { input: "$sets", as: "set", cond: { $eq: ["$$set.tiebreak", true] } } } } } </code></pre> <p>Now suppose that these two aggregations purpose is to delimit what part of the database a user can see, in the sense that those two queries delimit all the documents (and details) that are visible to the user. This is similar to 2 sql views that user has rights to access.</p> <p><strong>I need/want to try to rewrite the previous distinct aggregations in only one. Can this be achieved?</strong></p> <p>It is mandatory to keep all restriction that were set in Aggregation A &amp; B, without loosing any control on data and without leaking and data that was not available in query A or B.</p> <p>Specifically, matches in Wimbledon can only be seen if they had at least one set which ended with a tiebreak. Player1 field CAN be seen. Single sets must be hidden if they did not end with a tiebreak and hidden otherwise. <em>If needed, it is acceptable, but not desirable, to not see player1 at all.</em></p> <p>Conversely, matches in Roland Garros can be seen only if they had at least one set which ended without a tie break. Player1 field MUST be hidden. Single sets must be seen if they ended with a tiebreak and hidden otherwise.</p> <p>Again, the purpose is to UNION the two aggregations while keeping the limits imposed by the two aggregations.</p> <p>MongoDB is version 3.5, can be upgraded to unstable releases if needed.</p>
2
Hadoop 2 node cluster UI showing 1 live Node
<p>I am trying to configure Hadoop 2.7 2-node cluster.When i start hadoop using start-dfs.sh and start-yarn.sh.All services on master and slave start perfectly.</p> <pre><code>Here is my jps command on my master: 23913 Jps 22140 SecondaryNameNode 22316 ResourceManager 22457 NodeManager 21916 DataNode 21777 NameNode Here is my jps command on my slave: 17223 Jps 14225 DataNode 14363 NodeManager </code></pre> <p>But if i see Hadoop cluster UI it shows only 1 live data node.</p> <pre><code>Here is the dfs admin report : /bin/hdfs dfsadmin -report Live datanodes (1): Name: 192.168.1.104:50010 (nn1.cluster.com) Hostname: nn1.cluster.com Decommission Status : Normal Configured Capacity: 401224601600 (373.67 GB) DFS Used: 237568 (232 KB) Non DFS Used: 48905121792 (45.55 GB) DFS Remaining: 352319242240 (328.12 GB) DFS Used%: 0.00% DFS Remaining%: 87.81% </code></pre> <p>I am able to ssh on all machines. </p> <pre><code>Here is the sample of name node logs(i.p = 192.168.1.104) : 2016-07-12 01:17:34,293 INFO BlockStateChange: BLOCK* processReport: from storage DS-d9ed40cf-bd5d-4033-a6ca-14fb4a8c3587 node DatanodeRegistration(192.168.1.104:50010, datanodeUuid=b702b518-5daa-4fa1-8e69-e4d620a72470, infoPort=50075, infoSecurePort=0, ipcPort=50020, storageInfo=lv=-56;cid=CID-e86d0353-9f33-495b-88fa-16035abd3672;nsid=616310490;c=0), blocks: 24, hasStaleStorage: false, processing time: 0 msecs 2016-07-12 01:17:35,501 INFO org.apache.hadoop.hdfs.StateChange: BLOCK* registerDatanode: from DatanodeRegistration(192.168.1.104:50010, datanodeUuid=37038a9f-23ac-42e2-abea-bdf356aaefbe, infoPort=50075, infoSecurePort=0, ipcPort=50020, storageInfo=lv=-56;cid=CID-e86d0353-9f33-495b-88fa-16035abd3672;nsid=616310490;c=0) storage 37038a9f-23ac-42e2-abea-bdf356aaefbe 2016-07-12 01:17:35,501 INFO org.apache.hadoop.hdfs.server.namenode.NameNode: BLOCK* registerDatanode: 192.168.1.104:50010 2016-07-12 01:17:35,501 INFO org.apache.hadoop.net.NetworkTopology: Removing a node: /default-rack/192.168.1.104:50010 2016-07-12 01:17:35,501 INFO org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor: Number of failed storage changes from 0 to 0 2016-07-12 01:17:35,502 INFO org.apache.hadoop.net.NetworkTopology: Adding a new node: /default-rack/192.168.1.104:50010 2016-07-12 01:17:35,504 INFO org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor: Number of failed storage changes from 0 to 0 2016-07-12 01:17:35,504 INFO org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor: Adding new storage ID DS-495b6b0e-f1fc-407c-bb9f-6c314c2fdaec for DN 192.168.1.104:50010 here is the sample datanode logs (i.p = 192.168.1.104): 2016-07-12 02:02:12,044 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: DatanodeCommand action : DNA_REGISTER from nn1.cluster.com/192.168.1.104:8020 with active state 2016-07-12 02:02:12,045 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Block pool BP-1235752202-192.168.1.104-1468159707934 (Datanode Uuid b702b518-5daa-4fa1-8e69-e4d620a72470) service to nn1.cluster.com/192.168.1.104:8020 beginning handshake with NN 2016-07-12 02:02:12,047 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Block pool Block pool BP-1235752202-192.168.1.104-1468159707934 (Datanode Uuid b702b518-5daa-4fa1-8e69-e4d620a72470) service to nn1.cluster.com/192.168.1.104:8020 successfully registered with NN 2016-07-12 02:02:12,050 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Successfully sent block report 0x236119eb3082, containing 1 storage report(s), of which we sent 1. The reports had 24 total blocks and used 1 RPC(s). This took 0 msec to generate and 1 msecs for RPC and NN processing. Got back one command: FinalizeCommand/5. 2016-07-12 02:02:12,050 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Got finalize command for block pool BP-1235752202-192.168.1.104-1468159707934 2016-07-12 02:02:15,049 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: DatanodeCommand action : DNA_REGISTER from nn1.cluster.com/192.168.1.104:8020 with active state 2016-07-12 02:02:15,052 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Block pool BP-1235752202-192.168.1.104-1468159707934 (Datanode Uuid b702b518-5daa-4fa1-8e69-e4d620a72470) service to nn1.cluster.com/192.168.1.104:8020 beginning handshake with NN 2016-07-12 02:02:15,056 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Block pool Block pool BP-1235752202-192.168.1.104-1468159707934 (Datanode Uuid b702b518-5daa-4fa1-8e69-e4d620a72470) service to nn1.cluster.com/192.168.1.104:8020 successfully registered with NN 2016-07-12 02:02:15,061 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Successfully sent block report 0x2361cd4be40d, containing 1 storage report(s), of which we sent 1. The reports had 24 total blocks and used 1 RPC(s). This took 0 msec to generate and 2 msecs for RPC and NN processing. Got back one command: FinalizeCommand/5. 2016-07-12 02:02:15,061 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Got finalize command for block pool BP-1235752202-192.168.1.104-1468159707934 Here is the sample of 2nd datanode logs(ip :192.168.35.128) 2016-07-12 11:45:07,346 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: DatanodeCommand action : DNA_REGISTER from nn1.cluster.com/192.168.1.104:8020 with active state 2016-07-12 11:45:07,349 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Block pool BP-1235752202-192.168.1.104-1468159707934 (Datanode Uuid 37038a9f-23ac-42e2-abea-bdf356aaefbe) service to nn1.cluster.com/192.168.1.104:8020 beginning handshake with NN 2016-07-12 11:45:07,355 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Block pool Block pool BP-1235752202-192.168.1.104-1468159707934 (Datanode Uuid 37038a9f-23ac-42e2-abea-bdf356aaefbe) service to nn1.cluster.com/192.168.1.104:8020 successfully registered with NN 2016-07-12 11:45:07,364 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Successfully sent block report 0xb0de42ec7c, containing 1 storage report(s), of which we sent 1. The reports had 0 total blocks and used 1 RPC(s). This took 0 msec to generate and 4 msecs for RPC and NN processing. Got back one command: FinalizeCommand/5. 2016-07-12 11:45:07,364 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Got finalize command for block pool BP-1235752202-192.168.1.104-1468159707934 2016-07-12 11:45:10,360 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: DatanodeCommand action : DNA_REGISTER from nn1.cluster.com/192.168.1.104:8020 with active state 2016-07-12 11:45:10,363 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Block pool BP-1235752202-192.168.1.104-1468159707934 (Datanode Uuid 37038a9f-23ac-42e2-abea-bdf356aaefbe) service to nn1.cluster.com/192.168.1.104:8020 beginning handshake with NN 2016-07-12 11:45:10,370 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Block pool Block pool BP-1235752202-192.168.1.104-1468159707934 (Datanode Uuid 37038a9f-23ac-42e2-abea-bdf356aaefbe) service to nn1.cluster.com/192.168.1.104:8020 successfully registered with NN 2016-07-12 11:45:10,377 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Successfully sent block report 0xb191ea9cb9, containing 1 storage report(s), of which we sent 1. The reports had 0 total blocks and used 1 RPC(s). This took 0 msec to generate and 3 msecs for RPC and NN processing. Got back one command: FinalizeCommand/5. 2016-07-12 11:45:10,377 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Got finalize command for block pool BP-1235752202-192.168.1.104-1468159707934 2016-07-12 11:45:13,376 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: DatanodeCommand action : DNA_REGISTER from nn1.cluster.com/192.168.1.104:8020 with active state 2016-07-12 11:45:13,380 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Block pool BP-1235752202-192.168.1.104-1468159707934 (Datanode Uuid 37038a9f-23ac-42e2-abea-bdf356aaefbe) service to nn1.cluster.com/192.168.1.104:8020 beginning handshake with NN 2016-07-12 11:45:13,385 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Block pool Block pool BP-1235752202-192.168.1.104-1468159707934 (Datanode Uuid 37038a9f-23ac-42e2-abea-bdf356aaefbe) service to nn1.cluster.com/192.168.1.104:8020 successfully registered with NN 2016-07-12 11:45:13,395 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Successfully sent block report 0xb245b893c4, containing 1 storage report(s), of which we sent 1. The reports had 0 total blocks and used 1 RPC(s). This took 0 msec to generate and 5 msecs for RPC and NN processing. Got back one command: FinalizeCommand/5. 2016-07-12 11:45:13,396 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Got finalize command for block pool BP-1235752202-192.168.1.104-1468159707934 </code></pre> <p>Why is this happening? Thank you so much for help!</p>
2
How to add eliminate new line character from a byte in c#
<p>I have a code as mentioned below. I have a "inputText" variable which contains the string as well as some new line characters. Just assume my variable inputText contains something like "Test\nTest". So when I get final output I need to remove \n new line char from the string.</p> <pre><code>currentText = Encoding.UTF8.GetString(Encoding.Convert( Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(inputText))); </code></pre>
2
SMS app received messages multiple times
<p>I have built an SMS messaging app, which both sends and receives text messages. In MainActivity, I have a two-dimensional array of people's names and phone numbers, and in my sending class, I have a for loop which sends the same message to all of the recipients by going through each of the numbers:</p> <pre><code>for (i=0; i&lt;names.length; i++) { phoneNo = names[i][2] + names[i][3]; sendMessage(phoneNo, message); } private void sendMessage(String phoneNo, String message) { try { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(phoneNo, null, message, null, null); Toast.makeText(getApplicationContext(), "SMS sent", Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(getApplicationContext(), "SMS failed. Please try again!", Toast.LENGTH_LONG).show(); e.printStackTrace(); } } </code></pre> <p>When I send a message through the app, I can see very clearly from my own Samsung messaging app that the same message gets sent to each of the numbers in the list, which is perfect.</p> <p>This is my shortened receiver class:</p> <pre><code>public class Receiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { Bundle extras = intent.getExtras(); SmsMessage[] smgs = null; String infoSender = ""; String infoSMS = ""; if (extras != null) { // Retrieve the sms message received Object[] pdus = (Object[]) extras.get("pdus"); smgs = new SmsMessage[pdus.length]; for (int i = 0; i &lt; smgs.length; i++) { smgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); infoSender += smgs[i].getOriginatingAddress(); infoSMS += smgs[i].getMessageBody().toString(); } } </code></pre> <p>I have found that despite the message being sent out once to each recipient, some recipients (with this app) receive it more than once consecutively. Hence, I suspected that there was something wrong with my receiver code, which is seemingly treating one received message as several consecutive received messages. This is not a consistent problem, as different people receive the consecutive messages at different times.</p> <p>However, what I've also found is that if I hardcode phoneNo in the sending class to just one phone number, or if I have only one phone number in the array in MainActivity, then this problem doesn't occur. The message still gets sent out once to that one phone number only, but the receiver will always receive it just once as intended.</p> <p>I am so confused by this now, so can somebody please give some suggestions as to what I could try? Literally in the last minute, I thought that it could be a problem with createFromPdu being deprecated? If so, please advise how to change my receiver code, as I couldn't find anything which resembles my current code too much.</p> <p>Many thanks in advance:-)</p>
2
C++ - Failing to parse CSV into my struct
<p>I have a CSV with the following format:</p> <pre><code>date,fruit,quantity1,quantity2,quantity3 2016-07-14,banana,3,20,6 2016-07-14,banana,3,50,15 2016-07-14,banana,0,25,15 2016-07-14,banana,3,25,6 2016-07-14,apple,3,10,20.5 2016-07-14,apple,0,30,5 2016-07-14,apple,0,5,30 2016-07-14,peach,3,10,30.2 2016-07-14,peach,3,40,4 2016-07-14,peach,3,10,12 2016-07-14,peach,0,10,8 2016-07-14,peach,3,200,3 </code></pre> <p>I want to parse this file and store it in a struct. But I am getting a stack overflow error. Where is it failing exactly? Is it because of clashing data types in the struct? Some of the data types are a float and I'm trying to use getline and a temporary string variable to store the info.</p> <p>Here is the complete code:</p> <pre><code>#include "stdafx.h" #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;string&gt; using namespace std; struct FruitInventory { string date; string fruit; float quantity1; float quantity2; float quantity3; }; int main() { ifstream myfile; myfile.open("fruit_inventory.csv", ios::in); string line; FruitInventory todaysFruitSupply[15000]; int i = 0; int lineCount = 0; while (myfile.good()) { getline(myfile, line); stringstream mystream(line); string temp; if (i &gt; 0) //ignore header line { getline(mystream, todaysFruitSupply[i].date, ','); getline(mystream, todaysFruitSupply[i].fruit, ','); getline(mystream, temp, ','); todaysFruitSupply[i].quantity1 = stof(temp); getline(mystream, temp, ','); todaysFruitSupply[i].quantity2 = stof(temp); getline(mystream, temp, ','); todaysFruitSupply[i].quantity3 = stof(temp); } i++; lineCount++; } myfile.close(); system("pause"); return 0; } </code></pre> <p>EDIT: It was breaking on the last line of the file because there was a new-line character. After deleting that, it now executes completely. How can I make sure it can handle that correctly in the future?</p>
2
Accessing data-xxx attribute values with jquery
<p>In Chrome console I can access(select) a required element and see the content as bellow:</p> <pre><code>&gt; x = $(".sidebar-message a[data-id ='" + 2885 + "']")[0] &lt;a href=​"#" data-id=​"2885" data-uid=​"197025959" data-mobile=​"08021111134" data-lastname=​"Aliu" data-firstname=​"Isa" data-verified=​"true" data-assigned=​"false"&gt;​…​&lt;/a&gt;​ </code></pre> <p>Please how do i access the data-mobile , data-lastname etc using jQuery?</p> <p>I tried <code>x.data-mobile</code> and <code>x[data-mobile]</code>, both are <em><code>undefined</code></em></p>
2
Android Robolectric and vector drawables
<p>I am using some vector drawables in my app but only for v21 and up - they are in the resource folder drawable-anydpi-v21 and also have fallback bitmap versions for the other api levels (drawable-hdpi.mdpi,...).</p> <p>When I run a robolectric with this config</p> <pre><code>@Config(sdk = 16, application = MyApp.class, constants = BuildConfig.class, packageName = "com.company.app") </code></pre> <p>I get the following error on inflate of the views using these drawables</p> <pre><code>Caused by: android.content.res.Resources$NotFoundException: File ./app/build/intermediates/data-binding-layout-out/dev/debug/drawable-anydpi-v21/ic_info_outline_white_24dp.xml from drawable resource ID #0x7f02010e Caused by: org.xmlpull.v1.XmlPullParserException: XML file ./app/build/intermediates/data-binding-layout-out/dev/debug/drawable-anydpi-v21/ic_info_outline_white_24dp.xml line #-1 (sorry, not yet implemented): invalid drawable tag vector </code></pre> <p>the relevant parts of the build.gradle are:</p> <pre><code> android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { applicationId "com.example.app" minSdkVersion 16 targetSdkVersion 23 versionCode 79 versionName "0.39" // Enabling multidex support. multiDexEnabled true vectorDrawables.useSupportLibrary = true testApplicationId "com.example.app.test" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } testOptions { unitTests.returnDefaultValues = true } } dependencies { compile 'com.android.support:support-vector-drawable:23.4.0' testCompile "org.robolectric:robolectric:3.1" testCompile "org.robolectric:shadows-multidex:3.1" testCompile "org.robolectric:shadows-support-v4:3.1" } </code></pre> <p>So it looks as though even though i have specified sdk=16 Robolectric seems to take the drawables from drawable-anydpi-v21. </p> <ol> <li><p>Is this a bug is roboelectric? or</p></li> <li><p>Is there a better way to specify what the APK level is? or</p></li> <li><p>Is there a way to let roboelectric read the vector tag? or</p></li> <li><p>Some other way of doing it?</p></li> </ol>
2
Using Ajax to create session and echo results
<p>I'm trying my best to get this to work. But AJAX is pretty new to me. So hang in there... </p> <p>Ok, I've asked a couple of questions here about getting this issue that I'm having to work. I (We)'ve come a long way. But now the next issue is here.</p> <p>I'm trying to <em>echo a session</em> in a div using <strong>AJAX</strong>. The AJAX code is working, I can echo plain text to the div I want it to go. <em>The only problem I have is it does not display the title of the item.</em></p> <p>I have some items (lets say 3 for this example) and I would like to have the custom save the Items in a Session. So when the customer clicks on save. The ajax div displays the title. And if the custom clicks the 3rd item it show the 1st and 3rd item, etc...</p> <p><strong>My HTML:</strong> </p> <pre><code>&lt;button type="submit" class="btn btn-primary text-right" data-toggle="modal" data-target=".post-&lt;?php the_ID(); ?&gt;" data-attribute="&lt;?php the_title(); ?&gt;" data-whatever="&lt;?php the_title(); ?&gt;"&gt;Sla deze boot op &lt;span class="glyphicon glyphicon-heart" aria-hidden="true"&gt;&lt;/span&gt;&lt;/button&gt; </code></pre> <p><strong>My AJAX code:</strong></p> <pre><code>$(".ajaxform").submit(function(event){ event.preventDefault(); $.ajax({ type: "POST", url: "example.com/reload.php", success: function(data) { $(".txtHint").html(data); }, error: function() { alert('Not OKay'); } }); return false; }); </code></pre> <p>My PHP <strong>reload.php</strong>:</p> <pre><code>&lt;h4&gt;Saved Items&lt;/h4&gt; &lt;p&gt;Blaat...&lt;/p&gt; &lt;?php echo "Product Name = ". $_SESSION['item'];?&gt; </code></pre> <p>I saw this code on here: <em>I'm not using this code. Only wondering if I can use it for my code, and then how?</em></p> <p>Change session.php to this:</p> <pre><code>&lt;?php session_start(); // store session data $_SESSION['productName'] = $_POST['productName']; //retrieve session data echo "Product Name = ". $_SESSION['productName']; ?&gt; </code></pre> <p>And in your HTML code:</p> <pre><code>function addCart(){ var brandName = $('iframe').contents().find('.section01a h2').text(); $.post("sessions.php", {"name": brandName}, function(results) { $('#SOME-ELEMENT').html(results); }); } </code></pre> <p>How I'm getting my title();:</p> <pre><code>&lt;?php // Set session variables $_SESSION["item"][] = get_the_title(); ?&gt; </code></pre> <p>Is this some thing I can use? And could someone help me with the code?</p> <p>Thanks in advance!</p>
2
c# rules about: a mod b, while a is bigger than b
<p>I was examining a code about operator overloading, and I saw an interesting way of use of % to convert seconds to minutes if second variable is bigger than 59.</p> <p>It seems while <code>a&lt;b</code> (both int) <code>a%b</code> returns a, I havent read a rule about this before, I wanna learn why it returns a, is it about they are declared as integers, are there any more rules about %?</p> <p>Thanks</p>
2
The page isn't redirecting properly in asp.net
<p>I am trying to publish my website to the server .So i published that and i got a lot of errors,i fixed them ,i get another error <code>The page isn't redirecting properly in asp.net</code> when i call the url .</p> <p>When i call a picture from my website for example <code>127.0.0.1/i.png</code> it works and the ie shows me the picture but when i call <code>127.0.0.1/fa/default.aspx</code> i get this error :</p> <p><a href="https://i.stack.imgur.com/msUNz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/msUNz.png" alt="enter image description here"></a></p> <p>Here is my web.config</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --&gt; &lt;configuration&gt; &lt;connectionStrings&gt; &lt;add name="BaHamayeshban" connectionString="Data Source=(local);Initial Catalog= hamayeshban.ir_conf.qums;integrate security=true;" providerName="System.Data.SqlClient" /&gt; &lt;/connectionStrings&gt; &lt;system.webServer&gt; &lt;validation validateIntegratedModeConfiguration="false"/&gt; &lt;handlers&gt; &lt;remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit"/&gt; &lt;remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"/&gt; &lt;remove name="ExtensionlessUrlHandler-Integrated-4.0"/&gt; &lt;add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0"/&gt; &lt;add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0"/&gt; &lt;add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/&gt; &lt;/handlers&gt; &lt;security&gt; &lt;requestFiltering&gt; &lt;requestLimits maxAllowedContentLength="1073741824"/&gt; &lt;/requestFiltering&gt; &lt;/security&gt; &lt;/system.webServer&gt; &lt;system.web&gt; &lt;compilation debug="true" targetFramework="4.5"/&gt; &lt;httpRuntime maxRequestLength="1048576"/&gt; &lt;pages controlRenderingCompatibilityVersion="4.0" clientIDMode="AutoID"/&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <p>actually the IIS doesn't show me the resource of the error ,and i couldn't find the error resource.</p> <p>Here is the iis folder </p> <p><a href="https://i.stack.imgur.com/11hxu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/11hxu.png" alt="enter image description here"></a> Best regards</p>
2
A Codility test that needs to be solved
<p>I can not understand the question, can someone clarify it a little bit ?</p> <p>Update : here is my solution using Kadane algorithm but it fails at the following arrays:</p> <pre><code>Example test: [-8, 3, 0, 5, -3, 12] WRONG ANSWER (got 17 expected 12) Example test: [-1, 2, 1, 2, 0, 2, 1, -3, 4, 3, 0, -1] WRONG ANSWER (got 12 expected 8) int max_so_far = 0, max_ending_here = 0; for (int i = 0; i &lt; A.size(); i++) { max_ending_here = max_ending_here + A[i]; if (max_ending_here &lt; 0) max_ending_here = 0; if (max_so_far &lt; max_ending_here) max_so_far = max_ending_here; } return max_so_far; </code></pre>
2
Find Repeating Sublist Within Large List
<p>I have a large list of sub-lists (approx. 16000) that I want to find where the repeating pattern starts and ends. I am not 100% sure that there is a repeat, however I have a strong reason to believe so, due to the diagonals that appear within the sub-list sequence. The structure of a list of sub-lists is preferred, as it is used that way for other things in this script. The data looks like this:</p> <pre><code>data = ['1100100100000010', '1001001000000110', '0010010000001100', '0100100000011011', etc </code></pre> <p>I do not have any time constraints, however the fastest method would not be frown upon. The code should be able to return the starting/ending sequence and location within the list, to be called upon in the future. If there is an arrangement of the data that would be more useful, I can try to reformat it if necessary. Python is something that I have been learning for the past few months, so I am not quite able to just create my own algorithms from scratch just yet. Thank you! </p>
2
Invalid Data in Excel File. Index was outside the bounds of the array.C#
<p>Cant find answer in any of the suggestions.I am trying to upload an excel file to the postgre Db.</p> <p><strong>Here is the C# code :</strong></p> <pre><code> public static List&lt;Common.Transactions.TransactionDetail&gt; GetTransactionDetails(string path) { if (!File.Exists(path)) { return null; } var transactionDetails = new List&lt;Common.Transactions.TransactionDetail&gt;(); foreach (var sheet in Workbook.Worksheets(path)) { int officeId = 0; foreach (var row in sheet.Rows.Skip(1)) { var td = new Common.Transactions.TransactionDetail { GlAccountId = Core.GlAccounts.GetGlAcccountId(row.Cells[1]?.Text), AccountNumberId = Deposit.AccountHolders.GetAccountNumberId(row.Cells[2]?.Text), ShareAccountId = Core.ShareAccounts.GetShareAccountId(row.Cells[3]?.Text), LoanId = Loan.LoanAccounts.GetLoanId(row.Cells[4]?.Text), Debit = row.Cells[5]?.Text.ToDecimal(), Credit = row.Cells[6]?.Text.ToDecimal(), StatementReference = row.Cells[7]?.Text }; if (row.Cells[7] != null) { td.OfficeId = Office.Offices.GetOfficeIdByCode(row.Cells[7]?.Text); officeId = Office.Offices.GetOfficeIdByCode(row.Cells[7]?.Text); } if (td.AccountNumberId == 0) { td.AccountNumberId = null; } if (td.LoanId == 0) { td.LoanId = null; } if (td.ShareAccountId == 0) { td.ShareAccountId = null; } if (row.Cells[0] != null) { td.AccountName = row.Cells[0].Text; } if (row.Cells[1] != null &amp;&amp; string.IsNullOrWhiteSpace(td.AccountName)) { td.AccountName = row.Cells[1].Text; } if (row.Cells[2] != null &amp;&amp; string.IsNullOrWhiteSpace(td.AccountName)) { td.AccountName = row.Cells[2].Text; } if (row.Cells[3] != null &amp;&amp; string.IsNullOrWhiteSpace(td.AccountName)) { td.AccountName = row.Cells[3].Text; } #region OfficeId if (td.AccountNumberId != null) { officeId = Deposit.AccountHolders.GetAccountOfficeId(td.AccountNumberId.ToLong()); } if (td.LoanId != null) { officeId = Loan.LoanGrant.GetAccountOfficeId(td.LoanId.ToLong()); } if (td.ShareAccountId != null) { officeId = Core.ShareAccounts.GetAccountOfficeId(td.ShareAccountId.ToLong()); } #endregion td.OfficeId = officeId != 0 ? officeId : SessionHelper.GetOfficeId(); td.OfficeCode = Office.Offices.GetOfficeCode(officeId); transactionDetails.Add(td); } } foreach (var detail in transactionDetails) { if (detail.Debit.ToDecimal() &gt; 0 &amp;&amp; detail.Credit &gt; 0) { throw new TransactionDetailException( $@"Invalid transaction. Either debit or credit should be null for '{detail.AccountName}'."); } if (detail.AccountNumberId &gt; 0) { if (detail.Debit.ToDecimal() &gt; 0) { if (detail.Debit &gt; Deposit.AccountHolders.GetDepositAccountBalance(detail.AccountNumberId.ToLong())) { throw new TransactionDetailException( $@"Insufficient balance in account '{detail.AccountName}'."); } } detail.GlAccountId = Deposit.AccountHolders.GetGlAccountId(detail.AccountNumberId); } if (detail.ShareAccountId &gt; 0) { if (detail.Debit.ToDecimal() &gt; 0) { if (detail.Debit &gt; Core.ShareAccounts.GetShareBalance(detail.ShareAccountId.ToLong())) { throw new TransactionDetailException( $@"Insufficient balance in account '{detail.AccountName}'."); } } detail.GlAccountId = Core.ShareAccounts.GetGlAccountId(detail.ShareAccountId.ToLong()); } if (detail.LoanId &gt; 0) { if (detail.Credit.ToDecimal() &gt; 0) { if (detail.Credit &gt; Loan.LoanAccounts.GetLoanCollectionBalance(detail.LoanId.ToLong(), Core.DateConversion.GetCurrentServerDate())) { throw new TransactionDetailException( $@"Insufficient balance in account '{detail.AccountName}'."); } } detail.GlAccountId = Loan.LoanGrant.GetLoanTransactionGLAccountId(detail.LoanId.ToLong()); } detail.AuditUserId = Common.Helpers.SessionHelper.GetUserId(); detail.AccountNumberId = detail.AccountNumberId &lt;= 0 ? null : detail.AccountNumberId; detail.LoanId = detail.LoanId &lt;= 0 ? null : detail.LoanId; detail.ShareAccountId = detail.ShareAccountId &lt;= 0 ? null : detail.ShareAccountId; detail.EnableDeleteButton = true; if (detail.GlAccountId == 0) { throw new TransactionDetailException($@"{detail.AccountName} is not a valid account."); } } return transactionDetails; } } </code></pre> <p>I get error Index was outside the bounds of array.Invalid excel data.</p> <p><strong>My excel data</strong> </p> <pre><code>Gl Account Deposit A/C Share A/C Loan A/C Debit Credit Statement Reference </code></pre> <p>Loss Recovery Fund 0 1000 uploaded from excel Risk Coverage Fund 0 1106 uploaded from excel</p>
2
How to create transparent controls in Windows Forms when controls are layered
<p>I am trying to implement a "Fillable Form" in which editable text fields appear over top of an image of a pre-preprinted form for a dot matrix printer. (using c# and Windows Forms and targeting .Net 2.0) My first idea was to use the image as the Windows Form background, but it looked horrible when scrolling and also did not scroll properly with the content.</p> <p>My next attempt was to create a fixed-size window with a panel that overflows the bounds of the window (for scrolling purposes.) I added a PictureBox to the panel, and added my textboxes on top of it. This works fine, except that TextBoxes do not support transparency, so I tried several methods to make the TextBoxes transparent. One approach was to use an odd background color and a transparency key. Another, described in the following links, was to create a derived class that allows transparency:</p> <p><a href="https://stackoverflow.com/questions/16050249/transparency-for-windows-forms-textbox">Transparency for windows forms textbox</a></p> <p><a href="https://stackoverflow.com/questions/5557365/textbox-with-a-transparent-background">TextBox with a Transparent Background </a></p> <p>Neither method works, because as I have come to find out, "transparency" in Windows Forms just means that the background of the window is painted onto the control background. Since the PictureBox is positioned between the Window background and the TextBox, it gives the appearance that the TextBox is not transparent, but simply has a background color equal to the background color of the Window. With the transparency key approach, the entire application becomes transparent so that you can see Visual Studio in the background, which is not what I want. So now I am trying to implement a class that derives from TextBox and overrides either OnPaint or OnPaintBackground to paint the appropriate part of the PictureBox image onto the control background to give the illusion of transparency as described in the following link:</p> <p><a href="https://stackoverflow.com/questions/592538/how-to-create-a-transparent-control-which-works-when-on-top-of-other-controls">How to create a transparent control which works when on top of other controls?</a></p> <p>First of all, I can't get it working (I have tried various things, and either get a completely black control, or just a standard label background), and second of all, I get intermittent ArgumentExceptions from the DrawToBitmap method that have the cryptic message "Additional information: targetBounds." Based on the following link from MSDN, I believe that this is because the bitmap is too large - in either event it seems inefficient to capture the whole form image here because I really just want a tiny piece of it.</p> <p><a href="https://msdn.microsoft.com/en-us/library/system.windows.forms.control.drawtobitmap(v=vs.100).aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/system.windows.forms.control.drawtobitmap(v=vs.100).aspx</a></p> <p>Here is my latest attempt. Can somebody please help me with the OnPaintBackground implementation or suggest a different approach? Thanks in advance!</p> <pre><code>public partial class TransparentTextbox : TextBox { public TransparentTextbox() { InitializeComponent(); SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true); } protected override void OnPaintBackground(PaintEventArgs e) { //base.OnPaintBackground(e); // not sure whether I need this if (Parent != null) { foreach (Control c in Parent.Controls) { if (c.GetType() == typeof(PictureBox)) { PictureBox formImg = (PictureBox)c; Bitmap bitmap = new Bitmap(formImg.Width, formImg.Height); formImg.DrawToBitmap(bitmap, formImg.Bounds); e.Graphics.DrawImage(bitmap, -Left, -Top); break; } } Debug.WriteLine(Name + " didn't find the PictureBox."); } } } </code></pre> <p>NOTE: This has been tagged as a duplicate, but I referenced the "duplicate question" in my original post, and explained why it was not working. That solution only works if the TextBox sits directly over the Window - if another control (such as my Panel and PictureBox) sit between the window and the TextBox, then .Net draws the Window background onto the TextBox background, effectively making its background look gray, not transparent.</p>
2
How to Add Data Validation in a Column with leading Zero
<p>For example I want the data in my Column A to be in 4digits whole number only.</p> <pre><code>1111 2222 3333 4444 0033 0032 </code></pre> <p>Now, I've added a data validation in this column, </p> <pre><code>Allow = Whole Number Min = 0 Max = 9999 </code></pre> <p>Now, What if the data contains "0" at the beginning? How can I include this value?</p> <p>Also, I've tried the formula below but it will not retain the leading zero.</p> <pre><code>=IF(LEN(A1),MOD(A1,1)=0,"") </code></pre>
2
Tint Android vector menu icons through XML
<p>I've read answers and blog posts explaining VectorDrawables in Android and how they can be used instead of PNG files of different pixel densities.</p> <p>I've seen that there is an <code>android:tint</code> XML attribute that can be used on <code>ImageButton</code>s and similar <code>View</code>s, but I want to be able to apply a tint to vector icons I use as menu items, as you are unable to use <code>android:tint</code> on menu items.</p> <p><a href="http://www.murrayc.com/permalink/2014/11/11/android-changing-action-icon-colors-with-android-5-0s-drawable-tinting/" rel="noreferrer">One blog post</a> explained that tinted drawables can be created like so:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/ic_action_something" android:tint="@color/color_action_icons_tint"/&gt; </code></pre> <p>where the XML file above is the tinted drawable, the referenced drawable through <code>src</code> is the original vector (black), and the <code>tint</code> is the colour that the icon will be tinted to.</p> <p>However, the above did not work for me, giving me the following error:</p> <pre><code>android.content.res.Resources$NotFoundException: File res/drawable/ic_chevron_left_white_24dp.xml from drawable resource ID #0x7f02007e at android.content.res.Resources.loadDrawableForCookie(Resources.java:3735) at android.content.res.Resources.loadDrawable(Resources.java:3603) at android.content.res.Resources.getDrawable(Resources.java:1852) at android.content.Context.getDrawable(Context.java:408) at android.support.v4.content.ContextCompatApi21.getDrawable(ContextCompatApi21.java:26) at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:352) at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:193) at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:181) at ... Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #2: &lt;bitmap&gt; requires a valid src attribute at android.graphics.drawable.BitmapDrawable.updateStateFromTypedArray(BitmapDrawable.java:761) at android.graphics.drawable.BitmapDrawable.inflate(BitmapDrawable.java:726) at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:1150) at android.graphics.drawable.Drawable.createFromXml(Drawable.java:1063) at android.content.res.Resources.loadDrawableForCookie(Resources.java:3719) at android.content.res.Resources.loadDrawable(Resources.java:3603)  at android.content.res.Resources.getDrawable(Resources.java:1852)  at android.content.Context.getDrawable(Context.java:408)  at android.support.v4.content.ContextCompatApi21.getDrawable(ContextCompatApi21.java:26)  at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:352)  at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:193)  at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:181)  at ... </code></pre> <hr> <p><strong>Edit:</strong> This is my drawable <code>ic_chevron_left_white_24dp.xml</code>:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/ic_chevron_left_black_24dp" android:tint="@color/white"/&gt; </code></pre> <p>Both the above file, and the referenced one exist.</p> <hr> <p>Furthermore, with the above, my IDE (Android Studio) displays this warning:</p> <blockquote> <p>Rendering Problems : requires a valid 'src' attribute</p> </blockquote> <p>This leads me to the question - how can I tint an XML vector drawable menu icon?</p> <p>I am aware I can create a copy of the vector and change the <code>fillColor</code> attribute to the colour I want, but apart from this, is there a way to do it non-programmatically?</p>
2
Extending or overwriting a docstring when composing classes
<p>I have a class <code>MyClass</code>:</p> <pre><code>class MyClass(object): def __init__(self): pass def my_function(self, x): # MyClass.my_function.__doc__ is not writable! # Otherwise, I could just set it here. Origin.func(self, x) </code></pre> <p>The class borrows from <code>Origin</code>:</p> <pre><code>class Origin(object): def func(obj, x): """This is a function """ # do stuff pass </code></pre> <p>How can I copy the docstring from Origin.func to MyClass.my_function automatically so that Sphinx Autodoc recognises it? And how can I extend the original docstring by a couple of words?</p> <p><em>Edit:</em></p> <p>Afaik, I cannot just change <code>__doc__</code> after the definition of the function since Sphinx would not find it then. Or if it did, where would the "docfix" go?</p>
2
How to save multiple images from database to TMemoryStream at runtime and extract them later on
<p>I am creating a project at delphi(RAD Studio). There are images stored at database table at some rows. I want to extract images at runtime (for which I am using Array of TMemoryStream) and show them at frxReport.</p> <p>My code snippet as follows</p> <p>Public variable TStream is declared as</p> <p><code>Stream2 : Array of TStream; i,k: integer</code></p> <p>Code segment for view button click event, which is placed on MainForm and expected to show frxReport.</p> <p>`</p> <pre><code>procedure TFrmMain.btnViewClick(Sender: TObject); begin i := 0; k := 0; UniTable1.SQL.Text := 'Select * from userplays order by id'; UniTable1.Execute; rowcount := UniTable1.RecordCount; SetLength(myid, rowcount); SetLength(mydesc, rowcount); SetLength(myimg, rowcount); SetLength(Stream2, rowcount); while not UniTable1.Eof do begin try Stream2[k] := TMemoryStream.Create; myid[k] := UniTable1.FieldByName('id').Value; Stream2[k] := UniTable1.CreateBlobStream(TBlobField(UniTable1.FieldByName('image')), bmRead); mydesc[k] := UniTable1.FieldByName('description').Value; UniTable1.Next; inc(k); finally //Stream2[k].Free; end; end; frxUserDataSet1.RangeEnd := reCount; frxUserDataSet1.RangeEndCount := rowcount; frxReport1.ShowReport; i := 0; end; </code></pre> <p>`</p> <p>However this method is not loading any image to Stream2 array. There is an option to use array of JPEGImage however if JPEGImage array used then it would be problem to display it on frxRaport at</p> <p><code> procedure TFrmMain.frxReport1GetValue(const VarName: string; var Value: Variant); </code></p> <p>`</p> <pre><code>Graphic := TJPEGImage.Create; Graphic.LoadFromStream(Stream2[j]); TfrxPictureView(frxreport1.FindObject('Picture1')).Picture.Graphic := Graphic; </code></pre> <p>` Kindly let me know how to do this.</p>
2
Java class has 2 methods with the same function signature but different return types
<p>AFAIK it's not possible to have a method with the same call signature. However:</p> <pre><code>$ javap -public java.time.LocalTime | grep "minus" | grep "Temporal" | grep -v "long" public java.time.LocalTime minus(java.time.temporal.TemporalAmount); public java.time.temporal.Temporal minus(java.time.temporal.TemporalAmount); </code></pre> <p>These clearly show multiple methods with the same call signature. </p> <ol> <li>How does Java resolve the function call? </li> <li>Why are there multiple functions?</li> </ol> <p>EDIT: Simplified the question by keeping only the relevant bit.</p>
2
XMLHttpRequest in Edge (responseURL property)
<p>Basically I use the responseURL variable that XMLHttpRequest's give back. The problem is for some reason my code wasn't working on Microsoft Edge, but it was on Chrome/Firefox.</p> <p>You will also notice that the responseURL property isn't in the Edge docs, <a href="https://msdn.microsoft.com/en-us/library/ms535874(v=vs.85).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/ms535874(v=vs.85).aspx</a></p> <p>but is in the Mozilla docs</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest?redirectlocale=en-US&amp;redirectslug=DOM%2FXMLHttpRequest" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest?redirectlocale=en-US&amp;redirectslug=DOM%2FXMLHttpRequest</a></p> <p><br> <strong>Is the responseURL property not available on Microsoft Edge? If so, are there any alternatives I can use?</strong></p>
2
Initializing an `atomic_int` with a braced constant: Is this valid C code? If so why does it not compile in clang?
<p>I'm porting some code from C11 to C++. The project compiles fine in <code>gcc</code> and <code>g++</code> but <code>clang</code> refuses to compile it. The offending lines are shown below:</p> <pre><code>static atomic_int sem = {0}; </code></pre> <blockquote> <p>src/testdir.c:27:25: error: illegal initializer type 'atomic_int' (aka '_Atomic(int)')</p> </blockquote> <p>and</p> <pre><code>struct container { volatile atomic_ullong workerThreadCount; struct cfgoptions *config; repaircmd_t *cmd; }; Container container = {{0}, s, NULL}; </code></pre> <blockquote> <p>src/testdir.c:334:25: error: illegal initializer type 'volatile atomic_ullong' (aka 'volatile _Atomic(unsigned long long)')</p> </blockquote> <p>Clang: clang version 3.7.0 (tags/RELEASE_370/final)</p> <p>gcc: gcc (GCC) 5.3.1 20160406 (Red Hat 5.3.1-6)</p> <p>Operating system: Fedora 23</p> <p>Test code: <a href="https://gist.github.com/clockley/eb42964003a2e4fe6de97d5b192d61d3" rel="nofollow">https://gist.github.com/clockley/eb42964003a2e4fe6de97d5b192d61d3</a></p> <p>P.S i = {0} or i(0) are the only valid initializers in C++ as atomic ints are not primitive types of the two only the former is valid C.</p>
2
Faster alternative to STL std::map
<p>I do have a data structure:</p> <pre><code>typedef std::pair&lt;boost::shared_ptr&lt;X&gt;, boost::shared_ptr&lt;X&gt; &gt; pair_ptr; std::map&lt; pair_ptr, int &gt; </code></pre> <p>that I use in a iterative process. In each iteration I <em>need</em> to copy the the std::map and possibly destroy one copy. However, the std::map can become large, over 100k elements. This significantly slows down the program. I've defined the operator&lt; as:</p> <pre><code> inline bool operator&lt;(const pair_ptr&amp; a, const pair_ptr&amp; b) { return (a.first &lt; b.first) or (a.first == b.first and a.second &lt; b.second); } </code></pre> <p>I use the std::map copy constructor and destructor. Is there a faster alternative?</p>
2
How to select a sheet via a counter variable in vba?
<p>I want to select sheets in an excel document. They are all named, but I know that you can select a sheet using its intrinsic number (ie. even though the second sheet created is named "risk ranking", I can still select it via Sheet2.select). Is there anyway to set this up using a counter variable? Here is a simplified and isolated code line from the macro:</p> <pre><code>counter = 0 Sheet &amp; counter &amp; .Select counter = counter + 1 </code></pre> <p>Anyone have any ideas?</p>
2
Scala Try/Catch block in Scala fails to catch Exception
<p>In the code below, when a ConnectException is thrown by the first line inside the try block, it is not caught. I am rethrowing the exception as the original exception message, "Connection Refused", is not useful for debugging, so I am adding some more information. However, my exception with the "Failed to connect..." message is never displayed. I only ever see the original "Connection Refused" exception message.</p> <pre><code>private[this] def getClient(system: ActorSystem, config: Config): ConfigException Xor Conn = for { natsConfig &lt;- config.configAt("messaging.nats") userName &lt;- natsConfig.readString("user") password &lt;- natsConfig.readString("password") host &lt;- natsConfig.readString("host") port &lt;- natsConfig.readString("port") } yield { val props = new Properties() props.put("servers", "nats://" + userName + ":" + password + "@" + host + ":" + port) log.debug("NATS connection properties:" + props.getProperty("servers")) try { val client = Conn.connect(props) system.registerOnTermination { client.close() } client } catch { case ex:ConnectException =&gt; throw new ConnectException("Failed to connect to nats using props:" + props.getProperty("servers")) } } </code></pre> <p>The output I get is:</p> <blockquote> <p>I|16:25:15.561|o.g.s.messaging.MessageBusManager$|Starting NATS java.net.ConnectException: Connection refused at sun.nio.ch.Net.connect0(Native Method) at sun.nio.ch.Net.connect(Net.java:454) at sun.nio.ch.Net.connect(Net.java:446) at sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:648) at java.nio.channels.SocketChannel.open(SocketChannel.java:189) at org.nats.Connection.connect(Connection.java:211) at org.nats.Connection.(Connection.java:164) at org.nats.Conn.(Conn.scala:5) at org.nats.Conn$.connect(Conn.scala:68) at org.genivi.sota.messaging.nats.NatsClient$$anonfun$getClient$1$$anonfun$apply$3$$anonfun$apply$4$$anonfun$apply$5$$anonfun$apply$6.apply(NatsClient.scala:30)</p> </blockquote> <p>Note the exception message, which does not match the one in the catch block. NatsClient:30 is the first line of the catch block</p> <p>The code above is trying to connect to a NATS messaging server using scala_nats. Even if I change the catch case to Throwable, the exception is still not caught. However, if I throw a ConnectException in the first line of the try, that exception is caught. I have also tried adding <em>root</em> to my imports to ensure there is no namespace conflicts, to no avail.</p> <p>Under what circumstances can Scala fail to catch exceptions here?</p>
2
Why is this macro generating a syntax error?
<p>So this is my code:</p> <pre><code>// Defines a tuple #define __WINDOW__RESOLUTION__ 500, 200 // Seperate the tuple #define __WINDOW__X__1(Width, Height) (Width) #define __WINDOW__Y__1(Width, Height) (Height) // Add another sort of indirection because my tuple is a macro #define __WINDOW__X__(Macro) __WINDOW__X__1(Macro) #define __WINDOW__Y__(Macro) __WINDOW__Y__1(Macro) // These should be the final values 500 and 200 #define __WINDOW__RESOLUTION__X__ (__WINDOW__X__(__WINDOW__RESOLUTION__)) #define __WINDOW__RESOLUTION__Y__ (__WINDOW__Y__(__WINDOW__RESOLUTION__)) </code></pre> <p>When i use the first macro where the final number should be something seems to go wrong:</p> <pre><code>std::cout &lt;&lt; __WINDOW__RESOLUTION__X__ &lt;&lt; std::endl; // Outputs 200 instead of 500 </code></pre> <p>above line outputs the number 200, so the Y value instead of the X value</p> <pre><code>std::cout &lt;&lt; __WINDOW__RESOLUTION__Y__ &lt;&lt; std::endl; // ERR with macro underlined </code></pre> <p>this line won't even compile [ C2059, syntax error: ")" ]</p> <p>Thank you for helping me Alex</p>
2