title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
ng-repeat hide a property if its equals DateTime.MinValue
<p>Im trying to <em>hide cells</em> (not the complete row) containg a date that is equal to <code>DateTime.MinValue</code> which is basically <code>0001-01-01T00:00:00</code>.</p> <p>Here is my view model:</p> <pre><code>$scope.vm.users = [ { "Username": "user1", "EarliestLogin": "0001-01-01T00:00:00", "LatestLogin": "0001-01-01T00:00:00" }, { "Username": "user2", "EarliestLogin": "2016-07-15T11:18:19Z", "LatestLogin": "2016-07-15T11:18:19Z" }, { "Username": "user3", "EarliestLogin": "0001-01-01T00:00:00", "LatestLogin": "0001-01-01T00:00:00" } ]; </code></pre> <p>The table looks like that:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;th&gt;User Name&lt;/th&gt; &lt;th&gt;Earliest Login&lt;/th&gt; &lt;th&gt;Latest Login&lt;/th&gt; &lt;/tr&gt; &lt;tr ng-repeat="user in vm.users"&gt; &lt;td&gt;{{user.Username}}&lt;/td&gt; &lt;td&gt;{{user.EarliestLogin | date:'short'}}&lt;/td&gt; &lt;td&gt;{{user.LatestLogin | date:'short'}}&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <hr> <p><strong>Current Output:</strong></p> <pre><code>User Name Earliest Login Latest Login user1 1/1/01 12:00 AM 1/1/01 12:00 AM user2 7/15/16 1:18 PM 7/15/16 1:18 PM user3 1/1/01 12:00 AM 1/1/01 12:00 AM </code></pre> <p><strong>Desired Output:</strong></p> <pre><code>User Name Earliest Login Latest Login user1 user2 7/15/16 1:18 PM 7/15/16 1:18 PM user3 </code></pre> <hr> <p>I was able to hide the complete row using a filter on the <code>ng-repeat</code> but I don't know how to only hide a cell if its <code>DateTime.MinValue</code>...</p> <p>Here is my <a href="https://plnkr.co/edit/lLRpvKzHs9d3V4W4D6Fh?p=preview" rel="nofollow">plnkr</a>.</p>
2
how to show products under the categories on rails
<p>am working on a rails app and on the show page for a category, i want to show all the products found under that category here is how my </p> <p>show in category is </p> <pre><code>def show @products = Category.friendly.where(params[:name]) end </code></pre> <p>and in my views i have it like this </p> <pre><code>&lt;% @products.each do |product| %&gt; &lt;%= link_to product_path(id: product.slug, category_name: product.category.name), class: "card" do %&gt; &lt;div class="product-image"&gt; &lt;%= image_tag product.productpic.url if product.productpic? %&gt; &lt;/div&gt; &lt;div class="product-text"&gt; &lt;h2 class="product-title"&gt; &lt;%= product.name %&gt;&lt;/h2&gt; &lt;h3 class="product-price"&gt;£&lt;%= product.price %&gt;&lt;/h3&gt; &lt;/div&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>here is my products model </p> <pre><code>class Product &lt; ApplicationRecord belongs_to :category mount_uploader :productpic, ProductpicUploader has_many :order_items acts_as_taggable extend FriendlyId friendly_id :name, use: [:slugged, :finders] default_scope { where(active: true) } end </code></pre> <p>and my category like this</p> <pre><code>class Category &lt; ApplicationRecord has_many :products extend FriendlyId friendly_id :name, use: [:slugged, :finders] end </code></pre> <p>what am i doing wrong here?</p>
2
Set_post_thumbnail not working on Single Page, WordPress
<p>WordPress Codex states usage for 'set_post_thumbnail' is as followed:</p> <pre><code>&lt;?php set_post_thumbnail( $post_id, $thumbnail_id ); ?&gt; </code></pre> <p>On the single-page.php I am working in, I have the following code snippets</p> <pre><code>$post_id = get_the_ID(); // Returns the ID of the current post </code></pre> <p>And</p> <pre><code>$thumb_url2 = mpp_media_src( 'full' ); $thumb_url = $thumb_url2[0]; //Returns the full URL path of first MediaPress image. </code></pre> <p>&amp; Lastly I have the following function in my functions.php file.</p> <pre><code>function get_attachment_id_from_src ($image_src) { global $wpdb; $query = "SELECT ID FROM {$wpdb-&gt;posts} WHERE guid='$image_src'"; $id = $wpdb-&gt;get_var($query); return $id; } </code></pre> <p>Along with the following back on my single-page</p> <pre><code>$thumb_id = get_attachment_id_from_src($thumb_url); </code></pre> <hr> <p>A test of </p> <pre><code>echo $post_id; </code></pre> <p>returns </p> <pre><code>3544 </code></pre> <p>which is the correct post id number.</p> <p>A test of </p> <pre><code>echo $thumb_url; </code></pre> <p>returns the image url </p> <pre><code>http://localhost/mydomain/wp-content/uploads/mediapress/members/374/3535/ATOMS-FOR-PEACE2.jpg </code></pre> <p>which is the correct image url.</p> <p>A test of</p> <pre><code>echo $thumb_id; </code></pre> <p>returns</p> <pre><code>1627 </code></pre> <p>Which is the correct thumbnail id.</p> <hr> <p>So why, I am wondering, after testing to make sure values in variables are proper and accurate, does inserting the following code seem to have no effect?</p> <pre><code>&lt;?php set_post_thumbnail( $post_id, $thumb_id ); ?&gt; </code></pre>
2
android locationRequest interval not update as required
<p>in my project , i use GoogleApiClient and locationRequest to get current location and update it periodically after certain interval , I know that there is difference between setInterval and setFastestInterval and </p> <p>interval is variable that i change from my app settings and has the values of </p> <p>so I call this :</p> <pre><code> public int interval = 1 * 1000; locationRequest.setFastestInterval(interval); locationRequest.setInterval(interval); switch (interval_index) { case 0: interval = 1 * 1000; break; case 1: interval = 1 * 60 * 1000; break; case 2: interval = 5 * 60 * 1000; break; case 3: interval = 10 * 60 * 1000; break; case 4: interval = 30 * 60 * 1000; break; } </code></pre> <p>if i set interval for example to 30 minutes i get updates after 5 minutes for example , it is not constant time but i get updates randomly so why ?</p>
2
Visual Studio 2015 c++ breakpoint will not be hit
<p>Hi I have a c++ app in visual studio 2015. My .exe's pdb wont work and it cant hit breakpoints. when I open the modules window, the status says Symbol format not supported. my debug file flag is /ZI in the projects settings. I've tried deleting the object and bin folders. When I create a new project, it hits the breakpoint. Any ideas?</p>
2
How to speed up writing to an Excel sheet
<p>I am currently using Interop objects to write to an Excel spreadsheet. Using stopwatches, I have found that the following implementation is quite timely. The processes in the <code>foreach</code> loop will usually take around 50 seconds to write around 2000 rows, each with 9 columns.</p> <p>Is there any way to speed this up?</p> <pre><code>List&lt;string[]&gt; allEntries = fillStringArrayList(); // Set-up for running Excel xls = new Excel.Application(); workBooks = xls.Workbooks; workBook = workBooks.Open(workbookPath); var workSheet = workBook.Sheets["Sheet1"]; // Insert new entries foreach (string[] entry in allEntries) { // Get the final row in the sheet that is being used Excel.Range usedRange = workSheet.UsedRange; int rowCount = usedRange.Rows.Count; // Format Column A to be type "text" workSheet.Cells[rowCount + 1, 1].NumberFormat = "@"; workSheet.Cells[rowCount + 1, 1] = entry[0]; workSheet.Cells[rowCount + 1, 2] = entry[1]; workSheet.Cells[rowCount + 1, 3] = entry[2]; workSheet.Cells[rowCount + 1, 4] = entry[3]; workSheet.Cells[rowCount + 1, 5] = entry[4]; workSheet.Cells[rowCount + 1, 6] = entry[5]; workSheet.Cells[rowCount + 1, 7] = entry[6]; workSheet.Cells[rowCount + 1, 8] = entry[7]; workSheet.Cells[rowCount + 1, 9] = entry[8]; } </code></pre>
2
No 'Access-Control-Allow-Origin' header - apache
<blockquote> <p>XMLHttpRequest cannot load <a href="https://example1.com" rel="nofollow">https://example1.com</a>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '<a href="http://example2.com" rel="nofollow">http://example2.com</a>' is therefore not allowed access.</p> </blockquote> <p>How to resolve this on apache.</p>
2
website htaccess redirect conflict with wordpress
<p>I'm not too clued up on how htaccess file coding works, but I have got the following htaccess code in my root directory and it is responsible for redirecting from url.html to url.php:</p> <pre><code>RedirectMatch permanent ^(.*)\.htm(l?)$ $1.php RewriteEngine on RewriteRule ^index\.htm$ index.php [NC,R] </code></pre> <p>This code is important because all of the file names on the website have been changed over from 'html' to 'php' and I want all bookmarks and links made prior to the change over to remain valid.</p> <p>The problem is, the above htaccess code seems to prevent the wordpress blog from opening, displaying the message "Too many redirects occurred when trying to open url".</p> <p>Clearly there is some kind of redirect loop happening, but I cannot for the life of me work out exactly what the problem is.</p> <p>In my wordpress directory (/blog) the htaccess file contains the usual for wordpress:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /blog/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog/index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>When the above htaccess file is removed, the wordpress index file works fine, but because the wordpress htaccess file writes the rules for the post urls, they no longer work.</p> <p>To summarise, I think there is a conflict between the two htaccess files (first one in the root directory, second one in the /blog directory) that is creating a redirect loop.</p> <p>Any ideas as to how I might solve this will be very well received.</p> <p>Thank you all in anticipation.</p>
2
Vertical line showing current week in timeline
<p>Ok so I recently added a vertical line showing the current week in a chart using this method: <a href="http://www.officetooltips.com/excel/tips/how_to_add_a_vertical_line_to_the_chart.html" rel="nofollow noreferrer">http://www.officetooltips.com/excel/tips/how_to_add_a_vertical_line_to_the_chart.html</a></p> <p>but now I want to add one to a sheet without a chart. Is this possible?</p> <p>So my timeline looks like this: <a href="https://i.stack.imgur.com/KC2Ll.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KC2Ll.png" alt="Timeline image"></a> Is vba needed or is this possible with formulas I really have no idea.</p>
2
Playing mpeg2ts with Gstreamer-1.0
<p>I am trying to play a .ts file with Gstreamer-1.0 as well as gst-omx have been successfully installed . Try to play ts video using below command line format but failed to play.</p> <pre><code>test@test-Gardenia:~/Videos$ gst-launch-1.0 -v filesrc location= mpeg2.ts ! tsdemux ! mpegvideoparse ! omxmpeg2dec ! videoconvert ! ximagesink Setting pipeline to PAUSED ... Pipeline is PREROLLING ... ERROR: from element /GstPipeline:pipeline0/GstTSDemux:tsdemux0: Internal data stream error. Additional debug info: mpegtsbase.c(1347): mpegts_base_loop (): /GstPipeline:pipeline0/GstTSDemux:tsdemux0: stream stopped, reason not-linked ERROR: pipeline doesn't want to preroll. Setting pipeline to NULL ... /GstPipeline:pipeline0/GstTSDemux:tsdemux0.GstPad:audio_0044: caps = "NULL" Freeing pipeline ... </code></pre> <p>Tried below command also but not did not work.</p> <pre><code>test@test:~/Videos$ gst-launch-1.0 filesrc location= mpeg2.ts ! tsdemux ! tsparse ! omxmpeg2dec ! videoconvert ! ximagesink WARNING: erroneous pipeline: could not link mpegtsparse2-0 to omxmpeg2videodec-omxmpeg2dec0 </code></pre> <p>Can any one help me how to play .ts file with mpeg2 codec format using gstreamer</p>
2
2 box searchable multiselect with ajax
<p>i am looking for a 2 box searchable multiselect along the lines of the one shown here: <a href="http://www.jqueryrain.com/?qmi2lw8H" rel="nofollow">http://www.jqueryrain.com/?qmi2lw8H</a> but with the left box fill-able using ajax autocomplete - i.e. you start typing 'abc' and the left box fill with everything containing 'abc' based on the jsonp results.</p> <p>i have not had any luck so far using available code in the format below</p> <pre><code>&lt;head&gt; &lt;!-- BS CSS --&gt; &lt;link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet"&gt; &lt;!-- jQuery --&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;!-- Multiselect/BS --&gt; &lt;script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script src="http://myip/multiselect.js" language="javascript" type="text/javascript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="post" name="myForm"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-5"&gt; &lt;select name="from[]" id="search" class="form-control" size="8" multiple="multiple"&gt;&lt;/select&gt; &lt;/div&gt; &lt;div class="col-xs-2"&gt; &lt;button type="button" id="search_rightAll" class="btn btn-block"&gt;&lt;i class="glyphicon glyphicon-forward"&gt;&lt;/i&gt;&lt;/button&gt; &lt;button type="button" id="search_rightSelected" class="btn btn-block"&gt;&lt;i class="glyphicon glyphicon-chevron-right"&gt;&lt;/i&gt;&lt;/button&gt; &lt;button type="button" id="search_leftSelected" class="btn btn-block"&gt;&lt;i class="glyphicon glyphicon-chevron-left"&gt;&lt;/i&gt;&lt;/button&gt; &lt;button type="button" id="search_leftAll" class="btn btn-block"&gt;&lt;i class="glyphicon glyphicon-backward"&gt;&lt;/i&gt;&lt;/button&gt; &lt;/div&gt; &lt;div class="col-xs-5"&gt; &lt;select name="to[]" id="search_to" class="form-control" size="8" multiple="multiple"&gt;&lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; jQuery(document).ready(function($) { var $select = $('#search').multiselect({ search: { left: '&lt;input type="text" name="q" class="form-control" placeholder="Search..." /&gt;', right: '&lt;input type="text" name="q" class="form-control" placeholder="Search..." /&gt;', } }); $select.multiselect('disable'); $.ajax({ type: "POST", url: "../terms_by_name.php", dataType: 'jsonp', data: {term: request.term}, success: function OnPopulateControl(response) { list = response.d; if (list.length &gt; 0) { $select.multiselect('enable'); $("#search").empty().append('&lt;option value="0"&gt;Please select&lt;/option&gt;'); $.each(list, function () { $("#search").append($("&lt;option&gt;&lt;/option&gt;").val(this['Value']).html(this['Text'])); }); $("#search").val(valueselected); } else { $("#search").empty().append('&lt;option selected="selected" value="0"&gt;Not available&lt;option&gt;'); } $("#search").multiselect('refresh'); //refresh the select here }, error: function () { alert("Error"); } }); }); &lt;/script&gt; &lt;/form&gt; </code></pre> <p></p> <p>the multiselect boxes display, and if i put options manually into the select that works, but the one on the left does not fill from the autocomplete. i'm pretty new to this stuff. what am i missing?</p>
2
How to write unit tests for proxy pattern?
<p>Will be thankful for your attention, time and efforts ! <br /> I have the following code</p> <pre><code>public class Employee { public string FirstName { get; set; } public string LastName { get; set; } public string Role { get; set; } } public interface IEmployeeRepository { Employee GetEmployee(string firstName, string role); } public class EmployeeRepository : IEmployeeRepository { public Employee GetEmployee(string firstName, string role) { //logic here return new Employee(); } } </code></pre> <p>Now i want to implement cache for <code>EmployeeRepository</code>. At first i did it using Proxy design pattern</p> <pre><code> public class ProxyEmployeeRepository : IEmployeeRepository { private EmployeeRepository _employeeRepository = new EmployeeRepository(); private MemoryCache _cache = new MemoryCache("UsualCache"); public Employee GetEmployee(string firstName, string role) { //do not cache administrators if (role == "admin") { return _employeeRepository.GetEmployee(firstName, role); } else { //get from cache at first //if absent call _employeeRepository.GetEmployee and add to cache //... } } </code></pre> <p>But when wanted to write unit tests for this class i couldn't do it(i cannot create mock for _employeeRepository and verify whether it was called or not) <br/> If i implement cache with Decorator pattern then i would have the following code</p> <pre><code> public class DecoratorEmployeeRepository : IEmployeeRepository { private IEmployeeRepository _employeeRepository; public DecoratorEmployeeRepository(IEmployeeRepository repository) { _employeeRepository = repository; } private MemoryCache _cache = new MemoryCache("UsualCache"); public Employee GetEmployee(string firstName, string role) { //do not cache administrators if (role == "admin") { return _employeeRepository.GetEmployee(firstName, role); } else { //get from cache at first //if absent call _employeeRepository.GetEmployee and add to cache return null; } } } </code></pre> <p>and unit tests for it</p> <pre><code> [TestClass] public class EmployeeRepositoryTests { [TestMethod] public void GetEmployeeTest_AdminRole() { var innerMock = Substitute.For&lt;IEmployeeRepository&gt;(); var employeeRepository = new DecoratorEmployeeRepository(innerMock); employeeRepository.GetEmployee("Ihor", "admin"); innerMock.Received().GetEmployee(Arg.Any&lt;string&gt;(), Arg.Any&lt;string&gt;()); } [TestMethod] public void GetEmployeeTest_NotAdminRole() { var innerMock = Substitute.For&lt;IEmployeeRepository&gt;(); var employeeRepository = new DecoratorEmployeeRepository(innerMock); employeeRepository.GetEmployee("Ihor", "NotAdmin"); innerMock.DidNotReceive().GetEmployee("Ihor", "NotAdmin"); } } </code></pre> <p><strong>Is it possible to write unit tests for first approach with proxy pattern ? i just don't understand how it is possible to cover proxy class with unit tests ...</strong></p>
2
Django ImageField error : cannot open image file
<p>I put the ImageField into the Model and can successfully upload the image file. But when try to open the file through admin page. Cannot open the file but there is an error says "500 Internal server error". </p> <p>In the file name there are some non-ascii letters inside. How can I fix this problem?</p> <pre><code>class Customer(User): profile_image = models.ImageField(upload_to='customers/photos', null=True, blank=True) hospital = models.ForeignKey('Hospital', null=True, blank=True) treatments = models.ManyToManyField('Treatment', blank=True) verified = models.BooleanField(default=False) def get_full_name(self): return self.email def get_short_name(self): return self.email image file name = "데이비드_베컴2.jpg" </code></pre> <p>actually this model has more then one field..</p> <p>+) admin.py</p> <pre><code>class CustomerAdmin(UserAdmin): form = CustomerChangeForm add_form = CustomerCreationForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ('email', 'phonenumber', 'is_admin') list_filter = ('is_admin',) fieldsets = ( (None, {'fields': ('email', 'password', 'phonenumber', 'smscheck', 'name', 'hospital', 'major', 'treatments', 'info', 'profile_image', 'verified', )}), ('Personal info', {'fields': ()}), ('Permissions', {'fields': ('is_active', 'is_admin',)}), ) # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin # overrides get_fieldsets to use this attribute when creating a user. add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'phonenumber', 'smscheck', 'name', 'hospital', 'major', 'treatments', 'info', 'verified', 'is_active', 'is_admin')} ), ) search_fields = ('email', 'phonenumber') ordering = ('email',) filter_horizontal = () </code></pre> <p>also when I put the file encoded with english it has no problem.. for example, "myprofile.jpg"</p> <p>+) error in detail</p> <pre><code>Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/usr/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/usr/local/lib/python2.7/site-packages/whitenoise/base.py", line 57, in __call__ static_file = self.find_file(environ['PATH_INFO']) File "/usr/local/lib/python2.7/site-packages/whitenoise/django.py", line 72, in find_file if self.use_finders and url.startswith(self.static_prefix): UnicodeDecodeError: 'ascii' codec can't decode byte 0xeb in position 22: ordinal not in range(128) </code></pre> <p>How can I fix this problem? thanks in advance!</p>
2
Generic and efficient way to send files from a Controller to remote ApiController in ASP.NET MVC
<p>I am working on a multi-level ASP.NET MVC web platform and I have the requirement to send a file from a <code>System.Web.Mvc.Controller</code> to an ASP.NET MVC web-service's <code>System.Web.Http.ApiController</code>, running remotely on a different machine.</p> <p>Currently, I have this in my <code>Mvc.Controller</code>:</p> <pre><code>public ActionResult ForwardThisFile(HttpPostedFileBase file) { // TODO: Forward file to remote DocumentApi: DocumentApi.DocumentApiClient client = new DocumentApi.DocumentApiClient(); client.StoreDocument(file /* &lt;-- How-To? */); return View(); } </code></pre> <p>where the <code>DocumentApiClient</code> has been generated via Visual Studio's <em>Add REST API Client...</em> function from a Swagger Url. (The generated client internally uses the <code>Microsoft.Rest.ClientRuntime</code> which is relying on <code>System.Net.Http.HttpClient</code>, <code>HttpRequestMessage</code>, etc.)</p> <p>The question is, how do I define and implement the DocumentApi to transfer files to it in an efficient and generic way in the <code>ApiController</code>. Currently, I am thinking of three different options:</p> <ul> <li><code>[HttpPut] public async Task&lt;IHttpActionResult&gt; StoreDocument(HttpPostedFileBase file)</code></li> <li><code>[HttpPut] public async Task&lt;IHttpActionResult&gt; StoreDocument(byte[] fileContents, string contentType, string fileName)</code></li> <li><code>[HttpPut] public async Task&lt;IHttpActionResult&gt; StoreDocument(Stream fileStream, string contentType, string fileName)</code></li> </ul> <p>I was thinking, that maybe I could just forward the <code>HttpPostedFileBase</code> instance from the <code>Mvc.Controller</code> to the <code>ApiController</code>, so I've tried the first option. However, <em>Add REST API Client...</em> creates a <code>DocumentApi.Models.HttpPostedFileBase</code> model class in that case and is NOT of the original type <code>System.Web.HttpPostedFileBase</code>. Now, I'm not sure what I should do...</p> <pre><code>new DocumentApi.Models.HttpPostedFileBase() { InputStream = file.InputStream, ContentType = file.ContentType, ContentLength = file.ContentLength, FileName = file.FileName, } </code></pre> <p>^ that doesn't work, because for the <code>InputStream</code>, it creates a <code>DocumentApi.Models.Stream</code> class and I have no idea how to convert the <code>System.IO.Stream</code> from the <code>file</code> parameter into a <code>DocumentApi.Models.Stream</code>.</p> <p>Is it even possible to send a stream across ASP.NET MVC webservices? (Which would basically be the answer to option 3)</p> <p>In my current state of knowledge, the only alternative appears to me being option 2, where I would send a byte-array containing the whole file. I am asking myself, however, if there is any more convenient or more efficient way to send a file from a <code>Mvc.Controller</code> to a remote <code>ApiController</code>. Is there?<br> Which one of the options would work and which one is the way to go?</p> <p>Additionally, I have a <strong>bonus question</strong> to the above regarding <code>HttpPostedFileBase</code>: Is the way via <code>HttpPostedFileBase</code> the most efficient way to handle uploaded files in ASP.NET MVC? I have seen various alternatives:</p> <ul> <li><code>HttpPostedFileBase</code> like shown above in the first code sample</li> <li>Using the raw HTTP-request via <code>Request.Content.ReadAsStreamAsync()</code> or something similar. Maybe the stream is more efficient for my use case?</li> <li>Using JavaScript to encode a file into a Base64 string and send it via a hidden input field to the controller. (via <code>FileReader</code>'s method <code>readAsDataURL(file)</code>)</li> </ul> <p>So many options... Which one is best/most generic/most efficient?</p>
2
Excel UDF to find first and last cell in range with a given value - runs slowly
<p>I'm writing a function which takes a column range and finds the first and last cell in that column which have a certain value. This gives a first row number and a last row number that are then used to return the corresponding subrange in another column.<br> The idea is that with this function I can apply Excel functions to a (continuous) subsection of a range. E.g. suppose I have a table with various prices of Apples and Bananas, grouped so that all prices of Apples come first, then Bananas. I want to find the minimum price of Apples and the minimum of Bananas, but selecting the whole range and without changing the range over which to minimise. I would use my desired function to feed a range to Excel's MIN function which included just Apples, or just Bananas, without having to manually select these subranges. A MINIF, if you will - like a weak version of SUMIF but for MIN (and potentially many other functions).<br> I've found a way of doing it but it's running really quite slow. I think it may have to do with the for loop, but I don't understand enough about efficiency in Excel/VBA to know how to improve it. I'm using this code on an Excel table, so the columns I pass are named columns of a table object. I'm using Excel 2010 on Windows 7 Enterprise.</p> <p>Grateful for any help. Even solutions on how to conditionally apply functions to ranges that deviate radically from this are well received.</p> <p>Code:</p> <pre><code>' ParentRange and CriterionRange are columns of the same table. 'I want to extract a reference to the part of ParentRange which corresponds 'by rows to the part of CriterionRange that contains cells with a certain value. Function CorrespondingSubrange(CriterionRange As Range, Criterion As _ String, ParentRange As Range) As Range Application.ScreenUpdating = False Dim RowCounter As Integer Dim SubRangeFirstRow As Integer Dim SubRangeFirstCell As Range Dim SubRangeLastRow As Integer Dim SubRangeLastCell As Range Dim RangeCountStarted As Boolean RangeCountStarted = False Set SubRangeFirstCell = CriterionRange.Find(What:=Criterion, LookIn:=xlValues, _ LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not (SubRangeFirstCell Is Nothing) Then RangeCountStarted = True SubRangeFirstRow = SubRangeFirstCell.Row - CriterionRange.Range("A1").Row + 1 For RowCounter = SubRangeFirstRow To CriterionRange.Cells.Count If Not (CriterionRange.Cells(RowCounter, 1).Value = Criterion) Then SubRangeLastRow = RowCounter - 1 Exit For End If Next End If If RangeCountStarted = True And SubRangeLastRow = 0 Then SubRangeLastRow = RowCounter Set CorrespondingSubrange = ParentRange.Range("A" &amp; SubRangeFirstRow &amp; ":A" &amp; SubRangeLastRow) Application.ScreenUpdating = True End Function </code></pre>
2
Frequency of Node/value in a binary search tree
<p>Given a binary search tree where there may contain duplicates, but all other logic of the BST is intact,determine the most frequently occurring element. </p> <pre><code>class TreeNode { public: TreeNode* right = NULL; TreeNode* left = NULL; int val; TreeNode(int value) { val = value; } }; // To keep track of the frequency of the value/node struct holder { public: TreeNode* most = NULL; int count = 0; }; int frequencyOfNode(TreeNode* root, struct holder* ptr) { if (root == NULL) { return 0; } int left = frequencyOfNode(root-&gt;left, ptr); int right = frequencyOfNode(root-&gt;right, ptr); // need to check of left and right are nor null if (left != 0 &amp;&amp; root-&gt;val == root-&gt;left-&gt;val) { return 1 + left; } else if (right != 0 &amp;&amp; root-&gt;val == root-&gt;right-&gt;val) { return 1 + right; } else { // left has a higher frequency if (left &gt;= right) { // left is bigger; if (left &gt; ptr-&gt;count) { ptr-&gt;most = root-&gt;left; ptr-&gt;count = left; } } else { // right has a higher frequency if (right &gt; ptr-&gt;count) { ptr-&gt;most = root-&gt;right; ptr-&gt;count = right; } } return 1; } } </code></pre> <p>I am doing a post order traversal of the binary search tree. my logic works when the nodes appears in consecutive order, but if the node is not in consecutive order; the frequency of the node is reset.</p> <p>my time is O(n) and space is O(1).</p> <p>the issue is when the Nodes do not linked in succession.</p> <p>my sample Tree:</p> <pre><code>int main() { TreeNode *root = new TreeNode(6); root-&gt;right = new TreeNode(8); root-&gt;right-&gt;left = new TreeNode(7); root-&gt;right-&gt;right = new TreeNode(8); root-&gt;right-&gt;right-&gt;right = new TreeNode(8); root-&gt;right-&gt;right-&gt;right-&gt;right = new TreeNode(9); root-&gt;right-&gt;right-&gt;right-&gt;right-&gt;left = new TreeNode(8); root-&gt;left = new TreeNode(4); root-&gt;left-&gt;right = new TreeNode(5); root-&gt;left-&gt;right-&gt;right = new TreeNode(5); root-&gt;left-&gt;right-&gt;right-&gt;right = new TreeNode(5); root-&gt;left-&gt;left = new TreeNode(1); root-&gt;left-&gt;left-&gt;right = new TreeNode(1); root-&gt;left-&gt;left-&gt;right-&gt;right = new TreeNode(1); root-&gt;left-&gt;left-&gt;right-&gt;right = new TreeNode(2); root-&gt;left-&gt;left-&gt;left = new TreeNode(0); struct holder freq; int ran = frequencyOfNode(root, &amp;freq); std::cout &lt;&lt; "random" &lt;&lt; ran &lt;&lt; std::endl; std::cout &lt;&lt; "The Node: " &lt;&lt; freq.most-&gt;val &lt;&lt; " frequency " &lt;&lt; freq.count &lt;&lt; std::endl; return 0; } </code></pre> <p>I'm really confused on how to take into account, when the nodes are not consecutive( i.e 8->8->8->9->8).</p>
2
Tensorflow conv3d_transpose *** Error in 'python': free(): invalid pointer
<p><strong>EDIT</strong> opened issue: <a href="https://github.com/tensorflow/tensorflow/issues/3128" rel="nofollow">https://github.com/tensorflow/tensorflow/issues/3128</a></p> <p>I'm trying to use the newly added <code>conv3d_transpose</code> created <a href="https://github.com/tensorflow/tensorflow/pull/3049" rel="nofollow">here</a></p> <p>But I'm getting the error in the title: <code>*** Error in 'python': free(): invalid pointer</code></p> <p>I have the network working in 2D (using the same data), but it won't run in 3D. </p> <p>I have tried on two different linux machines both running Ubuntu 14.04. I am currently trying to get it to run on my Mac, but I can't find a build with with the <code>conv3d_transpose</code> included. I had to install the nightly build on my linux machine, but the nightly build for OSX doesn't include it. Does anyone know where I could find it?</p> <p>The way I input the 3D data may be the cause. My data inputs in 2D images, and I essentially concatenate them into a 3D matrix. For testing purposes, I'm keeping my data set small. My batch size is 1 and my depth is 5. I pull in <code>n_depth * batch_size</code> from my data class, and then reshape it into <code>[batch_size, n_depth, x, y, n_classes]</code></p> <p>The network itself builds, and it doesn't throw any dimension errors. The error occurs on the first training session. </p> <p>Full code is below:</p> <pre><code>import tensorflow as tf import pdb import numpy as np from numpy import genfromtxt from PIL import Image from tensorflow.contrib.learn.python.learn.datasets.scroll import scroll_data # Parameters learning_rate = 0.001 training_iters = 1000000 batch_size = 1 display_step = 1 # Network Parameters n_input_x = 200 # Input image x-dimension n_input_y = 200 # Input image y-dimension n_depth = 5 n_classes = 2 # Binary classification -- on a surface or not dropout = 0.75 # Dropout, probability to keep units # tf Graph input x = tf.placeholder(tf.float32, [None, n_depth, n_input_x, n_input_y]) y = tf.placeholder(tf.float32, [None, n_depth, n_input_x, n_input_y, n_classes], name="ground_truth") keep_prob = tf.placeholder(tf.float32) #dropout (keep probability) # This function converts the ground truth data into a # 2 channel classification -- n_input_x x n_input_y x 2 # one layer for 0's and the other for 1's def convert_to_2_channel(x, size): #assume input has dimension (batch_size,x,y) #output will have dimension (batch_size,x,y,2) output = np.empty((size, 200, 200, 2)) temp_temp_arr1 = np.empty((size, 200, 200)) temp_temp_arr2 = np.empty((size, 200, 200)) for i in xrange(size): for j in xrange(n_input_x): for k in xrange(n_input_y): if x[i][j][k] == 1: temp_temp_arr1[i][j][k] = 1 temp_temp_arr2[i][j][k] = 0 else: temp_temp_arr1[i][j][k] = 0 temp_temp_arr2[i][j][k] = 1 for i in xrange(size): for j in xrange(n_input_x): for k in xrange(n_input_y): for l in xrange(2): try: if l == 0: output[i][j][k][l] = temp_temp_arr1[i][j][k] else: output[i][j][k][l] = temp_temp_arr2[i][j][k] except IndexError: print "Index error" pdb.set_trace() return output # Create some wrappers for simplicity def conv3d(x, W, b, strides=1): # Conv2D wrapper, with bias and relu activation x = tf.nn.conv3d(x, W, strides=[1, strides, strides, strides, 1], padding='SAME') x = tf.nn.bias_add(x, b) return tf.nn.relu(x) def maxpool3d(x, k=2): # MaxPool2D wrapper return tf.nn.max_pool3d(x, ksize=[1, k, k, k, 1], strides=[1, k, k, k, 1], padding='SAME') def deconv3d(prev_layer, w, b, output_shape, strides): # Deconv layer deconv = tf.nn.conv3d_transpose(prev_layer, w, output_shape=output_shape, strides=strides, padding="VALID") deconv = tf.nn.bias_add(deconv, b) deconv = tf.nn.relu(deconv) return deconv # Create model def conv_net(x, weights, biases, dropout): # Reshape input picture x = tf.reshape(x, shape=[-1, 5, 200, 200, 1]) with tf.name_scope("conv1") as scope: # Convolution Layer conv1 = conv3d(x, weights['wc1'], biases['bc1']) # Max Pooling (down-sampling) #conv1 = tf.nn.local_response_normalization(conv1) conv1 = maxpool3d(conv1, k=2) # Convolution Layer with tf.name_scope("conv2") as scope: conv2 = conv3d(conv1, weights['wc2'], biases['bc2']) # Max Pooling (down-sampling) # conv2 = tf.nn.local_response_normalization(conv2) conv2 = maxpool3d(conv2, k=2) # Convolution Layer with tf.name_scope("conv3") as scope: conv3 = conv3d(conv2, weights['wc3'], biases['bc3']) # Max Pooling (down-sampling) # conv3 = tf.nn.local_response_normalization(conv3) conv3 = maxpool3d(conv3, k=2) pdb.set_trace() temp_batch_size = tf.shape(x)[0] #batch_size shape with tf.name_scope("deconv1") as scope: output_shape = [temp_batch_size, 2, 50, 50, 64] strides = [1,1,2,2,1] conv4 = deconv3d(conv3, weights['wdc1'], biases['bdc1'], output_shape, strides) # conv4 = tf.nn.local_response_normalization(conv4) with tf.name_scope("deconv2") as scope: output_shape = [temp_batch_size, 3, 100, 100, 32] strides = [1,1,2,2,1] conv5 = deconv3d(conv4, weights['wdc2'], biases['bdc2'], output_shape, strides) # conv5 = tf.nn.local_response_normalization(conv5) with tf.name_scope("deconv3") as scope: output_shape = [temp_batch_size, 5, 200, 200, 2] #this time don't use ReLu -- since output layer conv6 = tf.nn.conv3d_transpose(conv5, weights['wdc3'], output_shape=output_shape, strides=[1,1,2,2,1], padding="VALID") conv6 = tf.nn.bias_add(conv6, biases['bdc3']) # conv6 = tf.nn.relu(conv6) # Include dropout #conv6 = tf.nn.dropout(conv6, dropout) return conv6 weights = { # 5x5 conv, 1 input, 32 outputs 'wc1' : tf.Variable(tf.random_normal([5, 5, 5, 1, 32])), # 5x5 conv, 32 inputs, 64 outputs 'wc2' : tf.Variable(tf.random_normal([3, 5, 5, 32, 64])), # 5x5 conv, 32 inputs, 64 outputs 'wc3' : tf.Variable(tf.random_normal([2, 5, 5, 64, 128])), 'wdc1' : tf.Variable(tf.random_normal([2, 2, 2, 64, 128])), 'wdc2' : tf.Variable(tf.random_normal([2, 2, 2, 32, 64])), 'wdc3' : tf.Variable(tf.random_normal([3, 2, 2, 2, 32])), } biases = { 'bc1': tf.Variable(tf.random_normal([32])), 'bc2': tf.Variable(tf.random_normal([64])), 'bc3': tf.Variable(tf.random_normal([128])), 'bdc1': tf.Variable(tf.random_normal([64])), 'bdc2': tf.Variable(tf.random_normal([32])), 'bdc3': tf.Variable(tf.random_normal([2])), } # Construct model # with tf.name_scope("net") as scope: pred = conv_net(x, weights, biases, keep_prob) pdb.set_trace() pred = tf.reshape(pred, [-1, n_input_x, n_input_y, n_depth, n_classes]) #Reshape to shape-Y # Define loss and optimizer # Reshape for cost function temp_pred = tf.reshape(pred, [-1, 2]) temp_y = tf.reshape(y, [-1, 2]) with tf.name_scope("loss") as scope: # cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(pred, y)) cost = (tf.nn.softmax_cross_entropy_with_logits(temp_pred, temp_y)) with tf.name_scope("opt") as scope: optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Evaluate model with tf.name_scope("acc") as scope: # accuracy is the difference between prediction and ground truth matrices correct_pred = tf.equal(0,tf.cast(tf.sub(tf.nn.softmax(temp_pred),temp_y), tf.int32)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) # Initializing the variables init = tf.initialize_all_variables() saver = tf.train.Saver() # Launch the graph with tf.Session() as sess: sess.run(init) summary = tf.train.SummaryWriter('/tmp/logdir/', sess.graph) #initialize graph for tensorboard step = 1 # Import data data = scroll_data.read_data('/home/kendall/Desktop/') # Keep training until reach max iterations while step * batch_size &lt; training_iters: batch_x, batch_y = data.train.next_batch(n_depth) # Run optimization op (backprop) batch_x = batch_x.reshape((batch_size, n_depth, n_input_x, n_input_y)) batch_y = batch_y.reshape((n_depth, n_input_x, n_input_y)) batch_y = convert_to_2_channel(batch_y, n_depth) # Converts the 200x200 ground truth to a 200x200x2 classification batch_y = batch_y.reshape(batch_size * n_input_x * n_input_y * n_depth, 2) sess.run(optimizer, feed_dict={x: batch_x, temp_y: batch_y, keep_prob: dropout}) pdb.set_trace() if step % display_step == 0: batch_y = batch_y.reshape(batch_size, n_input_x, n_input_y, 2) loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x, y: batch_y, keep_prob: 1.0}) print "Accuracy = " + str(acc) #print "Loss = " + str(loss) # Save network and make prediction if acc &gt; 0.7: # Save network save_path = "model.ckpt" saver.save(sess, save_path) # Make prediction im = Image.open('/home/kendall/Desktop/HA900_frames/frame0001.tif') batch_x = np.array(im) batch_x = batch_x.reshape((1, n_input_x, n_input_y)) batch_x = batch_x.astype(float) prediction = sess.run(pred, feed_dict={x: batch_x, keep_prob: 1.0}) prediction = prediction.reshape((40000,2)) prediction = tf.nn.softmax(prediction) prediction = prediction.eval() prediction = prediction.reshape((n_input_x, n_input_y, 2)) # Temp arrays are to splice the prediction n_input_x x n_input_y x 2 # into 2 matrices n_input_x x n_input_y temp_arr1 = np.empty((n_input_x, n_input_y)) temp_arr2 = np.empty((n_input_x, n_input_y)) for i in xrange(n_input_x): for j in xrange(n_input_x): for k in xrange(2): if k == 0: temp_arr1[i][j] = prediction[i][j][k] else: temp_arr2[i][j] = prediction[i][j][k] # np.savetxt("small_dataset_1.csv", temp_arr1, delimiter=",") # np.savetxt("small_dataset_2.csv", temp_arr2, delimiter=",") if acc &gt; 0.70 and acc &lt; 0.73: np.savetxt("run_1_step_1-1.csv", temp_arr1, delimiter=",") # np.savetxt("run_1_step_1-2.csv", temp_arr2, delimiter=",") if acc &gt; 0.73 and acc &lt; 0.78: np.savetxt("run_1_step_2-1.csv", temp_arr1, delimiter=",") # np.savetxt("run_1_step_2-2.csv", temp_arr2, delimiter=",") if acc &gt; 0.78 and acc &lt; 0.81: np.savetxt("run_1_step_3-1.csv", temp_arr1, delimiter=",") # np.savetxt("run_1_step_3-2.csv", temp_arr2, delimiter=",") if acc &gt; 0.81 and acc &lt; 0.84: np.savetxt("run_1_step_4-1.csv", temp_arr1, delimiter=",") # np.savetxt("run_1_step_4-2.csv", temp_arr2, delimiter=",") if acc &gt; 0.84 and acc &lt; 0.87: np.savetxt("run_1_step_5-1.csv", temp_arr1, delimiter=",") # np.savetxt("run_1_step_5-2.csv", temp_arr2, delimiter=",") if acc &gt; 0.87 and acc &lt; 0.9: np.savetxt("run_1_step_6-1.csv", temp_arr1, delimiter=",") # np.savetxt("run_1_step_6-2.csv", temp_arr2, delimiter=",") if acc &gt; 0.9 and acc &lt; 0.95: np.savetxt("run_1_step_7-1.csv", temp_arr1, delimiter=",") # np.savetxt("run_1_step_7-2.csv", temp_arr2, delimiter=",") if acc &gt; 0.95: np.savetxt("run_1_step_8-1.csv", temp_arr1, delimiter=",") # np.savetxt("run_1_step_8-2.csv", temp_arr2, delimiter=",") if acc &gt; 0.98: break step += 1 print "Optimization Finished!" # Measure accuracy on test set print "Testing Accuracy:", test_img = data.test.labels[0:].reshape((5, n_input_x, n_input_y)) test_img = convert_to_2_channel(test_img, 5) acc = sess.run(accuracy, feed_dict={x: data.test.images[0:].reshape((5, n_input_x, n_input_y)), y: test_img, keep_prob: 1.}) print acc </code></pre>
2
gradle.daemon react-native: Could not find or load main class “Dorg.gradle.daemon=true”
<p>When I try to build the project with the command 'react-native run-android' the following error appears: <strong>Error: Could not find or load main class “Dorg.gradle.daemon=true”</strong></p> <pre><code>JS server already running. Building and installing the app on the device (cd android &amp;&amp; ./gradlew installDebug... Error: Could not find or load main class “Dorg.gradle.daemon=true” Could not install the app on the device, read the error above for details. </code></pre> <p><strong>.bash_profile</strong> contains the following global variables:</p> <pre><code>export ANDROID_HOME=$HOME/Library/Android/Android-SDK export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/Hom export GRADLE_OPTS=“Dorg.gradle.daemon=true” </code></pre> <p>I have my emulator running and I have ran the command "source ~/.bash_profile".</p> <p><strong>All I want is to enable gradle daemon and execute the project</strong>.</p>
2
Finding the index of an element in a LinkedList C#
<p>Let's say that I have a LinkedList&lt; Client> and each Client object has an ID property. I want to set each client's ID according to their index in the LinkedList.</p> <p>In Java i used to do it like this</p> <pre><code> for (Client i : clientList) { i.setClientId(clientList.indexOf(i)); } </code></pre> <p>I can't seem to find an equivalent function of indexOf() in C#</p>
2
C2227: left of '->send' must point to class/struct/union/generic type
<p>I wrote a socket client server, and I create a socket vector list in mythread.h file but it gives me these errors that I can't fix:</p> <p><strong>Code:</strong></p> <pre><code>for (int i = 0; i &lt; v_-&gt;size(); i++) { if(((MYThread *)(v_)[i])-&gt;user_id_ != user_id_) { ((MYThread *)(v_)[i])-&gt;send(strArray); } } </code></pre> <p><strong>Errors:</strong></p> <blockquote> <p>D:\My_Socket\My_Socket\server\server\mythread.cpp:101: error: C2440: 'type > cast': cannot convert from 'std::vector>' to > 'MYThread *' with [ _Ty=MYThread * ]</p> <p>D:\My_Socket\My_Socket\server\server\mythread.cpp:101: error: C2227: left of '->user_id_' must point to class/struct/union/generic type</p> </blockquote> <p>mythrad.h file</p> <pre><code>#ifndef MYTHREAD_H #define MYTHREAD_H #include &lt;QListWidget&gt; #include &lt;QObject&gt; #include &lt;QTcpSocket&gt; #include &lt;QAbstractSocket&gt; #include &lt;QDebug&gt; #include &lt;vector&gt; #include &lt;QThread&gt; #include &lt;QString&gt; #include &lt;QPixmap&gt; class MYThread : public QThread { public: explicit MYThread(QThread *parent = 0); explicit MYThread(QTcpSocket *socket, QListWidget *list, std::vector&lt;MYThread *&gt; *v, int user_id); void doConnect(); void send(QByteArray data); signals: public slots: void connected(); void disconnected(); void bytesWritten(qint64 bytes); void readyRead(); void quitThread(); private: QTcpSocket *socket_; QListWidget *list_; std::vector&lt;MYThread *&gt; *v_; MYThread *tt; void run(); QPixmap *pixmap; MYThread *socket; public: int user_id_; }; #endif // MYTHREAD_H </code></pre>
2
WMI .NET Invalid query
<p>I keep getting an "Invalid Query" exception when trying to execute the following query:</p> <pre><code>ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskQuota WHERE QuotaVolume.DeviceID = 'C:'"); ManagementObjectCollection quotaCollection = searcher.Get(); </code></pre> <p>However this works: "SELECT * FROM Win32_DiskQuota".</p> <p>According to MSDN:</p> <blockquote> <p>For most uses of class descriptors in a WHERE clause, WMI flags the query as invalid and returns an error. However, use the dot (.) operator for properties of type object in WMI. For example, the following query is valid if Prop is a valid property of MyClass and is type object:</p> <p>SELECT * FROM MyClass WHERE Prop.embedprop = 5</p> </blockquote> <p>Does it mean this only works if Prop declared as OBJECT?</p> <p>Here are the exception details:</p> <pre><code>System.Management.ManagementException was unhandled HResult=-2146233087 Message=Invalid query Source=System.Management StackTrace: в System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode) в System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext() в UserQuota.Program.getQuota() в c:\users\administrator\documents\visual studio 2015\Projects\UserQuota\UserQuota\Program.cs:строка 40 в UserQuota.Program.Main(String[] args) в c:\users\administrator\documents\visual studio 2015\Projects\UserQuota\UserQuota\Program.cs:строка 33 в System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) в System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) в Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() в System.Threading.ThreadHelper.ThreadStart_Context(Object state) в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) в System.Threading.ThreadHelper.ThreadStart() InnerException: </code></pre>
2
VB 6.0 Binary Reading and Writing from VB.NET
<p>I have a vb.net code and want to convert it in vb 6.0. But I have some difficulties. I cant find equivalent of some .net classes </p> <pre><code> Dim byteswritten As Integer Dim fs As System.IO.FileStream Dim r As System.IO.BinaryReader Dim CHUNK_SIZE As Integer = 65554 fs = New System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read) r = New System.IO.BinaryReader(fs) Dim FSize As Integer = CType(fs.Length, Integer) Dim chunk() As Byte = r.ReadBytes(CHUNK_SIZE) While (chunk.Length &gt; 0) dmPutStream.Write(chunk, chunk.Length, byteswritten) If (FSize &lt; CHUNK_SIZE) Then CHUNK_SIZE = FSize chunk = r.ReadBytes(CHUNK_SIZE) Else chunk = r.ReadBytes(CHUNK_SIZE) End If End While </code></pre> <p>Well, the document can be big then we used chunk. But I dont know steps for vb 6.0</p> <p>Such as what i should do for binary reading. </p>
2
Hibernate doesn't want to map the class in hibernate.cfg.xml
<p>I have a class User which is Entity. When I'm trying to map it in hibernate.cfg.xml</p> <pre><code>&lt;mapping class=&quot;com.igorgorbunov3333.entities.User&quot;/&gt; </code></pre> <p>get an error:</p> <blockquote> <p>Exception in thread &quot;main&quot; org.hibernate.MappingException: Unknown entity: com.igorgorbunov3333.entities.User</p> </blockquote> <p>But when I map class User programmatically It's work fine.</p> <pre><code>configuration.addAnnotatedClass(User.class); </code></pre> <p>What is the reason?</p> <p>My Entity class:</p> <pre><code>package com.igorgorbunov3333.entities; import javax.persistence.*; /** * Created by Игорь on 01.07.2016. */ @Entity @Table(name=&quot;user&quot;) public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private String email; private String password; public int getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } </code></pre>
2
How to install phpMailer on azure Web App
<p>I've been researching lots of solutions in mail services for azure and I decided that the best solution for me is with phpMailer. I already tried to use the sendgrid API but I want to utilize the Ajax post method with jquery/javascript.</p> <p>I have also found another solution that involves CURL. But the I'm getting an error on </p> <pre><code>Dotenv::load(__DIR__); </code></pre> <p>The error seems to be from sendGrids own php-files.</p> <p>How do I solve any of these issues on azure. </p> <p>The code I'm using is the following:</p> <pre><code>&lt;?php require 'vendor/autoload.php'; Dotenv::load(__DIR__); $sendgrid_apikey = getenv('YOUR_SENDGRID_APIKEY'); $sendgrid = new SendGrid($sendgrid_apikey); $url = 'https://api.sendgrid.com/'; $pass = $sendgrid_apikey; $template_id = '&lt;your_template_id&gt;'; $js = array( 'sub' =&gt; array(':name' =&gt; array('Elmer')), 'filters' =&gt; array('templates' =&gt; array('settings' =&gt; array('enable' =&gt; 1, 'template_id' =&gt; $template_id))) ); $params = array( 'to' =&gt; "[email protected]", 'toname' =&gt; "Example User", 'from' =&gt; "[email protected]", 'fromname' =&gt; "Your Name", 'subject' =&gt; "PHP Test", 'text' =&gt; "I'm text!", 'html' =&gt; "&lt;strong&gt;I'm HTML!&lt;/strong&gt;", 'x-smtpapi' =&gt; json_encode($js), ); $request = $url.'api/mail.send.json'; // Generate curl request $session = curl_init($request); // Tell PHP not to use SSLv3 (instead opting for TLS) curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); curl_setopt($session, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $sendgrid_apikey)); // Tell curl to use HTTP POST curl_setopt ($session, CURLOPT_POST, true); // Tell curl that this is the body of the POST curl_setopt ($session, CURLOPT_POSTFIELDS, $params); // Tell curl not to return headers, but do return the response curl_setopt($session, CURLOPT_HEADER, false); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); // obtain response $response = curl_exec($session); curl_close($session); // print everything out print_r($response); ?&gt; </code></pre> <p>Best wishes, Stanner </p>
2
Postgres - Cascade delete not working
<p>I have a table called "Reviews" and it references a record in a table "ReviewSetups". When I delete a ReviewSetup I was to also delete all child Reviews (so cascade delete).</p> <p>I have setup the foreign key like below on the Reviews table but nothing gets deleted when I delete a parent ReviewSetup.</p> <p>I have other entities in by db as well which I migrated with a FK in exactly the same way and those work fine.</p> <p>Does anyone have an idea what is going on here?</p> <p><a href="https://i.stack.imgur.com/FujEi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FujEi.png" alt="enter image description here"></a></p> <p>EDIT </p> <p>Here's the code:</p> <pre><code>-- Foreign Key: "FK_Reviews_ReviewSetup_Id_ReviewSetups_Id" -- ALTER TABLE "Reviews" DROP CONSTRAINT "FK_Reviews_ReviewSetup_Id_ReviewSetups_Id"; ALTER TABLE "Reviews" ADD CONSTRAINT "FK_Reviews_ReviewSetup_Id_ReviewSetups_Id" FOREIGN KEY ("ReviewSetup_Id") REFERENCES "ReviewSetups" ("Id") MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE; </code></pre>
2
UPDATE table with WHERE multiple condition from another table
<p>I have 2 tables:</p> <p><strong>users</strong></p> <pre><code>| id | amount | --------------- | 1 | 10 | | 2 | 20.50 | | 3 | 0 | | 4 | 80 | | 5 | 0 | --------------- </code></pre> <p><strong>vehicle_travel</strong></p> <pre><code>| id | user_id | costprice | status | -------------------------------------- | 1 | 1 | 80.00 | active | | 2 | 1 | 20.00 | expired | | 3 | 2 | 130.50 | active | | 4 | 5 | 325.00 | active | | 5 | 3 | 99.50 | expired | -------------------------------------- </code></pre> <p>I want to <code>UPDATE</code> <strong>users table</strong> and <code>SET</code> <strong>users.amount</strong> to <strong>users.amount+vehicle_travel.costprice</strong> <code>WHERE</code> the <strong>users.id</strong> equals to <strong>vehicle_travel.user_id</strong> <code>AND</code> <strong>vehicle_travel.status</strong> equals to <strong>'expired'</strong></p> <p>This is my full query:</p> <pre><code>UPDATE users SET users.amount=users.amount+vehicle_travel.costprice WHERE users.id=vehicle_travel.user_id AND vehicle_travel.status='expired' </code></pre> <p>But i keep getting <strong>unknown column</strong> errors from phpMyAdmin.</p> <p>What am i doing wrong?</p>
2
Installing Minecraft server from .exe instead of .jar
<p>Very new to minecraft, and I'm trying to install server 1.8 (protocol number 42)..</p> <p>Not sure if the .jar file (mcversions.net) is the normal way to install, but can't get it to work - either double clicking or using </p> <pre><code> java -Xmx1024M -Xms1024M -jar minecraft_server.jar nogui' </code></pre> <p>Minecraft 1.8 (client game) works on the same computer so I don't think it's a java versioning issue.</p> <p>Is there an executable of the 1.8 server that can be used instead? If not, would installing the latest version using the .exe and replacing the .jar with 1.8 work?</p>
2
Python Django - print within a loop, inside view function
<p>I'm trying to find a way to print within a loop, inside a view function.</p> <p>I want to do something like this: </p> <pre><code>def some_page(request): for i in range(1, 5): print("&lt;span&gt;current index: %s&lt;/span&gt;") % (i) </code></pre> <p>But I need to use HttpResponse, (or render, but from what I learned until now, HttpResponse is for small things, like this)</p> <p>so I need to do</p> <pre><code>return HttpResponse("&lt;span&gt;current...") </code></pre> <p>Which will not works - because <code>return</code> will end the function.</p> <p>So how can i do function that will prints within loop ? (like the example above)</p> <p>*With Python, not in the template (not Jinja)</p> <p>Thanks in advance.</p>
2
Laravel : How to count in query
<p>I have the following query :</p> <pre><code>App\User::join('gift_sents', function($builder){ $builder-&gt;on('gift_sents.receiver_id', '=', 'users.id'); }) -&gt;select('users.*', 'COUNT(gift_sents.receiver_id as total_posts') -&gt;groupBy('gift_sents.id') -&gt;orderBy('total_posts', 'ASC') -&gt;limit(3)-&gt;get(); </code></pre> <p>The count isn't working, Its supposed to be working ! </p> <p>The following error comes up :</p> <p><code>Column not found: 1054 Unknown column 'COUNT(gift_sents.receiver_id' in 'field list' (SQL: select</code>users<code>.*,</code>COUNT(gift_sents<code>.</code>receiver_id<code>as</code>total_posts<code>from</code>users<code>inner join</code>gift_sents<code>on</code>gift_sents<code>.</code>receiver_id<code>=</code>users<code>.</code>id<code>group by</code>gift_sents<code>.</code>id<code>order by</code>total_posts<code>asc limit 3)</code></p>
2
InputStream closed unexpectedly while using Jersey MultiPart file upload & Server-Sent Events (SSE)
<p>I'm using Jersey Multipart for uploading file to the server via Rest API. In the resource method, I accessed the file content via InputStream. I want to return the uploaded file size to the client with <a href="https://jersey.java.net/apidocs/2.23.1/jersey/org/glassfish/jersey/media/sse/EventOutput.html" rel="nofollow">EventOutput</a> using <a href="https://jersey.java.net/documentation/latest/sse.html#overview" rel="nofollow">SSE</a> so the client easily get the uploaded file size directly from upload resource method. I'm using Jersey as JAX-RS implementation in java with Grizzly Http server. Here is my code:</p> <pre><code>@POST @Path("upload") @Produces(SseFeature.SERVER_SENT_EVENTS) @Consumes("multipart/form-data;charset=utf-8") public EventOutput upload(@FormDataParam("file") InputStream file, @FormDataParam("file") FormDataContentDisposition fileDisposition) { final EventOutput eventOutput = new EventOutput(); try { new Thread(new Runnable() { @Override public void run() { try { int read = -1; byte[] buffer = new byte[1024]; OutboundEvent.Builder eventBuilder = new OutboundEvent.Builder(); OutboundEvent event = null; long totalRead = 0, lastReadMB = 0; while ((read = file.read(buffer)) != -1) { totalRead += read; if (lastReadMB != (totalRead / (1024 * 1024))) { lastReadMB = totalRead / (1024 * 1024); event = eventBuilder.name("uploaded").data(Long.class, totalRead).build(); eventOutput.write(event); } } event = eventBuilder.name("uploaded").data(Long.class, totalRead).build(); eventOutput.write(event); } catch (Exception e) { throw new RuntimeException( "Error when writing the event.", e); } finally { try { eventOutput.close(); } catch (Exception ioClose) { throw new RuntimeException( "Error when closing the event output.", ioClose); } } } }).start(); return eventOutput; } catch (Exception e) { logger.error(e.toString(), e); } throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR). entity("something happened").build()); } </code></pre> <p>​ The problem is when my resource method return EventOutput as a response and request processing thread back to the I/O container, the InputStream closed and the processing thread can't access to the uploaded file. Here is the exception:</p> <pre><code>Exception in thread "Thread-1" java.lang.RuntimeException: Error when writing the event. at com.WebService.ContentService$1.run(ContentService.java:192) at java.lang.Thread.run(Thread.java:745) Caused by: org.jvnet.mimepull.MIMEParsingException: java.io.IOException: Stream Closed at org.jvnet.mimepull.WeakDataFile.read(WeakDataFile.java:115) at org.jvnet.mimepull.DataFile.read(DataFile.java:77) at org.jvnet.mimepull.FileData.read(FileData.java:69) at org.jvnet.mimepull.DataHead$ReadMultiStream.fetch(DataHead.java:265) at org.jvnet.mimepull.DataHead$ReadMultiStream.read(DataHead.java:219) at java.io.InputStream.read(InputStream.java:101) at com.WebService.ContentService$1.run(ContentService.java:181) ... 1 more Caused by: java.io.IOException: Stream Closed at java.io.RandomAccessFile.seek0(Native Method) at java.io.RandomAccessFile.seek(RandomAccessFile.java:557) at org.jvnet.mimepull.WeakDataFile.read(WeakDataFile.java:112) ... 7 more </code></pre> <p><br/>​ 1- What's the problem in the code? Why InputStream is closed in the middle of the file transfer?<br/><br/> 2- Is there any alternative way to return the uploaded file size to the client in server side? (REQUIREMENT: the upload resource method must handle upload file asynchronously in different thread)</p>
2
cx_Freeze: Python error in main script
<p>I am a beginner in python and django. This error keeps coming, even after installing cx_freeze from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#cx_freeze" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#cx_freeze</a> I am trying to make an executable file and I want to run my server through it, which I normally do by:</p> <pre><code>manage.py runserver </code></pre> <p>I am currently using commands:</p> <pre><code>setup.py build </code></pre> <p>I have already tried:</p> <pre><code>pyinstaller --name=mysite myproject_dir/manage.py </code></pre> <p>and my setup.py file contains</p> <pre><code>import sys from distutils.core import setup from cx_Freeze import setup, Executable setup( name = "Management System", version = "1.0", description = "A Database Management System", py_modules=['virtualenv'], executables = [Executable("manage.py", base = "Win32GUI")]) </code></pre> <p>I have also tried py2exe, it doesn't work. You can also suggest to read something for this knowledge.</p> <p><a href="http://i.stack.imgur.com/zHmiy.jpg" rel="nofollow">Here is the image of error that keeps appearing on running the exe file</a></p> <p>If I use this command: Barcode.exe runserver There also comes an error</p> <pre><code>WindowsError: [Error 3] The system cannot find the path specified:'C:\\Users\\D ell\\AppData\\Local\\Temp\\_MEI85~1\\Entry\\migrations/*.*' </code></pre>
2
How to get the marker-end position in svg?
<p>Below is the code you can run and see the output which is a black coloured line with a marker at its end position. </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;svg width="600px" height="200px"&gt; &lt;defs&gt; &lt;marker id="arrow" markerWidth="10" markerHeight="10" refx="0" refy="3" orient="auto" markerUnits="strokeWidth"&gt; &lt;path d="M0,0 L0,6 L9,3 z" fill="#000" /&gt; &lt;/marker&gt; &lt;/defs&gt; &lt;line x1="50" y1="50" x2="250" y2="150" stroke="#000" stroke-width="5" marker-end="url(#arrow)" /&gt; &lt;/svg&gt;</code></pre> </div> </div> </p> <p>I want to know whether its is possible to calculate the value of marker end position as shown in the image below<a href="https://i.stack.imgur.com/Wkdvw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wkdvw.png" alt="enter image description here"></a> with a circle in red color which is pointed by the arrow in red color? Is it possible mathematically to calculate the position of marker end?</p>
2
Observe progress of UIView.animateWithDuration/CABasicAnimation?
<p>Is there a way to observe the "time progress" of UIView.animateWithDuration...family of methods from UIView /alternatively CA animations?</p> <p>I am animating a view's frame and I need to be informed how it is progressing. My line of thinking was I can either </p> <p>1) tap into CAAnimation related stuff or </p> <p>2) observe the animated properties (like frame) and do my own calculations each screen frame.</p> <p>Approach 1) turns out to be a dead end, inspecting the internal of how CAAnimations work told me absolutely nothing...and 2) is flawed as the "model layer tree is updated immediately and tapping into the presentation tree is difficult as the presentation layer is nil when you start. </p> <p>I am pretty desperate, I was thinking that hooking into CADisplayLink will give me a tick and then I simply check something that is affected by the animation but there is nothing to tap to. Do you think going the NSTimer way that is launched in the same scope as the animation method is ok? If I know animation duration then I can generate the progress myself.</p>
2
BrowserMob proxy doesn't blacklist https resources
<p>I am using proxy to exclude third party resources . But I have a problem with all resources which start with https . Could you please suggest any solution ? For example I am trying to exclude static.licdn.com from <a href="http://linkedin.com" rel="noreferrer">http://linkedin.com</a> . It change status but download the resource .</p> <pre><code> public void setUp() throws Exception { setName("test"); try { FirefoxBinary firefoxbinary = new FirefoxBinary(new File("firefoxpath")); File file = new File("profilePath"); FirefoxProfile firefoxprofile = new FirefoxProfile(file); firefoxprofile.setPreference("browser.startup.homepage", "http://www.google.com"); BrowserMobProxyServer server = new BrowserMobProxyServer(); server.start(); ArrayList arraylist = new ArrayList(); arraylist.add(new BlacklistEntry(".*static\\.licdn\\.com.*", 204)); server.setBlacklist(arraylist); org.openqa.selenium.Proxy proxy = ClientUtil.createSeleniumProxy(server); proxy.setSslProxy("localhost:" + server.getPort()); DesiredCapabilities desiredcapabilities = new DesiredCapabilities(); desiredcapabilities.setCapability("proxy", proxy); desiredcapabilities.setCapability("acceptSslCerts", true); driver = new FirefoxDriver(firefoxbinary, firefoxprofile, desiredcapabilities); } catch(Throwable throwable) { LOG.error("Problem in setup: ", throwable); } } </code></pre> <ul> <li>browser mob version : 2.1.1 </li> <li>selenium version : 2.53 </li> <li>FF version : 46</li> </ul>
2
Ubuntu default port permissions
<p>I am trying to communicate with an external GPS device using UART on a Raspberry Pi, but I am having some issues with the default permissions on the serial port.</p> <pre><code> ubuntu@ubuntu:~$ ls -la /dev/ttyS0 crw--w---- 1 root tty 4, 64 Jul 2 17:43 /dev/ttyS0 </code></pre> <p>As you can see, the group 'tty' only has permission to write to the port, not read. This then leads to 'permission denied' messages when I try to read from the port in Python. I have been working around the problem for now using:</p> <pre><code> sudo chmod g+r /dev/ttyS0 </code></pre> <p>But this wont work forever, as the goal is for this port to be used automatically after startup.</p> <p>Is there a way to change the default permissions so that the group 'tty' always has read access?</p> <p>Running the unofficial Ubuntu 16.04 release on a Raspberry Pi 3.</p>
2
SQL Server stored procedure to read xml file
<p>I have an application where I want to list all the products that matches requested filter category. I can send all the filters from c# code via XML file. my XML file would look like...</p> <pre><code>&lt;filter CategoryId="" ForHomepage="" StartingIndex=""&gt; &lt;brand&gt; &lt;id&gt;&lt;/id&gt; &lt;id&gt;&lt;/id&gt; &lt;/brand&gt; &lt;os&gt; &lt;id&gt;&lt;/id&gt; &lt;id&gt;&lt;/id&gt; &lt;/os&gt; &lt;touch value="" /&gt; &lt;display&gt; &lt;id&gt;&lt;/id&gt; &lt;id&gt;&lt;/id&gt; &lt;/display&gt; &lt;ram&gt; &lt;id&gt;&lt;/id&gt; &lt;id&gt;&lt;/id&gt; &lt;/ram&gt; &lt;storage&gt; &lt;id&gt;&lt;/id&gt; &lt;id&gt;&lt;/id&gt; &lt;/storage&gt; &lt;camera&gt; &lt;id&gt;&lt;/id&gt; &lt;id&gt;&lt;/id&gt; &lt;/camera&gt; &lt;battery&gt; &lt;id&gt;&lt;/id&gt; &lt;id&gt;&lt;/id&gt; &lt;/battery&gt; &lt;/filter&gt; </code></pre> <p>I can read the XML and store the data in temp table but I want to read categoryid, touch, forhomepage and startingindex fields in variables declared in sp (an not in table because this is non repetitive data).</p> <p>Can anyone have such issues in past? To store the XML data in declared variables.</p> <p>Taken from OP's comment:</p> <pre><code>&lt;filter CategoryId="12" ForHomepage="true" StartingIndex="0"&gt; &lt;brand&gt; &lt;id&gt;1001&lt;/id&gt; &lt;id&gt;1006&lt;/id&gt; &lt;/brand&gt; &lt;os&gt; &lt;id&gt;7005&lt;/id&gt; &lt;id&gt;7009&lt;/id&gt; &lt;/os&gt; &lt;touch value="true" /&gt; &lt;display&gt; &lt;id&gt;3002&lt;/id&gt; &lt;id&gt;3005&lt;/id&gt; &lt;/display&gt; &lt;ram&gt; &lt;id&gt;2006&lt;/id&gt; &lt;id&gt;2009&lt;/id&gt; &lt;/ram&gt; &lt;storage&gt; &lt;id&gt;4006&lt;/id&gt; &lt;/storage&gt; &lt;camera&gt; &lt;id&gt;9009&lt;/id&gt; &lt;id&gt;9014&lt;/id&gt; &lt;/camera&gt; &lt;battery&gt; &lt;id&gt;1501&lt;/id&gt; &lt;id&gt;1581&lt;/id&gt; &lt;/battery&gt; &lt;/filter&gt; </code></pre>
2
Error while publishing a Web API with Entity Framework
<p>I created a Web Api using Entity Framework with Visual Studio 2015. A database is linked with the api. When I run it in Visual Studio, everything works fine and the url returns a json response. But when I publish the Api using Web Deploy method and run the following url <code>http://localhost/books/api/books/</code> I get an error:</p> <blockquote> <p>{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.",</p> <p>"ExceptionType":"System.Data.SqlClient.SqlException","StackTrace":" at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)\r\n at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)\r\n at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)\r\n at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)\r\n at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)\r\n at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal&amp; connection)\r\n at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource<code>1 retry, DbConnectionOptions userOptions, DbConnectionInternal&amp; connection)\r\n at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource</code>1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&amp; connection)\r\n at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<code>1 retry, DbConnectionOptions userOptions)\r\n at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource</code>1 retry)\r\n at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource<code>1 retry)\r\n at System.Data.SqlClient.SqlConnection.Open()\r\n at System.Data.Entity.Infrastructure.Interception.InternalDispatcher</code>1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action<code>2 operation, TInterceptionContext interceptionContext, Action</code>3 executing, Action<code>3 executed)\r\n at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)\r\n at System.Data.Entity.SqlServer.SqlProviderServices.&lt;&gt;c__DisplayClass33.&lt;UsingConnection&gt;b__32()\r\n at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.&lt;&gt;c__DisplayClass1.&lt;Execute&gt;b__0()\r\n at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func</code>1 operation)\r\n at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action<code>1 act)\r\n at System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable</code>1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)\r\n at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable<code>1 commandTimeout, StoreItemCollection storeItemCollection)\r\n at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)\r\n at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)\r\n at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)\r\n at System.Data.Entity.MigrateDatabaseToLatestVersion</code>2.InitializeDatabase(TContext context)\r\n at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)\r\n at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()\r\n at System.Data.Entity.Internal.RetryAction<code>1.PerformAction(TInput input)\r\n at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action</code>1 action)\r\n at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)\r\n at System.Data.Entity.Internal.Linq.InternalSet<code>1.Initialize()\r\n at System.Data.Entity.Internal.Linq.InternalSet</code>1.GetEnumerator()\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.WebHost.HttpControllerHandler.d__1b.MoveNext()"}</p> </blockquote> <p>Actually the same url when used while running the Visual Studio application with a port specified by it the url gives a JSON response. Please do help me. I am a beginner in this context. Sorry if there are any technical terms used incorrectly.</p>
2
how to copy and overwrite file in command prompt even if the file is being use by another program
<p>Hi all,</p> <p>I want copy file from one location to another in <strong>command prompt</strong> using <strong>XCOPY</strong> method of copying files in windows.</p> <p><p>It actually works fine, but the problem is whenever the file is used by another program is cannot be overwritten rather leave the files in the destination as it is.</p> <p>Here are the command i used.</p> <pre><code> if not exist "%systemdrive%\Program Files (x86)" ( if not exist "C:\Program Files\MySQL\MySQL Server 5.0\data\indigenedb" ( No Database to be restored ) else ( XCOPY "C:\Users\Engr\Desktop\hahahahah" "C:\Program Files (x86)\MySQL\MySQL Server 5.0\data\indigenedb" /D /E /C /R /I /K /Y /F ) ) else ( if not exist "C:\Program Files (x86)\MySQL\MySQL Server 5.0\data\indigenedb" ( No Database to be restored ) else ( XCOPY "C:\Users\Engr\Desktop\hahahahah" "C:\Program Files (x86)\MySQL\MySQL Server 5.0\data\indigenedb" /D /E /C /R /I /K /Y /F ) ) </code></pre> <p>The command would check if the system is not <strong>32-Bit</strong> Processor then the operation is going to be in <strong>C:\Program Files (x86)</strong> instead of <strong>C:\Program Files</strong>. and if the it is <strong>32-Bit</strong> not <strong>64-Bit</strong> then it would perform the operation in <strong>C:\Program Files</strong>.</p> <p>Thank you.</p>
2
how to retrieve multiple array json with php
<p>i know it sounds so easy. just use foreach looping or <strong>json_decode</strong>, and you can retrieve json data. </p> <p>yeah it was, until i got multiple array json when trying retrieving data from elasticsearch.</p> <p>im confused how to retrieve this :</p> <pre><code>{ "took":3, "status": "taken", "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total":2, "msg":"ilusm", "hits": [ { //goes here "id":1234 }, { //goes here "id":4321 } ] }, "date-created": "2016-06-06" } </code></pre> <p>i use this to retrieve my first data :</p> <pre><code>$result = json_decode(json_encode($product),true); echo "total took:"; echo $result['took']; echo "total shards:"; echo $result['_shards']['total']; </code></pre> <p>the problem is,i cant retrieve data inside hits. how can i retrieve hits id : 1234 ?</p> <pre><code>echo"view all total hits :"; echo $result['hits']['total']; echo"view all total msg:"; echo $result['hits']['msg']; echo"view hist data :"; echo json_decode(json_encode($result['hits']['hits']), true); </code></pre> <p>i got this <strong>error</strong> :</p> <blockquote> <p>Message: Array to string conversion</p> </blockquote> <p>please help me to fix this out. many thanks in advance.</p>
2
jQuery slideUp on Table Row and remove
<p>I'm having trouble with the following code. I'm trying to remove a specific row from a table using jQuery, but I'd like to use the slideUp effect so the row slides up and then removes itself. I've tried the following, but it does not seem to respect the effect. It just removes itself.</p> <pre><code>$('[data-company-id='+companyId+']').closest('tr').slideUp('fast', function() { $(this).remove(); }); </code></pre> <p>My table row contains a button in one of the cells with a data-company-id attribute. This does work in getting the right cell, and corresponding parent and remove it. But it does not slide Up before the remove.</p> <p>What am I doing wrong?</p>
2
AudioSource in Unity3D does not play WAV file
<p>I am updating an AudioSource in Unity3D during runtime when I click.</p> <p>I created a Cube game object. </p> <p>When I click the cube I send properties to my AudioSource. </p> <p><strong>NOTE:</strong> this is to eventually play many other wav files that are passed in via a string array of pipe delimited wav files (which exist in the Assets Audio folder). </p> <p>So I need to update the AudioSource with each CLICK EVENT whereby each time it will load a new file selected from the array.</p> <p>Okay, the Unity3D Editor shows my public variables from the script, and it fills them out at runtime (upon clicking the cube.)</p> <p>My <strong>path</strong> variable shows up perfectly in the Unity3D editor.</p> <p>But the problem is although the <strong>Audio Clip</strong> <em>property</em> in the editor shows the small orange audio logo (as if something is there/loaded), the name of the file that I grabbed from my Assets/Audio folder is always empty.</p> <p>Nothing plays, but I get <strong>no errors</strong>!</p> <p>And the properties <em>playOnAwake</em>, <em>volume</em>, <em>etc</em>. all show me exactly what I express them to do via my script.</p> <p><strong>NOTE:</strong> In the first image, the <strong>path</strong> <em>variable</em> correctly points to the .wav file.</p> <p>Why is my .wav not playing? </p> <p>Why is the .wav filename not appearing in the <strong>Audio Clip</strong> text box area?</p> <p><a href="https://i.stack.imgur.com/zDLcB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zDLcB.png" alt="My publicly declared variables in the script."></a></p> <p><a href="https://i.stack.imgur.com/m8ZcK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m8ZcK.png" alt="My created Audio Source."></a></p> <pre><code>public Color clickColor; public Color releaseColor; public int clickcount = 0; public WWW www; public AudioClip myAudioClip; public string path; void CubeClicked(GameObject tmpGameObject) { // CLICK COUNT clickcount++; // CLICK COLOR tmpGameObject.GetComponent&lt;Renderer&gt;().materials[0].color = clickColor; // IS TRIGGER tmpGameObject.GetComponent&lt;Collider&gt;().isTrigger = true; //AUDIO path = "file://" + Application.dataPath.Substring(0, Application.dataPath.LastIndexOf("/")) + "/Assets/Audio/JetEngine.wav"; www = new WWW(path); myAudioClip = www.audioClip; tmpGameObject.GetComponent&lt;AudioSource&gt;().clip = myAudioClip; tmpGameObject.GetComponent&lt;AudioSource&gt;().playOnAwake = false; tmpGameObject.GetComponent&lt;AudioSource&gt;().volume = 0.999f; tmpGameObject.GetComponent&lt;AudioSource&gt;().Play(); } </code></pre>
2
JDK version showing 1.8.0_92 in Command Prompt, but not being able to import in NetBeans or Eclipse
<p>java - version in DOS shows the version to be </p> <p>java version "1.8.0_91".</p> <p>However, my code <a href="http://pastebin.com/kSZKszYy" rel="nofollow">http://pastebin.com/kSZKszYy</a> in Eclipse is showing major.minor error 52. A little research told me there was a mismatch in my code and the JDK version I am running. In windows->preferences I found out my JDK to be version 1.7.</p> <p>I could not try and import 1.8 which is supposedly already present on my computer. </p> <p>A step by step approach of how to import the newer version of JDK will be appreciated. </p> <p>JDK version I have installed is jre-8u91-windows-x64.exe. </p> <p>My Machine runs on windows 10 and has a 64 bit architecture. </p> <p>I am running Eclipse Mars. </p>
2
How to make a RecyclerView adapter to get 3 items of an arraylist in every row
<p>I need some help with a RecyclerView.Adapter. I pass to a recyclerview adapter an arraylist of object Dart, I have an simple_list_item.xml where it has 3 textviews (dart1Txt, dart2Txt and dart3Txt). I want the adapter to get the values from the arraylist and fill the textviews. For example I have the values 10, 20, 30, 3, 5, 6 and I want to be printed like that</p> <p>10 20 30</p> <p>3 5 6</p> <p>and so on.</p> <p>I cant understand how to make this. This my onBindViewHolder.</p> <pre><code>onBindViewHolder(RoundsStatsAdapter.ViewHolder holder, int position){ Dart dart = mDarts.get(position); holder.dart1Textview.setText(String.valueOf(dart.getScore())); } </code></pre> <p><strong>Update for more info:</strong> I have a Dart object which has a field dartScore. I sent an arrayList of Dart objects and I want the recyclerview adapter to get the first 3 Darts from the arraylist and fill the 3 textviews with the dartScore, after that take the next 3 Darts from the arraylist and to a new row fill again the 3 textviews and so on.</p> <p>Thank you</p>
2
SpringBoot Couchbase Integration
<p>I want to make a filterable list of my UserTask entity with the QueryDslPredicateExecutor interface, so the parameters given in the query string will be autoprocessed into a Predicate.</p> <p>I have the following classes/interfaces</p> <pre><code>public interface UserTaskQuerydslRepository extends CrudRepository&lt;UserTask, String&gt;, QueryDslPredicateExecutor&lt;UserTask&gt;, QuerydslBinderCustomizer&lt;QUserTask&gt; { @Override default void customize(QuerydslBindings bindings, QUserTask userTask) { ... } } </code></pre> <p>UserTask is my class that represents the (couchbase) model</p> <pre><code>@QueryEntity @Document(expiry = 0) public class UserTask { @Id private String id; ... } </code></pre> <p>If i annotate this class with @QueryEntity then Maven generates the QUserTask class for me</p> <pre><code>@Generated("com.mysema.query.codegen.EntitySerializer") public class QUserTask extends EntityPathBase&lt;UserTask&gt; { private static final long serialVersionUID = 493434469L; public static final QUserTask userTask = new QUserTask("userTask"); public final StringPath id = createString("id"); ... public QUserTask(String variable) { super(UserTask.class, forVariable(variable)); } public QUserTask(Path&lt;? extends UserTask&gt; path) { super(path.getType(), path.getMetadata()); } public QUserTask(PathMetadata&lt;?&gt; metadata) { super(UserTask.class, metadata); } } </code></pre> <p>To generate QUserTask i added the following lines to pom.xml</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;com.mysema.maven&lt;/groupId&gt; &lt;artifactId&gt;apt-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.1.3&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;goals&gt; &lt;goal&gt;process&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;outputDirectory&gt;target/generated-sources/apt&lt;/outputDirectory&gt; &lt;processor&gt;com.mysema.query.apt.jpa.JPAAnnotationProcessor&lt;/processor&gt; &lt;processor&gt;com.mysema.query.apt.QuerydslAnnotationProcessor&lt;/processor&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;com.mysema.querydsl&lt;/groupId&gt; &lt;artifactId&gt;querydsl-apt&lt;/artifactId&gt; &lt;version&gt;3.4.3&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/plugin&gt; </code></pre> <p>In the project we have both JPA entities and couchbase entities, that's why i have the JPAAnnotationProcessor there.</p> <p>If i run the application like this i get the following error:</p> <blockquote> <p>org.springframework.data.mapping.PropertyReferenceException: No property findAll found for type UserTask!</p> </blockquote> <p>I tried to annotate my UserTaskQuerydslRepository with @NoRepositoryBean, it solved my findAll problem, but when i tries to @Inject this repository to a Resource (or controller, JHipster calls it Resource) i get the following error</p> <blockquote> <p>No qualifying bean of type [.UserTaskQuerydslRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}</p> </blockquote> <p>Can anyone help me what did I do wrong?</p>
2
error in syncing project after upgrading Firebase to 9.2.0
<p>I want to use firebase in my project and it needs the latest version of dependencies inside .gradle file but when I set the version to latest which is 9.2.0 it doesn't and gives error but when I set it to previous version it works the previous version is 9.0.2 . This is my .gradle file : </p> <pre><code> apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion '23.0.3' defaultConfig { applicationId "naqibshayea.afghanbazaar" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } repositories { mavenCentral() } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:appcompat-v7:23.3.0' compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2' compile 'com.android.support:design:23.3.0' compile 'com.android.support:recyclerview-v7:23.3.0' compile 'com.android.support:support-v4:23.3.0' compile 'com.mcxiaoke.volley:library:1.0.19' compile 'com.firebase:firebase-client-android:2.5.2+' compile 'com.facebook.android:facebook-android-sdk:[4,5)' compile 'com.google.firebase:firebase-core:9.2.0' compile 'com.google.firebase:firebase-auth:9.2.0' compile 'com.google.firebase:firebase-database:9.2.0' compile 'com.google.firebase:firebase-config:9.2.0' } apply plugin: 'com.google.gms.google-services' </code></pre> <p>and this is the error it shows :</p> <pre><code>Error:(37, 13) Failed to resolve: com.google.firebase:firebase-config:9.2.0 Error:(35, 13) Failed to resolve: com.google.firebase:firebase-auth:9.2.0 Error:(36, 13) Failed to resolve: com.google.firebase:firebase-database:9.2.0 Error:(34, 13) Failed to resolve: com.google.firebase:firebase-core:9.2.0 </code></pre>
2
Change text background color for hyper link in PHPExcel
<p>In my <code>PHPExcel</code> library, I changed the color of hyper link using the below code</p> <pre><code>$link_style_array = array( 'font' =&gt; array( 'color' =&gt; array('rgb' =&gt; '0000FF'), 'underline' =&gt; 'single' ) ); $sheet-&gt;getStyle("A1")-&gt;applyFromArray($link_style_array); </code></pre> <p>And it works perfect. But the text have a background color like the below image</p> <p><a href="https://i.stack.imgur.com/Yprlh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Yprlh.png" alt="enter image description here"></a></p> <p><strong>I would like to remove the background color or make it white.</strong></p> <p>Is there any way to do the same? Any help could be appreciated</p>
2
AutoSave files in NetBeans
<p>Tell me please is it possible to NetBeans IDE 8.1 will automatically save files like in IntelliJ IDEA, i.e. not constantly pushing <kbd>Ctrl</kbd> + <kbd>S</kbd>.</p>
2
Swift Redundant conformance
<p>I am learning iOS. And now local database on iOS. I'm from Android and finding local DB a bit difficult to understand. I wrote a question which brought me several down votes (instead of simple use of <code>CoreStore</code> or <code>Sync</code> or <code>MagicalRecord</code>). I then started reading <a href="https://www.raywenderlich.com/106856/getting-started-magicalrecord" rel="nofollow">this tutorial</a>. After downloading the sample project I'm getting <code>Redundant conformance of 'BeerListViewController' to protocol 'UITableViewDataSource'</code> error in <code>BeerListViewController</code>. Please tell me how can I get it solved.</p> <p>Here is the code:</p> <pre><code>import UIKit import Foundation class BeerListViewController: UITableViewController { @IBOutlet weak var sortByControl: UISegmentedControl! @IBOutlet weak var searchBar: UISearchBar! let sortKeyName = "name" let sortKeyRating = "beerDetails.rating" let wbSortKey = "wbSortKey" //------------------------------------------ // Rating var amRatingCtl: AnyObject! let beerEmptyImage: UIImage = UIImage(named: "beermug-empty")! let beerFullImage: UIImage = UIImage(named: "beermug-full")! //##################################################################### // MARK: - Initialization required init(coder aDecoder: NSCoder) { // Automatically invoked by UIKit as it loads the view controller from the storyboard. amRatingCtl = AMRatingControl(location: CGPointMake(190, 10), emptyImage: beerEmptyImage, solidImage: beerFullImage, andMaxRating: 5) // A call to super is required after all variables and constants have been assigned values but before anything else is done. super.init(coder: aDecoder)! } //##################################################################### // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Allows data to be passed to the new view controller before the new view is displayed. // "destinationViewController" must be cast from its generic type (AnyObject) to the specific type used in this app // (BeerDetailViewController) before any of its properties can be accessed. let controller = segue.destinationViewController as? BeerDetailViewController if segue.identifier == "editBeer" { controller!.navigationItem.rightBarButtonItems = [] //------------------------------------------------------------------------------------ } else if segue.identifier == "addBeer" { controller!.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: controller, action: "cancelAdd") controller!.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: controller, action: "addNewBeer") } } //##################################################################### // MARK: - UIViewController - Responding to View Events override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //------------------------------------------ // Sorting Key if !(NSUserDefaults.standardUserDefaults().objectForKey(wbSortKey) != nil) { // User's sort preference has not been saved. Set default to sort by rating. NSUserDefaults.standardUserDefaults().setObject(sortKeyRating, forKey: wbSortKey) } // Keep the sort control in the UI in sync with the means by which the list is sorted. if NSUserDefaults.standardUserDefaults().objectForKey(wbSortKey) as! String == sortKeyName { sortByControl.selectedSegmentIndex = 1 } //------------------------------------------ fetchAllBeers() // Cause tableView(cellForRowAtIndexPath) to be called again for every visible row in order to update the table. tableView.reloadData() } //##################################################################### // MARK: - UIViewController - Managing the View // viewDidLoad() is called after prepareForSegue(). override func viewDidLoad() { super.viewDidLoad() //------------------------------------------ tableView.contentOffset = CGPointMake(0, 44) } //##################################################################### // MARK: - Action Methods @IBAction func sortByControlChanged(sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: NSUserDefaults.standardUserDefaults().setObject(sortKeyRating, forKey: wbSortKey) fetchAllBeers() tableView.reloadData() case 1: NSUserDefaults.standardUserDefaults().setObject(sortKeyName, forKey: wbSortKey) fetchAllBeers() tableView.reloadData() default: break } } //##################################################################### // MARK: - MagicalRecord Methods func fetchAllBeers() { } //##################################################################### func saveContext() { } //##################################################################### } //##################################################################### // MARK: - Table View Data Source extension BeerListViewController: UITableViewDataSource { // THE ERROR APPEARS HERE //##################################################################### // MARK: Configuring a Table View override func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int { return 1 } //##################################################################### override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return 10 } //##################################################################### override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { let cellIdentifier = "Cell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) configureCell(cell!, atIndex: indexPath) return cell! } //##################################################################### // MARK: Helper Methods func configureCell(cell: UITableViewCell, atIndex indexPath: NSIndexPath) { //------------------------------------------ // Rating let ratingText = "" let myRect = CGRect(x:250, y:0, width:200, height:50) var ratingLabel = UILabel(frame: myRect) if !(cell.viewWithTag(20) != nil) { ratingLabel.tag = 20 ratingLabel.text = ratingText cell.addSubview(ratingLabel) } else { ratingLabel = cell.viewWithTag(20) as! UILabel } //---------------------- ratingLabel.text = ratingText } //##################################################################### // MARK: Inserting or Deleting Table Rows override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -&gt; Bool { return true } //##################################################################### override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // When the commitEditingStyle method is present in a view controller, the table view will automatically enable swipe-to-delete. if (editingStyle == .Delete) { } } //##################################################################### } //##################################################################### // MARK: - Search Bar Delegate extension BeerListViewController: UISearchBarDelegate { // MARK: Editing Text func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if searchBar.text != "" { performSearch() } else { fetchAllBeers() tableView.reloadData() } } //##################################################################### func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchBar.showsCancelButton = true } //##################################################################### // MARK: Clicking Buttons func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() searchBar.text = "" searchBar.showsCancelButton = false fetchAllBeers() tableView.reloadData() } //##################################################################### func searchBarSearchButtonClicked(searchBar: UISearchBar) { // This method is invoked when the user taps the Search button on the keyboard. searchBar.resignFirstResponder() performSearch() } //##################################################################### // MARK: Helper Methods func performSearch() { tableView.reloadData() } //##################################################################### // MARK: - Bar Positioning Delegate // UISearchBarDelegate Protocol extends UIBarPositioningDelegate protocol. // Method positionForBar is part of the UIBarPositioningDelegate protocol. // This delegate method is required to prevent a gap between the top of the screen and the search bar. // That happens because, as of iOS 7, the status bar is no longer a separate area but is directly drawn on top of the view controller. func positionForBar(bar: UIBarPositioning) -&gt; UIBarPosition { // Tell the search bar to extend under the status bar area. return .TopAttached } //##################################################################### } </code></pre>
2
How to Save multiple images on database using PHP Script
<p>On my custom CMS, </p> <p>I am successfully able to save all the values from the admin form into the database.</p> <p>All of these have a single value, but what about multiple element? </p> <p>How can I save the input file with more than one image ?</p> <p>Here is my full code of the add post page:</p> <pre><code>&lt;?php if(isset($_POST['submit'])) { $title_bg = $_POST['title_bg']; $title_en = $_POST['title_en']; $body_bg = $_POST['body_bg']; $body_en = $_POST['body_en']; $image = $_FILES['image']['name']; $image_tmp = $_FILES['image']['tmp_name']; move_uploaded_file($image_tmp, '../uploads/' . $image); $status = $_POST['status']; $query = "INSERT INTO posts(title_bg, title_en, body_bg, body_en, image, status, created) "; $query .= "VALUES('$title_bg', '$title_en', '$body_bg', '$body_en', '$image', '$status', now())"; $create_post = mysqli_query($connection, $query); header("Location: posts.php"); } ?&gt; &lt;form action="" method="post" enctype="multipart/form-data"&gt; &lt;div class="form-item"&gt; &lt;label for="title_bg"&gt;Post title BG&lt;/label&gt; &lt;input type="text" name="title_bg"&gt; &lt;/div&gt; &lt;div class="form-item"&gt; &lt;label for="title_en"&gt;Post title EN&lt;/label&gt; &lt;input type="text" name="title_en"&gt; &lt;/div&gt; &lt;div class="form-item"&gt; &lt;label for="body_bg"&gt;Post body BG&lt;/label&gt; &lt;textarea id="editor" name="body_bg" rows="10" cols="30"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-item"&gt; &lt;label for="body_en"&gt;Post body EN&lt;/label&gt; &lt;textarea id="editor2" name="body_en" rows="10" cols="30"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-item"&gt; &lt;label for="image"&gt;Image&lt;/label&gt; &lt;input type="file" name="image"&gt; &lt;/div&gt; &lt;div class="form-item"&gt; &lt;label for="status"&gt;Post status&lt;/label&gt; &lt;select name="status"&gt; &lt;option value="published"&gt;published&lt;/option&gt; &lt;option value="draft"&gt;draft&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="form-item"&gt; &lt;input type="submit" class="form-submit" name="submit" value="Submit"&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>Right now the image value is saving into the database image field like this: sample-1.jpg.</p> <p>As far as I know, in HTML multiple element has the attribute <strong>multiple</strong> and using array this line should be like this:</p> <pre><code>&lt;input type="file" name="image[]" multiple&gt; </code></pre> <p>but how do I set an array element $image and save the multiple values into one field, so when I upload let's say three images, the saved values in the database image field should be like this: sample-1.jpg, sample-2.jpg, sample-3.jpg</p>
2
Powershell Use Parameterized Queries
<p>I am trying to insert data into a SQL Server. Without Parameters, this works fine</p> <pre><code>$adw_command.CommandText = "INSERT INTO dbo.facts (factID, factName, factKey, factDiv) VALUES ('$factID', '$factName', '$factKey', '$factDiv')" $adw_command.ExecuteNonQuery() </code></pre> <p>When I try to use Parameters like this, it does not work</p> <pre><code>$adw_command.CommandText = "INSERT INTO dbo.facts (factID, factnName, factKey, factDiv) VALUES (@factID, @factName, @factKey, @factDiv)" $adw_command.Prepare() $adw_command.Parameters.AddWithValue('@factID', $factID) $adw_command.Parameters.AddWithValue('@factName', $factName) $adw_command.Parameters.AddWithValue('@factKey', $factKey) $adw_command.Parameters.AddWithValue('@factDiv', $factDiv) $adw_command.ExecuteNonQuery() </code></pre> <p>I must be missing something obvious</p>
2
JavaFX thread makes the UI unresponsive , any alternative [Thread delay]
<p>JavaFX thread is making the UI slow and it hangs.</p> <p>This is the code, if anyone can suggest the reason or an alternative, it would be helpful.</p> <p>It's an MVC application. when the code hits this thread it works fine and UI do not hang but it's not then it become blank and unresponsive.</p> <p>It's a thread delay issue.</p> <pre><code>Platform.runLater(new Runnable() { @Override public void run() { DecimalFormat df = new DecimalFormat("#,##0.00"); setLabel(bidSide, viewResource_.getString(SELL), 95, 121, JFXConstants.jfxWhiteSmoke); setLabel(askSide, viewResource_.getString(BUY), 145, 121, JFXConstants.jfxWhiteSmoke); setLabel(bidAmount, df.format(0.0), 0, 122, JFXConstants.jfxGrey); setLabel(askAmount, df.format(0.0), 146, 122, JFXConstants.jfxGrey); bidAmount.setPrefWidth(110); bidAmount.setScaleX(0.87); bidAmount.setScaleY(0.87); bidAmount.setAlignment(Pos.CENTER_LEFT); askAmount.setPrefWidth(110); askAmount.setScaleX(0.87); askAmount.setScaleY(0.87); askAmount.setAlignment(Pos.CENTER_RIGHT); unlock.setVisible(false); lock.setVisible(false); lock.setOpacity(0.7); root.setStyle(FX_BACKGROUND_COLOR + fxBlackString); greyPanel = createRectangle(310.0, 135.0, JFXConstants.jfxGrey, 0.0, 5.0); greyPanel.setOpacity(0.6); root.getChildren().add(greyPanel); if (getFastFXController().getModel() != null &amp;&amp; getFastFXController().getModel() .getCurrency_() != null &amp;&amp; !getFastFXController().getModel().getCurrency_().equals(LNFConstants.EMPTY_STRING)) { try { javafx.scene.image.Image image = new javafx.scene.image.Image(setImagePath(getFastFXController().getModel() .getCurrency_())); flagView = new ImageView(image); } catch (Exception e) { flagView = new ImageView(); } flagView.setLayoutX(6.0); flagView.setLayoutY(11.0); flagView.setFitWidth(242); flagView.setFitHeight(108); root.getChildren().add(flagView); } bidRect = new javafx.scene.shape.Rectangle(); offerRect = new javafx.scene.shape.Rectangle(); nearTenorGroup.getChildren().addAll(nearTenorRect, createJFxLabel(nearLabel, NEAR, 1, 0, JFXConstants.jfxWhite, javafx.scene.text.Font.font(FONT_ARIAL, FontWeight.NORMAL, 12)), createJFxLabel(tenor_, FastFXView.this.getFastFXController().getModel().getTenor_(), 9, 7, JFXConstants.jfxWhite, javafx.scene.text.Font.font(FONT_ARIAL, FontWeight.EXTRA_BOLD, 14)) ); nearLabel.setOpacity(0.4); tenor_.setOnMouseClicked(new EventHandler&lt;javafx.scene.input.MouseEvent&gt;() { @Override public void handle(javafx.scene.input.MouseEvent mouseEvent) { popUpGroups.get(NEAR_TENOR).requestFocus(); popUpGroups.get(NEAR_TENOR).setVisible(true); popUpGroups.get(NEAR_TENOR).setLayoutX(219); popUpGroups.get(NEAR_TENOR).setLayoutY(1); popUpGroups.get(NEAR_TENOR).requestFocus(); tenor_.setTextFill(JFXConstants.jfxGrey); } }); tenor_.setOnMouseEntered(new EventHandler&lt;javafx.scene.input.MouseEvent&gt;() { @Override public void handle(javafx.scene.input.MouseEvent mouseEvent) { tenor_.setOpacity(0.8); } }); tenor_.setOnMouseExited(new EventHandler&lt;javafx.scene.input.MouseEvent&gt;() { @Override public void handle(javafx.scene.input.MouseEvent mouseEvent) { tenor_.setOpacity(1); } }); root.getChildren().add(nearTenorGroup); farTenorGroup.getChildren().addAll(farTenorRect, createJFxLabel(farLabel, FAR, 1, 0, JFXConstants.jfxWhite, javafx.scene.text.Font.font(FONT_ARIAL, FontWeight.NORMAL, 12)), createJFxLabel(tenorFar_, FastFXView.this.getFastFXController().getModel().getTenorFar_(), 9, 7, JFXConstants.jfxWhite, javafx.scene.text.Font.font(FONT_ARIAL, FontWeight.EXTRA_BOLD, 14)) ); farLabel.setOpacity(0.4); tenorFar_.setOnMouseClicked(new EventHandler&lt;javafx.scene.input.MouseEvent&gt;() { @Override public void handle(javafx.scene.input.MouseEvent mouseEvent) { popUpGroups.get(FAR_TENOR).requestFocus(); popUpGroups.get(FAR_TENOR).setVisible(true); popUpGroups.get(FAR_TENOR).setLayoutX(219); popUpGroups.get(FAR_TENOR).setLayoutY(5); popUpGroups.get(FAR_TENOR).requestFocus(); tenorFar_.setTextFill(JFXConstants.jfxGrey); } }); tenorFar_.setOnMouseEntered(new EventHandler&lt;javafx.scene.input.MouseEvent&gt;() { @Override public void handle(javafx.scene.input.MouseEvent mouseEvent) { tenorFar_.setOpacity(0.8); } }); tenorFar_.setOnMouseExited(new EventHandler&lt;javafx.scene.input.MouseEvent&gt;() { @Override public void handle(javafx.scene.input.MouseEvent mouseEvent) { tenorFar_.setOpacity(1); } }); root.getChildren().add(farTenorGroup); nearTenorGroup.setLayoutX(257); nearTenorGroup.setLayoutY(10); farTenorGroup.setLayoutX(257); farTenorGroup.setLayoutY(25); setItemsForPopup(NEAR_TENOR, getFastFXController().getModel().getTenors_()); setItemsForPopup(FAR_TENOR, getFastFXController().getModel().getTenorsFar_()); mapRectToPane(bidRect, liveBid); mapRectToPane(offerRect, liveAsk); bidRect.setFill(JFXConstants.jfxTransparent); offerRect.setFill(JFXConstants.jfxTransparent); root.getChildren().addAll(liveBid, liveAsk); root.getChildren().addAll(flip, toggle, lock, unlock); root.getChildren().addAll(offerRect, bidRect); root.getChildren().addAll(bidSide, bidAmount, askSide, askAmount); mouseEvents(); } } </code></pre>
2
Why does Python's pathlib and os lib return different results for mapped network drives in Windows?
<p>Trying to resolve a path using Python 3 on Windows 10. The path in question is available as a Mapped Network Drive. (This happens to be done through VirtualBox Shared Folders, but I hope that is not relevant here).</p> <p>The good old <code>os.path.abspath</code> gives me a path that starts with the drive letter that was mapped in Windows. This is exactly what I expected and needed.</p> <p>But when I try to upgrade to <code>pathlib</code>'s <code>resolve</code> function, I get a different result, in UNC notation. This is not expected, and not useful for my purposes. (Many programs do not accept UNC paths as input, they require a 'local' path.)</p> <ol> <li>What is the reason for this difference?</li> <li>How can one control this behavior so that <code>pathlib</code> can return a drive-letter-based path?</li> <li>Can anyone point me to documentation of this? I cannot find it in Python's documentation.</li> </ol> <p>Demonstration:</p> <pre><code>PS C:\Users\user&gt; python Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; import pathlib &gt;&gt;&gt; path = 'd:\\asdf' &gt;&gt;&gt; print(os.path.abspath(path)) d:\asdf &gt;&gt;&gt; print(pathlib.Path(path).resolve()) \\vboxsrv\code\asdf </code></pre>
2
Responsive Layout with DIV Percentages
<p>I've have started working on a new PHP based chat system for one of my projects and recently I've been spending a lot of time reading about Responsive layouts, I've decided that I'd like to avoid using bootstrap even so it does offer lots of great features, and I feel there is more to learn in doing things from scratch then using an already established set of code...that being said.</p> <p>Here is some sample code I put together that is not behaving the way I expected.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;Chat Room &lt;/title&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width; initial-scale=1.0l; maximum-scale=1.0; user-scalable=0;" &gt; &lt;style type="text/css"&gt; #container { position:relative; width:90%; height:600px; margin: 0 auto; border: 1px solid red; } #messages { width:75%; margin:5px; padding:10px; height:80%; border: 1px solid blue; float: left; } #users { width:21%; margin:5px; padding:10px; height:80%; border: 1px solid green; float: left; } #message_entry { width:100%; margin:5px; padding:10px; height:20%; border: 1px solid green; clear: left; } &lt;/style&gt; &lt;/head&gt; &lt;body width="device-width"&gt; &lt;div id="container"&gt; &lt;div id="messages"&gt; Existing Messages &lt;/div&gt; &lt;div id="users"&gt; User List &lt;/div&gt; &lt;div id="message_entry"&gt; New Message Box &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I noticed that the percentages assigned to inner DIV's don't seem to relate to their parent div as in the case of "message_entry" to the container.</p> <p>Any thoughts would be much appreciated.</p>
2
Java - ConcurrentModificationException in multithreaded program, Set is wrapped with synchronized
<p>I have a crash in the following code:</p> <pre><code>private LocalBundle(Bundle b, Map&lt;Bundle, LocalBundle&gt; clonnedObjs) { this(); synchronized (b.getVariables()) { // b.getVariables() is Set addFrom(b, clonnedObjs); } } </code></pre> <p>but in addFrom I get the crash:</p> <pre><code>private synchronized void addFrom(Bundle b, Map&lt;Bundle, LocalBundle&gt; clonnedObjs) { Set&lt;TaintedVariable&gt; variablesOfBundle = b.getVariables(); for(TaintedVariable v : variablesOfBundle) { </code></pre> <p>Exception message:</p> <pre><code>Exception in thread "pool-4-thread-1" java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextNode(Unknown Source) at java.util.HashMap$KeyIterator.next(Unknown Source) at x.y.z.LocalBundle.addFrom(VisitedNodesWithBundle.java:198) </code></pre> <p>Does someone know why it happens? I wrapped with <code>synchronized (b.getVariables())</code>, but it looks like that two threads are executing <code>for(TaintedVariable v : variablesOfBundle)</code> </p>
2
Notice: Undefined index: roles in Symfony 2.7
<p>I am trying to learn Symfony2 and currently : Entity Relationships/Associations (Joining to Related Records) . I have a problem I can not get correct</p> <blockquote> <p>Notice: Undefined index: roles 500 Internal Server Error - ContextErrorException</p> </blockquote> <p>This is the my code:</p> <p>*Class Role:</p> <pre><code>class Roles { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="nom_roles", type="string", length=225, nullable=false) *@Assert\NotBlank(message="le champ nom du role est obligatoire") * */ Private $name_role; /** * @var ArrayCollection $groups * * @ORM\OneToMany(targetEntity="Groups", mappedBy="roles", cascade={"persist","merge"}) *@Assert\Valid() */ protected $groups; /** * @var ArrayCollection Permissions $permision * * @ORM\ManyToMany(targetEntity="Permissions", inversedBy="roleGroup", cascade={"persist", "merge"}) * @ORM\JoinTable(name="roles_permissions", * joinColumns={@ORM\JoinColumn(name="id_rolesGR", referencedColumnName="id")}, * inverseJoinColumns={@ORM\JoinColumn(name="id_permGR", referencedColumnName="id_per")} * ) * @Assert\Valid() */ protected $permissions_role; /** * Roles constructor. */ public function __construct() { $this-&gt;groups = new ArrayCollection(); $this-&gt;permissions_role = new ArrayCollection(); } </code></pre> <p>-class permissions: </p> <pre><code>class Permissions { /** * @var integer * * @ORM\Column(name="id_per", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * @ORM\Column(name="nom_permisions", length=255, nullable=true) * @Assert\NotBlank(message="le choix des permissions sont obligatoire") */ private $name_permissions; /** * @var ArrayCollection Roles $roleGroup * * Inverse Side * * @ORM\ManyToMany(targetEntity="Roles", mappedBy="permissions", cascade={"persist", "merge"}) *@Assert\Valid() */ protected $roleGroup; </code></pre> <p>-Class Groups:</p> <pre><code>class Groups { /** * @var integer * * @ORM\Column(name="id_groupes", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") * */ private $id; /** * @var string * *-- contrainte sur le chmap * * @Assert\NotBlank(message="le champ nom du groupe est obligatoire") * * @Assert\Type( * type="string", * message="la valeur {{ value }} n'est pas valide {{ type }}. * Elle est de type chaine des cractéres" * ) * * @Assert\Length( * min=5, * max= 50, * minMessage="votre nom du groupe doit comprendre au moins {{ limit }} caractéres", * maxMessage="votre nom du groupe doit comprendre au maximun {{ limit }} caractéres" * ) * * @ORM\Column(name="nom_groupe", type="string", length=225, nullable=false) *@Assert\NotBlank(message="le champ nom du groupe est obligatoire") * * */ Private $name_groups; /** * @var DateTime() * * @ORM\Column(name="date_creation", type="datetime",nullable=false) * *@Assert\DateTime() */ private $date_create; /** * @ORM\OneToOne(targetEntity="Images", cascade={"persist", "merge", "remove"}) * @ORM\JoinColumn(name="image_id", referencedColumnName="id_images") * @Assert\Valid() */ protected $image; /** * @var Roles $role * * @ORM\ManyToOne(targetEntity="Roles", inversedBy="groups", cascade={"persist", "merge"}) * @ORM\JoinColumns({ * @ORM\JoinColumn(name="role_id", referencedColumnName="id", nullable=false) * }) * @Assert\Valid() */ protected $role; </code></pre> <p>-here is my controller</p> <pre><code>class GroupsController extends Controller { public function indexAction() { $em = $this-&gt;getDoctrine()-&gt;getManager(); $entities = $em-&gt;getRepository('GroupsBundle:Groups')-&gt;findAll(); return $this-&gt;render('GroupsBundle:Groups:index.html.twig', array( 'entities' =&gt; $entities, )); } /** * Creates a new Groups entity. * */ public function createAction(Request $request) { $entity = new Groups(); $form = $this-&gt;createCreateForm($entity); $form-&gt;handleRequest($request); if ($form-&gt;isValid()) { $em = $this-&gt;getDoctrine()-&gt;getManager(); $em-&gt;persist($entity); $em-&gt;flush(); return $this-&gt;redirect($this-&gt;generateUrl('groups_show', array('id' =&gt; $entity-&gt;getId()))); } return $this-&gt;render('GroupsBundle:Groups:new.html.twig', array( 'entity' =&gt; $entity, 'form' =&gt; $form-&gt;createView(), )); } /** * Creates a form to create a Groups entity. * * @param Groups $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createCreateForm(Groups $entity) { $form = $this-&gt;createForm(new GroupsType(), $entity, array( 'action' =&gt; $this-&gt;generateUrl('groups_create'), 'method' =&gt; 'POST', )); $form-&gt;add('submit', 'submit', array('label' =&gt; 'Create')); return $form; } /** * Displays a form to create a new Groups entity. * */ public function newAction() { $entity = new Groups(); $form = $this-&gt;createCreateForm($entity); return $this-&gt;render('GroupsBundle:Groups:new.html.twig', array( 'entity' =&gt; $entity, 'form' =&gt; $form-&gt;createView(), )); } /** * Finds and displays a Groups entity. * */ public function showAction($id) { $em = $this-&gt;getDoctrine()-&gt;getManager(); $entity = $em-&gt;getRepository('GroupsBundle:Groups')-&gt;find($id); if (!$entity) { throw $this-&gt;createNotFoundException('Unable to find Groups entity.'); } $deleteForm = $this-&gt;createDeleteForm($id); return $this-&gt;render('GroupsBundle:Groups:show.html.twig', array( 'entity' =&gt; $entity, 'delete_form' =&gt; $deleteForm-&gt;createView(), )); } /** * Displays a form to edit an existing Groups entity. * */ public function editAction($id) { $em = $this-&gt;getDoctrine()-&gt;getManager(); $entity = $em-&gt;getRepository('GroupsBundle:Groups')-&gt;find($id); if (!$entity) { throw $this-&gt;createNotFoundException('Unable to find Groups entity.'); } $editForm = $this-&gt;createEditForm($entity); $deleteForm = $this-&gt;createDeleteForm($id); return $this-&gt;render('GroupsBundle:Groups:edit.html.twig', array( 'entity' =&gt; $entity, 'edit_form' =&gt; $editForm-&gt;createView(), 'delete_form' =&gt; $deleteForm-&gt;createView(), )); } /** * Creates a form to edit a Groups entity. * * @param Groups $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createEditForm(Groups $entity) { $form = $this-&gt;createForm(new GroupsType(), $entity, array( 'action' =&gt; $this-&gt;generateUrl('groups_update', array('id' =&gt; $entity-&gt;getId())), 'method' =&gt; 'PUT', )); $form-&gt;add('submit', 'submit', array('label' =&gt; 'Update')); return $form; } /** * Edits an existing Groups entity. * */ public function updateAction(Request $request, $id) { $em = $this-&gt;getDoctrine()-&gt;getManager(); $entity = $em-&gt;getRepository('GroupsBundle:Groups')-&gt;find($id); if (!$entity) { throw $this-&gt;createNotFoundException('Unable to find Groups entity.'); } $deleteForm = $this-&gt;createDeleteForm($id); $editForm = $this-&gt;createEditForm($entity); $editForm-&gt;handleRequest($request); if ($editForm-&gt;isValid()) { $em-&gt;flush(); return $this-&gt;redirect($this-&gt;generateUrl('groups_edit', array('id' =&gt; $id))); } return $this-&gt;render('GroupsBundle:Groups:edit.html.twig', array( 'entity' =&gt; $entity, 'edit_form' =&gt; $editForm-&gt;createView(), 'delete_form' =&gt; $deleteForm-&gt;createView(), )); } /** * Deletes a Groups entity. * */ public function deleteAction(Request $request, $id) { $form = $this-&gt;createDeleteForm($id); $form-&gt;handleRequest($request); if ($form-&gt;isValid()) { $em = $this-&gt;getDoctrine()-&gt;getManager(); $entity = $em-&gt;getRepository('GroupsBundle:Groups')-&gt;find($id); if (!$entity) { throw $this-&gt;createNotFoundException('Unable to find Groups entity.'); } $em-&gt;remove($entity); $em-&gt;flush(); } return $this-&gt;redirect($this-&gt;generateUrl('groups')); } /** * Creates a form to delete a Groups entity by id. * * @param mixed $id The entity id * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm($id) { return $this-&gt;createFormBuilder() -&gt;setAction($this-&gt;generateUrl('groups_delete', array('id' =&gt; $id))) -&gt;setMethod('DELETE') -&gt;add('submit', 'submit', array('label' =&gt; 'Delete')) -&gt;getForm() ; } </code></pre> <p>}</p> <p>the problem:</p> <blockquote> <p>Catchable Fatal Error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, object given, called in /home/cros/Desktop/Project_Console/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 555 and defined 500 Internal Server Error - ContextErrorException</p> </blockquote> <p>*Stack Trace:</p> <p>in vendor/doctrine/collections/lib/Doctrine/Common/Collections/ArrayCollection.php at line 48 -</p> <pre><code> /* * @param array $elements */ public function __construct(array $elements = array()) { $this-&gt;elements = $elements; } </code></pre> <blockquote> <p>at ErrorHandler ->handleError ('4096', 'Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, object given, called in /home/cros/Desktop/Project_Console/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 555 and defined', '/home/Cros/Desktop/Project_Console/vendor/doctrine/collections/lib/Doctrine/Common/Collections/ArrayCollection.php',</p> </blockquote> <p>My GroupsType and RolesType:</p> <pre><code> class GroupsType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder -&gt;add('image',new ImagesType()) -&gt;add('name_groups', 'text',array('required' =&gt; true, 'attr' =&gt; array('placeholder' =&gt; 'Nom du groupe'))) -&gt;add('role', new RolesType()) ; } } //My RolesType: class RolesType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder -&gt;add('groups', 'entity',array( 'class' =&gt; 'GroupsBundle:Roles', 'choice_label' =&gt; 'name_role', /*'query_builder' =&gt; function(EntityRepository $er) { return $er-&gt;createQueryBuilder('r') -&gt;orderBy('r.id', 'ASC'); },*/ 'required' =&gt; true, 'placeholder' =&gt; 'Choisir le role du votre groupe' ) ) -&gt;add('permissions_role','entity',array( 'class' =&gt; 'GroupsBundle:Permissions', 'multiple' =&gt; true, 'expanded' =&gt; true, 'query_builder' =&gt; function(EntityRepository $er) { return $er-&gt;createQueryBuilder('u') -&gt;orderBy('u.id', 'ASC'); }, 'required' =&gt; true ) ) // -&gt;add('permissions_role','number') ; </code></pre> <p>Thank you</p>
2
Why do I get "DSO missing" error even when the linker can locate the library?
<p>I am compiling a program against a shared library I have written. This library in turn relies on <code>Boost::program_options</code> (among other libraries). When I compile my program, I need of course to mention my library, but I get a DSO error:</p> <pre><code>g++ ism_create_conf.cc -o ism_create_conf -lglsim_ol -lglsim -lhdf5 -lgsl /usr/bin/ld.real: /tmp/cc9mBWmM.o: undefined reference to symbol_ZN5boost15program_options8validateERNS_3anyERKSt6vectorISsSaISsEEPSsi' //usr/lib/x86_64-linux-gnu/libboost_program_options.so.1.55.0: error adding symbols: DSO missing from command line collect2: error: ld returned 1 exit status </code></pre> <p>I know that the error goes away if I add <code>-lboost_program_options</code>. What I don't understand is </p> <ol> <li><p>Why do I have to do this even if my program does not call Boost directly (only through my glsim library).</p></li> <li><p>Why does the linker want <code>-lboost_program_options</code> when it actually found the correct library (and location) by itself (see the second line of the error message).</p></li> </ol> <p>The situation is similar to what was asked e.g <a href="https://stackoverflow.com/questions/19901934">here</a>, but I am asking something different: I know the solution is to mention the library in the command line, I want to know <em>why</em> I have to do this <em>even if the linker already knows</em> where the library is. There is obviously something I do not understand about how shared libraries work, it seems to me that when I use other shared libraries, these libraries can automatically call other shared libraries <em>they</em> need. However, the shared library I built does not have this ability.</p>
2
Upload file to server using ionic
<p>I am building a mobile app using ionic. One of the usecase is to let the user browse a file and upload it to the backend server (which exposes a rest service).</p> <p>On the UI, I am using the html file tag</p> <pre><code>&lt;input type="file" ng-select="uploadFile($files)" multiple&gt; </code></pre> <p>This opens a file browser to select a file. Then in the controller, I am doing the following</p> <pre><code>.controller('UploadDocCtrl', function ($scope, $cordovaFileTransfer) { $scope.uploadFile = function(files) { console.log("selected file "+files); // hard coded file path "/android_asset/www/img/ionic.pdf" to be replaced with the user selected file $cordovaFileTransfer.upload(restServiceEndpoint, "/android_asset/www/img/ionic.pdf", properties).then(function(result) { console.log("SUCCESS: " + JSON.stringify(result.response)); }, function(err) { console.log("ERROR: " + JSON.stringify(err)); }, function (progress) { // constant progress updates }); }); </code></pre> <p>The problem is that I am not able to get a reference to the selected file. Can someone please help with the steps to achieve this. Thanks!</p>
2
Inaccurate line reporting of React JS error
<p>I have been having numerous issues with error reporting in React js. So the actual error will be correct, but the line reported will not be. I'm guessing this is because the JSX is converted into regular Javascript, thus either creating more or less lines of code. This makes it rather difficult to actually track down and fix these errors, when the console is telling me it occurs on line x and line x is a newline or other random code that is obviously not connected to the error. Has anyone else solved this issue?</p> <p>I am using Google Chrome and I also have the react developer tools installed.</p>
2
Asynchornous SNMP get message with SNMP4J
<p>I have been working in a simple SNMP manager for java using the library SNMP4J. I am trying to send simple asynchronous get messages. I have greated a SNMPmanager to create the PDUs and start the listeners and a simple class named SNMPget that makes a simple get request. </p> <p>As stated in the <a href="http://www.snmp4j.org/doc/org/snmp4j/package-summary.html" rel="nofollow">javadoc</a>:</p> <blockquote> <p>Asynchronous responses are returned by calling a callback method on an object instance that implements the ResponseListener interface. </p> </blockquote> <p>I have followed the exact instructions to implement the callback but looks like the callback method onResponse is never executed when sending a get request. In fact, I have used wireshark to check if packets are being send and the request is correctly send and the correct response is received. Any clue on what I am doing wrong?</p> <pre><code> public class SNMPManager { private static SNMPManager instance = new SNMPManager(); private Snmp snmp_ = null; //Common SNMP variables private int requestPort = 161; private int timeout = 10000; private int retryCount = 1; private int maxRepetitions = 20; private int nonRepeaters = 0; //Singleton pattern public static SNMPManager getInstance() { return instance; } //Empty Constructor private SNMPManager() { } //Start the manager public void start() throws IOException { //Create a UDP transport on all interfaces DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping(); //Create a SNMP instance snmp_ = new Snmp(transport); //Put all the transport mappings into listen mode snmp_.listen(); } //Methods for creating targets // Create the target for version 2c public Target createVersion2cTarget(String ipaddress, String communityName) { CommunityTarget target = new CommunityTarget(); target.setAddress(new UdpAddress(String.format("%s/%d", ipaddress, requestPort))); target.setCommunity(new OctetString(communityName)); target.setTimeout(timeout); target.setRetries(retryCount); target.setVersion(SnmpConstants.version2c); return target; } //Methods for creating PDUs public PDU createGetRequestPdu(String requestOID) { PDU pdu = new PDU(); //Set the request type pdu.setType(PDU.GET); //Set the OID OID rOID = new OID(requestOID); pdu.add(new VariableBinding(rOID)); return pdu; } //Methods for the request (async mode) public void getRequest(PDU pdu, Target target, Object userHandle, ResponseListener listener) throws IOException { snmp_.get(pdu, target, userHandle, listener); } </code></pre> <p>}</p> <pre><code>public class SNMPget { protected final SNMPManager snmp_; private String requestOID; private String ipAddress; private String communityName; public SNMPget(String newRequestOID, String hostIpAddress, String newCommunityName) { snmp_ = SNMPManager.getInstance(); requestOID = newRequestOID; ipAddress = hostIpAddress; communityName = newCommunityName; } public void get(ResponseListener listener) throws IOException { Target targetHost = snmp_.createVersion2cTarget(ipAddress, communityName); PDU pduSNMPget = snmp_.createGetRequestPdu(requestOID); snmp_.getRequest(pduSNMPget, targetHost, null, listener); } </code></pre> <p>}</p> <pre><code>public class mainTest { public static void main(String[] args) throws IOException { SNMPManager snmp = SNMPManager.getInstance(); snmp.start(); ResponseListener listener = new ResponseListener() { @Override public void onResponse(ResponseEvent event) { // Always cancel async request when response has been received // otherwise a memory leak is created! Not canceling a request // immediately can be useful when sending a request to a broadcast // address. ((Snmp) event.getSource()).cancel(event.getRequest(), this); PDU response = event.getResponse(); System.out.println("Received response "+response); } }; SNMPget snmpGetCmd = new SNMPget("1.3.6.1.2.1.1.1.0", "192.168.137.104", "public"); snmpGetCmd.get(listener); } </code></pre> <p>}</p>
2
what does [ -n "$VARIABLE" ] || exit 0 mean
<p>Looking at correcting an issue in /etc/init.d/hostapd on Debian. However, I have no clue what this line of code does nor how it works</p> <pre><code>[ -n "$DAEMON_CONF" ] || exit 0 </code></pre> <p>In searching online for bash tutorials, I've never seen anyone do this</p> <p>When I run the code, my shell window closes (because $DAEMON_CONF is not set to anything). If I change the code to </p> <pre><code>[ -n "not empty" ] || exit 0 </code></pre> <p>my console window does not close. </p> <p>so, -n evaluates to true, and or'ed with exit 0, is what?</p>
2
AngularJS services and promises best practice
<p>I have an AngularJS application where I have <code>service</code>s that calls <code>$http</code> resource and returns a <code>promise</code> that I resolve in my controller. Here's a sample of what I'm doing:</p> <pre><code>app.service('Blog', function($http, $q) { var deferred = $q.defer(); $http.get('http://blog.com/sampleblog') .then(function(res) { // data massaging stuffs return deferred.resolve(res.data); }, function(err) { // may be some error message checking and beautifying error message return deferred.reject(err); }); // chain if further more HTTP calls return deferred.promise; }); </code></pre> <p>But I could simply do the following as well:</p> <pre><code>app.service('Blog', function($http) { return $http.get('http://blog.com/sampleblog'); }); </code></pre> <p>And then do the validation, error beautifying, chaining promises, etc. at the <code>controller</code> level.</p> <p>My question is : Which is considered as 'best practice', if any, in terms of code resiliency and flexibility? Or is there a better way to do it completely different than this ?</p>
2
Issue with Laravel 5.2 and jenssegers/laravel-mongodb
<p>I am trying to integrate mongodb to an application I am developing with Laravel 5.2. I have mongodb installed on my computer and the php driver working correctly <i>(I have a standalone php file with a very basic connection to my database and the results are brought correctly).</i></p> <p>As the application will work as a REST API, I created a very basic function that will return all the documents in the collection in the database but I get this error:</p> <pre><code>ConnectionTimeoutException in Collection.php line 437: No suitable servers found (`serverselectiontryonce` set): [connection timeout calling ismaster on '127.0.0.1:3306'] </code></pre> <p>I used both the Eloquent as well as the DB approach but the result is the same. </p> <p>The code belongs to the Collection.php file inside the <i>vendor/mongodb/mongodb/src/</i> folder and the line contains this:</p> <pre><code>$server = $this-&gt;manager-&gt;selectServer($options['readPreference']); </code></pre> <p>I'm using <b>Mongo 3.2.7</b> and <b>jenssegers/laravel-mongodb 3.0.x</b>.</p> <p>My standalone php file and the mongo shell work as they should and when I run <code>pgrep mongod</code> the process id is returned so I know it's working, but I can't get this to work within my Laravel 5.2 application.</p> <p>Any ideas?</p>
2
use array.prototype.map via call on a string
<p>I know the basic of call and array.prototype.map.call() function takes two arguments, the first one is the object context to be used as this is inside the called function and second is the argument list. But in MDN I found an example where array.prototype.map is used via a call method and a string is passed as the first argument.</p> <p>I want to know how the passed string gets manipulated inside map function. No this keyword inside map function. How does the map know that it is called on a string?</p> <pre><code>var map = Array.prototype.map; var a = map.call('Hello World', function(x) { return x.charCodeAt(0); }); </code></pre>
2
TableView selected cells - checkmarks disappear when scrolled out of sight and new cell checked
<p>I have a tableViewCell that uses a checkmark in <code>accessoryType</code> of cell. I have a function that puts the contents of the cell into textField and similarly removes the text from the text field when it is unchecked.</p> <p>It seems to work fine but if I check a cell and want to check a cell thats not visible (IOW) I need to scroll the tableView, the cell that was checked (is now not visible) seems to uncheck itself (Only when I check a new visible cell).</p> <p>The multi select works with visible cells only.</p> <p>Here is my code:</p> <pre><code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) let row = indexPath.row cell.textLabel?.text = painArea[row] cell.accessoryType = .None return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //selectedRow = indexPath tableView.deselectRowAtIndexPath(indexPath, animated: true) let row = indexPath.row let cell = tableView.cellForRowAtIndexPath(indexPath) if cell!.accessoryType == .Checkmark { cell!.accessoryType = .None } else { cell!.accessoryType = .Checkmark } populateDescription() print(painArea[row]) } var painDescription = ["very sore"] func populateDescription() { painDescription.removeAll() severityText.text = "" for cell in tableView.visibleCells { if cell.accessoryType == .Checkmark { painDescription.append((cell.textLabel?.text)! + " ") } var painArea = "" var i = 1 while i &lt;= painDescription.count { painArea += painDescription[i-1] + "~" i = i + 1 } severityText.text = painArea } </code></pre> <p>I hope I am explaining myself adequately. I don't want the non visible cells to be unchecked and thus removed from my text field unless I uncheck it.</p> <p>Any ideas would be most appreciated.</p> <p>Kind regards</p> <p>Wayne</p>
2
Spark (Java) - Adding a single average as a new column
<p>I have two dataframes, <code>df1</code> and <code>df2</code>, and I'd like to add a new column to the second one. This new column should be the average of a column from the first dataframe. Something like this:</p> <pre><code>df1 df2 df2 userid count value userid count userid count value 11 2 5 10 1 10 1 5 22 3 4 20 1 ======&gt; 20 1 5 33 5 6 30 1 30 1 5 </code></pre> <p>I'm trying</p> <pre><code>df2 = df2.withColumn("value", avg(df1.col("value"))); </code></pre> <p>which is not working. How can I do this? Thank you!</p>
2
Node js selenium multiple loop
<p>I have written a script in node with selenium webdriver for automation testing. Below in the script</p> <pre><code>var webdriver = require('selenium-webdriver'), By = webdriver.By, until = webdriver.until, _und = require('underscore'); var driver = new webdriver.Builder() .forBrowser('chrome') .build(); driver.get('http://www.????.com/'); driver.wait(function() { driver.findElement(By.xpath("//*[@id='container']/div/div/div[1]/div[1]/div/a[1]")).then(function(link) { link.click(); }); driver.findElements(By.css("div.pu-final &gt; span.fk-bold")).then(function(priceSpans) { console.log(priceSpans.length) _und.each(priceSpans, function(span) { span.getText().then( function(price) { console.log(price) } ); }); }); }, 20000); driver.quit(); </code></pre> <p>But it prints the output multiple time in console.</p> <pre><code>32 Rs. 5,499 Rs. 13,499 Rs. 10,999 Rs. 15,990 Rs. 8,499 Rs. 11,998 Rs. 6,999 Rs. 12,990 Rs. 7,999 Rs. 9,199 Rs. 9,990 Rs. 15,499 Rs. 9,999 Rs. 17,499 Rs. 9,999 Rs. 8,999 Rs. 8,990 Rs. 21,499 Rs. 38,499 Rs. 11,390 Rs. 10,999 Rs. 14,249 Rs. 8,999 Rs. 6,999 Rs. 6,999 Rs. 12,499 Rs. 22,999 Rs. 10,999 Rs. 18,499 Rs. 27,900 Rs. 27,900 Rs. 16,999 32 Rs. 5,499 Rs. 13,499 Rs. 10,999 Rs. 15,990 Rs. 8,499 Rs. 11,998 Rs. 6,999 Rs. 12,990 Rs. 7,999 Rs. 9,199 Rs. 9,990 Rs. 15,499 Rs. 9,999 Rs. 17,499 Rs. 9,999 Rs. 8,999 Rs. 8,990 Rs. 21,499 Rs. 38,499 Rs. 11,390 Rs. 10,999 Rs. 14,249 Rs. 8,999 Rs. 6,999 Rs. 6,999 Rs. 12,499 Rs. 22,999 Rs. 10,999 Rs. 18,499 Rs. 27,900 Rs. 27,900 Rs. 16,999 </code></pre>
2
Determine available memory in pure Python
<p>I am aware of the <a href="https://github.com/giampaolo/psutil" rel="nofollow">psutil</a> package which provides (along with many other things) a way to access information about system memory, including the amount of available memory (<code>psutil.virtual_memory().available</code>). How would I go about querying available memory in a pure Python implementation? The solution would need to work for UNIX-like systems, including Linux, OS X, and so on.</p>
2
Codeigniter Load header and footer only once
<p>I'm developing an admin portal using Codeigniter. Here i want to load the header and footer and sidebar only once and change the main content without loading the header and footer everytime. Please provide some good reference which i can refer. I dont want to go about with the ajax technique since im using angular js I think codeigniter templates will be the right approach but im new to codeigniter templates. So some good links to template tutorials would be preferable. Thanks in advance</p>
2
Visual Studio Build - Azure 2.9 SDK
<p>I am trying to build my software on Visual Studio Team Services. I recently upgraded from VS 2013 to VS 2015. I upgraded from the Azure 2.6 to the Azure 2.9 SDK. When the software builds, I get this error:</p> <p>C:\a\src\CCC\Azure\CloudService1\CloudService1.ccproj (95, 0) The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Windows Azure Tools\2.9\Microsoft.WindowsAzure.targets" was not found. Confirm that the path in the declaration is correct, and that the file exists on disk.</p> <p>Is 2.9 not supported at this time? Here is my ccproj file:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"&gt; &lt;Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /&gt; &lt;PropertyGroup&gt; &lt;Configuration Condition=" '$(Configuration)' == '' "&gt;Debug&lt;/Configuration&gt; &lt;Platform Condition=" '$(Platform)' == '' "&gt;AnyCPU&lt;/Platform&gt; &lt;ProductVersion&gt;2.9&lt;/ProductVersion&gt; &lt;ProjectGuid&gt;XX&lt;/ProjectGuid&gt; &lt;OutputType&gt;Library&lt;/OutputType&gt; &lt;AppDesignerFolder&gt;Properties&lt;/AppDesignerFolder&gt; &lt;RootNamespace&gt;CloudService1&lt;/RootNamespace&gt; &lt;AssemblyName&gt;CloudService1&lt;/AssemblyName&gt; &lt;StartDevelopmentStorage&gt;True&lt;/StartDevelopmentStorage&gt; &lt;Name&gt;CloudService1&lt;/Name&gt; &lt;SccProjectName&gt;SAK&lt;/SccProjectName&gt; &lt;SccProvider&gt;SAK&lt;/SccProvider&gt; &lt;SccAuxPath&gt;SAK&lt;/SccAuxPath&gt; &lt;SccLocalPath&gt;SAK&lt;/SccLocalPath&gt; &lt;UseEmulatorExpressByDefault&gt;False&lt;/UseEmulatorExpressByDefault&gt; &lt;/PropertyGroup&gt; &lt;!-- Import the target files for this project template --&gt; &lt;PropertyGroup&gt; &lt;VisualStudioVersion Condition=" '$(VisualStudioVersion)' == '' "&gt;10.0&lt;/VisualStudioVersion&gt; &lt;CloudExtensionsDir Condition=" '$(CloudExtensionsDir)' == '' "&gt;$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Windows Azure Tools\2.9\&lt;/CloudExtensionsDir&gt; &lt;/PropertyGroup&gt; &lt;Import Project="$(CloudExtensionsDir)Microsoft.WindowsAzure.targets" /&gt; </code></pre> <p></p>
2
PHP Connect to MS SQL Database
<p>I have a website locally hosted on my computer. My server is using PHP 5.6.21. I am trying to connect to a SQL Database on another computer Microsoft SQL Server 2000. </p> <p>I have installed the PHP extensions, PHP_sqlsrv_56_ts and PHP_sqlsrv_56_nts. I have enabled them in the php.ini: extension=php_sqlsrv_56_nts.dll extension=php_sqlsrv_56_ts.dll</p> <p>I have tried to connect using this:</p> <pre><code>&lt;?php $serverName = "serverName\sqlexpress, 1542"; //serverName\instanceName, portNumber (default is 1433) $connectionInfo = array( "Database"=&gt;"dbName", "UID"=&gt;"userName", "PWD"=&gt;"password"); $conn = sqlsrv_connect( $serverName, $connectionInfo); if( $conn ) { echo "Connection established.&lt;br /&gt;"; }else{ echo "Connection could not be established.&lt;br /&gt;"; die( print_r( sqlsrv_errors(), true)); } ?&gt; </code></pre> <p>And I tried using this:</p> <pre><code>&lt;?php $connection_string = 'DRIVER={SQL Server};SERVER=&lt;Hector\SQLEXPRESS&gt;;DATABASE=tempdb'; $user = 'sqltestclient'; $pass = 'paSSword'; $connection = odbc_connect( $connection_string, $user, $pass ) or die("Unable to connect to server"); echo $connection.' '.$user.' '.$pass; ?&gt; </code></pre> <p>But neither work, the top wont load the page and the bottom just sasys unable to connect.</p> <p>Im not sure what Im doing wrong</p>
2
FireBase-Analytics IOS
<h1>i'm new mobile developer, today i add firebase analytics framework in my project using code [FIRApp configure], so when i running app, the app be crash.Someone can help me fix this bug? Thanks all! Here's log in xcode:</h1> <p><strong>* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSData gtm_dataByGzippingData:]: unrecognized selector sent to class 0x1a0c5a8b8' *</strong> First throw call stack: (0x1834f9900 0x182b67f80 0x183500514 0x1834fd5b8 0x18340168c 0x1001cda2c 0x1001e17c8 0x1001e13b8 0x1012d1bf0 0x1012d1bb0 0x1012de6c8 0x1012d58a0 0x1012d1bb0 0x1012e0e10 0x1012e04d8 0x183161470 0x183161020) libc++abi.dylib: terminating with uncaught exception of type NSException</p>
2
Waiting for incoming connection with ide key 'PHPSTORM'
<p>Not working xDebug in PhpStorm. Waiting for connection all time.</p> <p>My configuration</p> <pre><code>[Xdebug] zend_extension="c:/openserver/modules/php/PHP-5.6-x64/ext/php_xdebug.dll" xdebug.auto_trace = 0 xdebug.collect_includes = 1 xdebug.dump.REQUEST = * xdebug.dump.SESSION = * xdebug.dump.SERVER = REMOTE_ADDR,REQUEST_METHOD xdebug.dump_globals = 1 xdebug.dump_once = 1 xdebug.dump_undefined = 1 xdebug.extended_info = 1 xdebug.idekey = "PHPSTORM" xdebug.max_nesting_level = 256 xdebug.overload_var_dump = 1 xdebug.profiler_enable = 0 xdebug.profiler_enable_trigger = 0 xdebug.profiler_output_dir="c:/openserver/userdata/temp/xdebug/" xdebug.profiler_output_name = "cachegrind.out.%H%R" xdebug.remote_enable = 1 xdebug.remote_handler = "dbgp" xdebug.remote_host = "localhost" xdebug.remote_port = 9000 xdebug.trace_output_dir = "c:/openserver/userdata/temp/xdebug/" xdebug.var_display_max_children = 256 xdebug.var_display_max_depth = 16 </code></pre> <p><a href="https://i.stack.imgur.com/g5qXM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g5qXM.png" alt="configuration in PHPStorm"></a></p> <p><a href="https://i.stack.imgur.com/Fh652.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Fh652.png" alt="error"></a></p> <p>Where is my mistake?</p>
2
Retrieve return value from stored procedure
<p>I have written a table-valued parameter stored procedure, It returns the Id that was inserted. If I run it from a query inside SSMS, it works and returns the value correctly. </p> <p>When I call the procedure from code, it runs, and inserts the data but does not set the return parameter I have added and marked as a return parameter. </p> <p>What am I doing wrong here?</p> <p>SP:</p> <pre><code>ALTER PROCEDURE [dbo].[InsertUpdateMeeting] -- Add the parameters for the stored procedure here @Meeting MeetingsTableType READONLY, @Area AreasTableType READONLY, @MeetingLocation MeetingLocationsTableType READONLY AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Insert statements for procedure here DECLARE @MeetingId int = 0; DECLARE @AreaId int; DECLARE @MeetingLocationId int; SELECT TOP 1 @MeetingId=m.MeetingId FROM @Meeting AS m; SELECT TOP 1 @MeetingLocationId = ml.MeetingLocationId FROM @MeetingLocation AS ml; SELECT TOP 1 @AreaId = a.AreaId FROM @Area AS a; UPDATE Areas SET Hotline=areaParam.Hotline, Name=areaParam.Name FROM Areas INNER JOIN @Area AS areaParam ON Areas.AreaId=areaParam.AreaId; IF(@@ROWCOUNT=0) BEGIN; INSERT INTO Areas (Hotline,Name) SELECT areaParam.Hotline,areaParam.Name FROM @Area AS areaParam; SET @AreaId=SCOPE_IDENTITY(); END; UPDATE MeetingLocations SET Address1=ml.Address1, Address2=ml.Address2, Address3=ml.Address3, City=ml.City, [State]=ml.[State], Zip=ml.Zip, ClubName=ml.ClubName, ClubDescription=ml.ClubDescription, MapLink=ml.MapLink FROM MeetingLocations INNER JOIN @MeetingLocation AS ml ON MeetingLocations.MeetingLocationId=ml.MeetingLocationId; IF(@@ROWCOUNT=0) BEGIN; INSERT INTO MeetingLocations (Address1,Address2,Address3,City,[State],Zip,ClubName,ClubDescription,MapLink) SELECT ml.Address1,ml.Address2,ml.Address3,ml.City,ml.[State],ml.Zip,ml.ClubName,ml.ClubDescription,ml.MapLink FROM @MeetingLocation AS ml; SET @MeetingLocationId=SCOPE_IDENTITY(); END; UPDATE Meetings SET AreaId = @AreaId, MeetingLocationId=@MeetingLocationId, Name = meetingParam.Name FROM Meetings INNER JOIN @Meeting AS meetingParam ON Meetings.MeetingId=meetingParam.MeetingId; IF(@@ROWCOUNT=0) BEGIN; INSERT INTO Meetings (MeetingLocationId,AreaId,Name) SELECT @MeetingLocationId,@AreaId,meetingParam.Name FROM @Meeting AS meetingParam; SET @MeetingId=SCOPE_IDENTITY(); END; RETURN @MeetingId; END </code></pre> <p>C# code:</p> <pre><code>...create tables... var meetingLocationParam = new SqlParameter("@MeetingLocation", meetingLocationTable); meetingLocationParam.SqlDbType = SqlDbType.Structured; meetingLocationParam.TypeName = "MeetingLocationsTableType"; var meetingParam = new SqlParameter("@Meeting", meetingTable); meetingParam.SqlDbType = SqlDbType.Structured; meetingParam.TypeName = "MeetingsTableType"; var areaParam = new SqlParameter("@Area", areaTable); areaParam.TypeName = "AreasTableType"; areaParam.SqlDbType = SqlDbType.Structured; using (var connection = new SqlConnection(conn.ConnectionString)) using (var command = new SqlCommand()) { connection.Open(); command.Connection = connection; command.CommandText = "EXEC dbo.InsertUpdateMeeting"; command.Parameters.AddRange(new SqlParameter[] {meetingParam, areaParam, meetingLocationParam, new SqlParameter() { Value=0, Direction=ParameterDirection.ReturnValue, SqlDbType=SqlDbType.Int, ParameterName="@MeetingId" } }); var otherRet = command.ExecuteNonQuery(); //Assert.IsTrue(ret &gt; 0); } </code></pre>
2
Does kryo serialization work on non serializable class and class have non serializable attributes?
<p>I'm trying to use Kryo library to convert any given object to byteArray and store in a data store or queue for later use. But is it possible to serialize any given object or only object implementing serializable interface can be converted.</p>
2
Using multiple instances of same user control simultaneously
<p>I am creating an application using wpf and MVVM. I've run into an issue where one of the controls uses three copies of another control at the same time. All three need to have their own instance of the related view model. Currently I have bindings in the user control's view that relate to the view model, but I do not have the control's data context set in its own xaml.</p> <p>I don't remember where I saw this, but my initial attempt was to use an observable collection like so: In the model:</p> <pre><code>private ObservableCollection&lt;SignalStrengthViewModel&gt; signalStrengths; public GyroViewModel() { this.signalStrengths = new ObservableCollection&lt;SignalStrengthViewModel&gt;(); this.signalStrengths.Add(new SignalStrengthViewModel(Color.FromRgb(0, 128, 255))); this.signalStrengths.Add(new SignalStrengthViewModel(Color.FromRgb(63, 163, 153))); this.signalStrengths.Add(new SignalStrengthViewModel(Color.FromRgb(121, 132, 196))); </code></pre> <p>}</p> <p>and the xaml of the containing control:</p> <pre><code>&lt;controls:SignalStrengthUserControl x:Name="Link1SignalStrengthControl" DataContext="{Binding SignalStrengths[0], Mode=OneWayToSource}"/&gt; &lt;controls:SignalStrengthUserControl x:Name="Link2SignalStrengthControl" DataContext="{Binding SignalStrengths[1], Mode=OneWayToSource}"/&gt; &lt;controls:SignalStrengthUserControl x:Name="Link3SignalStrengthControl" DataContext="{Binding SignalStrengths[2], Mode=OneWayToSource}"/&gt; </code></pre> <p>This doesn't seem to actually bind the instances of the control with the instances of the view models. I've also tried moving the list to the code behind containing control's xaml with no change in the result.</p> <p>Can anyone tell me what I'm doing wrong?</p> <p>I have seen questions here and elsewhere that use data templates for text boxes, but I haven't found a way to make that work here (and they were all for text boxes).</p> <p>Some of the other questions I've looked at:</p> <p><a href="http://blog.scottlogic.com/2012/02/06/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight.html" rel="nofollow noreferrer">A SIMPLE PATTERN FOR CREATING RE-USEABLE USERCONTROLS IN WPF / SILVERLIGHT</a> <a href="https://stackoverflow.com/questions/9909982/multiple-instances-of-a-wpf-user-control-all-use-the-same-viewmodel">Multiple instances of a wpf user control all use the same viewmodel</a></p>
2
Is it possible to disable ssl certificate download in Weblogic server
<p>It's for personal test. I use weblogic server 12.2.1. I enabled ssl, I can access to my server by https with my web browser, when I do it, it proposes me to donwload the server certificate, all it's ok.</p> <p>But I want to disable this donwload of certificate, and access to the server only by installing manualy the certificate in my web browser. Is it possible to disable this download function in Weblogic ?</p>
2
.NET Standard Library vs. .NET Standard
<p>Reading some blogs and the official <a href="https://docs.microsoft.com/en-us/dotnet/articles/standard/library">documentation for .NET Core 1.0</a>, I'm still quite confused (like many others).<br> Don't get me wrong, I've literally read dozens of posts on the web trying to understand the architecture and terms for this new platform.</p> <p>Reading the docs and blogs, this is what they say about <strong>.NET Standard Library</strong>:</p> <blockquote> <p>The .NET Standard Library is a formal specification of .NET APIs that are intended to be available on all .NET runtimes.</p> </blockquote> <p>But they also use this term: <strong>.NET Standard</strong> and <strong>netstandard</strong> as you can see on the <a href="https://docs.microsoft.com/en-us/dotnet/articles/standard/library#net-platforms-support">Platform Support table</a>.</p> <p>Question: <strong>.NET Standard Library</strong> <code>==</code> <strong>.NET Standard</strong>? If not, what's difference?</p>
2
Yii 2. Using a model from a string
<p>I have a weird scenario, I am getting the model name as a string, so If I wanted to use it, but how do I manage the import class part? Any ideas?</p> <p>I have tried:</p> <pre><code> $model = new $tmpModel; var_dump($model); </code></pre> <p>Now I get: "Class 'Organization' not found", but I have imported the class manually just to test, but still error.</p> <pre><code>use app\models\Organization; </code></pre> <p>Any ideas?</p> <p><strong>EDIT</strong>: I think I needed some sleep. With help of comments here code looks like these:</p> <pre><code>$className = "app\models\\".$this-&gt;modelSave; $model = Yii::createObject([ 'class' =&gt; $className, ]); var_dump($model); </code></pre>
2
Dynamically added UserControl does not adjust to parent size
<p>I have a UserControl which will be loaded at runtime into a ContentControl. The user control does not adjust its size to the parent control even I haven't set Width nor Height. What is it that I miss?</p> <pre><code> &lt;ContentControl x:Name="MainContentControl" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" &gt; &lt;Label Background="LightGray" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" &gt;Sample control &lt;/Label&gt; &lt;/ContentControl&gt; </code></pre> <p>The sample control ( label ) inside the ContentControl works just fine and expands depending on size changes of the ContentControl.</p> <p>When I now replace the Label with an UserControl the size of the Usercontrol has as maxsize the position of the label which is inside it</p> <p>Here the UserControl</p> <pre><code>&lt;UserControl x:Class="test.testUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"&gt; &lt;Grid&gt; &lt;Label Content="Label" HorizontalAlignment="Left" Margin="235,200,0,0" VerticalAlignment="Top"/&gt; &lt;/Grid&gt; </code></pre> <p></p>
2
Automatically adding spaces before semicolon in Visual Studio 2015
<p>I have been using VS2015 for about a year but I have had to reinstall it recently and I can't find the option to automatically add spaces to a expression as soon as a semicolon is entered. I have use it before but just can't find it now.</p> <p><strong>Example:</strong></p> <p><em>before semicolon:</em> <code>A=a+b+myFunction(a,b)</code></p> <p><em>after semicolon:</em> <code>A = a + b + myFunction(a, b);</code></p>
2
Ghostscript spatie/pdf-to-image
<p>I am using spatie/pdf-to-image to convert pdf to jpg on a laravel web app. To do that I need first to install Imagick and Ghostscript. I did install the Imagick but I don't know how to install ghostscript. I am hosting my app on Godaddy shared hosting. any help?</p>
2
Saving a comment object to a post in a blog in django database
<p>I am making a simple post and comment page.In this,when i comment on a post i am trying to save that comment on the database.I am retrieving the title of the post on which comment is made by using its id.But when i try to instantiate the post_title attribute of Post_Comment by doing comments.post_title=header.title it gives a value eror saying Cannot assign "u'kjashdkh'": "Post_Comment.post_title" must be a "Post" instance. Please note that "kjashdkh" is the post title.</p> <pre><code>class Post(models.Model): title= models.CharField (max_length=100) body= models.TextField () created=models.DateTimeField() def __str__(self): return self.title class Post_Comment(models.Model): comment= models.TextField() post_title=models.ForeignKey(Post) </code></pre> <p>And my view is:</p> <pre><code>def comment(request,pk): header=Post.objects.get(id=pk) comments=Post_Comment(comment=request.POST['comment']) comments.post_title=header.title header.delete() comments.save() return HttpResponseRedirect('/blog/') </code></pre>
2
Heterogenous Layouts inside RecyclerView
<p>I am developing a weather app in which i wanted to use two <code>Views</code> inside <code>RecyclerView</code> which is having <code>CursorAdapter</code> as its member. I want to use one <code>View</code> to display todays weather and other view to display other days weathers. My <code>RecyclerView</code> is working perfectly if I only use one <code>View</code> to display weather. I have also overwritten <code>getItemViewType()? to get to know which</code>View` type I should inflate.</p> <p>Code for <code>getItemViewType()</code>:</p> <pre><code>private static int VIEW_TYPE_TODAY = 0; private static int VIEW_TYPE_FUTURE_DAY = 1; @Override public int getItemViewType(int position) { if(position == VIEW_TYPE_TODAY) return VIEW_TYPE_TODAY; else return VIEW_TYPE_FUTURE_DAY; } </code></pre> <p>Code for the <code>newView()</code> of <code>CursorAdapter</code> which I have overwritten:</p> <pre><code>@Override public View newView(Context context, Cursor cursor, ViewGroup parent) { int viewType = getItemViewType(cursor.getPosition()); int layoutId = -1; if(viewType==VIEW_TYPE_TODAY) layoutId = R.layout.list_item_forecast_today; else if(viewType==VIEW_TYPE_FUTURE_DAY) layoutId = R.layout.list_item_forecast; View view = LayoutInflater.from(context).inflate(layoutId, parent, false); return view; } </code></pre> <p>No matter what the value of <code>position</code> in <code>getItemViewType()</code> is, the function is always returning <code>VIEW_TYPE_TODAY</code>.</p> <p>Can some please tell what I am doing wrong? </p>
2
Can you pass multiple glob strings to vscode findFiles api
<p>I would like to ignore folders that have been excluded in the workspace settings when I call the api <code>findFiles</code> (<a href="https://code.visualstudio.com/Docs/extensionAPI/vscode-api#WorkspaceConfiguration" rel="noreferrer">https://code.visualstudio.com/Docs/extensionAPI/vscode-api#WorkspaceConfiguration</a>), however I'm not sure how to do this. I have tried looking for a way to combine glob statements but I haven't had much luck. I've found the GLOB_BRACE examples, but I don't think that will work in this case.</p> <p>(e.g. glob("{foo/<em>.cpp,bar/</em>.cpp}", GLOB_BRACE))</p> <p>Is there a way to pass multiple directories to the glob statement in findFiles to ignore?</p> <p>I ideally would like to do something like this...</p> <pre><code>let search_config = vscode.workspace.getConfiguration( "search" ); let search_exclude_settings = search_config.get( "exclude" ); let exclude_properties = "{"; for ( var exclude in search_exclude_settings ) { if( search_exclude_settings.hasOwnProperty( exclude ) ) { exclude_properties += exclude + ","; } } exclude_properties += filename_and_extension + "}"; var files = vscode.workspace.findFiles(filename_search, exclude_properties, 100); </code></pre> <p>but unfortunately that doesn't work. Any ideas would be greatly appreciated! I do apologise if I'm probably missing something blindingly obvious.</p> <p>Thank you for your time!</p> <p>Tom</p>
2
Angular upload text file then get content
<p>I'm trying to figure out how to read a text/xml file's content which is uploaded onto my WebApp. At this point I don't want/need to hit the server, I simply want to get the file's content/text.</p> <p>Here's what I have done so far: <strong>xmlDiff.html:</strong></p> <pre><code>&lt;div id="xmlDiff-div" class="wrapper"&gt; &lt;div class="configurationView "&gt; &lt;div class="panelHeader"&gt;Upload XML Files&lt;/div&gt; &lt;div class="treeWrapper panelBody"&gt; &lt;button ngf-select="uploadLeftFile($file)" accept="xml/*" ngf-max-height="1000" ngf-max-size="2MB"&gt; Upload Left File&lt;/button&gt; &lt;br&gt;&lt;br&gt; &lt;button ngf-select="uploadRightFile($file)" accept="xml/*" ngf-max-height="1000" ngf-max-size="2MB"&gt; Upload Right File&lt;/button&gt; &lt;br&gt;&lt;br&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="diff_editors_div"&gt; &lt;div class="panelheader sectionHeader"&gt;XML Diff Results&lt;/div&gt; &lt;div id="compare"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Now, here's my controller:</p> <pre><code>app.controller('XmlDiffCtrl', ['$scope', '$q', '$location', '$timeout', function ($scope, $q, $location, $timeout) { $('#compare').mergely({ cmsettings: {readOnly: false, lineNumbers: true}, ignorews: true, width: 'auto', height: 'auto', lhs: function (setValue) { setValue('paste left XML here'); }, rhs: function (setValue) { setValue('paste right XML here'); } }); $scope.uploadRightFile = function (file) { console.log("Upload Right File has been called"); console.log("file content :" + file); $scope.rightFileText = file.data; **doesn't work, need an alternative** }; $scope.uploadLeftFile = function (file) { }; }]); </code></pre> <p>Just as a note, I'm a beginner Angular developer so if anyone wants to bash my Angular skills go right ahead, but I primarily need help with figuring out how to access the file's content after uploading.</p> <p>Let me know if I haven't been clear enough if y'all need more details.</p>
2
Cannot cast App Delegate to App Delegate in XCTest
<p>I am working in an ios app in Xcode 7.3.1.In that I am trying to start unit testing on my swift iOS app. I cannot see to access anything that uses my appDelegate.I tried the following to solve from the following.But still am getting the same issue.Please help me to solve this. <a href="https://stackoverflow.com/questions/28042105/swift-dynamic-cast-failed-error-when-trying-to-run-unit-tests">link1</a>, <a href="https://stackoverflow.com/questions/31179382/cannot-access-appdelegate-while-testing-xcode-project">link2</a></p> <p>I am getting the following issue,while i am running unit test. My sample code is</p> <pre><code>import UIKit import XCTest @testable import MyAppName class FreshBossTests: XCTestCase { var login:LoginPageController! override func setUp() { super.setUp() login = LoginPageController() } override func tearDown() { super.tearDown() } func testlogin() { let email:String! = "[email protected]" if login.isValidEmail(email) == true { XCTAssertEqual(true, true,"email in valid format") } } </code></pre> <p>In my LoginPageController,I am having the following code.</p> <pre><code>let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate </code></pre> <p>In that line only am getting the error like </p> <pre><code>Could not cast value of type 'MyAppName.AppDelegate' (0x10dc09e80) to 'MyAppNameTests.AppDelegate' (0x11cc190c0). </code></pre>
2
Why does the Ruby module Kernel exist?
<p>In the book <em>OO Design in Ruby</em>, Sandi Metz says that the main use of modules is to implement duck types with them and include them in every class needed. Why is the Ruby <code>Kernel</code> a module included in <code>Object</code>? As far as I know it isn't used anywhere else. What's the point of using a module?</p>
2
State of thread while in run() method (Java)
<p>I am trying to understand multithreading in java. As I was going through the various states a Java thread can be in (new, Runnable, Running, Waiting/Blocked, Dead). I tried to run some simple code to check the states of the thread.</p> <p>I created a class <code>MyThread</code> that extends <code>Thread</code> and overrode <code>run()</code> method.</p> <pre><code>package com.practice.threads; public class MyThread extends Thread { @Override public void run() { super.run(); System.out.println("Running Mythread."); System.out.println("State of thread : " + this.getState()); // line 2 } } </code></pre> <p>Now I have created a simple class to test the states of thread : </p> <pre><code>package com.practice.threads; public class ThreadStateDemo { /** * @param args */ public static void main(String[] args) { MyThread myThread = new MyThread(); System.out.println("State of thread : " + myThread.getState()); // line 1 myThread.start(); } } </code></pre> <p>Running this class give the following output : </p> <pre> State of thread : NEW Running Mythread. State of thread : RUNNABLE </pre> <p>The output of line 2 is something I don't understand. When <code>run()</code> method of a thread instance is being executed, how can it be in RUNNABLE state? I saw mention of a RUNNING state in a book (SCJP Suncertified Programmer). Should it not show RUNNING?</p>
2
Using TLS 1.1/1.2 in WSO2 ESB out-going request
<p>I'm trying to consume a web service over HTTPS using WSO2 ESB (4.7.0). The web service requires all callers to use a TLS version >1.0 (1.1 or 1.2).</p> <p>I'm using Java 1.7.</p> <p>I've added the following line to my PassthroughTransportSender (and Receiver) definition to no avail:</p> <pre><code>&lt;parameter name="HttpsProtocols"&gt;TLSv1.2&lt;/parameter&gt; </code></pre> <p>How can I make WSO2 Callout and Send mediators use newer TLS versions (preferably TLS 1.2)?</p>
2
Java iterator nextIndex pointer
<p>Could you explain behaviour of Iterator result:</p> <pre><code> ArrayList&lt; String &gt; list = new ArrayList&lt; &gt;( Arrays.asList( new String[] { "a", "b", "c", "d" } ) ); int i = 0; ListIterator&lt; String &gt; iterator = list.listIterator(); while( iterator.hasNext() ) { if( ++i == 3 ) { System.out.println( iterator.previous() + iterator.nextIndex() ); } System.out.println( iterator.next() + iterator.nextIndex() ); } </code></pre> <p>The output is: a1 b2 b1 b2 c3 d4 Why third output is "b1" but not "a1"? I figure the structure</p> <p>0 1 2 3 element index</p> <p>a b c d element value</p>
2
Access violation error at delphi while saving/loading image to/from stream
<p>I am developing an application in delphi. I am trying to extract an image that is saved in database, save it to <code>TMemoryStream</code> and load same image at <code>TImage</code> control placed on other form that will populate dynamically. I am getting <strong>access violation</strong> error when I try to load image from stream to image control placed on the form.</p> <p>Error Description is as follows <br /></p> <blockquote> <p>Access violation at address 00B548C in module abc.exe. Read of address 0000000</p> </blockquote> <p>My code snippet is as follows<br /></p> <pre><code>UniConnection1.Connected := true; UniQuery2.SQL.Text := 'Select image from userplays where id = :id'; UniQuery2.Params.ParamByName('id').Value := idpub1; UniQuery2.Open; if UniQuery2.FieldByName('image').AsString &lt;&gt; '' then begin try Stream121 := TMemoryStream.Create; TBlobField(UniQuery2.FieldByName('image')).SaveToStream(Stream121); Stream121.Position := 0; if Assigned(Stream121) then begin Image1.Picture.Graphic.LoadFromStream(Stream121); Image1.Update; end; finally Stream121.Free; end; end; </code></pre>
2
Gmail API changes the content disposition from "inline" to "attachment"
<p>I'm running into an odd problem with sending inline attachments via Gmail's API. I am using the .NET client (version 1.10.0). The email is a reply to a message I've received with an inline attachment, so the attachment is part of the quoted block in the reply.</p> <p>Here's the raw MIME message that I'm sending out:</p> <pre><code>From: ... To: ... Date: Fri, 01 Jul 2016 11:48:29 -0700 Subject: Re: attachment test #2 Message-Id: ... In-Reply-To:... References: ... MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="=-JOa+9Bw0690XCFj1YCPc1Q==" --=-JOa+9Bw0690XCFj1YCPc1Q== Content-Type: text/html; charset=utf-8 Content-Id: &lt;W4PKNTOPLYT4.32IVHE45EWK21@BILLRAVDIN9F02&gt; &lt;div style="font-family: Helvetica, Arial, sans-serif;"&gt;back atcha.&lt;div&gt;&lt;br&gt;On Fri, Jul 01, 2016 at 11:38 AM, ... wrote:&lt;div&gt;[Omitted for clarity]&lt;img height="168" width="300" src="cid:8AF6D64A-9AAD-4E54-8998-5F08C42F537F"&gt;&lt;/span&gt;&lt;/div&gt;&lt;br&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt; --=-JOa+9Bw0690XCFj1YCPc1Q== Content-Type: image/jpeg; name="ha ha.jpeg" Content-Disposition: inline; filename="ha ha.jpeg" Content-Transfer-Encoding: base64 Content-Id: &lt;8AF6D64A-9AAD-4E54-8998-5F08C42F537F&gt; [Base64 encoded attachment] --=-JOa+9Bw0690XCFj1YCPc1Q==-- </code></pre> <p>Note above the content disposition on the mime part for the inline attachment: </p> <p><strong>Content-Disposition: <em>inline</em>; filename="ha ha.jpeg"</strong></p> <p>Here's what the MIME headers on the inline attachment part look like when it comes in:</p> <pre><code>Content-Type: image/jpeg; name="ha ha.jpeg" Content-Disposition: attachment; filename="ha ha.jpeg" Content-Transfer-Encoding: base64 Content-ID: &lt;8AF6D64A-9AAD-4E54-8998-5F08C42F537F&gt; X-Attachment-Id: 594301951148d672_0.1 </code></pre> <p>My question is: why is the Content-Disposition now rewritten as <strong>attachment</strong> rather than <strong>inline</strong>?</p> <p>I've found that when viewing the email in my browser, it appears as expected. But when viewing with my Mac's Mail client, the inline attachment appears in the email twice. I suspect that the change in the content disposition might be the reason- any light you can shed on this would be much appreciated!</p>
2
TileOverlay with android and google maps
<p>I've used MapTiler to create some tiles that I'm trying to overlay onto a Google map with android and not having much luck. The Android documentation is pretty sparse on this topic but I've done what I think should work, yet I'm not seeing the tiles when I zoom in to the correct level. I'm trying to make the overlay happen in the onMapReady() callback, should I be doing that somewhere else?</p> <p>Here's the code I have for the onMapReady method:</p> <pre><code>@Override public void onMapReady(GoogleMap googleMap) { googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); googleMap.setMyLocationEnabled(true); CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(44.481705,-114.9378269)).zoom(16).build(); googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); mTileOverlay = googleMap.addTileOverlay(new TileOverlayOptions() .tileProvider((new UrlTileProvider(256, 256) { @Override public URL getTileUrl(int x, int y, int zoom) { String s = "http://www.example.com/tiles/"+zoom+"/"+x+"/"+y+".png"; // added this logging to see what the url is Log.d("home", s); try { return new URL(s); } catch (MalformedURLException e) { throw new AssertionError(e); } } }))); } </code></pre> <p>any ideas here?</p> <p>TIA</p> <p>EDIT: I've adding some logging to see what 's' (my url) is returning, and it's returning the correct url and my server is serving up the tiles correctly from that url but still not seeing anything on the map in android.</p>
2
SQL Server cannot process this media family
<p>I am trying to restore one backup file but I am not able to do it. </p> <p>I get this error:</p> <blockquote> <p>Msg 3241, Level 16, State 0, Line 4<br> The media family on device 'D:\Case_info\NEWPMS_db_201606261000.bak' is incorrectly formed. SQL Server cannot process this media family.</p> <p>Msg 3013, Level 16, State 1, Line 4<br> RESTORE FILELIST is terminating abnormally.</p> </blockquote>
2
no response to HTTP POST with spark java
<p>I get a response to a http POST request if I set the response to a empty String. </p> <pre><code>post("/hello", (request, response) -&gt; { obj.toClass(request.body()); return ""; } ); </code></pre> <p>However I dont get a response if I set the return statement to a non empty string (Time Out).</p> <pre><code>post("/hello", (request, response) -&gt; { obj.toClass(request.body()); return "Success"; } ); </code></pre> <p>Any suggestions?</p>
2
std::wcstok in VS 2015
<p>I have this toned down used case of code which when compiled with VS 2015 C++ compiler produces a warning. </p> <pre><code>#include &lt;cwchar&gt; #include &lt;iostream&gt; int main() { wchar_t input[100] = L"A bird came down the walk"; wchar_t* token = std::wcstok(input, L" "); while (token) { std::wcout &lt;&lt; token &lt;&lt; '\n'; token = std::wcstok(nullptr, L" "); } } </code></pre> <p>This produced following warnings.</p> <pre><code>warning C4996: 'wcstok': wcstok has been changed to conform with the ISO C standard, adding an extra context parameter. To use the legacy Microsoft wcstok, define _CRT_NON_CONFORMING_WCSTOK. 1&gt; c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\corecrt_wstring.h(254): note: see declaration of 'wcstok' warning C4996: 'wcstok': wcstok has been changed to conform with the ISO C standard, adding an extra context parameter. To use the legacy Microsoft wcstok, define _CRT_NON_CONFORMING_WCSTOK. 1&gt; c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\corecrt_wstring.h(254): note: see declaration of 'wcstok' </code></pre> <p>Looking up online, I read about <a href="http://en.cppreference.com/w/cpp/string/wide/wcstok" rel="noreferrer">std::wcstok</a> and <a href="https://msdn.microsoft.com/en-us/library/bb531344.aspx" rel="noreferrer">breaking changes in VS 2015</a> which mentions that C standard has introduced a third parameter and that</p> <blockquote> <p>It used an internal, per-thread context to track state across calls, as is done for strtok. The function now has the signature <code>wchar_t* wcstok(wchar_t*, wchar_t const*, wchar_t**)</code>, and requires the caller to pass the context as a third argument to the function.</p> </blockquote> <p>At the cost of sounding inherently stupid, I will still go ahead and ask, Can anybody please explain the purpose of this third parameter in simple terms and how it has changed <code>std::wcstok</code> from its earlier version?</p>
2
.NET DPAPI and AES Encryption: Sense-Check
<p>I am just about to write a new encryption system for a website I'm currently working on, and wanted to see if i could get someone to sense-check it before I get started if possible!</p> <p><strong>Update:</strong> <strong><em>Should have been clearer with my original question. I need to encrypt some user data that I also need to be able to read back at a later data. And, I also need to store the users password or a hash of the password for verifying the user upon login.</em></strong></p> <p>The plan is:</p> <ol> <li><p><strong>Master Key:</strong> Create a DPAPI key-setter application to take a text-based master key, encrypt via DPAPI, then save the encrypted output to a text file on the server. This is a one-off task that I'll perform every time I move the site to a new server. The master key will be used to perform AES encryption.</p></li> <li><p><strong>When a new user registers:</strong></p> <p>2.1. Save password data / hash of password data.</p> <p>2.2. Load master key file, decrypt the key using DPAPI. Use the decrypted master key, and a new random IV for each piece of user data to create an AES-encrypted string. Save each encrypted string by prefixing the encrypted string with the corresponding random IV, and insert into a varchar column in the database.</p></li> <li><p><strong>Upon user login:</strong></p> <p>3.1. Match password hash to validate user. </p> <p>3.2. For each encrypted user data field, split content into two parts: the IV and the encrypted data. Taking the master key from DPAPI, and the IV, decrypt the data and display on-screen.</p></li> </ol> <p>How does that sound? Are there any obvious flaws to the above? </p> <p>I'm new to this having previously used Enterprise Library Security for this sort of the stuff in the past (which is no longer available in .NET core!), so any help would be massively appreciated!</p>
2
Cross Domain Ajax call to get static Html?
<p>I am trying to make cross domain call to get some HTML , I am getting below error please some one can help me what need to be done. below is error which i am getting.</p> <p><strong>"Error" :</strong> Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at <a href="http://test.com/webclient/widget/GetPromotionalBanner/%7bA301A86A-87CB-4F49-BF0E-A8EE355295BD%7d/Bright" rel="nofollow">http://test.com/webclient/widget/GetPromotionalBanner/%7bA301A86A-87CB-4F49-BF0E-A8EE355295BD%7d/Bright</a>. (Reason: missing token 'access-control-allow-origin' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).</p> <p>Always going on error section.</p> <p>JAVASCRIPT CODE</p> <pre><code>(function ($) { 'use strict'; //================================================== // DOCUMENT READY //-------------------------------------------------- function mytest(ss){ console.log(ss); } $.ajax({ type: "Get", url:"http://mytesturl.com", cache: "false", headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Request-Headers':'X-Custom-Header','Access-Control-Request-Method':"GET"}, crossDomain : true, success: function(html) { alert("Cross Domain Call Success"); console.log(html); }, error:function(error){ alert("Error Response :", error); console.log(error); } }); //-------------------------------------------------- // end DOCUMENT READY... //================================================== }(jQuery)); </code></pre> <blockquote> <p><strong>Respone Header of Ajax call</strong></p> </blockquote> <p>Access-Control-Allow-Orig... * Cache-Control private Content-Encoding gzip Content-Length 886 Content-Type text/html; charset=utf-8 Date Mon, 18 Jul 2016 07:46:49 GMT Server Microsoft-IIS/8.5 Set-Cookie ASP.NET_SessionId=pe1r0iiklzj5ch3fuanhzlun; path=/; HttpOnly SC_ANALYTICS_GLOBAL_COOKIE=a874641e69b948898f6dcb596a987fbc|False; expires=Sat, 18-Jul-2026 07:46:49 GMT; path=/; HttpOnly Vary Accept-Encoding X-AspNet-Version 4.0.30319 X-AspNetMvc-Version 5.2 X-Powered-By ASP.NET</p> <p><strong>Request Header</strong> Accept text/html,application/xhtml+xml,application/xml;q=0.9,<em>/</em>;q=0.8 Accept-Encoding gzip, deflate Accept-Language en-US,en;q=0.5 Access-Control-Request-He... access-control-allow-origin Access-Control-Request-Me... GET Cache-Control max-age=0 Connection keep-alive Host test.com Origin null User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0</p>
2
Check login status in routeProvider
<p>I'm working on an Angular project but I'm having a little problem and I'd appreciate any help because I'm really lost. Basically I need to check if a user is logged in, and if he is, he should not be allowed to access a certain view/route, here's the code I'm using for this:</p> <pre><code>'use strict'; angular.module('testApp') .config(function ($routeProvider) { $routeProvider .when('/registroVisitante', { template: '&lt;registro-visitante&gt;&lt;/registro-visitante&gt;', resolve: { "check": function(Auth, $location) { console.log(Auth.isLoggedIn()); if (!Auth.isLoggedIn()) { alert("Access allowed"); } else { $location.path('/'); //redirect user to home. alert("Access denied"); } } } }); }); </code></pre> <p>The problem itself is that, this is actually working, but only when I try to access the route via an anchor click or ng-click or whatever, however, when I type the route in the address bar it lets me access but it shouldn't, anyone has any idea why?</p>
2
Value of a short variable in C
<p>I have a simple program with a short variable declaration:</p> <pre><code> short int v=0XFFFD; printf(&quot;v = %d\n&quot;,v); printf(&quot;v = %o\n&quot;,v); printf(&quot;v = %X\n&quot;,v); </code></pre> <p>The result is:</p> <pre><code>v = -3 ; v = 37777777775 ; v = FFFFFFFD </code></pre> <p>I don't understand how to calculate these values. I know that a short variable can hold values between -32768 and 32767, and the value 0XFFFD causes an overflow, but I don't know how to calculate the exact value, which is -3 in this case.</p> <p>Also, if my declaration is v=0XFFFD why the output v=%X is FFFFFFFD?</p>
2