title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
Array Definition Modelling in MongoAlchemy
<p>I try to model my MongoAlchemy class in Flask. Here is my model:</p> <pre><code>{ "_id" : ObjectId("adfafdasfafag24t24t"), "name" : "sth." "surname" : "sth." "address" : [ { "city" : "Dublin" "country" : "Ireland" } ] } </code></pre> <p>Here is my documents.py class:</p> <pre><code> class Language_School(db.Document): name = db.StringField() surname = db.StringField() address = db.??? </code></pre> <p>How can I define this like array model (address) in Flask?</p> <p><strong>Edit:</strong> I have already tried to my models like before asking question. But I took error like "AttributeError AttributeError: 'list' object has no attribute 'items'".</p> <pre><code>class Address(db.Document): city = db.StringField() country = db.StringField() class Language_School(db.Document): name = db.StringField() surname = db.StringField() address = db.DocumentField(Address) </code></pre>
2
Two ng-clicks on in same div
<p>So I've been looking around for an answer for this but I just couldn't find the answer. So what I have is a ng-repeat of items that are in a particular class="list-items". When I click on each of the item in items, it should execute a function. Within each list I have an remove button which I would like to remove the item when clicked.</p> <p>So some code for reference:</p> <pre><code> &lt;div ng-click="executeCallback($index)" class="list-items"&gt; &lt;div class="item-info"&gt; &lt;span&gt;some info here&lt;/span&gt; &lt;/div&gt; &lt;button ng-click="removeItem($index)"&gt;X&lt;/button&gt; &lt;/div&gt; </code></pre> <p>So I did right now, in my CSS, i tried using an position absolute on the button and a z-index of like 10000 to show that it is greater than, but when I click the removeItem button, it still calls the executeCallback function. I don't want it to call the executeCallback function.</p> <p>Is there a way to have the removeItem function be called only when the remove button is clicked and not the parent class?</p>
2
Firebase snapshot.val() not binding to $scope
<p>I'm using FireBase and trying to do some queries, the results are logging in but are not visible in the HTML <code>$scope</code>. </p> <pre><code>var shopRef = firebaseDataService.intro; $scope.shops = []; var taskRef = shopRef.orderByChild("cat").equalTo("Accomodation"); taskRef.on("value", function(snapshot) { var snapData = snapshot.val(); console.log(snapData); $scope.shops.push(snapData); }); </code></pre> <p>When I use <code>$scope.$apply()</code>, I manage to get the data updated to shops, but it's still not passing anything to my directive .</p> <pre><code> &lt;search-card shops="shops"&gt; &lt;/search-card&gt; &lt;p&gt; Shops are {{shops}}&lt;/p&gt; </code></pre> <p>I got it working somehow with $firebaseArray </p> <pre><code> $scope.shops = $firebaseArray(taskRef); </code></pre> <p>but I`d still like to know what I'm doing wrong and why it's not working with the snapshot.</p>
2
How to use react inside a polymer component?
<p>It seems it could posible to use react inside a polymer web component but I couldn’t find a working example, only <a href="http://codepen.io/mcondon/pen/HKtBq" rel="nofollow">this</a>, but it seems outdated.</p> <p><strong>HTML</strong></p> <pre><code>&lt;link rel="import" href="http://www.polymer-project.org/components/polymer/polymer.html" /&gt; &lt;polymer-element name="my-polymer" constructor="" attributes="name"&gt; &lt;template&gt; &lt;P&gt;I AM {{name}}&lt;/P&gt; &lt;div id="reactContainer"&gt;&lt;/div&gt; &lt;/template&gt; &lt;script type="text/jsx"&gt; /** @jsx React.DOM **/ Polymer('my-polymer', { created: function(){}, ready: function(){}, attached: function(){}, domReady: function(){ React.renderComponent(&lt;MyReact name="REACT INSIDE POLYMER"/&gt;, this.$.reactContainer); }, detached: function(){}, attributeChanged: function(attrName, oldVal, newVal) {} }); &lt;/script&gt; &lt;/polymer-element&gt; &lt;my-polymer name="POLYMER"&gt;&lt;/my-polymer&gt; </code></pre> <p><strong>JS</strong></p> <pre><code>/** @jsx React.DOM */ var MyReact = React.createClass({ render: function() { return ( &lt;p&gt;I AM {this.props.name}&lt;/p&gt; ); } }); </code></pre>
2
Bitmap Rotate And Save Image
<p>I would like to rotate and save the rotated image and move it elsewhere within my android device.</p> <ol> <li>I am able to rotate my image and set it to image view.</li> <li>I can copy an UN-ROTATED image to a destination of my choice.</li> </ol> <p>The only thing I am unable to do is get the saved rotated image FILE (rotated.jpg)</p> <p>My code below to rotate: (this does not save rotated file to storage?)</p> <pre><code> Bitmap bmp = BitmapFactory.decodeFile(filePathLocal); Matrix matrix = new Matrix(); matrix.postRotate(getImageOrientation(filePathLocal)); rotatedBitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true); //Set Image ImageButton ibProfile = (ImageButton) findViewById(R.id.ibProfile); ibProfile.setImageBitmap(rotatedBitmap); </code></pre> <p>Now the above only rotates temporarily until the activity is ended, now I would like to save this rotated image from above code and move it somehwere before uploading it to server, I already know how to copy/move files and upload so no need to post those codes - all I need is the code for SAVING ROTATED IMAGE, so that I have something like /sdcard/saved_rotated_image.jpg</p>
2
Google geocoder API: Lookup partial postal code (Germany)
<p>I am trying to build an autocomplete where people can start typing a postal code, and get meaningful suggestions before the postal code is complete.</p> <h3>Existing example</h3> <p>An existing example can be found here: <a href="https://weisse-liste.de/de/arzt/arztsuche/" rel="nofollow">https://weisse-liste.de/de/arzt/arztsuche/</a></p> <p>Typing "120" in "Ort oder Postleitzahl" gets a list of suggestions where the postal code starts with "120". I am not affiliated with this site, and don't know if they are even using the Google geocoding API. (The request goes to their own server, then they do something with it.)</p> <h3>Attempt with Google geocoding API</h3> <p>The closest I can get with Google API is <a href="http://maps.googleapis.com/maps/api/geocode/json?address=120&amp;sensor=false&amp;components=country:DE" rel="nofollow">http://maps.googleapis.com/maps/api/geocode/json?address=120&amp;sensor=false&amp;components=country:DE</a></p> <p>But the only result this gives me is the one with "formatted_address" : "Germany", so the entire country.</p> <h3>EDIT: client-side js vs server-side php / handcrafted request url</h3> <p>The existing answer proposes client-side javascript. Which is totally valid given the question.</p> <p>It would still be interesting to see an answer giving a hand-crafted url similar to the one above, which can be used in a server-side request. If this is not possible, no problem. An advantage could be privacy of the visitor, by avoiding a client-side request to Google. I am not even saying this is a good idea, but it could still be useful information.</p>
2
How to get .CSV file into local machine from Docker image of Cassandra database
<p>currently i am using cassandra database with kong gateway i want to import and export data from my local machine to docker contianers.</p> <p><code>copy kong.apis to 'apis.csv';</code></p> <p><code>copy kong.apis from 'apis.csv'</code></p>
2
Unresolved dependencies: com.typesafe.play (Play Java)
<p>I am receiving a similar error regarding typesafe.play. I have added scalaVersion := "2.11.7" to my build.sbt file and still seeing the same error.</p> <p><strong>build.sbt</strong></p> <pre><code>version := "1.0-SNAPSHOT" lazy val root = (project in file(".")) .enablePlugins(PlayJava, PlayEbean) .dependsOn(celsus) .aggregate(celsus) lazy val celsus = (project in file("libs/celsus")) .enablePlugins(PlayJava) scalaVersion := "2.11.7" libraryDependencies ++= Seq( javaJdbc, cache, javaWs, "com.amazonaws" % "aws-java-sdk" % "1.3.11" ) </code></pre> <p><strong>plugins.sbt</strong></p> <pre><code>resolvers += "Typesafe repository" at http://repo.typesafe.com/typesafe/releases/" addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.4") </code></pre> <p><strong>Error received</strong></p> <pre><code>Error:Error while importing SBT project: ... [trace] Stack trace suppressed: run 'last root/:ssExtractDependencies' for the full output. [error] (celsus/:update) sbt.ResolveException: unresolved dependency: com.typesafe.play#play-server_2.10;2.5.4: not found [error] unresolved dependency: com.typesafe.play#play-java_2.10;2.5.4: not found [error] unresolved dependency: com.typesafe.play#play-netty-server_2.10;2.5.4: not found [error] unresolved dependency: com.typesafe.play#play-logback_2.10;2.5.4: not found [error] unresolved dependency: com.typesafe.play#play-test_2.10;2.5.4: not found [error] unresolved dependency: com.typesafe.play#play-omnidoc_2.10;2.5.4: not found </code></pre> <p>Can someone please help?</p>
2
CAShapeLayer path spring animation not 'overshooting'
<p>I'm experimenting with animating CAShapeLayer paths with CASpringAnimation. The expected result is a 'morphing' between shapes that acts 'springy'.</p> <p>I have a basic code example between a circle and square path as below, however the end result is a spring animation that does not 'overshoot' past the final, larger square path, which is the expected behaviour.</p> <p><a href="https://i.stack.imgur.com/NTDGp.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NTDGp.gif" alt="enter image description here"></a></p> <p>My code is:</p> <pre><code>let springAnimation = CASpringAnimation(keyPath: "path") springAnimation.damping = 1 springAnimation.duration = springAnimation.settlingDuration springAnimation.fromValue = standardCirclePath().cgPath springAnimation.toValue = standardSquarePath().cgPath circleLayer.add(springAnimation, forKey: nil) // Where circleLayer (red background) is a sublayer of a basic UIView in the frame (blue background) </code></pre> <p>I got my paths <a href="https://stackoverflow.com/questions/24788283/ios-animate-morph-shape-from-circle-to-square">from this answer</a>.</p> <p>Is there a way with CASpringAnimation to achieve this for a CAShapeLayer path transform? Otherwise, what are the alternatives?</p>
2
java.lang.IllegalArgumentException: Cannot find elements when the XPath expression is null error displaying while sending keys through Method
<p>Getting error while Sendkeys through methods.</p> <pre><code>public static void enterTask(String task) throws Exception { // Entering task name GUIFunctions.typeTxtboxValue(driver,By.xpath(ObjRepoProp.getProperty("enterTaskName_XPATH")),task); Thread.sleep(5000); } </code></pre> <p>But while send keys directly it is working fine.</p> <pre><code>driver.findElement(By.xpath(ObjRepoProp.getProperty("enterTaskName_xpath"))).sendKeys("qaz"); </code></pre>
2
action attached to selector in bootstrap table will not fire on page change
<p>This is an issue I have with Wenzhixin's Bootstrap table.</p> <p>If I have a selector (ie a link) with an action attached (eg <em>on('click', fucntion() {...});</em> ) in any of the cells, that action won't fire when page is changed, sorting is applied search is performed.</p> <p>Here's a short example: <a href="https://jsfiddle.net/L4h0gs4g/" rel="nofollow">https://jsfiddle.net/L4h0gs4g/</a></p> <p><strong>HTML</strong>:</p> <pre><code>&lt;table class="table table-striped table-bordered table-hover table-condensed table-responsive" data-show-toggle="true" data-show-columns="true" data-toggle="table" data-sort-name="device" data-sort-order="desc" data-striped="true" data-pagination="true" data-search="true"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th data-sortable="true" data-field="device"&gt;Device&lt;/th&gt; &lt;th data-sortable="true" data-field="assettag"&gt;Asset Tag&lt;/th&gt; &lt;th data-sortable="true" data-field="serial"&gt;Serial No.&lt;/th&gt; &lt;th data-sortable="false"&gt;Service&lt;br /&gt;History&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;RICOH SPC242SF PRINTER&lt;/td&gt; &lt;td&gt;C013991&lt;/td&gt; &lt;td&gt;T222PB01287&lt;/td&gt; &lt;td class="fleet_machine_actions"&gt; &lt;a href="javascript:void(0);" class="machine_actions" title="Service History"&gt;check&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;RICOH SPC242SF PRINTER&lt;/td&gt; &lt;td&gt;C013991&lt;/td&gt; &lt;td&gt;T222PB01287&lt;/td&gt; &lt;td class="fleet_machine_actions"&gt; &lt;a href="javascript:void(0);" class="machine_actions" title="Service History"&gt;check&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p><strong>jQuery</strong>:</p> <pre><code>&lt;script&gt; $(document).ready(function() { $(".machine_actions").on('click', function(e){ alert($(this).attr("title")); }); }) &lt;/script&gt; </code></pre> <p>The link will trigger the alert box at first, but if you sort the table it will not trigger again. It's like jQuery cannot see that selector once the table's been changed / updated.</p> <p>Is this a known bug or is there a workaround this at all?</p> <p>Also posted on <a href="https://github.com/wenzhixin/bootstrap-table/issues/2488" rel="nofollow">https://github.com/wenzhixin/bootstrap-table/issues/2488</a></p>
2
Ruby subclass not inheriting parent method or not able to call parent methods in class body
<p>I'm making a page-object.</p> <pre><code>require 'watir-webdriver' class Page attr_accessor :driver def initialize @driver = Watir::Browser.new :phantomjs @driver.goto(some_arbitrary_url) end def element(**attrs) @driver.element( id: attrs[:id], tag_name: attrs[:tag_name]) end def elements(**attrs) @driver.elements( class: attrs[:class], tag_name: attrs[:tag_name]) end end </code></pre> <p>However when I subclass the <code>Page</code> class, I cannot use it's <code>element</code> methods in the class body, unless I put them in a method, like so:</p> <pre><code>class Home &lt; Page #throws NoMethodError: undefined method 'element' for Home:Class some_element = element(id: 'elements_id') #works def some_arbitrary_element element(id: 'elements_id') end end </code></pre> <p>So far, just tinkering, I've tried doing <code>protected: element, elements</code> as well as <code>self.element(...)</code> both to no avail. So what's going on? I'm not reading anything enlightening in Matz' Ruby book about method inheritance, and usually Ruby is so unsurprising, so it's hard for me to identify where the problem actually is.</p>
2
selenium webdriver not working
<p>Selenium version: 2.53.6 Firefox version: 47.0.1 Chrome version: 51.0.2704.106 m</p> <p>Now if I want to use them like that:</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() driver2 = webdriver.Chrome() </code></pre> <p>i get an error: FileNotFoundError: [WinError 2]</p> <p>i even checked the manual twice that its the correct way to code it.</p> <p>So why cant it find the browsers even though everything is updated to latest version? Firefox and chrome work fine if I use them as person.</p> <p>edit: can provide error code in comment so here it is, (srry some parts are in german, as it is the main language istalled on my pc):</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; driver = webdriver.Firefox() File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 80, in __init__ self.binary, timeout) File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\firefox\extension_connection.py", line 52, in __init__ self.binary.launch_browser(self.profile, timeout=timeout) File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py", line 67, in launch_browser self._start_from_profile_path(self.profile.path) File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py", line 90, in _start_from_profile_path env=self._firefox_env) File "C:\Program Files (x86)\Python35-32\lib\subprocess.py", line 947, in __init__ restore_signals, start_new_session) File "C:\Program Files (x86)\Python35-32\lib\subprocess.py", line 1224, in _execute_child startupinfo) FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden </code></pre> <p>and for Chrome its:</p> <pre><code>Traceback (most recent call last): File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\common\service.py", line 64, in start stdout=self.log_file, stderr=self.log_file) File "C:\Program Files (x86)\Python35-32\lib\subprocess.py", line 947, in __init__ restore_signals, start_new_session) File "C:\Program Files (x86)\Python35-32\lib\subprocess.py", line 1224, in _execute_child startupinfo) FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;pyshell#2&gt;", line 1, in &lt;module&gt; driver2 = webdriver.Chrome() File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 62, in __init__ self.service.start() File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\common\service.py", line 71, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home </code></pre> <p>the wierd thing is i did include it in path enivornment variables. I can type in 'chromedriver' in the cmd and it finds it.... so python should too. 1 more mistake: doing last thing says some wierd stuff about: only local connetctions are allowed.</p>
2
NiFi ExecuteScript with Groovy: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
<p>I'm trying to execute a Groovy script which is using Microsoft SQL server JDBC driver. I'm trying to specify the path of the sql jdbc jar in the modules directory. However, my groovy script complains that the SQLServerDriver class is not found.</p> <p>This is what the configuration looks like - <img src="https://i.stack.imgur.com/snBzH.jpg" alt="enter image description here"></p> <p>This is the error that I get</p> <pre><code>Caused by: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:264) at groovy.sql.Sql.loadDriver(Sql.java:705) at groovy.sql.Sql.newInstance(Sql.java:445) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93) at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325) at org.codehaus.groovy.runtime.callsite.StaticMetaMethodSite$StaticMetaMethodSiteNoUnwrap.invoke(StaticMetaMethodSite.java:133) at org.codehaus.groovy.runtime.callsite.StaticMetaMethodSite.call(StaticMetaMethodSite.java:91) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:149) at Script1.run(Script1.groovy:23) at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:352) </code></pre> <p>When I print my java classpath in my groovy script I don't see the added module in the classpath either.</p> <pre><code>println "classPath:" + System.getProperty("java.class.path") </code></pre> <p><a href="https://i.stack.imgur.com/Q3WeM.jpg" rel="nofollow noreferrer">The added URL shows up in the classloader.</a></p>
2
AngularJS how to assign response data to a variable
<p>How can i assign the response to a variable or $scope. Here i want to assign the response to data variable</p> <p>here is the screen shot <a href="https://i.stack.imgur.com/TgnQq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TgnQq.png" alt="enter image description here"></a></p> <pre><code>'use strict'; `var dashModule = angular.module("Student");` dashModule.controller("studentDashboardCtrl", ['$scope', 'authService', 'StudentService', function ($scope, authService, StudentService) { //Check authorised user var data; authService.checAuthentication(); StudentService.getBatchList(function (response) { console.log(response); }); }]); </code></pre>
2
"Got unknown error from server ..." using Socket.io on Swift
<p>I'm trying to connect to my Xcode Server's internal socket.io. I initialize the client using this:</p> <pre><code>self.socket = SocketIOClient(socketURL: NSURL(string: "https://37.203.216.82")!, options: [.Path("/xcode/internal/socket.io"), .Log(true), .Reconnects(true), .ForceNew(true), .SessionDelegate(self), .SelfSigned(true)]) </code></pre> <p>But when I use <code>self.socket.connect()</code> I get this response:</p> <pre><code>2016-07-15 16:13:49.179 MyApp[84260:1941316] LOG SocketIOClient: Adding handler for event: connect 2016-07-15 16:13:49.180 MyApp[84260:1941316] LOG SocketIOClient: Adding handler for event: integrationStatus 2016-07-15 16:13:49.180 MyApp[84260:1941316] LOG SocketIOClient: Adding handler for event: advisoryIntegrationStatus 2016-07-15 16:13:49.180 MyApp[84260:1941316] LOG SocketIOClient: Adding engine 2016-07-15 16:13:49.181 MyApp[84260:1941316] LOG SocketEngine: Starting engine. Server: https://37.203.216.82 2016-07-15 16:13:49.181 MyApp[84260:1941316] LOG SocketEngine: Handshaking 2016-07-15 16:13:49.182 MyApp[84260:1941792] LOG SocketEnginePolling: Doing polling request 2016-07-15 16:13:49.317 MyApp[84260:1941792] LOG SocketEnginePolling: Got polling response 2016-07-15 16:13:49.322 MyApp[84260:1941786] LOG SocketEngine: Got message: Welcome to socket.io. 2016-07-15 16:13:49.324 MyApp[84260:1941786] ERROR SocketIOClient: Got unknown error from server Welcome to socket.io. 2016-07-15 16:13:49.326 MyApp[84260:1941786] LOG SocketIOClient: Handling event: error with data: ( "Got unknown error from server Welcome to socket.io." ) </code></pre> <p>I've tried changing the path to the <code>socket.io.js</code> file or <code>xcode/internal/socket.io/1/</code> but it all gives the same response, instead, <code>Welcome to socket.io</code> is replaced by the contents of the file there.</p>
2
Spring-MVC @modelAttribute how to send list of object to view in separate form and update one object at a time
<p>I have a controller that goes to the DB and get a list of books. I like to use @modelAttribute to display individual books in separate form so I can do quick edits on each item.</p> <p>Controller</p> <pre><code>@RequestMapping("/") public String pagIndex(Model model){ System.out.println("loading index page"); // Get list of books List&lt;Book&gt; books = bookDao.getBookList(); // List of object to Model model.addAttribute("books", books); return "index"; } </code></pre> <p>View</p> <pre><code>&lt;h3&gt;Book Inventory&lt;/h3&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;ID&lt;/td&gt; &lt;td&gt;Book Name&lt;/td&gt; &lt;td&gt;ISPN&lt;/td&gt; &lt;td&gt;Price&lt;/td&gt; &lt;td&gt;&lt;/br&gt;&lt;td&gt; &lt;td&gt;Object&lt;/td&gt; &lt;/tr&gt; &lt;!-- Each book in separate form for easy update --&gt; &lt;c:forEach var="book" items="${books}"&gt; &lt;tr&gt; &lt;sf:form class="editeForm" action="${pageContext.request.contextPath}/edititem" modelAttribute="book" method="POST"&gt; &lt;td&gt;${book.id} &lt;input type="hidden" path="id" name="id"&gt;&lt;/td&gt; &lt;td&gt;&lt;sf:input type="text" path="name" name="name" /&gt;&lt;/td&gt; &lt;td&gt;&lt;sf:input type="text" path="ispn" name="ispn" /&gt;&lt;/td&gt; &lt;td&gt;&lt;sf:input type="text" path="price" name="price" /&gt;&lt;/td&gt; &lt;td&gt;&lt;/br&gt;&lt;td&gt; &lt;td&gt;${book}&lt;/td&gt; &lt;td&gt;&lt;input type="submit" value="save edite"&gt;&lt;input type="submit" name="delete" value="delete"&gt;&lt;/td&gt; &lt;/sf:form&gt; &lt;/tr&gt; &lt;/c:forEach&gt; &lt;/table&gt; </code></pre> <p>When i set modelAttribute="book" stack trace is </p> <pre><code>Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'book' available as request attribute at org.springframework.web.servlet.support.BindStatus.&lt;init&gt;(BindStatus.java:144) </code></pre> <p>modelAttribute="${book}" stack trace is</p> <pre><code>java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'Book bean [id=1, name=Java: A Beginner's Guide, ispn=978-0071809252, price=18' available as request attribute </code></pre> <p>Update: If I use plain JSTL it works but anyway to use modelAttriburte?</p> <pre><code>&lt;h3&gt;Book Inventory&lt;/h3&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;ID&lt;/td&gt; &lt;td&gt;Book Name&lt;/td&gt; &lt;td&gt;ISPN&lt;/td&gt; &lt;td&gt;Price&lt;/td&gt; &lt;td&gt;&lt;/br&gt;&lt;td&gt; &lt;td&gt;Object&lt;/td&gt; &lt;/tr&gt; &lt;!-- Each book in separate form for easy update --&gt; &lt;c:forEach var="book" items="${books}"&gt; &lt;tr&gt; &lt;form class="editeForm" action="${pageContext.request.contextPath}/edititem" method="POST"&gt; &lt;td&gt;${book.id} &lt;input type="hidden" name="id" value="${book.id}"/&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="name" value="${book.name} /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="ispn" value="${book.ispn} /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="price" value="${book.price} /&gt;&lt;/td&gt; &lt;td&gt;&lt;/br&gt;&lt;td&gt; &lt;td&gt;${book}&lt;/td&gt; &lt;td&gt;&lt;input type="submit" value="save edite"&gt;&lt;input type="submit" name="delete" value="delete"&gt;&lt;/td&gt; &lt;/form&gt; &lt;/tr&gt; &lt;/c:forEach&gt; &lt;/table&gt; </code></pre>
2
How can I check if textarea (tinymce) only contains space?
<p>I have a form using Tinymce, I need to check if it only contains space.</p> <p>I try using this function</p> <pre><code>function validation_form() { var content = tinyMCE.get('main-comment').getContent().replace('&amp;nbsp;',''); if(content == "" || content == null || content == '&lt;p&gt; &lt;/p&gt;') { return false; } } </code></pre> <p>But it returns <strong>true</strong> when I input several spaces and submit, I want it to return false instead.</p> <p>Can anyone help me? Thanks,</p>
2
pyOpenSSL NotImplementedError Google App Engine
<p>I'm trying to download some data using Google Analytics Reporting API V4.</p> <p>Inside my <code>lib/</code> folder (on the GAE project) I have <code>pyOpenSSL</code> and all its dependencies.</p> <p>Locally, in my virtualenv, it works fine.</p> <p>That's the error I'm getting:</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>Environment: Request Method: GET Request URL: ############### Django Version: 1.9 Python Version: 2.7.5 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/base/data/home/apps/myapp/1.394185263495829842/lib/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/base/data/home/apps/myapp/1.394185263495829842/lib/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/base/data/home/apps/myapp/1.394185263495829842/polls/views.py" in index 27. return HttpResponse(json.dumps(we.atualizacao_diaria())) File "lib/workers/worker_estacio.py" in atualizacao_diaria 41. return self.atualizar_periodo(f_date, f_date) File "lib/workers/worker_estacio.py" in atualizar_periodo 47. c_ga_estacio = ConectorEstacioGA() File "lib/workers/conectores/conector_ga.py" in __init__ 50. credentials = ServiceAccountCredentials.from_p12_keyfile(SERVICE_ACCOUNT_EMAIL, KEY_FILE_LOCATION, scopes=SCOPES) File "lib/oauth2client/service_account.py" in from_p12_keyfile 345. token_uri=token_uri, revoke_uri=revoke_uri) File "lib/oauth2client/service_account.py" in _from_p12_keyfile_contents 300. raise NotImplementedError(_PKCS12_ERROR) Exception Type: NotImplementedError at / Exception Value: This library only implements PKCS#12 support via the pyOpenSSL library. Either install pyOpenSSL, or please convert the .p12 file to .pem format: $ cat key.p12 | \ &gt; openssl pkcs12 -nodes -nocerts -passin pass:notasecret | \ &gt; openssl rsa &gt; key.pem</code></pre> </div> </div> </p> <p>Could someone help me please?</p>
2
Does single hive application(job) spawn multiple yarn applications?
<p>Does a single HIVE query that gets submitted to Yarn creates multiple jobs (i.e. multiple YARN applications) ? Here I treat job and application to be the same think in YARN context.</p> <p>From what I understand -- Yarn creates an Application Master (AM) per 'application'. So here that single HIVE query can be treated as an 'application'. So, the Resource Manager will create container on some node and start AM in that container. That container in turn may create multiple 'tasks' (not applications) i.e. mappers and reducers within other containers reserved for that AM (on the same or different node -- this is immaterial here). Now the collection of all these Application Masters are engaged in solving that single HIVE query that is submitted to YARN. In fact that's why we say that AM is per application. Since we submitted just one HIVE query, from YARN point of view there is only one application. So when I fire the below YARN command, it should show me just one application running:-</p> <pre><code>yarn application -list </code></pre> <p>Is this understanding correct? Or that if we have several mappers and reducers spawned for that one HIVE query, multiple YARN applications are invoked?</p>
2
Pig CSVExcelStorage DoubleQuoted Commas
<p>I am receiving csv formatted files (fields are comma delimited and double-quoted) into HDFS and have developed a pig script which removes the header rows and strips the double quotes before I insert the data into Hive using an HQL script.</p> <p>This process has been working fine; however, today I discovered a data issue with one of the tables. The files for this table in particular have a string field which can contain multiple commas within the double quotes. This is resulting in the data being incorrectly loaded into the wrong columns in Hive for some of the records.</p> <p>I cannot change the format of the files at the source.</p> <p>Currently I am using the PiggyBank CSVExcelStorage to process the csv formatting as follows. Can this be modified to produce the correct result? What other options do I have? I noticed that there is also a CSVLoader now but havent found any examples showing how to use/implement it. <a href="https://pig.apache.org/docs/r0.8.1/api/org/apache/pig/piggybank/storage/CSVLoader.html" rel="nofollow">Pig CSVLoader</a></p> <pre><code>USING org.apache.pig.piggybank.storage.CSVExcelStorage(',','NO_MULTILINE','NOCHANGE','SKIP_INPUT_HEADER') </code></pre> <p><strong>Editing to add additional sample data and results of testing</strong>:</p> <p>Sample Input File Data:</p> <pre><code>"P_NAME","P_ID","C_ID","C_NAME","C_TYPE","PROT","I_NAME","I_ID","A_NAME","A_IDS","C_NM","CO" "SAMPLEPNAME","123456","789123","SAMPLECNAME","Upload","SAMPLEINAME","This Sample Name of A, B, and C","3234","This Sample Name of A, B, and C","3234","c_name","R" "SAMPLEPNAME2","123457","789124","SAMPLECNAME2","Download","SAMPLEINAME2","This Sample Name","3235","This Sample Name","3235","c_name2","Q" </code></pre> <p>Using CSVExcelLoader with formatting provided above:</p> <pre><code>SAMPLEPNAME,123456,789123,SAMPLECNAME,Upload,SAMPLEINAME,This Sample Name of A, B, and C,3234,This Sample Name of A, B, and C,3234,c_name,R SAMPLEPNAME2,123457,789124,SAMPLECNAME2,Download,SAMPLEINAME2,This Sample Name,3235,This Sample Name,3235,c_name2,Q </code></pre> <p>Using CSVLoader as CSVLoader(): Notice - Didn't see any options for parameters to be provided to the constructor</p> <pre><code>P_NAME,,,C_NAME,C_TYPE,PROT,I_NAME,,A_NAME,,C_NM,CO SAMPLEPNAME,123456,789123,SAMPLECNAME,Upload,SAMPLEINAME,This Sample Name of A, B, and C,3234,This Sample Name of A, B, and C,3234,c_name,R SAMPLEPNAME2,123457,789124,SAMPLECNAME2,Download,SAMPLEINAME2,This Sample Name,3235,This Sample Name,3235,c_name2,Q </code></pre> <p>The only real difference I see is that CSVLoader isn't removing the header row as I saw no option to select this and instead its removing some of the header names.</p> <p>Am I doing something incorrectly? A working solution will be appreciated.</p>
2
how to exclude negative numbers from average calculation in while loop
<p>I have a program that accepts user inputs and calculate Max, Min, and Average. The program closes when the user inputs any negative number. How do i exclude the negative number from the average calculation? Here is what i have so far.</p> <pre><code> // variable double n = 1; double ave = 0; double sum = 0; double max = Double.MIN_VALUE; double min = Double.MAX_VALUE ; int count = 0; double neg; //creat scanner object Scanner input = new Scanner(System.in); //loop while (n &gt; 0) { System.out.print("Input an income (any negative number to quit): "); n = input.nextDouble(); sum = sum + n; count++; ave = sum / count; if(n&lt;0) neg = n; if(n&gt;max &amp;&amp; n &gt;= 0 ) max = n; if(n&lt;min &amp;&amp; n &gt;= 0) min = n; if(n&gt;0) ave = n; } System.out.print(" Average " + ave + "\n Maximum " + max + "\n Minimum " + min); } </code></pre> <p>} </p>
2
PHP Notice: String offset cast occurred line 251 & 258
<p>i get php notice with this</p> <pre><code>$code = ""; while ($id &gt; $length - 1) { // determine the value of the next higher character // in the short code should be and prepend $code = self::$chars[fmod($id, $length)] . $code; //&lt;-- line 251 // reset $id to remaining value to be converted $id = floor($id / $length); } // remaining value of $id is less than the length of // self::$chars $code = self::$chars[$id] . $code; //&lt;-- line 258 return $code; </code></pre> <p>The NOTICE code is this part:</p> <pre><code>$code = self::$chars[fmod($id, $length)] . $code; $code = self::$chars[$id] . $code; </code></pre> <p>How to fix it? I can’t find it, please your help all.. :)</p>
2
How to prevent the calls to onCreate/onCreateView methods if the activity is finishing
<p>I have an <code>ActivityA</code> and which host a <code>fragmentA</code></p> <p><code>onAttach()</code> method of <code>fragmentA</code>, I need to check some conditions and if it fails, I need to finish the activity. I'm finishing the activity by calling <code>getActivity().finish()</code>.</p> <p>Even after I call the finish method, it is still calling the <code>onCreate()</code>, <code>onCreateView()</code> and <code>onViewCreated()</code> methods in <code>fragmentA</code> .</p> <p>Is there any way I can stop these calls?</p>
2
Get only the structure(row names & column name) of data set in R
<p>Consider a data frame with row names and column names:</p> <pre><code>&gt; data &lt;- data.frame(a=1:3,b=2:4,c=3:5,row.names=c("x","y","z")) &gt; data a b c x 1 2 3 y 2 3 4 z 3 4 5 </code></pre> <p>I just want to display the row names and column names of data like:</p> <pre><code> a b c x y z </code></pre>
2
Parse POST HTTP response using Python
<p>i want to parse a POST HTTP response using python.</p> <p>My response looks like:</p> <pre><code>{ "Result": 0, "ResponseStatus": { "ErrorCode": null, "Message": null, "StackTrace": null, "Errors": null }, "SessionId": "68ebcd6f-0aef-420d-a12b-c953f8df8ed1", "ResponseHeader": { "Succeeded": true, "Errors": [] } } </code></pre> <p>I want to parse the - "SessionID" to a 2nd http request. How can i achieve it? Thanks ! </p>
2
How can I initialize a list and append objects of any type to it in Python
<p>I am trying to write a Python program that will initialize a list and add objects of any type to the list. I believe that I have initialized the list properly in my <code>__init__</code> method, but I cannot seem to pass any objects to it using the <code>.join()</code> method. I chose the <code>.join()</code> method because the <code>.append()</code> doesn't seem to handle object type <code>str</code>. </p> <pre><code>class Bag(object): '''This is where the docstring goes.''' def __init__(self): self.contents = [] def put_in_bag(self, contents): contents.join(contents) def __str__(self): return "The bag has: " + str(self.contents) if __name__ == "__main__": bag1 = Bag() bag1.put_in_bag("comb") bag1.put_in_bag("candy bar") print bag1 </code></pre> <p>I receive the following output:</p> <p><code>The bag has: []</code></p> <p>This is homework for a college course and I am an inexperienced Python programmer. It seems like it should be pretty straight forward, but I am obviously missing something.</p>
2
Oracle APEX Shuttle Refresh to Display Shuttle Right Values in Session State
<p>I'm using Oracle APEX v4.2 with Oracle 11g R2 DB and IE11 browser.</p> <p>I have a shuttle item within my page called <code>P1_MY_SHUTTLE</code> that has some values on the left based on a LOV query, which is all good.</p> <p>What I also have is the ability to let the user enter their value from a separate text field <code>(P1_MY_VALUE)</code> with an "Add" button next to it.</p> <p>So when the user enters their value and presses the "Add" button, I want this value to be added to the shuttle (right side).</p> <p>I have a Dynamic Action click happening with the "Add" button that runs the following <code>PL/SQL</code> code:</p> <pre><code> begin if :P1_MY_VALUE is null then :P1_MY_SHUTTLE := :P1_MY_VALUE; else :P1_MY_SHUTTLE := :P1_MY_SHUTTLE || ':' || :P1_MY_VALUE; end if; end; </code></pre> <p>Now, this all works fine as I have the values in session state but my problem is, I need to show these values within my <code>P1_MY_SHUTTLE</code> to the user each time they press the "Add" button.</p> <p>Unfortunately I can't refresh the shuttle item using a DA Refresh as this doesn't work but if I perform a full page refresh (F5), the results in session are then displayed.</p> <p>How can I show the results without performing a full page refresh? I basically need to show the values in session state after each click of the "Add" button.</p>
2
Mongo db skip-limit work before match after unwind
<p>This is my query:</p> <pre><code>db.getCollection('grades'). aggregate([{ "$match" : { "class_id" : 28, "student_id" : 0 } }, { "$unwind" : "$scores" }, { "$match" : { "scores.type" : "homework" } }, { "$skip" : 3 }, { "$limit" : 3 }, { "$group" : { "_id" : { "id" : "$_id" }, "scores" : { "$push" : "$scores" } } }, { "$project" : { "_id" : "$_id.id", "scores" : 1 } }]) </code></pre> <p><code>scores</code> - is a nested array of objects. <code>Score object</code> - <code>{type: "someType", score: someScore}</code>. This query returns one document. </p> <p>The problem: array of <code>scores</code> has 6 objects and 4 of them have type <code>homework</code>. </p> <blockquote> <p>The result, what I've received: <a href="http://prntscr.com/bq217r" rel="nofollow">http://prntscr.com/bq217r</a> </p> <p>The original document: <a href="http://prntscr.com/bq23bv" rel="nofollow">http://prntscr.com/bq23bv</a></p> </blockquote> <p>Why <code>skip-limit</code> performed before <code>match</code> operator? How can I fix it?</p>
2
How to use GeoDataApi.getPlaceById?
<p><strong>Question</strong>: What is the cleanest way to create a <code>Place</code> object from an ID string?</p> <p>I want make some <code>place</code> objects out of hard-coded ids. Think something like <code>Place place1 = new Place("ChIJS_zBNNbXAhURy-FuRT5ib9k")</code>, but that of-course doesn't work.</p> <p>I came across <code>GeoDataApi.getPlaceById</code>, but the documentation is confusing.</p> <p>That API is usually used for looking up whatever a user inputs (optionally with autocompletion), but I need something smaller and cleaner (think: unit testing purposes)</p> <hr> <p><strong>My research:</strong> <a href="https://developers.google.com/places/android-api/place-details#get-place" rel="nofollow">How to get a Place by ID</a></p> <blockquote> <p>To get a place by ID, call <a href="https://developers.google.com/android/reference/com/google/android/gms/location/places/GeoDataApi.html#public-methods" rel="nofollow"><code>GeoDataApi.getPlaceById</code></a>, passing one or more place IDs.</p> <p>The API returns a <a href="https://developers.google.com/android/reference/com/google/android/gms/location/places/PlaceBuffer" rel="nofollow"><code>PlaceBuffer</code></a> in a <a href="https://developers.google.com/android/reference/com/google/android/gms/common/api/PendingResult" rel="nofollow"><code>PendingResult</code></a>. The <a href="https://developers.google.com/android/reference/com/google/android/gms/location/places/PlaceBuffer" rel="nofollow"><code>PlaceBuffer</code></a> contains a list of <a href="https://developers.google.com/android/reference/com/google/android/gms/location/places/Place" rel="nofollow"><code>Place</code></a> objects that match the supplied place IDs.</p> </blockquote> <p>Documentation:</p> <p><a href="https://developers.google.com/android/reference/com/google/android/gms/location/places/Place" rel="nofollow">Place</a> (the object required)</p> <p><a href="https://developers.google.com/android/reference/com/google/android/gms/location/places/PlaceBuffer" rel="nofollow">PlaceBuffer</a> (convertable to a Place)</p> <p><a href="https://developers.google.com/android/reference/com/google/android/gms/common/api/PendingResult" rel="nofollow">PendingResult</a></p> <p><a href="https://developers.google.com/android/reference/com/google/android/gms/location/places/GeoDataApi.html#public-methods" rel="nofollow">getPlaceById</a> (returns a PendingResult)</p> <hr> <p><strong>What I'm stuck with</strong>: I can't find an elegant way to turn a <code>PendingResult</code> in to a <code>PlaceBuffer</code>.</p> <blockquote> <p>The API returns a <code>PlaceBuffer</code> in a <code>PendingResult</code>.</p> </blockquote> <p>...</p> <blockquote> <p>The final result object from a <code>PendingResult&lt;R&gt;</code> is of type <code>R</code>, which can be retrieved in one of two ways.</p> <ul> <li>via blocking calls to <code>await()</code>, or <code>await(long, TimeUnit)</code>, or</li> <li>via a callback by passing in an object implementing interface <code>ResultCallback</code> to <code>setResultCallback(ResultCallback)</code>.</li> </ul> </blockquote> <p>A callback is too messy, and I can't find any code that uses <code>await</code> to learn from it.</p>
2
Mongodb display nested reference object
<p>I have the below Schema for mongodb (For my mean stack app).</p> <pre><code>var helpSchema = new Schema({ //_id: Number, description: String, summary: String, flows: [{ type: Schema.Types.ObjectId, ref: 'Flow' }] }); var flowSchema = new Schema({ _problem: { type: Number, ref: 'Help' }, name: String, steps: [{ type: Schema.Types.ObjectId, ref: 'Step' }] }); </code></pre> <p>I am inserting to the database as below:</p> <pre><code>var help = new models.Help(); help.description = 'description'; help.summary = 'summary'; var flow = new models.Flow(); flow.name = 'name'; help.flows.push(flow); help.save(function(err) { ... } </code></pre> <p>Value is inserted to db and i am able to query. <strong>db.helps.find();</strong> returns below result</p> <pre><code>{ "_id" : ObjectId("5786520f580cc96c31c90769"), "summary" : "summary", "description" : "description", "flows" : [ ObjectId("5786520f580cc96c31c9076a") ], "__v" : 0 } </code></pre> <p>Now can i query from command line and see the value within the object in flows array? I searched and found that in can query a field within nested object. But can i display this value in command line?</p>
2
Creating user defined function for firebird 2.5 with c++builder 2010
<p>I tried to create a simple user defined function (UDF) for Firebird 2.5 with C++ Builder 2010 but I don't manage to get it to work in Firebird.</p> <ol> <li>Creating a DLL project with default setting in C++ Builder 2010. </li> <li><p>Adding a unit with my example UDF including "ibase.h" and "ib_util.h":</p> <pre class="lang-c prettyprint-override"><code>extern "C" __declspec(dllexport) int __stdcall MYFUNC ( int i ) { int result = 2 * i; return result; } </code></pre></li> <li><p>Building the DLL <code>FBUDFMBD.dll</code> in path <code>C:\Program Files (x86)\Firebird\Firebird_2_5\UDF</code></p></li> <li><p>Registering my UDF via IBExpert in a sample db with </p> <pre class="lang-sql prettyprint-override"><code>DECLARE EXTERNAL FUNCTION F_MYFUNC INTEGER RETURNS INTEGER ENTRY_POINT 'MYFUNC' MODULE_NAME 'FBUDFMBD'; </code></pre></li> <li><p>Calling the UDF with </p> <pre class="lang-sql prettyprint-override"><code>select F_MYFUNC( 3 ) from RDB$DATABASE; </code></pre> <p>results in error message</p> <pre><code>Invalid token. invalid request BLR at offset 36. function F_MYFUNC is not defined. module name or entrypoint could not be found. </code></pre></li> </ol> <p>With the tool <em>GExperts - PE Information</em> I can see my UDF as DLL-Export <code>MYFUNC</code> ordinal <code>$1</code> and entry point <code>$1538</code>.</p> <p>What I am doing wrong, Firebird can't register my DLL and its UDF correctly?</p> <p>Is there anything in my DLL project to change regarding to default compiler options?</p>
2
LINQ - Multiple left joins with nullable values
<p>I'm trying to translate the following SQL query to LINQ, but I get an "Object reference not set to an instance of an object."</p> <p>SQL QUERY</p> <pre><code>SELECT a.ID_TARGET,a.TARGET_NAME, b.OBJECTIVE_NAME, c.PERSPECTIVE_NAME FROM IL_OPR_MTR_TGT AS a LEFT JOIN IL_OPR_MTR_OBJ b ON a.TARGET_OBJECTIVE_ID = b.ID_OBJECTIVE LEFT JOIN IL_OPR_MTR_PRSPCT c ON b.OBJECTIVE_PERSPECT_ID = c.PERSPECTIVE_ID; </code></pre> <p>SQL OUTPUT</p> <pre><code>ID_TARGET |TARGET_NAME |OBJECTIVE_NAME |PERSPECTIVE_NAME ----------|-------------|---------------|---------------- 7 |TGT_01 | TST02 |PERSPECTIVE_01 8 |TGT01 | TST02 |PERSPECTIVE_01 9 |TARGET_02 | TST02 |PERSPECTIVE_01 10 |TARGET003AA | (null) |(null) </code></pre> <p>LINQ QUERY </p> <pre><code>var data = (from a in allTargets join b in allObjectives on a.TARGET_OBJECTIVE_ID equals b.ID_OBJECTIVE into partial1 from b in partial1.DefaultIfEmpty() join c in allPerspectives on b.OBJECTIVE_PERSPECT_ID equals c.PERSPECTIVE_ID into partial2 from c in partial2.DefaultIfEmpty() select new { ID_TARGET = a.ID_TARGET, TARGET_NAME = a.TARGET_NAME, OBJECTIVE_NAME = b != null ? b.OBJECTIVE_NAME : "", PERSPECTIVE_NAME = c != null ? c.PERSPECTIVE_NAME : "" }).ToList(); </code></pre> <p>I guess the problem is here, since i'm trying to join two NULL values, but I cant figure out how to fix that...</p> <pre><code>join c in allPerspectives on b.OBJECTIVE_PERSPECT_ID equals c.PERSPECTIVE_ID into partial2 from c in partial2.DefaultIfEmpty() </code></pre>
2
How to MySQL Between used for Higher value to Lower value?
<p>Here I mentioned query:</p> <p>lowerValue = 3, upperValue = 6</p> <pre><code>SELECT * FROM SampleTable where tableDay BETWEEN 'lowerValue' AND 'upperValue'; </code></pre> <p>This query is working fine, but I need given below query type</p> <p>lowerValue = 3, upperValue = 6</p> <pre><code>SELECT * FROM SampleTable where tableDay BETWEEN 'upperValue' AND 'lowerValue'; </code></pre> <p>It's return as empty list, because both values are dynamic, what I'm doing wrong?</p>
2
Julia : random normal distribution
<p>l want to generate random normal distribution between 0.1 and 0.3 using randn() how can l use it ?</p> <p>l tried this one but it's not working</p> <p>randn(0.1:0.3,(3,1)) # (3,1) three lines and one column</p>
2
Git: list all least recently changed files
<p>I have a large git repository and I would like to find the list of files that were not modified for the long time sorted by date, I tried the command:</p> <pre><code>git log --pretty=format: --summary --before="&lt;date&gt;" </code></pre> <p>It gives me the list of files modified files before <code>date</code>, but I would like to know all files sorted by date of last modification in descending order (the oldest files will be on top). Also the list should have only files currently present in the repository, I don't care about already deleted files.</p> <p>Can anyone suggest the right command? </p>
2
Custom index comparator in MongoDB
<p>I'm working with a dataset composed by probabilistic encrypted elements indistinguishable from random samples. This way, sequential encryptions of the same number results in different ciphertexts. However, these still comparable through a special function that applies algorithms like SHA256 to compare two ciphertexts. </p> <p>I want to add a list of the described ciphertexts to a MongoDB database and index it using a tree-based structure (i.e.: AVL). I can't simply apply the default indexing of the database because, as described, the records must be comparable using the special function. </p> <p>An example: Suppose I have a database <strong>db</strong> and a collection <strong>c</strong> composed by the following document type:</p> <pre><code>{ "_id":ObjectId, "r":string } </code></pre> <p>Moreover, let F(int,string,string) be the following function:</p> <pre><code>F(h,l,r) = ( SHA256(l | r) + h ) % 3 </code></pre> <p>where the operator | is a standard concatenation function.</p> <p>I want to execute the following query <strong>in an efficient way</strong>, such as in a collection with some suitable indexing: </p> <pre><code>db.c.find( { F(h,l,r) :{ $eq: 0 } } ) </code></pre> <p>for h and l chosen arbitrarily but not constants. I.e.: Suppose I want to find all records that satisfy F(h1,l1,r), for some pair (h1, l1). Later, in another moment, I want to do the same but using (h2, l2) such that h1 != h2 and l1 != l2. h and l may assume any value in the set of integers.</p> <p>How can I do that? </p>
2
Signal async completion with Gulp, Babel and config.yml
<p>Current project handle babel and gulp for task and load a yml config file for paths.</p> <p>This is the <code>cofing.yml</code>:</p> <pre><code>PATHS: # Path to source folder sources: "jet/static/jet_src" # Path to dist folder dist: "jet/static/jet" # Paths to static assets that aren't images, CSS, or JavaScript assets: - "jet/static/jet_src/**/*" - "!jet/static/jet_src/{img,js,scss,fonts}/**/*" # Paths to fonts folder fonts: - "jet/static/jet_src/fonts/**/*" - "node_modules/font-awesome/fonts/**/*" # Paths to Sass libraries, which can then be loaded with @import sass: - "jet/static/jet_src/scss" - "jet/static/jet_src/scss/select2" - "node_modules/font-awesome/scss/" - "node_modules/select2/src/scss/" - "node_modules/perfect-scrollbar/src/scss/" # Paths to JavaScript libraries, which are compined into one file javascript: - "jet/static/jet_src/js/!(main).js" - "jet/static/jet_src/js/main.js" - "jet/static/jet_src/js/!(select2.jet).js" - "jet/static/jet_src/js/select2.jet.js" libraries: - "node_modules/jquery/dist/jquery.js" # - "node_modules/jquery-ui/jquery-ui.js" - "node_modules/select2/dist/js/select2.full.js" - "node_modules/perfect-scrollbar/dist/js/perfect-scrollbar.js" - "node_modules/perfect-scrollbar/dist/js/perfect-scrollbar.jquery.js" - "node_modules/js-cookie/src/js.cookie.js" </code></pre> <p>This is the <code>gulpfile.babel.js</code>:</p> <pre><code>'use strict'; import plugins from 'gulp-load-plugins'; import yargs from 'yargs'; import browser from 'browser-sync'; import merge from 'merge-stream'; import gulp from 'gulp'; // import panini from 'panini'; import rimraf from 'rimraf'; // import sherpa from 'style-sherpa'; import yaml from 'js-yaml'; import fs from 'fs'; import path from 'path'; // Themes path const themesPath = "jet/static/jet_src/scss/themes/"; // Load all Gulp plugins into one variable const $ = plugins(); // Check for --production flag const PRODUCTION = !!(yargs.argv.production); // Load settings from settings.yml const {COMPATIBILITY, PORT, UNCSS_OPTIONS, PATHS} = loadConfig(); function loadConfig() { let ymlFile = fs.readFileSync('config.yml', 'utf8'); return yaml.load(ymlFile); } function getFolders(dir) { return fs.readdirSync(dir) .filter(function (file) { return fs.statSync(path.join(dir, file)).isDirectory(); }); } // Build the "dist" folder by running all of the below tasks gulp.task('build', gulp.series(clean, gulp.parallel(sass, javascript, images, fonts))); // Build the site, run the server, and watch for file changes gulp.task('default', gulp.series('build', server, watch)); // Delete the "dist" folder // This happens every time a build starts function clean(done) { rimraf(PATHS.dist, done); } // Compile Sass into CSS // In production, the CSS is compressed function sass() { var folders = getFolders(themesPath); return folders.map(folder =&gt; { gulp.src(path.join(themesPath, folder, '/**/*.scss')) .pipe($.sourcemaps.init()) .pipe($.sass({ includePaths: PATHS.sass }) .on('error', $.sass.logError)) .pipe($.autoprefixer({ browsers: COMPATIBILITY })) // Comment in the pipe below to run UnCSS in production .pipe($.if(PRODUCTION, $.uncss(UNCSS_OPTIONS))) .pipe($.if(PRODUCTION, $.cssnano())) .pipe($.if(!PRODUCTION, $.sourcemaps.write())) .pipe(gulp.dest(PATHS.dist + '/css/themes/' + folder)) .pipe(browser.reload({stream: true})); }); } // Combine JavaScript into one file // In production, the file is minified function javascript() { var js = gulp.src(PATHS.javascript) .pipe($.sourcemaps.init()) .pipe($.babel()) .pipe($.concat('main.js')) .pipe($.if(PRODUCTION, $.uglify() .on('error', e =&gt; { console.log(e); }) )) .pipe($.if(!PRODUCTION, $.sourcemaps.write())) .pipe(gulp.dest(PATHS.dist + '/js')); var libs = gulp.src(PATHS.libraries) .pipe($.sourcemaps.init()) .pipe($.babel()) .pipe($.concat('libraries.js')) .pipe($.if(PRODUCTION, $.uglify() .on('error', e =&gt; { console.log(e); }) )) .pipe($.if(!PRODUCTION, $.sourcemaps.write())) .pipe(gulp.dest(PATHS.dist + '/js')); return merge(js, libs); } // Copy images to the "dist" folder // In production, the images are compressed function images() { return gulp.src(PATHS.sources + '/img/**/*') .pipe($.if(PRODUCTION, $.imagemin({ progressive: true }))) .pipe(gulp.dest(PATHS.dist + '/img')); } // Copy fonts to the "dist" folder function fonts() { return gulp.src(PATHS.fonts) .pipe(gulp.dest(PATHS.dist + '/fonts')); } // Start a server with BrowserSync to preview the site in function server(done) { browser.init({ server: PATHS.dist, port: PORT }); done(); } // Reload the browser with BrowserSync function reload(done) { browser.reload(); done(); } // Watch for changes to static assets, Sass, and JavaScript function watch() { gulp.watch(PATHS.sources + '/scss/**/*.scss', sass); gulp.watch(PATHS.sources + '/js/**/*.js').on('change', gulp.series(javascript, browser.reload)); gulp.watch(PATHS.sources + '/img/**/*').on('change', gulp.series(images, browser.reload)); gulp.watch(PATHS.sources + '/fonts/**/*').on('change', gulp.series(fonts, browser.reload)); } </code></pre> <p>In single view this files haven't problems, but, when exute <code>gulp</code> command i have the next error in console:</p> <pre><code>npm start  ✓  1949  10:49:29 &gt; [email protected] start /Users/jose/Proyectos/django-jetpack &gt; gulp [10:49:35] Requiring external module babel-register [10:49:40] Using gulpfile ~/Proyectos/django-jetpack/gulpfile.babel.js [10:49:40] Starting 'default'... [10:49:40] Starting 'build'... [10:49:40] Starting 'clean'... [10:49:40] Finished 'clean' after 3.23 ms [10:49:40] Starting 'sass'... [10:49:40] Starting 'javascript'... [10:49:40] Starting 'images'... [10:49:40] Starting 'fonts'... [10:49:46] Finished 'images' after 5.91 s [BABEL] Note: The code generator has deoptimised the styling of "/Users/jose/Proyectos/django-jetpack/node_modules/jquery/dist/jquery.js" as it exceeds the max of "100KB". [BABEL] Note: The code generator has deoptimised the styling of "/Users/jose/Proyectos/django-jetpack/node_modules/select2/dist/js/select2.full.js" as it exceeds the max of "100KB". [10:49:57] Finished 'javascript' after 16 s [10:49:57] Finished 'fonts' after 16 s [10:49:57] The following tasks did not complete: default, build, &lt;parallel&gt;, sass [10:49:57] Did you forget to signal async completion? </code></pre> <p>The <code>npm</code>installed packages are:</p> <pre><code>"devDependencies": { "babel-preset-es2015": "^6.9.0", "babel-preset-react": "^6.5.0", "babel-register": "^6.9.0", "browser-sync": "^2.13.0", "font-awesome": "^4.6.3", "gulp": "github:gulpjs/gulp#4.0", "gulp-autoprefixer": "^3.1.0", "gulp-babel": "^6.1.2", "gulp-cli": "^1.2.1", "gulp-concat": "^2.6.0", "gulp-cssnano": "^2.1.2", "gulp-extname": "^0.2.2", "gulp-if": "^2.0.1", "gulp-imagemin": "^3.0.1", "gulp-load-plugins": "^1.2.4", "gulp-sass": "^2.3.2", "gulp-sourcemaps": "^1.6.0", "gulp-uglify": "^1.5.3", "gulp-uncss": "^1.0.5", "jquery": "^3.0.0", "js-cookie": "^2.1.2", "js-yaml": "^3.6.1", "merge-stream": "^1.0.0", "node-sass": "^3.8.0", "perfect-scrollbar": "^0.6.11", "rimraf": "^2.5.2", "select2": "^4.0.3", "susy": "^2.2.12", "yargs": "^4.7.1" } </code></pre> <p>This setting was taked from <a href="https://github.com/zurb/foundation-zurb-template" rel="nofollow">Zurb Foundation Template</a> and it works fine, so, we think that have to works fine, but isn't.</p> <p>I don't understand why i have this problem because all task are in <code>series</code> function, <code>sass</code>task works fine, compile all scss files, <code>javascript</code>task join all js scripts in <code>main.js</code>and <code>libraries.js</code>files, so, i think that this task are good defined, but, what happen with the other task?</p>
2
How to show more details in `seaborn.kdeplot()`?
<p>I have a scatter plot on the left-hand side below, where there are lots of data points, and the figure on the right are corresponding density plot using <code>seaborn.kdeplot()</code>. But unfortunately since the variance of the density is so large that <code>kdeplot</code> fails to capture many details in other low-density area (e.g. there is basically no information about the density distribution on the top right). </p> <p>Does anyone have any ways to fix this issue?</p> <p>Thanks!</p> <p><a href="https://i.stack.imgur.com/vAydj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vAydj.png" alt="enter image description here"></a></p>
2
How to scrape multiple pages of search results using R
<p>I'd like to scrape a website which lists all the qualifications in South Africa (<a href="http://allqs.saqa.org.za/search.php" rel="nofollow">http://allqs.saqa.org.za/search.php</a>)</p> <p>When you first go to the link you will note that its a page with search criteria. I want to scrape all the results so I don't enter anything in the search criteria - just click "GO" which then returns the search results which I want to scrape. The results are displayed for 20 records and there are 16521 pages of results. At this stage the URL is still as above.</p> <p>Is it possible to scrape these results? From the online searching I've been doing I've found solutions to where you the page results search criteria are defined in the URL. However for the site I want to scrape this is not option</p> <p>Ideally I'd like to use R to do the scraping, however I'm open to other suggestions if its not possible in R</p> <p>Many thanks Ria</p>
2
Model persistence in Scikit-Learn?
<p>I am trying to save and load scikit-learn model but facing issues when the save and load are happening on different python versions. Here what I have tried:</p> <ol> <li><p>Using pickle to save a model in python3 and deserialize in python2.This works for some of the models like LR,SVM but it fails for KNN.</p> <pre><code>&gt;&gt;&gt; pickle.load(open("inPy3.pkl", 'rb')) #KNN model ValueError: non-string names in Numpy dtype unpickling </code></pre></li> <li><p>Also , I tried to serialize and deserialize in json using jsonpickle but getting the following error.</p> <pre><code>data = jsonpickle.encode(lr) #lr = logisticRegression Model jsonpickle.decode(data) AttributeError: 'dict' object has no attribute '__name__' </code></pre></li> </ol> <p>Also, I want to know if there is some utility which I can use to serialize and deserialize scikit-learn model objects to human readable format (json,xml,protobuf etc).</p>
2
Why is dynamic real time not recommended as per asterisk?
<p>In extconfig.conf they have mentioned that </p> <pre><code> "However, note that using dynamic realtime extensions is not recommended anymore as a best practice; instead, you should consider writing a static dialplan with proper data abstraction via a tool like func_odbc." </code></pre> <p>1) Why asterisk is not recommending dynamic realtime extensions? 2) How to do static dialplan with data abstraction using tool liek func_odbc?</p> <p>My requirement is having have more extensions (in this case mobile number) coming up, how can I dynamically add them to sip.conf and get it registered to the SIP server</p>
2
How to check if UDP packet received in C Linux
<p>"recvfrom()" in below sample code waits until UDP packet is received. </p> <p>But I need to check whether UDP packet is available or not. If packet is not received, then continue other tasks. If packet is received, then receive packet and parsing. How can I do this in Linux c program? Please help!</p> <pre><code>for (;;) { printf("waiting on port %d\n", SERVICE_PORT); recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&amp;remaddr, &amp;addrlen); printf("received %d bytes\n", recvlen); if (recvlen &gt; 0) { buf[recvlen] = 0; printf("received message: \"%s\"\n", buf); } } </code></pre>
2
Test-Path returns exception when testing if location exists
<p>I am trying to check if a location exists before copying it, using <code>Test-Path</code>. As I understand it this should return true or false, depending on if the location exists.</p> <p>My code</p> <pre><code>if (Test-Path $updatedsource) { Copy-Item $updatedsource $record.Target -Recurse -Container -Force } </code></pre> <p>Instead of true or false, this line is throwing an exception</p> <pre>Test-Path : An object at the specified path \\wnasdce03\SECENV_PROD-01\Users\Results\thorn-01.00rc3\ICEVol_BC_20160715 does not exist At \\VFIPPFIL005\EMT_Projects\Vimmi\SE\CoypHistoryData.ps1:31 char 22 + if (Test-Path &lt;&lt;&lt;&lt; $updatedsource) { + CategoryInfo: ObjectNotFound: (\\wnasdce03\SEC...tC_20160716:String) [Test-Path1. IOException + FullyQualifiedErrorId : ItemDoesNotExist.Microsoft.Powershell.Commands.TestPathCommand</pre> <p>Why am I getting an exception that the location doesn't exist? Surely this should just return false?</p>
2
how to count items/boolean after if-statements (python)
<p>I have a csv where I need to count the total number for each category: </p> <pre><code>New_Cell[2] Category I need to count 1 [A01] 1 [A01] 0 [A01] 1 [A01] 0 [A02] 1 [A02] 1 [A02] 2 [A02] 1 [A02] </code></pre> <p>I need it to count each occurrence of TRUE for the if-condition so that it will look like:</p> <pre><code>[A01] : 3 </code></pre> <p>instead of:</p> <pre><code> 1 1 1 </code></pre> <p>I currently have: </p> <pre><code>A01 = "[A01] Officials" data_out = open("mentees_all_attributes.csv", "rU") reader = csv.reader(data_out) next(reader,None) for line in reader: cells = line new_cell = cells[0], cells[6], cells[7], cells[8], cells[9], cells[10] # name, # of participation, primary occupation/industry, secondary occupation/industry if int(new_cell[1]) &gt; 0: #Isolate all the participants with more than 0 primary = new_cell[2] if primary == A01: if True: counts =+ 1 print counts data_out.close() </code></pre>
2
gulp-replace if content of files match regex
<p>I have a folder of HTML files that contain a comment at the top with metadata. I would like to run one <code>gulp-replace</code> operation if the metadata matches one regex, and another <code>gulp-replace</code> operation if it doesn't match, then continue on with the rest of the tasks pipeline. If tried various iterations using <code>gulp-if</code> but it always results in "TypeError: undefined is not a function" errors</p> <pre><code>import gulp from 'gulp'; import plugins from 'gulp-load-plugins'; const $ = plugins(); function preprocess() { var template_data = new RegExp('&lt;!-- template_language:(\\w+)? --&gt;\n', 'i'); var handlebars = new RegExp('&lt;!-- template_language:handlebars --&gt;', 'i'); var primaryColor = new RegExp('#dc002d', 'gi'); var mailchimpColorTag = '*|PRIMARY_COLOR|*'; var handlebarsColorTag = '{{PRIMARY_COLOR}}'; var replaceCondition = function (file) { return file.contents.toString().match(handlebars); } return gulp.src('dist/**/*.html') .pipe($.if( replaceCondition, $.replace(primaryColor, handlebarsColorTag), $.replace(primaryColor, mailchimpColorTag) )) .pipe($.replace, template_data, '') .pipe(gulp.dest('dist')); } </code></pre> <p>What's the most efficient way to go about this?</p>
2
WordPress: Move inline JS to be fired after deffered jQuery
<p>Trying to follow Google Page Insights suggestions, I've got the "JS render block" recommendation for and it is related to <code>jQuery</code> main file.</p> <p>My site use WordPress with some plugins. One of the plugins throw its JS inline. So when I move <code>jQuery</code> to load in the footer, or when I use "defer" mode to load it, I get <code>jQuery is not defined</code> once the inline code fired.</p> <p>I was trying to find a global solution to 'catch' all inline scripts and delay it after <code>jQuery</code> main file is executed at the end of the document.</p> <p>I wrote a solution that works great for me. It is very straight forward solution for my specific situation, but I failed to make this as a filter for <code>the_content</code> or widget output. I would like to make this a global solution, so I wouldn't need to worry about any JS firing somewhere.</p> <p>Any ideas how to make it work? Here my code so far, for this specific case, which runs through a shortcode:</p> <pre><code>/* Get shortcode HTML */ $widget_shortcode = do_shortcode($shortcode); /* Take out all scripts into an array */ $delayed_scripts = array(); preg_match_all('#&lt;script(.*?)&lt;/script&gt;#is', $widget_shortcode, $match); foreach ($match as $val){ $delayed_script = '&lt;script '.$val[0].'&lt;/script&gt;'; array_push($delayed_scripts, $delayed_script); } /* Remove all scripts from HTML */ $widget_shortcode = preg_replace('#&lt;script(.*?)&lt;/script&gt;#is', '', $widget_shortcode); /* Echo filtered HTML */ echo $widget_shortcode; </code></pre> <p>And just before the closing <code>&lt;/body&gt;</code> tag:</p> <pre><code>foreach ($delayed_scripts as $script) { echo $delayed_script; } </code></pre>
2
DataBinding: 'System.Data.DataRowView' does not contain a property with the name but all setting seems proper
<p>I have this major problem in my site. Hence I checked all my codes place in side many times but it seems all fine. </p> <p>E.g. on <a href="http://healthsaviour.com/chemists" rel="nofollow">this page</a> it shows this error</p> <pre><code>DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'chemistID'. </code></pre> <p>I checked my table column name which is same. Also inside code I checked column name is correct. I checked in side Listview code &amp; it was correct. Still it's showing error. Following is my ListView &amp; data binding codes.</p> <pre><code>&lt;asp:ListView ID="chemists" runat="server" DataKeyNames="chemistID" DataKey="chemistID"&gt; &lt;ItemTemplate&gt; &lt;!--list-content-blocks-starts--&gt;&lt;div class="list-content-blocks"&gt; &lt;!--list-data-starts--&gt;&lt;div class="list-data"&gt; &lt;!--head-title-starts--&gt;&lt;div class="head-title"&gt; &lt;h3&gt;&lt;asp:HyperLink ID="name" runat="server" NavigateUrl='&lt;%# "chemist-details?chemistID=" + Eval("chemistID").ToString() %&gt;' Text='&lt;%# Eval("name") %&gt;'&gt;HyperLink&lt;/asp:HyperLink&gt;&lt;/h3&gt; &lt;div class="list-address"&gt; &lt;asp:Label ID="address" runat="server" Text='&lt;%# Eval("address") %&gt;'&gt;&lt;/asp:Label&gt; &lt;%--&lt;asp:Label ID="street" runat="server" Text= '&lt;%# Eval("streetName") %&gt;'&gt;&lt;/asp:Label&gt;, &lt;asp:Label ID="area" runat="server" Text= '&lt;%# Eval("areaName") %&gt;'&gt;&lt;/asp:Label&gt;, &lt;asp:Label ID="city" runat="server" Text= '&lt;%# Eval("city") %&gt;'&gt;&lt;/asp:Label&gt;, &lt;asp:Label ID="zip" runat="server" Text= '&lt;%# Eval("zipCode") %&gt;'&gt;&lt;/asp:Label&gt;.--%&gt; &lt;/div&gt; &lt;/div&gt;&lt;!--head-title-ends--&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;!--content-in-starts--&gt;&lt;div class="content-in"&gt; &lt;!--contenr-dp-starts--&gt;&lt;div class="content-dp"&gt; &lt;img id="thumbnail" runat="server" src='&lt;%# Eval("thumbnail") %&gt;' /&gt; &lt;/div&gt;&lt;!--content-dp-ends--&gt; &lt;!--content-other-details-starts--&gt;&lt;div class="content-other-details"&gt; &lt;section class="known-for"&gt; &lt;ul class="bestFor"&gt; &lt;asp:Label ID="knownFor" runat="server" Text='&lt;%# Eval("products")%&gt;'&gt;&lt;/asp:Label&gt; &lt;li class="showMore"&gt;&lt;asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='&lt;%# "chemist-details?chemistID=" + Eval("chemistID").ToString() %&gt;' Text="More"&gt;&lt;/asp:HyperLink&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/section&gt; &lt;!--list-time-starts--&gt;&lt;div class="list-time"&gt; &lt;div class="list-time-inner"&gt;WORKING HOURS &amp;nbsp;&amp;nbsp;|&amp;nbsp;&amp;nbsp; &lt;asp:Label ID="opdFrom" runat="server" Text='&lt;%# Eval("slot1From") %&gt;'&gt;&lt;/asp:Label&gt; To &lt;asp:Label ID="opdTo" runat="server" Text='&lt;%# Eval("slot1To") %&gt;'&gt;&lt;/asp:Label&gt;&lt;/div&gt; &lt;/div&gt;&lt;!--list-time-ends--&gt; &lt;%-- &lt;!--list-time-starts--&gt;&lt;div class="feesC"&gt; &lt;div class="fees-inner"&gt;&lt;asp:Label ID="consulting" runat="server" Text='&lt;%# Eval("consultancyFees") %&gt;'&gt;&lt;/asp:Label&gt; / Doctor&lt;/div&gt; &lt;/div&gt;&lt;!--list-time-ends--&gt;--%&gt; &lt;!--sms-button-starts--&gt;&lt;div class="sms-button"&gt; &lt;asp:Button ID="getSMS" CssClass="get-sms" runat="server" Text="Get SMS" /&gt; &lt;/div&gt;&lt;!--sms-button-ends--&gt; &lt;/div&gt;&lt;!--content-other-details-ends--&gt; &lt;/div&gt;&lt;!--content-in-ends--&gt; &lt;/div&gt;&lt;!--list-data-ends--&gt; &lt;!--rating-show-starts--&gt;&lt;div class="rating-show"&gt; &lt;div class="rating-show-inner"&gt; &lt;div class="show-rating vote1"&gt;&lt;asp:Label ID="lblRating" runat="server"&gt;&lt;/asp:Label&gt;&lt;/div&gt; &lt;div class="show-votes"&gt;&lt;asp:label ID="totalVotes" runat="server"&gt;&lt;/asp:label&gt; &lt;asp:Label ID="seeVote" runat="server" Text="Vote"&gt;&lt;/asp:Label&gt;&lt;/div&gt; &lt;/div&gt; &lt;%--&lt;div class="rating-show-inner"&gt; &lt;div class="show-rating rank1"&gt;&lt;span&gt;8&lt;/span&gt;&lt;/div&gt; &lt;div class="show-votes"&gt;in Pune&lt;/div&gt; &lt;/div&gt;--%&gt; &lt;/div&gt;&lt;!--rating-show-ends--&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt;&lt;!--list-content-blocks-ends--&gt; &lt;/ItemTemplate&gt; &lt;EmptyDataTemplate&gt; &lt;div class="not-found"&gt; &lt;p&gt;Sorry! Selected Query Not Found&lt;/p&gt; &lt;center&gt;&lt;img src="images/not-found.jpg"&lt;/center&gt; &lt;/div&gt; &lt;/EmptyDataTemplate&gt; &lt;LayoutTemplate&gt; &lt;ul id="itemPlaceholderContainer" runat="server" style=""&gt; &lt;li runat="server" id="itemPlaceholder" /&gt; &lt;/ul&gt; &lt;/LayoutTemplate&gt; &lt;/asp:ListView&gt; &lt;div class="datapager" style="padding-bottom: 10px;"&gt; &lt;asp:DataPager ID="DataPager1" runat="server" PageSize="10" PagedControlID="chemists" ViewStateMode="Enabled"&gt; &lt;Fields&gt; &lt;asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="false" ShowPreviousPageButton="true" ShowNextPageButton="false" /&gt; &lt;asp:NumericPagerField ButtonType="Link" /&gt; &lt;asp:NextPreviousPagerField ButtonType="Link" ShowNextPageButton="true" ShowLastPageButton="false" ShowPreviousPageButton="false" /&gt; &lt;/Fields&gt; &lt;/asp:DataPager&gt; &lt;/div&gt; </code></pre> <p>DataBind code</p> <pre><code> Private Sub chemists_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender chemists.DataSource = GetData() chemists.DataBind() End Sub Private Function GetData() As Data.DataTable Try If Session("Data") IsNot Nothing Then Return Session("Data") Else DataPager1.SetPageProperties(0, DataPager1.PageSize, False) 'reinit Dim citySelector As Label = Page.Master.FindControl("locationPopupActivator") Using con As New MySql.Data.MySqlClient.MySqlConnection(ConfigurationManager.ConnectionStrings("conio").ConnectionString) Dim cmd As New MySql.Data.MySqlClient.MySqlCommand("SELECT chemistID, name, address, thumbnail, slot1From, slot1To, products FROM chemists where city like @city and status = 'active'", con) cmd.CommandType = Data.CommandType.Text cmd.Parameters.Add("@city", MySqlDbType.VarChar, 50).Value = citySelector.Text &amp; "%" 'same as Session("masterLocation") Dim table As New Data.DataTable() Dim da As New MySql.Data.MySqlClient.MySqlDataAdapter(cmd) da.Fill(table) countItems.Text = table.Rows.Count().ToString da.Dispose() cmd.Dispose() Session("Data") = table Return table End Using End If Catch ex As Exception Response.Write(ex) 'for debug purpose Return Nothing End Try End Function </code></pre>
2
adjusting tableView height while using self sizing cells and a non scrollable table
<p>The problem I have is that I am using self-sizing cells, and estimated row height. </p> <p>My tableview is a non scrollable table in a scrollview. I have a variable for the table height which I initially set to 0. </p> <p>I am trying to update my tables height to be the right size depending on how many cells will fill it and depending on the size those cells will take up. I am trying to use <code>tableview.contentSize.height</code> to get the tables height and set the variable to that size. </p> <p>I then recall my alignment function to reset the tables height. When I build and run the tables size isn't big enough to show all of the cells that it should. </p> <p>How can I fix this?</p>
2
RabbitMQ crashes
<p>My rabbitmq instance crashed with the following reason. I know nothing about Erlang so I cannot fully understand the stacktrace. I checked Mnesia's documentation. It seems that my rabbitmq crashed because some Mnesia transaction got aborted, and abort reason is rabbit_runtime_parameters and cluster_name missing? But what caused it?</p> <pre><code>=SUPERVISOR REPORT==== 9-Jun-2016::17:20:34 === Supervisor: {&lt;0.5605.7&gt;,rabbit_connection_sup} Context: child_terminated Reason: {aborted,{no_exists,[rabbit_runtime_parameters, cluster_name]}} Offender: [{pid,&lt;0.5607.7&gt;}, {name,reader}, {mfargs,{rabbit_reader,start_link,[&lt;0.5606.7&gt;]}}, {restart_type,intrinsic}, {shutdown,4294967295}, {child_type,worker}] =SUPERVISOR REPORT==== 9-Jun-2016::17:20:34 === Supervisor: {&lt;0.5605.7&gt;,rabbit_connection_sup} Context: shutdown Reason: reached_max_restart_intensity Offender: [ {pid,&lt;0.5607.7&gt;} , {name,reader}, {mfargs,{rabbit_reader,start_link,[&lt;0.5606.7&gt;]}}, {restart_type,intrinsic}, {shutdown,4294967295}, {child_type,worker}] Error in log handler ==================== Event: {info_msg,&lt;0.83.0&gt;, {&lt;0.5610.7&gt;,"accepting AMQP connection ~p (~s)~n", [&lt;0.5610.7&gt;,&lt;&lt;"192.168.100.69:44519 -&gt; 172.17.0.6:5672"&gt;&gt;]}} Error: badarg Stack trace: [{ets,lookup, [rabbit_exchange, {resource,&lt;&lt;"/"&gt;&gt;,exchange,&lt;&lt;"amq.rabbitmq.log"&gt;&gt;}], []}, {rabbit_misc,dirty_read,1,[]}, {rabbit_basic,publish,1,[]}, {rabbit_error_logger,publish1,4,[]}, {rabbit_error_logger,handle_event0,2,[]}, {rabbit_error_logger_file_h,safe_handle_event,3,[]}, {gen_event,server_update,4,[{file,"gen_event.erl"},{line,538}]}, {gen_event,server_notify,4,[{file,"gen_event.erl"},{line,520}]}] =INFO REPORT==== 9-Jun-2016::17:20:39 === accepting AMQP connection &lt;0.5610.7&gt; (192.168.100.69:44519 -&gt; 172.17.0.6:5672) =CRASH REPORT==== 9-Jun-2016::17:20:39 === crasher: initial call: rabbit_reader:init/2 pid: &lt;0.5610.7&gt; registered_name: [] exception exit: {aborted, {no_exists,[rabbit_runtime_parameters,cluster_name]}} in function mnesia:abort/1 (mnesia.erl, line 313) in call from rabbit_runtime_parameters:lookup0/2 in call from rabbit_runtime_parameters:value0/2 in call from rabbit_reader:server_properties/1 in call from rabbit_reader:start_connection/3 in call from rabbit_reader:handle_input/3 in call from rabbit_reader:recvloop/4 in call from rabbit_reader:run/1 ancestors: [&lt;0.5608.7&gt;,rabbit_tcp_client_sup,rabbit_sup,&lt;0.84.0&gt;] messages: [{'EXIT',#Port&lt;0.225508&gt;,normal}] links: [&lt;0.5608.7&gt;] dictionary: [{process_name, {rabbit_reader, &lt;&lt;"192.168.100.69:44519 -&gt; 172.17.0.6:5672"&gt;&gt;}}] trap_exit: true status: running heap_size: 610 stack_size: 27 reductions: 1175 neighbours: </code></pre>
2
Reducing CPU usage of navigator.webkitGetUserMedia (Electron: DesktopCapturer)
<p>I'm using <code>navigator.webkitGetUserMedia</code> to capture screenshot of a window once every second by assigning the returned <code>stream</code> to a <code>&lt;video&gt;</code> and copying it to a <code>&lt;canvas&gt;</code> and saving the Buffer to file.</p> <p>The CPU usage in my application is consistently high and I've pinpointed it to this area.</p> <h1>Code</h1> <pre><code>// Initialize the video, canvas, and ctx var localStream, _video = document.querySelector('#video'), _canvas = document.querySelector('#canvas'), _ctx = _canvas.getContext('2d'), sourceName = 'my-window-id'; // Load the stream from navigator.webkitGetUserMedia navigator.webkitGetUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: sourceName, minWidth: 1920, maxWidth: 1920, minHeight: 1080, maxHeight: 1080 } } }, gotStream, getUserMediaError); function gotStream(stream) { // Use the stream in our &lt;video&gt; _video.src = window.URL.createObjectURL(stream); // Reference the stream locally localStream = stream; } function captureState() { var buffer, dataURL; // Draw &lt;video&gt; to &lt;canvas&gt; and convert to buffer (image data) _ctx.drawImage(_video, 0, 0); dataURL = _canvas.toDataURL('image/png'); buffer = new Buffer(dataURL.split(&quot;,&quot;)[1], 'base64'); // Create an image from the data fs.writeFileSync('screenshot.png', buffer); } // Capture state every second setInterval(function() { captureState(); }, 1000); </code></pre> <p>This code my not run, it's a simplified version of what I have in my code to make it StackOverflow readable.</p> <h1>Things I've Tried</h1> <ol> <li><code>_video.pause()</code> and <code>_video.play()</code> when needed. Didn't seem to change CPU usage.</li> <li><code>_video.stop()</code>. This means I would have to get the stream again which causes a spike in CPU usage worse than keeping it open.</li> </ol> <p>My best lead right now is to change the frame rate by adding:</p> <pre><code> optional: [ { minFrameRate: 1 }, { frameRate: 1 } ] </code></pre> <p>Extremely low frame rate would be fine. However, I haven't been able to determine if the <code>frameRate</code> setting works in this case. <a href="https://developer.mozilla.org/en/docs/Web/API/Navigator/getUserMedia" rel="nofollow noreferrer">The docs</a> don't have it listed and I don't have the newer <code>mediaDevices.getUserMedia</code> available.</p> <p>Is it possible to set extremely low frame rates (or any at all) for <code>navigator.webkitGetUserMedia</code>?</p> <p>Has anyone been able to reduce CPU usage of the stream in any other way?</p> <p>Any alternative methods of achieving the same goal (state capture on interval) would also be helpful.</p> <p>Thanks!</p> <p><strong>Side Note</strong></p> <p>This is in an Electron app on Windows using <a href="https://github.com/electron/electron/blob/master/docs/api/desktop-capturer.md" rel="nofollow noreferrer">DesktopCapturer</a> to get the <code>chromeMediaSourceId</code>.</p> <hr /> <p><strong>Update on CPU Usage</strong></p> <ol> <li>Cost of running <code>stream</code>: 6% CPU Usage</li> <li>Calling <code>captureState</code> every 1000ms: 5% CPU Usage</li> </ol> <p>Total Current: 11%</p> <p>Currently working on reducing #2 based on the recommendations of Csaba Toth so far. I should be able to reduce <code>captureState</code> by changing how the canvas is captured. Will update when that's done.</p> <p>For #1, if I can't avoid capturing the video stream I'll have to just try to cap the total CPU usage at just over 6% by optimizing #2.</p>
2
gstreamer and QML: Drawing on a QML Window
<p>I have been trying to draw a gstreamer camera output onto a QML object for months now. At least on my ARM system none of the qt-gstreamer qml components really worked with the camera output (I can show the test video source) but never anything from the camera.</p> <p>So, I went to the old school of rendering onto a regular qt window with the following example:</p> <pre><code>#include &lt;glib.h&gt; #include &lt;gst/gst.h&gt; #include &lt;gst/video/videooverlay.h&gt; #include &lt;QApplication&gt; #include &lt;QTimer&gt; #include &lt;QWidget&gt; int main(int argc, char *argv[]) { if (!g_thread_supported ()) g_thread_init (NULL); gst_init (&amp;argc, &amp;argv); QApplication app(argc, argv); app.connect(&amp;app, SIGNAL(lastWindowClosed()), &amp;app, SLOT(quit ())); // prepare the pipeline GstElement *pipeline = gst_pipeline_new ("xvoverlay"); GstElement *src = gst_element_factory_make ("v4l2src", NULL); GstElement *sink = gst_element_factory_make ("xvimagesink", NULL); gst_bin_add_many (GST_BIN (pipeline), src, sink, NULL); gst_element_link (src, sink); // prepare the ui QWidget window; window.resize(320, 240); window.show(); WId xwinid = window.winId(); gst_video_overlay_set_window_handle (GST_VIDEO_OVERLAY (sink), xwinid); // run the pipeline GstStateChangeReturn sret = gst_element_set_state (pipeline, GST_STATE_PLAYING); if (sret == GST_STATE_CHANGE_FAILURE) { gst_element_set_state (pipeline, GST_STATE_NULL); gst_object_unref (pipeline); // Exit application QTimer::singleShot(0, QApplication::activeWindow(), SLOT(quit())); } int ret = app.exec(); window.hide(); gst_element_set_state (pipeline, GST_STATE_NULL); gst_object_unref (pipeline); return ret; } </code></pre> <p>Here I am window ID of the QWidget and overlaying the video in it. This is the only thing that ever worked for me.</p> <p>However, now I wonder, if it is possible to get the window ID of an underlying qt graphical element. So, for example if I have something like:</p> <pre><code>ApplicationWindow { id: rootWindow objectName: "window" visible: true width: 800 height: 480 color: "#FFFFFF" Rectangle { width: 100 height: 100 color: "red" border.color: "black" border.width: 5 radius: 10 } } </code></pre> <p>Is it possible to get the ID of the underlying graphical window object or does that not exist? is there some component which has its own graphical ID that I can use in QML and then query from my C++ app and use it to overlay the video?</p>
2
Sql remove milliseconds and Date Conversion
<p>Please could any one suggest me getting the right results?</p> <p>I have a Date field which results in "2016-07-08 10:09:22.910" format and wish to remove milliseconds and same time wish to convert this field in to "08/07/2016 10:09:22"</p> <p>I managed to remove the milliseconds by using <code>CONVERT(VARCHAR, [DateFileCreated], 20)</code> but unable to convert this in to the desired format.</p> <p>Please suggest</p>
2
Make tabs appear vertically on the side when using p:tabMenu?
<p>I am <code>p:tabMenu</code> to show menu items, but they all are horizontally ordered but now client demands vertically. How to make tabs appear vertically on the side when using <code>p:tabMenu</code>?</p>
2
BottomSheet appearing from the top
<p>How can I show a BottomSheet from the top instead of the bottom?</p> <pre><code> button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); } }); mBottomSheetBehavior = BottomSheetBehavior.from(bottomSheetLayout); </code></pre>
2
How do I write the contents of a hash to a file in Ruby?
<p>I have a hash that looks as follows:</p> <pre><code>character = {"Name: " =&gt; "#$name", "Weapon: " =&gt; "#$weapon", "Armor: " =&gt; "#$armor"} </code></pre> <p>I want to print each <strong>key</strong> and each <strong>value</strong> to a file so that it looks something like this.</p> <p>Name: Templar<br> Weapon: Sword<br> Armor: Heavy Armor </p> <p>I would like to use a basic method so that I understand what is going on. I've read that there are some modules that do this for you, such as Marshal, but I would like a basic method that involves beginner-level code.</p>
2
How to ignore the windows error prompt on program execution?
<p>I have a program running on Windows cmd and when the program throws an error it keeps waiting for user input to either ignore/continue or cancel, but i have this batch file wich restarts the program automatically on error but since it keeps waiting for user input i have to go there and press a button</p> <pre><code>:unturned echo (%time%) Unturned started. cd masterserver cd VisualStudio cd Debug masterserver.exe @echo All done! @echo Masterserver listening on port: 23466 echo (%time%) WARNING: Unturned closed or crashed, restarting. &gt;&gt;c:\crashlog.txt ping 1.1.1.1 -n 1 -w 10000 &gt;nul goto unturned </code></pre> <p>How to make it ignore the error and continue automatically?</p> <p>Here is an image of the prompt:</p> <p><a href="https://i.stack.imgur.com/LCZ2c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LCZ2c.png" alt="image"></a></p>
2
How to make Windows Services state to "Manual"?
<p>I'm stopping a windows service currently from my code as shown below:</p> <pre><code>srvc_status = ControlService(serviceHandle, SERVICE_CONTROL_STOP, (LPSERVICE_STATUS)&amp;status); </code></pre> <p>But it is changing the state of service to <strong>Automatic (Delayed Start)</strong>. But I need it to be set to <strong>Manual</strong>. I went through the windows documentation also regarding <strong>ChangeServiceConfig</strong> and didn't found anything which says about the options to explicitly set the state to <strong>Manual</strong>. Can anyone guide me here towards the correct API call ?</p>
2
Getting input value from a data attribute
<p>I have this code below where user can choose - each dropdown option has different data-tenure:</p> <pre><code>&lt;div class="ten columns"&gt; &lt;p class="slider-label"&gt;Loan Tenure (Years)&lt;/p&gt; &lt;!-- &lt;input type="text" class="loan-tenure numeric-only" /&gt; --&gt; &lt;div class="field"&gt; &lt;div class="picker picker-dd2"&gt; &lt;select class="dropdown2 loan-tenure"&gt; &lt;option class="dropdown2-opt" data-tenure=“0.0298” value="1"&gt;1&lt;/option&gt; &lt;option class="dropdown2-opt" data-tenure=“0.0387” value="2"&gt;2&lt;/option&gt; &lt;option class="dropdown2-opt" data-tenure=“0.0418” value="3"&gt;3&lt;/option&gt; &lt;option class="dropdown2-opt" data-tenure=“0.0434” value="4"&gt;4&lt;/option&gt; &lt;option class="dropdown2-opt" data-tenure=“0.0444” value="5"&gt;5&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>What I want is to set the input value to the data-tenure above - :</p> <pre><code> &lt;input type="hidden" class="loan-rate" value="??" /&gt; </code></pre> <p>Do I need to add onchange() function to the dropdown above?</p>
2
Change url of categories
<p>I created a page listing the categories with this function:</p> <pre><code>function show_categories_fn(){ return wp_list_categories("echo=0&amp;title_li"); } add_shortcode('show_categories', 'show_categories_fn'); </code></pre> <p>But, when I click the category link, I find the list of posts bound to this one, but the url is <code>mysite.com/category/mycategory</code></p> <p>Yet, I would like to have only <code>mysite.com/mycategory</code>. </p> <p>Do you know how can it be done?</p> <p><strong>Edit :</strong> </p> <p>I am not sure that this answer answers my question. For my posts I want the structure the url / categoryname / postname, but when I click a category I want only the category (url of archive page), without the sub-folder category which corresponds to nothing</p>
2
Struggling to make Bootstrap-select to work
<p>I'm trying to use bootstrap-select (<a href="http://silviomoreto.github.io/bootstrap-select/" rel="nofollow">http://silviomoreto.github.io/bootstrap-select/</a>) and cannot make it load any options. It renders the dropbox but not the options. I'm a little bit lost and not sure if I'm loading the proper dependencies in the proper order or doing something stupid.</p> <p>I'm starting to learn all that stuff and might be doing something wrong in here. I've created a plunker so I can clearly reproduced the issue.</p> <p>Appreciate any help!</p> <p>This is my code: <a href="https://plnkr.co/edit/f80WGOjxuxBfXomOgEZn?p=preview" rel="nofollow">https://plnkr.co/edit/f80WGOjxuxBfXomOgEZn?p=preview</a></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;script src="script.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"&gt; &lt;!-- Jquery javascript version 1.12.4 --&gt; &lt;script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;!--script data-require="jquery@*" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.min.js"&gt;&lt;/script--&gt; &lt;!-- Latest compiled and minified CSS for Bootstrap-select--&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/css/bootstrap-select.min.css"&gt; &lt;!-- Latest compiled and minified JavaScript for Bootstrap-select --&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/js/bootstrap-select.min.js"&gt;&lt;/script&gt; &lt;!-- (Optional) Latest compiled and minified JavaScript translation files --&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/js/i18n/defaults-*.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body onload="start()"&gt; &lt;h1&gt;Bootstrap-select Dropdown test!&lt;/h1&gt; &lt;select class="selectpicker"&gt; &lt;option&gt;Mustard&lt;/option&gt; &lt;option&gt;Ketchup&lt;/option&gt; &lt;option&gt;Relish&lt;/option&gt; &lt;/select&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
2
Calculate month on month change in Oracle SQL
<p>I have a data set that records revenue by member, by month, by product. I can sum the revenue by member like so:</p> <pre><code>select sum(revenue), member, month from member_revenue group by member, month </code></pre> <p>I want to calculate the month on month change is revenue by member, ideally without having to call the data in the table for a second time.</p>
2
Shuffle songs in music player
<p>I’m just starting Android development and Java, and this is my first app to get acquainted with Android development. I’m almost done with the app, the only thing left is shuffling songs. I tried many steps to get it right, and I’ve scoured the web and SO for related question, yet I still can’t get it right.</p> <p>This snippet of code is in my Service class, Playlist is passed from Main Activity:</p> <pre><code>public void setPlayList(ArrayList&lt;SongModel&gt; playlist) { playList = playlist; //Arraylist of integer to hold the number of indices list = new ArrayList&lt;Integer&gt;(); for(int i =0; i &lt;= playList.size();i++){ list.add(i); } Collections.shuffle(list, new Random(System.nanoTime())); } </code></pre> <p>The code below is how songs are played, this snippet is in configPlayBack() method that plays the song from the song id:</p> <pre><code>long item = 0; item = playList.get(MusicPref.isShuffle(this)? list.get(position): position).getSongId(); </code></pre> <p>the snippet for playing next song is:</p> <pre><code>public void playNext() { position++; if (position &gt;= playList.size()) { position = 0; } configPlayBack(); } </code></pre> <p>But the songs are still playing serially.</p> <p>EDIT:</p> <pre><code>public void configPlayBack(){ prepared = true; player.reset(); if ( playList.size()&gt;0){ long item = 0; item = playList.get(MusicPref.isShuffle(this)? list.get(position):position).getSongId(); playItem(item); } } public void playItem(long item){ Uri base = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; Uri trackUri = ContentUris.withAppendedId(base, item); try{ player.setDataSource(getApplicationContext(), trackUri); } catch(Exception e){ Log.e(TAG, "Errror setting data source", e); } try{ player.prepare(); } catch(Exception ee) { ee.printStackTrace(); Log.e(TAG, "Error setting data source", ee); Toast.makeText(getApplicationContext(), "Song corrupt or not supported", Toast.LENGTH_SHORT).show(); ee.printStackTrace(); isReady = false; } player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { isReady = true; setPlayState(); getAudioFocus(); mp.start(); updateNotificationPlayer(); updatePlayback(); updateSeek(); player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { isReady = false; mp.reset(); playNext(); } }); } }); } </code></pre>
2
Make deeply nested JSON from data frame in R
<p>I'm looking to take a nice tidy data frame and turn it into a deeply nested JSON using R. So far I haven't been able to find any other resources that directly address this task - most seem to be trying to take it in the other direction (un-nesting a JSON). </p> <p>Here's a small dummy version of the data frame I'm starting with. Imagine a survey was given to two audiences within a company, one for managers and a separate one for employees. The surveys have different sets of questions with different IDs but many questions overlap and I want to compare the responses between the two groups. The end goal is to make a JSON that matches up section IDs, question IDs, and option IDs/text from two surveys in the correct hierarchy. Some questions have subquestions that require a further level of nesting, which is what I’m having difficulty doing. </p> <pre><code>library(dplyr) library(tidyr) library(jsonlite) dummyDF &lt;- data_frame(sectionId = c(rep(1,9),rep(2,3)), questionId = c(rep(1,3),rep(2,6),rep(3,3)), subquestionId = c(rep(NA,3),rep("2a",3),rep("2b",3),rep(NA,3)), deptManagerQId = c(rep("m1",3),rep("m2",3),rep("m3",3),rep("m4",3)), deptEmployeeQId = c(rep("e1",3),rep("e3",3),rep("e4",3),rep("e7",3)), optionId = rep(c(1,2,3),4), text = rep(c("yes","neutral","no"),4)) </code></pre> <p>And here’s the end result I’m trying to achieve:</p> <pre><code>theGoal &lt;- fromJSON('{ "sections": [ { "sectionId": "1", "questions": [ { "questionId": "1", "deptManagerQId": "m1", "deptEmployeeQId": "e1", "options": [ { "optionId": 1, "text": "yes" }, { "optionId": 2, "text": "neutral" }, { "optionId": 3, "text": "no" } ] }, { "questionId": "2", "options": [ { "optionId": 1, "text": "yes" }, { "optionId": 2, "text": "neutral" }, { "optionId": 3, "text": "no" } ], "subquestions": [ { "subquestionId": "2a", "deptManagerQId": "m2", "deptEmployeeQId": "e3" }, { "subquestionId": "2b", "deptManagerQId": "m3", "deptEmployeeQId": "e4" } ] }, { "questionId": "3", "deptManagerQId": "m4", "deptEmployeeQId": "e7", "options": [ { "optionId": 1, "text": "yes" }, { "optionId": 2, "text": "neutral" }, { "optionId": 3, "text": "no" } ] } ] } ] }') </code></pre> <p>Here are a few approaches I’ve tried using nest from tidyr that end up either only getting me part of the way there or throwing an error message.</p> <h1>1</h1> <pre><code>list1 &lt;- dummyDF %&gt;% nest(-sectionId, .key=questions) %&gt;% mutate(questions = lapply(seq_along(.$questions), function(x) nest(.$questions[[x]], optionId, text, .key = options))) %&gt;% list(sections = .) </code></pre> <h1>2</h1> <pre><code>nested1 &lt;- dummyDF %&gt;% nest(-sectionId, .key=questions) %&gt;% mutate(questions = lapply(seq_along(.$questions), function(x) nest(.$questions[[x]], optionId, text, .key = options))) nested2 &lt;- nested1 %&gt;% mutate(questions = lapply(seq_along(.$questions), function(x) nest(.$questions[[x]], subquestionId, .key = subquestions))) #Gives this error: cannot group column options, of class 'list' </code></pre> <h1>3</h1> <pre><code>list2 &lt;- dummyDF %&gt;% nest(-sectionId, .key=questions) %&gt;% mutate(questions = lapply(seq_along(.$questions), function(x) {ifelse(is.na(.$questions[[x]]$subquestionId), function(x) {.$questions[[x]] %&gt;% select(-subquestionId) %&gt;% nest(optionId, text, .key = options)}, function(x) {.$questions[[x]] %&gt;% nest(subquestion_id, .key = subquestions)})})) %&gt;% list(sections = .) #Gives this error: attempt to replicate an object of type 'closure' </code></pre> <p>Any ideas would be greatly appreciated. I’m open to any approaches. I took the issue to a local R user group meet-up but wasn’t able to come up with any solutions so I’ve got my fingers crossed here. I realize R might not be the best tool to accomplish this but it’s the one I know so I’m giving it a shot. Thanks.</p>
2
updating xamarin.forms and xamarin.android
<p>I am developing in xamarin.forms for android and ios</p> <p>I have upgrade to to latest xamarin.forms package 2.3.0.107 in the pcl and it works fine - no compilation errors.</p> <p>when I try to upgrade the xamarin.android to the same version I get lots of packages error.</p> <p>I have seen in some posts that there is not need to upgrade the xamarin.android because the xamarin.forms knows to take the latest / most suitable package of amarin.android. is it true ?</p> <p>The default xamarin.android is from januray 2016 which is quite old...</p> <p>Here are the list of errors I get...</p> <pre><code>Severity Code Description Project File Line Suppression State Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.Vector.Drawable\23.3.0.0\content directory. SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.v7.CardView' available in SDK installer. Android resource directory C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.CardView\23.3.0.0\embedded\./ doesn't exist. SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.Design' available in SDK installer. Android resource directory C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.Design\23.3.0.0\embedded\./ doesn't exist. SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.v4' available in SDK installer. Java library file C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v4\23.3.0.0\embedded\classes.jar doesn't exist. SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.v7.MediaRouter' available in SDK installer. Java library file C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.MediaRouter\23.3.0.0\embedded\libs/internal_impl-23.3.0.jar doesn't exist. SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.Animated.Vector.Drawable' available in SDK installer. Java library file C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.Animated.Vector.Drawable\23.3.0.0\embedded\classes.jar doesn't exist. SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.MediaRouter\23.3.0.0\content directory. SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v4\23.3.0.0\content directory. SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.v7.MediaRouter' available in SDK installer. Java library file C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.MediaRouter\23.3.0.0\embedded\classes.jar doesn't exist. SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.Design\23.3.0.0\content directory. SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.Vector.Drawable\23.3.0.0\content directory. SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.v7.AppCompat' available in SDK installer. Java library file C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.AppCompat\23.3.0.0\embedded\classes.jar doesn't exist. SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.Animated.Vector.Drawable\23.3.0.0\content directory. SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.Animated.Vector.Drawable' available in SDK installer. Android resource directory C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.Animated.Vector.Drawable\23.3.0.0\embedded\./ doesn't exist. SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.v7.MediaRouter' available in SDK installer. Android resource directory C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.MediaRouter\23.3.0.0\embedded\./ doesn't exist. SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.v7.RecyclerView' available in SDK installer. Android resource directory C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.RecyclerView\23.3.0.0\embedded\./ doesn't exist. SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.Design' available in SDK installer. Java library file C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.Design\23.3.0.0\embedded\classes.jar doesn't exist. SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.v7.RecyclerView' available in SDK installer. Java library file C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.RecyclerView\23.3.0.0\embedded\classes.jar doesn't exist. SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.MediaRouter\23.3.0.0\content directory. SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v4\23.3.0.0\content directory. SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.Vector.Drawable' available in SDK installer. Java library file C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.Vector.Drawable\23.3.0.0\embedded\classes.jar doesn't exist. SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.Design\23.3.0.0\content directory. SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.RecyclerView\23.3.0.0\content directory. SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.CardView\23.3.0.0\content directory. SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.Animated.Vector.Drawable\23.3.0.0\content directory. SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.MediaRouter\23.3.0.0\content directory. SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v4\23.3.0.0\content directory. SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.CardView\23.3.0.0\content directory. SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.v7.CardView' available in SDK installer. Java library file C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.CardView\23.3.0.0\embedded\classes.jar doesn't exist. SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.AppCompat\23.3.0.0\content directory. SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.Vector.Drawable' available in SDK installer. Android resource directory C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.Vector.Drawable\23.3.0.0\embedded\./ doesn't exist. SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.AppCompat\23.3.0.0\content directory. SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.v7.AppCompat' available in SDK installer. Android resource directory C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.AppCompat\23.3.0.0\embedded\./ doesn't exist. SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.v4' available in SDK installer. Android resource directory C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v4\23.3.0.0\embedded\./ doesn't exist. SmartScout.Droid Error Please install package: 'Xamarin.Android.Support.v4' available in SDK installer. Java library file C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v4\23.3.0.0\embedded\libs/internal_impl-23.3.0.jar doesn't exist. SmartScout.Droid Error Unzipping failed. Please download https://dl-ssl.google.com/android/repository/android_m2repository_r29.zip and extract it to the C:\Users\asaf\AppData\Local\Xamarin\Xamarin.Android.Support.v7.RecyclerView\23.3.0.0\content directory. SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid Error Reason: C:\Users\asaf\AppData\Local\Xamarin\zips\2A3A8A6D6826EF6CC653030E7D695C41.zip is not a valid zip file SmartScout.Droid </code></pre>
2
Using FFmpeg to encode 2pass mp4
<p>I am trying to use FFmpeg to encode my 4K mp4 file to a 2pass 265 mp4 file for the purposes of testing. I am new to video compression and hope I'm making a simple mistake that someone can correct.</p> <p>All infos in command line as below:</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>C:\Ying\FF&gt;C:\Ying\FF\ffmpeg.exe -y -i C:\Ying\FF\Xman-4K_50sec_3840x2160.mp4 -preset veryslow -x265-params pass=1 -vcodec hevc -b:v 15M -acodec libvo _aacenc -b:a 128K C:\Ying\FF\Xman-4K_3840x2160_50sec_15M_H265_veryslow_2pass.mp4 ffmpeg version N-74286-ge5774f2 Copyright (c) 2000-2015 the FFmpeg developers built with gcc 4.9.3 (GCC) configuration: --disable-static --enable-shared --enable-gpl --enable-version3 --disable-w32threads --enable-avisynth --enable-bzlib --enable-fontco nfig --enable-frei0r --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libdcadec --enable-l ibfreetype --enable-libgme --enable-libgsm --enable-libilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-am rwb --enable-libopenjpeg --enable-libopus --enable-librtmp --enable-libschroedinger --enable-libsoxr --enable-libspeex --enable-libtheora --enable-lib twolame --enable-libvidstab --enable-libvo-aacenc --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --en able-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-lzma --enable-decklink --enable-zlib libavutil 54. 30.100 / 54. 30.100 libavcodec 56. 57.100 / 56. 57.100 libavformat 56. 40.101 / 56. 40.101 libavdevice 56. 4.100 / 56. 4.100 libavfilter 5. 32.100 / 5. 32.100 libswscale 3. 1.101 / 3. 1.101 libswresample 1. 2.101 / 1. 2.101 libpostproc 53. 3.100 / 53. 3.100 Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'C:\Ying\FF\Xman-4K_50sec_3840x2160.mp4': Metadata: major_brand : isom minor_version : 512 compatible_brands: isomiso2avc1mp41 title : X-MEN__DAYS_OF_FUTURE_PAST.Title800 encoder : Lavf56.40.101 Duration: 00:00:50.01, start: 0.000000, bitrate: 11067 kb/s Chapter #0:0: start 0.000000, end 50.000000 Metadata: title : (26)01:17:27:726 Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 3840x2160 [SAR 1:1 DAR 16:9], 11492 kb/s, 30 fps, 30 tbr, 15360 tbn, 60 tbc (de fault) Metadata: handler_name : VideoHandler Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 127 kb/s (default) Metadata: handler_name : SoundHandler Stream #0:2(eng): Subtitle: mov_text (text / 0x74786574), 0 kb/s Metadata: handler_name : SubtitleHandler x265 [info]: HEVC encoder version 1.7 x265 [info]: build info [Windows][GCC 4.9.2][64 bit] 8bpp x265 [info]: using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX x265 [info]: Main profile, Level-5 (Main tier) x265 [info]: Thread pool created using 32 threads x265 [info]: frame threads / pool features : 8 / wpp(34 rows) x265 [info]: Coding QT: max CU size, min CU size : 64 / 8 x265 [info]: Residual QT: max TU size, max depth : 32 / 3 inter / 3 intra x265 [info]: ME / range / subpel / merge : dia / 57 / 2 / 1 x265 [info]: Keyframe min / max / scenecut : 25 / 250 / 40 x265 [info]: Lookahead / bframes / badapt : 40 / 8 / 2 x265 [info]: b-pyramid / weightp / weightb / refs: 1 / 1 / 1 / 1 x265 [info]: AQ: mode / str / qg-size / cu-tree : 1 / 1.0 / 64 / 1 x265 [info]: Rate Control / qCompress : ABR-15000 kbps / 0.60 x265 [info]: tools: rd=2 psy-rd=0.30 rdoq=2 psy-rdoq=1.00 early-skip signhide x265 [info]: tools: tmvp b-intra fast-intra strong-intra-smoothing deblock sao x265 [info]: tools: stats-write Output #0, mp4, to 'C:\Ying\FF\Xman-4K_3840x2160_50sec_15M_H265_veryslow_2pass.mp4': Metadata: major_brand : isom minor_version : 512 compatible_brands: isomiso2avc1mp41 title : X-MEN__DAYS_OF_FUTURE_PAST.Title800 encoder : Lavf56.40.101 Chapter #0:0: start 0.000000, end 50.000000 Metadata: title : (26)01:17:27:726 Stream #0:0(und): Video: hevc (libx265) ([35][0][0][0] / 0x0023), yuv420p, 3840x2160 [SAR 1:1 DAR 16:9], q=2-31, 15000 kb/s, 30 fps, 15360 tbn, 30 tbc (default) Metadata: handler_name : VideoHandler encoder : Lavc56.57.100 libx265 Stream #0:1(und): Audio: aac (libvo_aacenc) ([64][0][0][0] / 0x0040), 48000 Hz, stereo, s16, 128 kb/s (default) Metadata: handler_name : SoundHandler encoder : Lavc56.57.100 libvo_aacenc Stream mapping: Stream #0:0 -&gt; #0:0 (h264 (native) -&gt; hevc (libx265)) Stream #0:1 -&gt; #0:1 (aac (native) -&gt; aac (libvo_aacenc)) Press [q] to stop, [?] for help frame= 1502 fps=2.6 q=-0.0 Lsize= 100652kB time=00:00:50.01 bitrate=16485.9kbits/s dup=75 drop=0 video:99814kB audio:782kB subtitle:0kB other streams:0kB global headers:1kB muxing overhead: 0.054657% x265 [info]: frame I: 11, Avg QP:13.26 kb/s: 59293.48 x265 [info]: frame P: 443, Avg QP:15.21 kb/s: 33977.10 x265 [info]: frame B: 1048, Avg QP:18.35 kb/s: 8420.64 x265 [info]: global : 1502, Avg QP:17.39 kb/s: 16330.84 x265 [info]: Weighted P-Frames: Y:4.5% UV:4.5% x265 [info]: Weighted B-Frames: Y:1.9% UV:1.6% x265 [info]: consecutive B-frames: 23.8% 11.9% 14.8% 22.9% 17.8% 7.0% 0.0% 0.0% 1.8% C:\Ying\FF&gt;C:\Ying\FF\ffmpeg.exe -y -i C:\Ying\FF\Xman-4K_50sec_3840x2160.mp4 -preset veryslow -x265-params pass=2 -vcodec hevc -b:v 15M -acodec libvo _aacenc -b:a 128K C:\Ying\FF\Xman-4K_3840x2160_50sec_15M_H265_veryslow_2pass.mp4 ffmpeg version N-74286-ge5774f2 Copyright (c) 2000-2015 the FFmpeg developers built with gcc 4.9.3 (GCC) configuration: --disable-static --enable-shared --enable-gpl --enable-version3 --disable-w32threads --enable-avisynth --enable-bzlib --enable-fontco nfig --enable-frei0r --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libdcadec --enable-l ibfreetype --enable-libgme --enable-libgsm --enable-libilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-am rwb --enable-libopenjpeg --enable-libopus --enable-librtmp --enable-libschroedinger --enable-libsoxr --enable-libspeex --enable-libtheora --enable-lib twolame --enable-libvidstab --enable-libvo-aacenc --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --en able-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-lzma --enable-decklink --enable-zlib libavutil 54. 30.100 / 54. 30.100 libavcodec 56. 57.100 / 56. 57.100 libavformat 56. 40.101 / 56. 40.101 libavdevice 56. 4.100 / 56. 4.100 libavfilter 5. 32.100 / 5. 32.100 libswscale 3. 1.101 / 3. 1.101 libswresample 1. 2.101 / 1. 2.101 libpostproc 53. 3.100 / 53. 3.100 Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'C:\Ying\FF\Xman-4K_50sec_3840x2160.mp4': Metadata: major_brand : isom minor_version : 512 compatible_brands: isomiso2avc1mp41 title : X-MEN__DAYS_OF_FUTURE_PAST.Title800 encoder : Lavf56.40.101 Duration: 00:00:50.01, start: 0.000000, bitrate: 11067 kb/s Chapter #0:0: start 0.000000, end 50.000000 Metadata: title : (26)01:17:27:726 Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 3840x2160 [SAR 1:1 DAR 16:9], 11492 kb/s, 30 fps, 30 tbr, 15360 tbn, 60 tbc (de fault) Metadata: handler_name : VideoHandler Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 127 kb/s (default) Metadata: handler_name : SoundHandler Stream #0:2(eng): Subtitle: mov_text (text / 0x74786574), 0 kb/s Metadata: handler_name : SubtitleHandler x265 [info]: HEVC encoder version 1.7 x265 [info]: build info [Windows][GCC 4.9.2][64 bit] 8bpp x265 [info]: using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX x265 [info]: Main profile, Level-6 (Main tier) x265 [info]: Thread pool created using 32 threads x265 [info]: frame threads / pool features : 8 / wpp(34 rows) x265 [error]: statistics are damaged at line 1495, parser out=1 [libx265 @ 0000000001e97d00] Cannot open libx265 encoder. Output #0, mp4, to 'C:\Ying\FF\Xman-4K_3840x2160_50sec_15M_H265_veryslow_2pass.mp4': Metadata: major_brand : isom minor_version : 512 compatible_brands: isomiso2avc1mp41 title : X-MEN__DAYS_OF_FUTURE_PAST.Title800 encoder : Lavf56.40.101 Chapter #0:0: start 0.000000, end 50.000000 Metadata: title : (26)01:17:27:726 Stream #0:0(und): Video: hevc, none, q=2-31, 128 kb/s, SAR 1:1 DAR 0:0, 30 fps (default) Metadata: handler_name : VideoHandler encoder : Lavc56.57.100 libx265 Stream #0:1(und): Audio: aac, 0 channels, 128 kb/s (default) Metadata: handler_name : SoundHandler encoder : Lavc56.57.100 libvo_aacenc Stream mapping: Stream #0:0 -&gt; #0:0 (h264 (native) -&gt; hevc (libx265)) Stream #0:1 -&gt; #0:1 (aac (native) -&gt; aac (libvo_aacenc)) Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height</code></pre> </div> </div> MediaInfo: <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>General Complete name : E:\4K\2ndRound\Xman-4K_50sec_3840x2160.mp4.mp4 Format : MPEG-4 Format profile : Base Media Codec ID : isom File size : 66.0 MiB Duration : 50s 6ms Overall bit rate : 11.1 Mbps Movie name : X-MEN__DAYS_OF_FUTURE_PAST.Title800 Writing application : Lavf56.40.101 Video ID : 1 Format : AVC Format/Info : Advanced Video Codec Format profile : [email protected] Format settings, CABAC : Yes Format settings, ReFrames : 4 frames Codec ID : avc1 Codec ID/Info : Advanced Video Coding Duration : 47s 567ms Bit rate : 11.5 Mbps Width : 3 840 pixels Height : 2 160 pixels Display aspect ratio : 16:9 Frame rate mode : Constant Frame rate : 30.000 fps Color space : YUV Chroma subsampling : 4:2:0 Bit depth : 8 bits Scan type : Progressive Bits/(Pixel*Frame) : 0.046 Stream size : 65.2 MiB (99%) Audio ID : 2 Format : AAC Format/Info : Advanced Audio Codec Format profile : LC Codec ID : 40 Duration : 50s 6ms Bit rate mode : Constant Bit rate : 128 Kbps Channel(s) : 2 channels Channel positions : Front: L R Sampling rate : 48.0 KHz Compression mode : Lossy Stream size : 781 KiB (1%) Menu #1 ID : 3 Codec ID : text Duration : 50s 0ms Language : English Menu #2 00:00:00.000 : (26)01:17:27:726 ​</code></pre> </div> </div> </p>
2
Change only the label text in Google gantt chart
<p>I'm using Google's gantt chart and I wish to change the text of the label only (Not the the tooltip). For example, one of the labels says "This is a very long label to test the width of the label on a google gantt chart" and I wish it to say on the label "This is a very ...". On the tooltip, I would like it to display the full text. </p> <p>If I make the change in when adding the row</p> <pre><code>data.addRows([ ['Research', 'This is a very long label to test the width of the label on a google gantt chart' </code></pre> <p>It changes both the label and the tooltip. I would just like it to change the label. Please see the <a href="https://jsfiddle.net/ccakn5870/ntectnth/" rel="nofollow noreferrer">jfiddle</a> and the image below. How can this be done?</p> <p><a href="https://i.stack.imgur.com/80VLU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/80VLU.png" alt="enter image description here"></a></p>
2
Gensim Doc2Vec - Pass corpus sentences to Doc2Vec function
<p>I used the <code>MySentences</code> class for extracting sentences from all files in a directory and use this sentences for train a <em>word2vec</em> model. My dataset is unlabeled.</p> <pre><code>class MySentences(object): def __init__(self, dirname): self.dirname = dirname def __iter__(self): for fname in os.listdir(self.dirname): for line in open(os.path.join(self.dirname, fname)): yield line.split() sentences = MySentences('sentences') model = gensim.models.Word2Vec(sentences) </code></pre> <p>Now I want to use that class to make a <em>doc2vec</em> model. I read <a href="https://radimrehurek.com/gensim/models/doc2vec.html" rel="nofollow">Doc2Vec</a> reference page. <code>Doc2Vec()</code> function gets sentences as parameter, but it doesn't accept above sentences variable and return error :</p> <pre><code>AttributeError: 'list' object has no attribute 'words' </code></pre> <p>What is the problem? What is the correct type of that parameter?</p> <p><strong>Update :</strong></p> <p>I think, unlabeled data is the problem. It seems doc2vec needs labeled data.</p>
2
Determine programmatically if we're connecting to SharePoint Online or on-premise with CSOM API
<p>I would like to know if there is a way to determine if we're about to connect to a SharePoint Online server or an on-premise one (as the Credentials object type differs). I'm using the CSOM API in C# with a SharePoint 2013 and a SharePoint Online server.</p> <p>So far, I haven't found anything useful in the <a href="https://msdn.microsoft.com/en-us/library/office/microsoft.sharepoint.client.clientcontext_members.aspx" rel="nofollow">ClientContext</a> object itself so I'm thinking to just check the login that the user to see if it's login is like "DOMAIN\ACCOUNT" or "[email protected]" but I don't know if it's possible to have a Domain\Account login type on SharePoint Online or something else.</p> <p>If it's impossible to do, I'll just ask the user to tell what type of server it is.</p>
2
Android manifest make apk a launcher app on tablet but normal app on phone
<p>How do you make one apk be a <strong>launcher</strong> app on tablets but just a <strong>normal</strong> app on phones? How do you configure the manifest file for this?</p> <p>By launcher app I mean it will show up as one of the option when the apk is run on tablets: <a href="https://i.stack.imgur.com/F3UaA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F3UaA.png" alt="Select home picker"></a></p> <p>If the same apk is run on phones, it will not show the "Select a home app" picker.</p> <p>In simple terms, this is the behaviour the apk needs to have:</p> <p><strong>Goal:</strong></p> <ul> <li>When I click home on <strong>phones</strong>, I should <strong>not see</strong> the app as one of the launcher choices. </li> <li>When I click home on <strong>tablet</strong> then I should <strong>see</strong> the app as one of the choices.</li> </ul> <p>My approach is I have a ChooserActivity.java that determines what kind of device is being run. If it is a tablet it will start TabletMainActivity.java, if it is phone it will start PhoneMainActivity.java. (The code for finding out if it is a tablet or a phone is okay.)</p> <p>ChooserActivity.java</p> <pre><code> public class ChooserActivity extends AppCompatActivity { ImageView tabIndicator; private static final String TAG = "Chooser"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chooser); Log.d(TAG, "onCreate2() Chooser"); finish(); if (findViewById(R.id.tabIndicator)==null){ //PHONE startActivity(new Intent(this, PhoneMainActivity.class)); }else{ //TABLET startActivity(new Intent(this, TabletMainActivity.class)); } } } </code></pre> <p>res/layout/activity_chooser.xml</p> <pre><code> &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.sample.tabletchecker.Chooser"&gt; &lt;TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="PHONE" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>res/layout-sw600dp/activity_chooser.xml</p> <pre><code> &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.sample.tabletchecker.Chooser"&gt; &lt;TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="TABLET" /&gt; &lt;ImageView android:layout_width="0dp" android:layout_height="0dp" android:id="@+id/tabIndicator" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>TabletMainActivity.java has the following launcher manifest settings:</p> <pre><code>&lt;activity android:name=".TabletMainActivity" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;!-- launcher setting --&gt; &lt;category android:name="android.intent.category.HOME" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; </code></pre> <p>PhoneMainActivity.java is just a normal activity, has nothing on the manifest. This is on purpose because I want this activity to be a normal activity on phones.</p> <pre><code>&lt;activity android:name=".PhoneActivity"&gt; &lt;/activity&gt; </code></pre> <p>My ChooserActivity.java is the first activity that gets started when the app gets clicked/opened, it then chooses between the 2. ChooserActivity manifest entry</p> <pre><code>&lt;activity android:name=".ChooserActivity"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; </code></pre> <p>I tried different variations for the intent-filter for the TabletMainActivity.java but never able to get the correct behaviour. I always see the launcher picker being shown. </p>
2
Processing in java (without IDE)
<p>I have seen alot of information about running processing with java using an IDE (eclipse, netbeans). I wanted to know how to run processing from java without using an IDE. Could someone describe step by step instructions in setting up and running processing from java or point me to a good website. I am using java 8 Thanks</p>
2
How to check the Support Library / AppCompat library version at Runtime?
<p>We have an SDK for Android that requires Support Library v4 with targetSdk 23 (meaning that the Support Library should be also 23). For commercial reasons, I have to upgrade the SDK so it should work even if the App is compiled against API 21. </p> <p>This means that some calls to the Support Library should be done conditionally depending on the current Support Library version of the App (<strong>not the current API level</strong>), so I have 3 options here (ranked by best to worst): </p> <p>1 - Check the Support Library version before the method call (This is what I have not figured out how to do, (if possible at all)).<br> 2 - Use reflection.<br> 3 - Use Try Catch blocks. </p> <p>So for the 1st option, is it possible to check the support library version at runtime?</p>
2
Add required to element if radio button is checked
<p>I have a form with radiobuttons and an input field. If any of the three top radio buttons are checked I need to add "required" to the input field. My code:</p> <pre><code>&lt;ng-form name="addShareholderForm"&gt; &lt;form name="form.addForm" class="form-validation" ng-submit=" $ctrl.addShareholder()" ng-init="$ctrl.setFormScope(this)"&gt; &lt;md-radio-group ng-model="data.group1" ng-required="true"&gt; &lt;md-radio-button value="passport" class="md-primary"&gt;Passport number&lt;/md-radio-button&gt; &lt;md-radio-button value="ssn"&gt;Social security number(SSN) &lt;/md-radio-button&gt; &lt;md-radio-button value="drivers-license"&gt;Drivers license number&lt;/md-radio-button&gt; &lt;md-radio-button value="person-other"&gt;Other&lt;/md-radio-button&gt; &lt;/md-radio-group&gt; &lt;input placeholder="Type number" ng-required="data.group1 == 'passport' || data.group1 == 'ssn' || data.group1 == 'drivers-license'"&gt; &lt;md-input-container&gt; &lt;md-button type="submit" ng-disabled="!addShareholderForm.$valid" class="md-raised md-primary md-no-ink submitshareholder" aria-label="Lägg till"&gt; &lt;i class="material-icons done-button-fab"&gt;add_circle&lt;/i&gt;Lägg till &lt;/md-button&gt; &lt;/md-input-container&gt; </code></pre> <p> </p> <p>However this is not working and I don't know what I'm doing wrong? The input field is not set to required.</p> <p>EDIT: I changed the code according to suggestions below and added the ng-form and the button to the code. The button is supposed to be disabled when the form is invalid but i´t is enabled as soon as I check a radio button without filling out the input. </p>
2
Get Email address of Facebook user from post comments
<p>I am trying to get email address from comments in posts of the Facebook page, but with no luck. I am requesting this URL:</p> <pre><code>feed?fields=message,id,description,created_time,from,comments{from,email, id,created_time,message},story </code></pre> <p>I am using v2.6 of Graph API. Is there any way for getting the mail in single call or I need to send another request where I will call the ID of the Facebook User and then access the email address which will be bad practice if there is a lot of comments and users.</p>
2
Date Range or Columns values entered in Prompt need to be used as variables in Spotfire IL modified SQL
<p>I need to use the prompted input of a date range/any column to be used as a variable in the modified SQl feature of the Information Link. I have some complex queries which uses multiple conditions and i wont be able to keep them in the view and want to add those conditions in modified SQL using this variable.</p> <p>This is a sample SQL where i need to use the variable/parameter instead of the dates given</p> <pre><code>SELECT xxxxx.yyyy FROM xxxxx, xxxxx, xxxxx, xxxxx WHERE xxxxx.yyyyy = xxxxx.yyyyy AND ( (( xxxxx.yyyy &gt;= (TO_DATE ('11/01/2015', 'MM/DD/YYYY')) AND xxxxx.yyyy &lt; (TO_DATE ('12/1/2015', 'MM/DD/YYYY')) AND xxxxx.zzzzz &gt;= (TO_DATE ('11/01/2015', 'MM/DD/YYYY')) AND xxxxx.zzzzz &lt; (TO_DATE ('12/1/2015', 'MM/DD/YYYY')) )) OR (( xxxxx.zzzzz &gt;= (TO_DATE ('11/01/2015', 'MM/DD/YYYY')) AND xxxxx.zzzzz &lt; (TO_DATE ('12/1/2015', 'MM/DD/YYYY')) AND xxxxx.yyyy = (TO_DATE ('01/01/1753', 'MM/DD/YYYY')) )) OR (( xxxxx.zzzzz &gt;= (TO_DATE ('11/01/2015', 'MM/DD/YYYY')) AND xxxxx.zzzzz &lt; (TO_DATE ('12/1/2015', 'MM/DD/YYYY')) AND xxxxx.yyyy &gt; (TO_DATE ('10/15/2015', 'MM/DD/YYYY')) AND xxxxx.yyyy &lt; (TO_DATE ('12/1/2015', 'MM/DD/YYYY')) )) ) </code></pre> <p>I need the above where conditions to be added into the Information link modified SQL with the parameter to be like this </p> <pre><code>WHERE xxxxx.yyyyy = xxxxx.yyyyy AND ( (( xxxxx.yyyy &gt;= @parameter1 AND xxxxx.yyyy &lt; @parameter2 AND xxxxx.zzzzz &gt;= @parameter1 AND xxxxx.zzzzz &lt; @parameter2 </code></pre> <p>Let me know if further clarification is required.</p>
2
RSpec Couldn't find with 'id'=
<p>I'm writing an RSpec controller test and I've run into the following problem.</p> <p>The relationship is such that Invoices belong to a Purchase, and a Purchase has many invoices. </p> <p>My controller has:</p> <pre><code>class InvoicesController &lt; ApplicationController def index @invoices = Invoice.all end def new @purchase = Purchase.find(params[:purchase]) @invoice = Invoice.new(:purchase_id =&gt; params[:purchase]) end </code></pre> <p>My factory has:</p> <pre><code>FactoryGirl.define do factory :invoice do |f| sequence(:id) { |number| number } f.purchase_id {rand(1..30)} f.number { FFaker::String.from_regexp(/\A[A-Za-z0-9]+\z/) } f.terms { FFaker::String.from_regexp(/\A[A-Za-z0-9\s]+\z/) } f.currency { FFaker::String.from_regexp(/\A[A-Z]+\z/) } f.total_due {'25000.00'} f.current_balance {'12500.00'} f.due_date { FFaker::Time.date } f.notes { FFaker::HipsterIpsum.paragraph } f.status {[:open, :paid, :canceled].sample} purchase end factory :invalid_invoice, parent: :invoice do |f| f.status nil end end </code></pre> <p>My controller spec (just the problematic part) has:</p> <pre><code>describe "GET new" do it "assigns a new invoice to @invoice" do invoice = FactoryGirl.create(:invoice) get :new expect(assigns(:invoice)).to_not eq(invoice) end it "renders the :new template" do get :new expect(response).to render_template :new end end </code></pre> <p>In my routes I have:</p> <pre><code>purchases GET /purchases(.:format) purchases#index POST /purchases(.:format) purchases#create new_purchase GET /purchases/new(.:format) purchases#new edit_purchase GET /purchases/:id/edit(.:format) purchases#edit purchase GET /purchases/:id(.:format) purchases#show PATCH /purchases/:id(.:format) purchases#update PUT /purchases/:id(.:format) purchases#update DELETE /purchases/:id(.:format) purchases#destroy invoices GET /invoices(.:format) invoices#index POST /invoices(.:format) invoices#create new_invoice GET /invoices/new(.:format) invoices#new edit_invoice GET /invoices/:id/edit(.:format) invoices#edit invoice GET /invoices/:id(.:format) invoices#show PATCH /invoices/:id(.:format) invoices#update PUT /invoices/:id(.:format) invoices#update DELETE /invoices/:id(.:format) invoices#destroy </code></pre> <p>When I run the test I get this:</p> <pre><code>1) InvoicesController GET new assigns a new invoice to @invoice Failure/Error: get :new ActiveRecord::RecordNotFound: Couldn't find Purchase with 'id'= # ./app/controllers/invoices_controller.rb:7:in `new' # ./spec/controllers/invoices_controller_spec.rb:38:in `block (3 levels) in &lt;top (required)&gt;' 2) InvoicesController GET new renders the :new template Failure/Error: get :new ActiveRecord::RecordNotFound: Couldn't find Purchase with 'id'= # ./app/controllers/invoices_controller.rb:7:in `new' # ./spec/controllers/invoices_controller_spec.rb:43:in `block (3 levels) in &lt;top (required)&gt;' </code></pre> <p>Here is a snippet from test.log</p> <p>[1m[36m (0.1ms)[0m [1mRELEASE SAVEPOINT active_record_1[0m [1m[35m (0.1ms)[0m SAVEPOINT active_record_1 [1m[36mSQL (0.3ms)[0m [1mINSERT INTO "purchases" ("id", "vendor_id", "order_number", "status", "notes", "tradegecko_url", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id"[0m [["id", 4], ["vendor_id", 4], ["order_number", "zzz"], ["status", "canceled"], ["notes", "Jean shorts cliche Williamsburg raw denim put a bird on it messenger bag. Shoreditch keytar Brooklyn lomo brunch. Mcsweeney's Cosby Sweater +1 PBR Austin biodiesel freegan."], ["tradegecko_url", "<a href="http://gorczany.info" rel="nofollow">http://gorczany.info</a>"], ["created_at", "2016-07-19 14:51:00.616108"], ["updated_at", "2016-07-19 14:51:00.616108"]] [1m[35m (0.1ms)[0m RELEASE SAVEPOINT active_record_1 [1m[36m (0.1ms)[0m [1mSAVEPOINT active_record_1[0m [1m[35mSQL (0.3ms)[0m INSERT INTO "invoices" ("id", "purchase_id", "number", "terms", "currency", "total_due", "current_balance", "due_date", "notes", "status", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING "id" [["id", 4], ["purchase_id", 4], ["number", "dd"], ["terms", "TT"], ["currency", "MM"], ["total_due", "25000.0"], ["current_balance", "12500.0"], ["due_date", "2015-11-13"], ["notes", "Scenester Carles cred quinoa fixie put a bird on it Four Loko next level. Biodiesel vice Wayfarers sustainable brunch butcher locavore. Keytar vice next level stumptown Rerry Richardson."], ["status", "canceled"], ["created_at", "2016-07-19 14:51:00.619066"], ["updated_at", "2016-07-19 14:51:00.619066"]] [1m[36m (0.1ms)[0m [1mRELEASE SAVEPOINT active_record_1[0m Processing by InvoicesController#new as HTML [1m[35mPurchase Load (0.3ms)[0m SELECT "purchases".* FROM "purchases" WHERE "purchases"."id" = $1 LIMIT 1 [["id", nil]] Completed 404 Not Found in 2ms (ActiveRecord: 0.3ms)</p> <p>I think the problem is that the factory associations are created, but not saved. So when the purchase.id is called it returns nil.</p>
2
Text inside div over black overlay WITHOUT opacity
<p>I'm implementing an on-boarding similar to Medium's which has text in the center of the box over an black-overlay with the background-image behind it. </p> <p><a href="https://i.stack.imgur.com/dUt0I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dUt0I.png" alt="enter image description here"></a> </p> <p>However, I'm struggling with making the text INSIDE the div with the background-image NOT having opacity effect. </p> <pre><code>&lt;div class="blackBackground"&gt; &lt;div class="topicImage opacityFilter" style="background-image: url(https://images.unsplash.com/photo-1444401045234-4a2ab1f645c0?ixlib=rb-0.3.5&amp;q=80&amp;fm=jp&amp;crop=entropy&amp;s=4372cb6539c799269e343dd9456b7eb3);"&gt; &lt;p class="text-inside-image"&gt;Fashion&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Here's my CSS:</p> <pre><code>.blackBackground { background-color: black; z-index: -1; } .opacityFilter { opacity: 0.8; position: relative; } .margin-bottom-negsix { margin-bottom: -6px !important; } .topicImage { padding-bottom: 75%; background-position: 50% 50%; background-repeat: no-repeat; background-size: cover; margin: 0 auto; position: relative !important; height:150px; background-color: rgba(0, 0, 0, 0.8) !important; } .text-inside-image { position: absolute; top: 20%; left: 35%; color: white; font-size: 24px; font-weight: 500; z-index: 1; } </code></pre> <p>I've tried several solutions such as <a href="https://stackoverflow.com/questions/2401953/css-opaque-text-on-low-opacity-div">CSS - Opaque text on low opacity div?</a> and <a href="https://stackoverflow.com/questions/6446795/how-to-keep-text-opacity-100-when-its-parent-container-is-having-opacity-of-50">How to keep text opacity 100 when its parent container is having opacity of 50</a></p> <p>and a couple more, but no luck. </p> <p>My progress with my JSFiddle is here: <a href="https://jsfiddle.net/RohitTigga/akz5zng7/1/" rel="nofollow noreferrer">https://jsfiddle.net/RohitTigga/akz5zng7/1/</a></p> <p>Why is this occurring and how to fix it? </p>
2
How to keep multiple select in sync onChange using jquery
<p>I'm trying to figure out how to keep in sync two or more selects. I actually created several select elements (I'm not sure if this is the most accurate approach, if there's another way I'd be grateful if someone tells me). </p> <p>If I select <code>North America</code> in the first one, only the select with <code>id="north"</code> will show automatically and the others will remain hidden, if I change to <code>Central America</code>, the rest will change as well, showing only the select with <code>id="central"</code> and the rest hidden.</p> <p>This is what I got so far:</p> <pre><code>&lt;select id="continent"&gt; &lt;option value="1"&gt;North America&lt;/option&gt; &lt;option value="2"&gt;Central America&lt;/option&gt; &lt;option value="3"&gt;South America&lt;/option&gt; &lt;/select&gt; &lt;select id="north"&gt; &lt;option value="1"&gt;Canada&lt;/option&gt; &lt;option value="2"&gt;USA&lt;/option&gt; &lt;option value="3"&gt;Mexico&lt;/option&gt; &lt;/select&gt; &lt;select id="central"&gt; &lt;option value="1"&gt;Guatemala&lt;/option&gt; &lt;option value="2"&gt;Costa Rica&lt;/option&gt; &lt;option value="3"&gt;Nicaragua&lt;/option&gt; &lt;/select&gt; &lt;select id="south"&gt; &lt;option value="1"&gt;Brazil&lt;/option&gt; &lt;option value="2"&gt;Argentina&lt;/option&gt; &lt;option value="3"&gt;Chile&lt;/option&gt; &lt;/select&gt; </code></pre> <p>So far I've only got to sync two selects with same value:</p> <pre><code>$("#continent").change(function(){ $("#north").val($("#continent").val()) }); </code></pre> <p>However, this is far from what I need. Could anyone help me figure out the correct approach?</p> <p>Thanks in advance! </p>
2
Does extension messaging like chrome.runtime.sendMessage internally use JSON.stringify?
<blockquote> <p>A message can contain any valid JSON object (null, boolean, number, string, array, or object)</p> </blockquote> <p>The chrome extension specification indicates that message passed between background and content script can be a Javascript object, which means that we can pass a Javascript object without using JSON.stringify. Does that mean Chrome internally execute JSON.stringify before sending messages? If not, is there a performance gain if I just pass Javascript object without JSONification?</p>
2
PyMongo query not returning results although the same query returns results in mongoDB shell
<pre><code>import pymongo uri = 'mongodb://127.0.0.1:27017' client = pymongo.MongoClient(uri) db = client.TeamCity students = db.students.find({}) for student in students: print (student) </code></pre> <hr> <p>Python Result:</p> <h2>Blank</h2> <p>MongoDB: Results </p> <pre><code>db.students.find({}) { "_id" : ObjectId("5788483d0e5b9ea516d4b66c"), "name" : "Jose", "mark" : 99 } { "_id" : ObjectId("57884cb3f7edc1fd01c3511e"), "name" : "Jordan", "mark" : 100 } </code></pre> <hr> <pre><code>import pymongo uri = 'mongodb://127.0.0.1:27017' client = pymongo.MongoClient(uri) db = client.TeamCity students = db.students.find({}) print (students.count()) </code></pre> <hr> <p>Python Result:</p> <h2>0</h2> <p>mongoDB Results</p> <pre><code>db.students.find({}).count() 2 </code></pre> <hr> <p>What am I missing?</p> <p>For </p> <pre><code>import pymongo uri = 'mongodb://127.0.0.1:27017' client = pymongo.MongoClient(uri) db = client.TeamCity students = db.students.find({}) print (students) </code></pre> <p>Python Result : </p> <p>So I think it is able to connect to the db successfully but not returning results</p>
2
How to make full size horizontal scroll pages?
<p>The code below shows a few divs with the class name <code>page</code>, each having a height of <code>100vh</code> whilst displaying some text within.</p> <p>I want the scrolling to be horizontal rather than vertical, how do I get this to work?</p> <p>HTML:</p> <pre><code>&lt;div class="all"&gt; &lt;div class="page"&gt;Page 1&lt;/div&gt; &lt;div class="page"&gt;Page 2&lt;/div&gt; &lt;div class="page"&gt;Page 3&lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>.all { overflow-x: scroll; overflow-y: hidden; white-space: nowrap; } .page { height: 100vh; position: relative; display: inline-block } </code></pre>
2
Can't find gitlab-ci-multi-runner package
<p>I'm trying to install <code>gitlab-ci-multi-runner</code> on ElementaryOS <strong>Freya</strong>, but having no success.</p> <p>I've correctly follow the steps in official documentation:</p> <p><a href="https://gitlab.com/gitlab-org/gitlab-ci-multi-runner/blob/master/docs/install/linux-repository.md#install-using-official-gitlab-repositories" rel="nofollow">https://gitlab.com/gitlab-org/gitlab-ci-multi-runner/blob/master/docs/install/linux-repository.md#install-using-official-gitlab-repositories</a></p> <p>The answer always is:</p> <pre><code>luiz@kryptonita:~/node/my-nodejs-app$ sudo apt-get install gitlab-ci-multi-runner Reading package lists... Done Building dependency tree Reading state information... Done E: Unable to locate package gitlab-ci-multi-runner </code></pre> <p>To understand: I'm trying to set up a Runner to test a Node.js "Hello World". I'm studying this technology.</p> <p><strong>EDIT:</strong> Result of <code>cat /etc/apt/sources.list.d/runner_gitlab-ci-multi-runner.list</code></p> <pre><code># this file was generated by packages.gitlab.com for # the repository at https://packages.gitlab.com/runner/gitlab-ci-multi-runner deb https://packages.gitlab.com/runner/gitlab-ci-multi-runner/elementaryos/ freya main deb-src https://packages.gitlab.com/runner/gitlab-ci-multi-runner/elementaryos/ freya main </code></pre>
2
Rolling 12 months for Reporting Services
<p>I'm trying to get 12 months of rolling data for a SSRS report. I'm not sure whether it should go in my query, which is below, or in an expression on SSRS. The Field for the date and time is called <code>CALL_TIME</code> and is only featured in my WHERE clause. Its formatted like '2016-04-01 13:46:00'. </p> <p>Here is my query:</p> <pre><code>select Street Town Incidents IncidentType A IncidentType B IncidentType C FROM OPENQUERY (POSTGRESQL, Street Town Incidents IncidentType A IncidentType B IncidentType C FROM ( select COUNT(I.INC_NUM) as Incidents, COUNT(case when i.INC_TYPE = ''A'' THEN 1 end) "IncidentType A" COUNT(case when i.INC_TYPE = ''B'' THEN 1 end) "IncidentType B" COUNT(case when i.INC_TYPE = ''C'' THEN 1 end) "IncidentType C" FROM Table i WHERE I.CALL_TIME &gt;= ''2016-01-01'' GROUP BY i.INC_NUM ) i </code></pre> <p>RESULT</p> <pre><code>Street Incidents IncidentType A IncidentType B IncidentType C back lane 5 2 0 3 </code></pre>
2
Ruby 'cannot load such file --RMagick'
<p>I have a default installation of a jekyll project (created with <code>jekyll new sample</code>) and have included a plugin, <a href="https://github.com/mattvh/JekyllGalleryTag" rel="nofollow">JekyllGalleryTag</a>. </p> <p>The plugin depends upon ImageMagick and RMagick. I have installed ImageMagick and RMagick successfully on Xubuntu 14.04 using these commands. </p> <pre><code>sudo apt-get update sudo apt-get install imagemagick --fix-missing sudo apt-get install libmagickcore-dev sudo apt-get install libmagickwand-dev </code></pre> <p>ImageMagick commands are functional, eg <code>convert logo.gif logo.jpg</code> works as expected.</p> <p>I am running ruby-2.3.0 via rvm 1.27.0</p> <pre><code>gem install rmagick </code></pre> <p>RMagick installs without any error messages.</p> <p>JekyllGalleryTag needs galleries.rb put in /_plugins, which I have done. The first line of galleries.rb reads ...</p> <pre><code>require 'RMagick' </code></pre> <p>The plugin requires some code in _config.yml, which looks like this...</p> <pre><code>gallerytag: dir: images/galleries url: /images/galleries thumb_width: 150 thumb_height: 150 columns: 4 </code></pre> <p>My gallery images are located in /images/galleries/dig/</p> <p>I created an html file with some Liquid code to display the result. Here's the code in dig.html</p> <pre><code>--- layout: default title: Dig In Italy --- {% gallery dig %} dig/current001.jpg:: A caption goes here! {% endgallery %} </code></pre> <p>When I preview the site, with <code>jekyll serve</code>, I get this error message...</p> <pre><code>Configuration file: /mnt/hgfs/proj/practice/jekyll/sample/_config.yml Dependency Error: Yikes! It looks like you don't have /mnt/hgfs/proj/practice/jekyll/sample/_plugins/galleries.rb or one of its dependencies installed. In order to use Jekyll as currently configured, you'll need to install this gem. The full error message from Ruby is: 'cannot load such file -- RMagick' If you run into trouble, you can find helpful resources at http://jekyllrb.com/help/! jekyll 3.1.6 | Error: /mnt/hgfs/proj/practice/jekyll/sample/_plugins/galleries.rb </code></pre> <p>I am new to ruby, jekyll, and linux generally. I have googled and read and experimented for hours searching for a fix. The summarized sequence above is a result of all that research. I have installed every suggested library. </p> <p>Other fixes I tried and discarded were:</p> <ul> <li>including <code>require 'rubygems'</code> as the first line in galleries.rb (in addition to <code>require 'RMagick'</code>)</li> <li><code>require 'rmagick'</code> instead of <code>require 'RMagick'</code></li> <li>all 4 combinations of these require statements</li> </ul> <p>Additional wrinkles that may be relevant or not;</p> <ul> <li>Xubuntu 14.04 is running in VMware Player 7.1.2 </li> <li>The host OS is Windows 7 Pro 64 bit. </li> <li>My jekyll files are on the host NTFS filesystem, and I've been editing them with Notepad++ (a windows editor). The files are shared with the guest OS via VMware Player's Shared Folders option. This arrangement works fine for static sites and WordPress sites.</li> <li>I am using the terminal in the guest OS, Xubuntu, for all command line work. The Xubuntu OS contains the AMP stack, along with rvm and ruby.</li> <li>Though bundler is installed, I did not use it to install RMagick.</li> </ul> <p>How do I fix this?</p> <p><strong>UPDATE:</strong> </p> <p>I have verified that RMagick is working properly. I made a couple of small .rb scripts from the code on the RMagick Usage page. Two identical script sets were stored, one in the linux filesystem, and one in the NTFS filesystem. Both execute as expected without errors. This demonstrates that ruby works and can find and use RMagick, and that RMagick can find and use ImageMagick. And that the location of the files doesn't make a difference.</p> <p>Yet file location does matter. I copied identical sample jekyll projects so there was one on the linux filesystem one on NTFS. On linux <code>jekyll serve</code> executes but the plugin is not generating the thumbnail file version that jekyll is expecting. The build completes but with errors due to the missing thumbnail file. So the build wont complete when the files reside on NTFS, but will when the files are on linux.</p> <p>At this point my theories are 1) weirdness caused by VMware Player file sharing (but one that does not affect ruby &amp; gems consistently) or 2) something in the plugin code, which I don't have the skill to assess.</p> <p>Any comments, ideas? </p>
2
Leaflet with GitHub Pages - not rendering
<p>I have a simple webpage into which I have embedded a basic leaflet map. When I try to publish this via my GitHub Pages website, the leaflet map won't render (everything else is fine).</p> <p>GitHub Pages spec says it supports JS and this shouldn't be a problem as it's an API. I have tried to use a downloaded version of leaflet (.css and .js files uploaded to my gh-pages repository), but still nothing.</p> <p>Anyone have any ideas why this isn't working? Is this what GitHub Pages means when it says that it will host "static" webpages (no APIs, no JS interactivity)?</p>
2
Redux actions/reducers vs. directly setting state
<p>I'm new to Redux. I'm having trouble understanding the value of actions and reducers vs. components directly modifying the store. </p> <p>In Redux, your React components don't change the store directly. Instead they dispatch an action -- sort of like publishing a message. Then a reducer handles the action -- sort of like a message subscriber -- and changes the state (more precisely, creates a new state) in response. </p> <p>I feel like the pub/sub-like interaction adds layers of indirection that make it harder to understand what a component is actually doing -- why not just allow components to pass new state to the Redux store directly? Would it be a bad thing to inject something like <code>this.props.setReduxState</code> into a React component? </p> <p>I'm starting to understand the value of why the state itself needs to be immutable (related question -- <a href="https://stackoverflow.com/questions/33424157/isnt-redux-just-glorified-global-state">Isn&#39;t Redux just glorified global state?</a>), related to checking for updates to see which component props need to be updated in response to state changes. My question is the extra action/reducer layers vs. manipulating the store directly.</p>
2
HTML table CSS design for a "calendar"
<p>I'm trying to create a "calendar" in a HTML Table.</p> <p>Here is the code idea:</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;21/04/2016&lt;/th&gt; &lt;th&gt;17/08/2016&lt;/th&gt; &lt;th&gt;22/10/2016&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;11:00&lt;/th&gt; &lt;th&gt;13:00&lt;/th&gt; &lt;th&gt;18:00&lt;/th&gt; &lt;th&gt;22:00&lt;/th&gt; &lt;th&gt;15:00&lt;/th&gt; &lt;th&gt;08:00&lt;/th&gt; &lt;th&gt;19:00&lt;/th&gt; &lt;th&gt;23:50&lt;/th&gt; &lt;th&gt;10:00&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; &lt;input type="checkbox" /&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="checkbox" /&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="checkbox" /&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="checkbox" /&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="checkbox" /&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="checkbox" /&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="checkbox" /&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="checkbox" /&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="checkbox" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; </code></pre> <p></p> <p>Here is the REAL idea:</p> <p><a href="https://i.stack.imgur.com/lHveU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lHveU.png" alt="enter image description here"></a></p> <p>1 Date can have 3 time</p> <p>The user is then able to select if he's available for any date / time</p> <p>The problem is, since we add another table row for the times, they won't stay in date's column.</p> <p>I guess some CSS can fix this.</p> <p>But I have NO IDEA how it can be done, any hint ?</p>
2
Resizing JFrame to fit resized JPanel
<p>I am pretty new with JPanel and JFrame and probably not working with them the way I should. I'm trying to create Pong game and after creating JFrame and adding JPanel to it, I'm able to resize my JPanel but I don't know how to resize my JFrame to fit it. Game class extends JPanel.</p> <p>main:</p> <pre><code> public static void main(String[] args) throws InterruptedException { int height = 500, width =(int) (height*1.56); //height = 500, width = 780; JFrame frame = new JFrame("Pong"); Game game = new Game(); frame.add(game); frame.setVisible(true); game.setSize(width, height); System.out.println(game.getHeight()); System.out.println(game.getWidth()); game.setBackground(Color.BLACK); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); System.out.println(frame.getHeight()); System.out.println(frame.getWidth()); } </code></pre> <p>output:</p> <pre><code>500 780 39 136 </code></pre> <p>The output should be somthing like:</p> <pre><code>500 780 *above* 500 *above* 780 </code></pre> <p>EDIT:</p> <pre><code> public static void main(String[] args) throws InterruptedException { int height = 500, width =(int) (height*1.56); //height = 500, width = 780; JFrame frame = new JFrame("Pong"); Game game = new Game(); frame.add(game); frame.setVisible(true); game.setPreferredSize(new Dimension(width, height)); frame.pack(); System.out.println(game.getHeight()); System.out.println(game.getWidth()); game.setBackground(Color.BLACK); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); System.out.println(frame.getHeight()); System.out.println(frame.getWidth()); } </code></pre> <p>Changing the setSize to setPreferredSize and then call pack() for the JFrame fixed it all.</p>
2
Clean Code Book by Robert Cecil Martin
<p>I know this has been asked before but I did not fully understand the answer nor did I feel the question was exactly the same as this one.</p> <p>In the book Clean Code Book by Robert Cecil Martin, He suggests with regards to methods you should...</p> <ul> <li>Prefer to not pass any parameters</li> <li>If you must pass paramters then pass only one.</li> <li>An only pass more than this under rare circumstances.</li> </ul> <p>This has me confused...</p> <p>So based on this which is correct?</p> <p>this class...</p> <pre><code> class FourNumberAdder { public int Num1 { get; } public int Num2 { get; } public int Num3 { get; } public int Num4 { get; } public FourNumberAdder(int n1, int n2,int n3,int n4 ) { this.Num1 = n1; this.Num2 = n2; this.Num3 = n3; this.Num4 = n4; } } </code></pre> <p>with this...</p> <pre><code>FourNumberAdder FNA = new FourNumberAdder(1,2,3,4); </code></pre> <p>Or, This class...</p> <pre><code>class FourNumberAdder { public int Num1 { get; set; } public int Num2 { get; set; } public int Num3 { get; set; } public int Num4 { get; set; } } </code></pre> <p>with this...</p> <pre><code>public void go() { FourNumberAdder FNA = new FourNumberAdder(); FNA.Num1 = 1; FNA.Num2 = 2; FNA.Num3 = 3; FNA.Num4 = 4; } </code></pre> <p>or these 2 classes...</p> <pre><code>class FourNumberAdder { public int Num1 { get; set; } public int Num2 { get; set; } public int Num3 { get; set; } public int Num4 { get; set; } public FourNumberAdder (FourNumbers fn) { this.Num1 = fn.Num1; this.Num2 = fn.Num2; this.Num3 = fn.Num3; this.Num4 = fn.Num4; } } class FourNumbers { public int Num1 { get; set; } public int Num2 { get; set; } public int Num3 { get; set; } public int Num4 { get; set; } } </code></pre> <p>with this...</p> <pre><code>FourNumbers fn = new FourNumbers(); fn.Num1 = 1; fn.Num2 = 2; fn.Num3 = 3; fn.Num4 = 4; FourNumberAdder FNA = new FourNumberAdder(fn); </code></pre> <p>or something else? Please note I thought the last option would be right as it 'bundles up' the 4 parameters in to a new class, but then you end up with the same problem with that class as you have to either pass all the parameters in individually or access them directly via there properties. </p> <p>Hope this is clear.</p>
2
Breaking SOLID Principles in multiple implementation of an Interface
<p>I am facing a problem with dependency inversion in a <code>factory</code> method and it is also breaking Open Closed principle. My code looks like below codes</p> <pre><code> public interface IWriter { void WriteToStorage(string data); } public class FileWriter : IWriter { public void WriteToStorage(string data) { //write to file } } public class DBWriter : IWriter { public void WriteToStorage(string data) { //write to DB } } </code></pre> <p>Now I an using a factory class to solve the object creation. It look like below code</p> <pre><code>public interface IFactory { IWriter GetType(string outputType); } public class Factory : IFactory { public IWriter GetType(string outputType) { IWriter writer = null; if (outputType.Equels("db")) { writer = new FileWriter(); } else if (outputType.Equels("db")) { writer = new DBWriter(); } } } </code></pre> <p>Now the problem is the <code>Factory</code> class is breaking <strong>Open closed principle</strong> so it also breakes <strong>Dependency Inversion Principle</strong></p> <p>And then </p> <pre><code>public interface ISaveDataFlow { void SaveData(string data, string outputType); } public class SaveDataFlow : ISaveDataFlow { private IFactory _writerFactory = null; public SaveDataFlow(IFactory writerFactory) { _writerFactory = writerFactory; } public void SaveData(string data, string outputType) { IWriter writer = _writerFactory.GetType(outputType); writer.WriteToStorage(data); } } </code></pre> <p>As the above factory class is breaking the dependency inversion I remove the <code>Factory</code> class and change the <code>SaveDataFlow</code> class like below</p> <pre><code>public class SaveDataFlow : ISaveDataFlow { private IWriter _dbWriter = null; private IWriter _fileWriter = null; public SaveDataFlow([Dependency("DB")]IWriter dbWriter, [Dependency("FILE")]IWriter fileWriter) { _dbWriter = dbWriter; _fileWriter = fileWriter; } public void SaveData(string data, string outputType) { if (outputType.Equals("DB")) { _dbWriter.WriteToStorage(data); } else if (outputType.Equals("FILE")) { _fileWriter.WriteToStorage(data); } } } </code></pre> <p>And resolved those dependencies using Unity Framework</p> <pre><code>container.RegisterType&lt;IWriter, DBWriter&gt;("DB"); container.RegisterType&lt;IWriter, FileWriter&gt;("FILE"); </code></pre> <p>Yet eventually I am ending up breaking <strong>Open Closed Principle</strong>. I need a better design/solution to solve such a problem yet I must follow SOLID Principles.</p>
2
Button text color isn't changing
<p>I'm trying to change md-button text color using accent Palette color using Angular material 1.0.9 version. But it is not changing button text color. If i'm using latest beta it got fix. But i'm not going to production with this unstable version. </p> <p>Code: </p> <pre><code>&lt;md-toolbar class="md-primary md-hue-1"&gt; &lt;div class="md-toolbar-tools"&gt; &lt;md-button class="md-accent"&gt;My Profile&lt;/md-button&gt; &lt;/div&gt; &lt;/md-toolbar&gt; </code></pre> <p>Below are the plnkr urls:</p> <p>Angular material 1-0-9 <a href="http://plnkr.co/edit/AB9zScM1aWw97WQn9nmo" rel="nofollow">Plnkr URL</a></p> <p>Angular material Latest beta <a href="http://plnkr.co/edit/1hO0TZDV5pMFrZ5Hl8bN" rel="nofollow">Plnkr URL</a></p> <p>Can anyone suggest a fix?</p>
2
What triggers Azure Functions to reload the referenced assemblies?
<p>I've been referencing external assemblies trying to work around the issue noted here: <a href="https://stackoverflow.com/questions/38314334/how-do-i-reference-a-portable-net-assembly-from-an-azure-cloud-function">Azure Function Cannot Load Portable Assembly</a>. However, often my function does not seem to reflect the changes made to the functionName\bin assemblies. I've intentionally referenced the wrong assemblies, and then reran the function. I experience no change to what is logged (and I'm logging exceptions). </p> <p>How do I force a complete reload of the Azure function? Can I somehow see what Azure functions has as its "loaded" assemblies?</p>
2
How to enable pointer events
<p>I noticed that in my angular app the property </p> <pre><code>window.navigator.pointerEnabled </code></pre> <p>returns <code>true</code></p> <p>Now, because I would like to do some testing which involves <strong>pointer-events</strong> inside a <code>jsfiddle</code>.net I noticed that these events are not present there. This probably has something to do with the fact that here the <code>pointerEnabled</code> property is <code>undefined</code>.</p> <p>My question is, how is this property controlled, how can I enabled it?</p>
2
How do I get two different Django projects to communicate?
<p>Like the title says, I have two Django projects. Unlike other SO questions, these are totally different projects, meaning they do not share database, hosting environment, domain name, etc. This is what I want and need, total decoupling between the projects.</p> <p>However, they have certain models (let's say UserProfile) from one app which I required in both projects. Also, I would like to have only one of the projects to allow sign-in, log-in, forgot/reset password functionality.</p> <p>My idea is to have RESTful APIs for both of them, but I still have some questions about how to correctly achieve this:</p> <ul> <li>what do I do with the duplicate models to keep them in-sync? Do I create endpoints which can be modified by the other project? </li> <li>how do I proceed with single-sign-on ? Do I need a specialised server for this? I would also like to take advantage of the tools provided by Django, such as having my current user on my request object.</li> </ul> <p>I have yet to find a good tutorial or some detailed explanations as to how to achieve all of these, so if anyone has any resources, please let me know.</p> <p>If my question is not clear enough, please let me know with a comment.</p> <p>Thank you.</p>
2
Toggle button style with text and image
<p>I have a next style:</p> <pre><code>&lt;Style x:Key="Style_MainButtons" TargetType="ToggleButton"&gt; &lt;Setter Property="Width" Value="110" /&gt; &lt;Setter Property="Height" Value="110" /&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type ToggleButton}"&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;RowDefinition /&gt; &lt;/Grid.RowDefinitions&gt; &lt;TextBlock x:Name="Text" HorizontalAlignment="Center" /&gt; &lt;Image x:Name="Image" Grid.Row="1" /&gt; &lt;/Grid&gt; &lt;ControlTemplate.Triggers&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>Because there are few toggle buttons using this style and each have different text and image, so how can I call “TextBlock” and “Image” from style in the next code? </p> <pre><code>&lt;ToggleButton x:Name="btnHorizontal" Style="{StaticResource Style_MainButtons}" Grid.Column="0" Grid.Row="1" Checked ="SetVersion" Unchecked ="SetVersion" IsChecked="True" &gt; &lt;/ToggleButton&gt; </code></pre>
2
Prestashop multi stores different servers
<p>Is it possible to do (read is there viable solution for) Prestashop multiple front ends in different servers ? Like shop1.com served from 1.1.1.1 and shop2.com from 1.1.1.2 (different servers), yet having same backend in server 1.1.1.3 OR in one of the storefront server ?</p> <p>I have googled yes, but have not found any good solution to this.</p>
2
Passing null values while using between in a query
<p>I'm writing a stored procedure in T-SQL to select records from the following table:</p> <pre><code>CREATE TABLE [dbo].[PHM_News_Entry] ( [NewsID] [int] IDENTITY(1,1) NOT NULL, [NewsTitle] [varchar](200) NULL, [NewsDate] [datetime] NULL, [NewsDescription] [nvarchar](max) NULL, [NewsDateEntry] [datetime] NULL, [NewAuthor] [varchar](200) NULL, [NewModificationDate] [datetime] NULL, [NewModifiedBy] [varchar](100) NULL, [Status] [varchar](50) NULL, [NewsAttatchmentPath] [nvarchar](max) NULL, [NewsImagePath] [nvarchar](max) NULL, ) </code></pre> <p>The stored procedure is as follows:</p> <pre><code>CREATE PROCEDURE Select_News @NewsTitle VARCHAR(200), @FromDate DATE, @ToDate DATE AS BEGIN SET NOCOUNT ON; SELECT * FROM PHM_News_Entry WHERE (NewsTitle LIKE '%'+@NewsTitle+'%' OR @NewsTitle IS NULL) AND NewsDate BETWEEN @FromDate AND @ToDate OR NewsDate IS NULL END </code></pre> <p>The parameters viz., @NewsTitle, @FromDate and @ToDate can either have values or be NULL. If all 3 parameters or NULL, there should be no record selected but if one of them has non-null value, it should select one or more matching records.</p> <p>If I pass NULL to all 3 parameters, it works as expected i.e., doesn't select any records but it's not working the other way i.e., if one of them one or two of them have non-null values.</p> <p>Please help me write the correct query for this case.</p> <p>Thanks and regards,</p> <p>Shyam Singh</p>
2
Bypass certificate validation with SSLSocketFactory
<p>I am building a client side application which will connect to a third party server through a soap message. I am using jax-ws 2.1.9 and jdk 1.6_18 running on JBoss 4.2.3.</p> <p>The problem itself is that the server, which is configured for testing purposes only, is returning an expired certificate, and, therefore, my application is throwing the exception below.</p> <pre><code>13:43:26,738 ERROR [STDERR] Caused by: javax.xml.ws.WebServiceException: java.io.IOException: Could not transmit message 13:43:26,739 ERROR [STDERR] at org.jboss.ws.core.jaxws.client.ClientImpl.handleRemoteException(ClientImpl.java:404) 13:43:26,739 ERROR [STDERR] at org.jboss.ws.core.jaxws.client.ClientImpl.invoke(ClientImpl.java:314) 13:43:26,739 ERROR [STDERR] at org.jboss.ws.core.jaxws.client.ClientProxy.invoke(ClientProxy.java:172) 13:43:26,739 ERROR [STDERR] at org.jboss.ws.core.jaxws.client.ClientProxy.invoke(ClientProxy.java:152) 13:43:26,739 ERROR [STDERR] at $Proxy724.solicitarBaixaOperation(Unknown Source) 13:43:26,740 ERROR [STDERR] at com.totvs.foundation.exchange.connector.ptu.implementation.v70_batch.InvoiceWriteOffConnector.process(InvoiceWriteOffConnector.java:91) 13:43:26,740 ERROR [STDERR] ... 98 more 13:43:26,740 ERROR [STDERR] Caused by: java.io.IOException: Could not transmit message 13:43:26,740 ERROR [STDERR] at org.jboss.ws.core.client.HTTPRemotingConnection.invoke(HTTPRemotingConnection.java:255) 13:43:26,740 ERROR [STDERR] at org.jboss.ws.core.client.SOAPProtocolConnectionHTTP.invoke(SOAPProtocolConnectionHTTP.java:73) 13:43:26,741 ERROR [STDERR] at org.jboss.ws.core.CommonClient.invoke(CommonClient.java:339) 13:43:26,741 ERROR [STDERR] at org.jboss.ws.core.jaxws.client.ClientImpl.invoke(ClientImpl.java:302) 13:43:26,741 ERROR [STDERR] ... 102 more 13:43:26,741 ERROR [STDERR] Caused by: org.jboss.remoting.CannotConnectException: Can not connect http client invoker. java.security.cert.CertificateExpiredException: NotAfter: Thu Sep 11 09:35:00 GMT-03:00 2014. 13:43:26,741 ERROR [STDERR] at org.jboss.remoting.transport.http.HTTPClientInvoker.useHttpURLConnection(HTTPClientInvoker.java:348) 13:43:26,742 ERROR [STDERR] at org.jboss.remoting.transport.http.HTTPClientInvoker.transport(HTTPClientInvoker.java:137) 13:43:26,742 ERROR [STDERR] at org.jboss.remoting.MicroRemoteClientInvoker.invoke(MicroRemoteClientInvoker.java:122) 13:43:26,742 ERROR [STDERR] at org.jboss.remoting.Client.invoke(Client.java:1634) 13:43:26,742 ERROR [STDERR] at org.jboss.remoting.Client.invoke(Client.java:548) 13:43:26,742 ERROR [STDERR] at org.jboss.ws.core.client.HTTPRemotingConnection.invoke(HTTPRemotingConnection.java:233) 13:43:26,743 ERROR [STDERR] ... 105 more 13:43:26,743 ERROR [STDERR] Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateExpiredException: NotAfter: Thu Sep 11 09:35:00 GMT-03:00 2014 13:43:26,743 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174) 13:43:26,743 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1611) 13:43:26,744 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:187) 13:43:26,744 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:181) 13:43:26,744 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1035) 13:43:26,744 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:124) 13:43:26,744 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:516) 13:43:26,745 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:454) 13:43:26,745 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:884) 13:43:26,745 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1112) 13:43:26,745 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1139) 13:43:26,745 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1123) 13:43:26,746 ERROR [STDERR] at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:434) 13:43:26,746 ERROR [STDERR] at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:166) 13:43:26,746 ERROR [STDERR] at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:904) 13:43:26,746 ERROR [STDERR] at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230) 13:43:26,746 ERROR [STDERR] at org.jboss.remoting.transport.http.HTTPClientInvoker.useHttpURLConnection(HTTPClientInvoker.java:277) 13:43:26,747 ERROR [STDERR] ... 110 more 13:43:26,747 ERROR [STDERR] Caused by: java.security.cert.CertificateExpiredException: NotAfter: Thu Sep 11 09:35:00 GMT-03:00 2014 13:43:26,747 ERROR [STDERR] at sun.security.x509.CertificateValidity.valid(CertificateValidity.java:256) 13:43:26,747 ERROR [STDERR] at sun.security.x509.X509CertImpl.checkValidity(X509CertImpl.java:570) 13:43:26,747 ERROR [STDERR] at sun.security.validator.SimpleValidator.engineValidate(SimpleValidator.java:134) 13:43:26,748 ERROR [STDERR] at sun.security.validator.Validator.validate(Validator.java:218) 13:43:26,748 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126) 13:43:26,748 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209) 13:43:26,748 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:249) 13:43:26,748 ERROR [STDERR] at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1014) 13:43:26,749 ERROR [STDERR] ... 122 more </code></pre> <p>So, for testing purposes, I am trying to bypass those validations. I found some blogs and posts which all drove me to the code snippet below.</p> <pre><code>/** Inner class for set a blind TrustManager **/ public class BlindTrustManager implements X509TrustManager { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } /*Get the port instance of the web service interface created by JAX-WS*/ SolicitarBaixaPortType port = InvoiceWriteOffWebService.getInstance(serviceName, wsdlLocation); /*set the socket factory*/ SSLContext ctx = SSLContext.getInstance("TLSv1"); ctx.init(null, new TrustManager[] { new BlindTrustManager() }, null); SSLSocketFactory sslSocketFactory = ctx.getSocketFactory(); ((BindingProvider) port).getRequestContext().put(BindingProviderProperties.SSL_SOCKET_FACTORY, sslSocketFactory); ((BindingProvider) port).getRequestContext().put(com.sun.xml.internal.ws.client.BindingProviderProperties.SSL_SOCKET_FACTORY, sslSocketFactory); /*message is the Object Jax generated*/ response = port.solicitarBaixaOperation(message); </code></pre> <p>Although I had set the <em>SSLSocketFactory</em> the <em>CertificateExpiredException</em> is still be throwing. So it raises the following questions:</p> <ol> <li>Am I doing it right?</li> <li>How can I be sure that the connection sees my <em>BlindTrustManager</em> class? For I can't see any mention of it on the log.</li> <li>How can I be sure of the right String that I need to pass to my <em>BindingProvider</em> request context for it can find my <em>SSLSocketFactory</em>?</li> <li>Is there some other configuration that I must do in JBoss?</li> </ol> <p>Thanks</p>
2
Ubuntu mysql stops working
<p>I am have vps setup with ubuntu 14 server. I have lamp stack installed. Everything works perfect but mysql server stops frequently and i have to restart it manually. Here is my my.cnf mysql config file. </p> <pre><code># The MySQL database server configuration file. # # You can copy this to one of: # - "/etc/mysql/my.cnf" to set global options, # - "~/.my.cnf" to set user-specific options. # # One can use all long options that the program supports. # Run program with --help to get a list of available options and with # --print-defaults to see which it would actually understand and use. # # For explanations see # http://dev.mysql.com/doc/mysql/en/server-system-variables.html # This will be passed to all mysql clients # It has been reported that passwords should be enclosed with ticks/quotes # escpecially if they contain "#" chars... # Remember to edit /etc/mysql/debian.cnf when changing the socket location. [client] port = 3306 socket = /var/run/mysqld/mysqld.sock # Here is entries for some specific programs # The following values assume you have at least 32M ram # This was formally known as [safe_mysqld]. Both versions are currently parsed. [mysqld_safe] socket = /var/run/mysqld/mysqld.sock nice = 0 [mysqld] # # * Basic Settings # user = mysql pid-file = /var/run/mysqld/mysqld.pid socket = /var/run/mysqld/mysqld.sock port = 3306 basedir = /usr datadir = /var/lib/mysql tmpdir = /tmp lc-messages-dir = /usr/share/mysql skip-external-locking # # Instead of skip-networking the default is now to listen only on # localhost which is more compatible and is not less secure. bind-address = 127.0.0.1 # # * Fine Tuning # key_buffer = 16M max_allowed_packet = 16M thread_stack = 192K thread_cache_size = 8 # This replaces the startup script and checks MyISAM tables if needed # the first time they are touched myisam-recover = BACKUP #max_connections = 100 #table_cache = 64 #thread_concurrency = 10 # # * Query Cache Configuration # query_cache_limit = 1M query_cache_size = 16M # # * Logging and Replication # # Both location gets rotated by the cronjob. # Be aware that this log type is a performance killer. # As of 5.1 you can enable the log at runtime! #general_log_file = /var/log/mysql/mysql.log #general_log = 1 # # Error log - should be very few entries. # log_error = /var/log/mysql/error.log # # Here you can see queries with especially long duration #log_slow_queries = /var/log/mysql/mysql-slow.log #long_query_time = 2 #log-queries-not-using-indexes # # The following can be used as easy to replay backup logs or for replication. # note: if you are setting up a replication slave, see README.Debian about # other settings you may need to change. #server-id = 1 #log_bin = /var/log/mysql/mysql-bin.log expire_logs_days = 10 max_binlog_size = 100M #binlog_do_db = include_database_name #binlog_ignore_db = include_database_name # # * InnoDB # # InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/. # Read the manual for more InnoDB related options. There are many! # # * Security Features # # Read the manual, too, if you want chroot! # chroot = /var/lib/mysql/ # # For generating SSL certificates I recommend the OpenSSL GUI "tinyca". # # ssl-ca=/etc/mysql/cacert.pem # ssl-cert=/etc/mysql/server-cert.pem # ssl-key=/etc/mysql/server-key.pem [mysqldump] quick quote-names max_allowed_packet = 16M [mysql] #no-auto-rehash # faster start of mysql but no tab completition [isamchk] key_buffer = 16M # # * IMPORTANT: Additional settings that can override those from this file! # The files must end with '.cnf', otherwise they'll be ignored. # !includedir /etc/mysql/conf.d/ </code></pre> <p>And following is my mysqltuner output. </p> <pre><code>-------- General Statistics ------------------------------------------------ [--] Skipped version check for MySQLTuner script [OK] Currently running supported MySQL version 5.5.49-0ubuntu0.14.04.1 [OK] Operating on 64-bit architecture -------- Storage Engine Statistics ------------------------------------------- [--] Status: +Archive -BDB -Federated +InnoDB -ISAM -NDBCluster [--] Data in MyISAM tables: 38K (Tables: 34) [--] Data in PERFORMANCE_SCHEMA tables: 0B (Tables: 17) [--] Data in InnoDB tables: 11M (Tables: 101) [!!] Total fragmented tables: 101 -------- Security Recommendations ------------------------------------------- [OK] All database users have passwords assigned -------- Performance Metrics ------------------------------------------------- [--] Up for: 1h 13m 27s (2K q [0.464 qps], 130 conn, TX: 5M, RX: 332K) [--] Reads / Writes: 81% / 19% [--] Total buffers: 192.0M global + 2.7M per thread (151 max threads) [!!] Maximum possible memory usage: 597.8M (121% of installed RAM) [OK] Slow queries: 0% (0/2K) [OK] Highest usage of available connections: 7% (12/151) [OK] Key buffer size / total MyISAM indexes: 16.0M/196.0K [OK] Query cache efficiency: 33.9% (493 cached / 1K selects) [OK] Query cache prunes per day: 0 [OK] Sorts requiring temporary tables: 0% (0 temp sorts / 77 sorts) [!!] Temporary tables created on disk: 33% (166 on disk / 498 total) [OK] Thread cache hit rate: 90% (12 created / 130 connections) [OK] Table cache hit rate: 94% (178 open / 189 opened) [OK] Open file limit used: 11% (116/1K) [OK] Table locks acquired immediately: 100% (1K immediate / 1K locks) [OK] InnoDB data size / buffer pool: 11.9M/128.0M -------- Recommendations ----------------------------------------------------- General recommendations: Run OPTIMIZE TABLE to defragment tables for better performance MySQL started within last 24 hours - recommendations may be inaccurate Reduce your overall MySQL memory footprint for system stability Enable the slow query log to troubleshoot bad queries When making adjustments, make tmp_table_size/max_heap_table_size equal Reduce your SELECT DISTINCT queries without LIMIT clauses Variables to adjust: *** MySQL's maximum memory usage is dangerously high *** *** Add RAM before increasing MySQL buffer variables *** tmp_table_size (&gt; 16M) max_heap_table_size (&gt; 16M) </code></pre> <p>And here is my memory uses </p> <pre><code>Every 5.0s: free -m Sun Jul 3 03:12:12 2016 total used free shared buffers cached </code></pre> <p>Mem: 490 476 13 64 10 183 -/+ buffers/cache: 281 208 Swap: 0 0 0</p> <p>What can be wrong here. Is there some misconfig on my my.cnf or something else is killing mysql. Please help me to find the issue.</p>
2
Display an alert when using AJAX
<p>I am two files, a PHP file and another file made of javascript and HTML.</p> <p>PHP file :</p> <pre><code>&lt;?php session_start(); //start session $_SESSION['data'] = "The content should be displayed as alert in the JS file"; </code></pre> <p>JS/HTML File:</p> <pre><code>&lt;script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;form class="form-item" id="idForm"&gt; &lt;input type="hidden" name="product_code" value="prince"/&gt; &lt;button id="btn_add" type="submit"&gt;Add to Cart&lt;/button&gt; &lt;/form&gt; &lt;script&gt; $(function(){ $("#idForm").submit(function(e) { var url = "test2.php"; $.ajax({ type: "POST", url: url, data: $("#idForm").serialize(), success: function() { alert(/*The content of the session in the php file should be display here*/); // show response from the php script. } }); e.preventDefault(); }); }); &lt;/script&gt; </code></pre> <p>In the PHP file, I have a session <code>$_SESSION['data']</code>. All I want to do, it is to be able display the content of that session in <code>alert()</code> after <code>making the ajax request to test2.php</code></p>
2