title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
How to store a pointer in a custom embedded Python object
<p>I have created a custom Python type in C as per the tutorial <a href="https://docs.python.org/2.7/extending/newtypes.html#the-basics" rel="nofollow noreferrer">https://docs.python.org/2.7/extending/newtypes.html#the-basics</a>. In my C I receive a pointer to a struct, I want to be able to get and set the values in the struct from Python without taking a copy of it. I.e.</p> <pre><code>a = myObject.x() # gets the x value in the struct. </code></pre> <p>or</p> <pre><code>myObject.x(255) # sets the x value in the struct. </code></pre> <p>However I cannot see how to store the pointer in the python object.</p> <p>My current object definition is currently just the basic object implementation from the python website.</p> <pre><code>typedef struct { PyObject_HEAD myStruct *s; } KeyObject; static PyTypeObject KeyType = { PyVarObject_HEAD_INIT(NULL, 0) "ckb.Key", /* tp_name */ sizeof(KeyObject), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "Key objects", /* tp_doc */ }; static PyMethodDef key_methods[] = { {NULL} /* Sentinel */ }; </code></pre>
0
1,029
MySQL Query Within JavaScript
<p>I am working on a form whereby JavaScript is used to add another line item. The purpose is to add line items to an invoice. I have successfully got this to work ok when using text boxes in my form, but am stuck on how to get this to work with a dropdown box that makes a call to mysql to get the dropdown box data.</p> <p>Here is what I have.</p> <pre><code> &lt;?php include $_SERVER['DOCUMENT_ROOT']."/connect.php"; include $_SERVER['DOCUMENT_ROOT']."/includes/header.php"; ?&gt; &lt;script type="text/javascript"&gt; var counter = 1; function addInput(divName){ var newdiv = document.createElement('div'); newdiv.innerHTML = "Entry " + (counter + 1) + " &lt;br&gt;&lt;select name='myInputs[]'&gt;&lt;?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "&lt;option value=\"".$row['name']."\"&gt;".$row['name']."&lt;/option&gt;";} ?&gt;&lt;/select&gt;"; document.getElementById(divName).appendChild(newdiv); } &lt;/script&gt; &lt;form method="POST"&gt; &lt;div id="dynamicInput"&gt; Entry 1&lt;br&gt;&lt;select name="myInputs[]"&gt;&lt;?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "&lt;option value=\"".$row['name']."\"&gt;".$row['name']."&lt;/option&gt;";} ?&gt;&lt;/select&gt; &lt;/div&gt; &lt;input type="button" value="Add another text input" onClick="addInput('dynamicInput');"&gt; &lt;/form&gt; </code></pre> <p>So here is some info on what is going on. Right now, the JavaScript code above shows the MySQL query in it. This kills the add line item functionality. If I simply remove the query but leave the other php in, the add line item begins to work again, but of course there is no data in the drop down.</p> <p>In the form itself, it gets the first line item from the database without using javascript and this is working ok.</p> <p>I feel like I am getting close, but don't know where to go from here.</p> <p>Thanks in advance.</p> <p>EDIT: Thanks to Nick, I got this working. Here is the code.</p> <pre><code> &lt;?php include $_SERVER['DOCUMENT_ROOT']."/connect.php"; include $_SERVER['DOCUMENT_ROOT']."/includes/header.php"; ?&gt; &lt;script type="text/javascript"&gt; var counter = 1; function addInput(div){ xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200){ var newdiv = document.createElement('div'); newdiv.innerHTML = "Entry " + (++counter) + " &lt;br&gt;&lt;select name='myInputs[]'&gt;" + xmlhttp.responseText + "&lt;/select&gt;"; } document.getElementById(div).appendChild(newdiv); } xmlhttp.open("GET", "update_text.php", false); xmlhttp.send(); } &lt;/script&gt; &lt;form method="POST"&gt; &lt;div id="dynamicInput"&gt; Entry 1&lt;br&gt;&lt;select name="myInputs[]"&gt;&lt;?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "&lt;option value=\"".$row['name']."\"&gt;".$row['name']."&lt;/option&gt;";} ?&gt;&lt;/select&gt; &lt;/div&gt; &lt;input type="button" value="Add" onClick="addInput('dynamicInput');"&gt; &lt;/form&gt; </code></pre> <p>Then the update_text.php</p> <pre><code> &lt;?php include $_SERVER['DOCUMENT_ROOT']."/connect.php"; $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "&lt;option value=\"".$row['name']."\"&gt;".$row['name']."&lt;/option&gt;"; } ?&gt; </code></pre> <p>And here is my php post into the database which is not working for the javascript add line item, only for the original entry that is created from the form. (I have other fields besides the dropdown).</p> <pre><code> &lt;?php include $_SERVER['DOCUMENT_ROOT']."/connect.php"; $company = mysql_real_escape_string($_POST['company']); foreach($_POST['item'] as $i =&gt; $item) { $item = mysql_real_escape_string($item); $quantity = mysql_real_escape_string($_POST['quantity'][$i]); mysql_query("INSERT INTO invoice (company, item, quantity) VALUES ('$company', '".$item."', '".$quantity."') ") or die(mysql_error()); } echo "&lt;br&gt;&lt;font color=\"green\"&gt;&lt;b&gt;Invoice added&lt;/b&gt;&lt;/font&gt;"; ?&gt; </code></pre> <p>Thanks, please let me know if I can clean this up better.</p>
0
1,637
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8") is NOT working
<p>I have the following method to write an XMLDom to a stream:</p> <pre><code>public void writeToOutputStream(Document fDoc, OutputStream out) throws Exception { fDoc.setXmlStandalone(true); DOMSource docSource = new DOMSource(fDoc); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "no"); transformer.transform(docSource, new StreamResult(out)); } </code></pre> <p>I am testing some other XML functionality, and this is just the method that I use to write to a file. My test program generates 33 test cases where files are written out. 28 of them have the following header:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;... </code></pre> <p>But for some reason, 1 of the test cases now produce:</p> <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;... </code></pre> <p>And four more produce:</p> <pre><code>&lt;?xml version="1.0" encoding="Windows-1252"?&gt;... </code></pre> <p>As you can clearly see, I am setting ENCODING output key to UTF-8. These tests used to work on an earlier version of Java. I have not run the tests in a while (more than a year) but running today on "Java(TM) SE Runtime Environment (build 1.6.0_22-b04)" I get this funny behavior.</p> <p>I have verified that the documents causing the problem were read from files that originally had those encoding. It seems that the new versions of the libraries are attempting to preserve the encoding of the source file that was read. But that is not what I want ... I really do want the output to be in UTF-8. </p> <p>Does anyone know of any other factor that might cause the transformer to ignore the UTF-8 encoding setting? Is there anything else that has to be set on the document to say to forget the encoding of the file that was originally read?</p> <p>UPDATE:</p> <p>I checked out the same project out on another machine, built and ran the tests there. On that machine all the tests pass! All the files have "UTF-8" in their header. That machine has "Java(TM) SE Runtime Environment (build 1.6.0_29-b11)" Both machines are running Windows 7. On the new machine that works correctly, jdk1.5.0_11 is used to make the build, but on the old machine jdk1.6.0_26 is used to make the build. The libraries used for both builds are exactly the same. Can it be a JDK 1.6 incompatibility with 1.5 at build time?</p> <p>UPDATE:</p> <p>After 4.5 years, the Java library is still broken, but due to the suggestion by Vyrx below, I finally have a proper solution!</p> <pre><code>public void writeToOutputStream(Document fDoc, OutputStream out) throws Exception { fDoc.setXmlStandalone(true); DOMSource docSource = new DOMSource(fDoc); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "no"); out.write("&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;".getBytes("UTF-8")); transformer.transform(docSource, new StreamResult(out)); } </code></pre> <p>The solution is to disable the writing of the header, and to write the correct header just before serializing the XML to the output steam. Lame, but it produces the correct results. Tests broken over 4 years ago are now running again!</p>
0
1,119
missing messages when reading with non-blocking udp
<p>I have problem with missing messages when using nonblocking read in udp between two hosts. The sender is on linux and the reader is on winxp. This example in python shows the problem.<br> Here are three scripts used to show the problem.<br> <strong>send.py</strong>:</p> <pre><code>import socket, sys s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) host = sys.argv[1] s.sendto('A'*10, (host,8888)) s.sendto('B'*9000, (host,8888)) s.sendto('C'*9000, (host,8888)) s.sendto('D'*10, (host,8888)) s.sendto('E'*9000, (host,8888)) s.sendto('F'*9000, (host,8888)) s.sendto('G'*10, (host,8888)) </code></pre> <p><strong>read.py</strong></p> <pre><code>import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('',8888)) while True: data,address = s.recvfrom(10000) print "recv:", data[0],"times",len(data) </code></pre> <p><strong>read_nb.py</strong></p> <pre><code>import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('',8888)) s.setblocking(0) data ='' address = '' while True: try: data,address = s.recvfrom(10000) except socket.error: pass else: print "recv:", data[0],"times",len(data) </code></pre> <p>Example 1 (works ok):</p> <p>ubuntu> <strong>python send.py</strong><br> winxp > <strong>read.py</strong> </p> <p>give this ok result from read.py:</p> <p>recv: A times 10<br> recv: B times 9000<br> recv: C times 9000<br> recv: D times 10<br> recv: E times 9000<br> recv: F times 9000<br> recv: G times 10 </p> <p>Example 2 (<strong>missing messages</strong>):<br> in this case the short messages will often not be catched by read_nb.py I give two examples of how it can look like.</p> <p>ubuntu> <strong>python send.py</strong><br> winxp > <strong>read_nb.py</strong> </p> <p>give this result from read_nb.py:</p> <p>recv: A times 10<br> recv: B times 9000<br> recv: C times 9000<br> recv: D times 10<br> recv: E times 9000<br> recv: F times 9000 </p> <p>above is the last 10 byte message missing</p> <p>below is a 10 byte message in the middle missing</p> <p>recv: A times 10<br> recv: B times 9000<br> recv: C times 9000<br> recv: E times 9000<br> recv: F times 9000<br> recv: G times 10 </p> <p>I have checked with wireshark on windows and every time all messages is captured so they reach the host interface but is not captured by read_nb.py. What is the explanation? </p> <p>I have also tried with read_nb.py on linux and send.py on windows and then it works. So I figure that this problem has something to do with winsock2</p> <p>Or maybe I am using nonblocking udp the wrong way?</p>
0
1,053
Select distinct value in XSLT for-each-group
<p>I'm having an issue selecting distinct values for each group. The result just doesn't display on screen. The desired result is shown below: </p> <pre><code>&lt;xsl:for-each-group select="Items/Item" group-by="ProviderName"&gt; &lt;xsl:sort select="current-grouping-key()"/&gt; &lt;tr&gt; &lt;th&gt; &lt;xsl:value-of select="current-grouping-key()"/&gt; &lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;xsl:text&gt;Item Number&lt;/xsl:text&gt; &lt;/td&gt; &lt;td&gt; &lt;xsl:text&gt;Quantity&lt;/xsl:text&gt; &lt;/td&gt; &lt;td&gt; &lt;xsl:text&gt;Unit Price&lt;/xsl:text&gt; &lt;/td&gt; &lt;td&gt; &lt;xsl:text&gt;Total&lt;/xsl:text&gt; &lt;/td&gt; &lt;/tr&gt; &lt;xsl:apply-templates select="current-group()"/&gt; &lt;/xsl:for-each-group&gt; </code></pre> <p>What I intend to do is to select <em>distinct</em> values for <code>current-group()</code> in the <code>apply-templates</code> tag which is like this</p> <pre><code> &lt;xsl:template match="Item"&gt; &lt;xsl:value-of select="distinct-values(./ItemName)"/&gt; &lt;/xsl:template&gt; </code></pre> <p>I've read several samples on the net and the most optimum way to do so is to employ the <code>generate-id()</code> function with the <code>for-each-group</code> loop. But I have tried and get no positive result. This is the source XML:</p> <pre><code>&lt;Items&gt; &lt;Item ItemNumber="1148087"&gt; &lt;ProductName&gt;Dolby Metal-Black-Matte&lt;/ProductName&gt; &lt;ProviderName&gt;Vestal Watches&lt;/ProviderName&gt; &lt;Quantity&gt;4&lt;/Quantity&gt; &lt;UnitPrice&gt;67.99&lt;/UnitPrice&gt; &lt;/Item&gt; &lt;Item ItemNumber="1150197"&gt; &lt;ProductName&gt;Vercilli Blk-Tan&lt;/ProductName&gt; &lt;ProviderName&gt;Boston Babes&lt;/ProviderName&gt; &lt;Quantity&gt;1&lt;/Quantity&gt; &lt;UnitPrice&gt;23.99&lt;/UnitPrice&gt; &lt;/Item&gt; &lt;Item ItemNumber="1151464"&gt; &lt;ProductName&gt;Spritz Grape Seat and Extra Seat&lt;/ProductName&gt; &lt;ProviderName&gt;Bambeano&lt;/ProviderName&gt; &lt;Quantity&gt;1&lt;/Quantity&gt; &lt;UnitPrice&gt;56.99&lt;/UnitPrice&gt; &lt;/Item&gt; &lt;Item ItemNumber="1148087"&gt; &lt;ProductName&gt;Dolby Metal-Black-Matte&lt;/ProductName&gt; &lt;ProviderName&gt;Vestal Watches&lt;/ProviderName&gt; &lt;Quantity&gt;2&lt;/Quantity&gt; &lt;UnitPrice&gt;67.99&lt;/UnitPrice&gt; &lt;/Item&gt; &lt;Item ItemNumber="1150197"&gt; &lt;ProductName&gt;Vercilli Blk-Tan&lt;/ProductName&gt; &lt;ProviderName&gt;Boston Babes&lt;/ProviderName&gt; &lt;Quantity&gt;2&lt;/Quantity&gt; &lt;UnitPrice&gt;23.99&lt;/UnitPrice&gt; &lt;/Item&gt; &lt;Item ItemNumber="1150173"&gt; &lt;ProductName&gt;Lucille Tan&lt;/ProductName&gt; &lt;ProviderName&gt;Boston Babes&lt;/ProviderName&gt; &lt;Quantity&gt;1&lt;/Quantity&gt; &lt;UnitPrice&gt;24.99&lt;/UnitPrice&gt; &lt;/Item&gt; &lt;Item ItemNumber="1151464"&gt; &lt;ProductName&gt;Spritz Grape Seat and Extra Seat&lt;/ProductName&gt; &lt;ProviderName&gt;Bambeano&lt;/ProviderName&gt; &lt;Quantity&gt;1&lt;/Quantity&gt; &lt;UnitPrice&gt;56.99&lt;/UnitPrice&gt; &lt;/Item&gt; &lt;Item ItemNumber="1148089"&gt; &lt;ProductName&gt;Plexi Leather-Silver-Black&lt;/ProductName&gt; &lt;ProviderName&gt;Vestal Watches&lt;/ProviderName&gt; &lt;Quantity&gt;1&lt;/Quantity&gt; &lt;UnitPrice&gt;189.99&lt;/UnitPrice&gt; &lt;/Item&gt; &lt;/Items&gt; </code></pre> <p>Notice that the source XML contains several same <code>ProductName</code> elements with different <code>ItemNumber</code> attributes. What I desire is to group all the <code>Item</code> elements with similar <code>ItemNumber</code> and do a summation of the quantity. Thanks for the help guys. Really appreciate it.</p> <p>The example output would be: <img src="https://i.stack.imgur.com/6ZJxr.png" alt="enter image description here"></p>
0
2,024
How to make "HTTPS redirect" work on WebSphere Application Server Liberty Profile?
<p>I want make HTTP Redirect work on WebSphere Application Server Liberty Profile (WLP). For example:-</p> <p>When user types: <code>http://localhost:8080/helloworld</code>, the browser should automatically go (be redirected) to <code>https://localhost:9443/helloworld</code></p> <p>To achieve this, I followed this <a href="http://www.redbooks.ibm.com/redpieces/pdfs/sg248076.pdf" rel="nofollow">document</a>, Section 6.2, page no. 136.</p> <p>Below is the sample server.xml and web.xml:-</p> <p><strong>server.xml</strong></p> <pre><code>&lt;server description="new server"&gt; &lt;!-- Enable features --&gt; &lt;featureManager&gt; &lt;feature&gt;jsp-2.2&lt;/feature&gt; &lt;feature&gt;wab-1.0&lt;/feature&gt; &lt;feature&gt;jaxrs-1.1&lt;/feature&gt; &lt;feature&gt;blueprint-1.0&lt;/feature&gt; &lt;feature&gt;localConnector-1.0&lt;/feature&gt; &lt;feature&gt;ssl-1.0&lt;/feature&gt; &lt;feature&gt;appSecurity-2.0&lt;/feature&gt; &lt;/featureManager&gt; &lt;httpEndpoint host="localhost" httpPort="8081" httpsPort="9442" id="defaultHttpEndpoint"&gt; &lt;/httpEndpoint&gt; &lt;applicationMonitor updateTrigger="mbean"/&gt; &lt;keyStore id="defaultKeyStore" password="{xor}Lz4sLCgwLTtu"/&gt; &lt;application id="Hello.app" location="Hello.app.eba" name="Hello.app" type="eba"/&gt; </code></pre> <p></p> <p><strong>web.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"&gt; &lt;display-name&gt;Hello&lt;/display-name&gt; &lt;security-constraint&gt; &lt;display-name&gt;HTTPS Redirect Security Constraint&lt;/display-name&gt; &lt;web-resource-collection&gt; &lt;web-resource-name&gt;Sample Web Service service&lt;/web-resource-name&gt; &lt;url-pattern&gt;/Hello&lt;/url-pattern&gt; &lt;http-method&gt;GET&lt;/http-method&gt; &lt;/web-resource-collection&gt; &lt;user-data-constraint&gt; &lt;transport-guarantee&gt;CONFIDENTIAL&lt;/transport-guarantee&gt; &lt;/user-data-constraint&gt; &lt;/security-constraint&gt; &lt;/web-app&gt; </code></pre> <p>Have removed the <code>&lt;servlet&gt;</code> and <code>&lt;servlet-mapping&gt;</code> tag for brevity.</p> <p>Below are the versions that I am using:- Java 7, WLP 8.5.5, Eclipse Juno, Google Chrome.</p> <p>Any help, guidelines on why HTTPS redirect is not working will be much appreciated.</p>
0
1,157
Is there some decompiler for Kotlin files that decompile into kotlin *.kt files
<p>I try to learn how to decompile Android program(APK) and found this site <a href="http://www.javadecompilers.com" rel="noreferrer">Decompilers online</a> . It´s working grate for java code but when there are Kotlin files code the decompiler produces java code and it mixes Kotlin and java.</p> <p>Here's what I see from the file <code>ColorCircle.kt</code>. As you see Kotlin <code>Lazy</code> is there and other Kotlin code. My questions are: Is there some other <strong>decompiler for Kotlin files that decompile into kotlin *.kt files</strong>?<br> Can I have Kotlin imports in <code>*.java</code> files without problems?</p> <pre><code>package io.coolbe.vai.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import io.coolbe.vai.C1300R; import java.util.HashMap; import kotlin.Lazy; import kotlin.Metadata; import kotlin.jvm.functions.Function0; import kotlin.jvm.internal.Intrinsics; import kotlin.jvm.internal.PropertyReference1Impl; import kotlin.jvm.internal.Reflection; import kotlin.reflect.KProperty; import org.jetbrains.annotations.NotNull; @Metadata(bv = {1, 0, 3}, d1 = {"\u0000&gt;\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0010\u0007\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0005\n\u0002\u0010\b\n\u0002\b\u0002\n\u0002\u0010\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\u0018\u00002\u00020\u0001B\u000f\b\u0016\u0012\u0006\u0010\u0002\u001a\u00020\u0003¢\u0006\u0002\u0010\u0004B\u0017\b\u0016\u0012\u0006\u0010\u0002\u001a\u00020\u0003\u0012\u0006\u0010\u0005\u001a\u00020\u0006¢\u0006\u0002\u0010\u0007J\u0010\u0010\u0014\u001a\u00020\u00152\u0006\u0010\u0016\u001a\u00020\u0017H\u0014R\u000e\u0010\b\u001a\u00020\tX\u000e¢\u0006\u0002\n\u0000R\u000e\u0010\n\u001a\u00020\tX\u000e¢\u0006\u0002\n\u0000R\u001b\u0010\u000b\u001a\u00020\f8BX\u0002¢\u0006\f\n\u0004\b\u000f\u0010\u0010\u001a\u0004\b\r\u0010\u000eR\u000e\u0010\u0011\u001a\u00020\u0012X\u000e¢\u0006\u0002\n\u0000R\u000e\u0010\u0013\u001a\u00020\tX\u000e¢\u0006\u0002\n\u0000¨\u0006\u0018"}, d2 = {"Lio/coolbe/vai/view/ColoredCircle;", "Landroid/view/View;", "context", "Landroid/content/Context;", "(Landroid/content/Context;)V", "attrs", "Landroid/util/AttributeSet;", "(Landroid/content/Context;Landroid/util/AttributeSet;)V", "offsetX", "", "offsetY", "paint", "Landroid/graphics/Paint;", "getPaint", "()Landroid/graphics/Paint;", "paint$delegate", "Lkotlin/Lazy;", "strokeColor", "", "strokeWidth", "onDraw", "", "canvas", "Landroid/graphics/Canvas;", "app_release"}, k = 1, mv = {1, 1, 13}) /* compiled from: ColoredCircle.kt */ public final class ColoredCircle extends View { static final /* synthetic */ KProperty[] $$delegatedProperties = new KProperty[]{Reflection.property1(new PropertyReference1Impl(Reflection.getOrCreateKotlinClass(ColoredCircle.class), "paint", "getPaint()Landroid/graphics/Paint;"))}; private HashMap _$_findViewCache; private float offsetX; private float offsetY; private final Lazy paint$delegate; private int strokeColor; private float strokeWidth; private final Paint getPaint() { Lazy lazy = this.paint$delegate; KProperty kProperty = $$delegatedProperties[0]; return (Paint) lazy.getValue(); } public vaid _$_clearFindViewByIdCache() { HashMap hashMap = this._$_findViewCache; if (hashMap != null) { hashMap.clear(); } } public View _$_findCachedViewById(int i) { if (this._$_findViewCache == null) { this._$_findViewCache = new HashMap(); } View view = (View) this._$_findViewCache.get(Integer.valueOf(i)); if (view != null) { return view; } view = findViewById(i); this._$_findViewCache.put(Integer.valueOf(i), view); return view; } public ColoredCircle(@NotNull Context context) { Intrinsics.checkParameterIsNotNull(context, "context"); super(context); this.strokeColor = -7829368; this.strokeWidth = 10.0f; this.paint$delegate = LazyKt__LazyJVMKt.lazy((Function0) new ColoredCircle$paint$2(this)); } public ColoredCircle(@NotNull Context context, @NotNull AttributeSet attributeSet) { Intrinsics.checkParameterIsNotNull(context, "context"); Intrinsics.checkParameterIsNotNull(attributeSet, "attrs"); super(context, attributeSet); this.strokeColor = -7829368; this.strokeWidth = 10.0f; this.paint$delegate = LazyKt__LazyJVMKt.lazy(new ColoredCircle$paint$2(this)); context = context.getTheme().obtainStyledAttributes(attributeSet, C1300R.styleable.ColoredCircle, 0, 0); try { this.offsetX = context.getDimension(0, this.offsetX); this.offsetY = context.getDimension(1, this.offsetY); this.strokeColor = context.getColor(2, this.strokeColor); this.strokeWidth = context.getDimension(3, this.strokeWidth); } finally { context.recycle(); } } protected vaid onDraw(@NotNull Canvas canvas) { Intrinsics.checkParameterIsNotNull(canvas, "canvas"); super.onDraw(canvas); float f = (float) getLayoutParams().width; float f2 = (float) getLayoutParams().height; float f3 = (float) 2; float min = (Math.min(f, f2) / f3) - (this.strokeWidth / f3); canvas.save(); canvas.translate(this.offsetX, this.offsetY); canvas.drawCircle(f / f3, f2 / f3, min, getPaint()); canvas.restore(); } } </code></pre>
0
2,526
Android unable to find my onClick method
<p>I am having an issue where my Button (id <code>i_am_a_problem</code>) which is declared in the fragment's layout XML, is generating an error when the button is clicked. Android tries to call the onClick method <code>public void calculate(View v)</code> but is unable to find it (despite it being declared in MainActivity). Details of my code are below, and the error is after that. Please help me determine why android is unable to find the onClick method. Thanks.</p> <p>There is really not anything else going on in this code (fresh new project)</p> <p>MainActivity.java</p> <pre><code>package supercali.FRAG.alistic; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { /*snip - irrelevance*/ } @Override public boolean onOptionsItemSelected(MenuItem item) { /*snip - irrelevance*/ } public void calculcate(View v){ TextView tv = (TextView)findViewById(R.id.results); tv.setText(calculate_value()); } private String calculate_value(){ return "Abra Kadabra"; } } </code></pre> <p>MainActivity's layout just contains a fragment</p> <pre><code>&lt;fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/fragment" android:name="supercali.FRAG.alistic.MainActivityFragment" tools:layout="@layout/fragment_main" android:layout_width="match_parent" android:layout_height="match_parent" /&gt; </code></pre> <p>And the layout for that Fragment is:</p> <pre><code>&lt;LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivityFragment"&gt; &lt;Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/calculate" android:onClick="calculate" android:id="@+id/i_am_a_problem"/&gt; &lt;TextView android:text="@string/results_pending" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/results"/&gt; &lt;/LinearLayout&gt; </code></pre> <p><strong>The problem Button is just there ^^ with id i_am_a_problem</strong></p> <p>LogCat:</p> <pre><code>06-18 09:49:41.280 31642-31642/supercali.FRAG.alistic E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: supercali.FRAG.alistic, PID: 31642 java.lang.IllegalStateException: Could not find method calculate(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:4441) at android.view.View$DeclaredOnClickListener.onClick(View.java:4405) at android.view.View.performClick(View.java:5147) at android.view.View$PerformClick.run(View.java:21069) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5401) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:725) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:615) </code></pre>
0
1,523
UICollectionView with Custom UICollectionViewCell
<p>I have a UICollectionView with a custom cell. I had this working completely till I tried to create the collection view programmatically rather than from the storyboard. I did this because I was not able to change the frame size of the collection view for different screen sizes. So I tried to create a collection view programmatically. My problem is my custom cells are not working. For my custom cells I draw a circle in the view, user <code>cornerradius</code> on the view of the cell, have a UILabel and a UIImageView. </p> <p>I draw the circle and the perform the <code>cornerradius</code> thing in the <code>drawRect:</code> of the custom cell. The rest i.e: put image in ImageView and text in UILabel, I do it in the collectionView datasource method. </p> <p>The problem I am having is I don't get the <code>cornerradius</code> thing working although weirdly enough I can draw a circle on the view. second problem is I don't get the image in the image view and no text in the label</p> <p>Here is my code. I create the collection view in <code>ViewDidload:</code> method.</p> <pre><code> [layout setSectionInset:UIEdgeInsetsMake(24, 10, 24, 10)]; [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal]; [layout setMinimumLineSpacing:15]; [layout setMinimumInteritemSpacing:10]; self.collectionView = [[UICollectionView alloc]initWithFrame:rect collectionViewLayout:layout]; self.collectionView.delegate=self; self.collectionView.dataSource=self; [self.collectionView registerClass:[customCell class] forCellWithReuseIdentifier:@"cell"]; self.collectionView.backgroundColor= [UIColor blackColor]; self.searchBar.delegate = self; self.locations = [[NSArray alloc]init]; self.location = [[NSString alloc]init]; [self.view addSubview:self.collectionView]; </code></pre> <p>Here is the <code>drawRect:</code> for my customCell.m</p> <pre><code>- (void)drawRect:(CGRect)rect { UIBezierPath *circularpath = [[UIBezierPath alloc]init]; CGRect Rect = CGRectMake(6, 20, 130, 130);//338 CGPoint mypoint = CGPointMake(Rect.origin.x + (Rect.size.width / 2), Rect.origin.y + (Rect.size.height / 2)); NSLog(@"Circle center point::%f, %f", mypoint.x, mypoint.y); circularpath = [UIBezierPath bezierPathWithOvalInRect:Rect]; circularpath.lineWidth = 3.0; [[UIColor whiteColor]setStroke]; UIImage *ori = [UIImage imageNamed:@"drogba.jpg"]; UIImage *image = [[UIImage alloc]initWithCGImage:ori.CGImage scale:1.45 orientation:UIImageOrientationUp]; [[UIColor colorWithPatternImage:image]setFill]; NSLog(@"Circular path:%@", circularpath); //this works [circularpath stroke]; //this does not self.viewForBaselineLayout.layer.cornerRadius = 8.0f; } </code></pre> <p>and here is my datasource method</p> <pre><code>customCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]; UIImage *image = [[UIImage alloc]init]; if([self.allInfo count]&gt;0){ image = [self getImageForLocation:[self.allInfo objectAtIndex:indexPath.item]]; NSDictionary *dict = [[NSDictionary alloc]initWithDictionary:[self.allInfo objectAtIndex:indexPath.item]]; NSDictionary *city = [dict objectForKey:@"city"]; NSString *name = [[NSString alloc]initWithString:[city objectForKey:@"name"]]; cell.locationLabel.text = name; cell.imageView.image = [self getImageForSky:dict]; cell.viewForBaselineLayout.backgroundColor = [UIColor colorWithPatternImage:image]; cell.tempLabel.text = [self getTempForLocation:dict]; } NSLog(@"image description:%f", image.size.height); count =1; return cell; </code></pre> <p>I don't think it is a problem with my data because all I changed is creating Collection view programmatically rather than using storyboard.</p> <p>EDIT:: I had to alloc init the image view and the labels for the custom cell and then add them as subview. now 3 of my 4 problems are solved. I still cannot get the corner radius to work for me. I want a slightly curved border for my cell</p>
0
1,328
Custom incoming/outgoing call screen in Android
<p>I am trying to implement custom incoming/outgoing calling screen. The following is what I have tried. U gave two problems </p> <ol> <li><p>Sometime it calls the default incoming screen on my phone or sometimes it calls the customized screen. I would the phone always call customized screen.</p></li> <li><p>I am not able to initiate calls for outgoing. the customized screen just comes up but doesn't make any calls.</p></li> </ol> <p>How to solve this issue, I am not sure what is wrong here. It would be great if somebody can help me out fixing this..</p> <p>Here is what I am trying:</p> <p><strong>Manifest:</strong></p> <pre><code>&lt;uses-permission android:name="android.permission.READ_PHONE_STATE" /&gt; &lt;uses-permission android:name="android.permission.READ_CONTACTS" /&gt; &lt;uses-permission android:name="android.permission.CALL_PHONE" /&gt; &lt;uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" /&gt; &lt;uses-permission android:name="android.permission.MODIFY_PHONE_STATE" /&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar" &gt; &lt;activity android:name="com.honey.ringer.MainActivity" android:label="@string/app_name" &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; &lt;activity android:name="com.honey.ringer.AcceptCall" android:screenOrientation="portrait" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.ANSWER" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;receiver android:name="com.honey.ringer.PhoneListenerBroad"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.PHONE_STATE" /&gt; &lt;action android:name="android.intent.action.NEW_OUTGOING_CALL" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; &lt;/application&gt; </code></pre> <p></p> <p><strong>BroadCastReciever: This has both incoming and outgoing</strong></p> <pre><code>public class PhoneListenerBroad extends BroadcastReceiver { Context c; private String outgoing; @Override public void onReceive(Context context, Intent intent) { c = context; if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) { outgoing = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); int state = 2; Intent intentPhoneCall = new Intent(c, AcceptCall.class); intentPhoneCall.putExtra("incomingnumber", outgoing); intentPhoneCall.putExtra("state", state); intentPhoneCall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); c.startActivity(intentPhoneCall); } try { TelephonyManager tmgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); MyPhoneStateListener PhoneListener = new MyPhoneStateListener(); tmgr.listen(PhoneListener, PhoneStateListener.LISTEN_CALL_STATE); } catch (Exception e) { Log.e("Phone Receive Error", " " + e); } } private class MyPhoneStateListener extends PhoneStateListener { public void onCallStateChanged(final int state, final String incomingNumber) { Handler callActionHandler = new Handler(); Runnable runRingingActivity = new Runnable() { @Override public void run() { if (state == 1) { Intent intentPhoneCall = new Intent(c, AcceptCall.class); intentPhoneCall.putExtra("incomingnumber", incomingNumber); intentPhoneCall.putExtra("state", state); intentPhoneCall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); c.startActivity(intentPhoneCall); } } }; if (state == 1) { callActionHandler.postDelayed(runRingingActivity, 100); } if (state == 0) { callActionHandler.removeCallbacks(runRingingActivity); } } } </code></pre> <p>}</p> <p><strong>AcceptCall.java (For UI purpose - Incoming and outgoing):</strong></p> <pre><code> @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public class AcceptCall extends Activity implements OnClickListener { LinearLayout answerButton; LinearLayout rejectButton; LinearLayout timerLayout; TextView contactName; TextView contactNumber; ImageView profile; private String incomingnumber; private int state; String name = null; String contactId = null; InputStream photo_stream; TextView callType; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.testactivity); answerButton = (LinearLayout) findViewById(R.id.callReceive); answerButton.setOnClickListener(this); rejectButton = (LinearLayout) findViewById(R.id.callReject); rejectButton.setOnClickListener(this); timerLayout = (LinearLayout) findViewById(R.id.timerLayout); contactName = (TextView) findViewById(R.id.contactName); contactNumber = (TextView) findViewById(R.id.contactNumber); callType = (TextView) findViewById(R.id.callType); timerValue = (TextView) findViewById(R.id.timerValue); profile = (ImageView)findViewById(R.id.contactPhoto); Bundle bundle = getIntent().getExtras(); if(bundle != null) { incomingnumber = bundle.getString("incomingnumber"); state = bundle.getInt("state"); } contactslookup(incomingnumber); contactName.setText(name); contactNumber.setText(incomingnumber); if (state == 2) { /*String uri = "tel:" + incomingnumber.trim(); Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse(uri)); startActivity(intent);*/ } PhoneStateListener phoneStateListener = new PhoneStateListener() { @Override public void onCallStateChanged(int state, String incomingNumber) { //wen ringing if (state == TelephonyManager.CALL_STATE_RINGING) { Log.e("CALL_STATE_RINGING","CALL_STATE_RINGING"); } //after call cut else if(state == TelephonyManager.CALL_STATE_IDLE) { RejectCall(); } //wen speaking / outgoing call else if(state == TelephonyManager.CALL_STATE_OFFHOOK) { Log.e("CALL_STATE_OFFHOOK","CALL_STATE_OFFHOOK"); } super.onCallStateChanged(state, incomingNumber); } }; TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); if(mgr != null) { mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); } } private void contactslookup(String number) { Log.v("ffnet", "Started uploadcontactphoto..."); //InputStream input = null; // define the columns I want the query to return String[] projection = new String[] {ContactsContract.PhoneLookup.DISPLAY_NAME,ContactsContract.PhoneLookup._ID}; // encode the phone number and build the filter URI Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)); // query time Cursor cursor = getContentResolver().query(contactUri, projection, null, null, null); if (cursor.moveToFirst()) { // Get values from contacts database: contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID)); name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)); } else { return; // contact not found } int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (currentapiVersion &gt;= 14) { Uri my_contact_Uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId)); photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(), my_contact_Uri, true); } else { Uri my_contact_Uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId)); photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(), my_contact_Uri); } if(photo_stream != null) { BufferedInputStream buf =new BufferedInputStream(photo_stream); Bitmap my_btmp = BitmapFactory.decodeStream(buf); profile.setImageBitmap(my_btmp); } else { profile.setImageResource(R.drawable.contactpic); } cursor.close(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View v) { // TODO Auto-generated method stub if(v.getId() == answerButton.getId()) { timerLayout.setVisibility(0); startTime = SystemClock.uptimeMillis(); customHandler.postDelayed(updateTimerThread, 0); callType.clearAnimation(); // Simulate a press of the headset button to pick up the call Intent buttonDown = new Intent(Intent.ACTION_MEDIA_BUTTON); buttonDown.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK)); this.sendOrderedBroadcast(buttonDown, "android.permission.CALL_PRIVILEGED"); // froyo and beyond trigger on buttonUp instead of buttonDown Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON); buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK)); this.sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED"); } if(v.getId() == rejectButton.getId()) { RejectCall(); } } private void RejectCall() { TelephonyManager telephony = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE); try { // Java reflection to gain access to TelephonyManager's // ITelephony getter Class c = Class.forName(telephony.getClass().getName()); Method m = c.getDeclaredMethod("getITelephony"); m.setAccessible(true); com.android.internal.telephony.ITelephony telephonyService = (ITelephony) m.invoke(telephony); telephonyService.endCall(); finish(); timeSwapBuff += timeInMilliseconds; customHandler.removeCallbacks(updateTimerThread); } catch (Exception e) { e.printStackTrace(); Log.e("Error", "FATAL ERROR: could not connect to telephony subsystem"); Log.e("Error", "Exception object: " + e); } } private Runnable updateTimerThread = new Runnable() { public void run() { timeInMilliseconds = SystemClock.uptimeMillis() - startTime; updatedTime = timeSwapBuff + timeInMilliseconds; int secs = (int) (updatedTime / 1000); int mins = secs / 60; int hours = mins / 60; secs = secs % 60; int milliseconds = (int) (updatedTime % 1000); timerValue.setText(""+ hours + ":" + String.format("%02d", mins) + ":" + String.format("%02d", secs)); customHandler.postDelayed(this, 0); } }; } </code></pre>
0
4,818
java.lang.NumberFormatException: Invalid int: "" EXCEPTION
<p>If the user left the edittext empty an error occurs java.lang.NumberFormatException: Invalid int: "". The error comes at line</p> <pre><code> if (a=="" &amp;&amp; b=="") </code></pre> <p>and also at line</p> <pre><code> int result = Integer.parseInt(a) + Integer.parseInt(b); t1.setText(Integer.toString(result)); </code></pre> <p><strong>Calci.java</strong></p> <pre><code>package com.example.calculator; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Calci extends Activity { TextView t1; EditText e1, e2; Button add, sub, mul, div; Context c=this; String b, a; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calci); e1 = (EditText) findViewById(R.id.EditText01); e2 = (EditText) findViewById(R.id.EditText02); add = (Button) findViewById(R.id.add); sub = (Button) findViewById(R.id.sub); mul = (Button) findViewById(R.id.mul); div = (Button) findViewById(R.id.div); t1 = (TextView) findViewById(R.id.textView1); a = e1.getText().toString(); b = e2.getText().toString(); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { if (a=="" &amp;&amp; b==""){ AlertDialog.Builder a1 = new AlertDialog.Builder(c); // Setting Dialog Title a1.setTitle("Alert Dialog"); // Setting Dialog Message a1.setMessage("PLEASE ENTER SOMETHING"); a1.setPositiveButton("yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int button1) { // if this button is clicked, close // current activity dialog.cancel(); } }); // Showing Alert Message AlertDialog alertDialog = a1.create(); a1.show(); } else{ int result = Integer.parseInt(a) + Integer.parseInt(b); t1.setText(Integer.toString(result)); InputMethodManager imm = (InputMethodManager)getSystemService( Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(add.getWindowToken(), 0); } } }); } } </code></pre> <p><strong>LogCat:</strong></p> <pre><code>03-19 15:42:21.165: E/Trace(25381): error opening trace file: Permission denied (13) 03-19 15:42:21.165: D/ActivityThread(25381): setTargetHeapUtilization:0.25 03-19 15:42:21.165: D/ActivityThread(25381): setTargetHeapIdealFree:8388608 03-19 15:42:21.165: D/ActivityThread(25381): setTargetHeapConcurrentStart:2097152 03-19 15:42:21.385: D/libEGL(25381): loaded /system/lib/egl/libEGL_adreno200.so 03-19 15:42:21.465: D/libEGL(25381): loaded /system/lib/egl/libGLESv1_CM_adreno200.so 03-19 15:42:21.475: D/libEGL(25381): loaded /system/lib/egl/libGLESv2_adreno200.so 03-19 15:42:21.475: I/Adreno200-EGL(25381): &lt;qeglDrvAPI_eglInitialize:299&gt;: EGL 1.4 QUALCOMM build: (Merge) 03-19 15:42:21.475: I/Adreno200-EGL(25381): Build Date: 07/09/13 Tue 03-19 15:42:21.475: I/Adreno200-EGL(25381): Local Branch: AU_41 03-19 15:42:21.475: I/Adreno200-EGL(25381): Remote Branch: 03-19 15:42:21.475: I/Adreno200-EGL(25381): Local Patches: 03-19 15:42:21.475: I/Adreno200-EGL(25381): Reconstruct Branch: 03-19 15:42:21.675: D/OpenGLRenderer(25381): Enabling debug mode 0 03-19 15:42:24.325: D/AndroidRuntime(25381): Shutting down VM 03-19 15:42:24.325: W/dalvikvm(25381): threadid=1: thread exiting with uncaught exception (group=0x41972378) 03-19 15:42:24.395: E/AndroidRuntime(25381): FATAL EXCEPTION: main 03-19 15:42:24.395: E/AndroidRuntime(25381): java.lang.NumberFormatException: Invalid int: "" 03-19 15:42:24.395: E/AndroidRuntime(25381): at java.lang.Integer.invalidInt(Integer.java:138) 03-19 15:42:24.395: E/AndroidRuntime(25381): at java.lang.Integer.parseInt(Integer.java:359) 03-19 15:42:24.395: E/AndroidRuntime(25381): at java.lang.Integer.parseInt(Integer.java:332) 03-19 15:42:24.395: E/AndroidRuntime(25381): at com.example.calculator.Calci$1.onClick(Calci.java:67) 03-19 15:42:24.395: E/AndroidRuntime(25381): at android.view.View.performClick(View.java:4147) 03-19 15:42:24.395: E/AndroidRuntime(25381): at android.view.View$PerformClick.run(View.java:17161) 03-19 15:42:24.395: E/AndroidRuntime(25381): at android.os.Handler.handleCallback(Handler.java:615) 03-19 15:42:24.395: E/AndroidRuntime(25381): at android.os.Handler.dispatchMessage(Handler.java:92) 03-19 15:42:24.395: E/AndroidRuntime(25381): at android.os.Looper.loop(Looper.java:213) 03-19 15:42:24.395: E/AndroidRuntime(25381): at android.app.ActivityThread.main(ActivityThread.java:4787) 03-19 15:42:24.395: E/AndroidRuntime(25381): at java.lang.reflect.Method.invokeNative(Native Method) 03-19 15:42:24.395: E/AndroidRuntime(25381): at java.lang.reflect.Method.invoke(Method.java:511) 03-19 15:42:24.395: E/AndroidRuntime(25381): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 03-19 15:42:24.395: E/AndroidRuntime(25381): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556) 03-19 15:42:24.395: E/AndroidRuntime(25381): at dalvik.system.NativeStart.main(Native Method) 03-19 15:42:25.685: I/Process(25381): Sending signal. PID: 25381 SIG: 9 </code></pre> <p>Anybody have an idea how to solve these stack trace error.</p>
0
2,674
JSF 2.0 navigation not working properly
<p>I am trying to get started with JSF 2.0. I am trying a basic navigation example and it's not working properly. </p> <p>The file structure is the following:</p> <p><img src="https://i.stack.imgur.com/aI7Pw.png" alt="enter image description here"></p> <p>I have configured the mapping in web.xml:</p> <pre><code>&lt;!-- Change to "Production" when you are ready to deploy --&gt; &lt;context-param&gt; &lt;param-name&gt;javax.faces.PROJECT_STAGE&lt;/param-name&gt; &lt;param-value&gt;Development&lt;/param-value&gt; &lt;/context-param&gt; &lt;!-- Welcome page --&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.xhtml&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;!-- JSF mapping --&gt; &lt;servlet&gt; &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt; &lt;servlet-class&gt;javax.faces.webapp.FacesServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt; &lt;url-pattern&gt;*.xhtml&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p>And the index page has 2 buttons which take you to different pages when clicked</p> <p>The faces-config.xml file defines some navigation cases:</p> <pre><code>&lt;!-- Configuration of navigation rules --&gt; &lt;navigation-rule&gt; &lt;from-view-id&gt;/index.xhtml&lt;/from-view-id&gt; &lt;navigation-case&gt; &lt;from-outcome&gt;success&lt;/from-outcome&gt; &lt;to-view-id&gt;/pages/success.xhtml&lt;/to-view-id&gt; &lt;/navigation-case&gt; &lt;navigation-case&gt; &lt;from-outcome&gt;error&lt;/from-outcome&gt; &lt;to-view-id&gt;/pages/error.xhtml&lt;/to-view-id&gt; &lt;/navigation-case&gt; &lt;/navigation-rule&gt; </code></pre> <p>E.g. the following button should take you to the success page (/pages/success.xhtml):</p> <pre><code>&lt;p:commandButton id="addUser" value="Add" action="#{userMB.addUser}" ajax="false"/&gt; </code></pre> <p>I have debugged this an the return value of addUser is definitely "success".</p> <p>The page switches to success.xhtml because I see the content is changed, but the browser URL points to index.xhtml....</p> <p>At startup: URL is <strong>localhost:8080/PROJECT/</strong> with no index.xhtml probably because we configured it as the welcome file. When we hit the button above, the URL becomes <strong>localhost:8080/PROJECT/index.xhtml</strong></p> <p>I believe I have messed up something with the mappings or the relative paths. I have found some advice that the only mapping should be the one with *.xhtml but I did not really understand why and how to address multiple subfolders of pages.</p> <p>Any help is appreciated, thanks</p>
0
1,070
"Invalid privatekey" when using JSch
<p>I'm using the following code to work with Git in a Java application. I have a valid key (use it all the time), and this specific code has work for me before with the same key and git repository, but now I get the following exception:</p> <blockquote> <p>invalid privatekey: [B@59c40796.</p> </blockquote> <p>At this line:</p> <pre><code>jSch.addIdentity("&lt;key_path&gt;/private_key.pem"); </code></pre> <p>My full code:</p> <pre><code> String remoteURL = "ssh://git@&lt;git_repository&gt;"; TransportConfigCallback transportConfigCallback = new SshTransportConfigCallback(); File gitFolder = new File(workingDirectory); if (gitFolder.exists()) FileUtils.delete(gitFolder, FileUtils.RECURSIVE); Git git = Git.cloneRepository() .setURI(remoteURL) .setTransportConfigCallback(transportConfigCallback) .setDirectory(new File(workingDirectory)) .call(); } private static class SshTransportConfigCallback implements TransportConfigCallback { private final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() { @Override protected void configure(OpenSshConfig.Host hc, Session session) { session.setConfig("StrictHostKeyChecking", "no"); } @Override protected JSch createDefaultJSch(FS fs) throws JSchException { JSch jSch = super.createDefaultJSch(fs); jSch.addIdentity("&lt;key_path&gt;/private_key.pem"); return jSch; } }; </code></pre> <p>After searching online, I've change createDefaultJSch to use pemWriter:</p> <pre><code>@Override protected JSch createDefaultJSch(FS fs) throws JSchException { JSch jSch = super.createDefaultJSch(fs); byte[] privateKeyPEM = null; try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); List&lt;String&gt; lines = Files.readAllLines(Paths.get("&lt;my_key&gt;.pem"), StandardCharsets.US_ASCII); PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(String.join("", lines))); RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec); PKCS8Generator pkcs8 = new PKCS8Generator(privKey); StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(pkcs8); privateKeyPEM = writer.toString().getBytes("US-ASCII"); } catch (Exception e) { e.printStackTrace(); } jSch.addIdentity("git", privateKeyPEM, null, null); return jSch; } </code></pre> <p>But still getting <em>"invalid privatekey"</em> exception.</p>
0
1,036
Adding custom filter in spring security
<p>I am trying to make a custom AuthenticationProcessingFilter to save some user data in the session after successful login</p> <p>here's my filter:</p> <pre><code>package projects.internal; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.Authentication; import org.springframework.security.ui.webapp.AuthenticationProcessingFilter; public class MyAuthenticationProcessingFilter extends AuthenticationProcessingFilter { protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException { super.onSuccessfulAuthentication(request, response, authResult); request.getSession().setAttribute("myValue", "My value is set"); } } </code></pre> <p>and here's my security.xml file</p> <pre><code>&lt;beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd"&gt; &lt;global-method-security pre-post-annotations="enabled"&gt; &lt;/global-method-security&gt; &lt;http use-expressions="true" auto-config="false" entry-point-ref="authenticationProcessingFilterEntryPoint"&gt; &lt;intercept-url pattern="/" access="permitAll" /&gt; &lt;intercept-url pattern="/images/**" filters="none" /&gt; &lt;intercept-url pattern="/scripts/**" filters="none" /&gt; &lt;intercept-url pattern="/styles/**" filters="none" /&gt; &lt;intercept-url pattern="/p/login.jsp" filters="none" /&gt; &lt;intercept-url pattern="/p/register" filters="none" /&gt; &lt;intercept-url pattern="/p/**" access="isAuthenticated()" /&gt; &lt;form-login login-processing-url="/j_spring_security_check" login-page="/p/login.jsp" authentication-failure-url="/p/login_error.jsp" /&gt; &lt;logout /&gt; &lt;/http&gt; &lt;authentication-manager alias="authenticationManager"&gt; &lt;authentication-provider&gt; &lt;jdbc-user-service data-source-ref="dataSource"/&gt; &lt;/authentication-provider&gt; &lt;/authentication-manager&gt; &lt;beans:bean id="authenticationProcessingFilter" class="projects.internal.MyAuthenticationProcessingFilter"&gt; &lt;custom-filter position="AUTHENTICATION_PROCESSING_FILTER" /&gt; &lt;/beans:bean&gt; &lt;beans:bean id="authenticationProcessingFilterEntryPoint" class="org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntryPoint"&gt; &lt;/beans:bean&gt; &lt;/beans:beans&gt; </code></pre> <p>it gives an error here:</p> <pre><code>&lt;custom-filter position="AUTHENTICATION_PROCESSING_FILTER" /&gt; </code></pre> <blockquote> <p>multiple annotation found at this line:cvc-attribute.3 cvc-complex-type.4 cvc-enumeration-vaild</p> </blockquote> <p>what is the problem?</p>
0
1,134
How to upload image to Firebase using Flutter
<p>I am using the image_picker library <a href="https://pub.dartlang.org/packages/image_picker" rel="noreferrer">https://pub.dartlang.org/packages/image_picker</a> with for selecting/taking the photo that I want to upload. The code so far uploads the image to Firebase storage successfully the only issue is that after the image is uploaded the app shuts down (doesn't really crash, it just closes and VS code looses connection to the device). The code is the following:</p> <pre><code> File _image; Future _takeProfilePicture() async{ var image = await ImagePicker.pickImage(source: ImageSource.camera); setState((){ _image = image; }); } Future _selectProfilePicture() async{ var image = await ImagePicker.pickImage(source: ImageSource.gallery); setState((){ _image = image; }); } Future&lt;Null&gt; _uploadProfilePicture() async{ FirebaseUser user = await FirebaseAuth.instance.currentUser(); final StorageReference ref = FirebaseStorage.instance.ref().child('${user.email}/${user.email}_profilePicture.jpg'); final StorageUploadTask uploadTask = ref.putFile(_image); final Uri downloadUrl = (await uploadTask.future).downloadUrl; } void _selectAndUploadPicture() async{ await _selectProfilePicture(); await _uploadProfilePicture(); } void _takeAndUploadPicture() async{ await _takeProfilePicture(); await _uploadProfilePicture(); } </code></pre> <p>And the terminal prints the following:</p> <pre><code>W/Firestore( 6873): (0.6.6-dev) [Firestore]: The behavior for java.util.Date objects stored in Firestore is going to change AND YOUR APP MAY BREAK. W/Firestore( 6873): To hide this warning and ensure your app does not break, you need to add the following code to your app before calling any other Cloud Firestore methods: W/Firestore( 6873): W/Firestore( 6873): FirebaseFirestore firestore = FirebaseFirestore.getInstance(); W/Firestore( 6873): FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder() W/Firestore( 6873): .setTimestampsInSnapshotsEnabled(true) W/Firestore( 6873): .build(); W/Firestore( 6873): firestore.setFirestoreSettings(settings); W/Firestore( 6873): W/Firestore( 6873): With this change, timestamps stored in Cloud Firestore will be read back as com.google.firebase.Timestamp objects instead of as system java.util.Date objects. So you will also need to update code expecting a java.util.Date to instead expect a Timestamp. For example: W/Firestore( 6873): W/Firestore( 6873): // Old: W/Firestore( 6873): java.util.Date date = snapshot.getDate("created_at"); W/Firestore( 6873): // New: W/Firestore( 6873): Timestamp timestamp = snapshot.getTimestamp("created_at"); W/Firestore( 6873): java.util.Date date = timestamp.toDate(); W/Firestore( 6873): W/Firestore( 6873): Please audit all existing usages of java.util.Date when you enable the new behavior. In a future release, the behavior will be changed to the new behavior, so if you do not follow these steps, YOUR APP MAY BREAK. </code></pre> <p>I tried implementing the suggested java code from the terminal but I cannot seem to find a way to write the equivalent in flutter using the cloud_firestore library <a href="https://pub.dartlang.org/packages/cloud_firestore" rel="noreferrer">https://pub.dartlang.org/packages/cloud_firestore</a> , it does not have an equivalent for FirebaseFirestoreSettings (or I cannot seem to find one). Is there a way around this?</p> <p>Thank you in advance!</p>
0
1,064
How to create a generator/iterator with the Python C API?
<p>How do I replicate the following Python code with the Python C API?</p> <pre><code>class Sequence(): def __init__(self, max): self.max = max def data(self): i = 0 while i &lt; self.max: yield i i += 1 </code></pre> <p>So far, I have this:</p> <pre><code>#include &lt;Python/Python.h&gt; #include &lt;Python/structmember.h&gt; /* Define a new object class, Sequence. */ typedef struct { PyObject_HEAD size_t max; } SequenceObject; /* Instance variables */ static PyMemberDef Sequence_members[] = { {&quot;max&quot;, T_UINT, offsetof(SequenceObject, max), 0, NULL}, {NULL} /* Sentinel */ }; static int Sequence_Init(SequenceObject *self, PyObject *args, PyObject *kwds) { if (!PyArg_ParseTuple(args, &quot;k&quot;, &amp;(self-&gt;max))) { return -1; } return 0; } static PyObject *Sequence_data(SequenceObject *self, PyObject *args); /* Methods */ static PyMethodDef Sequence_methods[] = { {&quot;data&quot;, (PyCFunction)Sequence_data, METH_NOARGS, &quot;sequence.data() -&gt; iterator object\n&quot; &quot;Returns iterator of range [0, sequence.max).&quot;}, {NULL} /* Sentinel */ }; /* Define new object type */ PyTypeObject Sequence_Type = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ &quot;Sequence&quot;, /* tp_name */ sizeof(SequenceObject), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/ &quot;Test generator object&quot;, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ Sequence_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Sequence_init, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; static PyObject *Sequence_data(SequenceObject *self, PyObject *args) { /* Now what? */ } </code></pre> <p>But I'm not sure where to go next. Could anyone offer some suggestions?</p> <h1>Edit</h1> <p>I suppose the main problem I'm having with this is simulating the <code>yield</code> statement. As I understand it, it is a pretty simple-looking, but in reality complex, statement — it creates a generator with its own <code>__iter__()</code> and <code>next()</code> methods which are called automatically. Searching through the docs, it seems to be associated with the <a href="http://docs.python.org/c-api/gen.html" rel="noreferrer">PyGenObject</a>; however, how to create a new instance of this object is unclear. <code>PyGen_New()</code> takes as its argument a <code>PyFrameObject</code>, the only reference to which I can find is <a href="http://docs.python.org/c-api/reflection.html" rel="noreferrer"><code>PyEval_GetFrame()</code></a>, which doesn't seem to be what I want (or am I mistaken?). Does anyone have any experience with this they can share?</p> <h1>Further Edit</h1> <p>I found this to be clearer when I (essentially) expanded what Python was doing behind the scenes:</p> <pre><code>class IterObject(): def __init__(self, max): self.max = max def __iter__(self): self.i = 0 return self def next(self): if self.i &gt;= self.max: raise StopIteration self.i += 1 return self.i class Sequence(): def __init__(self, max): self.max = max def data(self): return IterObject(self.max) </code></pre> <p>Technically the sequence is off by one but you get the idea.</p> <p>The only problem with this is it's very annoying to create a new object every time one needs a generator — even more so in Python than C because of the required monstrosity that comes with defining a new type. And there can be no <code>yield</code> statement in C because C has no closures. What I did instead (since I couldn't find it in the Python API — <em>please</em> point me to a standard object if it already exists!) was create a simple, generic generator object class that called back a C function for every <code>next()</code> method call. Here it is (note that I have not yet tried compiling this because it is not complete — see below):</p> <pre><code>#include &lt;Python/Python.h&gt; #include &lt;Python/structmember.h&gt; #include &lt;stdlib.h&gt; /* A convenient, generic generator object. */ typedef PyObject *(*callback)(PyObject *callee, void *info) PyGeneratorCallback; typedef struct { PyObject HEAD PyGeneratorCallback callback; PyObject *callee; void *callbackInfo; /* info to be passed along to callback function. */ bool freeInfo; /* true if |callbackInfo| should be free'()d when object * dealloc's, false if not. */ } GeneratorObject; static PyObject *Generator_iter(PyObject *self, PyObject *args) { Py_INCREF(self); return self; } static PyObject *Generator_next(PyObject *self, PyObject *args) { return self-&gt;callback(self-&gt;callee, self-&gt;callbackInfo); } static PyMethodDef Generator_methods[] = { {&quot;__iter__&quot;, (PyCFunction)Generator_iter, METH_NOARGS, NULL}, {&quot;next&quot;, (PyCFunction)Generator_next, METH_NOARGS, NULL}, {NULL} /* Sentinel */ }; static void Generator_dealloc(GenericEventObject *self) { if (self-&gt;freeInfo &amp;&amp; self-&gt;callbackInfo != NULL) { free(self-&gt;callbackInfo); } self-&gt;ob_type-&gt;tp_free((PyObject *)self); } PyTypeObject Generator_Type = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ &quot;Generator&quot;, /* tp_name */ sizeof(GeneratorObject), /* tp_basicsize */ 0, /* tp_itemsize */ Generator_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; /* Returns a new generator object with the given callback function * and arguments. */ PyObject *Generator_New(PyObject *callee, void *info, bool freeInfo, PyGeneratorCallback callback) { GeneratorObject *generator = (GeneratorObject *)_PyObject_New(&amp;Generator_Type); if (generator == NULL) return NULL; generator-&gt;callee = callee; generator-&gt;info = info; generator-&gt;callback = callback; self-&gt;freeInfo = freeInfo; return (PyObject *)generator; } /* End of Generator definition. */ /* Define a new object class, Sequence. */ typedef struct { PyObject_HEAD size_t max; } SequenceObject; /* Instance variables */ static PyMemberDef Sequence_members[] = { {&quot;max&quot;, T_UINT, offsetof(SequenceObject, max), 0, NULL}, {NULL} /* Sentinel */ } static int Sequence_Init(SequenceObject *self, PyObject *args, PyObject *kwds) { if (!PyArg_ParseTuple(args, &quot;k&quot;, &amp;self-&gt;max)) { return -1; } return 0; } static PyObject *Sequence_data(SequenceObject *self, PyObject *args); /* Methods */ static PyMethodDef Sequence_methods[] = { {&quot;data&quot;, (PyCFunction)Sequence_data, METH_NOARGS, &quot;sequence.data() -&gt; iterator object\n&quot; &quot;Returns generator of range [0, sequence.max).&quot;}, {NULL} /* Sentinel */ }; /* Define new object type */ PyTypeObject Sequence_Type = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ &quot;Sequence&quot;, /* tp_name */ sizeof(SequenceObject), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/ &quot;Test generator object&quot;, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ Sequence_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Sequence_init, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; static PyObject *Sequence_data(SequenceObject *self, PyObject *args) { size_t *info = malloc(sizeof(size_t)); if (info == NULL) return NULL; *info = 0; /* |info| will be free'()d by the returned generator object. */ GeneratorObject *ret = Generator_New(self, info, true, &amp;Sequence_data_next_callback); if (ret == NULL) { free(info); /* Watch out for memory leaks! */ } return ret; } PyObject *Sequence_data_next_callback(PyObject *self, void *info) { size_t i = info; if (i &gt; self-&gt;max) { return NULL; /* TODO: How do I raise StopIteration here? I can't seem to find * a standard exception. */ } else { return Py_BuildValue(&quot;k&quot;, i++); } } </code></pre> <p>However, unfortunately, I'm still not finished. The only question I have left is: How do I raise a <code>StopIteration</code> exception with the C API? I can't seem to find it listed in the <a href="http://docs.python.org/c-api/exceptions.html#standard-exceptions" rel="noreferrer">Standard Exceptions</a>. Also, perhaps more importantly, is this the correct way to approach this problem?</p> <p>Thanks to anyone that's still following this.</p>
0
6,751
How to Get A Div to Smoothly Move Up Using CSS Transitions?
<p>The title kind of describes it. Here's the code:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#main { float: left; width: 20%; height: 10vh; margin-top: 10vh; margin-left: 40%; text-align: center; } #k { font-family: Questrial; font-size: 70px; margin-top: -7px; margin-left: -2px; color: #404040; border-bottom: 2px solid #404040; line-height: 0.85; } #about { float: left; clear: both; width: 38%; height: 30vh; margin-top: 7vh; margin-left: 31%; text-align: center; background-color: #33CC33; border-radius: 100%; opacity: 0.6; transition: opacity .5s; -webkit-transition: opacity .5s; transition: margin-top .5s; -webkit-transition: margin-top .5s; transition: margin-bottom .5s; -webkit-transition: margin-bottom .5s; } #about:hover { opacity: 0.8; margin-top: 5vh; margin-bottom: 2vh; } #work { float: left; width: 38%; height: 30vh; margin-top: 0vh; margin-left: 10%; text-align: center; background-color: #323280; border-radius: 100%; opacity: 0.6; transition: opacity .5s; -webkit-transition: opacity .5s; } #work:hover { opacity: 0.8; } #contact { float: right; width: 38%; height: 30vh; margin-top: 0vh; margin-right: 10%; text-align: center; background-color: #FF6600; border-radius: 100%; opacity: 0.6; transition: opacity .5s; -webkit-transition: opacity .5s; } #contact:hover { opacity: 0.8; } .label { font-family: Questrial; color: white; font-size: 35px; margin-top: 80px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;KURB - Home&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="kurb.css"/&gt; &lt;link href='http://fonts.googleapis.com/css?family=Questrial' rel='stylesheet' type='text/css'&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="main"&gt; &lt;p id="k"&gt;KURB&lt;/p&gt; &lt;/div&gt; &lt;div id="about"&gt; &lt;p class="label"&gt;Blah blah blah&lt;/p&gt; &lt;/div&gt; &lt;div id="work"&gt; &lt;p class="label"&gt;Blah blah blah blah blah&lt;/p&gt; &lt;/div&gt; &lt;div id="contact"&gt; &lt;p class="label"&gt;Blah blah blah blah&lt;/p&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Basically, what I'm trying to do is get the top div (#about) to rise up above the lower two by about 2 vh when moused over. As you can see, I've already kind of got it, but it's not doing an actual animation - it rises up instantly. Also, there should be a color transition on the mouseover - it should become less transparent. This works on the others, but not on this one.</p> <p>It gets really interesting when you get rid of the dashes in margin-top and margin-bottom. Then, instead of the bottom two slowly moving down, they all just kind of snap into place. This is what I'm looking for, only with an animation. I have no idea what's going on. Is there something I'm missing here? </p>
0
1,535
How to resize an iTextSharp.text.Image size into my code?
<p>I am pretty new in <strong>iText</strong> nd <strong>iTextSharp</strong> (the C# version of iText) and I have the following problem.</p> <p>I am inserting some jpg charts inside my PDF. These charts are rapresented by some jpg like this one:</p> <p><img src="https://i.stack.imgur.com/qeOA5.jpg" alt="enter image description here"></p> <p>I insert it into a table of my PDF in this way:</p> <pre><code>iTextSharp.text.Image img = null; .......................................... .......................................... .......................................... if (currentVuln.UrgencyRating &gt; 0) { img = ChartHelper.GetPdfChartV2((int)currentVuln.UrgencyRating * 10, _folderImages); vulnerabilityDetailsTable.AddCell(new PdfPCell(img) { Border = PdfPCell.RIGHT_BORDER, BorderColor = new BaseColor(79, 129, 189), BorderWidth = 1, Padding = 5, MinimumHeight = 30, PaddingTop = 10 }); } </code></pre> <p>And this is a section of the <strong>GetPdfChartV2()</strong> method in which I load a chart immage:</p> <pre><code> public static iTextSharp.text.Image GetPdfChartV2(int percentage, string _folderImmages) { iTextSharp.text.Image chart = null; string folderImmages = _folderImmages; if (percentage == 0) { return null; } else if (percentage == 10) { chart = iTextSharp.text.Image.GetInstance(_folderImmages + "1.jpg"); } else if (percentage == 20) { chart = iTextSharp.text.Image.GetInstance(_folderImmages + "2.jpg"); } .................................................... .................................................... .................................................... else if (percentage == 100) { chart = iTextSharp.text.Image.GetInstance(_folderImmages + "10.jpg"); } return chart; } } </code></pre> <p>The problem is that the chart immage is too big for my PDF and I obtain this orrible result:</p> <p><img src="https://i.stack.imgur.com/AFLWg.png" alt="enter image description here"></p> <p>So I have the following 2 questions:</p> <p>1) Can I resize the <strong>iTextSharp.text.Image</strong> size into my code or have I to do it with an image editor? If is it possible where have I to do it? when I load the immage into <strong>GetPdfChartV2()</strong> by the lines as:</p> <pre><code>chart = iTextSharp.text.Image.GetInstance(_folderImmages + "1.jpg"); </code></pre> <p>or when I put the immage into my PDF table cell:</p> <pre><code>vulnerabilityDetailsTable.AddCell(new PdfPCell(img) { Border = PdfPCell.RIGHT_BORDER, BorderColor = new BaseColor(79, 129, 189), BorderWidth = 1, Padding = 5, MinimumHeight = 30, PaddingTop = 10 }); </code></pre> <p>Can you help me to solve this issue?</p> <p>2) Why when I see the previous chart immage on my Windows Photo Viewer (100% of the size) I see it much smaller or here in the StackOverflow page?</p>
0
1,153
Implement pagination for React Material table
<p>I have this Spring Boot endpoint for listing items from database:</p> <pre><code>import React, { useEffect, useState } from &quot;react&quot;; import clsx from &quot;clsx&quot;; import { createStyles, lighten, makeStyles, Theme, } from &quot;@material-ui/core/styles&quot;; import CircularProgress from &quot;@material-ui/core/CircularProgress&quot;; import Table from &quot;@material-ui/core/Table&quot;; import TableBody from &quot;@material-ui/core/TableBody&quot;; import TableCell from &quot;@material-ui/core/TableCell&quot;; import TableContainer from &quot;@material-ui/core/TableContainer&quot;; import TableHead from &quot;@material-ui/core/TableHead&quot;; import TablePagination from &quot;@material-ui/core/TablePagination&quot;; import TableRow from &quot;@material-ui/core/TableRow&quot;; import TableSortLabel from &quot;@material-ui/core/TableSortLabel&quot;; import Toolbar from &quot;@material-ui/core/Toolbar&quot;; import Typography from &quot;@material-ui/core/Typography&quot;; import Paper from &quot;@material-ui/core/Paper&quot;; import Checkbox from &quot;@material-ui/core/Checkbox&quot;; import IconButton from &quot;@material-ui/core/IconButton&quot;; import Tooltip from &quot;@material-ui/core/Tooltip&quot;; import DeleteIcon from &quot;@material-ui/icons/Delete&quot;; import FilterListIcon from &quot;@material-ui/icons/FilterList&quot;; import axios, { AxiosResponse } from &quot;axios&quot;; import { getTask } from &quot;../../service/merchants&quot;; const baseUrl = &quot;http://185.185.126.15:8080/api&quot;; interface OnboardingTaskDto { id?: number; name: string; } async function getTask( page: number, size: number ): Promise&lt;AxiosResponse&lt;OnboardingTaskDto[]&gt;&gt; { return await axios.get&lt;OnboardingTaskDto[]&gt;( `${baseUrl}/management/onboarding/task?page=${page}&amp;size=${size}` ); } interface Data { id: number; businessName: string; title: string; status: string; } function createData( id: number, businessName: string, title: string, status: string ): Data { return { id, businessName, title, status }; } function descendingComparator&lt;T&gt;(a: T, b: T, orderBy: keyof T) { if (b[orderBy] &lt; a[orderBy]) { return -1; } if (b[orderBy] &gt; a[orderBy]) { return 1; } return 0; } type Order = &quot;asc&quot; | &quot;desc&quot;; function getComparator&lt;Key extends keyof any&gt;( order: Order, orderBy: Key ): ( a: { [key in Key]: number | string }, b: { [key in Key]: number | string } ) =&gt; number { return order === &quot;desc&quot; ? (a, b) =&gt; descendingComparator(a, b, orderBy) : (a, b) =&gt; -descendingComparator(a, b, orderBy); } function stableSort&lt;T&gt;(array: T[], comparator: (a: T, b: T) =&gt; number) { const stabilizedThis = array.map((el, index) =&gt; [el, index] as [T, number]); stabilizedThis.sort((a, b) =&gt; { const order = comparator(a[0], b[0]); if (order !== 0) return order; return a[1] - b[1]; }); return stabilizedThis.map((el) =&gt; el[0]); } interface HeadCell { disablePadding: boolean; id: keyof Data; label: string; numeric: boolean; } const headCells: HeadCell[] = [ { id: &quot;id&quot;, numeric: false, disablePadding: true, label: &quot;id&quot; }, { id: &quot;businessName&quot;, numeric: true, disablePadding: false, label: &quot;businessName&quot;, }, { id: &quot;title&quot;, numeric: true, disablePadding: false, label: &quot;title&quot; }, { id: &quot;status&quot;, numeric: true, disablePadding: false, label: &quot;status&quot; }, ]; interface EnhancedTableProps { classes: ReturnType&lt;typeof useStyles&gt;; numSelected: number; onRequestSort: ( event: React.MouseEvent&lt;unknown&gt;, property: keyof Data ) =&gt; void; onSelectAllClick: (event: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; void; order: Order; orderBy: string; rowCount: number; } function EnhancedTableHead(props: EnhancedTableProps) { const { classes, onSelectAllClick, order, orderBy, numSelected, rowCount, onRequestSort, } = props; const createSortHandler = (property: keyof Data) =&gt; (event: React.MouseEvent&lt;unknown&gt;) =&gt; { onRequestSort(event, property); }; return ( &lt;TableHead&gt; &lt;TableRow&gt; &lt;TableCell padding=&quot;checkbox&quot;&gt; &lt;Checkbox indeterminate={ numSelected &gt; 0 &amp;&amp; numSelected &lt; rowCount } checked={rowCount &gt; 0 &amp;&amp; numSelected === rowCount} onChange={onSelectAllClick} inputProps={{ &quot;aria-label&quot;: &quot;select all desserts&quot; }} /&gt; &lt;/TableCell&gt; {headCells.map((headCell) =&gt; ( &lt;TableCell key={headCell.id} align={headCell.numeric ? &quot;right&quot; : &quot;left&quot;} padding={headCell.disablePadding ? &quot;none&quot; : &quot;normal&quot;} sortDirection={orderBy === headCell.id ? order : false} &gt; &lt;TableSortLabel active={orderBy === headCell.id} direction={orderBy === headCell.id ? order : &quot;asc&quot;} onClick={createSortHandler(headCell.id)} &gt; {headCell.label} {orderBy === headCell.id ? ( &lt;span className={classes.visuallyHidden}&gt; {order === &quot;desc&quot; ? &quot;sorted descending&quot; : &quot;sorted ascending&quot;} &lt;/span&gt; ) : null} &lt;/TableSortLabel&gt; &lt;/TableCell&gt; ))} &lt;/TableRow&gt; &lt;/TableHead&gt; ); } const useToolbarStyles = makeStyles((theme: Theme) =&gt; createStyles({ root: { paddingLeft: theme.spacing(2), paddingRight: theme.spacing(1), }, highlight: theme.palette.type === &quot;light&quot; ? { color: theme.palette.secondary.main, backgroundColor: lighten( theme.palette.secondary.light, 0.85 ), } : { color: theme.palette.text.primary, backgroundColor: theme.palette.secondary.dark, }, title: { flex: &quot;1 1 100%&quot;, }, }) ); interface EnhancedTableToolbarProps { numSelected: number; onClick: (e: React.MouseEvent&lt;unknown&gt;) =&gt; void; } const EnhancedTableToolbar = (props: EnhancedTableToolbarProps) =&gt; { const classes = useToolbarStyles(); const { numSelected } = props; return ( &lt;Toolbar className={clsx(classes.root, { [classes.highlight]: numSelected &gt; 0, })} &gt; {numSelected &gt; 0 ? ( &lt;Typography className={classes.title} color=&quot;inherit&quot; variant=&quot;subtitle1&quot; component=&quot;div&quot; &gt; {numSelected} selected &lt;/Typography&gt; ) : ( &lt;Typography className={classes.title} variant=&quot;h6&quot; id=&quot;tableTitle&quot; component=&quot;div&quot; &gt; Customers &lt;/Typography&gt; )} {numSelected &gt; 0 ? ( &lt;Tooltip title=&quot;Delete&quot;&gt; &lt;IconButton aria-label=&quot;delete&quot; onClick={props.onClick}&gt; &lt;DeleteIcon /&gt; &lt;/IconButton&gt; &lt;/Tooltip&gt; ) : ( &lt;Tooltip title=&quot;Filter list&quot;&gt; &lt;IconButton aria-label=&quot;filter list&quot;&gt; &lt;FilterListIcon /&gt; &lt;/IconButton&gt; &lt;/Tooltip&gt; )} &lt;/Toolbar&gt; ); }; const useStyles = makeStyles((theme: Theme) =&gt; createStyles({ root: { width: &quot;100%&quot;, }, paper: { width: &quot;100%&quot;, marginBottom: theme.spacing(2), }, table: { minWidth: 750, }, visuallyHidden: { border: 0, clip: &quot;rect(0 0 0 0)&quot;, height: 1, margin: -1, overflow: &quot;hidden&quot;, padding: 0, position: &quot;absolute&quot;, top: 20, width: 1, }, }) ); export default function BusinessCustomersTable() { const classes = useStyles(); const [order, setOrder] = React.useState&lt;Order&gt;(&quot;asc&quot;); const [orderBy, setOrderBy] = React.useState&lt;keyof Data&gt;(&quot;businessName&quot;); const [selected, setSelected] = React.useState&lt;number[]&gt;([]); const [page, setPage] = React.useState(0); const [rowsPerPage, setRowsPerPage] = React.useState(5); const [rows, setRows] = useState&lt;Data[]&gt;([]); const [loading, setLoading] = useState(false); let updatedState: Data[] = []; // TODO - move this to API file const apiUrl = &quot;http://185.185.126.15:8080/api/management/onboarding/task&quot;; useEffect(() =&gt; { const getData = async () =&gt; { setLoading(true); getTask(1, 100) .then((resp) =&gt; { console.log(resp.data); }) .catch((error) =&gt; { console.error(error); }); const response = await axios.get(apiUrl, { params: { page: 1, size: 100 }, }); setLoading(false); const objContent: any = response.data.content; for (let a = 0; a &lt; objContent.length; a++) { updatedState[a] = createData( objContent[a].id, objContent[a].businessName, objContent[a].title, objContent[a].status ); setRows([...rows, ...updatedState]); } }; getData(); }, []); const handleRequestSort = ( event: React.MouseEvent&lt;unknown&gt;, property: keyof Data ) =&gt; { const isAsc = orderBy === property &amp;&amp; order === &quot;asc&quot;; setOrder(isAsc ? &quot;desc&quot; : &quot;asc&quot;); setOrderBy(property); }; const handleSelectAllClick = ( event: React.ChangeEvent&lt;HTMLInputElement&gt; ) =&gt; { if (event.target.checked) { const newSelecteds = rows.map((n) =&gt; n.id); setSelected(newSelecteds); return; } setSelected([]); }; const handleClick = (event: React.MouseEvent&lt;unknown&gt;, id: number) =&gt; { const selectedIndex = selected.indexOf(id); let newSelected: number[] = []; if (selectedIndex === -1) { newSelected = newSelected.concat(selected, id); } else if (selectedIndex === 0) { newSelected = newSelected.concat(selected.slice(1)); } else if (selectedIndex === selected.length - 1) { newSelected = newSelected.concat(selected.slice(0, -1)); } else if (selectedIndex &gt; 0) { newSelected = newSelected.concat( selected.slice(0, selectedIndex), selected.slice(selectedIndex + 1) ); } setSelected(newSelected); }; const handleChangePage = (event: unknown, newPage: number) =&gt; { setPage(newPage); }; const handleChangeRowsPerPage = ( event: React.ChangeEvent&lt;HTMLInputElement&gt; ) =&gt; { setRowsPerPage(parseInt(event.target.value, 10)); setPage(0); }; const handleDeleteClick = async () =&gt; { // npm install qs var qs = require(&quot;qs&quot;); const response = await axios.delete(apiUrl, { params: { ids: selected, }, paramsSerializer: (params) =&gt; { return qs.stringify(params); }, }); if (response.status === 204) { const updatedData = rows.filter( (row) =&gt; !selected.includes(row.id) ); // It'll return all data except selected ones setRows(updatedData); // reset rows to display in table. } }; const isSelected = (id: number) =&gt; selected.indexOf(id) !== -1; const emptyRows = rowsPerPage - Math.min(rowsPerPage, rows.length - page * rowsPerPage); return ( &lt;div className={classes.root}&gt; &lt;Paper className={classes.paper}&gt; &lt;EnhancedTableToolbar numSelected={selected.length} onClick={handleDeleteClick} /&gt; &lt;TableContainer&gt; &lt;Table className={classes.table} aria-labelledby=&quot;tableTitle&quot; aria-label=&quot;enhanced table&quot; &gt; &lt;EnhancedTableHead classes={classes} numSelected={selected.length} order={order} orderBy={orderBy} onSelectAllClick={handleSelectAllClick} onRequestSort={handleRequestSort} rowCount={rows.length} /&gt; &lt;TableBody&gt; {loading ? ( &lt;div className=&quot;spinerr&quot;&gt; &lt;CircularProgress /&gt; &lt;/div&gt; ) : null} {stableSort(rows, getComparator(order, orderBy)) .slice( page * rowsPerPage, page * rowsPerPage + rowsPerPage ) .map((row, index) =&gt; { const isItemSelected = isSelected(row.id); const labelId = `enhanced-table-checkbox-${index}`; return ( &lt;TableRow hover onClick={(event) =&gt; handleClick(event, row.id) } role=&quot;checkbox&quot; aria-checked={isItemSelected} tabIndex={-1} key={row.businessName} selected={isItemSelected} &gt; &lt;TableCell padding=&quot;checkbox&quot;&gt; &lt;Checkbox checked={isItemSelected} inputProps={{ &quot;aria-labelledby&quot;: labelId, }} /&gt; &lt;/TableCell&gt; &lt;TableCell component=&quot;th&quot; id={labelId} scope=&quot;row&quot; padding=&quot;none&quot; &gt; {row.id} &lt;/TableCell&gt; &lt;TableCell align=&quot;right&quot;&gt; {row.businessName} &lt;/TableCell&gt; &lt;TableCell align=&quot;right&quot;&gt; {row.title} &lt;/TableCell&gt; &lt;TableCell align=&quot;right&quot;&gt; {row.status} &lt;/TableCell&gt; &lt;/TableRow&gt; ); })} {emptyRows &gt; 0 &amp;&amp; ( &lt;TableRow style={{ height: 53 * emptyRows }}&gt; &lt;TableCell colSpan={6} /&gt; &lt;/TableRow&gt; )} &lt;/TableBody&gt; &lt;/Table&gt; &lt;/TableContainer&gt; &lt;TablePagination rowsPerPageOptions={[5, 10, 25]} component=&quot;div&quot; count={rows.length} rowsPerPage={rowsPerPage} page={page} onPageChange={handleChangePage} onRowsPerPageChange={handleChangeRowsPerPage} /&gt; &lt;/Paper&gt; &lt;/div&gt; ); } </code></pre> <p>Sandbox: <a href="https://stackblitz.com/edit/react-ts-tnpk85?file=Hello.tsx" rel="nofollow noreferrer">https://stackblitz.com/edit/react-ts-tnpk85?file=Hello.tsx</a></p> <p>When data is loaded first time and I switch pages I don't see additional requests to Back end. Looks like data table rows data is loaded only once. I need to implement a lazy pagination and load current page data when I switch page. Do you know how I can fix this?</p>
0
8,904
JavaScript template (underscore)
<p>Underscore has me stumped! In my code everything works in regards to getting the data after $.when. the console.log (posts); works but when i try to pass it into the template and reference </p> <pre><code>&lt;h1&gt;&lt;%=posts.id %&gt;&lt;/h1&gt; </code></pre> <p>I get "Uncaught ReferenceError: posts is not defined" on line </p> <pre><code>$("#target").html(_.template(template,posts)); </code></pre> <p>Here's the whole page</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="js/api.js"&gt;&lt;/script&gt; &lt;link href="css/styles.css" media="" rel="stylesheet" type="text/css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="target"&gt;&lt;/div&gt; &lt;!-- BEGIN: Underscore Template Definition. --&gt; &lt;script type="text/template" id="template"&gt; &lt;h1&gt;&lt;%=posts.id %&gt;&lt;/h1&gt; &lt;/script&gt; &lt;!-- END: Underscore Template Definition. --&gt; &lt;!-- Include and run scripts. --&gt; &lt;script src="js/jquery-1.9.1.min.js"&gt;&lt;/script&gt; &lt;script src="js/underscore.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $.when(results).done(function(posts){ var template = $("#template").html(); console.log(posts); $("#target").html(_.template(template,posts) ); }); &lt;/script&gt; &lt;/body&gt; </code></pre> <p></p> <pre><code>[Object] 0: Object created_at: "2013-04" id: "444556663333" num_comments: 1 num_likes: 0 text: "&lt;p&gt;dfgg&lt;/p&gt;" title: "title1" updated_at: "2013-04" user: Object first_name: "bob" id: "43633" last_name: "ddd" </code></pre> <p><em><strong></em>****</strong><em>Upadated</em><strong><em>*</em>**<em>*</em>**</strong> Thanks to all of you I got my templates working. _.each loops through an array of objects and populates chunks of html and data from an API. Now, what i need to do is pop open a modal with that specific posts content. Im struggling with my .click event. All of the different modals populate the correct data (when hidden, bootstrap modal) but im not sure how to reference them when i click on their corresponding div. I always get the post content for the first post. </p> <pre><code>$(".datachunk").click(function (){ $("#myModal").modal(); }); </code></pre> <p>.datachunk refers to the current div.datachunk you clicked on. Here is my template:</p> <pre><code> &lt;!-- BEGIN: Underscore Template Definition. --&gt; &lt;script type="text/template" id="template"&gt; &lt;% _.each(posts,function(post){ %&gt; &lt;div class = "datachunk borderBottom"&gt; &lt;div class="openModall"&gt;&lt;i class="icon-plus-sign-alt"&gt;&lt;/i&gt; &lt;/div&gt; &lt;h2&gt;&lt;%= post.title %&gt;&lt;/h2&gt; &lt;div class="postInfo"&gt; &lt;p&gt;&lt;%= post.user.first_name %&gt;&lt;%= post.user.last_name %&gt;&lt;/p&gt;&lt;p&gt; &lt;% var date=moment(post.created_at).format("M/DD/YYYY");%&gt; &lt;%= date %&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;!--datachunk--&gt; &lt;% }) %&gt; &lt;!--BEGIN Modal--&gt; &lt;% _.each(posts,function(post){ %&gt; &lt;div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria- labelledby="myModalLabel" aria-hidden="true"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;×&lt;/button&gt; &lt;div class="datachunk"&gt; &lt;div class= "postInfo"&gt; &lt;h2&gt;&lt;%= post.title %&gt;&lt;/h2&gt; &lt;p&gt;&lt;%= post.user.first_name %&gt;&lt;%= post.user.last_name %&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!--end modal header--&gt; &lt;div class="modal-body"&gt; &lt;p&gt;&lt;%=post.text %&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;!--END Modal--&gt; &lt;% }) %&gt; &lt;/script&gt; &lt;!-- END: Underscore Template Definition. --&gt; </code></pre>
0
1,809
Heroku code=H10 desc="App crashed" - Can't figure out why it's crashing
<p>I've been searching around on this one for a while and can't find anything that seems to be applicable in my situation. I've been staring at these logs and I can't see what the problem is. </p> <p>This has happened during deployments before, but always seemed to resolve itself. Now this just happened on its own (no deployment) and I can't get out of it. Tried reverting back to a previous version of the app, but it appears I'm stuck. I've reset the dyno and have also done a rake db:migrate.</p> <p>There are some repetitive things in the log, but I just don't know what to read out of them. Anybody have any idea where the problem is? Any guidance would be greatly appreciated. See the logs below.</p> <pre><code>Jun 18 15:51:54 snapclass-production app/heroku-postgres: source=HEROKU_POSTGRESQL_WHITE measure.current_transaction=1077 measure.db_size=6153016bytes measure.tables=0 measure.active-connections=3 measure.waiting-connections=0 measure.index-cache-hit-rate=0.99981 measure.table-cache-hit-rate=0.99349 Jun 18 15:52:06 snapclass-production heroku/router: at=error code=H10 desc="App crashed" method=GET path=/ host=www.snapclass.com fwd="46.165.195.139" dyno= connect= service= status=503 bytes= Jun 18 15:52:07 snapclass-production heroku/router: at=error code=H10 desc="App crashed" method=GET path=/ host=www.snapclass.com fwd="178.255.152.2" dyno= connect= service= status=503 bytes= Jun 18 15:52:12 snapclass-production app/postgres: [47-1] [] LOG: checkpoint starting: time Jun 18 15:52:13 snapclass-production app/postgres: [48-1] [] LOG: checkpoint complete: wrote 0 buffers (0.0%); 0 transaction log file(s) added, 0 removed, 0 recycled; write=0.000 s, sync=0.000 s, total=0.334 s; sync files=0, longest=0.000 s, average=0.000 s Jun 18 15:52:51 snapclass-production app/heroku-postgres: source=HEROKU_POSTGRESQL_WHITE measure.current_transaction=1077 measure.db_size=6153016bytes measure.tables=0 measure.active-connections=3 measure.waiting-connections=0 measure.index-cache-hit-rate=0.99994 measure.table-cache-hit-rate=0.99997 Jun 18 15:53:06 snapclass-production heroku/router: at=error code=H10 desc="App crashed" method=GET path=/ host=www.snapclass.com fwd="95.141.32.46" dyno= connect= service= status=503 bytes= Jun 18 15:53:48 snapclass-production app/heroku-postgres: source=HEROKU_POSTGRESQL_WHITE measure.current_transaction=1077 measure.db_size=6153016bytes measure.tables=0 measure.active-connections=3 measure.waiting-connections=0 measure.index-cache-hit-rate=0.97826 measure.table-cache-hit-rate=0.99999 Jun 18 15:54:06 snapclass-production heroku/router: at=error code=H10 desc="App crashed" method=GET path=/ host=www.snapclass.com fwd="95.211.217.68" dyno= connect= service= status=503 bytes= Jun 18 15:54:17 snapclass-production heroku/router: at=error code=H10 desc="App crashed" method=GET path=/ host=www.snapclass.com fwd="205.197.158.210" dyno= connect= service= status=503 bytes= Jun 18 15:54:17 snapclass-production heroku/router: at=error code=H10 desc="App crashed" method=GET path=/favicon.ico host=www.snapclass.com fwd="205.197.158.210" dyno= connect= service= status=503 bytes= Jun 18 15:54:25 snapclass-production heroku/router: at=error code=H10 desc="App crashed" method=GET path=/ host=demosidney.snapclass.com fwd="202.46.61.33" dyno= connect= service= status=503 bytes= Jun 18 15:54:44 snapclass-production heroku/web.1: State changed from crashed to starting Jun 18 15:54:44 snapclass-production app/heroku-postgres: source=HEROKU_POSTGRESQL_WHITE measure.current_transaction=1077 measure.db_size=6153016bytes measure.tables=0 measure.active-connections=3 measure.waiting-connections=0 measure.index-cache-hit-rate=0.98897 measure.table-cache-hit-rate=0.99087 Jun 18 15:54:48 snapclass-production heroku/web.1: Starting process with command `bundle exec thin start -R config.ru -e $RAILS_ENV -p 50180` Jun 18 15:55:40 snapclass-production app/heroku-postgres: source=HEROKU_POSTGRESQL_WHITE measure.current_transaction=1077 measure.db_size=6153016bytes measure.tables=0 measure.active-connections=3 measure.waiting-connections=0 measure.index-cache-hit-rate=0.99926 measure.table-cache-hit-rate=0.99996 Jun 18 15:55:50 snapclass-production heroku/web.1: Error R10 (Boot timeout) -&gt; Web process failed to bind to $PORT within 60 seconds of launch Jun 18 15:55:50 snapclass-production heroku/web.1: Stopping process with SIGKILL Jun 18 15:55:51 snapclass-production heroku/web.1: Process exited with status 137 Jun 18 15:55:51 snapclass-production heroku/web.1: State changed from starting to crashed Jun 18 15:55:52 snapclass-production heroku/router: at=error code=H10 desc="App crashed" method=GET path=/ host=demosidney.snapclass.com fwd="119.63.193.130" dyno= connect= service= status=503 bytes= Jun 18 15:55:52 snapclass-production heroku/router: at=error code=H10 desc="App crashed" method=GET path=/snapclasses/sat-prep-math/register host=www.snapclass.com fwd="173.199.115.115" dyno= connect= service= status=503 bytes= Jun 18 15:55:53 snapclass-production heroku/router: at=error code=H10 desc="App crashed" method=GET path=/ host=www.snapclass.com fwd="23.21.36.78" dyno= connect= service= status=503 bytes= Jun 18 15:55:54 snapclass-production heroku/router: at=error code=H10 desc="App crashed" method=GET path=/ host=www.snapclass.com fwd="23.22.98.102" dyno= connect= service= status=503 bytes= Jun 18 15:55:54 snapclass-production heroku/router: at=error code=H10 desc="App crashed" method=GET path=/ host=www.snapclass.com fwd="91.109.115.41" dyno= connect= service= status=503 bytes= Jun 18 15:56:06 snapclass-production heroku/router: at=error code=H10 desc="App crashed" method=GET path=/ host=www.snapclass.com fwd="174.34.224.167" dyno= connect= service= status=503 bytes= </code></pre>
0
1,971
notifyDatasetChanged() is not working in Kotlin
<ul> <li><code>notifyDatasetChanged()</code> is not working, But instead of <code>notifydatasetChanged()</code>, if i pass the <code>eventList</code> with data to adapter directly after initializing <code>recyclerview</code> list loads fine.</li> <li>How to resolve this</li> </ul> <hr> <p><strong>ActEvents.kt</strong></p> <pre><code>class ActEvents : AppCompatActivity(){ // Initializing an empty ArrayList to be filled with animals var eventList: MutableList&lt;TestModel&gt; = ArrayList() @set:Inject var retrofit: Retrofit? = null private lateinit var personDisposable: Disposable /******************* Life Cycle Methods *************************/ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initOnCreate() } override fun onDestroy() { super.onDestroy() initOnDestroy() } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } override fun onCreateOptionsMenu(menu: Menu): Boolean { initOnCreateOptionsMenu(menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return initOnOptionsItemSelected(item) } /******************* Life Cycle Methods *************************/ /******************** Subscribers *******************************/ private fun setRxJavaRecievers() { personDisposable = RxBus.listen(RxEvent.RxEventList::class.java).subscribe { eventList = it.personName.getmData() event_list.adapter!!.notifyDataSetChanged() } } /******************** Subscribers *******************************/ /******************* Init Methods *******************************/ /** Init On Create **/ private fun initOnCreate() { //Set up the UI setContentView(R.layout.act_events) //Inject Dagger Component (application as CaringApp).netComponent.inject(this) //Set up toolbar setToolbar() //Set up the recycler view initRecyclerView() //Set Rx java receivers setRxJavaRecievers() } /** Init On Destroy **/ private fun initOnDestroy() { //Un Register disposable if (!personDisposable.isDisposed) personDisposable.dispose() } /** Initialize recyclerView **/ private fun initRecyclerView() { val mLayoutManager = LinearLayoutManager(applicationContext) event_list.layoutManager = mLayoutManager event_list.itemAnimator = DefaultItemAnimator() event_list.adapter = AdptEvents(eventList,this) } /******************* Init Methods *******************************/ } </code></pre> <p><strong>AdptEvents.kt</strong></p> <pre><code>class AdptEvents (val items: MutableList&lt;TestModel&gt;, val context: Context) : RecyclerView.Adapter&lt;ViewHolder&gt;() { override fun onCreateViewHolder(parent: ViewGroup, p1: Int): ViewHolder { return ViewHolder(LayoutInflater.from(context).inflate(R.layout.row_event, parent, false)) } override fun getItemCount(): Int { return items.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.tvAnimalType.text = items[position].getName() } } class ViewHolder (view: View) : RecyclerView.ViewHolder(view) { // Holds the TextView that will add each animal to val tvAnimalType = view.txtTitle!! } </code></pre>
0
1,274
JavaFX position dialog and stage in center of screen
<p>The following codes demonstrates centering of a dialog and the stage in the center of the screen. The dialog is supposed to be displayed first for the user to enter the login credentials. After successful login, the main window (stage) is then displayed. I found the solution of centering the dialog and stage from this web site, but it doesn't seem very ideal. For both the dialog and stage, they have to be displayed first before we can calculate the coordinates and then positioning them in the center. This means that we can see the dialog and the main window moving to the center after they are displayed. Is there a better way? Ideally, they should be positioned in the center before they are displayed.</p> <pre><code>import javafx.application.Application; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.geometry.Rectangle2D; import javafx.scene.Cursor; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.Alert.AlertType; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.stage.Window; public class Demo extends Application { private Stage primaryStage; private Dialog&lt;String&gt; dialog; private Button createUserButton = new Button("Create User"); @Override public void start(Stage primaryStage) throws Exception { this.primaryStage = primaryStage; Text usersLabel = new Text("Current Users:"); TableColumn&lt;User, String&gt; indexColumn = new TableColumn&lt;User, String&gt;("No."); indexColumn.setMaxWidth(1f * Integer.MAX_VALUE * 10); indexColumn.setCellValueFactory(p -&gt; p.getValue().indexProperty()); TableColumn&lt;User, String&gt; userNameColumn = new TableColumn&lt;User, String&gt;("User Name"); userNameColumn.setMaxWidth(1f * Integer.MAX_VALUE * 60); userNameColumn.setCellValueFactory(p -&gt; p.getValue().userNameProperty()); TableColumn&lt;User, String&gt; roleColumn = new TableColumn&lt;User, String&gt;("Role"); roleColumn.setMaxWidth(1f * Integer.MAX_VALUE * 30); roleColumn.setCellValueFactory(p -&gt; p.getValue().roleProperty()); TableView&lt;User&gt; tableView = new TableView&lt;User&gt;(); tableView.getColumns().add(indexColumn); tableView.getColumns().add(userNameColumn); tableView.getColumns().add(roleColumn); tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); Text dummyLabel = new Text(""); VBox leftPane = new VBox(5); leftPane.getChildren().addAll(usersLabel, tableView); VBox rightPane = new VBox(20); rightPane.setFillWidth(true); rightPane.getChildren().addAll(dummyLabel, createUserButton); GridPane mainPane = new GridPane(); mainPane.setPadding(new Insets(10, 0, 0, 10)); mainPane.setHgap(20); mainPane.add(leftPane, 0, 0); mainPane.add(rightPane, 1, 0); Scene scene = new Scene(mainPane); primaryStage.setScene(scene); primaryStage.setResizable(false); showDialog(); } private void showDialog() { dialog = new Dialog&lt;&gt;(); dialog.setTitle("Login"); dialog.setHeaderText("Please enter User Name and Password to login."); dialog.setResizable(false); Label userNameLabel = new Label("User Name:"); Label passwordLabel = new Label("Password:"); TextField userNameField = new TextField(); PasswordField passwordField = new PasswordField(); GridPane grid = new GridPane(); grid.setAlignment(Pos.CENTER); grid.setHgap(10); grid.setVgap(10); grid.setPadding(new Insets(20, 35, 20, 35)); grid.add(userNameLabel, 1, 1); grid.add(userNameField, 2, 1); grid.add(passwordLabel, 1, 2); grid.add(passwordField, 2, 2); dialog.getDialogPane().setContent(grid); dialog.getDialogPane().getButtonTypes().add(ButtonType.OK); Button okButton = (Button) dialog.getDialogPane().lookupButton(ButtonType.OK); okButton.addEventFilter(ActionEvent.ACTION, event -&gt; { createUser(userNameField.getText().trim(), passwordField.getText()); event.consume(); }); dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL); Platform.runLater(() -&gt; { Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds(); Window window = dialog.getDialogPane().getScene().getWindow(); window.setX((screenBounds.getWidth() - window.getWidth()) / 2); window.setY((screenBounds.getHeight() - window.getHeight()) / 2); }); dialog.showAndWait(); } private void createUser(String userName, String password) { dialog.getDialogPane().setDisable(true); dialog.getDialogPane().getScene().setCursor(Cursor.WAIT); Task&lt;Boolean&gt; task = new Task&lt;Boolean&gt;() { @Override public Boolean call() { try { Thread.sleep(100); } catch (InterruptedException exception) { } return Boolean.TRUE; } }; task.setOnSucceeded(e -&gt; { Boolean success = task.getValue(); dialog.getDialogPane().setDisable(false); dialog.getDialogPane().getScene().setCursor(Cursor.DEFAULT); if (success.booleanValue()) { Platform.runLater(() -&gt; { dialog.close(); primaryStage.show(); Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds(); primaryStage.setX((screenBounds.getWidth() - primaryStage.getWidth()) / 2); primaryStage.setY((screenBounds.getHeight() - primaryStage.getHeight()) / 2); }); } else { Alert alert = new Alert(AlertType.ERROR); alert.setTitle("Login Error"); alert.setHeaderText("Unable to login."); alert.showAndWait(); } }); new Thread(task).start(); } public static void main(String[] arguments) { Application.launch(arguments); } } class User { private StringProperty index; private StringProperty userName; private StringProperty role; public String getIndex() { return indexProperty().get(); } public StringProperty indexProperty() { if (index == null) { index = new SimpleStringProperty(this, "index"); } return index; } public void setIndex(String index) { indexProperty().set(index); } public String getUserName() { return userNameProperty().get(); } public StringProperty userNameProperty() { if (userName == null) { userName = new SimpleStringProperty(this, "userName"); } return userName; } public void setUserName(String userName) { userNameProperty().set(userName); } public String getRole() { return roleProperty().get(); } public StringProperty roleProperty() { if (role == null) { role = new SimpleStringProperty(this, "role"); } return role; } public void setRole(String role) { roleProperty().set(role); } } </code></pre> <p>Below is solution by setting custom dimensions to stage and dialog. It works for the stage but it doesn't work for the dialog.</p> <pre><code>import javafx.application.Application; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.geometry.Rectangle2D; import javafx.scene.Cursor; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.Alert.AlertType; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.stage.Window; import javafx.stage.WindowEvent; public class Demo extends Application { private Stage primaryStage; private Dialog&lt;String&gt; dialog; private Button createUserButton = new Button("Create User"); @Override public void start(Stage primaryStage) throws Exception { this.primaryStage = primaryStage; Text usersLabel = new Text("Current Users:"); TableColumn&lt;User, String&gt; indexColumn = new TableColumn&lt;User, String&gt;("No."); indexColumn.setMaxWidth(1f * Integer.MAX_VALUE * 10); indexColumn.setCellValueFactory(p -&gt; p.getValue().indexProperty()); TableColumn&lt;User, String&gt; userNameColumn = new TableColumn&lt;User, String&gt;("User Name"); userNameColumn.setMaxWidth(1f * Integer.MAX_VALUE * 60); userNameColumn.setCellValueFactory(p -&gt; p.getValue().userNameProperty()); TableColumn&lt;User, String&gt; roleColumn = new TableColumn&lt;User, String&gt;("Role"); roleColumn.setMaxWidth(1f * Integer.MAX_VALUE * 30); roleColumn.setCellValueFactory(p -&gt; p.getValue().roleProperty()); TableView&lt;User&gt; tableView = new TableView&lt;User&gt;(); tableView.getColumns().add(indexColumn); tableView.getColumns().add(userNameColumn); tableView.getColumns().add(roleColumn); tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); Text dummyLabel = new Text(""); VBox leftPane = new VBox(5); leftPane.getChildren().addAll(usersLabel, tableView); VBox rightPane = new VBox(20); rightPane.setFillWidth(true); rightPane.getChildren().addAll(dummyLabel, createUserButton); GridPane mainPane = new GridPane(); mainPane.setPadding(new Insets(10, 0, 0, 10)); mainPane.setHgap(20); mainPane.add(leftPane, 0, 0); mainPane.add(rightPane, 1, 0); float width = 372f; float height = 470f; Scene scene = new Scene(mainPane, width, height); primaryStage.setScene(scene); primaryStage.setResizable(false); Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds(); primaryStage.setX((screenBounds.getWidth() - width) / 2); primaryStage.setY((screenBounds.getHeight() - height) / 2); showDialog(); } private void showDialog() { dialog = new Dialog&lt;&gt;(); dialog.setTitle("Login"); dialog.setHeaderText("Please enter User Name and Password to login."); dialog.setResizable(false); Label userNameLabel = new Label("User Name:"); Label passwordLabel = new Label("Password:"); TextField userNameField = new TextField(); PasswordField passwordField = new PasswordField(); GridPane grid = new GridPane(); grid.setAlignment(Pos.CENTER); grid.setHgap(10); grid.setVgap(10); grid.setPadding(new Insets(20, 35, 20, 35)); grid.add(userNameLabel, 1, 1); grid.add(userNameField, 2, 1); grid.add(passwordLabel, 1, 2); grid.add(passwordField, 2, 2); dialog.getDialogPane().setContent(grid); dialog.getDialogPane().getButtonTypes().add(ButtonType.OK); Button okButton = (Button) dialog.getDialogPane().lookupButton(ButtonType.OK); okButton.addEventFilter(ActionEvent.ACTION, event -&gt; { login(userNameField.getText().trim(), passwordField.getText()); event.consume(); }); dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL); float width = 509f; float height = 168f; dialog.setWidth(width); dialog.setHeight(height); Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds(); dialog.setX((screenBounds.getWidth() - width) / 2); dialog.setY((screenBounds.getHeight() - height) / 2); dialog.showAndWait(); } private void login(String userName, String password) { dialog.getDialogPane().setDisable(true); dialog.getDialogPane().getScene().setCursor(Cursor.WAIT); Task&lt;Boolean&gt; task = new Task&lt;Boolean&gt;() { @Override public Boolean call() { try { Thread.sleep(100); } catch (InterruptedException exception) { } return Boolean.TRUE; } }; task.setOnSucceeded(e -&gt; { Boolean success = task.getValue(); dialog.getDialogPane().setDisable(false); dialog.getDialogPane().getScene().setCursor(Cursor.DEFAULT); if (success.booleanValue()) { Platform.runLater(() -&gt; { primaryStage.show(); }); } else { Alert alert = new Alert(AlertType.ERROR); alert.setTitle("Login Error"); alert.setHeaderText("Unable to login."); alert.showAndWait(); } }); new Thread(task).start(); } public static void main(String[] arguments) { Application.launch(arguments); } } class User { private StringProperty index; private StringProperty userName; private StringProperty role; public String getIndex() { return indexProperty().get(); } public StringProperty indexProperty() { if (index == null) { index = new SimpleStringProperty(this, "index"); } return index; } public void setIndex(String index) { indexProperty().set(index); } public String getUserName() { return userNameProperty().get(); } public StringProperty userNameProperty() { if (userName == null) { userName = new SimpleStringProperty(this, "userName"); } return userName; } public void setUserName(String userName) { userNameProperty().set(userName); } public String getRole() { return roleProperty().get(); } public StringProperty roleProperty() { if (role == null) { role = new SimpleStringProperty(this, "role"); } return role; } public void setRole(String role) { roleProperty().set(role); } } </code></pre> <p>JKostikiadis's solution:</p> <pre><code>import javafx.application.Application; import javafx.geometry.Pos; import javafx.geometry.Rectangle2D; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.layout.HBox; import javafx.stage.Screen; import javafx.stage.Stage; public class TestApp extends Application { private static final double WIDTH = 316.0; private static final double HEIGHT = 339.0; public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws Exception { HBox pane = new HBox(); pane.setAlignment(Pos.CENTER); Button b = new Button("click me"); b.setOnAction(e -&gt; { showDialog(); }); pane.getChildren().add(b); Scene scene = new Scene(pane, 300, 300); stage.setScene(scene); centerStage(stage, WIDTH, HEIGHT); stage.show(); } private void showDialog() { Alert dialog = new Alert(AlertType.ERROR); dialog.setTitle("Error Dialog"); dialog.setHeaderText("Look, an Error Dialog"); dialog.setContentText("Ooops, there was an error!\nOoops, there was an error!"); Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow(); centerStage(stage, -10000, -10000); dialog.show(); System.out.println(stage.getWidth() + " " + stage.getHeight()); dialog.hide(); centerStage(stage, stage.getWidth(), stage.getHeight()); dialog.showAndWait(); } private void centerStage(Stage stage, double width, double height) { Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds(); stage.setX((screenBounds.getWidth() - width) / 2); stage.setY((screenBounds.getHeight() - height) / 2); } } </code></pre>
0
7,161
import matplotlib.pyplot hangs
<p>I'm trying to get matplotlib up and running on OS X 10.8.4. I've installed matplotlib and the dependencies (libping, freetype, numpy, scipy). I am able to import matplotlib just fine. However, if I try to import matplotlib.pyplot, it just hangs. There's no error, it's just that nothing happens.</p> <pre><code>&gt;&gt;&gt; import matplotlib.pyplot </code></pre> <p>...I've waited maybe 20 minutes an nothing happens. I'm using version 1.2.1, but even uninstalled that and tried version 1.2.0, but to no avail. I've seen a number of questions on SO about import errors with matplotlib.pyplot, but nothing where it just hangs. I then tried to get it working using the Enthought/Canopy python distribution, but again, the same hanging issue. Here's what I see if I kill the import:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages/matplotlib/pyplot.py", line 26, in &lt;module&gt; from matplotlib.figure import Figure, figaspect File "/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages/matplotlib/figure.py", line 34, in &lt;module&gt; import matplotlib.colorbar as cbar File "/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages/matplotlib/colorbar.py", line 29, in &lt;module&gt; import matplotlib.collections as collections File "/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages/matplotlib/collections.py", line 23, in &lt;module&gt; import matplotlib.backend_bases as backend_bases File "/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 37, in &lt;module&gt; import matplotlib.widgets as widgets File "/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages/matplotlib/widgets.py", line 17, in &lt;module&gt; from lines import Line2D File "/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages/matplotlib/lines.py", line 25, in &lt;module&gt; from matplotlib.font_manager import FontProperties File "/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages/matplotlib/font_manager.py", line 1335, in &lt;module&gt; _rebuild() File "/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages/matplotlib/font_manager.py", line 1322, in _rebuild fontManager = FontManager() File "/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages/matplotlib/font_manager.py", line 980, in __init__ self.ttffiles = findSystemFonts(paths) + findSystemFonts() File "/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages/matplotlib/font_manager.py", line 317, in findSystemFonts for f in get_fontconfig_fonts(fontext): File "/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/site-packages/matplotlib/font_manager.py", line 274, in get_fontconfig_fonts output = pipe.communicate()[0] File "/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/subprocess.py", line 746, in communicate stdout = _eintr_retry_call(self.stdout.read) File "/Applications/Canopy.app/appdata/canopy-1.0.3.1262.macosx-x86_64/Canopy.app/Contents/lib/python2.7/subprocess.py", line 478, in _eintr_retry_call return func(*args) KeyboardInterrupt </code></pre> <p>The output was the same when I was using the default python 2.7 that comes with OS X.</p> <h3>UPDATE</h3> <p>Allowing <code>import matplotlib.pyplot</code> to run for a few hours and then interrupting the import now gives me this output:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Library/Python/2.7/site-packages/matplotlib/pyplot.py", line 26, in &lt;module&gt; from matplotlib.figure import Figure, figaspect File "/Library/Python/2.7/site-packages/matplotlib/figure.py", line 34, in &lt;module&gt; import matplotlib.colorbar as cbar File "/Library/Python/2.7/site-packages/matplotlib/colorbar.py", line 29, in &lt;module&gt; import matplotlib.collections as collections File "/Library/Python/2.7/site-packages/matplotlib/collections.py", line 23, in &lt;module&gt; import matplotlib.backend_bases as backend_bases File "/Library/Python/2.7/site-packages/matplotlib/backend_bases.py", line 37, in &lt;module&gt; import matplotlib.widgets as widgets File "/Library/Python/2.7/site-packages/matplotlib/widgets.py", line 17, in &lt;module&gt; from lines import Line2D File "/Library/Python/2.7/site-packages/matplotlib/lines.py", line 25, in &lt;module&gt; from matplotlib.font_manager import FontProperties File "/Library/Python/2.7/site-packages/matplotlib/font_manager.py", line 1335, in &lt;module&gt; _rebuild() File "/Library/Python/2.7/site-packages/matplotlib/font_manager.py", line 1322, in _rebuild fontManager = FontManager() File "/Library/Python/2.7/site-packages/matplotlib/font_manager.py", line 980, in __init__ self.ttffiles = findSystemFonts(paths) + findSystemFonts() File "/Library/Python/2.7/site-packages/matplotlib/font_manager.py", line 324, in findSystemFonts files = list_fonts(path, fontexts) File "/Library/Python/2.7/site-packages/matplotlib/font_manager.py", line 171, in list_fonts return cbook.listFiles(directory, pattern) File "/Library/Python/2.7/site-packages/matplotlib/cbook.py", line 944, in listFiles for dirname, dirs, files in os.walk(root): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 284, in walk if isdir(join(top, name)): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py", line 41, in isdir st = os.stat(s) KeyboardInterrupt </code></pre> <p>Does anyone know what the recursive <code>for x in walk(new_path, topdown, onerror, followlinks):</code> might indicate?</p>
0
7,935
Steps for changing process template for an existing project in TFS 2010
<p>I have an TFS server installation that through time has gone through upgrades from TFS 2005 to TFS 2008 and then to TFS 2010. During the lifetime of the installation a lot of projects have been created and different project templates have been used. MSF Agile 4.0, 4.1, 4.2 and 5.0. and a few MSF CMMI ones.</p> <p>What I would like to do is "replace" the project template used for all these projects to use a new one common one: Microsoft Visual Studio Scrum 1.0.</p> <p>I am aware that TFS project templates are used as <em>templates</em> for creating new projects and cannot modify the tfs projects definitions after creation.</p> <p>Uptil now only the version control and build server part of TFS have been used and there are no existing work item types.</p> <p>Additionally all projects and build scripts are depending on the source code paths stay the same.</p> <p>As I see it I have the following options:</p> <p><strong>Create new TFS projects using the correct project template and then move/branch the source code to the new project.</strong> </p> <ol> <li>All code is moved to a temporary team project. </li> <li>The old project is deleted </li> <li>New project with the original name and correct process template is created </li> <li>Code is moved to the new team project </li> <li><p>Temporary team project is deleted</p> <ul> <li><p>All the build definitions needs to be to recreated which is not an option.</p></li> <li><p>The source code move/branch will "mess up" the versioning history</p></li> </ul></li> </ol> <p><img src="https://i.stack.imgur.com/SVezi.jpg" alt="alt text"><br> By messing up the versioning history I mean that when you move source code it will behind the scenes do a delete + source rename on the original location and the history will still be located in the old project. This will make searching in the history difficult and if I actually delete the old project I will loose all the history before the source code move.</p> <p>This is really not an option for me since there is years of code change history that is needed to for supporting the different applications being built.</p> <p><strong>Use the TFS migration tools to migrate to another TFS project</strong></p> <ul> <li>This has the same downsides as the first solution</li> </ul> <p><strong>Replace/import work item types, install new reports, create new SharePoint sites</strong></p> <p>For each tfs project</p> <ul> <li><p>Delete existing work item definitions using "witadmin deletewitd"</p></li> <li><p>Import each work item definition from the new process template using "witadmin importwitd"</p></li> <li><p>Import work item categories using "witadmin importcategories"</p></li> <li><p>Delete old reports in project folder in report server</p></li> <li><p>Upload the report definitions from the new process template</p></li> <li><p>Modify data sources used for the reports using the report manager to point to the correct shared data sources (TfsReportDS and TfsOlapReportsDS)</p></li> <li><p>Modify the report parameter ExplicitProject default value to "" (empty string) and disable prompt user option.</p></li> <li><p>Export the documents in the old SharePoint site using stsadm</p></li> <li><p>Delete the old SharePoint site</p></li> <li><p>Recreate the sharepoint site using the TFS2010 Agile Dashboard site template</p></li> <li><p>Activate site feature "Team Foundation Server Scrum dashboard"</p></li> <li><p>In TFS Project Settings -> Project Portal Settings: Enable "team project portal" and ensure the url is correct. Enable "reports and dashboards refer to data for this team project"</p></li> </ul> <p>And finally..</p> <ul> <li><p>Process the Warehouse</p></li> <li><p>Process the Analysis Database</p></li> </ul> <p>Even though that this involves a lot of small steps this looks more appealing because this option will not force me to move the source code and my existing build definitions will be intact.</p> <p><strong>My question:</strong></p> <p>Are there other ways to achieve the replacement of work item types that I haven't mentioned?</p> <p>And/or am I missing any steps in last solution?</p>
0
1,177
How to stick footer to bottom (not fixed) even with scrolling
<p>I want the footer of this page to stick to the bottom, below all content, but not fixed in the screen. The problem is that when the body has more than 100% of height, the footer stay in the middle of the screen, and not in the bottom.</p> <p>I've seen a lot of tutorials on how to achieve this, using &quot;position: absolute&quot; + &quot;bottom: 0&quot; and stuff, but everything failed.</p> <p>Check it out:</p> <pre class="lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;iso-8859-1&quot; /&gt; &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;index.css&quot; /&gt; &lt;link href='https://fonts.googleapis.com/css?family=Arvo|Open+Sans|Ubuntu+Roboto' rel='stylesheet' type='text/css'&gt; &lt;title&gt;Matheus's Page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;wrapper&quot;&gt; &lt;header&gt; &lt;div class=&quot;title-div&quot;&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;/div&gt; &lt;nav&gt; &lt;ul&gt; &lt;li&gt; &lt;h3&gt;Home&lt;/h3&gt; &lt;/li&gt; &lt;li&gt; &lt;h3&gt;Articles&lt;/h3&gt; &lt;/li&gt; &lt;li&gt; &lt;h3&gt;Perfil&lt;/h3&gt; &lt;/li&gt; &lt;li&gt; &lt;h3&gt;Settings&lt;/h3&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/header&gt; &lt;div id=&quot;body&quot;&gt; &lt;p&gt;Texto teste Texto teste Texto teste Texto teste Texto teste Texto teste Texto teste Texto teste Texto teste Texto teste &lt;/p&gt; &lt;/div&gt; &lt;footer&gt; &lt;p&gt;Footer&lt;/p&gt; &lt;/footer&gt; &lt;div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>CSS:</p> <pre class="lang-css prettyprint-override"><code>body { font-family: 'Arvo', serif; height: 100%; margin: 0; padding: 0; } #wrapper { min-height: 100%; } header { position: absolute; float: top; width: 100%; height: 8%; background-color: #424242; color: #FFD740; } .title-div { position: absolute; height: 100%; margin: auto 5%; padding-right: 3%; border-right: solid 2px #FFD740; } header nav { position: absolute; width: 75%; left: 15%; } header ul { list-style: none outside none; } header ul li { display: inline-block; margin: auto 2% auto 0; } #body { padding: 10px; padding-top: 8%; padding-bottom: 15%; /* Height of the footer */ } footer { position: absolute; width: 100%; height: 15%; right: 0; bottom: 0; left: 0; color: #FFD740; background-color: #424242; clear: both; } </code></pre> <p>Link to printscreen of the result:</p> <p><img src="https://i.stack.imgur.com/s2LhG.png" alt="link to printscreen of the result" /></p>
0
1,350
SqlBulkCopy Multiple Tables Insert under single Transaction OR Bulk Insert Operation between Entity Framework and Classic Ado.net
<p>I have two tables which need to be inserted when my application run.<br> Let's say that I have tables as followed</p> <ul> <li>tbl_FirstTable and tbl_SecondTable</li> </ul> <p>My problem is data volume.<br> I need to insert over 10,000 rows to tbl_FirstTable and over 500,000 rows to tbl_SecondTable.</p> <p>So fristly, I use entity framework as follow.</p> <pre><code>public bool Save_tbl_FirstTable_Vs_tbl_SecondTable(List&lt;tbl_FirstTable&gt; List_tbl_FirstTable, List&lt;tbl_SecondTable&gt; List_tbl_SecondTable) { bool IsSuccessSave = false; try { using (DummyDBClass_ObjectContext _DummyDBClass_ObjectContext = new DummyDBClass_ObjectContext()) { foreach (tbl_FirstTable _tbl_FirstTable in List_tbl_FirstTable) { _DummyDBClass_ObjectContext.tbl_FirstTable.InsertOnSubmit(_tbl_FirstTable); } foreach (tbl_SecondTable _tbl_SecondTable in List_tbl_SecondTable) { _DummyDBClass_ObjectContext.tbl_SecondTable.InsertOnSubmit(_tbl_SecondTable); } _DummyDBClass_ObjectContext.SubmitChanges(); IsSuccessSave = true; } } catch (Exception ex) { Log4NetWrapper.WriteError(string.Format("{0} : {1} : Exception={2}", this.GetType().FullName, (new StackTrace(new StackFrame(0))).GetFrame(0).GetMethod().Name.ToString(), ex.Message.ToString())); if (ex.InnerException != null) { Log4NetWrapper.WriteError(string.Format("{0} : {1} : InnerException Exception={2}", this.GetType().FullName, (new StackTrace(new StackFrame(0))).GetFrame(0).GetMethod().Name.ToString(), ex.InnerException.Message.ToString())); } } return IsSuccessSave; } </code></pre> <p>That is the place I face error <code>Time out exception</code>.<br> I think that exception will be solved If I use below code.</p> <pre><code>DummyDBClass_ObjectContext.CommandTimeout = 1800; // 30 minutes </code></pre> <p>So I used it. It solved but I face another error <code>OutOfMemory Exception</code>.<br> So I searched the solutions, fortunately, I found below articles.</p> <ol> <li> <a href="http://praneethmoka.wordpress.com/2012/02/22/problem-with-bulk-insert-using-entity-framework/" rel="noreferrer">Problem with Bulk insert using Entity Framework</a> </li> <li> <a href="https://web.archive.org/web/20211016211619/http://www.4guysfromrolla.com/articles/111109-1.aspx" rel="noreferrer">Using Transactions with SqlBulkCopy</a> </li> <li> <a href="http://msdn.microsoft.com/en-sg/library/tchktcdk(v=vs.80).aspx" rel="noreferrer">Performing a Bulk Copy Operation in a Transaction</a> </li> </ol> <p>According to that articles, I change my code from Entity Framework to Classic ADO.net code.</p> <pre><code>public bool Save_tbl_FirstTable_Vs_tbl_SecondTable(DataTable DT_tbl_FirstTable, DataTable DT_tbl_SecondTable) { bool IsSuccessSave = false; SqlTransaction transaction = null; try { using (DummyDBClass_ObjectContext _DummyDBClass_ObjectContext = new DummyDBClass_ObjectContext()) { var connectionString = ((EntityConnection)_DummyDBClass_ObjectContext.Connection).StoreConnection.ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (transaction = connection.BeginTransaction()) { using (SqlBulkCopy bulkCopy_tbl_FirstTable = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) { bulkCopy_tbl_FirstTable.BatchSize = 5000; bulkCopy_tbl_FirstTable.DestinationTableName = "dbo.tbl_FirstTable"; bulkCopy_tbl_FirstTable.ColumnMappings.Add("ID", "ID"); bulkCopy_tbl_FirstTable.ColumnMappings.Add("UploadFileID", "UploadFileID"); bulkCopy_tbl_FirstTable.ColumnMappings.Add("Active", "Active"); bulkCopy_tbl_FirstTable.ColumnMappings.Add("CreatedUserID", "CreatedUserID"); bulkCopy_tbl_FirstTable.ColumnMappings.Add("CreatedDate", "CreatedDate"); bulkCopy_tbl_FirstTable.ColumnMappings.Add("UpdatedUserID", "UpdatedUserID"); bulkCopy_tbl_FirstTable.ColumnMappings.Add("UpdatedDate", "UpdatedDate"); bulkCopy_tbl_FirstTable.WriteToServer(DT_tbl_FirstTable); } using (SqlBulkCopy bulkCopy_tbl_SecondTable = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) { bulkCopy_tbl_SecondTable.BatchSize = 5000; bulkCopy_tbl_SecondTable.DestinationTableName = "dbo.tbl_SecondTable"; bulkCopy_tbl_SecondTable.ColumnMappings.Add("ID", "ID"); bulkCopy_tbl_SecondTable.ColumnMappings.Add("UploadFileDetailID", "UploadFileDetailID"); bulkCopy_tbl_SecondTable.ColumnMappings.Add("CompaignFieldMasterID", "CompaignFieldMasterID"); bulkCopy_tbl_SecondTable.ColumnMappings.Add("Value", "Value"); bulkCopy_tbl_SecondTable.ColumnMappings.Add("Active", "Active"); bulkCopy_tbl_SecondTable.ColumnMappings.Add("CreatedUserID", "CreatedUserID"); bulkCopy_tbl_SecondTable.ColumnMappings.Add("CreatedDate", "CreatedDate"); bulkCopy_tbl_SecondTable.ColumnMappings.Add("UpdatedUserID", "UpdatedUserID"); bulkCopy_tbl_SecondTable.ColumnMappings.Add("UpdatedDate", "UpdatedDate"); bulkCopy_tbl_SecondTable.WriteToServer(DT_tbl_SecondTable); } transaction.Commit(); IsSuccessSave = true; } connection.Close(); } } } catch (Exception ex) { if (transaction != null) transaction.Rollback(); Log4NetWrapper.WriteError(string.Format("{0} : {1} : Exception={2}", this.GetType().FullName, (new StackTrace(new StackFrame(0))).GetFrame(0).GetMethod().Name.ToString(), ex.Message.ToString())); if (ex.InnerException != null) { Log4NetWrapper.WriteError(string.Format("{0} : {1} : InnerException Exception={2}", this.GetType().FullName, (new StackTrace(new StackFrame(0))).GetFrame(0).GetMethod().Name.ToString(), ex.InnerException.Message.ToString())); } } return IsSuccessSave; } </code></pre> <p>Finally, It perform insert process in less than 15 seconds for over 500,000 rows.</p> <p>There is two reasons why I post this scenario.</p> <ol> <li>I would like to share what I found out.<br></li> <li>As I am not perfect, I still need to get more suggestion from you.</li> </ol> <p>So, every better solution will be appreciated.</p>
0
3,574
How get sum of total values in stackedBar ChartJs
<p>I'm trying to get the sum of all values of a stackedBar and include this total in tooltip.</p> <blockquote> <p>Note: my datasets aren't static, this is an example</p> </blockquote> <pre><code>var barChartData = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: 'Corporation 1', backgroundColor: "rgba(220,220,220,0.5)", data: [50, 40, 23, 45, 67, 78, 23] }, { label: 'Corporation 2', backgroundColor: "rgba(151,187,205,0.5)", data: [50, 40, 78, 23, 23, 45, 67] }, { label: 'Corporation 3', backgroundColor: "rgba(151,187,205,0.5)", data: [50, 67, 78, 23, 40, 23, 55] }] }; window.onload = function() { var ctx = document.getElementById("canvas").getContext("2d"); window.myBar = new Chart(ctx, { type: 'bar', data: barChartData, options: { title:{ display:true, text:"Chart.js Bar Chart - Stacked" }, tooltips: { mode: 'label', callbacks: { label: function(tooltipItem, data) { var corporation = data.datasets[tooltipItem.datasetIndex].label; var valor = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]; var total = eval(data.datasets[tooltipItem.datasetIndex].data.join("+")); return total+"--"+ corporation +": $" + valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'); } } }, responsive: true, scales: { xAxes: [{ stacked: true, }], yAxes: [{ stacked: true }] } } }); }; </code></pre> <p>Now <code>total</code> is the sum per dataset and I need the sum per stackedBar.</p> <p>Example</p> <p>Label A: value A</p> <p>Label B: value B</p> <p>Label C: value C</p> <p>TOTAL: value A + value B + value C</p> <p>It is possible to get that total value?</p> <p>Thanks, Idalia.</p>
0
1,327
Disable WPF buttons during longer running process, the MVVM way
<p>I have a WPF/MVVM app, which consists of one window with a few buttons.<br> Each of the buttons triggers a call to an external device (an <a href="http://www.dreamcheeky.com/thunder-missile-launcher" rel="nofollow noreferrer">USB missile launcher</a>), which takes a few seconds.</p> <p>While the device is running, the GUI is frozen.<br> <em>(<strong>This is okay</strong>, because the only purpose of the app is to call the USB device, and you can't do anything else anyway while the device is moving!)</em></p> <p>The only thing that's a bit ugly is that the frozen GUI still accepts additional clicks while the device is moving.<br> When the device still moves and I click on the same button a second time, the device immediately starts moving again as soon as the first "run" is finished.</p> <p>So I'd like to disable all the buttons in the GUI as soon as one button is clicked, and enable them again when the button's command has finished running.</p> <p>I have found a solution for this that looks MVVM-conform.<br> <em>(at least to me...note that I'm still a WPF/MVVM beginner!)</em></p> <p>The problem is that this solution doesn't work (as in: the buttons are not disabled) when I call the external library that communicates with the USB device.<br> But the actual code to disable the GUI is correct, because it <strong>does</strong> work when I replace the external library call by <code>MessageBox.Show()</code>.</p> <p>I've constructed a minimal working example that reproduces the problem (<a href="https://github.com/christianspecht/code-examples/tree/master/WpfDatabindingQuestion" rel="nofollow noreferrer">complete demo project here</a>):</p> <p>This is the view:</p> <pre><code>&lt;Window x:Class="WpfDatabindingQuestion.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"&gt; &lt;Grid&gt; &lt;StackPanel&gt; &lt;Button Content="MessageBox" Command="{Binding MessageCommand}" Height="50"&gt;&lt;/Button&gt; &lt;Button Content="Simulate external device" Command="{Binding DeviceCommand}" Height="50" Margin="0 10"&gt;&lt;/Button&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>...and this is the ViewModel <em>(using the <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030" rel="nofollow noreferrer"><code>RelayCommand</code> from Josh Smith's MSDN article</a>)</em>:</p> <pre><code>using System.Threading; using System.Windows; using System.Windows.Input; namespace WpfDatabindingQuestion { public class MainWindowViewModel { private bool disableGui; public ICommand MessageCommand { get { return new RelayCommand(this.ShowMessage, this.IsGuiEnabled); } } public ICommand DeviceCommand { get { return new RelayCommand(this.CallExternalDevice, this.IsGuiEnabled); } } // here, the buttons are disabled while the MessageBox is open private void ShowMessage(object obj) { this.disableGui = true; MessageBox.Show("test"); this.disableGui = false; } // here, the buttons are NOT disabled while the app pauses private void CallExternalDevice(object obj) { this.disableGui = true; // simulate call to external device (USB missile launcher), // which takes a few seconds and pauses the app Thread.Sleep(3000); this.disableGui = false; } private bool IsGuiEnabled(object obj) { return !this.disableGui; } } } </code></pre> <p>I'm suspecting that opening a <code>MessageBox</code> triggers some stuff in the background that does <strong>not</strong> happen when I just call an external library.<br> But I'm not able to find a solution.</p> <p>I have also tried:</p> <ul> <li>implementing <code>INotifyPropertyChanged</code> (and making <code>this.disableGui</code> a property, and calling <code>OnPropertyChanged</code> when changing it)</li> <li>calling <code>CommandManager.InvalidateRequerySuggested()</code> all over the place<br> <em>(I found that in several answers to similar problems here on SO)</em></li> </ul> <p>Any suggestions?</p>
0
1,663
datepicker specified value does not conform to the required format jquery.js
<p>So yesterday I asked a question about setting the date for a calendar. I was missing some references so have since added them. Please see the HTML section below.</p> <p>I believe my code to be correct for how to set the date for a calendar. However upon loading the page I get these errors,</p> <blockquote> <p>Uncaught SyntaxError: Unexpected token datepicker.css:11 </p> <p>The specified value "09/01/2018" does not conform to the required format, "yyyy-MM-dd". jquery.js:8254 </p> </blockquote> <p>Not sure why this is not working and where the date "09/01/2018" is coming from at all?</p> <p>I also think in my the datepicker.css should be like below. </p> <blockquote> <p>link href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.css" rel="stylesheet" type="text/css" /></p> </blockquote> <p>When I do this the Uncaught SyntaxError message disappears but still have the other issue.</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-js lang-js prettyprint-override"><code>$(document).ready(function() { $("#dtSelectorStatic").datepicker(); $("#dtSelectorStatic").datepicker("setDate", new Date(2018, 8, 1)); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" /&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.min.css" /&gt; &lt;input id="dtSelectorStatic" /&gt;</code></pre> </div> </div> </p> <p><strong>Update</strong></p> <p>Below are all the references I have in my page. One thing (might be nothing) but when I type "script src=" the intelli sense picks on my folder scripts and list 3 files (image below, jQES is the file I created) but it does not list the other two files also in that folder, jquery-ui.js or jquery-ui.min.js</p> <p><a href="https://i.stack.imgur.com/c5ztD.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/c5ztD.jpg" alt="script folder in visual studio"></a></p> <pre><code> &lt;script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; google.charts.load('current', { 'packages': ['corechart', 'table'] }); &lt;/script&gt; &lt;script src="/scripts/external/jquery/jquery.js"&gt;&lt;/script&gt; &lt;script src="/scripts/jquery-ui.min.js"&gt;&lt;/script&gt; &lt;script src="/scripts/jQES.js"&gt;&lt;/script&gt; &lt;link href="CSS/MyCSSFile.css" rel="stylesheet" type="text/css"/&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" /&gt; </code></pre> <p><strong>update 2</strong></p> <p>This is how it looks on load up.</p> <p><a href="https://i.stack.imgur.com/tolER.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/tolER.jpg" alt="on load up"></a></p> <p>If I click in the area where the blue arrow is pointing to the calendar below is shown.</p> <p><a href="https://i.stack.imgur.com/FypZ7.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/FypZ7.jpg" alt="click in the area where the blue arrow is pointing to"></a></p> <p>If I click on the big black arrow I get both calendars</p> <p><a href="https://i.stack.imgur.com/3fKoZ.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/3fKoZ.jpg" alt="big arrow"></a></p> <p>I have another calendar box which is exactly the same. Which only shows the calendar shown below no matter what I do. The only difference is that on load up I do not try to set the date as I do in the calendar above.</p> <pre><code> &lt;input id="someId" type="date"/&gt; </code></pre> <p><a href="https://i.stack.imgur.com/RMFVV.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/RMFVV.jpg" alt="normal calendar"></a></p>
0
1,616
Specify cert to use for SSL in docker-compose.yml file?
<p>I've got a small <code>docker-compose.yaml</code> file that looks like this (it's used to fire up a local test-environment):</p> <pre><code>version: '2' services: ubuntu: build: context: ./build dockerfile: ubuntu.dock volumes: - ./transfer:/home/ ports: - "60000:22" python: build: context: ./build dockerfile: python.dock volumes: - .:/home/code links: - mssql - ubuntu mssql: image: "microsoft/mssql-server-linux" environment: SA_PASSWORD: "somepassword" ACCEPT_EULA: "Y" ports: - "1433:1433" </code></pre> <p>The issue that I run into is that when I run <code>docker-compose up</code> it fails at this step (which is in the <code>python.dock</code> file):</p> <pre><code>Step 10/19 : RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - ---&gt; Running in e4963c91a05b </code></pre> <p>The error looks like this:</p> <pre><code> % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 curl: (60) server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none More details here: http://curl.haxx.se/docs/sslcerts.html </code></pre> <p>The part where it fails in the <code>python.dock</code> file looks like this:</p> <pre><code># This line fails RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - RUN curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list &gt; /etc/apt/sources.list.d/mssql-release.list RUN apt-get update -y </code></pre> <p>I've had issues with curl / docker in the past - because we use a self-signed cert for decrypting/encrypting at the firewall level (network requirement); is there a way for me to specify a self-signed cert for the containers to use?</p> <p>That would allow curl to reach out and download the required files. </p> <p>I've tried running something like <code>docker-compose -f docker-compose.yaml --tlscert ~/certs/the-self-signed-ca.pem up</code> but it fails.</p> <p>How can I do this a bit more programatically so I can just run <code>docker-compose up</code> ?</p>
0
1,040
Bootstrap 4 Tabs are not switching
<p>I am currently using bootstrap 4. I read the bootstrap documentation and am currently trying to incorporate tabs but they are not switching my code is the following:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Info&lt;/title&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0- alpha.3/css/bootstrap.min.css" integrity="sha384-MIwDKRSSImVFAZCVLtU0LMDdON6KVCrZHyVQQj6e8wIEJkW4tvwqXrbMIya1vriY" crossorigin="anonymous"&gt; &lt;/head&gt; &lt;body&gt; &lt;?php include_once("template_pageTop.php"); ?&gt; &lt;div class="container p-t-md"&gt; &lt;div class="row"&gt; &lt;div class="col-md-6"&gt; &lt;ul class="nav nav-tabs"&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link active" href="#currentPreferences"&gt;Current Preferences&lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link" href="#alternative"&gt; Alternative &lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link" href="#"&gt;Link&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;div class="tab-content"&gt; &lt;div role="tabpanel" class="tab-pane fade in active" id="currentPreferences"&gt; &lt;ul class="list-group media-list media-list-stream"&gt; &lt;?php display(); ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div role="tabpanel" class="tab-pane fade in" id="alternative"&gt; &lt;ul class="list-group media-list media-list-stream"&gt; &lt;p&gt;Test&lt;/p&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php include_once("template_pageBottom.php"); ?&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"&gt; &lt;/script&gt; &lt;script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I have added the javascript libraries but it does not seem to be switching is there anything else I can add? Any feedback is welcomed. Thank you</p>
0
1,526
Printing all Possible nCr Combinations in Java
<p>I'm trying to print out all possibilities of nCr, which are the combinations when order doesn't matter. So 5C1 there are 5 possibilities: 1 , 2, 3, 4, 5. 5C2 there are 10 possibilities: 1 2, 1 3, 1 4, 1 5, 2 3, 2 4, 2 5, 3 4, 3 5, 4 5.</p> <p>I made functions that print what I want for r = 2, r = 3, and r = 4, and I sort of see the pattern, but I cant seem to make a working method for variable r:</p> <pre><code>public void printCombinationsChoose2(int n, int k) //for when k = 2 { for (int a = 1; a &lt; n; a++) { for (int b = a + 1; b &lt;= n; b++) { System.out.println("" + a + " " + b); } } } public void printCombinationsChoose3(int n, int k) //for when k = 3 { for (int a = 1; a &lt; n - 1; a++) { for (int b = a + 1; b &lt; n; b++) { for (int c = b + 1; c &lt;= n; c++) { System.out.println("" + a + " " + b + " " + c); } } } } public void printCombinationsChoose4(int n, int k) //for when k = 4 { for (int a = 1; a &lt; n - 2; a++) { for (int b = a + 1; b &lt; n - 1; b++) { for (int c = b + 1; c &lt; n; c++) { for (int d = c + 1; d &lt;= n; d++) { System.out.println("" + a + " " + b + " " + c + " " + d); } } } } } public void printCombinations(int n, int k) //Doesn't work { int[] nums = new int[k]; for (int i = 1; i &lt;= nums.length; i++) nums[i - 1] = i; int count = 1; while (count &lt;= k) { for (int a = nums[k - count]; a &lt;= n; a++) { nums[k - count] = a; for (int i = 0; i &lt; nums.length; i++) System.out.print("" + nums[i] + " "); System.out.println(); } count++; } } </code></pre> <p>So I think the layout of my last method is right, but I'm just not doing the right things, because when I call <code>printCominbations(5, 2)</code>, it prints</p> <pre><code>1 2 1 3 1 4 1 5 1 5 2 5 3 5 4 5 5 5 </code></pre> <p>when it should be what I said earlier for 5C2.</p> <p><strong>Edit</strong> The last example was bad. This is a better one to illustrate what it's doing wrong: <code>printCombinations(5, 3)</code> gives this:</p> <pre><code>1 2 3 1 2 4 1 2 5 1 2 5 1 3 5 1 4 5 1 5 5 1 5 5 2 5 5 3 5 5 4 5 5 5 5 5 </code></pre> <p>How do I get it to be:</p> <pre><code>1 2 3 1 2 4 1 2 5 1 3 4 1 3 5 1 4 5 2 3 4 2 3 5 2 4 5 3 4 5 </code></pre>
0
1,324
Status: "MariaDB server is down"
<p>Hope someone can help me:</p> <p>I have many sites running on my server and I am using mariadb. when I do:</p> <pre><code>sudo service mysql restart </code></pre> <p>I get:</p> <pre><code>Job for mariadb.service failed because the control process exited with error code. See "systemctl status mariadb.service" and "journalctl -xe" for details. </code></pre> <blockquote> <p>systemctl status mariadb.service</p> </blockquote> <pre><code> mariadb.service - MariaDB database server Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled) Drop-In: /etc/systemd/system/mariadb.service.d └─migrated-from-my.cnf-settings.conf Active: failed (Result: exit-code) since Thu 2017-09-14 03:16:51 UTC; 1min 6s ago Process: 13247 ExecStart=/usr/sbin/mysqld $MYSQLD_OPTS $_WSREP_NEW_CLUSTER $_WSREP_START_POSITION (code= Process: 13086 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] &amp;&amp; VAR= || VAR=`/usr/bin/gale Process: 13070 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, s Process: 13033 ExecStartPre=/usr/bin/install -m 755 -o mysql -g root -d /var/run/mysqld (code=exited, st Main PID: 13247 (code=exited, status=1/FAILURE) Status: "MariaDB server is down" CGroup: /system.slice/mariadb.service └─3803 /usr/sbin/mysqld </code></pre> <blockquote> <p>sudo journalctl -xe</p> </blockquote> <pre><code> Sep 14 03:35:51 ubuntu systemd[1]: Failed to start MariaDB database server. -- Subject: Unit mariadb.service has failed -- Defined-By: systemd -- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- Unit mariadb.service has failed. -- -- The result is failed. Sep 14 03:35:51 ubuntu systemd[1]: mariadb.service: Unit entered failed state. Sep 14 03:35:51 ubuntu sudo[13566]: pam_unix(sudo:session): session closed for user root Sep 14 03:35:51 ubuntu systemd[1]: mariadb.service: Failed with result 'exit-code'. Sep 14 03:35:52 ubuntu sshd[13753]: Failed password for root from 123.183.209.136 port 38816 ssh2 Sep 14 03:35:52 ubuntu sshd[13753]: Received disconnect from 123.183.209.136 port 38816:11: [preauth] Sep 14 03:35:52 ubuntu sshd[13753]: Disconnected from 123.183.209.136 port 38816 [preauth] Sep 14 03:35:52 ubuntu sshd[13753]: PAM 1 more authentication failure; logname= uid=0 euid=0 tty=ssh ruser Sep 14 03:36:34 ubuntu sshd[13756]: Connection closed by 123.183.209.136 port 60477 [preauth] Sep 14 03:36:36 ubuntu postfix/pickup[12161]: 703AA5C0C5: uid=0 from=&lt;root&gt; Sep 14 03:36:36 ubuntu postfix/cleanup[12162]: 703AA5C0C5: message-id=&lt;20170914033636.703AA5C0C5@ubuntu.me Sep 14 03:36:36 ubuntu postfix/cleanup[12162]: warning: 703AA5C0C5: write queue file: No space left on dev Sep 14 03:36:36 ubuntu postfix/pickup[12161]: warning: maildrop/5152F5C0C4: error writing 703AA5C0C5: queu Sep 14 03:37:17 ubuntu sshd[13760]: Received disconnect from 123.183.209.136 port 25567:11: [preauth] Sep 14 03:37:17 ubuntu sshd[13760]: Disconnected from 123.183.209.136 port 25567 [preauth] Sep 14 03:37:36 ubuntu postfix/pickup[12161]: 7764B5C0C5: uid=0 from=&lt;root&gt; Sep 14 03:37:36 ubuntu postfix/cleanup[12162]: 7764B5C0C5: message-id=&lt;20170914033736.7764B5C0C5@ubuntu.me Sep 14 03:37:36 ubuntu postfix/cleanup[12162]: warning: 7764B5C0C5: write queue file: No space left on dev Sep 14 03:37:36 ubuntu postfix/pickup[12161]: warning: maildrop/5152F5C0C4: error writing 7764B5C0C5: queu Sep 14 03:37:47 ubuntu sudo[13765]: bob : TTY=pts/0 ; PWD=/home/bob ; USER=root ; COMMAND=/bin/journa Sep 14 03:37:47 ubuntu sudo[13765]: pam_unix(sudo:session): session opened for user root by bob(uid=0) lines 1238-1265/1265 (END) </code></pre> <p>I really don't want to lose my db. What should I do next?</p> <p>Many thanks</p> <p>this is what df gives me:</p> <pre><code> Filesystem 1K-blocks Used Available Use% Mounted on /dev/root 49362256 46854648 0 100% / devtmpfs 2019828 0 2019828 0% /dev tmpfs 2021768 0 2021768 0% /dev/shm tmpfs 2021768 17968 2003800 1% /run tmpfs 5120 0 5120 0% /run/lock tmpfs 2021768 0 2021768 0% /sys/fs/cgroup tmpfs 404356 0 404356 0% /run/user/1000 tmpfs 404356 0 404356 0% /run/user/0 </code></pre>
0
1,943
BeanAlreadyExistsException - Oracle WebLogic
<p>I deployed an app on my web server and now I am trying to deply another one on the web server and I am getting a BeanAlreadyExistsException. I thought it might be due to the fact that I have two beans with the same name in the two different projects. So I removed the first project from the server - however that didn't work - I still ended up getting this exception when deploying the second app.</p> <p>Here is the stack trace:</p> <pre><code>####&lt;Jun 29, 2012 11:35:47 AM EDT&gt; &lt;Warning&gt; &lt;Deployer&gt; &lt;GAATLITISDAU88W&gt; &lt;AdminServer&gt; &lt;[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'&gt; &lt;&lt;WLS Kernel&gt;&gt; &lt;&gt; &lt;&gt; &lt;1340984147265&gt; &lt;BEA-149004&gt; &lt;Failures were detected while initiating deploy task for application 'jwds0002.ear'.&gt; ####&lt;Jun 29, 2012 11:35:47 AM EDT&gt; &lt;Warning&gt; &lt;Deployer&gt; &lt;GAATLITISDAU88W&gt; &lt;AdminServer&gt; &lt;[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'&gt; &lt;&lt;WLS Kernel&gt;&gt; &lt;&gt; &lt;&gt; &lt;1340984147265&gt; &lt;BEA-149078&gt; &lt;Stack trace for message 149004 weblogic.management.DeploymentException: Unmarshaller failed at weblogic.application.internal.EarDeploymentFactory.findOrCreateComponentMBeans(EarDeploymentFactory.java:193) at weblogic.application.internal.MBeanFactoryImpl.findOrCreateComponentMBeans(MBeanFactoryImpl.java:48) at weblogic.application.internal.MBeanFactoryImpl.createComponentMBeans(MBeanFactoryImpl.java:110) at weblogic.application.internal.MBeanFactoryImpl.initializeMBeans(MBeanFactoryImpl.java:76) at weblogic.management.deploy.internal.MBeanConverter.createApplicationMBean(MBeanConverter.java:89) at weblogic.management.deploy.internal.MBeanConverter.createApplicationForAppDeployment(MBeanConverter.java:67) at weblogic.management.deploy.internal.MBeanConverter.setupNew81MBean(MBeanConverter.java:315) at weblogic.deploy.internal.targetserver.operations.ActivateOperation.compatibilityProcessor(ActivateOperation.java:81) at weblogic.deploy.internal.targetserver.operations.AbstractOperation.setupPrepare(AbstractOperation.java:295) at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doPrepare(ActivateOperation.java:97) at weblogic.deploy.internal.targetserver.operations.AbstractOperation.prepare(AbstractOperation.java:217) at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentPrepare(DeploymentManager.java:747) at weblogic.deploy.internal.targetserver.DeploymentManager.prepareDeploymentList(DeploymentManager.java:1216) at weblogic.deploy.internal.targetserver.DeploymentManager.handlePrepare(DeploymentManager.java:250) at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.prepare(DeploymentServiceDispatcher.java:159) at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doPrepareCallback(DeploymentReceiverCallbackDeliverer.java:171) at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$000(DeploymentReceiverCallbackDeliverer.java:13) at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$1.run(DeploymentReceiverCallbackDeliverer.java:46) at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:528) at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209) at weblogic.work.ExecuteThread.run(ExecuteThread.java:178) Caused By: weblogic.descriptor.BeanAlreadyExistsException: Bean already exists: "weblogic.j2ee.descriptor.wl.ApplicationParamBeanImpl@b68b07b2(/ApplicationParams[webapp.encoding.default])" at weblogic.descriptor.internal.ReferenceManager.registerBean(ReferenceManager.java:231) at weblogic.j2ee.descriptor.wl.WeblogicApplicationBeanImpl.setApplicationParams(WeblogicApplicationBeanImpl.java:564) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.bea.staxb.runtime.internal.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:48) at com.bea.staxb.runtime.internal.RuntimeBindingType$BeanRuntimeProperty.setValue(RuntimeBindingType.java:539) at com.bea.staxb.runtime.internal.AttributeRuntimeBindingType$QNameRuntimeProperty.fillCollection(AttributeRuntimeBindingType.java:381) at com.bea.staxb.runtime.internal.MultiIntermediary.getFinalValue(MultiIntermediary.java:52) at com.bea.staxb.runtime.internal.AttributeRuntimeBindingType.getFinalObjectFromIntermediary(AttributeRuntimeBindingType.java:140) at com.bea.staxb.runtime.internal.UnmarshalResult.unmarshalBindingType(UnmarshalResult.java:200) at com.bea.staxb.runtime.internal.UnmarshalResult.unmarshalDocument(UnmarshalResult.java:169) at com.bea.staxb.runtime.internal.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:65) at weblogic.descriptor.internal.MarshallerFactory$1.createDescriptor(MarshallerFactory.java:150) at weblogic.descriptor.BasicDescriptorManager.createDescriptor(BasicDescriptorManager.java:323) at weblogic.application.descriptor.AbstractDescriptorLoader2.getDescriptorBeanFromReader(AbstractDescriptorLoader2.java:788) at weblogic.application.descriptor.AbstractDescriptorLoader2.createDescriptorBean(AbstractDescriptorLoader2.java:409) at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBeanWithoutPlan(AbstractDescriptorLoader2.java:759) at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBean(AbstractDescriptorLoader2.java:768) at weblogic.application.ApplicationDescriptor.getWeblogicApplicationDescriptor(ApplicationDescriptor.java:324) at weblogic.application.internal.EarDeploymentFactory.findOrCreateComponentMBeans(EarDeploymentFactory.java:181) at weblogic.application.internal.MBeanFactoryImpl.findOrCreateComponentMBeans(MBeanFactoryImpl.java:48) at weblogic.application.internal.MBeanFactoryImpl.createComponentMBeans(MBeanFactoryImpl.java:110) at weblogic.application.internal.MBeanFactoryImpl.initializeMBeans(MBeanFactoryImpl.java:76) at weblogic.management.deploy.internal.MBeanConverter.createApplicationMBean(MBeanConverter.java:89) at weblogic.management.deploy.internal.MBeanConverter.createApplicationForAppDeployment(MBeanConverter.java:67) at weblogic.management.deploy.internal.MBeanConverter.setupNew81MBean(MBeanConverter.java:315) at weblogic.deploy.internal.targetserver.operations.ActivateOperation.compatibilityProcessor(ActivateOperation.java:81) at weblogic.deploy.internal.targetserver.operations.AbstractOperation.setupPrepare(AbstractOperation.java:295) at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doPrepare(ActivateOperation.java:97) at weblogic.deploy.internal.targetserver.operations.AbstractOperation.prepare(AbstractOperation.java:217) at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentPrepare(DeploymentManager.java:747) at weblogic.deploy.internal.targetserver.DeploymentManager.prepareDeploymentList(DeploymentManager.java:1216) at weblogic.deploy.internal.targetserver.DeploymentManager.handlePrepare(DeploymentManager.java:250) at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.prepare(DeploymentServiceDispatcher.java:159) at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doPrepareCallback(DeploymentReceiverCallbackDeliverer.java:171) at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$000(DeploymentReceiverCallbackDeliverer.java:13) at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$1.run(DeploymentReceiverCallbackDeliverer.java:46) at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:528) at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209) at weblogic.work.ExecuteThread.run(ExecuteThread.java:178) </code></pre> <blockquote> <p></p> </blockquote> <p>Here is the web.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&gt; &lt;display-name&gt;jwds0002&lt;/display-name&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.html&lt;/welcome-file&gt; &lt;welcome-file&gt;index.htm&lt;/welcome-file&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;welcome-file&gt;default.html&lt;/welcome-file&gt; &lt;welcome-file&gt;default.htm&lt;/welcome-file&gt; &lt;welcome-file&gt;default.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;servlet&gt; &lt;description&gt;&lt;/description&gt; &lt;display-name&gt;PubAlertAccessor&lt;/display-name&gt; &lt;servlet-name&gt;PubAlertAccessor&lt;/servlet-name&gt; &lt;servlet-class&gt;com.myPackage.PubAlertAccessor&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;PubAlertAccessor&lt;/servlet-name&gt; &lt;url-pattern&gt;/PubAlertAccessor&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;listener&gt; &lt;listener-class&gt;com.myPackage.Configurator&lt;/listener-class&gt; &lt;/listener&gt; &lt;/web-app&gt; </code></pre>
0
3,590
Spring maven dependency issue
<p>I have a problem that my pom.xml throw an error</p> <p>ArtifactTransferException:</p> <blockquote> <p>Failure to transfer org.springframework:spring-tx:jar:3.2.4.RELEASE from http:// repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.springframework:spring-tx:jar: 3.2.4.RELEASE from/to central (<a href="http://repo.maven.apache.org/maven2" rel="nofollow">http://repo.maven.apache.org/maven2</a>): No response received after 60000</p> </blockquote> <p>This is my pom.xml</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;spring-mvc-demo&lt;/groupId&gt; &lt;artifactId&gt;spring-mvc-tiles&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;spring-mvc-tiles Maven Webapp&lt;/name&gt; &lt;url&gt;http://maven.apache.org&lt;/url&gt; &lt;properties&gt; &lt;org.maven.compiler.version&gt;3.1&lt;/org.maven.compiler.version&gt; &lt;org.springframework.version&gt;3.2.4.RELEASE&lt;/org.springframework.version&gt; &lt;jre.version&gt;1.7&lt;/jre.version&gt; &lt;jstl.version&gt;1.2&lt;/jstl.version&gt; &lt;org.apache.tiles.version&gt;2.2.2&lt;/org.apache.tiles.version&gt; &lt;org.slf4j.version&gt;1.7.5&lt;/org.slf4j.version&gt; &lt;org.hibernate.version&gt;4.2.7.Final&lt;/org.hibernate.version&gt; &lt;mysql.version&gt;5.1.27&lt;/mysql.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;!-- MySQL connector --&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;${mysql.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-dbcp&lt;/groupId&gt; &lt;artifactId&gt;commons-dbcp&lt;/artifactId&gt; &lt;version&gt;1.4&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Servlet --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.inject&lt;/groupId&gt; &lt;artifactId&gt;javax.inject&lt;/artifactId&gt; &lt;version&gt;1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;servlet-api&lt;/artifactId&gt; &lt;version&gt;2.5&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet.jsp&lt;/groupId&gt; &lt;artifactId&gt;jsp-api&lt;/artifactId&gt; &lt;version&gt;2.1&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet.jsp&lt;/groupId&gt; &lt;artifactId&gt;javax.servlet.jsp-api&lt;/artifactId&gt; &lt;version&gt;2.2.1&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet.jsp.jstl&lt;/groupId&gt; &lt;artifactId&gt;jstl-api&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.validation&lt;/groupId&gt; &lt;artifactId&gt;validation-api&lt;/artifactId&gt; &lt;version&gt;1.1.0.Final&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Hibernate --&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;version&gt;${org.hibernate.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-validator&lt;/artifactId&gt; &lt;version&gt;5.0.1.Final&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Spring framework --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;exclusions&gt; &lt;!-- Exclude Commons Logging in favor of SLF4j --&gt; &lt;exclusion&gt; &lt;groupId&gt;commons-logging&lt;/groupId&gt; &lt;artifactId&gt;commons-logging&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-web&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-tx&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-orm&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Log --&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;jcl-over-slf4j&lt;/artifactId&gt; &lt;version&gt;${org.slf4j.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt; &lt;version&gt;${org.slf4j.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- JSTL --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;jstl&lt;/artifactId&gt; &lt;version&gt;${jstl.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Apache Tiles --&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.tiles&lt;/groupId&gt; &lt;artifactId&gt;tiles-jsp&lt;/artifactId&gt; &lt;version&gt;${org.apache.tiles.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.tiles&lt;/groupId&gt; &lt;artifactId&gt;tiles-extras&lt;/artifactId&gt; &lt;version&gt;${org.apache.tiles.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.tiles&lt;/groupId&gt; &lt;artifactId&gt;tiles-servlet&lt;/artifactId&gt; &lt;version&gt;${org.apache.tiles.version}&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;finalName&gt;spring-mvc-tiles&lt;/finalName&gt; &lt;/build&gt; </code></pre> <p></p>
0
3,834
Huffman encoding in C
<p>I am trying to write a module which assigns huffman encoded words to the input symbols, but the given codes differ from what they should look like.</p> <p>For example, if I run it with following symbol probabilities:</p> <p>(1st column: probabilities; 2nd column: my huffman codes; 3rd column: correct huffman codes) </p> <p>0,25 --> 01 --> 10</p> <p>0,15 --> 101 --> 111</p> <p>0,15 --> 110 --> 110</p> <p>0,1 --> 1111 --> 010</p> <p>0,1 --> 000 --> 001</p> <p>0,05 --> 0010 --> 0110</p> <p>0,05 --> 0011 --> 0001</p> <p>0,05 --> 1000 --> 0000</p> <p>0,05 --> 1001 --> 01111</p> <p>0,05 --> 1110 --> 01110</p> <p>I think the problem might be caused in my function for <strong>generating huffman codes</strong>, since <em>strcat()</em> function's behaviour was initially not good for my idea, so I combined it with <em>strcat()</em>. Not sure if it is good that way tho.</p> <p>I am providing you with two functions responsible for codes assign, <strong>build_huffman_tree()</strong> and <strong>generate_huffman_tree()</strong>, hopefully you can help me out with this, and point out where the problem could be.</p> <p>Generate guffman tree:</p> <pre><code>void generate_huffman_tree(node *n, char *code){ if(n-&gt;left== NULL &amp;&amp; n-&gt;right== NULL){ SYMBOLS[code_counter] = n-&gt;symbol; // this 3 lines just store current code, not important CODES[code_counter] = strdup(code); code_counter += 1; } if(n-&gt;left!= NULL){ char temp[100]; strcpy(temp, code); strcat(temp, "0"); generate_huffman_tree(n-&gt;left, temp); } if(n-&gt;right!= NULL){ char temp[100]; strcpy(temp, code); strcat(temp, "1"); generate_huffman_tree(n-&gt;right, temp); } </code></pre> <p>Build Huffman tree:</p> <pre><code>node *build_huffman_tree(double *probabilities){ int num_of_nodes = NUM_SYMBOLS; int num = NUM_SYMBOLS; // 1) Initialization: Create new node for every probability node *leafs = (node*) malloc(num_of_nodes*sizeof(node)); int i; for(i=0; i&lt;num_of_nodes; i+=1){ node c; c.probability= *(probability+ i); c.symbol= *(SYMBOLS + i); c.left= NULL; c.right= NULL; *(leafs+i) = c; } node *root= (node*) malloc(sizeof(node)); // Root node which will be returned while(num_of_nodes&gt; 1){ // 2) Find 2 nodes with lowest probabilities node *min_n1= (node*)malloc(sizeof(node)); node *min_n2 = (node*)malloc(sizeof(node)); *min_n1 = *find_min_node(leafs, num, min_n1); leafs = remove_node(leafs, min_n1, num); num -= 1; *min_n2= *find_min_node(leafs, num, min_n2); leafs = remove_node(leafs, min_n2, num); num -= 1; // 3) Create parent node, and assign 2 min nodes as its children // add parent node to leafs, while its children have been removed from leafs node *new_node = (node*) malloc(sizeof(node)); new_node-&gt;probabilty= min_n1-&gt;probability + min_n2-&gt;probability; new_node-&gt;left= min_n1; new_node-&gt;right= min_n2; leafs = add_node(leafs, new_node, num); num += 1; num_of_nodes -= 1; root = new_node; } return root; </code></pre> <p>I have tested functions for finding 2 min nodes, removing and adding nodes to leafs structure, and it is proven to work fine, so I guess the problem should be something about this here.</p>
0
1,344
VSCode prettier adds `value` to imports in TypeScript React
<p>After configuring prettier with the plugin in VSCode the format on save function adds weird <code>value</code> keywords to every non-default import in my React+TS code.</p> <p>Like this:</p> <pre><code>import { value ApolloProvider } from '@apollo/client'; import { value BrowserRouter as Router, value Switch } from 'react-router-dom'; import Routes from './routes'; import { value client } from './data/apollo-config'; </code></pre> <p>With this TS complains about <code>Duplicate identifier 'value'.ts(2300)</code></p> <p>Could anyone help me with this? Not sure why this is happening and how to solve it. Running <code>npx prettier --write someFile</code> doesn't add the <code>value</code> keywords.</p> <p>My package.json:</p> <pre><code> &quot;dependencies&quot;: { &quot;@apollo/client&quot;: &quot;^3.3.6&quot;, &quot;axios&quot;: &quot;^0.21.1&quot;, &quot;graphql&quot;: &quot;^15.4.0&quot;, &quot;react&quot;: &quot;^17.0.1&quot;, &quot;react-dom&quot;: &quot;^17.0.1&quot;, &quot;react-router-dom&quot;: &quot;^5.1.2&quot;, &quot;react-scripts&quot;: &quot;^4.0.0&quot; }, &quot;devDependencies&quot;: { &quot;prettier&quot;: &quot;^2.1.2&quot;, &quot;eslint-config-prettier&quot;: &quot;^8.3.0&quot;, &quot;eslint-plugin-cypress&quot;: &quot;^2.11.2&quot;, &quot;eslint-plugin-prettier&quot;: &quot;^3.1.4&quot;, &quot;@types/jest&quot;: &quot;^26.0.15&quot;, &quot;@types/lodash.merge&quot;: &quot;^4.6.6&quot;, &quot;@types/node&quot;: &quot;^14.14.6&quot;, &quot;@types/react&quot;: &quot;^16.9.55&quot;, &quot;@types/react-dom&quot;: &quot;^16.9.5&quot;, &quot;@types/react-router-dom&quot;: &quot;^5.1.3&quot;, &quot;cypress&quot;: &quot;^6.4.0&quot;, &quot;http-proxy-middleware&quot;: &quot;^1.0.3&quot;, &quot;lodash.merge&quot;: &quot;^4.6.2&quot;, &quot;start-server-and-test&quot;: &quot;^1.11.7&quot;, &quot;typescript&quot;: &quot;^4.5.4&quot; }, </code></pre> <p>tsconfig.json</p> <pre><code>{ &quot;compilerOptions&quot;: { &quot;baseUrl&quot;: &quot;.&quot;, &quot;target&quot;: &quot;es5&quot;, &quot;lib&quot;: [ &quot;es6&quot;, &quot;dom&quot; ], &quot;allowJs&quot;: true, &quot;rootDir&quot;: &quot;src&quot;, &quot;skipLibCheck&quot;: true, &quot;esModuleInterop&quot;: true, &quot;allowSyntheticDefaultImports&quot;: true, &quot;strict&quot;: true, &quot;forceConsistentCasingInFileNames&quot;: true, &quot;module&quot;: &quot;esnext&quot;, &quot;moduleResolution&quot;: &quot;node&quot;, &quot;resolveJsonModule&quot;: true, &quot;isolatedModules&quot;: true, &quot;noEmit&quot;: true, &quot;jsx&quot;: &quot;react-jsx&quot;, &quot;sourceMap&quot;: true, &quot;declaration&quot;: true, &quot;noUnusedLocals&quot;: true, &quot;noUnusedParameters&quot;: true, &quot;noFallthroughCasesInSwitch&quot;: true, &quot;noImplicitAny&quot;: false }, &quot;include&quot;: [ &quot;src/**/*&quot; ], &quot;exclude&quot;: [ &quot;node_modules&quot;, &quot;build&quot; ], &quot;typeRoots&quot;: [ &quot;./node_modules/@types&quot; ], &quot;types&quot;: [ &quot;react&quot;, &quot;react-dom&quot;, &quot;react-dom-router&quot;, &quot;jest&quot;, &quot;node&quot; ] } </code></pre> <p>eslintrc.js</p> <pre><code>{ &quot;parser&quot;: &quot;@typescript-eslint/parser&quot;, // Specifies the ESLint parser &quot;extends&quot;: [ &quot;react-app&quot;, &quot;plugin:react/recommended&quot;, // Uses the recommended rules from @eslint-plugin-react &quot;plugin:@typescript-eslint/recommended&quot;, // Uses the recommended rules from @typescript-eslint/eslint-plugin+ 'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier &quot;plugin:prettier/recommended&quot; // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array. ], &quot;plugins&quot;: [&quot;react&quot;, &quot;@typescript-eslint&quot;, &quot;jest&quot;, &quot;cypress&quot;], &quot;env&quot;: { &quot;browser&quot;: true, &quot;es6&quot;: true, &quot;jest&quot;: true }, &quot;parserOptions&quot;: { &quot;ecmaVersion&quot;: 2018, // Allows for the parsing of modern ECMAScript features &quot;sourceType&quot;: &quot;module&quot;, // Allows for the use of imports &quot;ecmaFeatures&quot;: { &quot;jsx&quot;: true // Allows for the parsing of JSX } }, &quot;rules&quot;: { &quot;no-unused-vars&quot;: &quot;off&quot;, &quot;@typescript-eslint/no-unused-vars&quot;: &quot;off&quot;, &quot;@typescript-eslint/explicit-module-boundary-types&quot;: &quot;off&quot;, &quot;@typescript-eslint/no-redeclare&quot;: &quot;off&quot;, &quot;@typescript-eslint/explicit-function-return-type&quot;: &quot;off&quot;, &quot;@typescript-eslint/triple-slash-reference&quot;: &quot;off&quot; }, &quot;settings&quot;: { &quot;react&quot;: { &quot;version&quot;: &quot;detect&quot; // Tells eslint-plugin-react to automatically detect the version of React to use } } } </code></pre>
0
2,825
JSP AJAX file uploading
<p>I tried to upload a file and display content of the file back to the browser with ajax and jsp. However, it doesn't seem to work very well for me.</p> <p>Apparently, in JSP page Upload.jsp, when I try to getContentType() from request, <code>request.getcontentType() == null</code> .</p> <p>Does anyone have experience with this? Thank you much.</p> <p>Form</p> <pre><code>&lt;form id="uploadform" name="uploadform" enctype="multipart/form-data" action="Upload.jsp" method="post"&gt; &lt;input type="file" name="file" id="listfile" onChange="upload(this.value)"/&gt; &lt;/form&gt; </code></pre> <p>This is the Javascript function upload(ifile)</p> <pre><code>function upload(ifile){ if (window.XMLHttpRequest){ //IE7 + and other browsers xmlhttp = new XMLHttpRequest(); }else{ //IE 6, 5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } if(xmlhttp == null){ alert("File Uploading is not available because your browser does not support AJAX"); return; } //Function to process response form upload.jsp xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200){ var response = xmlhttp.responseText; alert(response); } } xmlhttp.open("POST", "Upload.jsp?file="+ifile, true); xmlhttp.send(null); } </code></pre> <p>And this is the JSP page Upload.jsp</p> <pre><code>&lt;%@page import="java.util.StringTokenizer"%&gt; &lt;%@page import="java.io.*" %&gt; &lt;% response.setContentType("text/html"); response.setHeader("Cache-control", "no-cache"); String contentType = request.getContentType(); if ((contentType != null) &amp;&amp; (contentType.indexOf("multipart/form-data") &gt;= 0)) { DataInputStream in = new DataInputStream(request.getInputStream()); //get length of Content type data int formDataLength = request.getContentLength(); byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; //convert the uploaded file into byte code while (totalBytesRead &lt; formDataLength) { byteRead = in.read(dataBytes, totalBytesRead,formDataLength); totalBytesRead += byteRead; } //decode byte array using default charset String file = new String(dataBytes); //Using StringTokenizer to extract genes list StringTokenizer st = new StringTokenizer(file, " "); int numtoken = st.countTokens(); for(int i = 0; i &lt; numtoken-1; i++){ st.nextToken(); } String a = st.nextToken(); st = new StringTokenizer(a, " \n"); numtoken = st.countTokens(); String postlink = ""; st.nextToken(); st.nextToken(); for(int i = 1; i &lt; numtoken-3; i++){ String temp = st.nextToken(); char[] c = temp.toCharArray(); temp = new String(c, 0, c.length-1); if(!" ".equalsIgnoreCase(temp)){ postlink = postlink + temp + ","; } } String temp = st.nextToken(); postlink = postlink + temp; out.println(postlink); out.flush(); out.close(); }else if (contentType == null){ out.println("Not a valid file"); out.flush(); } %&gt; </code></pre>
0
1,929
Heroku - Application Error
<p>I've created simple application with Ruby on Rails and I’ve tried to commit it on Heroku. I’ve followed this <a href="http://devcenter.heroku.com/articles/quickstart" rel="nofollow">Getting Started on Heroku guide</a>, I finished it and try to open my page but I still see an Error: Application Error:</p> <blockquote> <p>An error occurred in the application and your page could not be served. Please try again in a few moments.</p> <p>If you are the application owner, check your logs for details.</p> </blockquote> <p>Anybody know how to deal with it?</p> <hr> <p>I don’t know what was happen but I’ve done this step, unfortunately I have another problem, I run a few commands:</p> <blockquote> <p># <strong>git add .</strong><br> # <strong>git commit -m "my commit"</strong><br> On branch master nothing to commit (working directory clean)<br> # <strong>git push heroku master</strong> Everything up-to-date<br> # <strong>heroku open</strong> Opening http ://eerie-meadow-9207.heroku.com/<br> # <strong>heroku restart</strong> Restarting processes... done<br> # <strong>heroku open</strong> Opening http ://eerie-meadow-9207.heroku.com/</p> </blockquote> <p>And I see a message:</p> <blockquote> <p>We're sorry, but something went wrong.</p> <p>We've been notified about this issue and we'll take a look at it shortly.</p> </blockquote> <p>From <code>heroku logs</code> <em>[timestamps removed for clarity]</em>:</p> <pre><code>app[web.1]: Started GET "/" for 77.236.11.34 at 2011-10-31 11:50:38 -0700 app[web.1]: Processing by StoreController#index as HTML app[web.1]: Completed 500 Internal Server Error in 3ms heroku[router]: GET eerie-meadow-9207.heroku.com/ dyno=web.1 queue=0 wait=0ms service=13ms status=500 bytes=728 heroku[nginx]: 77.236.11.34 - - [31/Oct/2011:11:50:38 -0700] "GET / HTTP/1.1" 500 728 "-" "Mozilla/5.0 (X11; U; Linux i686; pl-PL; rv:1.9.2.23) Gecko/20110921 Ubuntu/10.04 (lucid) Firefox/3.6.23" eerie-meadow-9207.heroku.com app[web.1]: heroku[web.1]: State changed from up to bouncing heroku[web.1]: State changed from bouncing to created heroku[web.1]: State changed from created to starting heroku[web.1]: Starting process with command `thin -p 40376 -e production -R /home/heroku_rack/heroku.ru start` heroku[web.1]: Process exited app[web.1]: &gt;&gt; Maximum connections set to 1024 app[web.1]: &gt;&gt; Listening on 0.0.0.0:40376, CTRL+C to stop app[web.1]: &gt;&gt; Thin web server (v1.2.6 codename Crazy Delicious) heroku[web.1]: State changed from starting to up app[web.1]: app[web.1]: Started GET "/" for 77.236.11.34 at 2011-10-31 11:50:59-0700 app[web.1]: app[web.1]: Processing by StoreController#index as HTML app[web.1]: Completed 500 Internal Server Error in 4ms app[web.1]: app[web.1]: ActiveRecord::StatementInvalid (PGError: ERROR: relation "products" does not exist app[web.1]: : SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull app[web.1]: FROM pg_attribute a LEFT JOIN pg_attrdef d app[web.1]: ON a.attrelid = d.adrelid AND a.attnum = d.adnum app[web.1]: WHERE a.attrelid = '"products"'::regclass app[web.1]: AND a.attnum &gt; 0 AND NOT a.attisdropped app[web.1]: ORDER BY a.attnum app[web.1]: ): app[web.1]: app/controllers/store_controller.rb:3:in `index' app[web.1]: app[web.1]: app[web.1]: cache: [GET /] miss heroku[router]: GET eerie-meadow-9207.heroku.com/ dyno=web.1 queue=0 wait=0ms service=81ms status=500 bytes=728 heroku[nginx]: 77.236.11.34 - - [31/Oct/2011:11:50:59 -0700] "GET / HTTP/1.1" 500 728 "-" "Mozilla/5.0 (X11; U; Linux i686; pl-PL; rv:1.9.2.23) Gecko/20110921 Ubuntu/10.04 (lucid) Firefox/3.6.23" eerie-meadow-9207.heroku.com app[web.1]: app[web.1]: app[web.1]: Started GET "/" for 77.236.11.34 at 2011-10-31 11:54:00-0700 app[web.1]: Processing by StoreController#index as HTML </code></pre> <p>I cannot understand it because on my netbook it works on localhost, any ideas?</p>
0
1,571
python argparse set behaviour when no arguments provided
<p>I'm fairly new to python and I'm stuck on how to structure my simple script when using command line arguments.</p> <p>The purpose of the script is to automate some daily tasks in my job relating to sorting and manipulating images. </p> <p>I can specify the arguments and get them to call the relevant functions, but i also want to set a default action when no arguments are supplied.</p> <p>Here's my current structure.</p> <pre><code>parser = argparse.ArgumentParser() parser.add_argument("-l", "--list", help="Create CSV of images", action="store_true") parser.add_argument("-d", "--dimensions", help="Copy images with incorrect dimensions to new directory", action="store_true") parser.add_argument("-i", "--interactive", help="Run script in interactive mode", action="store_true") args = parser.parse_args() if args.list: func1() if args.interactive: func2() if args.dimensions: func3() </code></pre> <p>But when I supply no arguments nothing will be called.</p> <pre><code>Namespace(dimensions=False, interactive=False, list=False) </code></pre> <p>What i want is some default behaviour if no arguements are supplied</p> <pre><code>if args.list: func1() if args.interactive: func2() if args.dimensions: func3() if no args supplied: func1() func2() func3() </code></pre> <p>This seems like it should be fairly easy to achieve but I'm lost on the logic of how to detect all arguments are false without looping through the arguments and testing if all are false.</p> <h2>Update</h2> <p>Multiple arguments are valid together, that is why I didn't go down the elif route.</p> <h2>Update 2</h2> <p>Here is my updated code taking into account the answer from @unutbu</p> <p>it doesn't seem ideal as everything is wrapped in an if statement but in the short term i couldn't find a better solution. I'm happy to accept the answer from @unutbu, any other improvements offered would be appreciated.</p> <pre><code>lists = analyseImages() if lists: statusTable(lists) createCsvPartial = partial(createCsv, lists['file_list']) controlInputParital = partial(controlInput, lists) resizeImagePartial = partial(resizeImage, lists['resized']) optimiseImagePartial = partial(optimiseImage, lists['size_issues']) dimensionIssuesPartial = partial(dimensionIssues, lists['dim_issues']) parser = argparse.ArgumentParser() parser.add_argument( "-l", "--list", dest='funcs', action="append_const", const=createCsvPartial, help="Create CSV of images",) parser.add_argument( "-c", "--convert", dest='funcs', action="append_const", const=resizeImagePartial, help="Convert images from 1500 x 2000px to 900 x 1200px ",) parser.add_argument( "-o", "--optimise", dest='funcs', action="append_const", const=optimiseImagePartial, help="Optimise filesize for 900 x 1200px images",) parser.add_argument( "-d", "--dimensions", dest='funcs', action="append_const", const=dimensionIssuesPartial, help="Copy images with incorrect dimensions to new directory",) parser.add_argument( "-i", "--interactive", dest='funcs', action="append_const", const=controlInputParital, help="Run script in interactive mode",) args = parser.parse_args() if not args.funcs: args.funcs = [createCsvPartial, resizeImagePartial, optimiseImagePartial, dimensionIssuesPartial] for func in args.funcs: func() else: print 'No jpegs found' </code></pre>
0
1,328
Replace NA in column with value in adjacent column
<p>This question is related to a post with a similar title (<a href="https://stackoverflow.com/questions/13514266/replace-na-in-an-r-vector-with-adjacent-values">replace NA in an R vector with adjacent values</a>). I would like to scan a column in a data frame and replace NA's with the value in the adjacent cell. In the aforementioned post, the solution was to replace the NA not with the value from the adjacent vector (e.g. the adjacent element in the data matrix) but was a conditional replace for a fixed value. Below is a reproducible example of my problem:</p> <pre><code>UNIT &lt;- c(NA,NA, 200, 200, 200, 200, 200, 300, 300, 300,300) STATUS &lt;-c('ACTIVE','INACTIVE','ACTIVE','ACTIVE','INACTIVE','ACTIVE','INACTIVE','ACTIVE','ACTIVE', 'ACTIVE','INACTIVE') TERMINATED &lt;- c('1999-07-06' , '2008-12-05' , '2000-08-18' , '2000-08-18' ,'2000-08-18' ,'2008-08-18', '2008-08-18','2006-09-19','2006-09-19' ,'2006-09-19' ,'1999-03-15') START &lt;- c('2007-04-23','2008-12-06','2004-06-01','2007-02-01','2008-04-19','2010-11-29','2010-12-30', '2007-10-29','2008-02-05','2008-06-30','2009-02-07') STOP &lt;- c('2008-12-05','4712-12-31','2007-01-31','2008-04-18','2010-11-28','2010-12-29','4712-12-31', '2008-02-04','2008-06-29','2009-02-06','4712-12-31') #creating dataframe TEST &lt;- data.frame(UNIT,STATUS,TERMINATED,START,STOP); TEST UNIT STATUS TERMINATED START STOP 1 NA ACTIVE 1999-07-06 2007-04-23 2008-12-05 2 NA INACTIVE 2008-12-05 2008-12-06 4712-12-31 3 200 ACTIVE 2000-08-18 2004-06-01 2007-01-31 4 200 ACTIVE 2000-08-18 2007-02-01 2008-04-18 5 200 INACTIVE 2000-08-18 2008-04-19 2010-11-28 6 200 ACTIVE 2008-08-18 2010-11-29 2010-12-29 7 200 INACTIVE 2008-08-18 2010-12-30 4712-12-31 8 300 ACTIVE 2006-09-19 2007-10-29 2008-02-04 9 300 ACTIVE 2006-09-19 2008-02-05 2008-06-29 10 300 ACTIVE 2006-09-19 2008-06-30 2009-02-06 11 300 INACTIVE 1999-03-15 2009-02-07 4712-12-31 #using the syntax for a conditional replace and hoping it works :/ TEST$UNIT[is.na(TEST$UNIT)] &lt;- TEST$STATUS; TEST UNIT STATUS TERMINATED START STOP 1 1 ACTIVE 1999-07-06 2007-04-23 2008-12-05 2 2 INACTIVE 2008-12-05 2008-12-06 4712-12-31 3 200 ACTIVE 2000-08-18 2004-06-01 2007-01-31 4 200 ACTIVE 2000-08-18 2007-02-01 2008-04-18 5 200 INACTIVE 2000-08-18 2008-04-19 2010-11-28 6 200 ACTIVE 2008-08-18 2010-11-29 2010-12-29 7 200 INACTIVE 2008-08-18 2010-12-30 4712-12-31 8 300 ACTIVE 2006-09-19 2007-10-29 2008-02-04 9 300 ACTIVE 2006-09-19 2008-02-05 2008-06-29 10 300 ACTIVE 2006-09-19 2008-06-30 2009-02-06 11 300 INACTIVE 1999-03-15 2009-02-07 4712-12-31 </code></pre> <p>The outcome should be: </p> <pre><code> UNIT STATUS TERMINATED START STOP 1 ACTIVE ACTIVE 1999-07-06 2007-04-23 2008-12-05 2 INACTIVE INACTIVE 2008-12-05 2008-12-06 4712-12-31 3 200 ACTIVE 2000-08-18 2004-06-01 2007-01-31 4 200 ACTIVE 2000-08-18 2007-02-01 2008-04-18 5 200 INACTIVE 2000-08-18 2008-04-19 2010-11-28 6 200 ACTIVE 2008-08-18 2010-11-29 2010-12-29 7 200 INACTIVE 2008-08-18 2010-12-30 4712-12-31 8 300 ACTIVE 2006-09-19 2007-10-29 2008-02-04 9 300 ACTIVE 2006-09-19 2008-02-05 2008-06-29 10 300 ACTIVE 2006-09-19 2008-06-30 2009-02-06 11 300 INACTIVE 1999-03-15 2009-02-07 4712-12-31 </code></pre>
0
1,599
How to test Akka Actor functionality by mocking one or more methods in it
<p>I'm interested to know about how to test Akka Actor functionality, <strong>by mocking some methods</strong> (<em>substitute real object's/actor's method implementation by mocked one</em>) in Actor.</p> <p>I use <code>akka.testkit.TestActorRef</code>;</p> <p>Also: I tried to use <code>SpyingProducer</code> but it is not clear how to use it. (like I if I created actor inside its implementation it would be the same I have now). The google search result about that is not very <a href="https://www.google.com/search?q=SpyingProducer&amp;sugexp=chrome,mod=15&amp;sourceid=chrome&amp;ie=UTF-8#sclient=psy-ab&amp;q=SpyingProducer%20akka&amp;oq=SpyingProducer%20akka&amp;gs_l=serp.3...2684.3580.4.3806.5.1.4.0.0.0.212.212.2-1.1.0.epsugrccggmnoe..0.0...1.1.14.psy-ab.VAaiiJogNy0&amp;pbx=1&amp;bav=on.2,or.r_cp.r_qf.&amp;bvm=bv.46865395,d.cGE&amp;fp=9e0125f66928f75e&amp;biw=1536&amp;bih=754">verbose</a>.</p> <p>I use <code>powemockito</code> and <code>java</code>. But It does not matter. I would be interested to know <code>how to do it in principle</code> <strong>with any language with any framework</strong> </p> <blockquote> <p>(so if you do not know how power/mockito works just provide your code.. (please) or complete idea about how you would do it with your tools you know.)</p> </blockquote> <p>So, let's say we have an Actor to test:</p> <pre><code>package example.formock; import akka.actor.UntypedActor; public class ToBeTestedActor extends UntypedActor { @Override public void onReceive(Object message) throws Exception { if (message instanceof String) { getSender().tell( getHelloMessage((String) message), getSelf()); } } String getHelloMessage(String initMessage) { // this was created for test purposes (for testing mocking/spy capabilities). Look at the test return "Hello, " + initMessage; } } </code></pre> <p>And in our test we want to substitute <code>getHelloMessage()</code> returning something else.</p> <p>This is my try:</p> <pre><code>package example.formock; import akka.testkit.TestActorRef; ... @RunWith(PowerMockRunner.class) @PrepareForTest(ToBeTestedActor.class) public class ToBeTestedActorTest { static final Timeout timeout = new Timeout(Duration.create(5, "seconds")); @Test public void getHelloMessage() { final ActorSystem system = ActorSystem.create("system"); // given final TestActorRef&lt;ToBeTestedActor&gt; actorRef = TestActorRef.create( system, Props.create(ToBeTestedActor.class), "toBeTestedActor"); // First try: ToBeTestedActor actorSpy = PowerMockito.spy(actorRef.underlyingActor()); // change functionality PowerMockito.when(actorSpy.getHelloMessage (anyString())).thenReturn("nothing"); // &lt;- expecting result try { // when Future&lt;Object&gt; future = Patterns.ask(actorRef, "Bob", timeout); // then assertTrue(future.isCompleted()); // when String resultMessage = (String) Await.result(future, Duration.Zero()); // then assertEquals("nothing", resultMessage); // FAIL HERE } catch (Exception e) { fail("ops"); } } } </code></pre> <p><strong>Result:</strong></p> <pre><code>org.junit.ComparisonFailure: Expected :nothing Actual :Hello, Bob </code></pre>
0
1,375
ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR: syntax error at or near "."
<p>I am not sure why my query works on localhost but is failing on the server. This happens when i try to create a quiz which routes to QuizzesController#new</p> <pre><code># GET /quizzes/new def new @quiz = current_user.quizzes.new end </code></pre> <p>This is the query: </p> <pre><code>SELECT COUNT(*) FROM "questions" INNER JOIN "question_categories" ON "question_categories"."question_id" = "questions"."id" WHERE "questions"."deleted_at" IS NULL AND (`question_categories`.`category_id` IN (87,1)) (1.0ms) ROLLBACK Completed 500 Internal Server Error in 58ms (ActiveRecord: 13.4ms) </code></pre> <p>And i got an error as such.</p> <pre><code>ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR: syntax error at or near "." LINE 1: ...s"."deleted_at" IS NULL AND (`question_categories`.`category... </code></pre> <p>quiz.rb before creating i would run build_parts which should randomly grab questions and place them into quizzes. class Quiz &lt; ActiveRecord::Base belongs_to :user belongs_to :subject has_many :quiz_categories has_many :categories, through: :quiz_categories has_many :quiz_parts</p> <pre><code> accepts_nested_attributes_for :categories accepts_nested_attributes_for :quiz_parts validates :user, :subject, :number_of_questions, presence: true validates :number_of_questions, numericality: { only_integer: true, greater_than_or_equal_to: 1 } before_create :build_parts before_save :set_completed_at, if: -&gt; { completeness == 100.00 } def completeness answerable_quiz_parts = 0 quiz_parts.each do |q_part| answerable_quiz_parts += 1 if q_part.answerable.answers.present? end quiz_parts.joins(:choice).count.to_f * 100 / answerable_quiz_parts end def score quiz_parts.joins(:choice).where('choices.correct = ?', true).count { |qp| qp.choice.correct? } end private # select random questions def build_parts category_ids = self.categories.map(&amp;:id) question_pool = Question.joins(:question_categories).where('`question_categories`.`category_id` IN (?)', category_ids) #self.number_of_questions = [number_of_questions, question_pool.size].min puts question_pool.size if number_of_questions &gt; question_pool.size errors.add(:number_of_questions, 'is too high. Please select a lower question count or increase category selections') return false end number_of_questions.times do |i| question_pool.inspect self.quiz_parts &lt;&lt; question_pool[i].quiz_parts.new question_pool[i].question_parts.each do |question_part| self.quiz_parts &lt;&lt; question_part.quiz_parts.new end end end def set_completed_at self.completed_at = Time.zone.now end end </code></pre> <p>quizzes_controller.rb</p> <pre><code>class QuizzesController &lt; ApplicationController before_action :authenticate_user! before_action :set_quiz, only: [:show, :edit, :update, :destroy] # GET /quizzes # GET /quizzes.json def index @quizzes = current_user.quizzes.order(created_at: :desc) end # GET /quizzes/1 # GET /quizzes/1.json def show end # GET /quizzes/new def new @quiz = current_user.quizzes.new end # GET /quizzes/1/edit def edit end # POST /quizzes # POST /quizzes.json def create @quiz = current_user.quizzes.new(quiz_create_params) respond_to do |format| if @quiz.save format.html { redirect_to edit_quiz_path(@quiz), notice: 'Quiz was successfully created.' } format.json { render :show, status: :created, location: @quiz } else format.html { render :new } format.json { render json: @quiz.errors, status: :unprocessable_entity } end end end # PATCH/PUT /quizzes/1 # PATCH/PUT /quizzes/1.json def update respond_to do |format| if @quiz.update(quiz_update_params) format.html { redirect_to @quiz, notice: 'Quiz was successfully updated.' } format.json { render :show, status: :ok, location: @quiz } else format.html { render :edit } format.json { render json: @quiz.errors, status: :unprocessable_entity } end end end # DELETE /quizzes/1 # DELETE /quizzes/1.json def destroy @quiz.destroy respond_to do |format| format.html { redirect_to quizzes_url, notice: 'Quiz was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_quiz @quiz = current_user.quizzes.find(params[:id]) end # For quiz setup def quiz_create_params params.require(:quiz).permit(:subject_id, :number_of_questions, category_ids: []) end # For quiz answering def quiz_update_params params.require(:quiz).permit(quiz_parts_attributes: [:id, choice_attributes: [:id, :content, :answer_id, :_destroy]]) end end </code></pre> <p>schema.rb:</p> <pre><code>ActiveRecord::Schema.define(version: 20150726180000) do create_table "admins", force: :cascade do |t| t.string "email" t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.string "confirmation_token" t.datetime "confirmed_at" t.datetime "confirmation_sent_at" t.datetime "created_at" t.datetime "updated_at" end add_index "admins", ["confirmation_token"], name: "index_admins_on_confirmation_token", unique: true add_index "admins", ["email"], name: "index_admins_on_email", unique: true add_index "admins", ["reset_password_token"], name: "index_admins_on_reset_password_token", unique: true create_table "answers", force: :cascade do |t| t.integer "number" t.text "content" t.boolean "correct", default: false, null: false t.integer "answerable_id" t.string "answerable_type" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "answers", ["answerable_type", "answerable_id"], name: "index_answers_on_answerable_type_and_answerable_id" create_table "categories", force: :cascade do |t| t.string "name" t.integer "subject_id" t.integer "category_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "categories", ["category_id"], name: "index_categories_on_category_id" add_index "categories", ["subject_id"], name: "index_categories_on_subject_id" create_table "choices", force: :cascade do |t| t.string "content" t.integer "quiz_part_id" t.integer "answer_id" t.boolean "correct" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "choices", ["answer_id"], name: "index_choices_on_answer_id" add_index "choices", ["quiz_part_id"], name: "index_choices_on_quiz_part_id" create_table "ckeditor_assets", force: :cascade do |t| t.string "data_file_name", null: false t.string "data_content_type" t.integer "data_file_size" t.integer "assetable_id" t.string "assetable_type", limit: 30 t.string "type", limit: 30 t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end add_index "ckeditor_assets", ["assetable_type", "assetable_id"], name: "idx_ckeditor_assetable" add_index "ckeditor_assets", ["assetable_type", "type", "assetable_id"], name: "idx_ckeditor_assetable_type" create_table "levels", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "question_categories", force: :cascade do |t| t.integer "question_id" t.integer "category_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "question_categories", ["category_id"], name: "index_question_categories_on_category_id" add_index "question_categories", ["question_id"], name: "index_question_categories_on_question_id" create_table "question_parts", force: :cascade do |t| t.text "content" t.string "type" t.integer "question_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.datetime "deleted_at" end add_index "question_parts", ["deleted_at"], name: "index_question_parts_on_deleted_at" add_index "question_parts", ["question_id"], name: "index_question_parts_on_question_id" create_table "questions", force: :cascade do |t| t.text "content" t.string "type" t.integer "level_id" t.integer "subject_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.datetime "deleted_at" t.string "source" end add_index "questions", ["deleted_at"], name: "index_questions_on_deleted_at" add_index "questions", ["level_id"], name: "index_questions_on_level_id" add_index "questions", ["subject_id"], name: "index_questions_on_subject_id" create_table "quiz_categories", force: :cascade do |t| t.integer "category_id" t.integer "quiz_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "quiz_categories", ["category_id"], name: "index_quiz_categories_on_category_id" add_index "quiz_categories", ["quiz_id"], name: "index_quiz_categories_on_quiz_id" create_table "quiz_parts", force: :cascade do |t| t.integer "quiz_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "answerable_id" t.string "answerable_type" end add_index "quiz_parts", ["answerable_type", "answerable_id"], name: "index_quiz_parts_on_answerable_type_and_answerable_id" add_index "quiz_parts", ["quiz_id"], name: "index_quiz_parts_on_quiz_id" create_table "quizzes", force: :cascade do |t| t.integer "user_id" t.datetime "completed_at" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "subject_id" t.integer "number_of_questions" end add_index "quizzes", ["subject_id"], name: "index_quizzes_on_subject_id" add_index "quizzes", ["user_id"], name: "index_quizzes_on_user_id" create_table "subjects", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "users", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.datetime "created_at" t.datetime "updated_at" end add_index "users", ["email"], name: "index_users_on_email", unique: true add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true end </code></pre>
0
4,669
Efficient method of calculating density of irregularly spaced points
<p>I am attempting to generate map overlay images that would assist in identifying hot-spots, that is areas on the map that have high density of data points. None of the approaches that I've tried are fast enough for my needs. Note: I forgot to mention that the algorithm should work well under both low and high zoom scenarios (or low and high data point density).</p> <p>I looked through numpy, pyplot and scipy libraries, and the closest I could find was numpy.histogram2d. As you can see in the image below, the histogram2d output is rather crude. (Each image includes points overlaying the heatmap for better understanding)</p> <p><img src="https://i.stack.imgur.com/sOmIz.png" alt="enter image description here"> My second attempt was to iterate over all the data points, and then calculate the hot-spot value as a function of distance. This produced a better looking image, however it is too slow to use in my application. Since it's O(n), it works ok with 100 points, but blows out when I use my actual dataset of 30000 points.</p> <p>My final attempt was to store the data in an KDTree, and use the nearest 5 points to calculate the hot-spot value. This algorithm is O(1), so much faster with large dataset. It's still not fast enough, it takes about 20 seconds to generate a 256x256 bitmap, and I would like this to happen in around 1 second time.</p> <p><strong>Edit</strong></p> <p>The boxsum smoothing solution provided by 6502 works well at all zoom levels and is much faster than my original methods. </p> <p>The gaussian filter solution suggested by Luke and Neil G is the fastest.</p> <p>You can see all four approaches below, using 1000 data points in total, at 3x zoom there are around 60 points visible.</p> <p><img src="https://i.stack.imgur.com/tOUDI.png" alt="enter image description here"></p> <p>Complete code that generates my original 3 attempts, the boxsum smoothing solution provided by 6502 and gaussian filter suggested by Luke (improved to handle edges better and allow zooming in) is here:</p> <pre><code>import matplotlib import numpy as np from matplotlib.mlab import griddata import matplotlib.cm as cm import matplotlib.pyplot as plt import math from scipy.spatial import KDTree import time import scipy.ndimage as ndi def grid_density_kdtree(xl, yl, xi, yi, dfactor): zz = np.empty([len(xi),len(yi)], dtype=np.uint8) zipped = zip(xl, yl) kdtree = KDTree(zipped) for xci in range(0, len(xi)): xc = xi[xci] for yci in range(0, len(yi)): yc = yi[yci] density = 0. retvalset = kdtree.query((xc,yc), k=5) for dist in retvalset[0]: density = density + math.exp(-dfactor * pow(dist, 2)) / 5 zz[yci][xci] = min(density, 1.0) * 255 return zz def grid_density(xl, yl, xi, yi): ximin, ximax = min(xi), max(xi) yimin, yimax = min(yi), max(yi) xxi,yyi = np.meshgrid(xi,yi) #zz = np.empty_like(xxi) zz = np.empty([len(xi),len(yi)]) for xci in range(0, len(xi)): xc = xi[xci] for yci in range(0, len(yi)): yc = yi[yci] density = 0. for i in range(0,len(xl)): xd = math.fabs(xl[i] - xc) yd = math.fabs(yl[i] - yc) if xd &lt; 1 and yd &lt; 1: dist = math.sqrt(math.pow(xd, 2) + math.pow(yd, 2)) density = density + math.exp(-5.0 * pow(dist, 2)) zz[yci][xci] = density return zz def boxsum(img, w, h, r): st = [0] * (w+1) * (h+1) for x in xrange(w): st[x+1] = st[x] + img[x] for y in xrange(h): st[(y+1)*(w+1)] = st[y*(w+1)] + img[y*w] for x in xrange(w): st[(y+1)*(w+1)+(x+1)] = st[(y+1)*(w+1)+x] + st[y*(w+1)+(x+1)] - st[y*(w+1)+x] + img[y*w+x] for y in xrange(h): y0 = max(0, y - r) y1 = min(h, y + r + 1) for x in xrange(w): x0 = max(0, x - r) x1 = min(w, x + r + 1) img[y*w+x] = st[y0*(w+1)+x0] + st[y1*(w+1)+x1] - st[y1*(w+1)+x0] - st[y0*(w+1)+x1] def grid_density_boxsum(x0, y0, x1, y1, w, h, data): kx = (w - 1) / (x1 - x0) ky = (h - 1) / (y1 - y0) r = 15 border = r * 2 imgw = (w + 2 * border) imgh = (h + 2 * border) img = [0] * (imgw * imgh) for x, y in data: ix = int((x - x0) * kx) + border iy = int((y - y0) * ky) + border if 0 &lt;= ix &lt; imgw and 0 &lt;= iy &lt; imgh: img[iy * imgw + ix] += 1 for p in xrange(4): boxsum(img, imgw, imgh, r) a = np.array(img).reshape(imgh,imgw) b = a[border:(border+h),border:(border+w)] return b def grid_density_gaussian_filter(x0, y0, x1, y1, w, h, data): kx = (w - 1) / (x1 - x0) ky = (h - 1) / (y1 - y0) r = 20 border = r imgw = (w + 2 * border) imgh = (h + 2 * border) img = np.zeros((imgh,imgw)) for x, y in data: ix = int((x - x0) * kx) + border iy = int((y - y0) * ky) + border if 0 &lt;= ix &lt; imgw and 0 &lt;= iy &lt; imgh: img[iy][ix] += 1 return ndi.gaussian_filter(img, (r,r)) ## gaussian convolution def generate_graph(): n = 1000 # data points range data_ymin = -2. data_ymax = 2. data_xmin = -2. data_xmax = 2. # view area range view_ymin = -.5 view_ymax = .5 view_xmin = -.5 view_xmax = .5 # generate data xl = np.random.uniform(data_xmin, data_xmax, n) yl = np.random.uniform(data_ymin, data_ymax, n) zl = np.random.uniform(0, 1, n) # get visible data points xlvis = [] ylvis = [] for i in range(0,len(xl)): if view_xmin &lt; xl[i] &lt; view_xmax and view_ymin &lt; yl[i] &lt; view_ymax: xlvis.append(xl[i]) ylvis.append(yl[i]) fig = plt.figure() # plot histogram plt1 = fig.add_subplot(221) plt1.set_axis_off() t0 = time.clock() zd, xe, ye = np.histogram2d(yl, xl, bins=10, range=[[view_ymin, view_ymax],[view_xmin, view_xmax]], normed=True) plt.title('numpy.histogram2d - '+str(time.clock()-t0)+"sec") plt.imshow(zd, origin='lower', extent=[view_xmin, view_xmax, view_ymin, view_ymax]) plt.scatter(xlvis, ylvis) # plot density calculated with kdtree plt2 = fig.add_subplot(222) plt2.set_axis_off() xi = np.linspace(view_xmin, view_xmax, 256) yi = np.linspace(view_ymin, view_ymax, 256) t0 = time.clock() zd = grid_density_kdtree(xl, yl, xi, yi, 70) plt.title('function of 5 nearest using kdtree\n'+str(time.clock()-t0)+"sec") cmap=cm.jet A = (cmap(zd/256.0)*255).astype(np.uint8) #A[:,:,3] = zd plt.imshow(A , origin='lower', extent=[view_xmin, view_xmax, view_ymin, view_ymax]) plt.scatter(xlvis, ylvis) # gaussian filter plt3 = fig.add_subplot(223) plt3.set_axis_off() t0 = time.clock() zd = grid_density_gaussian_filter(view_xmin, view_ymin, view_xmax, view_ymax, 256, 256, zip(xl, yl)) plt.title('ndi.gaussian_filter - '+str(time.clock()-t0)+"sec") plt.imshow(zd , origin='lower', extent=[view_xmin, view_xmax, view_ymin, view_ymax]) plt.scatter(xlvis, ylvis) # boxsum smoothing plt3 = fig.add_subplot(224) plt3.set_axis_off() t0 = time.clock() zd = grid_density_boxsum(view_xmin, view_ymin, view_xmax, view_ymax, 256, 256, zip(xl, yl)) plt.title('boxsum smoothing - '+str(time.clock()-t0)+"sec") plt.imshow(zd, origin='lower', extent=[view_xmin, view_xmax, view_ymin, view_ymax]) plt.scatter(xlvis, ylvis) if __name__=='__main__': generate_graph() plt.show() </code></pre>
0
3,599
Consider defining a bean of type 'service' in your configuration [Spring boot]
<p>I get error when I run the main class. </p> <p><strong>Error:</strong></p> <pre><code>Action: Consider defining a bean of type 'seconds47.service.TopicService' in your configuration. Description: Field topicService in seconds47.restAPI.topics required a bean of type 'seconds47.service.TopicService' that could not be found </code></pre> <p>TopicService interface:</p> <pre><code>public interface TopicService { TopicBean findById(long id); TopicBean findByName(String name); void saveTopic(TopicBean topicBean); void updateTopic(TopicBean topicBean); void deleteTopicById(long id); List&lt;TopicBean&gt; findAllTopics(); void deleteAllTopics(); public boolean isTopicExist(TopicBean topicBean); } </code></pre> <p>controller:</p> <pre><code>@RestController public class topics { @Autowired private TopicService topicService; @RequestMapping(path = "/new_topic2", method = RequestMethod.GET) public void new_topic() throws Exception { System.out.println("new topic JAVA2"); } } </code></pre> <p>Implementation class:</p> <pre><code>public class TopicServiceImplementation implements TopicService { @Autowired private TopicService topicService; @Autowired private TopicRepository topicRepository; @Override public TopicBean findById(long id) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public TopicBean findByName(String name) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void saveTopic(TopicBean topicBean) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void updateTopic(TopicBean topicBean) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void deleteTopicById(long id) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public List&lt;TopicBean&gt; findAllTopics() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void deleteAllTopics() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isTopicExist(TopicBean topicBean) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } </code></pre> <p>Rest of the classes are defined too. I don't know why its throwing despite declaring <code>componentScan</code> in main class.</p> <p>Main class:</p> <pre><code>@SpringBootApplication(exclude = {SecurityAutoConfiguration.class }) @ComponentScan(basePackages = {"seconds47"}) @EnableJpaRepositories("seconds47.repository") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } </code></pre> <p>I have my packages like this:</p> <pre><code>seconds47 seconds47.beans seconds47.config seconds47.repository seconds47.restAPI seconds47.service </code></pre>
0
1,149
Swift: change tableview height on scroll
<p>I have a VC as shown in the image<a href="https://i.stack.imgur.com/1k8O2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1k8O2.png" alt="enter image description here"></a></p> <p>It has a <strong>UICollectionView</strong> on top, and a <strong>UITableView</strong> at the bottom. CollectionView has 1:3 of the screen and TableView has 2:3 of the screen(set using equalHeight constraint).</p> <p>I want to <strong>change the height</strong> of the <strong>UICollectionView</strong> when the <strong>tableView is scrolled</strong>.</p> <p>When the <strong>tableView</strong> is <strong>scrolled up</strong>,I want to change the multiplier of equalHeights constraint to like 1:5 and 4:5 of collectionView and tableView respectively.This will ensure that <strong>height of tableView increases</strong> and <strong>collectionView decreases</strong></p> <p>When the <strong>tableView</strong> is <strong>scrolled down</strong>, the multiplier of equalHeights constraint should <strong>reset to default</strong>.</p> <p>I've tried adding swipe and pan gestures to tableView, but they are unrecognised.</p> <p>How to achieve this functionality?</p> <p>P.S: Would love to achieve this functionality by using a pan gesture, so that dragging up and down changes the heights progressively. </p> <p>This is the view hierarchy<a href="https://i.stack.imgur.com/A9zx9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A9zx9.png" alt="enter image description here"></a></p> <p><strong>EDIT/UPDATE</strong></p> <p>This is the code that I'm using.</p> <pre><code>class MyConstant { var height:CGFloat = 10 } let myConstant = MyConstant() </code></pre> <p>MainScreenVC </p> <pre><code>override func viewWillAppear(_ animated: Bool) { myConstant.height = self.view.frame.size.height } func scrollViewDidScroll(_ scrollView: UIScrollView) { if (self.lastContentOffset &lt; scrollView.contentOffset.y) { NotificationCenter.default.post(name: Notifications.decreaseHeightNotification.name, object: nil) self.topViewConstraint.constant = -self.view.frame.height / 6 UIView.animate(withDuration: 0.3, animations: { self.view.layoutIfNeeded() }) } else if (self.lastContentOffset &gt; scrollView.contentOffset.y) { NotificationCenter.default.post(name: Notifications.increaseHeightNotification.name, object: nil) self.topViewConstraint.constant = 0 UIView.animate(withDuration: 0.3, animations: { self.view.layoutIfNeeded() }) } self.lastContentOffset = scrollView.contentOffset.y } </code></pre> <p>Cell.Swift</p> <pre><code>override func awakeFromNib() { super.awakeFromNib() NotificationCenter.default.addObserver(self, selector: #selector(decreaseHeight), name: Notification.Name("decreaseHeightNotification"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(increaseHeight), name: Notification.Name("increaseHeightNotification"), object: nil) self.contentView.translatesAutoresizingMaskIntoConstraints = false heightConstraint.constant = (myConstant.height / 3) - 10 widthConstraint.constant = heightConstraint.constant * 1.5 } @objc func decreaseHeight() { heightConstraint.constant = (myConstant.height / 6) - 10 widthConstraint.constant = (heightConstraint.constant * 1.5) self.layoutIfNeeded() } @objc func increaseHeight() { heightConstraint.constant = (myConstant.height / 3) - 10 widthConstraint.constant = (heightConstraint.constant * 1.5) self.layoutIfNeeded() } </code></pre> <p>Now when I scroll both simultaneously, the screen freezes. Also is there a better way of resizing the collectionViewCell size? </p>
0
1,296
Update data in access mdb database in c# form application " syntax error in update statement"
<p>I was working in C# form application with an MS-Access <code>mdb</code> database. I have a database in which I have a table <code>Customers</code> with two columns <code>CustomerId</code> And <code>Balance</code>. Both columns are of <code>integer</code> datatype.</p> <p>Error I was getting is</p> <blockquote> <p>System.Data.OleDb.OleDbException: <strong>Syntax error in UPDATE statement.</strong></p> <p>at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)<br> at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object&amp; executeResult)<br> at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object&amp; executeResult)<br> at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object&amp; executeResult)<br> at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)<br> at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()<br> at xml_and_db_test.Form1.button1_Click(Object sender, EventArgs e) in G:\my Documents\Visual Studio 2008\Projects\xml_and_db_test\xml_and_db_test\Form1.cs:line 45 </p> </blockquote> <p>Codes I have tried till now are</p> <pre><code>try { OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\database_for_kissan_Pashu_AhaR_Bills.mdb"); int balance = Convert.ToInt32(textBox2.Text); int id = Convert.ToInt32(textBox1.Text); // int recordnumb = int.Parse(recordTextBox.Text); // OleDbConnection oleDbConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Checkout-1\\Documents\\contact.accdb"); OleDbCommand update = new OleDbCommand("UPDATE Customers SET Balance = '" + balance + "', WHERE id = " + id + " ", con); con.Open(); update.ExecuteNonQuery(); con.Close(); // string queryText = "UPDATE Customers SET Balance = ?, where CustomerId = ?;"; //string queryText = " 'UPDATE Customers SET Balance =' " + balance+ " ' WHERE CustomerId= ' " + id + " ' " ; //OleDbCommand cmd = new OleDbCommand(queryText, con); //cmd.CommandType = CommandType.Text; //cmd.Parameters.AddWithValue("@balance", Convert.ToInt32(textBox2.Text)); //cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(textBox1.Text)); //cmd.Parameters.Add("Balance", OleDbType.Integer).Value = Convert.ToInt32(textBox2.Text); //cmd.Parameters.Add("CustomerId", OleDbType.Integer).Value = Convert.ToInt32(textBox1.Text); //con.Open(); // open the connection ////OleDbDataReader dr = cmd.ExecuteNonQuery(); //int yy = cmd.ExecuteNonQuery(); //con.Close(); } catch (Exception ex) { string c = ex.ToString(); MessageBox.Show(c); } //try //{ // OleDbConnection con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = G:\\my Documents\\Visual Studio 2008\\Projects\\xml_and_db_test\\xml_and_db_test\\bin\\Debug\\database_for_kissan_Pashu_AhaR_Bills.mdb"); // string queryText = "UPDATE Customers SET Balance = ?, where CustomerId = ?;"; // OleDbCommand cmd = new OleDbCommand(queryText, con); // cmd.CommandType = CommandType.Text; // //cmd.Parameters.AddWithValue("@balance", Convert.ToInt32(textBox2.Text)); // //cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(textBox1.Text)); // cmd.Parameters.Add("Balance", OleDbType.Integer).Value = Convert.ToInt32(textBox2.Text); // cmd.Parameters.Add("CustomerId", OleDbType.Integer).Value = Convert.ToInt32(textBox1.Text); // con.Open(); // open the connection // //OleDbDataReader dr = cmd.ExecuteNonQuery(); // int yy = cmd.ExecuteNonQuery(); // con.Close(); //} //catch (Exception ex) //{ // string c = ex.ToString(); // MessageBox.Show(c); //} //string connetionString = null; //OleDbConnection connection; //OleDbDataAdapter oledbAdapter = new OleDbDataAdapter(); //string sql = null; //connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = G:\\my Documents\\Visual Studio 2008\\Projects\\xml_and_db_test\\xml_and_db_test\\bin\\Debug\\database_for_kissan_Pashu_AhaR_Bills.mdb;"; //connection = new OleDbConnection(connetionString); //sql = "update Customers set Balance = '1807' where CustomerId = '1'"; //try //{ // connection.Open(); // oledbAdapter.UpdateCommand = connection.CreateCommand(); // oledbAdapter.UpdateCommand.CommandText = sql; // oledbAdapter.UpdateCommand.ExecuteNonQuery(); // MessageBox.Show("Row(s) Updated !! "); // connection.Close(); //} //catch (Exception ex) //{ // MessageBox.Show(ex.ToString()); //} </code></pre> <p>some codes are In comments and some are with every method i'm getting the same error.</p>
0
1,698
local variable or method `config' for main:Object (NameError)
<p>I'm following this post for integrating Omniauth Twitter + Devise <a href="http://sourcey.com/rails-4-omniauth-using-devise-with-twitter-facebook-and-linkedin/" rel="noreferrer">http://sourcey.com/rails-4-omniauth-using-devise-with-twitter-facebook-and-linkedin/</a> and I have encounter an issue that is blocking me to start my rails app.</p> <pre><code> /Users/javier/Desktop/definitive/config/environment.rb:8:in `&lt;top (required)&gt;': undefined local variable or method `config' for main:Object (NameError) from /Users/javier/.rvm/gems/ruby-2.1.2/gems/activesupport-4.1.1/lib/active_support/dependencies.rb:247:in `require' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/activesupport-4.1.1/lib/active_support/dependencies.rb:247:in `block in require' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/activesupport-4.1.1/lib/active_support/dependencies.rb:232:in `load_dependency' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/activesupport-4.1.1/lib/active_support/dependencies.rb:247:in `require' from /Users/javier/Desktop/definitive/config.ru:3:in `block in &lt;main&gt;' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/rack-1.5.2/lib/rack/builder.rb:55:in `instance_eval' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/rack-1.5.2/lib/rack/builder.rb:55:in `initialize' from /Users/javier/Desktop/definitive/config.ru:in `new' from /Users/javier/Desktop/definitive/config.ru:in `&lt;main&gt;' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/rack-1.5.2/lib/rack/builder.rb:49:in `eval' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/rack-1.5.2/lib/rack/builder.rb:49:in `new_from_string' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/rack-1.5.2/lib/rack/builder.rb:40:in `parse_file' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/rack-1.5.2/lib/rack/server.rb:277:in `build_app_and_options_from_config' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/rack-1.5.2/lib/rack/server.rb:199:in `app' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/railties-4.1.1/lib/rails/commands/server.rb:50:in `app' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/rack-1.5.2/lib/rack/server.rb:314:in `wrapped_app' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/railties-4.1.1/lib/rails/commands/server.rb:130:in `log_to_stdout' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/railties-4.1.1/lib/rails/commands/server.rb:67:in `start' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/railties-4.1.1/lib/rails/commands/commands_tasks.rb:81:in `block in server' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/railties-4.1.1/lib/rails/commands/commands_tasks.rb:76:in `tap' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/railties-4.1.1/lib/rails/commands/commands_tasks.rb:76:in `server' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/railties-4.1.1/lib/rails/commands/commands_tasks.rb:40:in `run_command!' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/railties-4.1.1/lib/rails/commands.rb:17:in `&lt;top (required)&gt;' from /Users/javier/Desktop/definitive/bin/rails:8:in `require' from /Users/javier/Desktop/definitive/bin/rails:8:in `&lt;top (required)&gt;' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/spring-1.1.3/lib/spring/client/rails.rb:27:in `load' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/spring-1.1.3/lib/spring/client/rails.rb:27:in `call' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/spring-1.1.3/lib/spring/client/command.rb:7:in `call' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/spring-1.1.3/lib/spring/client.rb:26:in `run' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/spring-1.1.3/bin/spring:48:in `&lt;top (required)&gt;' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/spring-1.1.3/lib/spring/binstub.rb:11:in `load' from /Users/javier/.rvm/gems/ruby-2.1.2/gems/spring-1.1.3/lib/spring/binstub.rb:11:in `&lt;top (required)&gt;' from /Users/javier/Desktop/definitive/bin/spring:16:in `require' from /Users/javier/Desktop/definitive/bin/spring:16:in `&lt;top (required)&gt;' from bin/rails:3:in `load' from bin/rails:3:in `&lt;main&gt;' </code></pre> <p>I guess the issue is in the line 8 of <code>config/environment.rb</code> but can not find with the right fix. Is it possible that environment.rb should be included in 'config/environments/'?</p>
0
1,904
Android Parcelable -- RetailerOrderActivity.java return null
<p>I have to pass one activity to another activity:</p> <p>I have SalesProduct enetity class: </p> <pre><code> public class Product implements Parcelable{ private double availableQuantity; private double price; private String productCode; private String description; private String description2; private String productGroup; private String alternateSearch; private String productTypeCode; private String nonStockItemFlag; private String salableFlag; private double weight; private double qty; private double grossValue; private double value; private ArrayList&lt;Product&gt; product; public Product() { } public Product(Parcel in) { this(); readFromParcel(in); } /* * Constructor calls read to create object */ private void readFromParcel(Parcel in) { in.readTypedList(product, Product.CREATOR); /* NULLPOINTER HERE */ } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeList(product); } public static final Parcelable.Creator&lt;Product&gt; CREATOR = new Parcelable.Creator&lt;Product&gt;() { public Product createFromParcel(Parcel in) { Product prod = new Product(); Bundle b = in.readBundle(Product.class.getClassLoader()); prod.product = b.getParcelableArrayList("enteredProduct"); return prod; } public Product[] newArray(int size) { return new Product[size]; } }; /** * @param product */ public Product(ArrayList&lt;Product&gt; product) { this.product = product; } /** * @param availableQuantity * @param price * @param productCode * @param description * @param nonStockItemFlag * @param kitProductFlag * @param qty * @param grossValue * @param value */ public Product(double availableQuantity, double price, String productCode, String description, String nonStockItemFlag, double qty, double value) { super(); this.availableQuantity = availableQuantity; this.price = price; this.productCode = productCode; this.description = description; this.nonStockItemFlag = nonStockItemFlag; this.qty = qty; this.value = value; } public ArrayList&lt;Product&gt; getProduct() { return product; } public void setProduct(ArrayList&lt;Product&gt; product) { this.product = product; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } public double getGrossValue() { return grossValue; } public void setGrossValue(double grossValue) { this.grossValue = grossValue; } public double getQty() { return qty; } public void setQty(double qty) { this.qty = qty; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public double getAvailableQuantity() { return availableQuantity; } public void setAvailableQuantity(double availableQuantity) { this.availableQuantity = availableQuantity; } public String getProductCode() { return productCode; } public void setProductCode(String productCode) { this.productCode = productCode; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDescription2() { return description2; } public void setDescription2(String description2) { this.description2 = description2; } public String getProductGroup() { return productGroup; } public void setProductGroup(String productGroup) { this.productGroup = productGroup; } public String getAlternateSearch() { return alternateSearch; } public void setAlternateSearch(String alternateSearch) { this.alternateSearch = alternateSearch; } public String getProductTypeCode() { return productTypeCode; } public void setProductTypeCode(String productTypeCode) { this.productTypeCode = productTypeCode; } public String getNonStockItemFlag() { return nonStockItemFlag; } public void setNonStockItemFlag(String nonStockItemFlag) { this.nonStockItemFlag = nonStockItemFlag; } public String getSalableFlag() { return salableFlag; } public void setSalableFlag(String salableFlag) { this.salableFlag = salableFlag; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } } </code></pre> <p>And caller Activity :</p> <pre><code> if(productMap.size() &gt;0){ ArrayList&lt;Product&gt; enteredProductList = new ArrayList&lt;Product&gt;(productMap.values()); Bundle b = new Bundle(); Product pr =new Product(enteredProductList); b.putParcelableArrayList("enteredProduct", enteredProductList); Intent showContent = new Intent(getApplicationContext(),RetailerOrderIActivity.class); showContent.putExtras(b); //Insert the Bundle object in the Intent' Extras startActivity(showContent); }else{ Toast.makeText(RetailerOrderActivity.this," You don't have invoice records" ,Toast.LENGTH_SHORT).show(); } </code></pre> <p>and receive part : </p> <pre><code> public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.order_main); Bundle b = this.getIntent().getExtras(); ArrayList&lt;Product&gt; p = b.getParcelableArrayList("enteredProduct"); System.out.println("-- RetailerOrderIActivity --" + p.size()); for (Product s : p) { System.out.println(" --Qty-" + s.getQty()); System.out.println(" --price -" + s.getPrice()); System.out.println(" --code -" + s.getProductCode()); } </code></pre> <p>This is my error part :</p> <pre><code> 09-13 16:22:43.236: ERROR/AndroidRuntime(343): FATAL EXCEPTION: main 09-13 16:22:43.236: ERROR/AndroidRuntime(343): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xont.controller/com.xont.controller.sales.RetailerOrderIActivity}: java.lang.NullPointerException 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.os.Handler.dispatchMessage(Handler.java:99) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.os.Looper.loop(Looper.java:123) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.app.ActivityThread.main(ActivityThread.java:3683) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at java.lang.reflect.Method.invokeNative(Native Method) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at java.lang.reflect.Method.invoke(Method.java:507) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at dalvik.system.NativeStart.main(Native Method) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): Caused by: java.lang.NullPointerException 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at com.xont.entity.Product$1.createFromParcel(Product.java:94) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at com.xont.entity.Product$1.createFromParcel(Product.java:1) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.os.Parcel.readParcelable(Parcel.java:1981) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.os.Parcel.readValue(Parcel.java:1846) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.os.Parcel.readListInternal(Parcel.java:2092) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.os.Parcel.readArrayList(Parcel.java:1536) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.os.Parcel.readValue(Parcel.java:1867) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.os.Parcel.readMapInternal(Parcel.java:2083) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.os.Bundle.unparcel(Bundle.java:208) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.os.Bundle.getParcelableArrayList(Bundle.java:1144) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at com.xont.controller.sales.RetailerOrderIActivity.onCreate(RetailerOrderIActivity.java:18) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 09-13 16:22:43.236: ERROR/AndroidRuntime(343): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) </code></pre> <p>Please help me..its return null ... where is wrong ?please advice me on this?</p> <p>Thanks in advance</p>
0
3,794
Why isn't factory_girl operating transactionally for me? - rows remain in database after tests
<p>I'm trying to use factory_girl to create a "user" factory (with RSpec) however it doesn't seem to be operating transactionally and is apparently failing because of remnant data from previous tests in the test database.</p> <pre><code>Factory.define :user do |user| user.name "Joe Blow" user.email "joe@blow.com" user.password 'password' user.password_confirmation 'password' end @user = Factory.create(:user) </code></pre> <p>Running the first set of tests is fine:</p> <pre><code>spec spec/ ... Finished in 2.758806 seconds 60 examples, 0 failures, 11 pending </code></pre> <p>All good and as expected, however running the tests again:</p> <pre><code>spec spec/ ... /Library/Ruby/Gems/1.8/gems/activerecord-2.3.8/lib/active_record/validations.rb:1102:in `save_without_dirty!': Validation failed: Email has already been taken (ActiveRecord::RecordInvalid) from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.8/lib/active_record/dirty.rb:87:in `save_without_transactions!' from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.8/lib/active_record/transactions.rb:200:in `save!' from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.8/lib/active_record/connection_adapters/abstract/database_statements.rb:136:in `transaction' from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.8/lib/active_record/transactions.rb:182:in `transaction' from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.8/lib/active_record/transactions.rb:200:in `save!' from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.8/lib/active_record/transactions.rb:208:in `rollback_active_record_state!' from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.8/lib/active_record/transactions.rb:200:in `save!' from /Library/Ruby/Gems/1.8/gems/factory_girl-1.2.3/lib/factory_girl/proxy/create.rb:6:in `result' from /Library/Ruby/Gems/1.8/gems/factory_girl-1.2.3/lib/factory_girl/factory.rb:316:in `run' from /Library/Ruby/Gems/1.8/gems/factory_girl-1.2.3/lib/factory_girl/factory.rb:260:in `create' from /Users/petenixey/Rails_apps/resample/spec/controllers/users_controller_spec.rb:7 from /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_group_methods.rb:183:in `module_eval' from /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_group_methods.rb:183:in `subclass' from /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_group_methods.rb:55:in `describe' from /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/example/example_group_factory.rb:31:in `create_example_group' from /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/dsl/main.rb:28:in `describe' from /Users/petenixey/Rails_apps/resample/spec/controllers/users_controller_spec.rb:3 from /Library/Ruby/Gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:147:in `load_without_new_constant_marking' from /Library/Ruby/Gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:147:in `load' from /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:15:in `load_files' from /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:14:in `each' from /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:14:in `load_files' from /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/runner/options.rb:133:in `run_examples' from /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/lib/spec/runner/command_line.rb:9:in `run' from /Library/Ruby/Gems/1.8/gems/rspec-1.3.0/bin/spec:5 from /usr/bin/spec:19:in `load' from /usr/bin/spec:19 </code></pre> <p><strong>Fix attempt - use Factory.sequence</strong></p> <p>Since I have a uniqueness constraint on my email field I attempted to fix the problem by using the sequence method of factory_girl:</p> <pre><code>Factory.define :user do |user| user.name "Joe Blow" user.sequence(:email) {|n| "joe#{n}@blow.com" } user.password 'password' user.password_confirmation 'password' end </code></pre> <p>I then ran </p> <pre><code>rake db:test:prepare spec spec/ .. # running the tests once executes fine spec spec/ .. # running them the second time produces the same set of errors as before </code></pre> <p><strong>Users seem to remain in the database</strong></p> <p>If I look at the /db/test.sqlite3 database it seems that the row for the test user is not being rolled back from the database between tests. I thought that these tests were supposed to be transactional but they don't seem to be so for me. </p> <p>This would explain why the test runs correctly the first time (and if I clear the database) but fails the second time. </p> <p><strong>Can anyone explain what I should change to ensure that the tests run transactionally?</strong></p>
0
1,964
Quasar App Routing Problems
<p>I am developing a Quasar App right now. So far I only have a login page and the default layout that quasar provides. I have a separate server I have set up running at port 100. I already set up the proxy to redirect all calls from axios and socket.io to my server which hosts my mySQL database for my application. I already set up my routes and if I manually type in the route in the browser's search I can go to it but once I use this.$router.push() in my login to go to the main page it doesn't navigate to it. For example I'm hosting this app on port 8080. By default it'll go to the login page which is: "localhost:8080". When the login authenticates, the user is supposed to be redirected to the main page within my quasar app using this.$router.push('/main'). However, it does not do this. When I press login, the url just changes to "localhost:8080/?". However, if I manually type in: "localhost:8080/main" in the browser it directs me toward the main page. Here is the code for my routes:</p> <pre><code>export default [ { path: '/', component: () =&gt; import('components/login'), }, { path: '/main', component: () =&gt; import('layouts/default'), children: [ { path: '', component: () =&gt; import('pages/index') }, { path: 'chat', component: () =&gt; import('components/chat')} ] }, { // Always leave this as last one path: '*', component: () =&gt; import('pages/404') } ] </code></pre> <p>Here is my code for my login component:</p> <pre><code>&lt;template&gt; &lt;div&gt; &lt;form id="login" label="Login"&gt; &lt;q-input type="text" float-label="Username" v-model="username" /&gt; &lt;br&gt; &lt;q-input v-model="password" type="password" float-label="Password" /&gt; &lt;q-btn input type="submit" @click="authenticate()"&gt;Submit&lt;/q-btn&gt; &lt;/form&gt; &lt;/div&gt; &lt;/template&gt; &lt;style&gt; input{ margin: 10px; } #login{ vertical-align: middle; text-align: center; } &lt;/style&gt; &lt;script&gt; module.exports = { data() { return { username: '', password: '' } }, methods: { authenticate () { this.$axios.post('/api/login', { Username: this.username, Password: this.password }) .then(response =&gt; { this.$Socket.emit('LoginInfo', { firstname: response.data[0].ClientFirstName, lastname: response.data[0].ClientLastName, name: response.data[0].ClientFirstName + ' ' + response.data[0].ClientLastName, userid: response.data[0].ClientID }) console.log(this.$router) this.$router.push({path: '/main'}) }) .catch(function (error) { console.log(error) }) } } } &lt;/script&gt; </code></pre> <p>I've spent hours trying to search up what might be the problem but so far I've come up with nothing useful. Maybe it might be a bug? My colleague looked over my code and he sees no problem as well. Hopefully you guys can help me out. I would really appreciate it.</p> <p>As requested, the server code:</p> <pre><code>const Express=require('express'); const path=require('path'); var cors = require('cors') var app = Express(); var http = require('http').Server(app); var io = require('socket.io')(http); var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "ChatDB" }); con.connect(function(err) { if (err)throw err; /*let query="INSERT INTO Client(ClientUserName, ClientPassword, ClientFirstName, ClientLastName) VALUES(\"jeffrey\", \"penner\", \"Jeffrey\", \"Penner\")"; con.query(query, function(err, result){ if(err) throw err; })*/ console.log("Connected!"); }); io.set('origins', 'http://localhost:8080'); app.use(Express.json()) //app.use('/public', Express.static(path.join(__dirname, 'public'))); app.use(cors()); app.post('/login', cors(), function(req, res){ let a=req.body.Username; let b=req.body.Password; let query="SELECT ClientID, ClientFirstName, ClientLastName FROM Client WHERE ClientUsername=\'" + a + "\' AND ClientPassword=\'" + b + "\';"; con.query(query, function (err, rows) { if (err){ throw err; } else if(rows.length) { console.log(rows); res.json(rows); } }) }); io.on('connection', function(socket){ console.log('a user connected'); socket.on('disconnect', function(){ console.log('user disconnected'); }); socket.on('LoginInfo', function(data) { console.log(data) }); }) http.listen(100, function(){ console.log('listening on *:100') }); </code></pre> <p>index.js for router code:</p> <pre><code>import Vue from 'vue' import VueRouter from 'vue-router' import routes from './routes' Vue.use(VueRouter) const Router = new VueRouter({ /* * NOTE! Change Vue Router mode from quasar.conf.js -&gt; build -&gt; vueRouterMode * * If you decide to go with "history" mode, please also set "build.publicPath" * to something other than an empty string. * Example: '/' instead of '' */ // Leave as is and change from quasar.conf.js instead! mode: process.env.VUE_ROUTER_MODE, base: process.env.VUE_ROUTER_BASE, scrollBehavior: () =&gt; ({ y: 0 }), routes }) export default Router </code></pre>
0
2,048
SAPUI5 Using XML-File as View with "data-sap-ui-resourceroots"?
<p>I'm doing the SAPUI5 Walkthrough and stuck at step 4. <a href="https://sapui5.hana.ondemand.com/#docs/guide/1409791afe4747319a3b23a1e2fc7064.html" rel="nofollow">(Walkthrough Step 4)</a></p> <p>I'm working with Eclipse and don't know how to change this code-line so it works for my project and is going to find my view.</p> <pre><code> data-sap-ui-resourceroots='{ "sap.ui.demo.wt": "./" }' </code></pre> <p>I need to know what to insert for "sap.ui.demo.wt" when using an Eclipse project.</p> <p>Thanks for any hints :)</p> <p>EDIT:</p> <p>Now I got a working page with a button which triggers a pop-up.</p> <p>Folder structure: </p> <pre><code>SAPUI5_Test - WebContent - controller -&gt; NewView.controller.js - view -&gt; NewView.view.xml - index.html </code></pre> <p>index.html:</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"/&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;SAPUI5 Walkthrough&lt;/title&gt; &lt;script id="sap-ui-bootstrap" src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js" data-sap-ui-theme="sap_bluecrystal" data-sap-ui-libs="sap.m" data-sap-ui-compatVersion="edge" data-sap-ui-preload="async" data-sap-ui-resourceroots='{ "SAPUI5_Test": "./" }'&gt; &lt;/script&gt; &lt;script&gt; sap.ui.getCore().attachInit(function () { sap.ui.xmlview({ viewName: "SAPUI5_Test.view.NewView" }).placeAt("content"); }); &lt;/script&gt; &lt;/head&gt; &lt;body class="sapUiBody" id="content"&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>NewView.view.xml:</p> <pre><code>&lt;mvc:View controllerName="SAPUI5_Test.controller.NewView" xmlns="sap.m" xmlns:mvc="sap.ui.core.mvc"&gt; &lt;Button text="Say hello" press="onShowHello"/&gt; &lt;/mvc:View&gt; </code></pre> <p>NewView.controller.js</p> <pre><code>sap.ui.controller("SAPUI5_Test.controller.NewView", { onShowHello : function() { alert("Hello SAPUI5_Controller"); } }); </code></pre> <p>So thanks for the help! And maybe this could help someone in the future :)</p>
0
1,111
How to refresh data of one component from another component in react js
<p>I'm new to react js and creating one sample application with and some basic CRUD operation.<br> I'm able to display a list, but I don't have any idea if I delete any record then how to refresh data grid.</p> <p>Here is my code:</p> <pre><code>var DeleteRow = React.createClass({ rowDelete: function (e) { console.log(this.props); var isConfirm = confirm("Are you sure want to delete this record?") if (isConfirm) { $.ajax({ type: 'POST', url: 'Students/DeleteStudent', data: { id: this.props.data }, success: function (data) { // refresh the list data }, error: function (error) { } }); } }, render: function () { return( &lt;button data={this.props.id} onClick={this.rowDelete} className="btn btn-danger"&gt;Delete&lt;/button&gt; ); }, }); var SudentList = React.createClass({ render: function () { var RowData = this.props.data.map(function(item){ return ( &lt;tr key={item.id}&gt; &lt;td&gt;{item.id}&lt;/td&gt; &lt;td&gt;{item.firstMidName}&lt;/td&gt; &lt;td&gt;{item.lastName}&lt;/td&gt; &lt;td&gt;{item.enrollmentDate}&lt;/td&gt; &lt;td&gt;Edit&lt;/td&gt; &lt;td&gt;&lt;DeleteRow data={item.id}/&gt;&lt;/td&gt; &lt;/tr&gt; ); }); return ( &lt;table className="table table-bordered table-responsive"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Id&lt;/th&gt; &lt;th&gt;Fist Name&lt;/th&gt; &lt;th&gt;Last Name&lt;/th&gt; &lt;th&gt;Enrollment Date&lt;/th&gt; &lt;th&gt;Edit&lt;/th&gt; &lt;th&gt;Delete&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {RowData} &lt;/tbody&gt; &lt;/table&gt; ); } }); var Gird = React.createClass({ loadStudentsFromServer: function () { $.get(this.props.dataUrl, function (data) { if (this.isMounted()) { this.setState({ items: data }); } }.bind(this)); }, getInitialState: function () { return { items: [] }; }, componentDidMount: function () { this.loadStudentsFromServer(); }, render: function () { var addBtnStyle = { margin:'10px', } return ( &lt;div&gt; &lt;button className="btn btn-primary pull-right" style={addBtnStyle}&gt;Add New&lt;/button&gt; &lt;SudentList data={this.state.items} /&gt; &lt;/div&gt; ); } }); ReactDOM.render( &lt;Gird dataUrl='/Students/GetAllStudent' /&gt;, document.getElementById('content') ); </code></pre> <p>I want to refresh the data of <code>Gird</code> component from <code>DeleteRow</code> component on ajax success, how can I do that?. I've gone through few questions on this site, but not luck so far.</p>
0
1,912
React router not allowing images to load
<p>I am using react-router for the first time and I am having a little problem with my project. React-router is changing the url fine, but then my images are not getting loaded. I believe it is because the base url changes, for example it works when the link it's like this: <code>http://localhost:3000/f0287893b2bcc6566ac48aa6102cd3b1.png</code> but it doesn't when it's like this <code>http://localhost:3000/module/f0287893b2bcc6566ac48aa6102cd3b1.png</code>. Here is my router code:</p> <pre><code>import { Router, Route, browserHistory, IndexRoute } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import { Provider } from 'react-redux' import ReactDOM from 'react-dom' import React from 'react' import App from './containers/App' import configure from './store' import Home from './components/home'; import Module from './components/module-page/module'; import Login from './components/login/login'; const store = configure(); const history = syncHistoryWithStore(browserHistory, store); ReactDOM.render( &lt;Provider store={store}&gt; &lt;Router history={history}&gt; &lt;Route path=&quot;/&quot; component={App}&gt; &lt;IndexRoute component={Login} /&gt; &lt;Router path=&quot;/home&quot; component={Home}/&gt; &lt;Router path=&quot;/module(/:module)&quot; component={Module}/&gt; &lt;/Route&gt; &lt;/Router&gt; &lt;/Provider&gt;, document.getElementById('root') ) </code></pre> <p>this is where the link is triggered:</p> <pre><code> import React, { Component } from 'react'; import { ROUTE_MODULE } from '../../constants/Routes'; import { Link } from 'react-router'; import styles from './side-bar-items.css'; import { Navbar, Nav, NavItem, Collapse } from 'react-bootstrap/lib' import FontAwesome from 'react-fontawesome'; class SideBarItems extends Component { constructor(prop) { super(prop); this.state = { open: false }; } render() { return ( &lt;Navbar.Collapse&gt; &lt;Nav&gt; &lt;NavItem className={styles.navItem} eventKey={1}&gt; &lt;FontAwesome className={styles.navItemIcon} name='globe' size=&quot;lg&quot;/&gt; &lt;span className={styles.navItemIconText}&gt;Dashboard&lt;/span&gt; &lt;/NavItem&gt; &lt;NavItem onClick={this.showModules} className={`${styles.navItem} ${styles.itemModule}`}&gt; &lt;FontAwesome className={styles.navItemIcon} name='clone' size=&quot;lg&quot;/&gt; &lt;span className={styles.navItemIconText}&gt;Modules&lt;/span&gt; &lt;Collapse in={this.state.open}&gt; &lt;div className={styles.collapse}&gt; &lt;div className={styles.module}&gt; &lt;Link to=&quot;/module/moduleCode=2999&quot;&gt;Programming III&lt;/Link&gt; &lt;/div&gt; &lt;/div&gt; &lt;/Collapse&gt; &lt;/NavItem&gt; &lt;/Nav&gt; &lt;/Navbar.Collapse&gt; ) } showModules = () =&gt; { this.setState({ open: !this.state.open }) } } export default (SideBarItems); </code></pre> <p>This is where I import the image:</p> <pre class="lang-js prettyprint-override"><code>import React, { Component } from 'react'; import Image from 'react-bootstrap/lib/Image' import avatar from '../../images/avatar.jpg'; import styles from './user-image.css'; class UserImage extends Component { render() { return ( &lt;div className={styles.userContainer}&gt; &lt;Image className={styles.avatar} src={avatar} rounded /&gt; &lt;span className={styles.userName}&gt;Hello, Daniel&lt;/span&gt; &lt;span className={styles.userCourse}&gt;SEC, Software Engineering&lt;/span&gt; &lt;/div&gt; ) } } export default (UserImage); </code></pre> <p>this is how the website looks when I click on the link</p> <p><a href="https://i.stack.imgur.com/mAIM9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mAIM9.png" alt="image" /></a></p>
0
1,716
Visual Studio 2012 + IIS 8.0 = how to deploy WCF service on localhost?
<p>I have a <code>Wcf Service Application</code> project that is referenced by and used in different projects. Everything works fine when started Visual Studio 2012 - IIS Express is launched, hosted on localhost.</p> <p>I tried to use <code>Publish</code> option in right-click menu of my <code>Wcf Service Application</code>. I created a new profile for publishing:</p> <p><img src="https://i.stack.imgur.com/mgNnH.jpg" alt="Connection settings"> <img src="https://i.stack.imgur.com/Bmcc0.jpg" alt="Settings"></p> <p>Hitting <code>Publish</code> works. I can access it through internet browser through <code>http://localhost</code>. However, when I launch my application normally, through the executable in bin/Debug - it doesn't work (app crashes). What should I do? Can I upload it and configure it easily with IIS Manager (tried it, but get some access errors)? I would need that in my virtual machine which doesn't have any VS installed.</p> <p>What's troubling me is that in my <code>Wcf Service Application</code> project's <code>Web.config</code> file I have base addresses specified like this: <code>http://localhost:8733/WcfServiceLibrary/MailingListService/</code> and in clients <code>App.config</code> I have endpoints with addresses like this: <code>http://localhost/MailingListService.svc</code>. Is it ok to have different ports and addresses (one is in root, the other in <code>WcfServiceLibrary</code>)? It works fine when run in Visual Studio.</p> <p><code>Web.config</code>:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt; &lt;connectionStrings&gt; &lt;add name="NewsletterEntities" connectionString="metadata=res://*/NewsletterDAL_EF.csdl|res://*/NewsletterDAL_EF.ssdl|res://*/NewsletterDAL_EF.msl;provider=System.Data.SqlClient;provider connection string=&amp;quot;Data Source=(local)\SQLEXPRESS;Initial Catalog=Newsletter;Integrated Security=True;Pooling=False;MultipleActiveResultSets=True&amp;quot;" providerName="System.Data.EntityClient"/&gt; &lt;/connectionStrings&gt; &lt;appSettings&gt; &lt;add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /&gt; &lt;/appSettings&gt; &lt;system.web&gt; &lt;compilation debug="true" targetFramework="4.5" /&gt; &lt;httpRuntime targetFramework="4.5"/&gt; &lt;/system.web&gt; &lt;system.serviceModel&gt; &lt;services&gt; &lt;service name="WCFHost.MessageService"&gt; &lt;endpoint address="" binding="basicHttpBinding" contract="WCFHost.IMessageService"&gt; &lt;identity&gt; &lt;dns value="localhost" /&gt; &lt;/identity&gt; &lt;/endpoint&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="http://localhost:8733/WcfServiceLibrary/MessageService/" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;service name="WCFHost.MailingListService"&gt; &lt;endpoint address="" binding="basicHttpBinding" contract="WCFHost.IMailingListService"&gt; &lt;identity&gt; &lt;dns value="localhost" /&gt; &lt;/identity&gt; &lt;/endpoint&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="http://localhost:8733/WcfServiceLibrary/MailingListService/" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;service name="WCFHost.RecipientService"&gt; &lt;endpoint address="" binding="basicHttpBinding" contract="WCFHost.IRecipientService"&gt; &lt;identity&gt; &lt;dns value="localhost" /&gt; &lt;/identity&gt; &lt;/endpoint&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="http://localhost:8733/WcfServiceLibrary/RecipientService/" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;service name="WCFHost.SenderService"&gt; &lt;endpoint address="" binding="basicHttpBinding" contract="WCFHost.ISenderService"&gt; &lt;identity&gt; &lt;dns value="localhost" /&gt; &lt;/identity&gt; &lt;/endpoint&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="http://localhost:8733/WcfServiceLibrary/SenderService/" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;/services&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior&gt; &lt;!-- To avoid disclosing metadata information, set the values below to false before deployment --&gt; &lt;serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/&gt; &lt;!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --&gt; &lt;serviceDebug includeExceptionDetailInFaults="false"/&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;protocolMapping&gt; &lt;add binding="basicHttpsBinding" scheme="https" /&gt; &lt;/protocolMapping&gt; &lt;serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /&gt; &lt;/system.serviceModel&gt; &lt;system.webServer&gt; &lt;modules runAllManagedModulesForAllRequests="true"/&gt; &lt;!-- To browse web app root directory during debugging, set the value below to true. Set to false before deployment to avoid disclosing web app folder information. --&gt; &lt;directoryBrowse enabled="true"/&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p><code>App.config</code>:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;startup&gt; &lt;supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /&gt; &lt;/startup&gt; &lt;system.serviceModel&gt; &lt;bindings&gt; &lt;basicHttpBinding&gt; &lt;binding name="BasicHttpBinding_IMessageService" /&gt; &lt;binding name="BasicHttpBinding_IRecipientService" /&gt; &lt;binding name="BasicHttpBinding_IMailingListService" /&gt; &lt;binding name="BasicHttpBinding_ISenderService" /&gt; &lt;/basicHttpBinding&gt; &lt;/bindings&gt; &lt;client&gt; &lt;endpoint address="http://localhost:2433/MessageService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IMessageService" contract="MessageServiceReference.IMessageService" name="BasicHttpBinding_IMessageService" /&gt; &lt;endpoint address="http://localhost/RecipientService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IRecipientService" contract="RecipientServiceReference.IRecipientService" name="BasicHttpBinding_IRecipientService" /&gt; &lt;endpoint address="http://localhost/MailingListService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IMailingListService" contract="MailingListServiceReference.IMailingListService" name="BasicHttpBinding_IMailingListService" /&gt; &lt;endpoint address="http://localhost/SenderService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ISenderService" contract="SenderServiceReference.ISenderService" name="BasicHttpBinding_ISenderService" /&gt; &lt;/client&gt; &lt;/system.serviceModel&gt; &lt;/configuration&gt; </code></pre>
0
3,323
curl_init undefined?
<p>I am importing the contacts from gmail to my page .....</p> <p>The process does not work due to this error </p> <blockquote> <p><code>'curl_init'</code> is not defined</p> </blockquote> <p>The suggestion i got is to </p> <ol> <li>uncomment destination curl.dll </li> <li>copy the following libraries to the windows/system32 dir: <code>ssleay32.dll</code> and <code>libeay32.dll</code></li> <li>copy php_curl.dll to windows/system32</li> </ol> <p>After trying all these, I refreshed my xampp, but even then error occurs.</p> <p>This is my page where I am trying to import the gmail contacts:</p> <pre><code>&lt;?php resource curl_init ([ string $url = NULL ] ) $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); ?&gt; &lt;?php echo "hi"; if($_POST['submit'] != '') { echo "hi"; $clientlogin_url = "https://www.google.com/accounts/ClientLogin"; $clientlogin_post = array( "accountType" =&gt; "HOSTED_OR_GOOGLE", "Email" =&gt; $_POST['Email'], echo "Passwd" =&gt; $_POST['Passwd'], "service" =&gt; "cp", "source" =&gt; "tutsmore/1.2" ); $curl = curl_init($clientlogin_url); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $clientlogin_post); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($curl); preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches); $auth = $matches[1]; $headers = array("Authorization: GoogleLogin auth=" . $auth); $curl = curl_init('http://www.google.com/m8/feeds/contacts/default/full?max-results=10000'); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $feed = curl_exec($curl); echo "contacts".$contacts=array(); $doc=new DOMDocument(); if (!empty($feed)) $doc-&gt;loadHTML($feed); $xpath=new DOMXPath($doc); $query="//entry"; $data=$xpath-&gt;query($query); foreach ($data as $node) { $entry_nodes=$node-&gt;childNodes; $tempArray=array(); foreach($entry_nodes as $child) { $domNodesName=$child-&gt;nodeName; switch($domNodesName) { case 'title' : { $tempArray['fullName']=$child-&gt;nodeValue; } break ; case 'email' : { if (strpos($child-&gt;getAttribute('rel'),'home')!==false) $tempArray['email_1']=$child-&gt;getAttribute('address'); elseif(strpos($child-&gt;getAttribute('rel'),'work')!=false) $tempArray['email_2']=$child-&gt;getAttribute('address'); elseif(strpos($child-&gt;getAttribute('rel'),'other')!==false) $tempArray['email_3']=$child-&gt;getAttribute('address'); } break ; } } if (!empty($tempArray['email_1']))$contacts[$tempArray['email_1']]=$tempArray; if(!empty($tempArray['email_2'])) $contacts[$tempArray['email_2']]=$tempArray; if(!empty($tempArray['email_3'])) $contacts[$tempArray['email_3']]=$tempArray; } foreach($contacts as $key=&gt;$val) { echo $key."&lt;br/&gt;"; } } else { ?&gt; &lt;form action="&lt;?=$PHP_SELF?&gt;" method="POST"&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;Email:&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="Email" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Password:&lt;/td&gt;&lt;td&gt;&lt;input type="password" name="Passwd" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt;&lt;td colspan="2" align="center"&gt;tutsmore don't save your email and password trust us.&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td colspan="2" align="center"&gt;&lt;input type="submit" name="submit" value="Get Contacts" /&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;?php } ?&gt; </code></pre> <p>This code is completely provided for debugging; if any optimization is needed, I will try to optimize the code.</p>
0
2,128
DispatchKeyEvent to listen for Spacebar being pressed
<p>I am working on an Android project and I need to check when the spacebar is pressed sos I can execute a certain function.</p> <p>The problem is, it was working on the emulator but not on my actual device. I think it might be because my emulator was using a physical keyboard, not the onscreen virtual keyboard but when testing on an actual device, its using a virtual keyboard.</p> <p>I'm trying the dispatch keyevent</p> <pre><code>@Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_SPACE &amp;&amp; event.getAction() == KeyEvent.ACTION_UP) { QueryEditor queryEditor = (QueryEditor)getSupportFragmentManager().findFragmentById(R.id.fragment_queryEditor); queryEditor.formatQueryText(); return true; } } </code></pre> <p>I've also tried the on key down</p> <pre><code>@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { disconnectDatabase(); } else if (keyCode == KeyEvent.KEYCODE_DEL) { QueryEditor queryEditor = (QueryEditor)getSupportFragmentManager().findFragmentById(R.id.fragment_queryEditor); queryEditor.formatQueryText(); } return super.onKeyDown(keyCode, event); } </code></pre> <p>Neither of these get fired though unless the back button is pressed but I need the spacebar to trigger the event.</p> <h2>Update</h2> <p>Below is my code for how QueryEditor Fragment is created and the event handler is created</p> <pre><code>@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); iQueryEditor = (IQueryEditor)this; iErrorHandler = (IErrorHandler)this; txtQueryEditor = (EditText)getActivity().findViewById(R.id.query_txtQueryEditor); btnSubmitQuery = (ImageButton)getActivity().findViewById(R.id.query_btnPerformQuery); btnClearQuery = (ImageButton)getActivity().findViewById(R.id.query_btnDeleteQuery); txtQueryEditor.addTextChangedListener(new QueryTextChanged(getActivity(), txtQueryEditor, iQueryEditor)); setDatabaseUsed(); txtQueryEditor.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if ((event != null &amp;&amp; (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || actionId == EditorInfo.IME_ACTION_DONE) { executeQuery(); return true; } else if (event.getKeyCode() == KeyEvent.KEYCODE_SPACE &amp;&amp; event.getAction() == KeyEvent.ACTION_UP) { Toast.makeText(getActivity(), &quot;Space Bar Pressed&quot;, Toast.LENGTH_SHORT).show(); return true; } return false; } }); btnSubmitQuery.setOnClickListener(mBtnSubmitQueryListener); btnClearQuery.setOnClickListener(mBtnDeleteQueryListener); } </code></pre> <p>txtQueryEditor is the EditText that I am trying to receive the space bar event on.</p>
0
1,446
How to get same session with Spring Security and Spring Session From multiple server
<p>I'm sorry that my english is still not so good. Please bear with me, I hope you can understand my question..</p> <hr> <p>I have two web servers. (each web application is same)</p> <p>Web servers are sharing one redis server. And I use Spring Security and Spring Session. When I login first server and access second server, I want to login second server automatically, but it isn't.</p> <p>I guess, because session id is different from different server ip.</p> <ul> <li>how to get same session id ?</li> </ul> <h2>WEB.XML</h2> <pre><code>&lt;!-- The definition of the Root Spring Container shared by all Servlets and Filters --&gt; &lt;!-- Loads Spring Security config file --&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt; /WEB-INF/spring/root-context.xml, /WEB-INF/spring/spring-security.xml, /WEB-INF/spring/jedis.xml &lt;/param-value&gt; &lt;/context-param&gt; &lt;!-- Creates the Spring Container shared by all Servlets and Filters --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- Processes application requests --&gt; &lt;servlet&gt; &lt;servlet-name&gt;appServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/spring/appServlet/servlet-context.xml&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;appServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;!-- Encoding --&gt; &lt;filter&gt; &lt;filter-name&gt;CharacterEncodingFilter&lt;/filter-name&gt; &lt;filter-class&gt;org.springframework.web.filter.CharacterEncodingFilter&lt;/filter-class&gt; &lt;init-param&gt; &lt;param-name&gt;encoding&lt;/param-name&gt; &lt;param-value&gt;utf-8&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;forceEncoding&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;CharacterEncodingFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;!-- Session Filter --&gt; &lt;filter&gt; &lt;filter-name&gt;springSessionRepositoryFilter&lt;/filter-name&gt; &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;springSessionRepositoryFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;!-- Spring Security --&gt; &lt;filter&gt; &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt; &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; </code></pre> <h2>jedis.xml</h2> <pre><code>&lt;bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"&gt; &lt;property name="hostName" value=""&lt;!-- My Server IP --&gt; /&gt; &lt;property name="port" value="6379" /&gt; &lt;property name="poolConfig" ref="redisPoolConfig" /&gt; &lt;/bean&gt; &lt;bean id="redisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"&gt; &lt;property name="testOnBorrow" value="true" /&gt; &lt;property name="minEvictableIdleTimeMillis" value="60000" /&gt; &lt;property name="softMinEvictableIdleTimeMillis" value="1800000" /&gt; &lt;property name="numTestsPerEvictionRun" value="-1" /&gt; &lt;property name="testOnReturn" value="false" /&gt; &lt;property name="testWhileIdle" value="true" /&gt; &lt;property name="timeBetweenEvictionRunsMillis" value="30000" /&gt; &lt;/bean&gt; &lt;!-- string serializer to make redis key more readible --&gt; &lt;bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" /&gt; &lt;!-- redis template definition --&gt; &lt;bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" &gt; &lt;property name="connectionFactory" ref="jedisConnectionFactory" /&gt; &lt;property name="keySerializer" ref="stringRedisSerializer" /&gt; &lt;property name="hashKeySerializer" ref="stringRedisSerializer" /&gt; &lt;/bean&gt; </code></pre> <h2>spring-security.xml</h2> <pre><code>&lt;http pattern="/resources/**" security="none" /&gt; &lt;http auto-config="true" &gt; &lt;session-management session-fixation-protection="changeSessionId"&gt; &lt;concurrency-control max-sessions="1" error-if-maximum-exceeded="true"/&gt; &lt;!-- I couldn't clear understand of this element--&gt; &lt;/session-management&gt; &lt;intercept-url pattern="/" access="ROLE_ANONYMOUS, ROLE_USER" /&gt; &lt;intercept-url pattern="/perBoard" access="ROLE_ANONYMOUS, ROLE_USER" /&gt; &lt;intercept-url pattern="/per" access="ROLE_ANONYMOUS, ROLE_USER" /&gt; &lt;intercept-url pattern="/perSearchTag" access="ROLE_ANONYMOUS, ROLE_USER" /&gt; &lt;intercept-url pattern="/**" access="ROLE_USER" /&gt; &lt;form-login login-page="/" authentication-success-handler-ref="loginSuccessHandler" authentication-failure-handler-ref="loginFailureHandler" always-use-default-target="true" username-parameter="j_username" password-parameter="j_password"/&gt; &lt;!-- default-target-url="/board" --&gt; &lt;logout logout-success-url="/" invalidate-session="true" delete-cookies="true" /&gt; &lt;/http&gt; &lt;authentication-manager&gt; &lt;authentication-provider user-service-ref="userDetailsService" /&gt; &lt;/authentication-manager&gt; &lt;beans:bean id="loginSuccessHandler" class=".......LoginSuccessHandler"&gt; &lt;beans:property name="sqlSession" ref="sqlSession" /&gt; &lt;/beans:bean&gt; &lt;beans:bean id="loginFailureHandler" class=".......LoginFailureHandler" /&gt; &lt;beans:bean id="userDetailsService" class="......UserDetailsServiceImpl"&gt; &lt;beans:property name="sqlSession" ref="sqlSession" /&gt; &lt;/beans:bean&gt; </code></pre>
0
2,765
Current user in owin authentication
<p>I started to build a web api for mobile apps and I'm having a hard time with implementing authentication. I use Bearer and although everything is supposed to be fine, I cannot get the current user from action in controller. HttpContext.Current.User.Identity.Name is null (the same is result of HttpContext.Current.User.Identity.GetUserId()). Here are the pieces of important code: </p> <p>Startup.cs:</p> <pre><code> public partial class Startup { public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); ConfigureAuth(app); WebApiConfig.Register(config); app.UseWebApi(config); } } </code></pre> <p>Startup.Auth.cs</p> <pre><code>public partial class Startup { static Startup() { OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/token"), Provider = new ApplicationOAuthProvider(), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), AllowInsecureHttp = true }; OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); } public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; } public static string PublicClientId { get; private set; } public void ConfigureAuth(IAppBuilder app) { app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { AccessTokenProvider = new AuthenticationTokenProvider() }); app.UseOAuthBearerTokens(OAuthOptions); app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); } } </code></pre> <p>ApplicationOAuthProvider.cs:</p> <pre><code> public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { string clientId, clientSecret; if (!context.TryGetBasicCredentials(out clientId, out clientSecret)) { return SetErrorAndReturn(context, "client error", ""); } if (clientId == "secret" &amp;&amp; clientSecret == "secret") { context.Validated(); return Task.FromResult&lt;object&gt;(null); } return SetErrorAndReturn(context, "client error", ""); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); using (AuthRepository _repo = new AuthRepository()) { IdentityUser user = await _repo.FindUser(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("sub", context.UserName)); identity.AddClaim(new Claim("role", "user")); context.Validated(identity); } public override Task TokenEndpoint(OAuthTokenEndpointContext context) { foreach (KeyValuePair&lt;string, string&gt; property in context.Properties.Dictionary) { context.AdditionalResponseParameters.Add(property.Key, property.Value); } return Task.FromResult&lt;object&gt;(null); } </code></pre> <p>AuthRepository.cs:</p> <pre><code>public class AuthRepository : IDisposable { private readonly AuthContext _ctx; private readonly UserManager&lt;IdentityUser&gt; _userManager; public AuthRepository() { _ctx = new AuthContext(); _userManager = new UserManager&lt;IdentityUser&gt;(new UserStore&lt;IdentityUser&gt;(_ctx)); } public async Task&lt;IdentityResult&gt; RegisterUser(UserModel userModel) { var user = new IdentityUser { UserName = userModel.UserName }; var result = await _userManager.CreateAsync(user, userModel.Password); return result; } public async Task&lt;IdentityUser&gt; FindUser(string userName, string password) { IdentityUser user = await _userManager.FindAsync(userName, password); return user; } public void Dispose() { _ctx.Dispose(); _userManager.Dispose(); } } </code></pre> <p>AuthContext.cs:</p> <pre><code>public class AuthContext : IdentityDbContext&lt;IdentityUser&gt; { public AuthContext() : base("AuthContext") { } } </code></pre> <p>And finnaly ValuesController.cs:</p> <pre><code>[Authorize] public class ValuesController : ApiController { public IEnumerable&lt;string&gt; Get() { return new String[] {HttpContext.Current.User.Identity.Name, HttpContext.Current.User.Identity.GetUserId(),ClaimsPrincipal.Current.Identity.Name}; } } </code></pre> <p>When i go to this action, i get null 3 times. Despite that, the whole authentication proccess seems to be fine - only when i send a good token, i have access. Does anybody have an idea what is wrong here? </p>
0
2,420
"End of Central Directory record could not be found" - NuGet in VS community 2015
<p>I am getting an error when i try to install any package from the NuGet in VS community edition 2015.</p> <pre><code>Attempting to gather dependencies information for package 'Microsoft.Net.Http.2.2.29' with respect to project 'ClassLibrary1', targeting '.NETFramework,Version=v4.5.2' Attempting to resolve dependencies for package 'Microsoft.Net.Http.2.2.29' with DependencyBehavior 'Lowest' Resolving actions to install package 'Microsoft.Net.Http.2.2.29' Resolved actions to install package 'Microsoft.Net.Http.2.2.29' Install failed. Rolling back... Package 'Microsoft.Bcl.Build 1.0.14' does not exist in project 'ClassLibrary1' Package 'Microsoft.Bcl.Build 1.0.14' does not exist in folder 'C:\Users\441793\documents\visual studio 2015\Projects\ClassLibrary1\packages' System.IO.InvalidDataException: End of Central Directory record could not be found. at System.IO.Compression.ZipArchive.ReadEndOfCentralDirectory() at System.IO.Compression.ZipArchive.Init(Stream stream, ZipArchiveMode mode, Boolean leaveOpen) at System.IO.Compression.ZipArchive..ctor(Stream stream, ZipArchiveMode mode, Boolean leaveOpen, Encoding entryNameEncoding) at System.IO.Compression.ZipArchive..ctor(Stream stream, ZipArchiveMode mode) at NuGet.Packaging.NuGetPackageUtils.ExtractPackage(String targetPath, FileStream stream) at NuGet.Packaging.NuGetPackageUtils.&lt;&gt;c__DisplayClass1_0.&lt;&lt;InstallFromStreamAsync&gt;b__0&gt;d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at NuGet.Common.ConcurrencyUtilities.&lt;ExecuteWithFileLocked&gt;d__0`1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at NuGet.Common.ConcurrencyUtilities.&lt;ExecuteWithFileLocked&gt;d__0`1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at NuGet.Packaging.NuGetPackageUtils.&lt;InstallFromStreamAsync&gt;d__1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at NuGet.Protocol.Core.v3.GlobalPackagesFolderUtility.&lt;AddPackageAsync&gt;d__1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at NuGet.Protocol.Core.v3.DownloadResourceV3.&lt;GetDownloadResourceResultAsync&gt;d__4.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at NuGet.PackageManagement.PackageDownloader.&lt;GetDownloadResourceResultAsync&gt;d__1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) at NuGet.PackageManagement.NuGetPackageManager.&lt;ExecuteNuGetProjectActionsAsync&gt;d__42.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at NuGet.PackageManagement.NuGetPackageManager.&lt;ExecuteNuGetProjectActionsAsync&gt;d__42.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at NuGet.PackageManagement.UI.UIActionEngine.&lt;ExecuteActionsAsync&gt;d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at NuGet.PackageManagement.UI.UIActionEngine.&lt;PerformActionAsync&gt;d__3.MoveNext() ========== Finished ========== </code></pre> <p>Error message i receive is in the Error List tab is</p> <pre><code>End of Central Directory record could not be found </code></pre> <p>I tried from Console application to Class libraries and getting this error for all packages i tried to install.</p> <p>NuGet Version is : 3.0.60624.657</p> <p>Any help will be appreciated</p>
0
1,650
Passing object in ngModel to a custom control Angular2
<p>I want to create custom control which contains other custom controls and use ngModel that connects all of them. Like : </p> <p>PersonSearchComponent :</p> <ul> <li>DeveloperSearchControl <ul> <li>Name - some string input</li> <li>Surname </li> <li>ProffesionSelect - custom control expecting ProffesionModel</li> </ul></li> <li>BuildingSearchControl <ul> <li>Some custom controls here</li> </ul></li> <li>CountryCustomControl - custom control expecting CountryModel</li> </ul> <hr> <ul> <li>PersonListComponent : -imported data about items from PersonSearchComponent by some service</li> </ul> <hr> <ul> <li>SomeOtherSearchComponent <ul> <li>DeveloperSearchControl - reusable</li> </ul></li> </ul> <p>So for now I have working version, but I think i have made something bad (maybe I should use FormBuilder):</p> <p>PersonSearch Template :</p> <pre><code> &lt;div&gt; &lt;developer-search-control [(ngModel)]="searchModel.developerSearchModel"&gt;&lt;/developer-search-control&gt; &lt;building-search-control [(ngModel)]="searchModel.buildingSearchModel"&gt;&lt;/building-search-control&gt; &lt;country-select [(ngModel)]="searchModel.countryModel"&gt;&lt;country-select&gt; &lt;/div&gt; </code></pre> <p></p> <p>ParentSearch component</p> <pre><code>... export class PersonSearch { @Output() searchDataEmitter= new EventEmitter();//Exports data to above component which contains this, and listComponent searchModel : PersonSearchModel : new PersonSearchModel(); performSearch() { //gets data from service with searchModel and searchDataEmitter transpors it to above component } } </code></pre> <p>Models : PersonSearchModel :</p> <pre><code>developerSearchModel : DeveloperSearchModel = new DeveloperSearchModel(); buildingSearchModel: BuildingSearchModel = new BuildingSearchModel(); countryModel : CountryModel; </code></pre> <p>DeveloperSearchModel :</p> <pre><code>name : string surname : string proffesion : ProfessionModel </code></pre> <p>Template developerSearchControl.component.html:</p> <pre><code>&lt;div *ngIf="value"&gt;//This is the problem &lt;input [(ngModel)]="value.name"&gt;&lt;/input&gt; &lt;input [(ngModel)]="value.surname"&gt;&lt;/input&gt; &lt;profesion-select [(ngModel)]="value.ProffesionSelect"&gt; &lt;/div&gt; </code></pre> <p>developerSearchControl.component:</p> <pre><code>... @Component({ selector: 'developer-search-control', templateUrl: './developerSearchControl.component.html', providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() =&gt; DeveloperSearchControlComponent), multi: true, }], }) export class DeveloperSearchControlComponent extends ElementBase&lt;DeveloperSearchModel &gt; { protected model: NgModel; constructor( @Optional() @Inject(NG_VALIDATORS) validators: Array&lt;any&gt;, @Optional() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: Array&lt;any&gt;, ) { super(validators, asyncValidators); } } </code></pre> <p>profesionSelect.component</p> <pre><code> ... @Component({ selector: 'profesion-select', template: ` &lt;div&gt; &lt;label *ngIf="label"&gt;{{label}}&lt;/label&gt; &lt;dx-select-box [dataSource]="data" [(ngModel)]="value" displayExpr="proffesionName" [placeholder]="placeholder" [searchEnabled]="true" &gt; &lt;/dx-select-box&gt; &lt;/div&gt;`, providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: ProfessionComponent, multi: true, }], }) export class ProfessionComponent extends ElementBase&lt;string&gt; implements OnInit { private data: ProfessionModel[]; private label: string = 'proffesion :'; private placeholder: string = 'Select profession'; @ViewChild(NgModel) model: NgModel; constructor(private proffesionService: ProfessionDataService, @Optional() @Inject(NG_VALIDATORS) validators: Array&lt;any&gt;, @Optional() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: Array&lt;any&gt;, ) { super(validators, asyncValidators); } ngOnInit() { this.professionService.getDevelopersProfessions().subscribe( data =&gt; { this.data = data; } ); } } </code></pre> <p>ElementBase is a generic ControlValueAccessor with validation from : <a href="http://blog.rangle.io/angular-2-ngmodel-and-custom-form-components/" rel="noreferrer">http://blog.rangle.io/angular-2-ngmodel-and-custom-form-components/</a></p> <p>So my problem is that when I create the template for children (developerSearch, buildingSearch) the value passed with ngModel is not initialized for them and i get :</p> <pre><code>EXCEPTION: Uncaught (in promise): Error: Error in ./DeveloperSearchControlComponent class DeveloperSearchControlComponent - inline template:2:33 caused by: Cannot read property 'name' of null Error: Error in ./DeveloperSearchControlComponent class DeveloperSearchControlComponent - inline template:2:33 caused by: Cannot read property 'name' of null </code></pre> <p>Because the value from ngModel is null at start. So I have to use *ngFor="value" in templates of child components which looks bad. Is there any solution to initialize the object before template verification? or Im doing this very wrong?</p>
0
1,988
WPF DataBound treeview expand / collapse
<p>I'm just trying to find a way to control the expand / collapse of the <code>TreeView</code> nodes through the object they're bound to. The object has an <code>IsExpanded</code> property, and I want to use that to show the <code>TreeView</code> node itself expanded or collapsed based on that property.</p> <p>Here's my code:</p> <p>C#:</p> <pre><code>public partial class Window2 : Window { public Window2() { InitializeComponent(); this.DataContext = new List&lt;Parent&gt;() { Base.GetParent("Parent 1"), Base.GetParent("Parent 2") }; } } public class Base { public string Name { get; set; } public bool IsExpanded { get; set; } public static Parent GetParent(string name) { Parent p = new Parent() { Name = name }; p.Children.Add(new Child() { Name = "Child 1", GrandChildren = new ObservableCollection&lt;GrandChild&gt;() { new GrandChild() { Name = "Grandchild 1" } } }); p.Children.Add(new Child() { Name = "Child 2", GrandChildren = new ObservableCollection&lt;GrandChild&gt;() { new GrandChild() { Name = "Grandchild 1" } } }); p.Children.Add(new Child() { Name = "Child 3", GrandChildren = new ObservableCollection&lt;GrandChild&gt;() { new GrandChild() { Name = "Grandchild 1" } } }); return p; } } public class Parent : Base { public ObservableCollection&lt;Child&gt; Children { get; set; } public Parent() { this.Children = new ObservableCollection&lt;Child&gt;(); } } public class Child : Base { public ObservableCollection&lt;GrandChild&gt; GrandChildren { get; set; } public Child() { this.GrandChildren = new ObservableCollection&lt;GrandChild&gt;(); } } public class GrandChild : Base { } </code></pre> <p>XAML:</p> <pre><code>&lt;Window x:Class="HeterogeneousExperimentExplorer.Window2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:HeterogeneousTree" Title="Window2" Height="300" Width="300"&gt; &lt;Window.Resources&gt; &lt;HierarchicalDataTemplate DataType="{x:Type local:Parent}" ItemsSource="{Binding Children}"&gt; &lt;TextBlock Text="{Binding Name}" /&gt; &lt;HierarchicalDataTemplate.ItemTemplate&gt; &lt;HierarchicalDataTemplate DataType="{x:Type local:Parent}" ItemsSource="{Binding GrandChildren}"&gt; &lt;TextBlock Text="{Binding Name}" /&gt; &lt;HierarchicalDataTemplate.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;TextBlock Text="{Binding Name}" /&gt; &lt;/DataTemplate&gt; &lt;/HierarchicalDataTemplate.ItemTemplate&gt; &lt;/HierarchicalDataTemplate&gt; &lt;/HierarchicalDataTemplate.ItemTemplate&gt; &lt;/HierarchicalDataTemplate&gt; &lt;/Window.Resources&gt; &lt;Grid&gt; &lt;TreeView ItemsSource="{Binding}" /&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre>
0
1,292
AndroidManifest.xml The markup in the document following the root element must be well formed
<p>I have got Eclipse to generate a Basic android Hello World app, But it has 2 errors: first, in my AndroidManifest.xml on these two lines:<br> I get The markup in the document following the root element must be well formed, Also My R.java Will not generate, no matter how many times I clean my project. Any Answers?</p> <p>the manifest is here: <a href="http://jsfiddle.net/NHDU6/" rel="nofollow">http://jsfiddle.net/NHDU6/</a></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.jfkingsley.maclogin" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="14" android:targetSdkVersion="15" /&gt; &lt;application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;activity android:name=".MainActivity" android:label="@string/title_activity_main" &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; &lt;/application&gt; &lt;/manifest&gt; &lt;!-- Declare the contents of this Android application. The namespace attribute brings in the Android platform namespace, and the package supplies a unique name for the application. When writing your own application, the package name must be changed from "com.example.*" to come from a domain that you own or have control over. --&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.jfkingsley.maclogin" &gt; &lt;uses-permission android:name="android.permission.CALL_PHONE" /&gt; &lt;uses-permission android:name="android.permission.GET_TASKS" /&gt; &lt;uses-permission android:name="android.permission.READ_CONTACTS" /&gt; &lt;uses-permission android:name="android.permission.SET_WALLPAPER" /&gt; &lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.EXPAND_STATUS_BAR" /&gt; &lt;application android:icon="@drawable/ic_launcher_home" android:label="@string/home_title" &gt; &lt;activity android:name="Home" android:launchMode="singleInstance" android:stateNotNeeded="true" android:theme="@style/Theme" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&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; &lt;activity android:name="Wallpaper" android:icon="@drawable/bg_android_icon" android:label="Wallpaper" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.SET_WALLPAPER" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>Thanks, Jonathan</p>
0
1,489
One-to-one relationship in EF Core (The child/dependent side could not be determined for the one-to-one relationship)
<p>I've been getting the following error message and I can't seem to grasp the reason why have I been getting it. Interestingly when adding migrations I didn't get any errors, but whenever I want to use the context I do get it.</p> <blockquote> <p>The child/dependent side could not be determined for the one-to-one relationship between 'Block.JobBlock' and 'JobBlock.Block'. To identify the child/dependent side of the relationship, configure the foreign key property. If these navigations should not be part of the same relationship configure them without specifying the inverse.</p> </blockquote> <p>A <code>Job</code> can have multiple <code>JobBlocks</code> (one-to-many); single <code>Block</code> can have only one <code>JobBlock</code> (one-to-one). So basically, a <code>JobBlock</code> is a reference table/entity used to reference <code>Job</code> and its <code>Blocks</code>. It is important to mention that a primary key in the <code>JobBlock</code> entity consists of two keys thus making it a compound primary key.</p> <p>One might argue that a <code>Block</code> entity should already contain an <code>IdJob</code> property and that the <code>JobBlock</code> entity could be entirely dismissed, but there is some reasoning why it shouldn't be done this way so let's leave it as it is :) </p> <p><strong>Models:</strong></p> <pre><code>public class Job : IEntity { public Job() { JobBlocks = new HashSet&lt;JobBlock&gt;(); } public Guid Id { get; set; } = Guid.NewGuid(); public ICollection&lt;JobBlock&gt; JobBlocks { get; set; } } public class Block : IEntity { public Guid Id { get; set; } = Guid.NewGuid(); public JobBlock JobBlock { get; set; } } public class JobBlock : IEntity { public Guid IdJob { get; set; } public Job Job { get; set; } public Guid IdBlock { get; set; } public Block Block { get; set; } } </code></pre> <p><strong>EF Configurations:</strong></p> <pre><code>public class JobConfiguration : IEntityTypeConfiguration&lt;Job&gt; { public void Configure(EntityTypeBuilder&lt;Job&gt; builder) { builder.HasKey(p =&gt; p.Id); builder.Property(p =&gt; p.Id) .IsRequired() .ValueGeneratedNever(); builder.HasMany(e =&gt; e.JobBlocks) .WithOne(e =&gt; e.Job) .HasForeignKey(p =&gt; p.IdJob); } } public class BlockConfiguration : IEntityTypeConfiguration&lt;Block&gt; { public void Configure(EntityTypeBuilder&lt;Block&gt; builder) { builder.HasKey(p =&gt; p.Id); builder.Property(p =&gt; p.Id).IsRequired().ValueGeneratedNever(); builder.HasOne(e =&gt; e.JobBlock) .WithOne(e =&gt; e.Block) .HasForeignKey&lt;JobBlock&gt;(p =&gt; new { p.IdJob, p.IdBlock }); } } public class JobBlockConfiguration : IEntityTypeConfiguration&lt;JobBlock&gt; { public void Configure(EntityTypeBuilder&lt;JobBlock&gt; builder) { builder.HasKey(p =&gt; new { p.IdJob, p.IdBlock }); builder.Property(p =&gt; p.IdJob).IsRequired(); builder.Property(p =&gt; p.IdBlock).IsRequired(); builder.HasOne(e =&gt; e.Job) .WithMany(e =&gt; e.JobBlocks) .HasForeignKey(p =&gt; p.IdJob); builder.HasOne(e =&gt; e.Block) .WithOne(e =&gt; e.JobBlock) .HasForeignKey&lt;JobBlock&gt;(p =&gt; new { p.IdJob, p.IdBlock }); } } </code></pre>
0
1,315
java.lang.IllegalArgumentException: Can not set int field it.besmart.models.Park.idPark to [Ljava.lang.Object;
<p>i'm dwelling with this problem. I have 3 classes</p> <p>User and Park have a ManyToMany relation, and Piano and Park have a ManyToOne relation.</p> <p>In the models, the interesting parts are User.java</p> <pre><code>@ManyToMany(fetch = FetchType.EAGER) @JoinTable(name="users_parcheggio", joinColumns = {@JoinColumn(name="user_id") }, inverseJoinColumns = { @JoinColumn(name="park_id") }) private Set&lt;Park&gt; parks = new HashSet&lt;Park&gt;(); </code></pre> <p>This is Park.java</p> <pre><code> @Entity @Table(name="parcheggio", catalog="SMARTPARK") public class Park implements Serializable{ /** * */ private static final long serialVersionUID = -7630704706109692038L; @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id_park", unique = true, nullable = false) private int idPark; @NotEmpty @Column(name="nome_park") private String nomePark; @Column(name="descrizione") private String descrizione; @Column(name="indirizzo") private String indirizzo; @Column(name="citta") private String citta; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name="users_parcheggio", joinColumns = {@JoinColumn(name="park_id") }, inverseJoinColumns = { @JoinColumn(name="user_id") }) private Set&lt;User&gt; users = new HashSet&lt;User&gt;(); @OneToMany(fetch = FetchType.LAZY, cascade=CascadeType.ALL, mappedBy = "park") private List&lt;Piano&gt; piano; public Park(){ } public Park(int idPark, String nomePark, String descrizione, String indirizzo, String citta, Set&lt;User&gt; users, List&lt;Piano&gt; piano){ this.idPark = idPark; this.nomePark = nomePark; this.descrizione = descrizione; this.indirizzo = indirizzo; this.citta = citta; this.users = users; this.piano = piano; } public List&lt;Piano&gt; getPiano() { return piano; } public void setPiano(List&lt;Piano&gt; piano) { this.piano = piano; } public int getIdPark() { return idPark; } public void setIdPark(int idPark) { this.idPark = idPark; } public String getNomePark() { return nomePark; } public void setNomePark(String nomePark) { this.nomePark = nomePark; } public String getDescrizione() { return descrizione; } public void setDescrizione(String descrizione) { this.descrizione = descrizione; } public String getIndirizzo() { return indirizzo; } public void setIndirizzo(String indirizzo) { this.indirizzo = indirizzo; } public String getCitta() { return citta; } public void setCitta(String citta) { this.citta = citta; } public Set&lt;User&gt; getUsers() { return users; } public void setUsers(Set&lt;User&gt; users) { this.users = users; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + idPark; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Park other = (Park) obj; if (idPark != other.idPark) return false; return true; } } </code></pre> <p>and in Piano.java</p> <pre><code>@ManyToOne @JoinColumn(name = "id_park") public Park getPark() { return park; } public void setPark(Park park) { this.park = park; } </code></pre> <p>When I use this 3 classes in couples (User with Park or Park with Piano) everything goes well, but now I have to get all Piano for a given User.</p> <p>In my PianoDaoImpl I have this method</p> <pre><code>public List&lt;Piano&gt; findPianoByUser() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String name = auth.getName(); User user = userService.findBySso(name); int userId = user.getId(); Query q = getSession().createQuery("from Park p join p.users u where u.id = :userId").setParameter("userId", userId); List&lt;Park&gt; parks = q.list(); Query query = getSession().createQuery("from Piano p where p.park in :parks").setParameterList("parks", parks); List piani = query.list(); return piani; } </code></pre> <p>The <em>q</em> query gives me correctly the parks list for the user. Then I pass this list to the second query and I got this exception</p> <pre><code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.PropertyAccessException: could not get a field value by reflection getter of it.besmart.models.Park.idPark </code></pre> <p>caused by</p> <pre><code>java.lang.IllegalArgumentException: Can not set int field it.besmart.models.Park.idPark to [Ljava.lang.Object; </code></pre> <p>What i'm doing wrong?</p>
0
2,157
PyInstaller-built Windows EXE fails with multiprocessing
<p>In my project I'm using Python's <code>multiprocessing</code> library to create multiple processes in __main__. The project is being packaged into a single Windows EXE using PyInstaller 2.1.1.</p> <p>I create new processes like so:</p> <pre><code>from multiprocessing import Process from Queue import Empty def _start(): while True: try: command = queue.get_nowait() # ... and some more code to actually interpret commands except Empty: time.sleep(0.015) def start(): process = Process(target=_start, args=args) process.start() return process </code></pre> <p>And in __main__:</p> <pre><code>if __name__ == '__main__': freeze_support() start() </code></pre> <p>Unfortunately, when packaging the application into an EXE and launching it, I get <code>WindowsError</code> 5 or 6 (seems random) at this line:</p> <pre><code>command = queue.get_nowait() </code></pre> <p>A recipe at PyInstaller's homepage claims that I have to modify my code to enable multiprocessing in Windows when packaging the application as a single file.</p> <p>I'm reproducing the code here:</p> <pre><code>import multiprocessing.forking import os import sys class _Popen(multiprocessing.forking.Popen): def __init__(self, *args, **kw): if hasattr(sys, 'frozen'): # We have to set original _MEIPASS2 value from sys._MEIPASS # to get --onefile mode working. # Last character is stripped in C-loader. We have to add # '/' or '\\' at the end. os.putenv('_MEIPASS2', sys._MEIPASS + os.sep) try: super(_Popen, self).__init__(*args, **kw) finally: if hasattr(sys, 'frozen'): # On some platforms (e.g. AIX) 'os.unsetenv()' is not # available. In those cases we cannot delete the variable # but only set it to the empty string. The bootloader # can handle this case. if hasattr(os, 'unsetenv'): os.unsetenv('_MEIPASS2') else: os.putenv('_MEIPASS2', '') class Process(multiprocessing.Process): _Popen = _Popen class SendeventProcess(Process): def __init__(self, resultQueue): self.resultQueue = resultQueue multiprocessing.Process.__init__(self) self.start() def run(self): print 'SendeventProcess' self.resultQueue.put((1, 2)) print 'SendeventProcess' if __name__ == '__main__': # On Windows calling this function is necessary. if sys.platform.startswith('win'): multiprocessing.freeze_support() print 'main' resultQueue = multiprocessing.Queue() SendeventProcess(resultQueue) print 'main' </code></pre> <p>My frustration with this "solution" is that, one, it's absolutely unclear what exactly it is patching, and, two, that it's written in such a convoluted way that it becomes impossible to infer which parts are the solution, and which are just an illustration.</p> <p>Can anyone share some light on this issue, and provide insight what exactly needs to be changed in a project that enables multiprocessing in PyInstaller-built single-file Windows executables?</p>
0
1,288
importing configurable products in Magento from CSV
<p>I'm trying to append complex data to my database products in <code>Magento</code> ver. 1.7.0.2, some are simple and other configurable. The exported Magento <code>CSV</code> doesn't greet with the needs for importing. I have this file for example for importing data:</p> <pre><code> sku,_store,_attribute_set,_type,_category,_root_category,_product_websites,price,special_price,special_from_date,special_to_date,image,media_gallery,news_from_date,news_to_date,url_key,url_path,minimal_price,visibility,custom_design,custom_layout_update,page_layout,options_container,required_options,has_options,image_label,small_image_label,thumbnail_label,created_at,updated_at,enable_googlecheckout,gift_message_available,is_imported,country_of_manufacture,msrp_enabled,msrp_display_actual_price_type,msrp,qty,min_qty,use_config_min_qty,is_qty_decimal,backorders,use_config_backorders,min_sale_qty,use_config_min_sale_qty,max_sale_qty,use_config_max_sale_qty,is_in_stock,notify_stock_qty,use_config_notify_stock_qty,manage_stock,use_config_manage_stock,stock_status_changed_auto,use_config_qty_increments,qty_increments,use_config_enable_qty_inc,enable_qty_increments,is_decimal_divided,_links_related_sku,_links_related_position,_links_crosssell_sku,_links_crosssell_position,_links_upsell_sku,_links_upsell_position,_associated_sku,_associated_default_qty,_associated_position,_tier_price_website,_tier_price_customer_group,_tier_price_qty,_tier_price_price,_group_price_website,_group_price_customer_group,_group_price_price,_media_attribute_id,_media_image,_media_lable,_media_position,_media_is_disabled,_super_products_sku,_super_attribute_code,_super_attribute_option,_super_attribute_price_corr "1202012000009S_freesoul,,PartesDeArriba_Hombre,simple,Hombre/Camisetas,""Default Category"",base,45.0000,,,,/t/n/tn_1202012000009-1_1.jpg,,,,camiseta-freesoul,camiseta-freesoul.html,,1,,,,""Bloque después de la columna de Información"",0,0,""Camiseta Freesoul"",""Camiseta Freesoul"",""Camiseta Freesoul"",""2012-10-05 08:41:01"",""2012-10-05 12:07:06"",1,,No,,""Usar configuración"",""Usar configuración"",,5.0000,0.0000,1,0,0,1,1.0000,1,0.0000,1,1,,1,0,1,0,1,0.0000,1,0,0,,,,,,,,,,,,,,,,,73,/t/n/tn_1202012000009-1_1.jpg,""Camiseta Freesoul"",1,0,,,," ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,73,/t/n/tn_1202012000009-2_1.jpg,""Camiseta para hombre Freesoul"",2,0,,,," "1202012000009M_freesoul,,PartesDeArriba_Hombre,simple,Hombre/Camisetas,""Default Category"",base,45.0000,,,,no_selection,,,,camiseta-freesoul,camiseta-freesoul-58.html,,1,,,,""Bloque después de la columna de Información"",0,0,/,/,/,""2012-10-05 08:41:51"",""2012-10-05 12:07:39"",1,,No,,""Usar configuración"",""Usar configuración"",,5.0000,0.0000,1,0,0,1,1.0000,1,0.0000,1,1,,1,0,1,0,1,0.0000,1,0,0,,,,,,,,,,,,,,,,,73,/t/n/tn_1202012000009-1_1_1.jpg,""Camiseta Freesoul"",1,0,,,," ",espanol,,,,,,,,,,,,,,,camiseta-freesoul.html,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,73,/t/n/tn_1202012000009-2_1_1.jpg,""Camiseta para hombre Freesoul"",2,0,,,," "1202012000009L_freesoul,,PartesDeArriba_Hombre,simple,Hombre/Camisetas,""Default Category"",base,45.0000,,,,no_selection,,,,camiseta-freesoul,camiseta-freesoul-59.html,,1,,,,""Bloque después de la columna de Información"",0,0,/,/,/,""2012-10-05 08:43:19"",""2012-10-05 12:08:03"",1,,No,,""Usar configuración"",""Usar configuración"",,5.0000,0.0000,1,0,0,1,1.0000,1,0.0000,1,1,,1,0,1,0,1,0.0000,1,0,0,,,,,,,,,,,,,,,,,73,/t/n/tn_1202012000009-1_1_1_1.jpg,""Camiseta Freesoul"",1,0,,,," ",espanol,,,,,,,,,,,,,,,camiseta-freesoul.html,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,73,/t/n/tn_1202012000009-2_1_1_1.jpg,""Camiseta para hombre Freesoul"",2,0,,,," "1202012000009XL_freesoul,,PartesDeArriba_Hombre,simple,Hombre/Camisetas,""Default Category"",base,45.0000,,,,no_selection,,,,camiseta-freesoul,camiseta-freesoul-60.html,,1,,,,""Bloque después de la columna de Información"",0,0,/,/,/,""2012-10-05 08:44:34"",""2012-10-05 12:08:29"",1,,No,,""Usar configuración"",""Usar configuración"",,5.0000,0.0000,1,0,0,1,1.0000,1,0.0000,1,1,,1,0,1,0,1,0.0000,1,0,0,,,,,,,,,,,,,,,,,73,/t/n/tn_1202012000009-1_1_1_1_1.jpg,""Camiseta Freesoul"",1,0,,,," ",espanol,,,,,,,,,,,,,,,camiseta-freesoul.html,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,73,/t/n/tn_1202012000009-2_1_1_1_1.jpg,""Camiseta para hombre Freesoul"",2,0,,,," "1202012000009XXL_freesoul,,PartesDeArriba_Hombre,simple,Hombre/Camisetas,""Default Category"",base,45.0000,,,,no_selection,,,,camiseta-freesoul,camiseta-freesoul-61.html,,1,,,,""Bloque después de la columna de Información"",0,0,/,/,/,""2012-10-05 11:39:42"",""2012-10-05 12:08:52"",1,,No,,""Usar configuración"",""Usar configuración"",,5.0000,0.0000,1,0,0,1,1.0000,1,0.0000,1,1,,1,0,1,0,1,0.0000,1,0,0,,,,,,,,,,,,,,,,,73,/t/n/tn_1202012000009-1_1_1_1_1_1.jpg,""Camiseta Freesoul"",1,0,,,," ",espanol,,,,,,,,,,,,,,,camiseta-freesoul.html,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,73,/t/n/tn_1202012000009-2_1_1_1_1_1.jpg,""Camiseta para hombre Freesoul"",2,0,,,," "12020120000093XL_freesoul,,PartesDeArriba_Hombre,simple,Hombre/Camisetas,""Default Category"",base,45.0000,,,,no_selection,,,,camiseta-freesoul,camiseta-freesoul-62.html,,1,,,,""Bloque después de la columna de Información"",0,0,/,/,/,""2012-10-05 11:41:45"",""2012-10-05 12:09:15"",1,,No,,""Usar configuración"",""Usar configuración"",,5.0000,0.0000,1,0,0,1,1.0000,1,0.0000,1,1,,1,0,1,0,1,0.0000,1,0,0,,,,,,,,,,,,,,,,,73,/t/n/tn_1202012000009-1_1_1_1_1_1_1.jpg,""Camiseta Freesoul"",1,0,,,," ",espanol,,,,,,,,,,,,,,,camiseta-freesoul.html,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,73,/t/n/tn_1202012000009-2_1_1_1_1_1_1.jpg,""Camiseta para hombre Freesoul"",2,0,,,," "1202012000009_freesoul,,PartesDeArriba_Hombre,configurable,Hombre/Camisetas,""Default Category"",base,45.0000,,,,/t/n/tn_1202012000009-1_3.jpg,,""2012-10-04 00:00:00"",,camiseta-freesoul-conf,camiseta-freesoul-conf.html,,4,,,,""Bloque después de la columna de Información"",1,1,,,,""2012-10-05 11:59:13"",""2012-10-10 11:02:47"",1,,No,,""Usar configuración"",""Usar configuración"",,0.0000,0.0000,1,0,0,1,1.0000,1,0.0000,1,1,,1,0,1,0,1,0.0000,1,0,0,,,,,,,,,,,,,,,,,73,/t/n/tn_1202012000009-1_3.jpg,,1,0,1202012000009S_freesoul,tallacamisetas_h,S, </code></pre> <p>I'm getting this error:</p> <pre><code>Product Type is invalid or not supported in rows: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, Product with specified super products `SKU` not found in rows: 14 </code></pre> <p>If tried this things to make it work:</p> <ul> <li>The <code>SKU</code> is required and I see some lines don't have them so, trying to import other lines put that the type is incorrect.</li> <li>I've converted the CSV to utf-8 and the error continues</li> <li>I've changed the column names putting "" and doesn't work neither</li> <li>I've used Magmi and when runnig the import file get this error: <code>SQLSTATE[28000] [1045] Access denied for user '&lt;&gt;'@'localhost' (using password: YES)</code></li> </ul> <p><strong>Edit</strong> After configuring correctly Magmi when I try to import from a CSV there's a problem with the path of the file and get this error:</p> <pre><code>C:wampwwwmagentoarimport/myfile.csv not found - </code></pre> <p>The thing is that the path is missing "/" because it should be:</p> <pre><code>C:wamp/www/magento/var/import/myfile.csv </code></pre> <p>How can I sort this out?</p>
0
3,181
How to set button click listener for Custom Dialog?
<p>I have made a main <code>Dialog</code> class on which I send the layout ID and shows the layout as a <code>Dialog</code> now when I send the layout from calling class it pops up the dialog but the contents of dialog i.e. buttons are inaccessible I can't set click listener for them. How to do that?</p> <p>CALLING CLASS:-</p> <pre><code>CustomDialog obj=new CustomDialog(MailSenderActivity.this , R.layout.mydialog); obj.show(); </code></pre> <p>MAIN CLASS</p> <pre><code>import android.app.Dialog; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class CustomDialog extends Dialog implements View.OnClickListener { Dialog dialog; int id; public CustomDialog(MailSenderActivity mailsender, int id) { super(mailsender); this.id = id; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(id); Button signInbutton=(Button)findViewById(R.id.signInButton); Button closebutton=(Button)findViewById(R.id.closeButton); } public void closebutton(View v) { Toast.makeText(getContext(), "You clicked a button!", Toast.LENGTH_LONG).show(); dismiss(); } @Override public void onClick(View v) { // TODO Auto-generated method stub } } </code></pre> <p>id is:-</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:layout_width="fill_parent" android:padding="30dip" android:orientation="horizontal" android:weightSum="1" android:background="@drawable/gmail"&gt; &lt;LinearLayout android:layout_width="296dp" android:orientation="vertical" android:layout_gravity="center" android:layout_weight="1.51" android:layout_height="497dp"&gt; &lt;TextView android:text="My Dialog" android:textSize="24.5sp" android:layout_width="wrap_content" android:layout_gravity="center" android:layout_height="wrap_content" android:layout_marginBottom="25dip"&gt;&lt;/TextView&gt; &lt;TextView android:text="Enter Gmail Id" android:layout_width="fill_parent" android:layout_height="wrap_content"&gt;&lt;/TextView&gt; &lt;EditText android:id="@+id/name" android:layout_width="358dp" android:singleLine="true" android:layout_height="wrap_content"&gt; &lt;/EditText&gt; &lt;TextView android:text="Enter Gmail Password" android:layout_width="fill_parent" android:layout_height="wrap_content"&gt;&lt;/TextView&gt; &lt;EditText android:id="@+id/name" android:layout_width="314dp" android:singleLine="true" android:layout_height="wrap_content" android:password="false" android:inputType="textPassword"&gt;&lt;/EditText&gt; &lt;Button android:text="Sign In" android:layout_width="67dp" android:id="@+id/signInButton" android:layout_height="wrap_content" android:clickable="true" android:onClick="signIn"&gt;&lt;/Button&gt; &lt;Button android:text="close" android:layout_width="67dp" android:id="@+id/closeButton" android:layout_height="wrap_content" android:clickable="true" android:onClick="closeButton"&gt;&lt;/Button&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre>
0
1,353
Importing CSV data using PHP/MySQL - Mysqli syntax
<p>IN THE BOTTOM OF THIS QUESTION THE FINAL CODE THAT FINALLY WORKED!</p> <p>Trying to implement this (<a href="https://stackoverflow.com/questions/11448307/importing-csv-data-using-php-mysql">Importing CSV data using PHP/MySQL</a>). I must be almost there...</p> <p>notes1: my $sql came straight from copy/paste phpmyadmin (generate php code) and ran just fine in the phpmyadmin.</p> <p>note2: If I comment the line $sql="DELETE FROM dbase" the code runs just fine (and the table is cleaned).</p> <p>So if i know my sql is right and my code can run other sqls, why does the below does not run?! Im getting: </p> <p>Call to a member function execute() on a non-object - for the line </p> <pre><code>$stmt-&gt;execute(); </code></pre> <p>Full code:</p> <pre><code>&lt;?php $mysqli = new mysqli('localhost','root','pass','dbase'); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $sql = "LOAD DATA INFILE \'./myfile.csv\' INTO TABLE tab\n" . " FIELDS TERMINATED BY \',\'\n" . " LINES TERMINATED BY \'\\r\\n\'\n" . " IGNORE 1 LINES"; //$sql="DELETE FROM dbase"; $stmt=$mysqli-&gt;prepare($sql); $stmt-&gt;execute(); $stmt-&gt;close(); $mysqli-&gt;close(); ?&gt; </code></pre> <p>tks in advance!</p> <p>EDIT:</p> <p>Made below changes and still not working!</p> <p>new code:</p> <pre><code>&lt;?php $mysqli = new mysqli('localhost','root','pass','dbase'); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* return name of current default database */ if ($result = $mysqli-&gt;query("SELECT DATABASE()")) { $row = $result-&gt;fetch_row(); printf("Default database is %s.\n", $row[0]); $result-&gt;close(); } $sql = "LOAD DATA INFILE 'C:/xampp/htdocs/myfile.csv' INTO TABLE tab FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\r\\n' IGNORE 1 LINES"; echo "&lt;br&gt;"; echo "&lt;br&gt;"; echo $sql; echo "&lt;br&gt;"; echo "&lt;br&gt;"; $stmt=$mysqli-&gt;prepare($sql); /* Prepared statement, stage 1: prepare */ if (!($stmt = $mysqli-&gt;prepare($sql))) { echo "Prepare failed: (" . $mysqli-&gt;errno . ") " . $mysqli-&gt;error; } // NOTE HERE WE'RE DUMPING OUR OBJ TO SEE THAT IT WAS // CREATED AND STATUS OF PREPARE AND THEN KILLING SCRIPT var_dump($mysqli); exit(); //$sql="DELETE FROM intrasdump $stmt=$mysqli-&gt;prepare($sql); $stmt-&gt;execute(); $stmt-&gt;close(); $mysqli-&gt;close(); ?&gt; </code></pre> <p>What i see in my browser when I ran this is the following:</p> <p>Default database is dbname. </p> <p>LOAD DATA INFILE 'C:/xampp/htdocs/myfile.csv' INTO TABLE tab FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' IGNORE 1 LINES</p> <p>Prepare failed: (1295) This command is not supported in the prepared statement protocol yetobject(mysqli)#1 (19) { ["affected_rows"]=> int(-1) ["client_info"]=> string(79) "mysqlnd 5.0.11-dev - 20120503 - $Id: 40933630edef551dfaca71298a83fad8d03d62d4 $" ["client_version"]=> int(50011) ["connect_errno"]=> int(0) ["connect_error"]=> NULL ["errno"]=> int(1295) ["error"]=> string(68) "This command is not supported in the prepared statement protocol yet" ["error_list"]=> array(0) { } ["field_count"]=> int(1) ["host_info"]=> string(20) "localhost via TCP/IP" ["info"]=> NULL ["insert_id"]=> int(0) ["server_info"]=> string(6) "5.6.11" ["server_version"]=> int(50611) ["stat"]=> string(133) "Uptime: 7993 Threads: 2 Questions: 865 Slow queries: 0 Opens: 75 Flush tables: 1 Open tables: 68 Queries per second avg: 0.108" ["sqlstate"]=> string(5) "00000" ["protocol_version"]=> int(10) ["thread_id"]=> int(117) ["warning_count"]=> int(0) }</p> <p>Note: If I copy paste the sql string echoed above in to mysql prompt, it runs just fine. That should mean that both the file location issue and the sql string itself are fine, no???</p> <p>how can this be so hard?!</p> <p>EDIT 3.</p> <p>Tks for all answers and comments. Final code version below works:</p> <pre><code>&lt;?php $mysqli = new mysqli('localhost','root','pass','dbname'); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $sql = "LOAD DATA INFILE 'C:/xampp/htdocs/myfile.csv' INTO TABLE tab FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\r\\n' IGNORE 1 LINES"; //Try to execute query (not stmt) and catch mysqli error from engine and php error if (!($stmt = $mysqli-&gt;query($sql))) { echo "\nQuery execute failed: ERRNO: (" . $mysqli-&gt;errno . ") " . $mysqli-&gt;error; }; ?&gt; </code></pre> <p>useful notes:</p> <ul> <li><p>note the file path uses <strong>frw-slash</strong> instead of windows-default back-slash. Orderwise will just note work. God knows how I figured that one out...</p></li> <li><p>take advantage of the many debugging codes offered in the answers. i guess one effective way to check if your sql is right to echo (<code>echo $sql</code>) it and copy/paste in your sql prompt. don't trust phpmyadmin 'create php PHP code' functionality. </p></li> <li><p>keep in mind 'Prepared stmts don't support LOAD DATA'</p></li> </ul>
0
1,981
java.sql.SQLException: Connection is not associated with a managed connection.org.jboss.resource.adapter.jdbc.jdk5.WrappedConnectionJDK5@42d0cb88
<p>I'm using <code>jboss5.1</code> with spring as the system's architecture. The version of <code>mysql</code> is <code>5.6.12</code>, and the version of <code>jdk</code> is <code>1.7</code>. Scenario : Because I need update the record which the system inserted into the DB no long before,<br> I try to get the id of the record while executing inserting record. </p> <p>I used <code>GeneratedKeyHolder</code>(class in spring) to get the auto id . The source is as below :</p> <pre><code> KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement(sql, new String[] { "id" }); ps.setString(1, record.getCmdName()); ps.setTimestamp(6, new Timestamp(System.currentTimeMillis())); return ps; } }, keyHolder); return keyHolder.getKey().intValue(); </code></pre> <p>In the most environments, the code work well , but in one environment it throws exception as below. It's so surprising , and we failed to reproduce the exception in our testing environment.</p> <pre><code>INFO | jvm 1 | 2013/09/24 11:03:47 | org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL []; SQL state [null]; error code [0]; Connection is not associated with a managed connection.org.jboss.resource.adapter.jdbc.jdk5.WrappedConnectionJDK5@42d0cb88; nested exception is java.sql.SQLException: Connection is not associated with a managed connection.org.jboss.resource.adapter.jdbc.jdk5.WrappedConnectionJDK5@42d0cb88 INFO | jvm 1 | 2013/09/24 11:03:47 | Caused by: INFO | jvm 1 | 2013/09/24 11:03:47 | java.sql.SQLException: Connection is not associated with a managed connection.org.jboss.resource.adapter.jdbc.jdk5.WrappedConnectionJDK5@42d0cb88 INFO | jvm 1 | 2013/09/24 11:03:47 | at org.jboss.resource.adapter.jdbc.WrappedConnection.lock(WrappedConnection.java:81) INFO | jvm 1 | 2013/09/24 11:03:47 | at org.jboss.resource.adapter.jdbc.WrappedConnection.prepareStatement(WrappedConnection.java:345) INFO | jvm 1 | 2013/09/24 11:03:47 | at RecordDao$1.createPreparedStatement(RecordDao.java:60) INFO | jvm 1 | 2013/09/24 11:03:47 | at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:532) INFO | jvm 1 | 2013/09/24 11:03:47 | at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:771) INFO | jvm 1 | 2013/09/24 11:03:47 | at RecordDao.insertGongdan(RecordDao.java:56) INFO | jvm 1 | 2013/09/24 11:03:47 | INFO | jvm 1 | 2013/09/24 11:03:47 | at java.lang.Thread.run(Thread.java:722) INFO | jvm 1 | 2013/09/24 11:03:47 | 11:03:47,543 INFO [TL1ServerSession] TL1ServerSession send! INFO | jvm 1 | 2013/09/24 11:03:47 | 11:03:47,543 INFO [TL1ServerSession] Send TL1 Message: INFO | jvm 1 | 2013/09/24 11:03:47 | </code></pre>
0
1,280
Request.Files is always null
<p>I'm writing a C# ASP.Net MVC application for client to post files to other server. I'm using a generic handler to handle posted files from client to server. But in my handler, System.Web.HttpContext.Current.Request.Files always empty (0 count).</p> <p>Form Code:</p> <pre><code>@model ITDB102.Models.UploadFileResultsModels @{ Layout = "~/Views/Shared/_Layout.cshtml"; } &lt;div&gt; &lt;h1&gt;Upload File&lt;/h1&gt; &lt;form id="file-form" action="/Files/UploadFile" method="post" data-ajax="false" enctype="multipart/form-data"&gt; &lt;div&gt;&lt;input type="file" id="FilePath" name="FilePath"/&gt; &lt;button type="submit"&gt;Send File&lt;/button&gt;&lt;/div&gt; &lt;/form&gt; &lt;/div&gt; @section scripts{ &lt;script src="~/Scripts/jquery-1.10.2.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; // Variable to store your files var files; var form = document.getElementById('file-form'); // Add events $('input[type=file]').on('change', prepareUpload); // Grab the files and set them to our variable function prepareUpload(event) { files = $('#FilePath').get(0).files; } form.onsubmit = function (event) { uploadFiles(event); } // Catch the form submit and upload the files function uploadFiles(event) { event.stopPropagation(); // Stop stuff happening event.preventDefault(); // Totally stop stuff happening // Create a formdata object and add the files var data = new FormData(); if (files.lenght &gt; 0) { data.append('UploadedFiles', files[0], file[0].name); } //setup request var xhr = new XMLHttpRequest(); //open connection xhr.open('POST', '/Files/UploadFile',false); xhr.setRequestHeader("Content-Type", files.type); //send request xhr.send(data); } &lt;/script&gt; } </code></pre> <p>Handler:</p> <pre><code>/// &lt;summary&gt; /// Uploads the file. /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; [HttpPost] public virtual ActionResult UploadFile() { HttpPostedFile myFile = System.Web.HttpContext.Current.Request.Files["UploadedFiles"]; bool isUploaded = false; string message = "File upload failed"; if (myFile != null &amp;&amp; myFile.ContentLength != 0) { string pathForSaving = Server.MapPath("~/Uploads"); if (this.CreateFolderIfNeeded(pathForSaving)) { try { myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName)); isUploaded = true; message = "File uploaded successfully!"; } catch (Exception ex) { message = string.Format("File upload failed: {0}", ex.Message); } } } return Json(new { isUploaded = isUploaded, message = message }, "text/html"); } #region Private Methods /// &lt;summary&gt; /// Creates the folder if needed. /// &lt;/summary&gt; /// &lt;param name="path"&gt;The path.&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; private bool CreateFolderIfNeeded(string path) { bool result = true; if (!Directory.Exists(path)) { try { Directory.CreateDirectory(path); } catch (Exception) { /*TODO: You must process this exception.*/ result = false; } } return result; } #endregion </code></pre> <p>Please help me. Thanks.</p>
0
1,858
Gradle Build Error - NullPointerException thrown during app:compileDebugJava gradle task
<p>I keep receiving this error message everytime I try to make a gradle build. I recently made a build before this and the application was created without any issue. I didn't make any changes to my build.gradle file. What is causing this?</p> <pre><code>:app:preBuild ...... :app:processDebugResources :app:generateDebugSources :app:compileDebugJava FAILED Error:Execution failed for task ':app:compileDebugJava'. &gt; java.lang.NullPointerException </code></pre> <p>I am using Android Studio version 0.8.1</p> <p>Here is the gradle stacktrace:</p> <pre><code>* Exception is: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugJava'. at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46) at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35) at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64) at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58) at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42) at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52) at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53) at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43) at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:289) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23) at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:86) at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:29) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:61) at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23) at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:67) at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:61) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:54) at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:166) at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:113) at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:81) at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:64) at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:33) at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:24) at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:35) at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26) at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:50) at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:171) at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:201) at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:174) at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:170) at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:139) at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33) at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22) at org.gradle.launcher.Main.doAction(Main.java:46) at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45) at org.gradle.launcher.Main.main(Main.java:37) at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:50) at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:32) at org.gradle.launcher.GradleMain.main(GradleMain.java:23) at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:33) at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:130) at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48) Caused by: java.lang.RuntimeException: java.lang.NullPointerException at com.sun.tools.javac.main.Main.compile(Main.java:469) at com.sun.tools.javac.api.JavacTaskImpl.call(JavacTaskImpl.java:132) at org.gradle.api.internal.tasks.compile.jdk6.Jdk6JavaCompiler.execute(Jdk6JavaCompiler.java:45) at org.gradle.api.internal.tasks.compile.jdk6.Jdk6JavaCompiler.execute(Jdk6JavaCompiler.java:38) at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:96) at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:49) at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:35) at org.gradle.api.internal.tasks.compile.DelegatingJavaCompiler.execute(DelegatingJavaCompiler.java:29) at org.gradle.api.internal.tasks.compile.DelegatingJavaCompiler.execute(DelegatingJavaCompiler.java:20) at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:33) at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:24) at org.gradle.api.tasks.compile.Compile.performCompilation(Compile.java:165) at org.gradle.api.tasks.compile.Compile.compile(Compile.java:153) at org.gradle.api.tasks.compile.Compile.compile(Compile.java:87) at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:63) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.java:236) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:212) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.java:223) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:201) at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:533) at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:516) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61) ... 46 more Caused by: java.lang.NullPointerException at dagger.internal.codegen.Util.getAnnotation(Util.java:192) at dagger.internal.codegen.GraphAnalysisProcessor.process(GraphAnalysisProcessor.java:107) at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:793) at com.sun.tools.javac.processing.JavacProcessingEnvironment.access$200(JavacProcessingEnvironment.java:97) at com.sun.tools.javac.processing.JavacProcessingEnvironment$DiscoveredProcessors$ProcessorStateIterator.runContributingProcs(JavacProcessingEnvironment.java:644) at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1027) at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1185) at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1108) at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:824) at com.sun.tools.javac.main.Main.compile(Main.java:439) ... 68 more </code></pre> <p>Here is my build.gradle (its a little messy):</p> <pre><code>buildscript { repositories { mavenCentral() maven { url 'http://download.crashlytics.com/maven' } } dependencies { classpath 'com.jakewharton.sdkmanager:gradle-plugin:0.9.+' classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:1.+' } } apply plugin: 'android-sdk-manager' apply plugin: 'android' apply plugin: 'crashlytics' repositories { maven { url 'http://download.crashlytics.com/maven' } } android { signingConfigs { release { storeFile file("") storePassword '' keyAlias '' keyPassword '' } debug { storeFile file('/home/andreperkins/.android/debug.keystore') } } //noinspection GroovyAssignabilityCheck compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION) //noinspection GroovyAssignabilityCheck buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION defaultConfig { applicationId 'com.liveauctioneers.and' //noinspection GroovyAssignabilityCheck minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION) //noinspection GroovyAssignabilityCheck targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION) versionCode 7 versionName '3.0' testInstrumentationRunner 'com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner' } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' //noinspection GroovyAssignabilityCheck signingConfig signingConfigs.release } debug { applicationIdSuffix '.debug' versionNameSuffix '-DEBUG' zipAlign false } qa { debuggable false jniDebugBuild false renderscriptDebugBuild false runProguard false applicationIdSuffix '.qa' versionNameSuffix '-QA' zipAlign true //noinspection GroovyAssignabilityCheck signingConfig signingConfigs.release } } productFlavors { } compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } packagingOptions { exclude 'LICENSE.txt' exclude 'META-INF/services/javax.annotation.processing.Processor' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile project(':facebook') provided 'com.squareup.dagger:dagger-compiler:1.2.1' //mockito dependencies androidTestCompile files('libs/dexmaker-mockito-1.0.jar') androidTestCompile 'org.mockito:mockito-core:1.9.5' androidTestCompile files('libs/dexmaker-1.0.jar') //espresso dependencies /*androidTestCompile files('libs/espresso-1.1.jar') androidTestCompile files('libs/testrunner-1.1.jar') androidTestCompile files('libs/testrunner-runtime-1.1.jar') */ androidTestCompile 'com.google.guava:guava:16.0' /*androidTestCompile 'org.hamcrest:hamcrest-core:1.1' androidTestCompile 'org.hamcrest:hamcrest-integration:1.1' androidTestCompile 'org.hamcrest:hamcrest-library:1.1'*/ androidTestCompile 'com.squareup.spoon:spoon-client:1.1.1' androidTestCompile('com.jakewharton.espresso:espresso:1.1-r3') { exclude group: 'com.squareup.dagger' } compile 'com.jakewharton:butterknife:4.0.+' compile 'com.squareup.dagger:dagger:1.2.1' compile 'com.squareup.okhttp:okhttp:1.3.+' compile 'com.squareup.retrofit:retrofit:1.5.1' compile 'com.google.code.gson:gson:2.2.+' compile 'com.crashlytics.android:crashlytics:1.+' compile 'com.squareup:otto:1.3.5' compile 'javax.annotation:javax.annotation-api:1.2' compile 'com.google.code.findbugs:jsr305:1.3.9' // You must install or update the Support Repository through the SDK manager to use this dependency. compile 'com.android.support:support-v13:19.0.1' compile 'com.j256.ormlite:ormlite-android:4.43' compile 'com.j256.ormlite:ormlite-core:4.43' } </code></pre>
0
4,991
Widget rebuild after TextField selection Flutter
<p>I'm developping a Flutter App that needed to have a form. So when the user open the app, a Splash Screen appear before the form that have the following code : </p> <pre><code>import 'package:flutter/material.dart'; import '../model/User.dart'; import './FileManager.dart'; import './MyListPage.dart'; class UserLoader extends StatefulWidget { @override _UserLoaderState createState() =&gt; new _UserLoaderState(); } class _UserLoaderState extends State&lt;UserLoader&gt; { final userFileName = "user_infos.txt"; User _user; @override Widget build(BuildContext context) { print("build UserLoader"); final _formKey = new GlobalKey&lt;FormState&gt;(); final _firstNameController = new TextEditingController(); final _lastNameController = new TextEditingController(); final _emailController = new TextEditingController(); final _phoneController = new TextEditingController(); return new Scaffold( appBar: new AppBar( title: new Text("Informations"), actions: &lt;Widget&gt;[ new IconButton( icon: const Icon(Icons.save), onPressed: () { _user = _onFormValidate( _formKey.currentState, _firstNameController.text, _lastNameController.text, _emailController.text, _phoneController.text); }) ], ), body: new Center( child: new SingleChildScrollView( child: new Form( key: _formKey, child: new Column(children: &lt;Widget&gt;[ new ListTile( leading: const Icon(Icons.person), title: new TextFormField( decoration: new InputDecoration( hintText: "Prénom", ), keyboardType: TextInputType.text, controller: _firstNameController, validator: _validateName, ), ), new ListTile( leading: const Icon(Icons.person), title: new TextFormField( decoration: new InputDecoration( hintText: "Nom", ), keyboardType: TextInputType.text, controller: _lastNameController, validator: _validateName, ), ), Etc, etc ... </code></pre> <p>However when i tap the TextField, the keyboard appear and close immediately and all the component is rebuild. So it is impossible for me to complete the form..</p> <p>Can someone have a solution please? Thanks in advance !</p>
0
1,428
POSTing multipart/form-data to a WCF REST service: the action changes
<p>I have a WCF Rest service:</p> <pre><code> [WebHelp(Comment = "Sample description for GetData")] [WebInvoke(Method="POST", UriTemplate = "invoke", BodyStyle =WebMessageBodyStyle.Bare)] [OperationContract] public string GetData( Stream input) { long incomingLength = WebOperationContext.Current.IncomingRequest.ContentLength; string[] result = new string[incomingLength]; int cnter = 0; int arrayVal = -1; do { if (arrayVal != -1) result[cnter++] = Convert.ToChar(arrayVal).ToString(); arrayVal = input.ReadByte(); } while (arrayVal != -1); return incomingLength.ToString(); } </code></pre> <p>That I want to upload files (well, file; one at a time) to. Using this form to test:</p> <pre><code> &lt;form method="post" action="Service.svc/invoke" &gt; &lt;input type="file" name="aFile" /&gt; &lt;/form&gt; &lt;input type="button" onclick="document.forms[0].submit();" /&gt; </code></pre> <p>I can see the service receive the data, even though with the enctype of the form being set to 'multipart/form-data', only receive the element name and the name of the uploaded file. However, if I set the enctype, I get nothing; the service is never hit. I put a break in the code to see what was going on, and it was never reached. Do I need to do something special in the URITemplate attribute for the 'multipart/form-data' enctype? What else am I missing? For the heck of it, I used Fiddler to see what was being sent to the service with each option, and there was nothing sinister looking.</p> <p>Without 'multipart/form-data':</p> <pre><code>POST /Service4/Service.svc/invoke HTTP/1.1 Accept: application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */* Referer: &lt;my machine&gt;/Service4/form.htm Accept-Language: en-US User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8; .NET CLR 1.1.4322) Content-Type: application/x-www-form-urlencoded Accept-Encoding: gzip, deflate Host: okrd14144 Content-Length: 89 Connection: Keep-Alive Pragma: no-cache </code></pre> <p>With:</p> <pre><code>POST /Service4/Service.svc/invoke HTTP/1.1 Accept: application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */* Referer: &lt;my machine&gt;/Service4/form.htm Accept-Language: en-US User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8; .NET CLR 1.1.4322) Content-Type: multipart/form-data; boundary=---------------------------7da1ce3aa0bd0 Accept-Encoding: gzip, deflate Host: okrd14144 Content-Length: 150119 Connection: Keep-Alive Pragma: no-cache </code></pre> <p>I'm out of ideas</p>
0
1,227
Aggregate (and other annotated) fields in Django Rest Framework serializers
<p>I am trying to figure out the best way to add annotated fields, such as any aggregated (calculated) fields to DRF (Model)Serializers. My use case is simply a situation where an endpoint returns fields that are NOT stored in a database but calculated from a database.</p> <p>Let's look at the following example:</p> <p>models.py</p> <pre><code>class IceCreamCompany(models.Model): name = models.CharField(primary_key = True, max_length = 255) class IceCreamTruck(models.Model): company = models.ForeignKey('IceCreamCompany', related_name='trucks') capacity = models.IntegerField() </code></pre> <p>serializers.py</p> <pre><code>class IceCreamCompanySerializer(serializers.ModelSerializer): class Meta: model = IceCreamCompany </code></pre> <p>desired JSON output:</p> <pre><code>[ { "name": "Pete's Ice Cream", "total_trucks": 20, "total_capacity": 4000 }, ... ] </code></pre> <p>I have a couple solutions that work, but each have some issues.</p> <p><strong>Option 1: add getters to model and use SerializerMethodFields</strong></p> <p>models.py</p> <pre><code>class IceCreamCompany(models.Model): name = models.CharField(primary_key=True, max_length=255) def get_total_trucks(self): return self.trucks.count() def get_total_capacity(self): return self.trucks.aggregate(Sum('capacity'))['capacity__sum'] </code></pre> <p>serializers.py</p> <pre><code>class IceCreamCompanySerializer(serializers.ModelSerializer): def get_total_trucks(self, obj): return obj.get_total_trucks def get_total_capacity(self, obj): return obj.get_total_capacity total_trucks = SerializerMethodField() total_capacity = SerializerMethodField() class Meta: model = IceCreamCompany fields = ('name', 'total_trucks', 'total_capacity') </code></pre> <p>The above code can perhaps be refactored a bit, but it won't change the fact that this option will perform 2 extra SQL queries <em>per IceCreamCompany</em> which is not very efficient.</p> <p><strong>Option 2: annotate in ViewSet.get_queryset</strong></p> <p>models.py as originally described.</p> <p>views.py</p> <pre><code>class IceCreamCompanyViewSet(viewsets.ModelViewSet): queryset = IceCreamCompany.objects.all() serializer_class = IceCreamCompanySerializer def get_queryset(self): return IceCreamCompany.objects.annotate( total_trucks = Count('trucks'), total_capacity = Sum('trucks__capacity') ) </code></pre> <p>This will get the aggregated fields in a single SQL query but I'm not sure how I would add them to the Serializer as DRF doesn't magically know that I've annotated these fields in the QuerySet. If I add total_trucks and total_capacity to the serializer, it will throw an error about these fields not being present on the Model. </p> <p>Option 2 can be made work without a serializer by using a <a href="http://www.django-rest-framework.org/api-guide/views/">View</a> but if the model contains a lot of fields, and only some are required to be in the JSON, it would be a somewhat ugly hack to build the endpoint without a serializer.</p>
0
1,133
Ionic-Angular.js Taking pictures & sending to server: null images
<p>So I have managed to use a custom directive to upload images to my server, through Angular.js. I have also managed to implement the camera functionality from Cordova. Now I am trying to connect the two, but when sending images to the server, they get stored as null. I believe the problem lies in the fact that I was using an input field to get the image, and it was getting the full Object, and now I am getting just the image path after I take the picture and send it. My problem is, I don't really understand how I could convert the path to an Object, IF that is the problem?</p> <p><strong>index.html</strong></p> <pre><code>&lt;form class="form-horizontal" role="form"&gt; &lt;button class="picButton" ng-click="getPhoto()" class="button button-block button-primary"&gt;Take Photo&lt;/button&gt; &lt;img ng-src="{{lastPhoto}}" style="max-width: 100%"&gt; ... &lt;/form&gt; </code></pre> <p><strong>controllers.js</strong></p> <pre><code>$scope.getPhoto = function() { Camera.getPicture().then(function(imageURI) { console.log(imageURI); $scope.lastPhoto = imageURI; $scope.upload(); &lt;-- call to upload the pic }, function(err) { console.err(err); }, { quality: 75, targetWidth: 320, targetHeight: 320, saveToPhotoAlbum: false }); }; $scope.upload = function() { var url = ''; var fd = new FormData(); //previously I had this //angular.forEach($scope.files, function(file){ //fd.append('image',file) //}); fd.append('image', $scope.lastPhoto); $http.post(url, fd, { transformRequest:angular.identity, headers:{'Content-Type':undefined } }) .success(function(data, status, headers){ $scope.imageURL = data.resource_uri; //set it to the response we get }) .error(function(data, status, headers){ }) } </code></pre> <p>When printing $scope.lastPhoto I get the image path: <em>file:///var/mobile/Applications/../tmp/filename.jpg</em></p> <p><strong>EDIT</strong></p> <p>Request Headers:</p> <pre><code>------WebKitFormBoundaryEzXidt71U741Mc45 Content-Disposition: form-data; name="image" file:///var/mobile/Applications/C65C8030-33BF-4BBB-B2BB-7ECEC86E87A7/tmp/cdv_photo_015.jpg ------WebKitFormBoundaryEzXidt71U741Mc45-- </code></pre> <p>Should this causing the problem? Since I can see I am sending the path but not the image itself..</p> <p>Before changing, I was using a custom directive, and was using $scope.files to append to my request in the upload function:</p> <pre><code>&lt;input type="file" file-input="files" multiple onchange="angular.element(this).scope().filesChanged(this);upload();"&gt; &lt;button ng-click="upload()"&gt;Upload&lt;/button&gt; </code></pre>
0
1,030
Find max and min DateTime in Linq group
<p>I'm trying to find the max and min <code>DateTime</code>s from a CSV import.</p> <p>I have this to import the data from the temp <code>DataTable</code>:</p> <pre><code>var tsHead = from h in dt.AsEnumerable() select new { Index = h.Field&lt;string&gt;("INDEX"), TimeSheetCategory = h.Field&lt;string&gt;("FN"), Date = DdateConvert(h.Field&lt;string&gt;("Date")), EmployeeNo = h.Field&lt;string&gt;("EMPLOYEE"), Factory = h.Field&lt;string&gt;("FACTORY"), StartTime = DdateConvert(h.Field&lt;string&gt;("START_TIME")), //min FinishTime = DdateConvert(h.Field&lt;string&gt;("FINISH_TIME")), //max }; </code></pre> <p>Which works fine. I then want to group the data and show the Start time and finish time which is the min / max of the respective fields.</p> <p>So far I have this:</p> <pre><code>var tsHeadg = from h in tsHead group h by h.Index into g //Pull out the unique indexes let f = g.FirstOrDefault() where f != null select new { f.Index, f.TimeSheetCategory, f.Date, f.EmployeeNo, f.Factory, g.Min(c =&gt; c).StartTime, //Min starttime should be timesheet start time g.Max(c =&gt; c).FinishTime, //Max finishtime should be timesheet finish time }; </code></pre> <p>With the thinking that <code>g.Min</code> and <code>g.Max</code> would give me the lowest and highest <code>DateTime</code> for each timesheet (grouped by index)</p> <p>This doesn't work however... Whats the best way of finding the highest and lowest value of DateTimes within a group?</p>
0
1,114
Adding the pagination to a razor view
<p>I have an asp.Net Mvc4 web applcation in which i have a list as a model:</p> <pre><code>&lt;table class="table_data" border="1"&gt; &lt;tr&gt; @if(Model.Count &gt; 0){ &lt;th&gt; @Html.Label("Fonction") &lt;/th&gt; &lt;th&gt; @Html.Label("Nom du client") &lt;/th&gt; &lt;th&gt; @Html.Label("Date de réception") &lt;/th&gt; &lt;th&gt; @Html.Label("Date de clôture") &lt;/th&gt; &lt;th&gt;&lt;/th&gt; } &lt;/tr&gt; @foreach(Planning.Models.Paire p in Model){ &lt;tr&gt; &lt;td&gt; &lt;label&gt;@p._tag&lt;/label&gt; &lt;/td&gt; &lt;td&gt; &lt;label&gt;@p._client&lt;/label&gt; &lt;/td&gt; &lt;td&gt; &lt;label&gt;@p._reception&lt;/label&gt; &lt;/td&gt; &lt;td&gt; &lt;label&gt;@p._cloture&lt;/label&gt; &lt;/td&gt; &lt;td&gt; @{ List&lt;Planning.Models.Impaire&gt; liste = u.Get_Impaire_List(); Planning.Models.Impaire imp = liste.Find(x =&gt; x.id_paire == p.Id); if (imp != null){ @Html.ActionLink("voir plus de détails", "Details", new { id_paire = p.Id })} } &lt;/td&gt; &lt;/tr&gt; } &lt;/table&gt; </code></pre> <p>The <code>Model</code> is <code>List&lt;Paire&gt;</code> . </p> <p>I'd like to display each 15 lines together in the same view, so how can i add the pagination between pages at the same view? Can i use <code>Ajax</code> to do that?</p>
0
1,341
Permission denied (missing INTERNET permission?): But permission is given
<p>I'm trying to call a httpClient and the response is "Permission denied (missing INTERNET permission?)". In the normal browser of Android I can open the URL without problems.</p> <pre><code> public static String getHttpResponse(URI uri) { StringBuilder response = new StringBuilder(); try { HttpGet get = new HttpGet(); get.setURI(uri); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(get); if (httpResponse.getStatusLine().getStatusCode() == 200) { Log.d("demo", "HTTP Get succeeded"); HttpEntity messageEntity = httpResponse.getEntity(); InputStream is = messageEntity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { response.append(line); } } } catch (Exception e) { Log.e("demo", e.getMessage()); } Log.d("demo", "Done with HTTP getting"); return response.toString(); } </code></pre> <p>The catch log tell me the error:</p> <pre><code>java.lang.SecurityException: Permission denied (missing INTERNET permission?) libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname) Permission denied (missing INTERNET permission?) </code></pre> <p>In my Manifest is the permission set:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="..." &gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /&gt; &lt;uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /&gt; &lt;uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt; &lt;uses-feature android:name="android.hardware.camera" android:required="true" /&gt; &lt;activity android:name=".main" android:label="@string/app_name" &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; &lt;/application&gt; </code></pre> <p></p>
0
1,079
Discord.JS Userinfo command
<p>I'm trying to make this bot able to do this...</p> <ul> <li>Display User Roles</li> <li>You do d!au @User and their user info shows</li> </ul> <p>The only thing is that I do not know how to do this, I've found some other stack overflow questions but their bot requires "moment" and I have no idea what moment is. This is in a command file, not a index.js file FYI.</p> <pre><code> var commando = require('discord.js-commando'); var discord = require('discord.js'); class aboutuser extends commando.Command { constructor(client) { super(client, { name: 'aboutuser', group: 'help', memberName: 'aboutuser', description: 'Lists information about a specific user.', aliases: ['au', 'aboutu', 'auser', 'user'], }) } async run(message, args){ let userinfo = {}; userinfo.bot = message.client.user.bot; userinfo.createdat = message.client.user.createdAt; userinfo.discrim = message.client.user.discriminator; userinfo.id = message.client.user.id; userinfo.mfa = message.client.user.mfaEnabled; userinfo.pre = message.client.user.premium; userinfo.presen = message.client.user.presence; userinfo.tag = message.client.user.tag; userinfo.uname = message.client.user.username; userinfo.verified = message.client.user.verified; userinfo.avatar = message.client.user.avatarURL; var myInfo = new discord.RichEmbed() .setAuthor(userinfo.uname, userinfo.avatar) .addField("Bot?",userinfo.bot, true) .addField("Created At",userinfo.createdat, true) .addField("Discriminator",userinfo.discrim, true) .addField("Client ID",userinfo.id, true) .addField("2FA/MFA Enabled?",userinfo.mfa, true) .addField("Paid Account?",userinfo.pre, true) .addField("Presence",userinfo.presen, true) .addField("Client Tag",userinfo.tag, true) .addField("Username",userinfo.uname, true) .addField("Verified?",userinfo.verified, true) .setColor(0xf0e5da) .setFooter('s!aboutserver') .setTitle("About this user...") .setThumbnail(userinfo.avatar) message.channel.sendEmbed(myInfo); } } module.exports = aboutuser; </code></pre> <p>I want to make my bot able to display a user's roles and make it so that you can tag them. </p> <p>Reality : The command results in a error, but the bot is online. Referance Error, blank is not defined.</p> <p>Expects : A bot that can list the roles of a user, and you can see the information of other users when using the command.</p> <p>I've only pasted the code that WORKS, not the ones that end up as failiures.</p>
0
1,047
TCP connection refused with FFMPEG
<p>OFFICIAL EDIT:</p> <p>I thank you so much for your help but I am still encountering problems.</p> <p>My ffserver.conf file is like this:</p> <pre><code># Port on which the server is listening. You must select a different # port from your standard HTTP web server if it is running on the same # computer. HTTPPort 8090 # Address on which the server is bound. Only useful if you have # several network interfaces. HTTPBindAddress 0.0.0.0 # Number of simultaneous HTTP connections that can be handled. It has # to be defined *before* the MaxClients parameter, since it defines the # MaxClients maximum limit. MaxHTTPConnections 2000 # Number of simultaneous requests that can be handled. Since FFServer # is very fast, it is more likely that you will want to leave this high # and use MaxBandwidth, below. MaxClients 1000 # This the maximum amount of kbit/sec that you are prepared to # consume when streaming to clients. MaxBandwidth 1000 # Access log file (uses standard Apache log file format) # '-' is the standard output. CustomLog - ################################################################## # Definition of the live feeds. Each live feed contains one video # and/or audio sequence coming from an ffmpeg encoder or another # ffserver. This sequence may be encoded simultaneously with several # codecs at several resolutions. &lt;Feed feed1.ffm&gt; # You must use 'ffmpeg' to send a live feed to ffserver. In this # example, you can type: # # ffmpeg http://localhost:8090/feed1.ffm # ffserver can also do time shifting. It means that it can stream any # previously recorded live stream. The request should contain: # "http://xxxx?date=[YYYY-MM-DDT][[HH:]MM:]SS[.m...]".You must specify # a path where the feed is stored on disk. You also specify the # maximum size of the feed, where zero means unlimited. Default: # File=/tmp/feed_name.ffm FileMaxSize=5M File /tmp/feed1.ffm FileMaxSize 200K # You could specify # ReadOnlyFile /saved/specialvideo.ffm # This marks the file as readonly and it will not be deleted or updated. # Specify launch in order to start ffmpeg automatically. # First ffmpeg must be defined with an appropriate path if needed, # after that options can follow, but avoid adding the http:// field #Launch ffmpeg # Only allow connections from localhost to the feed. #ACL allow 127.0.0.1 #ACL allow 189.34.0.158 &lt;/Feed&gt; ################################################################## # Now you can define each stream which will be generated from the # original audio and video stream. Each format has a filename (here # 'test1.mpg'). FFServer will send this stream when answering a # request containing this filename. &lt;Stream test1.mpg&gt; # coming from live feed 'feed1' Feed feed1.ffm # Format of the stream : you can choose among: # mpeg : MPEG-1 multiplexed video and audio # mpegvideo : only MPEG-1 video # mp2 : MPEG-2 audio (use AudioCodec to select layer 2 and 3 codec) # ogg : Ogg format (Vorbis audio codec) # rm : RealNetworks-compatible stream. Multiplexed audio and video. # ra : RealNetworks-compatible stream. Audio only. # mpjpeg : Multipart JPEG (works with Netscape without any plugin) # jpeg : Generate a single JPEG image. # asf : ASF compatible streaming (Windows Media Player format). # swf : Macromedia Flash compatible stream # avi : AVI format (MPEG-4 video, MPEG audio sound) Format mpeg # Bitrate for the audio stream. Codecs usually support only a few # different bitrates. AudioBitRate 32 # Number of audio channels: 1 = mono, 2 = stereo AudioChannels 1 # Sampling frequency for audio. When using low bitrates, you should # lower this frequency to 22050 or 11025. The supported frequencies # depend on the selected audio codec. AudioSampleRate 44100 # Bitrate for the video stream VideoBitRate 64 # Ratecontrol buffer size VideoBufferSize 40 # Number of frames per second VideoFrameRate 3 # Size of the video frame: WxH (default: 160x128) # The following abbreviations are defined: sqcif, qcif, cif, 4cif, qqvga, # qvga, vga, svga, xga, uxga, qxga, sxga, qsxga, hsxga, wvga, wxga, wsxga, # wuxga, woxga, wqsxga, wquxga, whsxga, whuxga, cga, ega, hd480, hd720, # hd1080 VideoSize 160x128 # Transmit only intra frames (useful for low bitrates, but kills frame rate). #VideoIntraOnly # If non-intra only, an intra frame is transmitted every VideoGopSize # frames. Video synchronization can only begin at an intra frame. VideoGopSize 12 # More MPEG-4 parameters # VideoHighQuality # Video4MotionVector # Choose your codecs: #AudioCodec mp2 #VideoCodec mpeg1video # Suppress audio #NoAudio # Suppress video #NoVideo #VideoQMin 3 #VideoQMax 31 # Set this to the number of seconds backwards in time to start. Note that # most players will buffer 5-10 seconds of video, and also you need to allow # for a keyframe to appear in the data stream. #Preroll 15 # ACL: # You can allow ranges of addresses (or single addresses) #ACL ALLOW &lt;first address&gt; &lt;last address&gt; # You can deny ranges of addresses (or single addresses) #ACL DENY &lt;first address&gt; &lt;last address&gt; # You can repeat the ACL allow/deny as often as you like. It is on a per # stream basis. The first match defines the action. If there are no matches, # then the default is the inverse of the last ACL statement. # # Thus 'ACL allow localhost' only allows access from localhost. # 'ACL deny 1.0.0.0 1.255.255.255' would deny the whole of network 1 and # allow everybody else. &lt;/Stream&gt; ################################################################## # Example streams # Multipart JPEG #&lt;Stream test.mjpg&gt; #Feed feed1.ffm #Format mpjpeg #VideoFrameRate 2 #VideoIntraOnly #NoAudio #Strict -1 #&lt;/Stream&gt; # Single JPEG #&lt;Stream test.jpg&gt; #Feed feed1.ffm #Format jpeg #VideoFrameRate 2 #VideoIntraOnly ##VideoSize 352x240 #NoAudio #Strict -1 #&lt;/Stream&gt; # Flash #&lt;Stream test.swf&gt; #Feed feed1.ffm #Format swf #VideoFrameRate 2 #VideoIntraOnly #NoAudio #&lt;/Stream&gt; # ASF compatible &lt;Stream test.asf&gt; Feed feed1.ffm Format asf VideoFrameRate 15 VideoSize 352x240 VideoBitRate 256 VideoBufferSize 40 VideoGopSize 30 AudioBitRate 64 StartSendOnKey &lt;/Stream&gt; # MP3 audio #&lt;Stream test.mp3&gt; #Feed feed1.ffm #Format mp2 #AudioCodec mp3 #AudioBitRate 64 #AudioChannels 1 #AudioSampleRate 44100 #NoVideo #&lt;/Stream&gt; # Ogg Vorbis audio #&lt;Stream test.ogg&gt; #Feed feed1.ffm #Metadata title "Stream title" #AudioBitRate 64 #AudioChannels 2 #AudioSampleRate 44100 #NoVideo #&lt;/Stream&gt; # Real with audio only at 32 kbits #&lt;Stream test.ra&gt; #Feed feed1.ffm #Format rm #AudioBitRate 32 #NoVideo #NoAudio #&lt;/Stream&gt; # Real with audio and video at 64 kbits #&lt;Stream test.rm&gt; #Feed feed1.ffm #Format rm #AudioBitRate 32 #VideoBitRate 128 #VideoFrameRate 25 #VideoGopSize 25 #NoAudio #&lt;/Stream&gt; ################################################################## # A stream coming from a file: you only need to set the input # filename and optionally a new format. Supported conversions: # AVI -&gt; ASF #&lt;Stream file.rm&gt; #File "/usr/local/httpd/htdocs/tlive.rm" #NoAudio #&lt;/Stream&gt; #&lt;Stream file.asf&gt; #File "/usr/local/httpd/htdocs/test.asf" #NoAudio #Metadata author "Me" #Metadata copyright "Super MegaCorp" #Metadata title "Test stream from disk" #Metadata comment "Test comment" #&lt;/Stream&gt; ################################################################## # RTSP examples # # You can access this stream with the RTSP URL: # rtsp://localhost:5454/test1-rtsp.mpg # # A non-standard RTSP redirector is also created. Its URL is: # http://localhost:8090/test1-rtsp.rtsp #&lt;Stream test1-rtsp.mpg&gt; #Format rtp #File "/usr/local/httpd/htdocs/test1.mpg" #&lt;/Stream&gt; # Transcode an incoming live feed to another live feed, # using libx264 and video presets #&lt;Stream live.h264&gt; #Format rtp #Feed feed1.ffm #VideoCodec libx264 #VideoFrameRate 24 #VideoBitRate 100 #VideoSize 480x272 #AVPresetVideo default #AVPresetVideo baseline #AVOptionVideo flags +global_header # #AudioCodec libfaac #AudioBitRate 32 #AudioChannels 2 #AudioSampleRate 22050 #AVOptionAudio flags +global_header #&lt;/Stream&gt; ################################################################## # SDP/multicast examples # # If you want to send your stream in multicast, you must set the # multicast address with MulticastAddress. The port and the TTL can # also be set. # # An SDP file is automatically generated by ffserver by adding the # 'sdp' extension to the stream name (here # http://localhost:8090/test1-sdp.sdp). You should usually give this # file to your player to play the stream. # # The 'NoLoop' option can be used to avoid looping when the stream is # terminated. #&lt;Stream test1-sdp.mpg&gt; #Format rtp #File "/usr/local/httpd/htdocs/test1.mpg" #MulticastAddress 224.124.0.1 #MulticastPort 5000 #MulticastTTL 16 #NoLoop #&lt;/Stream&gt; ################################################################## # Special streams # Server status &lt;Stream stat.html&gt; Format status # Only allow local people to get the status ACL allow localhost ACL allow 192.168.0.0 192.168.255.255 #FaviconURL http://pond1.gladstonefamily.net:8080/favicon.ico &lt;/Stream&gt; # Redirect index.html to the appropriate site &lt;Redirect index.html&gt; URL http://www.ffmpeg.org/ &lt;/Redirect&gt; </code></pre> <p>I started my server and executed:</p> <pre><code>ffserver -d -f /usr/share/doc/ffmpeg-2.6.8/ffserver.conf </code></pre> <p>No error message and everything looks fine.</p> <p>After that I execute this (in your answer, I think you forgot the port number):</p> <pre><code>ffmpeg -i "rtsp://200.180.90.95:554/onvif1" -r 25 -s 640x480 -c:v libx264 -flags +global_header -f flv "http://45.79.207.38:8090/feed1.ffm" </code></pre> <p>Then I get this log:</p> <pre><code> libavutil 54. 20.100 / 54. 20.100 libavcodec 56. 26.100 / 56. 26.100 libavformat 56. 25.101 / 56. 25.101 libavdevice 56. 4.100 / 56. 4.100 libavfilter 5. 11.102 / 5. 11.102 libavresample 2. 1. 0 / 2. 1. 0 libswscale 3. 1.101 / 3. 1.101 libswresample 1. 1.100 / 1. 1.100 libpostproc 53. 3.100 / 53. 3.100 [h264 @ 0x1a23580] RTP: missed 1 packets [pcm_alaw @ 0x1a24360] RTP: missed 2 packets [h264 @ 0x1a23580] RTP: missed 1 packets Invalid UE golomb code [h264 @ 0x1a23580] cbp too large (3199971767) at 76 33 [h264 @ 0x1a23580] error while decoding MB 76 33 [h264 @ 0x1a23580] Cannot use next picture in error concealment [h264 @ 0x1a23580] concealing 933 DC, 933 AC, 933 MV errors in P frame [h264 @ 0x1a23580] RTP: missed 1 packets [h264 @ 0x1a23580] cbp too large (62) at 50 24 [h264 @ 0x1a23580] error while decoding MB 50 24 [h264 @ 0x1a23580] Cannot use next picture in error concealment [h264 @ 0x1a23580] concealing 1679 DC, 1679 AC, 1679 MV errors in P frame [h264 @ 0x1a23580] RTP: missed 2 packets [h264 @ 0x1a23580] Cannot use next picture in error concealment [h264 @ 0x1a23580] concealing 1965 DC, 1965 AC, 1965 MV errors in P frame [pcm_alaw @ 0x1a24360] RTP: missed 1 packets Last message repeated 1 times [h264 @ 0x1a23580] RTP: missed 3 packets [h264 @ 0x1a23580] mb_type 49 in P slice too large at 74 25 [h264 @ 0x1a23580] error while decoding MB 74 25 [h264 @ 0x1a23580] Cannot use next picture in error concealment [h264 @ 0x1a23580] concealing 1575 DC, 1575 AC, 1575 MV errors in P frame [h264 @ 0x1a23580] RTP: missed 2 packets [h264 @ 0x1a23580] P sub_mb_type 29 out of range at 30 26 [h264 @ 0x1a23580] error while decoding MB 30 26 [h264 @ 0x1a23580] Cannot use next picture in error concealment [h264 @ 0x1a23580] concealing 1539 DC, 1539 AC, 1539 MV errors in P frame [h264 @ 0x1a23580] RTP: missed 1 packets [h264 @ 0x1a23580] out of range intra chroma pred mode at 72 29 [h264 @ 0x1a23580] error while decoding MB 72 29 [h264 @ 0x1a23580] Cannot use next picture in error concealment [h264 @ 0x1a23580] concealing 1257 DC, 1257 AC, 1257 MV errors in P frame [h264 @ 0x1a23580] RTP: missed 3 packets [h264 @ 0x1a23580] negative number of zero coeffs at 48 5 [h264 @ 0x1a23580] error while decoding MB 48 5 [h264 @ 0x1a23580] Cannot use next picture in error concealment [h264 @ 0x1a23580] concealing 3201 DC, 3201 AC, 3201 MV errors in P frame [pcm_alaw @ 0x1a24360] RTP: missed 1 packets [rtsp @ 0x1a20ee0] decoding for stream 0 failed Guessed Channel Layout for Input Stream #0.1 : mono Input #0, rtsp, from 'rtsp://200.180.90.95:554/onvif1': Metadata: title : H.264 Video, RtspServer_0.0.0.2 Duration: N/A, start: 0.000000, bitrate: N/A Stream #0:0: Video: h264 (Baseline), yuv420p, 1280x720, 90k tbr, 90k tbn, 180k tbc Stream #0:1: Audio: pcm_alaw, 8000 Hz, 1 channels, s16, 64 kb/s [libx264 @ 0x1b728a0] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX AVX2 FMA3 LZCNT BMI2 [libx264 @ 0x1b728a0] profile High, level 3.0 [libx264 @ 0x1b728a0] 264 - core 142 r2495 6a301b6 - H.264/MPEG-4 AVC codec - Copyleft 2003-2014 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=1 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00 [flv @ 0x1a66300] FLV does not support sample rate 8000, choose from (44100, 22050, 11025) [flv @ 0x1a66300] Audio codec mp3 not compatible with flv Output #0, flv, to 'http://45.79.207.38:8090/feed1.ffm': Metadata: title : H.264 Video, RtspServer_0.0.0.2 encoder : Lavf56.25.101 Stream #0:0: Video: h264 (libx264) ([7][0][0][0] / 0x0007), yuv420p, 640x480, q=-1--1, 25 fps, 1k tbn, 25 tbc Metadata: encoder : Lavc56.26.100 libx264 Stream #0:1: Audio: mp3 (libmp3lame) ([2][0][0][0] / 0x0002), 8000 Hz, mono, s16p Metadata: encoder : Lavc56.26.100 libmp3lame Stream mapping: Stream #0:0 -&gt; #0:0 (h264 (native) -&gt; h264 (libx264)) Stream #0:1 -&gt; #0:1 (pcm_alaw (native) -&gt; mp3 (libmp3lame)) Could not write header for output file #0 (incorrect codec parameters ?): Function not implemented </code></pre> <p>I am doing this in a clean install of CENTOS, no customization. Could you please helpe me?</p>
0
5,336
I can't run "bundle update" because of "mysql2" gem
<p>I have this in the Gemfile:</p> <pre><code>gem 'mysql2' </code></pre> <p>But when I run <strong>bundle update</strong>, I get this error message:</p> <pre><code>An error occurred while installing mysql2 (0.3.16), and Bundler cannot continue. Make sure that `gem install mysql2 -v '0.3.16'` succeeds before bundling. </code></pre> <p>I've tried to move this into the production section, like this:</p> <pre><code>group :production do gem 'mysql2' end </code></pre> <p>But after running <strong>bundle update</strong>, the result is the same. This section is processed only in the production mode, or not?</p> <p>How to get rid of this error message on localhost?</p> <p><strong>EDIT: The whole error message:</strong></p> <pre><code>Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension. /Users/radek/.rvm/rubies/ruby-1.9.3-p385/bin/ruby extconf.rb checking for ruby/thread.h... *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/Users/radek/.rvm/rubies/ruby-1.9.3-p385/bin/ruby /Users/radek/.rvm/rubies/ruby-1.9.3-p385/lib/ruby/1.9.1/mkmf.rb:381:in `try_do': The compiler failed to generate an executable file. (RuntimeError) You have to install development tools first. from /Users/radek/.rvm/rubies/ruby-1.9.3-p385/lib/ruby/1.9.1/mkmf.rb:506:in `try_cpp' from /Users/radek/.rvm/rubies/ruby-1.9.3-p385/lib/ruby/1.9.1/mkmf.rb:931:in `block in have_header' from /Users/radek/.rvm/rubies/ruby-1.9.3-p385/lib/ruby/1.9.1/mkmf.rb:790:in `block in checking_for' from /Users/radek/.rvm/rubies/ruby-1.9.3-p385/lib/ruby/1.9.1/mkmf.rb:284:in `block (2 levels) in postpone' from /Users/radek/.rvm/rubies/ruby-1.9.3-p385/lib/ruby/1.9.1/mkmf.rb:254:in `open' from /Users/radek/.rvm/rubies/ruby-1.9.3-p385/lib/ruby/1.9.1/mkmf.rb:284:in `block in postpone' from /Users/radek/.rvm/rubies/ruby-1.9.3-p385/lib/ruby/1.9.1/mkmf.rb:254:in `open' from /Users/radek/.rvm/rubies/ruby-1.9.3-p385/lib/ruby/1.9.1/mkmf.rb:280:in `postpone' from /Users/radek/.rvm/rubies/ruby-1.9.3-p385/lib/ruby/1.9.1/mkmf.rb:789:in `checking_for' from /Users/radek/.rvm/rubies/ruby-1.9.3-p385/lib/ruby/1.9.1/mkmf.rb:930:in `have_header' from extconf.rb:9:in `&lt;main&gt;' Gem files will remain installed in /Users/radek/.rvm/gems/ruby-1.9.3-p385/gems/mysql2-0.3.16 for inspection. Results logged to /Users/radek/.rvm/gems/ruby-1.9.3-p385/gems/mysql2-0.3.16/ext/mysql2/gem_make.out An error occurred while installing mysql2 (0.3.16), and Bundler cannot continue. Make sure that `gem install mysql2 -v '0.3.16'` succeeds before bundling. </code></pre> <p>Thank you</p>
0
1,305
Using clang++, -fvisibility=hidden, and typeinfo, and type-erasure
<p>This is a scaled down version of a problem I am facing with clang++ on Mac OS X. This was seriously edited to better reflect the genuine problem (the first attempt to describe the issue was not exhibiting the problem).</p> <h1>The failure</h1> <p>I have this big piece of software in C++ with a large set of symbols in the object files, so I'm using <code>-fvisibility=hidden</code> to keep my symbol tables small. It is well known that in such a case one must pay extra attention to the vtables, and I suppose I face this problem. I don't know however, how to address it elegantly in a way that pleases both gcc and clang.</p> <p>Consider a <code>base</code> class which features a down-casting operator, <code>as</code>, and a <code>derived</code> class template, that contains some payload. The pair <code>base</code>/<code>derived&lt;T&gt;</code> is used to implement type-erasure:</p> <pre><code>// foo.hh #define API __attribute__((visibility("default"))) struct API base { virtual ~base() {} template &lt;typename T&gt; const T&amp; as() const { return dynamic_cast&lt;const T&amp;&gt;(*this); } }; template &lt;typename T&gt; struct API derived: base {}; struct payload {}; // *not* flagged as "default visibility". API void bar(const base&amp; b); API void baz(const base&amp; b); </code></pre> <p>Then I have two different compilation units that provide a similar service, which I can approximate as twice the same feature: down-casting from <code>base</code> to <code>derive&lt;payload&gt;</code>:</p> <pre><code>// bar.cc #include "foo.hh" void bar(const base&amp; b) { b.as&lt;derived&lt;payload&gt;&gt;(); } </code></pre> <p>and</p> <pre><code>// baz.cc #include "foo.hh" void baz(const base&amp; b) { b.as&lt;derived&lt;payload&gt;&gt;(); } </code></pre> <p>From these two files, I build a dylib. Here is the <code>main</code> function, calling these functions from the dylib:</p> <pre><code>// main.cc #include &lt;stdexcept&gt; #include &lt;iostream&gt; #include "foo.hh" int main() try { derived&lt;payload&gt; d; bar(d); baz(d); } catch (std::exception&amp; e) { std::cerr &lt;&lt; e.what() &lt;&lt; std::endl; } </code></pre> <p>Finally, a Makefile to compile and link everybody. Nothing special here, except, of course, <code>-fvisibility=hidden</code>.</p> <pre><code>CXX = clang++ CXXFLAGS = -std=c++11 -fvisibility=hidden all: main main: main.o bar.dylib baz.dylib $(CXX) -o $@ $^ %.dylib: %.cc foo.hh $(CXX) $(CXXFLAGS) -shared -o $@ $&lt; %.o: %.cc foo.hh $(CXX) $(CXXFLAGS) -c -o $@ $&lt; clean: rm -f main main.o bar.o baz.o bar.dylib baz.dylib libba.dylib </code></pre> <p>The run succeeds with gcc (4.8) on OS X:</p> <pre><code>$ make clean &amp;&amp; make CXX=g++-mp-4.8 &amp;&amp; ./main rm -f main main.o bar.o baz.o bar.dylib baz.dylib libba.dylib g++-mp-4.8 -std=c++11 -fvisibility=hidden -c main.cc -o main.o g++-mp-4.8 -std=c++11 -fvisibility=hidden -shared -o bar.dylib bar.cc g++-mp-4.8 -std=c++11 -fvisibility=hidden -shared -o baz.dylib baz.cc g++-mp-4.8 -o main main.o bar.dylib baz.dylib </code></pre> <p>However with clang (3.4), this fails:</p> <pre><code>$ make clean &amp;&amp; make CXX=clang++-mp-3.4 &amp;&amp; ./main rm -f main main.o bar.o baz.o bar.dylib baz.dylib libba.dylib clang++-mp-3.4 -std=c++11 -fvisibility=hidden -c main.cc -o main.o clang++-mp-3.4 -std=c++11 -fvisibility=hidden -shared -o bar.dylib bar.cc clang++-mp-3.4 -std=c++11 -fvisibility=hidden -shared -o baz.dylib baz.cc clang++-mp-3.4 -o main main.o bar.dylib baz.dylib std::bad_cast </code></pre> <p>However it works if I use</p> <pre><code>struct API payload {}; </code></pre> <p>but I do not want to expose the payload type. So my questions are:</p> <ol> <li>why are GCC and Clang different here?</li> <li>is it <em>really</em> working with GCC, or I was just "lucky" in my use of undefined behavior?</li> <li>do I have a means to avoid making <code>payload</code> go public with Clang++?</li> </ol> <p>Thanks in advance.</p> <h1>Type equality of visible class templates with invisible type parameters (EDIT)</h1> <p>I have now a better understanding of what is happening. It is appears that both GCC <em>and</em> clang require both the class template and its parameter to be visible (in the ELF sense) to build a unique type. If you change the <code>bar.cc</code> and <code>baz.cc</code> functions as follows:</p> <pre><code>// bar.cc #include "foo.hh" void bar(const base&amp; b) { std::cerr &lt;&lt; "bar value: " &lt;&lt; &amp;typeid(b) &lt;&lt; std::endl &lt;&lt; "bar type: " &lt;&lt; &amp;typeid(derived&lt;payload&gt;) &lt;&lt; std::endl &lt;&lt; "bar equal: " &lt;&lt; (typeid(b) == typeid(derived&lt;payload&gt;)) &lt;&lt; std::endl; b.as&lt;derived&lt;payload&gt;&gt;(); } </code></pre> <p>and <em>if</em> you make <code>payload</code> visible too:</p> <pre><code>struct API payload {}; </code></pre> <p>then you will see that both GCC and Clang will succeed:</p> <pre><code>$ make clean &amp;&amp; make CXX=g++-mp-4.8 rm -f main main.o bar.o baz.o bar.dylib baz.dylib libba.dylib g++-mp-4.8 -std=c++11 -fvisibility=hidden -c -o main.o main.cc g++-mp-4.8 -std=c++11 -fvisibility=hidden -shared -o bar.dylib bar.cc g++-mp-4.8 -std=c++11 -fvisibility=hidden -shared -o baz.dylib baz.cc ./g++-mp-4.8 -o main main.o bar.dylib baz.dylib $ ./main bar value: 0x106785140 bar type: 0x106785140 bar equal: 1 baz value: 0x106785140 baz type: 0x106785140 baz equal: 1 $ make clean &amp;&amp; make CXX=clang++-mp-3.4 rm -f main main.o bar.o baz.o bar.dylib baz.dylib libba.dylib clang++-mp-3.4 -std=c++11 -fvisibility=hidden -c -o main.o main.cc clang++-mp-3.4 -std=c++11 -fvisibility=hidden -shared -o bar.dylib bar.cc clang++-mp-3.4 -std=c++11 -fvisibility=hidden -shared -o baz.dylib baz.cc clang++-mp-3.4 -o main main.o bar.dylib baz.dylib $ ./main bar value: 0x10a6d5110 bar type: 0x10a6d5110 bar equal: 1 baz value: 0x10a6d5110 baz type: 0x10a6d5110 baz equal: 1 </code></pre> <p>Type equality is easy to check, there is actually a single instantiation of the type, as witnessed by its unique address.</p> <p>However, if you remove the visible attribute from <code>payload</code>:</p> <pre><code>struct payload {}; </code></pre> <p>then you get with GCC:</p> <pre><code>$ make clean &amp;&amp; make CXX=g++-mp-4.8 rm -f main main.o bar.o baz.o bar.dylib baz.dylib libba.dylib g++-mp-4.8 -std=c++11 -fvisibility=hidden -c -o main.o main.cc g++-mp-4.8 -std=c++11 -fvisibility=hidden -shared -o bar.dylib bar.cc g++-mp-4.8 -std=c++11 -fvisibility=hidden -shared -o baz.dylib baz.cc g++-mp-4.8 -o main main.o bar.dylib baz.dylib $ ./main bar value: 0x10faea120 bar type: 0x10faf1090 bar equal: 1 baz value: 0x10faea120 baz type: 0x10fafb090 baz equal: 1 </code></pre> <p>Now there are several instantiation of the type <code>derived&lt;payload&gt;</code> (as witnessed by the three different addresses), but GCC sees these types are equal, and (of course) the two <code>dynamic_cast</code> pass.</p> <p>In the case of clang, it's different:</p> <pre><code>$ make clean &amp;&amp; make CXX=clang++-mp-3.4 rm -f main main.o bar.o baz.o bar.dylib baz.dylib libba.dylib clang++-mp-3.4 -std=c++11 -fvisibility=hidden -c -o main.o main.cc clang++-mp-3.4 -std=c++11 -fvisibility=hidden -shared -o bar.dylib bar.cc clang++-mp-3.4 -std=c++11 -fvisibility=hidden -shared -o baz.dylib baz.cc .clang++-mp-3.4 -o main main.o bar.dylib baz.dylib $ ./main bar value: 0x1012ae0f0 bar type: 0x1012b3090 bar equal: 0 std::bad_cast </code></pre> <p>There are also three instantiations of the type (removing the failing <code>dynamic_cast</code> does show that there are three), but this time, they are not equal, and the <code>dynamic_cast</code> (of course) fails.</p> <p>Now the question turns into: 1. is this difference between both compilers wanted by their authors 2. if not, what is "expected" behavior between both</p> <p>I prefer GCC's semantics, as it allows to really implement type-erasure without any need to expose publicly the wrapped types.</p>
0
3,240
How to hide ToolBar when I scrolling content up?
<p>I am trying to hide my tool bar when I scroll my text and image with content. Here I use scrollView for getting scroll content. When I scroll content up, how to hide the tool bar?</p> <p>Here is my XMl code:</p> <p>content_main.XML:</p> <pre><code>&lt;android.support.v4.widget.NestedScrollView xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; app:layout_behavior=&quot;@string/appbar_scrolling_view_behavior&quot;&gt; &lt;LinearLayout android:orientation=&quot;vertical&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot;&gt; &lt;LinearLayout android:paddingTop=&quot;?android:attr/actionBarSize&quot; android:orientation=&quot;vertical&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot;&gt; &lt;TextView android:layout_marginLeft=&quot;10dp&quot; android:layout_marginRight=&quot;10dp&quot; android:id=&quot;@+id/textone&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:textSize=&quot;23dp&quot; android:textStyle=&quot;bold&quot; android:text=&quot;hello world jheds sdjhs jds sjbs skjs ksjs kksjs ksj sdd dskd js sk &quot;/&gt; &lt;ImageView android:id=&quot;@+id/imge&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;250dp&quot; android:src=&quot;@drawable/imag_bg&quot;/&gt; &lt;TextView android:id=&quot;@+id/texttwo&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:layout_marginLeft=&quot;10dp&quot; android:layout_marginRight=&quot;10dp&quot; android:text=&quot;Pretty good, the Toolbar is moving along with the list and getting back just as we expect it to. This is thanks to the restrictions that we put on the mToolbarOffset variable. If we would omit checking if it’s bigger than 0 and lower than mToolbarHeight then when we would scroll up our list, the Toolbar would move along far away off the screen, so to show it back you would have to scroll the list down to 0. Right now it just scrolls up to mToolbarHeight position and not more so it’s “sitting” right above the list all of the time and if we start scrolling down, we can see it immediately showing. up our list, the Toolbar would move along far away off the screen, so to show it back you would have to scroll the list down to 0. Right now it just scrolls up to mToolbarHeight position and not more so it’s “sitting” right above the list all of the time and if we start scrolling down, we can see it immediately showing up our list, the Toolbar would move along far away off the screen, so to show it back you would have to scroll the list down to 0. Right now it just scrolls up to mToolbarHeight position and not more so it’s “sitting” right above the list all of the time and if we start scrolling down, we can see it immediately showing up our list, the Toolbar would move along far away off the screen, so to show it back you would have to scroll the list down to 0. Right now it just scrolls up to mToolbarHeight position and not more so it’s “sitting” right above the list all of the time and if we start scrolling down, we can see it immediately showing up our list, the Toolbar would move along far away off the screen, so to show it back you would have to scroll the list down to 0. Right now it just scrolls up to mToolbarHeight position and not more so it’s “sitting” right above the list all of the time and if we start scrolling down, we can see it immediately showing up our list, the Toolbar would move along far away off the screen, so to show it back you would have to scroll the list down to 0. Right now it just scrolls up to mToolbarHeight position and not more so it’s “sitting” right above the list all of the time and if we start scrolling down, we can see it immediately showing It works pretty well, but this is not what we want. It feels weird that you can stop it in the middle of the scroll and the Toolbar will stay half visible. Actually this is how it’s done in Google Play Games app which I consider as a bug It works pretty well, but this is not what we want. It feels weird that you can stop it in the middle of the scroll and the Toolbar will stay half visible. Actually this is how it’s done in Google Play Games app which I consider as a bug It works pretty well, but this is not what we want. It feels weird that you can stop it in the middle of the scroll and the Toolbar will stay half visible. Actually this is how it’s done in Google Play Games app which I consider as a bug.&quot;/&gt; &lt;/LinearLayout&gt; &lt;View android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;30dp&quot; /&gt; &lt;LinearLayout android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot;&gt; &lt;Button android:text=&quot;hai&quot; android:layout_width=&quot;160dp&quot; android:layout_height=&quot;match_parent&quot; /&gt; &lt;Button android:text=&quot;hello&quot; android:layout_width=&quot;160dp&quot; android:layout_height=&quot;match_parent&quot; /&gt; &lt;/LinearLayout&gt; </code></pre> <p>&lt;/android.support.v4.widget.NestedScrollView&gt;</p> <p>activity_main.XML</p> <pre><code>&lt;android.support.design.widget.AppBarLayout android:layout_height=&quot;wrap_content&quot; android:layout_width=&quot;match_parent&quot; android:theme=&quot;@style/AppTheme.AppBarOverlay&quot;&gt; &lt;android.support.v7.widget.Toolbar android:id=&quot;@+id/toolbar&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;?attr/actionBarSize&quot; android:background=&quot;?attr/colorPrimary&quot; app:popupTheme=&quot;@style/AppTheme.PopupOverlay&quot; /&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;include layout=&quot;@layout/content_main&quot; /&gt; </code></pre> <p><a href="https://i.stack.imgur.com/4CN3S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4CN3S.png" alt="here my image" /></a></p>
0
2,729
Getting WindowsIdentity in my WCF Web Service
<p>I took over code from a developer that is no longer with us. It's a WCF web service that was originally using a passed in username, but we need it to use the WindowsIdentity instead.</p> <pre><code>string identity = ServiceSecurityContext.Current.WindowsIdentity.Name; </code></pre> <p>That code ends up returning an empty string. I'm using a secure (wsHttpSecure) binding so ServiceSecurityContext.Current isn't null or anything. I've been searching for a solution for a day and haven't found anything yet.</p> <p>Because I'm new to WCF I'm not sure what other information will be relevant. Here are the enabled authentication settings for the web service in IIS:</p> <pre><code>Anonymous Authentication - Enabled Windows Authentication - Enabled </code></pre> <p>And here's the web.config for the web service:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;configuration&gt; &lt;connectionStrings&gt; &lt;clear /&gt; &lt;add name="LocalSqlServer" connectionString="Data Source=.\instanceNameHere;Initial Catalog=default;Integrated Security=SSPI;"/&gt; &lt;/connectionStrings&gt; &lt;appSettings configSource="appSettings.config" /&gt; &lt;system.diagnostics&gt; &lt;sources&gt; &lt;source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true"&gt; &lt;listeners&gt; &lt;add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="c:\ServiceLogs\WebServiceLog.svclog" /&gt; &lt;/listeners&gt; &lt;/source&gt; &lt;/sources&gt; &lt;/system.diagnostics&gt; &lt;system.web&gt; &lt;trace enabled="true" /&gt; &lt;membership defaultProvider="XIMembershipProvider" userIsOnlineTimeWindow="30"&gt; &lt;providers&gt; &lt;clear/&gt; &lt;add name="XIMembershipProvider" type="LolSoftware.MiddleTier.BusinessLogic.XIMembershipProvider" applicationName="LolWebService"/&gt; &lt;/providers&gt; &lt;/membership&gt; &lt;compilation debug="true" targetFramework="4.0" /&gt; &lt;/system.web&gt; &lt;system.serviceModel&gt; &lt;client /&gt; &lt;serviceHostingEnvironment multipleSiteBindingsEnabled="true" /&gt; &lt;behaviors configSource="behaviors.config" /&gt; &lt;bindings configSource="bindings.config" /&gt; &lt;services configSource="services.config" /&gt; &lt;/system.serviceModel&gt; &lt;system.webServer&gt; &lt;modules runAllManagedModulesForAllRequests="true" /&gt; &lt;handlers&gt; &lt;remove name="svc-ISAPI-4.0_64bit"/&gt; &lt;remove name="svc-ISAPI-4.0"/&gt; &lt;remove name="svc-Integrated-4.0"/&gt; &lt;add name="svc-ISAPI-4.0_64bit" path="*.svc" verb="*" modules="IsapiModule" scriptProcessor="%systemroot%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" preCondition="classicMode,runtimeVersionv4.0,bitness64" /&gt; &lt;add name="svc-ISAPI-4.0" path="*.svc" verb="*" modules="IsapiModule" scriptProcessor="%systemroot%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" preCondition="classicMode,runtimeVersionv4.0,bitness32" /&gt; &lt;add name="svc-Integrated-4.0" path="*.svc" verb="*" type="System.ServiceModel.Activation.HttpHandler, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" resourceType="Unspecified" preCondition="integratedMode" /&gt; &lt;/handlers&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>As well as bindings.config:</p> <pre><code>&lt;bindings&gt; &lt;wsHttpBinding&gt; &lt;binding name="wsHttpSecure"&gt; &lt;security mode="TransportWithMessageCredential"&gt; &lt;transport clientCredentialType="None" /&gt; &lt;message clientCredentialType="UserName" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;binding name="wsHttp"&gt; &lt;security mode="None" /&gt; &lt;/binding&gt; &lt;/wsHttpBinding&gt; &lt;/bindings&gt; </code></pre> <p>Behaviors.config:</p> <pre><code>&lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="serviceBehavior"&gt; &lt;serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" /&gt; &lt;serviceDebug includeExceptionDetailInFaults="true" /&gt; &lt;serviceThrottling maxConcurrentCalls="200" maxConcurrentSessions="200" /&gt; &lt;serviceCredentials&gt; &lt;userNameAuthentication userNamePasswordValidationMode="MembershipProvider" membershipProviderName="XIMembershipProvider"/&gt; &lt;/serviceCredentials&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;!-- --&gt; &lt;endpointBehaviors&gt; &lt;behavior name="restBehavior"&gt; &lt;webHttp/&gt; &lt;/behavior&gt; &lt;/endpointBehaviors&gt; &lt;!-- --&gt; &lt;/behaviors&gt; </code></pre> <p>Service.config:</p> <pre><code>&lt;services&gt; &lt;service name="LolSoftware.MiddleTier.WebService.LolWebService" behaviorConfiguration="serviceBehavior"&gt; &lt;endpoint name="LolWebService_WSHttpEndpointSecure" contract="LolSoftware.MiddleTier.Interfaces.ILolWebService" binding="wsHttpBinding" bindingConfiguration="wsHttpSecure"/&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /&gt; &lt;/service&gt; &lt;/services&gt; </code></pre> <p>Thanks in advance.</p>
0
2,406
Undefined Symbols for architecture x86_64: Compiling problems
<p>So I am trying to start an assignment, my professor gives us a Main.cpp, Main.h, Scanner.cpp, Scanner.h, and some other utilities.</p> <p>My job is to create a Similarity class to compare documents using the cosine and Jaccard coefficients. However, I can not seem to get the project linked correctly, therefore I am unable to start on the actual code.</p> <p>After trying for several hours to see what I am doing wrong, I need fresh eyes to see what I am doing wrong, I suspect it is obvious.</p> <p>Here is the Main.cpp</p> <pre><code>#include "Main.h" using namespace std; static const string TAG = "Main: "; int main(int argc, char *argv[]) { string inStreamName; string logStreamName; string outStreamName; ofstream outStream; string timeCallOutput; Scanner inStream; Similarity similarity; /////////////////////////////////////////////////////////////// // Boilerplate for naming files and opening files Utils::CheckArgs(3, argc, argv, "infilename outfilename logfilename"); outStreamName = static_cast&lt;string&gt;(argv[2]); logStreamName = static_cast&lt;string&gt;(argv[3]); Utils::FileOpen(outStream, outStreamName); Utils::LogFileOpen(logStreamName); timeCallOutput = Utils::timecall("beginning"); Utils::logStream &lt;&lt; timeCallOutput &lt;&lt; endl; Utils::logStream &lt;&lt; TAG &lt;&lt; "Beginning execution" &lt;&lt; endl; Utils::logStream &lt;&lt; TAG &lt;&lt; "outfile '" &lt;&lt; outStreamName &lt;&lt; "'" &lt;&lt; endl; Utils::logStream &lt;&lt; TAG &lt;&lt; "logfile '" &lt;&lt; logStreamName &lt;&lt; "'" &lt;&lt; endl; Utils::logStream.flush(); /////////////////////////////////////////////////////////////// // What follows here is the real work of this code. // read the entire input file and echo it back // compute the two similarity coefficients inStreamName = static_cast&lt;string&gt;(argv[1]); inStream.openFile(inStreamName); Utils::logStream &lt;&lt; TAG &lt;&lt; "infile '" &lt;&lt; inStreamName &lt;&lt; "'" &lt;&lt; endl; Utils::logStream.flush(); similarity.readData(inStream); outStream &lt;&lt; TAG &lt;&lt; "Data Begin\n" &lt;&lt; similarity.toString() &lt;&lt; endl; outStream &lt;&lt; TAG &lt;&lt; "Data End\n" &lt;&lt; endl; outStream.flush(); inStream.close(); outStream &lt;&lt; TAG &lt;&lt; "Begin similarity computation" &lt;&lt; endl; outStream &lt;&lt; TAG &lt;&lt; "Maximum Jaccard similarity:\n" &lt;&lt; similarity.maxJaccard() &lt;&lt; endl; outStream &lt;&lt; TAG &lt;&lt; "Maximum cosine similarity:\n" &lt;&lt; similarity.maxCosine() &lt;&lt; endl; outStream &lt;&lt; TAG &lt;&lt; "End similarity computation" &lt;&lt; endl; outStream.flush(); /////////////////////////////////////////////////////////////// // Boilerplate for terminating gracefully Utils::logStream &lt;&lt; TAG &lt;&lt; "Ending execution" &lt;&lt; endl; timeCallOutput = Utils::timecall("ending"); Utils::logStream &lt;&lt; timeCallOutput &lt;&lt; endl; Utils::logStream.flush(); outStream.flush(); Utils::FileClose(outStream); Utils::FileClose(Utils::logStream); return 0; } </code></pre> <p>And the Main.h</p> <pre><code>#ifndef MAIN_H #define MAIN_H #include "../../Utilities/Utils.h" #include "../../Utilities/Scanner.h" #include "Similarity.h" class Main { public: int main(); virtual ~Main(); private: }; #endif // MAIN_H </code></pre> <p>My Similarity.cpp</p> <pre><code>#include "Similarity.h" using namespace std; void readData(Scanner&amp; inStream){ } string maxCosine(){ return "cosine"; } string maxJaccard(){ return "jaccard"; } string toString(){ return "toString"; } </code></pre> <p>And finally my Similarity.h:</p> <pre><code>#ifndef SIMILARITY_H #define SIMILARITY_H #include "../../Utilities/Scanner.h" class Similarity { public: Similarity(); virtual ~Similarity(); void readData(Scanner&amp; inStream); string maxCosine(); string maxJaccard(); string toString(); private: }; #endif </code></pre> <p>When I use the makefile he provided, and the one I have to use in order for his script to work to grade it I get this error:</p> <pre><code>g++ -O3 -Wall -o Similarity.o -c Similarity.cpp g++ -O3 -Wall -o Aprog Main.o Similarity.o Scanner.o ScanLine.o Utils.o Undefined symbols for architecture x86_64: "Similarity::maxJaccard()", referenced from: _main in Main.o "Similarity::readData(Scanner&amp;)", referenced from: _main in Main.o "Similarity::toString()", referenced from: _main in Main.o "Similarity::maxCosine()", referenced from: _main in Main.o "Similarity::Similarity()", referenced from: _main in Main.o "Similarity::~Similarity()", referenced from: _main in Main.o ld: symbol(s) not found for architecture x86_64 collect2: ld returned 1 exit status make: *** [Aprog] Error 1 </code></pre> <p>Thank you for reading through all that, any suggestions or solutions would be greatly appreciated.</p>
0
1,857
how to resolve org.apache.commons.dbcp.SQLNestedException
<p>I am using hsqldb standalone as my database. i have a <code>hsqldb.jar(hsqldb-2.0.0)</code> which i added on my project build path so my project will find out where is my <code>hsqldb.jar</code>. i am using spring with these. my spring bean is:</p> <pre><code>&lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"&gt; &lt;property name="dataSource"&gt; &lt;ref local="adapterDataSource" /&gt; &lt;/property&gt; &lt;property name="configLocation" value="classpath:/com/hsqldb/example/dao/ibatis/SqlMapConfig.xml" /&gt; &lt;/bean&gt; &lt;bean id="adapterDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt; &lt;property name="driverClassName" value="org.hsqldb.jdbcDriver" /&gt; &lt;property name="url" value="data/db/hsqldb.jar" /&gt; &lt;property name="username" value="SA" /&gt; &lt;property name="password" value="password" /&gt; &lt;/bean&gt; &lt;bean id="testingDao" class="com.hsqldb.example.dao.TestingDao" init-method="setTestDao" depends-on="moodleAuthenticationDetails"&gt; &lt;property name="sqlMapClient"&gt; &lt;ref local="sqlMapClient" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="moodleAuthenticationDetails" class="com.hsqldb.example.HsqlDBAuthentication"&gt;&lt;/bean&gt; &lt;/beans&gt; </code></pre> <p>and i have a method which will return me a data source which is as below :</p> <pre><code>public static DataSource getDataSource(String filePath){ String url; //url="jdbc:hsqldb:file:"+filePath; url = "jdbc:hsqldb:file:D:/EclipseWorskpace/ew-pg/lmexadapter/hsqldb-example/src/main/webapp/WEB-INF/data/db/hsqldb.jar"; BasicDataSource basicDataSource = new BasicDataSource(); basicDataSource.setUsername("SA"); basicDataSource.setPassword("password"); basicDataSource.setDriverClassName("org.hsqldb.jdbc.JDBCDriver"); // basicDataSource.setUrl("jdbc:mysql://IP/moodle"); basicDataSource.setUrl(url); System.out.println("$$$$$$$$ URL is : " + url); return basicDataSource; } </code></pre> <p>but while running my test case by junit test it's giving me an exception :</p> <pre><code>org.apache.commons.dbcp.SQLNestedException: Cannot create JDBC driver of class 'org.hsqldb.jdbcDriver' for connect URL 'data/db/hsqldb.jar' at org.apache.commons.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1273) at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1192) at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:884) at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:113) at org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy$TransactionAwareInvocationHandler.invoke(TransactionAwareDataSourceProxy.java:213) ... 35 more Caused by: java.sql.SQLException: No suitable driver at java.sql.DriverManager.getDriver(DriverManager.java:264) at org.apache.commons.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1266) ... 39 more </code></pre> <p>please help to resolve this.</p> <p>Thank you</p>
0
1,578
Jasper report can't find package net.sf.jasperreports.engine
<p>I have a j2ee application using spring framework. I am trying to export jasper reports to xml, pdf and xhtml files. I am using eclipse ide with plugin for weblogic server and for apache tomcat server. It works fine when I run it on server(in eclipse) and choosing Tomcat as server. But when I try to run it on server(in eclipse) now choosing weblogic server I get an error. Heres the full stack trace of the error</p> <pre><code>&gt; net.sf.jasperreports.engine.JRException: &gt; Errors were encountered when compiling &gt; report expressions class file: &gt; C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:4: &gt; package net.sf.jasperreports.engine &gt; does not exist import &gt; net.sf.jasperreports.engine.*; ^ &gt; C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:5: &gt; package &gt; net.sf.jasperreports.engine.fill does &gt; not exist。 import &gt; net.sf.jasperreports.engine.fill.*; ^ &gt; C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:13: &gt; package net.sf.jasperreports.engine &gt; does not exist。 import &gt; net.sf.jasperreports.engine.*; ^ &gt; C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:15: &gt; package &gt; net.sf.jasperreports.engine.data does &gt; not exist。 import &gt; net.sf.jasperreports.engine.data.*; ^ &gt; C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:21: &gt; cannot find symbol。 symbol: class &gt; JREvaluator public class &gt; TestJasper_1262789093368_66389 extends &gt; JREvaluator ^ &gt; C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:28: &gt; cannot find symbol。 symbol: class &gt; JRFillParameter location : &gt; TestJasper_1262789093368_66389 の class &gt; private JRFillParameter &gt; parameter_REPORT_LOCALE = null; ^ &gt; C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:29: &gt; cannot find symbol。 symbol: class &gt; JRFillParameter location : &gt; TestJasper_1262789093368_66389 の class &gt; private JRFillParameter &gt; parameter_JASPER_REPORT = null; ^ &gt; C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:30: &gt; cannot find symbol。 symbol: class &gt; JRFillParameter location : &gt; TestJasper_1262789093368_66389 の class &gt; private JRFillParameter &gt; parameter_REPORT_VIRTUALIZER = null; ^ </code></pre> <p>C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:40:</p> <blockquote> <p>cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class private JRFillParameter parameter_title = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:41: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class private JRFillParameter parameter_REPORT_FORMAT_FACTORY = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:42: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class private JRFillParameter parameter_REPORT_MAX_COUNT = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:43: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class private JRFillParameter parameter_REPORT_TEMPLATES = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:44: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class private JRFillParameter parameter_REPORT_RESOURCE_BUNDLE = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:45: cannot find symbol。 symbol: class JRFillField location : TestJasper_1262789093368_66389 の class private JRFillField field_SERV_ID = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:46: cannot find symbol。 symbol: class JRFillField location : TestJasper_1262789093368_66389 の class private JRFillField field_EMP_FIRSTNAME = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:47: cannot find symbol。 symbol: class JRFillField location : TestJasper_1262789093368_66389 の class private JRFillField field_EMP_ID = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:48: cannot find symbol。 symbol: class JRFillField location : TestJasper_1262789093368_66389 の class private JRFillField field_EMP_SALARY = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:49: cannot find symbol。 symbol: class JRFillField location : TestJasper_1262789093368_66389 の class private JRFillField field_EMP_SURNAME = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:50: cannot find symbol。 symbol: class JRFillField location : TestJasper_1262789093368_66389 の class private JRFillField field_SERV_NAME = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:51: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class private JRFillVariable variable_PAGE_NUMBER = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:52: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class private JRFillVariable variable_COLUMN_NUMBER = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:53: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class private JRFillVariable variable_REPORT_COUNT = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:54: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class private JRFillVariable variable_PAGE_COUNT = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:55: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class private JRFillVariable variable_COLUMN_COUNT = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:56: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class private JRFillVariable variable_Service_COUNT = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:57: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class private JRFillVariable variable_total = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:58: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class private JRFillVariable variable_service_salary_subtotal = null; ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:81: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_REPORT_LOCALE = (JRFillParameter)pm.get("REPORT_LOCALE"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:82: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_JASPER_REPORT = (JRFillParameter)pm.get("JASPER_REPORT"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:83: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_REPORT_VIRTUALIZER = (JRFillParameter)pm.get("REPORT_VIRTUALIZER"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:84: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_REPORT_TIME_ZONE = (JRFillParameter)pm.get("REPORT_TIME_ZONE"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:85: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_REPORT_FILE_RESOLVER = (JRFillParameter)pm.get("REPORT_FILE_RESOLVER"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:86: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_REPORT_SCRIPTLET = (JRFillParameter)pm.get("REPORT_SCRIPTLET"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:87: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_REPORT_PARAMETERS_MAP = (JRFillParameter)pm.get("REPORT_PARAMETERS_MAP"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:88: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_REPORT_CONNECTION = (JRFillParameter)pm.get("REPORT_CONNECTION"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:89: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_REPORT_CLASS_LOADER = (JRFillParameter)pm.get("REPORT_CLASS_LOADER"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:90: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_REPORT_DATA_SOURCE = (JRFillParameter)pm.get("REPORT_DATA_SOURCE"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:91: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_REPORT_URL_HANDLER_FACTORY = (JRFillParameter)pm.get("REPORT_URL_HANDLER_FACTORY"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:92: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_IS_IGNORE_PAGINATION = (JRFillParameter)pm.get("IS_IGNORE_PAGINATION"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:93: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_title = (JRFillParameter)pm.get("title"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:94: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_REPORT_FORMAT_FACTORY = (JRFillParameter)pm.get("REPORT_FORMAT_FACTORY"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:95: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_REPORT_MAX_COUNT = (JRFillParameter)pm.get("REPORT_MAX_COUNT"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:96: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_REPORT_TEMPLATES = (JRFillParameter)pm.get("REPORT_TEMPLATES"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:97: cannot find symbol。 symbol: class JRFillParameter location : TestJasper_1262789093368_66389 の class parameter_REPORT_RESOURCE_BUNDLE = (JRFillParameter)pm.get("REPORT_RESOURCE_BUNDLE"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:106: cannot find symbol。 symbol: class JRFillField location : TestJasper_1262789093368_66389 の class field_SERV_ID = (JRFillField)fm.get("SERV_ID"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:107: cannot find symbol。 symbol: class JRFillField location : TestJasper_1262789093368_66389 の class field_EMP_FIRSTNAME = (JRFillField)fm.get("EMP_FIRSTNAME"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:108: cannot find symbol。 symbol: class JRFillField location : TestJasper_1262789093368_66389 の class field_EMP_ID = (JRFillField)fm.get("EMP_ID"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:109: cannot find symbol。 symbol: class JRFillField location : TestJasper_1262789093368_66389 の class field_EMP_SALARY = (JRFillField)fm.get("EMP_SALARY"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:110: cannot find symbol。 symbol: class JRFillField location : TestJasper_1262789093368_66389 の class field_EMP_SURNAME = (JRFillField)fm.get("EMP_SURNAME"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:111: cannot find symbol。 symbol: class JRFillField location : TestJasper_1262789093368_66389 の class field_SERV_NAME = (JRFillField)fm.get("SERV_NAME"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:120: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class variable_PAGE_NUMBER = (JRFillVariable)vm.get("PAGE_NUMBER"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:121: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class variable_COLUMN_NUMBER = (JRFillVariable)vm.get("COLUMN_NUMBER"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:122: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class variable_REPORT_COUNT = (JRFillVariable)vm.get("REPORT_COUNT"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:123: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class variable_PAGE_COUNT = (JRFillVariable)vm.get("PAGE_COUNT"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:124: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class variable_COLUMN_COUNT = (JRFillVariable)vm.get("COLUMN_COUNT"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:125: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class variable_Service_COUNT = (JRFillVariable)vm.get("Service_COUNT"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:126: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class variable_total = (JRFillVariable)vm.get("total"); ^ C:\Oracle\Middleware\user_projects\domains\wl_server\TestJasper_1262789093368_66389.java:127: cannot find symbol。 symbol: class JRFillVariable location : TestJasper_1262789093368_66389 の class variable_service_salary_subtotal = (JRFillVariable)vm.get("service_salary_subtotal"); ^ エラー 67 個</p> <p>at net.sf.jasperreports.engine.design.JRAbstractCompiler.compileReport(JRAbstractCompiler.java:195) at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:219) at jp.co.anicom.framework.reportutil.report.generateReport(report.java:39) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:328) at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:273) at org.jboss.el.parser.AstMethodSuffix.getValue(AstMethodSuffix.java:59) at org.jboss.el.parser.AstValue.getValue(AstValue.java:67) at org.jboss.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186) at org.springframework.binding.expression.el.BindingValueExpression.getValue(BindingValueExpression.java:54) at org.springframework.binding.expression.el.ELExpression.getValue(ELExpression.java:54) at org.springframework.webflow.action.EvaluateAction.doExecute(EvaluateAction.java:77) at org.springframework.webflow.action.AbstractAction.execute(AbstractAction.java:188) at org.springframework.webflow.execution.AnnotatedAction.execute(AnnotatedAction.java:145) at org.springframework.webflow.execution.ActionExecutor.execute(ActionExecutor.java:51) at org.springframework.webflow.engine.ActionList.execute(ActionList.java:155) at org.springframework.webflow.engine.Flow.start(Flow.java:534) at org.springframework.webflow.engine.impl.FlowExecutionImpl.start(FlowExecutionImpl.java:364) at org.springframework.webflow.engine.impl.FlowExecutionImpl.start(FlowExecutionImpl.java:222) at org.springframework.webflow.executor.FlowExecutorImpl.launchExecution(FlowExecutorImpl.java:140) at org.springframework.webflow.mvc.servlet.FlowHandlerAdapter.handle(FlowHandlerAdapter.java:193) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:875) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:807) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501) at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at javax.servlet.http.HttpServlet.service(HttpServlet.java:820) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227) at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125) at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:292) at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26) at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56) at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:378) at org.springframework.security.intercept.web.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109) at org.springframework.security.intercept.web.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390) at org.springframework.security.ui.SessionFixationProtectionFilter.doFilterHttp(SessionFixationProtectionFilter.java:67) at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53) at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390) at org.springframework.security.ui.ExceptionTranslationFilter.doFilterHttp(ExceptionTranslationFilter.java:101) at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53) at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390) at org.springframework.security.providers.anonymous.AnonymousProcessingFilter.doFilterHttp(AnonymousProcessingFilter.java:105) at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53) at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390) at org.springframework.security.ui.rememberme.RememberMeProcessingFilter.doFilterHttp(RememberMeProcessingFilter.java:116) at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53) at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390) at org.springframework.security.wrapper.SecurityContextHolderAwareRequestFilter.doFilterHttp(SecurityContextHolderAwareRequestFilter.java:91) at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53) at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390) at org.springframework.security.ui.basicauth.BasicProcessingFilter.doFilterHttp(BasicProcessingFilter.java:174) at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53) at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390) at org.springframework.security.ui.AbstractProcessingFilter.doFilterHttp(AbstractProcessingFilter.java:278) at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53) at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390) at org.springframework.security.ui.logout.LogoutFilter.doFilterHttp(LogoutFilter.java:89) at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53) at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390) at org.springframework.security.context.HttpSessionContextIntegrationFilter.doFilterHttp(HttpSessionContextIntegrationFilter.java:235) at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53) at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390) at org.springframework.security.concurrent.ConcurrentSessionFilter.doFilterHttp(ConcurrentSessionFilter.java:99) at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53) at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390) at org.springframework.security.util.FilterChainProxy.doFilter(FilterChainProxy.java:175) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:236) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167) at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56) at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27) at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56) at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3588) at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321) at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121) at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2200) at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2106) at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1428) at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201) at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)</p> </blockquote> <p>I had checked the jar files needed for jasper report and i think i have included all in my lib.<br> Weblogic.xml</p> <pre><code>&gt; &lt;?xml version="1.0" encoding="UTF-8"?&gt; &gt; &lt;wls:weblogic-web-app &gt; xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app" &gt; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" &gt; xsi:schemaLocation="http://java.sun.com/xml/ns/javaee &gt; http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd &gt; http://xmlns.oracle.com/weblogic/weblogic-web-app &gt; http://xmlns.oracle.com/weblogic/weblogic-web-app/1.0/weblogic-web-app.xsd"&gt; &gt; &lt;wls:container-descriptor&gt; &gt; &lt;wls:prefer-web-inf-classes&gt;true&lt;/wls:prefer-web-inf-classes&gt; &gt; &lt;/wls:container-descriptor&gt; &gt; &lt;wls:weblogic-version&gt;10.3.1&lt;/wls:weblogic-version&gt; &gt; &lt;wls:fast-swap&gt; &gt; &lt;wls:enabled&gt;false&lt;/wls:enabled&gt; &gt; &lt;/wls:fast-swap&gt; &lt;/wls:weblogic-web-app&gt; </code></pre>
0
9,180
VueJS async component data and promises
<p>Trying out VueJS 2.0 RC, and using the fetch API to load some data for some of the components. Here's a mock example:</p> <pre><code>const Component = { template: '#comp', name: "some-component", data: function () { return { basic: data.subset, records: function () { return fetch('/datasource/api', { method: 'get' }).then(function (response) { return response.json(); }).then(function (response) { if (response.status == "success") { return response.payload; } else { console.error(response.message); } }).catch(function (err) { console.error(err); }); } } } }; </code></pre> <p>The <code>data</code> object is a global application state, defined before the app's initialization, and only a subset of it is needed in the component, hence that part. The main set of the component's data comes from another endpoint which I'm trying to call. However, the <code>data</code> property expects an object, and it's getting back a Promise it can't really use in the context of a loop in the template for rendering etc (e.g. <code>v-for="record in records"</code>)</p> <p>Am I going about this the wrong way? What's the approach to get the data <code>records</code> property to update once it's fully fetched? Is there a way to force the code to stop until the promise resolves (effectively making it sync)? The component is useless without the data anyway, so there's a waiting period before it can be used regardless.</p> <p>What is <em>the right way</em> to asynchronously populate a component's data field without using plugins like vue-async or vue-resource?</p> <p>(I know I could use the XHR/jQuery methods of non-promise ajax calls to do this, but I want to learn how to do it using fetch)</p> <hr> <p>Update: I tried defining a created hook, and a method to load the data, <a href="https://jsfiddle.net/ytm9zscw/" rel="noreferrer">like this</a> but no dice - in my own experiments, the records property fails to update once it's loaded. It doesn't change, even though the data is successfully fetched (successfully logs into console).</p> <p>Could have something to do with me using vue-router and the component I'm dealing with triggering when a link is clicked, as opposed to being a regular Vue component. Investigating further...</p> <hr> <p>Update #2: If I continue investigating the jsfiddle approach above and log <code>this.records</code> and <code>response.payload</code> to the console, it shows the records object being populated. However, this doesn't seem to trigger a change in the template or the component itself - inspecting with Vue dev tools, the records property remains an empty array. Indeed, if I add a method <code>logstuff</code> and a button into the template which calls it, and then have this method log <code>this.records</code> into the console, it logs an observer with an empty array:</p> <p><a href="https://i.stack.imgur.com/XB0kC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XB0kC.png" alt="enter image description here"></a></p> <p>Now I'm wondering why the data property of a component would be not updated even after it's explicitly set to another value. Tried setting up a watcher for <code>$route</code> that triggers the <code>reload</code> method, but no dice - every subsequent load of that route does indeed re-issue the fetch, and the console logs <code>this.records</code> as populated (from within fetch), but the "real" <code>this.records</code> remains an empty array.</p>
0
1,120
React navigation make transparent screen inside other StackNavigator
<p>I have problem with transparent screen inside other StackNagigation. <a href="https://snack.expo.io/@sinhpn92/stacknavigator-issues" rel="nofollow noreferrer">demo</a></p> <p>I want to show <code>ScreenThree</code> overlay in the front of <code>ScreenTwo</code> after click <code>Go to ScreenThree</code> button in ScreenTwo.</p> <p>I have set <code>cardStyle</code> with <code>backgroundColor: 'transparent'</code> but it still doesn't working. </p> <p>I dont know what's wrong here? Have anyone please help me?</p> <pre><code>import { StackNavigator } from 'react-navigation'; // 2.2.5 import React from 'react' import { Image, View, Text, Button } from 'react-native' import { StyleSheet, Dimensions, TouchableOpacity } from 'react-native' export default class App extends React.Component { render() { return ( &lt;View style={{flex: 1, backgroundColor: 'red'}}&gt; &lt;Root/&gt; &lt;/View&gt; ) } } class HomeScreen extends React.Component { render() { return ( &lt;View style={{ backgroundColor: 'blue', flex: 1, justifyContent: 'center', alignItems: 'center', paddingTop: 20 }}&gt; &lt;TouchableOpacity onPress={ () =&gt; { this.props.navigation.navigate('ScreenTwo')} } style={{ padding: 16, backgroundColor: 'gray' }}&gt; &lt;Text&gt; Go to ScreenTwo &lt;/Text&gt; &lt;/TouchableOpacity&gt; &lt;/View&gt; ) } } class ScreenTwo extends React.Component { render() { return ( &lt;View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}&gt; &lt;Text style={{color: 'white'}}&gt; ScreenTwo &lt;/Text&gt; &lt;TouchableOpacity onPress={ () =&gt; { this.props.navigation.navigate('ScreenThree')} } style={{ padding: 16, backgroundColor: 'gray', marginTop: 16 }}&gt; &lt;Text&gt; Go to ScreenThree &lt;/Text&gt; &lt;/TouchableOpacity&gt; &lt;/View&gt; ) } } class ScreenThree extends React.Component { render() { return ( &lt;View style={{ backgroundColor: 'rgba(0,0,0,0.3)', flex: 1, justifyContent: 'center', alignItems: 'center' }}&gt; &lt;Text style={{color: 'white'}}&gt; ScreenThree &lt;/Text&gt; &lt;/View&gt; ) } } const DetailStack = StackNavigator({ ScreenThree: {screen: ScreenThree} }, { mode: 'modal', headerMode: 'none', cardStyle: { backgroundColor: 'transparent', shadowColor: 'transparent' }, }) const MainStack = StackNavigator({ HomeScreen: {screen: HomeScreen}, ScreenTwo: {screen: ScreenTwo}, DetailStack: {screen: DetailStack} }, { headerMode: 'none', cardStyle: {shadowColor: 'transparent'}, }) const Root = StackNavigator({ Main: {screen: MainStack} }, { mode: 'modal', headerMode: 'none', cardStyle: { shadowColor: 'transparent' }, }) </code></pre>
0
1,421
Application Error when attempting to deploy Node.js/Express/Socket.io application on Heroku
<p>I am fairly new to all of these technologies (including somewhat JavaScript) so you might have to bear with me here.</p> <p>I followed the ChatApp tutorial over at Socket.IO docs fairly closely and modified the application to my likings somewhat; however, I don't think I changed much on the side of server interaction and stuff. My problem is no matter what I do, I can't seem to be able to get my application to successfully run on Heroku. I get this error message when trying to load the app:</p> <blockquote> <p>Application Error An error occurred in the application and your page could not be served. Please try again in a few moments. If you are the application owner, check your logs for details.</p> </blockquote> <p>I am not sure if I am missing something obvious or what.</p> <p>Here is my main index.js file:</p> <pre><code>var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendfile('index.html'); }); app.use("/css", express.static(__dirname + '/css')); //array of users currently in chat var people = {}; io.on('connection', function(socket){ console.log('user connected!'); socket.on('join', function(name){ people[socket.id] = name; //create entry in 'people' with new user socket.emit("update", "You have connected to the server."); io.sockets.emit("update", name + " has joined the server."); io.sockets.emit("update_people_list", people); }); socket.on('disconnect', function(){ console.log('user disconnected!'); if(people[socket.id] != ""){ io.sockets.emit("update", people[socket.id] + " has left the server."); delete people[socket.id]; io.sockets.emit("update_people_list", people); } }); socket.on('chat message', function(msg){ console.log('message: ' + msg); io.sockets.emit('chat message', people[socket.id], msg); }); }); // http.listen(3000, function(){ // console.log('listening on *:3000'); // }); </code></pre> <p>index.html</p> <pre><code>&lt;script src="/socket.io/socket.io.js"&gt;&lt;/script&gt; &lt;script src="http://code.jquery.com/jquery.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function(){ var ready = false; var socket = io.connect(); $("#chat").hide(); $(".canvasDiv").hide(); $("#name").focus(); //prevent form from being submitted without name $("form").submit(function(event){ event.preventDefault(); }); //allows entering by hitting 'Enter' for name $("#name").keypress(function(e){ if(e.which == 13) { //if ENTER key var name = $("#name").val(); if(name != ""){ socket.emit("join", name); $("#login").detach(); $("#chat").show(); $("#msg").focus(); ready = true; } } }); $('#chatform').submit(function(){ //when submit chat message socket.emit('chat message', $('#msg').val()); //emit message + value of input $('#msg').val(''); //empty field? return false; //so that the page doesn't refresh }); //SOCKET LISTENING socket.on('chat message', function(user, msg){ if(ready){ $('#messages').append("&lt;p&gt;&lt;strong&gt;&lt;span class='chat-user'&gt;" + htmlEntities(user) + " &lt;/span&gt;&lt;/strong&gt;: " + htmlEntities(msg) + "&lt;/p&gt;"); //adjust height and scroll as need be: var $container = $('#messages'); var height = $container.get(0).scrollHeight; $container.scrollTop(height); } }); socket.on("update", function(io_message){ if(ready){ $('#messages').append("&lt;p class='notification'&gt;" + htmlEntities(io_message) + "&lt;/p&gt;") } }); socket.on("update_people_list", function(people){ if(ready){ $("#people").empty(); //clear to refresh it $.each(people, function(client_id, name){ $('#people').append("&lt;p class='notification'&gt;" + htmlEntities(name) + "&lt;/p&gt;"); }); var $container = $("#messages"); var height = $container.get(0).scrollHeight; $container.scrollTop(height); } }); }); &lt;/script&gt; </code></pre> <p>Additionally, my package.json file</p> <pre><code> { "name": "socket-chat-example", "version": "0.0.1", "description": "my first socket.io app", "dependencies": { "express": "^4.6.1", "socket.io": "^1.0.6" } } </code></pre> <p>Procfile:</p> <pre><code>web: node index.js </code></pre> <p>.gitignore:</p> <pre><code>node_modules/ </code></pre>
0
1,884
java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory
<p>I am getting the error as mentioned below, while running the feed utility. I am trying to load an image "<strong>logo.png</strong>". The <code>slf4j</code> jar file is also available in the runtime classpath. But still I am getting this error. </p> <pre><code>Oct 16, 2012 7:34:11 PM com.ibm.commerce.foundation.dataload.FeedRetriever invokeDataLoad SEVERE: An error occurred while performing data load. Throwable occurred: com.ibm.commerce.foundation.dataload.exception.DataLoadException: An error occurred while executing the data load. java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory at com.ibm.commerce.foundation.dataload.DataLoaderMain.execute(DataLoaderMain.java:664) at com.ibm.commerce.content.commands.DataLoadInvoker.execute(DataLoadInvoker.java:101) at com.ibm.commerce.foundation.dataload.FeedRetriever.invokeDataLoad(FeedRetriever.java:244) at com.ibm.commerce.foundation.dataload.FeedRetriever.execute(FeedRetriever.java:172) at com.ibm.commerce.foundation.dataload.FeedRetriever.main(FeedRetriever.java:321) Caused by: java.lang.RuntimeException: java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory at com.ibm.commerce.foundation.dataload.DataLoaderMain.execute(DataLoaderMain.java:488) ... 4 more Caused by: java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory at org.apache.wink.client.ClientConfig.&lt;clinit&gt;(ClientConfig.java:52) at java.lang.J9VMInternals.initializeImpl(Native Method) at java.lang.J9VMInternals.initialize(J9VMInternals.java:200) at java.lang.J9VMInternals.initialize(J9VMInternals.java:167) at com.ibm.commerce.foundation.dataload.feedreader.AtomReader.getFeed(AtomReader.java:104) at com.ibm.commerce.foundation.dataload.feedreader.AtomReader.getEntries(AtomReader.java:147) at com.ibm.commerce.foundation.dataload.feedreader.AtomReader.getEntries(AtomReader.java:1) at com.ibm.commerce.foundation.dataload.feedreader.BaseFeedReader.init(BaseFeedReader.java:252) at com.ibm.commerce.foundation.dataload.AbstractBusinessObjectLoader.initializeDataReaders(AbstractBusinessObjectLoader.java:1344) at com.ibm.commerce.foundation.dataload.AbstractBusinessObjectLoader.init(AbstractBusinessObjectLoader.java:369) at com.ibm.commerce.foundation.dataload.BusinessObjectLoader.init(BusinessObjectLoader.java:65) at com.ibm.commerce.foundation.dataload.DataLoaderMain.execute(DataLoaderMain.java:431) ... 4 more Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory at java.lang.ClassNotFoundException.&lt;init&gt;(ClassNotFoundException.java:76) at java.net.URLClassLoader.findClass(URLClassLoader.java:396) at java.lang.ClassLoader.loadClass(ClassLoader.java:660) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:358) at java.lang.ClassLoader.loadClass(ClassLoader.java:626) ... 16 more Oct 16, 2012 7:34:11 PM com.ibm.commerce.foundation.dataload.FeedRetriever main SEVERE: An error occurred while performing data load. Throwable occurred: com.ibm.commerce.foundation.dataload.exception.DataLoadException: An error has occurred. If this problem persists, contact product support. at com.ibm.commerce.foundation.dataload.FeedRetriever.invokeDataLoad(FeedRetriever.java:247) at com.ibm.commerce.foundation.dataload.FeedRetriever.execute(FeedRetriever.java:172) at com.ibm.commerce.foundation.dataload.FeedRetriever.main(FeedRetriever.java:321) </code></pre>
0
1,213
java.lang.NoClassDefFoundError: javax/el/ELManager
<p>I'm working on a webapp in Spring using Spring Tool Suite. If I build and deploy the application there using the IDE onto the provided Pivotal tc Server, it works just fine. However, if I do a manual "mvn clean package" build and attempt to deploy it to a standalone Tomcat server (using newest Tomcat 7), it throws the following exception:</p> <pre><code>2017-08-23 15:24:13 WARN AnnotationConfigWebApplicationContext:551 - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerAdapter' defined in org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcValidator' defined in org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager 2017-08-23 15:24:13 ERROR DispatcherServlet:502 - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerAdapter' defined in org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcValidator' defined in org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager </code></pre> <p>Upon further inspection, it does complain few lines higher above about not loading jars:</p> <pre><code>sie 23, 2017 3:24:12 PM org.apache.catalina.startup.HostConfig deployWAR INFO: Deploying web application archive D:\Apache-Tomcat-7.0\webapps\TestApp-0.0.1-SNAPSHOT.war sie 23, 2017 3:24:12 PM org.apache.catalina.loader.WebappClassLoader validateJarFile INFO: validateJarFile(D:\Apache-Tomcat-7.0\webapps\TestApp-0.0.1-SNAPSHOT\WEB-INF\lib\el-api-2.2.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/el/Expression.class sie 23, 2017 3:24:12 PM org.apache.catalina.loader.WebappClassLoader validateJarFile INFO: validateJarFile(D:\Apache-Tomcat-7.0\webapps\TestApp-0.0.1-SNAPSHOT\WEB-INF\lib\javax.servlet-api-3.1.0.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class sie 23, 2017 3:24:12 PM org.apache.catalina.loader.WebappClassLoader validateJarFile INFO: validateJarFile(D:\Apache-Tomcat-7.0\webapps\TestApp-0.0.1-SNAPSHOT\WEB-INF\lib\tomcat-el-api-8.0.21.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/el/Expression.class 2017-08-23 15:24:13 INFO ContextLoader:304 - Root WebApplicationContext: initialization started </code></pre> <p>My pom.xml:</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.exmaple.mvc&lt;/groupId&gt; &lt;artifactId&gt;TestApp&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;version&gt;4.3.10.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt; &lt;version&gt;4.3.10.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-web&lt;/artifactId&gt; &lt;version&gt;4.3.10.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-test&lt;/artifactId&gt; &lt;version&gt;4.3.10.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;slf4j-log4j12&lt;/artifactId&gt; &lt;version&gt;1.6.6&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j&lt;/artifactId&gt; &lt;version&gt;1.2.17&lt;/version&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;artifactId&gt;jms&lt;/artifactId&gt; &lt;groupId&gt;javax.jms&lt;/groupId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;artifactId&gt;jmxri&lt;/artifactId&gt; &lt;groupId&gt;com.sun.jmx&lt;/groupId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;artifactId&gt;jmxtools&lt;/artifactId&gt; &lt;groupId&gt;com.sun.jdmk&lt;/groupId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;jstl&lt;/groupId&gt; &lt;artifactId&gt;jstl&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.12&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/org.mockito/mockito-all --&gt; &lt;dependency&gt; &lt;groupId&gt;org.mockito&lt;/groupId&gt; &lt;artifactId&gt;mockito-all&lt;/artifactId&gt; &lt;version&gt;1.9.5&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/commons-lang/commons-lang --&gt; &lt;dependency&gt; &lt;groupId&gt;commons-lang&lt;/groupId&gt; &lt;artifactId&gt;commons-lang&lt;/artifactId&gt; &lt;version&gt;2.3&lt;/version&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator --&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-validator&lt;/artifactId&gt; &lt;version&gt;6.0.1.Final&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt; &lt;version&gt;3.1.0&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.1&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.8&lt;/source&gt; &lt;target&gt;1.8&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>What's the reason for this behavior and how can I solve this?</p> <p><strong>EDIT</strong> More information:</p> <p>Adding <code>&lt;scope&gt;provided&lt;/scope&gt;</code> to <code>javax.servlet-api</code> seems to fix the warning about <code>javax.servlet-api</code> not being loaded at the start. Problem with <code>el-api</code> still remains.</p> <p>I've checked the tomcat/lib directory and it already contains <code>el-api.jar</code> in it, which is likely why it tells me it's not going to load the one I list in pom.xml. The thing is, adding <code>&lt;scope&gt;provided&lt;/scope&gt;</code> doesn't fix it either. Whatever I do, it still complains gives me the same <code>java.lang.NoClassDefFoundError: javax/el/ELManager</code> error. </p> <p><strong>SOLUTION</strong></p> <p>In addition to the part in the edit above regarding <code>javax.servlet-api</code> the problem with <code>el-api</code> was that I was running a Tomcat 7 with provided <code>el-api</code> jar in version 2.2. The missing class was introduced in el-api 3.0. Running the same webapp in Tomcat 8 (with el-api 3.0 jar) works properly.</p>
0
3,893
application.properties vs hibernate.cfg.xml in spring boot application
<p>I've configured hibernate properties in <code>application.properties</code> file of my spring boot application. </p> <p><strong>application.properties</strong></p> <pre><code>#hibernate config spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect spring.datasource.url=&lt;db_url&gt; spring.datasource.username=&lt;username&gt; spring.datasource.password=&lt;password&gt; spring.datasource.driver-class-name=oracle.jdbc.OracleDriver # Show or not log for each sql query spring.jpa.show-sql = true # Naming strategy spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy # ThymeLeaf spring.thymeleaf.cache= false spring.thymeleaf.mode=LEGACYHTML5 </code></pre> <p>I am getting error when I am trying to get session as </p> <pre><code>Configuration configuration = new Configuration(); configuration.configure("application.properties"); StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build()); Session session = sessionFactory.openSession(); </code></pre> <p><strong>ERROR:</strong></p> <pre><code>Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: Could not parse configuration: application.properties] with root cause org.dom4j.DocumentException: Error on line 1 of document : Content is not allowed in prolog. Nested exception: Content is not allowed in prolog. </code></pre> <p>I think its expecting <code>hibernate.cfg.xml</code> file in the class path as well? </p> <p>Is there any way I can only use <code>application.properties</code> or I have to move all hibernate related properties to <code>hibernate.cfg.xml</code> or <code>hibernate.properties</code> file?</p> <p><strong>getSelectedStudents</strong></p> <pre><code>public List getSelectedStudents(){ final EntityManagerFactory emf = null; EntityManager em = emf.createEntityManager(); Query q = em.createNativeQuery("SELECT s.student_id, s.first_name, s.last_name, s.city FROM Student s " + "where s.city=:city and s.last_name = :lname", Student.class); q.setParameter("city", "London"); q.setParameter("lname", "Rizwan"); List&lt;Student&gt; students = q.getResultList(); for (Student s : students) { System.out.println("Student " + s.getFirstName() + " " + s.getLastName()); } return students; } </code></pre> <p><strong>Error 2:</strong></p> <pre><code>Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException: null at com.school.service.StudentServiceImplementation.getSelectedStudents(StudentServiceImplementation.java:69) ~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_77] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_77] </code></pre> <p>EDIT: as suggested to use Entity Manager, I've added getSelectedStudents method. I am still getting error at <code>EntityManager em = emf.createEntityManager();</code> see Error 2 for details.</p>
0
1,171
shared library locations for matlab mex files:
<p>I am trying to write a matlab mex function which uses libhdf5; My Linux install provides libhdf5-1.8 shared libraries and headers. However, my version of Matlab, r2007b, provides a libhdf5.so from the 1.6 release. (Matlab <code>.mat</code> files bootstrap hdf5, evidently). When I compile the mex, it segfaults in Matlab. If I downgrade my version of libhdf5 to 1.6 (not a long-term option), the code compiles and runs fine.</p> <p>question: how do I solve this problem? how do I tell the mex compilation process to link against /usr/lib64/libhdf5.so.6 instead of /opt/matlab/bin/glnxa64/libhdf5.so.0 ? When I try to do this using <code>-Wl,-rpath-link,/usr/lib64</code> in my compilation, I get errors like:</p> <pre><code>/usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/../../../../x86_64-pc-linux-gnu/bin/ld: warning: libhdf5.so.0, needed by /opt/matlab/matlab75/bin/glnxa64/libmat.so, may conflict with libhdf5.so.6 /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/../../../../lib64/crt1.o: In function `_start': (.text+0x20): undefined reference to `main' collect2: ld returned 1 exit status mex: link of 'hdf5_read_strings.mexa64' failed. make: *** [hdf5_read_strings.mexa64] Error 1 </code></pre> <p>ack. the last resort would be to download a local copy of the hdf5-1.6.5 headers and be done with it, but this is not future proof (a Matlab version upgrade is in my future.). any ideas?</p> <p>EDIT: per Ramashalanka's excellent suggestions, I </p> <p>A) called <code>mex -v</code> to get the 3 <code>gcc</code> commands; the last is the linker command;</p> <p>B) called that linker command with a <code>-v</code> to get the <code>collect</code> command;</p> <p>C) called that <code>collect2 -v -t</code> and the rest of the flags.</p> <p>The relevant parts of my output:</p> <pre><code>/usr/bin/ld: mode elf_x86_64 /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/../../../../lib64/crti.o /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/crtbeginS.o hdf5_read_strings.o mexversion.o -lmx (/opt/matlab/matlab75/bin/glnxa64/libmx.so) -lmex (/opt/matlab/matlab75/bin/glnxa64/libmex.so) -lhdf5 (/usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/../../../../lib64/libhdf5.so) /lib64/libz.so -lm (/usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/../../../../lib64/libm.so) -lstdc++ (/usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/libstdc++.so) -lgcc_s (/usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/libgcc_s.so) /lib64/libpthread.so.0 /lib64/libc.so.6 /lib64/ld-linux-x86-64.so.2 -lgcc_s (/usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/libgcc_s.so) /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/crtendS.o /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/../../../../lib64/crtn.o </code></pre> <p>So, in fact the <code>libhdf5.so</code> from <code>/usr/lib64</code> is being referenced. However, this is being overriden, I believe, by the environment variable <code>LD_LIBRARY_PATH</code>, which my version of Matlab automagically sets at run-time so it can locate its own versions of e.g. <code>libmex.so</code>, etc.</p> <p>I am thinking that the <code>crt_file.c</code> example works either b/c it does not use the functions I am using (<code>H5DOpen</code>, which had a signature change in the move from 1.6 to 1.8 (yes, I am using <code>-DH5_USE_16_API</code>)), or, less likely, b/c it does not hit the parts of Matlab internals that need hdf5. ack.</p>
0
1,377
VHDL State Machine testbench
<p>Description: </p> <p>I am trying to generate a test bench for a 5 state sequential state machine that detects 110 or any combination of (2) 1's and (1) 0. I already have written the code. see below. I am having trouble with the test bench which is wrong. I want to test for all possible sequences as well as input combinations that are off sequence. </p> <p>Please give me examples of a good test bench to achieve what I need for a mealy machine.</p> <p>vhdl code:</p> <pre><code>library IEEE; use IEEE.STD_LOGIC_1164.all; entity state is port( clk, x : in std_logic; z : out std_logic ); end entity; architecture behavioral of state is type state_type is (s0,s1,s2,s3,s4); signal state,next_s: state_type; ------------------------------------------------------------------------------ begin process (state,x) begin if clk='1' and clk'event then case state is when s0 =&gt; if(x ='0') then z &lt;= '0'; next_s &lt;= s4; else z &lt;= '0'; next_s &lt;= s1; end if; when s1 =&gt; --when current state is "s1" if(x ='0') then z &lt;= '0'; next_s &lt;= s3; else z &lt;= '0'; next_s &lt;= s2; end if; when s2 =&gt; --when current state is "s2" if(x ='0') then z &lt;= '1'; next_s &lt;= s0; else z &lt;= '0'; next_s &lt;= s0; end if; when s3 =&gt; --when current state is "s3" if(x ='0') then z &lt;= '0'; next_s &lt;= s0; else z &lt;= '1'; next_s &lt;= s0; end if; when s4 =&gt; --when current state is s4 if (x = '0') then z &lt;= '0'; next_s &lt;= s0; else z &lt;= '0'; next_s &lt;= s3; end if; end case; end if; end process; end behavioral; </code></pre> <p>Test Bench code:</p> <pre><code>library ieee; use ieee.std_logic_1164.all; -- Add your library and packages declaration here ... entity state_tb is end state_tb; architecture TB_ARCHITECTURE of state_tb is -- Component declaration of the tested unit component state port( clk : in STD_LOGIC; x : in STD_LOGIC; z : out STD_LOGIC ); end component; -- Stimulus signals - signals mapped to the input and inout ports of tested entity signal clk : STD_LOGIC; signal x : STD_LOGIC; -- Observed signals - signals mapped to the output ports of tested entity signal z : STD_LOGIC; -- Add your code here ... begin -- Unit Under Test port map UUT : state port map ( clk =&gt; clk, x =&gt; x, z =&gt; z ); -- CLOCK STIMULI CLOCK: process begin CLK &lt;= not clk after 20 ns; wait for 40 ns; end process; -- X input STIMULI X_Stimuli: process begin X &lt;= not x after 40 ns; wait for 80 ns; end process; end TB_ARCHITECTURE; configuration TESTBENCH_FOR_state of state_tb is for TB_ARCHITECTURE for UUT : state use entity work.state(behavioral); end for; end for; end TESTBENCH_FOR_state; </code></pre>
0
1,222
Using Traefik 2 as TCP proxy for MariaDB (Docker)
<p>I am trying to use Traefik as a reverse proxy for MariaDB so I can connect from my Client.</p> <p>Currently Traefik is working fine with HTTP and HTTPS for multiple WordPress Container but i am having trouble configuring it for MariaDB.</p> <p>Here is the current config:</p> <p>Traefik Compose File:</p> <pre><code>version: '3.5' networks: traefik: name: traefik services: traefik: image: traefik:latest restart: always container_name: traefik volumes: - /etc/localtime:/etc/localtime:ro - /var/run/docker.sock:/var/run/docker.sock:ro - ./traefik.toml:/traefik.toml:ro - ./acme.json:/acme.json ports: - 80:80 - 443:443 - 3306:3306 labels: - "traefik.enable=true" - "traefik.http.routers.traefik.rule=Host(`traefik.local`)" - "traefik.http.routers.traefik.entrypoints=websecure" - "traefik.http.routers.traefik.service=api@internal" - "traefik.http.routers.traefik.middlewares=auth" - "traefik.http.middlewares.auth.basicauth.users=username:$$apr1$$j994eiLb$$KmPfiii4e9VkZwTPW2/RF1" networks: - traefik </code></pre> <p>Traefik Configuration File (traefik.toml):</p> <pre><code># Network traffic will be entering our Docker network on the usual web ports # (ie, 80 and 443), where Traefik will be listening. [entyPoints] [entryPoints.web] address = ":80" [entryPoints.websecure] address= ":443" [entryPoints.websecure.http.tls] certResolver = "resolver" # [entryPoints.ssh] # address = ":2222" [entryPoints.mariadb] address = ":3306" #Redirection from HTTP to HTTPS [entryPoints.web.http] [entryPoints.web.http.redirections] [entryPoints.web.http.redirections.entryPoint] to = "websecure" scheme = "https" #Integration with Let's Encrypt [certificatesResolvers.resolver.acme] email = "service@local" storage = "acme.json" [certificatesResolvers.resolver.acme.tlsChallenge] #[log] # level = "DEBUG" [api] #Defaul=true dashboard = true # Enable retry sending request if network error [retry] # These options are for Traefik's integration with Docker. [providers.docker] endpoint = "unix:///var/run/docker.sock" exposedByDefault = false network = "traefik" </code></pre> <p>MariaDB Compose File: version: '3.5'</p> <pre><code>networks: traefik: external: name: traefik services: dbtest: image: mariadb:latest restart: always container_name: dbtest environment: - MYSQL_DATABASE=admin - MYSQL_USER=admin - MYSQL_PASSWORD=admin - MYSQL_ROOT_PASSWORD=admin networks: - traefik labels: - "traefik.enable=true" - "traefik.docker.network=traefik" - "traefik.tcp.routers.mariadb.entrypoints=mariadb" - "traefik.tcp.routers.mariadb.rule=HostSNI(`test.local`)" - "traefik.tcp.routers.mariadb.tls=true" # - "traefik.tcp.routers.mariadb.service=dbtest" # - "traefik.tcp.services.mariadb.loadbalancer.server.port=3306" </code></pre> <p>When I try to connect to the database from my Client it doesn't work</p> <p>Anyone having experience or a good example for that?</p>
0
1,393
Picture distorted with Camera and getOptimalPreviewSize
<p>I am on a Camera App which taking basic pictures. I have an issue when I get the best optimal preview size.</p> <p>In fact, with this first code :</p> <pre><code>public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { if (isPreviewRunning) { mCamera.stopPreview(); } Camera.Parameters parameters = mCamera.getParameters(); mCamera.setParameters(parameters); mCamera.startPreview(); isPreviewRunning = true; } </code></pre> <p>The picture has a good quality :</p> <p><a href="http://img689.imageshack.us/i/04042011172937.jpg/" rel="nofollow noreferrer">http://img689.imageshack.us/i/04042011172937.jpg/</a></p> <p>But, with this code :</p> <pre><code>private Size getOptimalPreviewSize(List&lt;Size&gt; sizes, int w, int h) { final double ASPECT_TOLERANCE = 0.05; double targetRatio = (double) w / h; if (sizes == null) return null; Size optimalSize = null; double minDiff = Double.MAX_VALUE; int targetHeight = h; // Try to find an size match aspect ratio and size for (Size size : sizes) { double ratio = (double) size.width / size.height; if (Math.abs(ratio - targetRatio) &gt; ASPECT_TOLERANCE) continue; if (Math.abs(size.height - targetHeight) &lt; minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } // Cannot find the one match the aspect ratio, ignore the requirement if (optimalSize == null) { minDiff = Double.MAX_VALUE; for (Size size : sizes) { if (Math.abs(size.height - targetHeight) &lt; minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } } return optimalSize; } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Now that the size is known, set up the camera parameters and begin // the preview. if (isPreviewRunning) { mCamera.stopPreview(); } Camera.Parameters parameters = mCamera.getParameters(); List&lt;Size&gt; sizes = parameters.getSupportedPreviewSizes(); Size optimalSize = getOptimalPreviewSize(sizes, w, h); parameters.setPreviewSize(optimalSize.width, optimalSize.height); mCamera.setParameters(parameters); mCamera.startPreview(); isPreviewRunning =true; } </code></pre> <p>The picture is totally distorted :</p> <p><a href="http://img97.imageshack.us/i/04042011173220.jpg/" rel="nofollow noreferrer">http://img97.imageshack.us/i/04042011173220.jpg/</a></p> <p>How can I resolve this problem??</p> <p>I am using a HTC Desire HD.</p> <p>It is probably my saving method too ? :</p> <pre><code>PictureCallback mPictureCallbackJpeg = new PictureCallback() { public void onPictureTaken(byte[] imageData, Camera camera) { .... BitmapFactory.Options options=new BitmapFactory.Options(); options.inSampleSize = 5; Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0,imageData.length,options); FileOutputStream fOut = new FileOutputStream(path + "/"+fl); BufferedOutputStream bos = new BufferedOutputStream(fOut); myImage.compress(CompressFormat.JPEG, 100, bos); bos.flush(); bos.close(); .... } </code></pre> <p>Thanks</p>
0
1,367
ObjectDataSource could not find a non-generic method that has parameters:
<p>I'm trying to use a Gridview to show a datatable from an Object data source. It's giving me the error:</p> <pre><code>ObjectDataSource 'odsStores' could not find a non-generic method 'ProcessDelete' that has parameters: ProcessID. </code></pre> <p>I've read a lot of other answers to this question about matching case, matching format, variables but I think I've done all of those correctly. Here's the aspx page:</p> <pre><code> &lt;asp:GridView ID="gridStores" runat="server" AllowSorting="False" AutoGenerateColumns="False" CssClass="grid-main" DataSourceID="odsStores" EnableViewState="False" OnDataBound="gridStores_DataBound" OnRowDataBound="gridStores_RowDataBound"&gt; &lt;Columns&gt; &lt;asp:TemplateField ShowHeader="False"&gt; &lt;ItemTemplate&gt; &lt;asp:Image ID="imgModel" runat="server" AlternateText="Click to See Details" CssClass="img-details" EnableViewState="False" ImageUrl="~/img/detail.gif" /&gt; &lt;/ItemTemplate&gt; &lt;ItemStyle CssClass="grid-main-detail" /&gt; &lt;/asp:TemplateField&gt; &lt;asp:BoundField DataField="ProcessID" HeaderText="ProcessID" /&gt; &lt;asp:BoundField DataField="ProcessName" HeaderText="Process Name" ReadOnly="False" /&gt; &lt;asp:BoundField DataField="ProcessDescription" HeaderText="Process Description" ReadOnly="False" /&gt; &lt;asp:BoundField DataField="UpdateUserID" HeaderText="Last Updated By" ReadOnly="True" /&gt; &lt;asp:BoundField DataField="UpdateTimestamp" HeaderText="Last Updated" ReadOnly="True" /&gt; &lt;asp:CommandField ShowEditButton="True" /&gt; &lt;asp:CommandField ShowDeleteButton="True" /&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>Here's the code behind, all I have is a break point and it never hits it.</p> <pre><code>&lt;DataObjectMethod(DataObjectMethodType.Delete)&gt; _ Private Sub ProcessDelete(ByVal ProcessID As String) Dim x As Integer = 0 x = x + 1 End Sub </code></pre> <p>Here's the object datasource:</p> <pre><code>&lt;asp:ObjectDataSource ID="odsStores" runat="server" EnableViewState="False" OldValuesParameterFormatString="original_{0}" SelectCountMethod="GetRowCount" SelectMethod="GetData" TypeName="DataWarehouseUserInterface.ProcessBSL" UpdateMethod="ProcessUpdate" DeleteMethod="ProcessDelete" &gt; &lt;UpdateParameters&gt; &lt;asp:FormParameter Name="ProcessName" Type="String" FormField="ProcessName" /&gt; &lt;asp:FormParameter Name="ProcessDescription" Type="String" FormField="ProcessDescription" /&gt; &lt;/UpdateParameters&gt; &lt;DeleteParameters&gt; &lt;asp:FormParameter Name="ProcessID" Type="String"/&gt; &lt;/DeleteParameters&gt; &lt;/asp:ObjectDataSource&gt; </code></pre>
0
1,545