title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
Configuring Log4j2 in web application using log4j-web.jar
|
<p>I am trying to configure log4j2 in my webapplication by following some tutorials. I am working with glassfish 4.1.1 server and servlet version 3.1. I am able to configure the logging feature with the below configuration:</p>
<p>log4j.properties</p>
<pre><code> # Root logger option
log4j.rootLogger=INFO, consoleAppender, fileAppender
# debug level logger
log4j.logger.kumar.suraj.college.administration.login=DEBUG
# Redirect log messages to console
log4j.appender.consoleAppender=org.apache.log4j.ConsoleAppender
log4j.appender.consoleAppender.Target=System.out
log4j.appender.consoleAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.consoleAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file, support file rolling.
log4j.appender.fileAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.fileAppender.File=E:\\DEVELOPMENT\\JAVA\\web-logs\\web-college-administration\\applicationLogs.log
log4j.appender.fileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.fileAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
</code></pre>
<p>the properties file is placed in src/main/resources folder</p>
<p>web.xml</p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>College Administration</display-name>
<!-- <context-param>
<param-name>log4jConfiguration</param-name>
<param-value>/log4j.properties</param-value>
</context-param>is it required
-->
<!--from where is this class referenced in dependency without web -->
<listener>
<listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>kumar.suraj.college.administration.login.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
</code></pre>
<p>the context param that defines file location is commented out. probably log4j looks by default for a file with name log4j.properties. However just wanted to know if its the right way to specify the file location.</p>
<p>Also I am not sure from which jar is org.apache.logging.log4j.web.Log4jServletContextListener being referenced. I searched all jar files but could not locate this class.</p>
<p>LoginServlet.java</p>
<pre><code> package kumar.suraj.college.administration.login;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import kumar.suraj.college.administration.adduser.AddUserServlet;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// final static Logger logger = LogManager.getLogger(LoginServlet.class);
final static Logger logger = Logger.getLogger(LoginServlet.class);
public LoginServlet() {
super();
}
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
LoginServlet.logger.debug("debug level logging supported"); response.getWriter().append("Servedat:").append(request.getContextPath());
response.getWriter().append("Hello Suraj");
}
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
LoginServlet.logger.debug("debug level logging supported");
this.doGet(request, response);
}
}
</code></pre>
<p>pom.xml dependency for log4j</p>
<pre><code> <dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</code></pre>
<p>All this works fine and I get logs in both console as well as file. But when I try to change the configuration as per the following links :</p>
<p><a href="https://logging.apache.org/log4j/2.x/manual/webapp.html#Servlet-3.0" rel="nofollow">https://logging.apache.org/log4j/2.x/manual/webapp.html#Servlet-3.0</a>
<a href="https://logging.apache.org/log4j/2.x/maven-artifacts.html" rel="nofollow">https://logging.apache.org/log4j/2.x/maven-artifacts.html</a></p>
<p>Like instead of dependency specified earlier I switch to </p>
<pre><code> <dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>2.6.2</version>
</dependency>
</code></pre>
<p>log4j-api and log4j-core are added as transitive dependencies with log4j-web.jar</p>
<p>other changes I made in LoginServlet.java is because of the compile time error I was getting after switching to log4j-web.jar which is as below :</p>
<pre><code> import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
final static Logger logger = LogManager.getLogger(LoginServlet.class);
// final static Logger logger = Logger.getLogger(LoginServlet.class);
</code></pre>
<p>the main changes are in the initialization of logger variable and the two imports. rest all configuration remained as it is. Also i was able to locate the listener class specified in web.xml in log4j-web.jar in this case. Still logging is not working with this configuartion.</p>
<p>Could some one please help me with it or tell me what I am doing wrong here ?</p>
| 0 | 2,632 |
mlogit.data() Error: Assigned data `ids` must be compatible with existing data
|
<p>I have been working hours on that and I simply cannot find any solution to the problem. Hopefully someone here can help.</p>
<p>I'm trying to create a personal choice matrix for some data with the following structure:</p>
<pre><code># A tibble: 2,152 x 32
age choice canton lr_s dist_svp dist_fdp dist_bdp dist_cvp dist_glp dist_sp
<dbl> <fct> <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 39 sp GE 3 49 25 25 4 16 1
2 67 sp ZH 0 100 49 64 4 25 0
3 42 svp ZH 7 4 4 1 36 4 36
dist_gps pid_svp pid_fdp pid_bdp pid_cvp pid_glp pid_sp pid_gps french italian
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 0 0 0 0 0 0 0 1 1 0
2 9 0 0 0 0 0 1 0 0 0
3 36 0 0 0 0 0 1 0 0 0
</code></pre>
<p>Now, I need to create a personal choice matrix with the 7 alternatives that are indicated by dist_* / pid_* in the columns. </p>
<p>This should, according to my understanding, work with the following code:</p>
<pre><code>work.pc <- mlogit.data(work,
varying = c(5:11, 12:18),
choice = "choice",
shape = "wide",
sep = "_")
</code></pre>
<p>However, when I run this code, I get the following Error message and a few Warning messages:</p>
<pre><code>Error: Assigned data `ids` must be compatible with existing data.
x Existing data has 15064 rows.
x Assigned data has 2152 rows.
ℹ Only vectors of size 1 are recycled.
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning messages:
1: Setting row names on a tibble is deprecated.
2: Setting row names on a tibble is deprecated.
3: Setting row names on a tibble is deprecated.
4: Setting row names on a tibble is deprecated.
5: Setting row names on a tibble is deprecated.
6: Setting row names on a tibble is deprecated.
7: Setting row names on a tibble is deprecated.
</code></pre>
<p>What's the issue here? I'm grateful for any help! I've tried everything.</p>
| 0 | 1,223 |
How to direct different users to different pages after login?
|
<p>I created a database (following an online tutorial) which directs all users to one login page. I was wondering how can I direct different users to different webpages. For example I want to direct JOHN SMITH (user1) to localhost/pages/johnsmith.html and JANE SMITH (user 2) to localhost/pages/janesmith.html.</p>
<p>Code: </p>
<p>db_const.php</p>
<pre><code><?php
# mysql db constants DB_HOST, DB_USER, DB_PASS, DB_NAME
const DB_HOST = 'localhost';
const DB_USER = 'root';
const DB_PASS = 'root';
const DB_NAME = 'ClientDashboard';
?>
</code></pre>
<p>login.php</p>
<pre><code><html>
<head>
<title>User Login Form - PHP MySQL Ligin System | W3Epic.com</title>
</head>
<body>
<h1>User Login Form - PHP MySQL Ligin System | W3Epic.com</h1>
<?php
if (!isset($_POST['submit'])){
?>
<!-- The HTML login form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" name="submit" value="Login" />
</form>
<?php
} else {
require_once("db_const.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
} else {
echo "<p>Logged in successfully</p>";
// do stuffs
}
}
?>
</body>
</html>
</code></pre>
<p>register.php </p>
<pre><code><html>
<head>
<title>User registration form- PHP MySQL Ligin System | W3Epic.com</title>
</head>
<body>
<h1>User registration form- PHP MySQL Ligin System | W3Epic.com</h1>
<?php
require_once("db_const.php");
if (!isset($_POST['submit'])) {
?> <!-- The HTML registration form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
First name: <input type="text" name="first_name" /><br />
Last name: <input type="text" name="last_name" /><br />
Email: <input type="type" name="email" /><br />
<input type="submit" name="submit" value="Register" />
</form>
<?php
} else {
## connect mysql server
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli- >connect_error}</p>";
exit();
}
## query database
# prepare data for insertion
$username = $_POST['username'];
$password = $_POST['password'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
# check if username and email exist else insert
$exists = 0;
$result = $mysqli->query("SELECT username from users WHERE username = '{$username}' LIMIT 1");
if ($result->num_rows == 1) {
$exists = 1;
$result = $mysqli->query("SELECT email from users WHERE email = '{$email}' LIMIT 1");
if ($result->num_rows == 1) $exists = 2;
} else {
$result = $mysqli->query("SELECT email from users WHERE email = '{$email}' LIMIT 1");
if ($result->num_rows == 1) $exists = 3;
}
if ($exists == 1) echo "<p>Username already exists!</p>";
else if ($exists == 2) echo "<p>Username and Email already exists! </p>";
else if ($exists == 3) echo "<p>Email already exists!</p>";
else {
# insert data into mysql database
$sql = "INSERT INTO `users` (`id`, `username`, `password`, `first_name`, `last_name`, `email`)
VALUES (NULL, '{$username}', '{$password}', '{$first_name}', '{$last_name}', '{$email}')";
if ($mysqli->query($sql)) {
//echo "New Record has id ".$mysqli->insert_id;
echo "<p>Registred successfully!</p>";
} else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error} </p>";
exit();
}
}
}
?>
</body>
</html>
</code></pre>
<p>Thanks!</p>
| 0 | 2,017 |
How to make a dropdown sub-menu expand to the right in Bootstrap 3
|
<p>I am using this code and CSS below. As you can see, the dropdown sub-menu expands to the left, which is when I hover my cursor over "More Options". I have changed every "left" keyword on my CSS but it just won't go to the right. How do I expand the dropdown sub-menu to the right, which means if I hover over "More Options", it will expand to the right like this?
<a href="http://i.stack.imgur.com/paFAK.jpg" rel="nofollow">click here</a></p>
<pre><code><div class="container-fluid">
<div class="btn-group pull-right">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
Menu
<span class="caret"></span>
</a>
<ul class="dropdown-menu dropdown-menu-right" role="menu" aria-labelledby="dropdownMenu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-submenu dropdown-menu-right">
<a tabindex="-1" href="#">More options</a>
<ul class="dropdown-menu">
<li><a tabindex="-1" href="#">Second level</a></li>
<li class="dropdown-submenu">
<a href="#">More..</a>
<ul class="dropdown-menu">
<li><a href="#">3rd level</a></li>
<li><a href="#">3rd level</a></li>
</ul>
</li>
<li><a href="#">Second level</a></li>
<li><a href="#">Second level</a></li>
</ul>
</li>
<li><a href="#">Something else here</a></li>
</ul>
</div>
</div>
</code></pre>
<p>Here is my CSS;</p>
<pre><code>.dropdown-submenu{position:relative;}
.dropdown-submenu>.dropdown-menu{top:0;left:-95%;max-width:180px;margin-top:-6px;margin-right:-1px;-webkit-border-radius:6px 6px 6px 6px;-moz-border-radius:6px 6px 6px 6px;border-radius:6px 6px 6px 6px;}
.dropdown-submenu:hover>.dropdown-menu{display:block;}
.dropdown-submenu>a:after{display:block;content:" ";float:left;width:0;height:0;border-color:transparent;border-style:solid;border-width:5px 5px 5px 0;border-right-color:#999;margin-top:5px;margin-right:10px;}
.dropdown-submenu:hover>a:after{border-left-color:#ffffff;}
.dropdown-submenu.pull-left{float:none;}
.dropdown-submenu.pull-left>.dropdown-menu{left:-100%;margin-left:10px;-webkit-border-radius:6px 6px 6px 6px;-moz-border-radius:6px 6px 6px 6px;border-radius:6px 6px 6px 6px;}
.dropdown-menu-right {margin-left:0;}
</code></pre>
| 0 | 1,396 |
python/pip error on osx
|
<p>I've recently purchased a new hard drive and installed a clean copy of OS X Mavericks. I installed python using homebrew and i need to create a python virtual environment. But when ever i try to run any command using pip, I get this error. I haven't been able to find a solution online for this problem. Any reference would be appreciated. Here is the error I'm getting. </p>
<pre><code>ERROR:root:code for hash md5 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 139, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type md5
ERROR:root:code for hash sha1 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 139, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha1
ERROR:root:code for hash sha224 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 139, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha224
ERROR:root:code for hash sha256 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 139, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha256
ERROR:root:code for hash sha384 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 139, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha384
ERROR:root:code for hash sha512 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 139, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 91, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha512
Traceback (most recent call last):
File "/usr/local/bin/pip", line 9, in <module>
load_entry_point('pip==1.5.6', 'console_scripts', 'pip')()
File "build/bdist.macosx-10.9-x86_64/egg/pkg_resources.py", line 356, in load_entry_point
File "build/bdist.macosx-10.9-x86_64/egg/pkg_resources.py", line 2439, in load_entry_point
File "build/bdist.macosx-10.9-x86_64/egg/pkg_resources.py", line 2155, in load
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/__init__.py", line 10, in <module>
from pip.util import get_installed_distributions, get_prog
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/util.py", line 18, in <module>
from pip._vendor.distlib import version
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/version.py", line 14, in <module>
from .compat import string_types
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/compat.py", line 31, in <module>
from urllib2 import (Request, urlopen, URLError, HTTPError,
ImportError: cannot import name HTTPSHandler
</code></pre>
<p>If you need any extra information from me let me know, this is my first time posting a question here. Thanks.</p>
| 0 | 1,814 |
Sending array of string as a parameter to web service method using JAXRPC
|
<p>I've got problem sending an array of string as parameter to a web service method, given in a specific wsdl. When am trying to send an array of strings, I get the following error.</p>
<h2>Error:</h2>
<pre><code>AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: org.xml.sax.SAXException: Bad types (class java.util.ArrayList &gt;
class usdjws65.ArrayOfString)
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}hostname:SSLSPSD001
org.xml.sax.SAXException: Bad types (class java.util.ArrayList -> class usdjws65.ArrayOfString)
at org.apache.axis.message.SOAPFaultBuilder.createFault(SOAPFaultBuilder.java:222)
at org.apache.axis.message.SOAPFaultBuilder.endElement(SOAPFaultBuilder.java:129)
at org.apache.axis.encoding.DeserializationContext.endElement(DeserializationContext.java:1087)
</code></pre>
<h2>Code written:</h2>
<pre><code>Call call1 = objService1.createCall(port1);
call1.setTargetEndpointAddress(targetEndPoint);
call1.addParameter("int_1", XMLType.XSD_INT, Integer.class,
ParameterMode.IN);
call1.addParameter("String_1", QNAME_TYPE_STRING, ParameterMode.IN);
call1.addParameter("String_2", QNAME_TYPE_STRING_ARRAY,
java.lang.String[].class, ParameterMode.IN);
call1.addParameter("String_3", QNAME_TYPE_STRING_ARRAY,
java.lang.String[].class, ParameterMode.IN);
call1.addParameter("String_4", QNAME_TYPE_STRING, ParameterMode.IN);
call1.addParameter("String_5", QNAME_TYPE_STRING_ARRAY,
java.lang.String[].class, ParameterMode.IN);
call1.addParameter("String_6", QNAME_TYPE_STRING, ParameterMode.IN);
call1.addParameter("String_7", QNAME_TYPE_STRING, ParameterMode.IN);
// --- Done adding PARAM's
String[] attrVals = { "description", "test from soapUI",
"customer", ticketHandle, "type", "I" };
String[] attributes = { "status", "ref_num" };
Object[] params1 = { new Integer(sid), ticketHandle, attrVals, "",
"cr_tpl:400005", attributes, "", "" };
String res = null;
try {
call1.invoke(params1);
</code></pre>
<p>Thanks !!!!
-Aj</p>
<p>=========================================================</p>
<h2><strong>Update-1</strong>:</h2>
<p>I added a class named ArrayOfString with following code in it.
protected java.lang.String[] string;</p>
<pre><code>public ArrayOfString() {
}
public ArrayOfString(java.lang.String[] string) {
this.string = string;
}
public java.lang.String[] getString() {
return string;
}
public void setString(java.lang.String[] string) {
this.string = string;
}
</code></pre>
<p>and thus did the following,
ArrayOfString attrVals = new ArrayOfString();
attrVals.setString(new String[] { "customer", "test from soapUI",
"customer", ticketHandle, "type", "I" });</p>
<p>Similarly, for attributes variable of type 'ArrayOfString'.</p>
<p>But now, I get the following error:: </p>
<blockquote>
<p>AxisFault
faultCode: {<a href="http://schemas.xmlsoap.org/soap/envelope/" rel="nofollow">http://schemas.xmlsoap.org/soap/envelope/</a>}Server.userException
faultSubcode:
faultString: java.io.IOException: No serializer found for class ArrayOfString in registry org.apache.axis.encoding.TypeMappingDelegate@ef2c60
faultActor:
faultNode:
faultDetail:
{<a href="http://xml.apache.org/axis/" rel="nofollow">http://xml.apache.org/axis/</a>}stackTrace:java.io.IOException: No serializer found for class ArrayOfString in registry org.apache.axis.encoding.TypeMappingDelegate@ef2c60
at org.apache.axis.encoding.SerializationContext.serializeActual(SerializationContext.java:1507)
at org.apache.axis.encoding.SerializationContext.serialize(SerializationContext.java:980)
at org.apache.axis.encoding.SerializationContext.outputMultiRefs(SerializationContext.java:1055)
at org.apache.axis.message.SOAPBody.outputImpl(SOAPBody.java:145)
at org.apache.axis.message.SOAPEnvelope.outputImpl(SOAPEnvelope.java:478)
at org.apache.axis.message.MessageElement.output(MessageElement.java:1208)
at org.apache.axis.client.Call.invoke(Call.java:2757)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)</p>
</blockquote>
<hr>
<h2><strong>Update-2:</strong></h2>
<p>Here is an update on the problem that am facing. In the WSDL file, I found something like this,</p>
<pre><code>complexType name="ArrayOfString"
sequence
element maxOccurs="unbounded" name="string" type="xsd:string" /
/sequence
/complexType
</code></pre>
<p>Well, now that am meant to use this method, </p>
<pre><code> <element name="createRequest">
<complexType>
<sequence>
<element name="sid" type="xsd:int" />
<element name="creatorHandle" type="xsd:string" />
<element name="attrVals" type="impl:ArrayOfString" />
<element name="propertyValues" type="impl:ArrayOfString" />
<element name="template" type="xsd:string" />
<element name="attributes" type="impl:ArrayOfString" />
<element name="newRequestHandle" type="xsd:string" />
<element name="newRequestNumber" type="xsd:string" />
</sequence>
</complexType>
</element>
</code></pre>
<p>Now, I tried sending the parameters 'attrVals','attibutes' like this</p>
<pre><code>ArrayOfstring attrVals = new ArrayOfstring();
ArrayOfstring attributes = new ArrayOfstring();
attrVals.setString(new String[] { "customer", "test from soapUI",
"customer", ticketHandle, "type", "I" });
attributes.setString(new String[] { "status", "ref_num" });
</code></pre>
<p>Its throwing the following exception</p>
<pre><code>AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: java.io.IOException: No serializer found for class org.tempuri.complex.data.arrays.xsd.ArrayOfstring in registry org.apache.axis.encoding.TypeMappingDelegate@11e1e67
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}stackTrace:java.io.IOException: No serializer found for class org.tempuri.complex.data.arrays.xsd.ArrayOfstring in registry org.apache.axis.encoding.TypeMappingDelegate@11e1e67
at org.apache.axis.encoding.SerializationContext.serializeActual(SerializationContext.java:1507)
at org.apache.axis.encoding.SerializationContext.serialize(SerializationContext.java:980)
</code></pre>
| 0 | 2,585 |
Weblogic 12c - Connection was forcibly closed by the remote host
|
<p>can someone please help me resolve the following exception,</p>
<pre><code><Feb 10, 2015 11:43:47 AM CST> <Error> <HTTP> <BEA-101019> <[ServletContext@1297842065[app:_auto_generated_ear_ module:dmportal path:null spec-version:3.0]] Servlet failed with an IOException.
java.io.IOException: An existing connection was forcibly closed by the remote Host
at sun.nio.ch.SocketDispatcher.write0(Native Method)
at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:51)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
at sun.nio.ch.IOUtil.write(IOUtil.java:65)
at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:470)
Truncated. see log file for complete stacktrace
<Feb 10, 2015 11:43:50 AM CST> <Error> <HTTP> <BEA-101020> <[ServletContext@1297842065[app:_auto_generated_ear_ module:dmportal path:null spec-version:3.0]] Servlet failed with an Exception
weblogic.servlet.internal.ServletNestedRuntimeException: Cannot parse POST parameters of request: '/dmportal/pushTime.do'
at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.mergePostParams(ServletRequestImpl.java:2426)
at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.parseQueryParams(ServletRequestImpl.java:2243)
at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.peekParameter(ServletRequestImpl.java:2462)
at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.peekPostParameter(ServletRequestImpl.java:2445)
at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.access$2600(ServletRequestImpl.java:2014)
Truncated. see log file for complete stacktrace
Caused By: java.net.ProtocolException: EOF after reading only: '0' of: '16' promised bytes, out of which at least: '0' were already buffered
at weblogic.servlet.internal.PostInputStream.complain(PostInputStream.java:84)
at weblogic.servlet.internal.PostInputStream.read(PostInputStream.java:189)
at weblogic.servlet.internal.ServletInputStreamImpl$1.read(ServletInputStreamImpl.java:189)
at weblogic.servlet.internal.ServletInputStreamImpl.read(ServletInputStreamImpl.java:251)
at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.mergePostParams(ServletRequestImpl.java:2400)
Truncated. see log file for complete stacktrace
<Feb 10, 2015 11:43:50 AM CST> <Error> <Kernel> <BEA-000802> <ExecuteRequest failed
java.lang.AssertionError: Assertion violated.
java.lang.AssertionError: Assertion violated
at weblogic.utils.Debug.assertion(Debug.java:58)
at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.mergePostParams(ServletRequestImpl.java:2404)
at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.parseQueryParams(ServletRequestImpl.java:2243)
at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.peekParameter(ServletRequestImpl.java:2462)
at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.peekPostParameter(ServletRequestImpl.java:2445)
Truncated. see log file for complete stacktrace
</code></pre>
<p>I am using Oracle OEPE eclipse with weblogic 12c. It was working fine before i started working on the Mobile application. </p>
<p>i have installed following plugins in my eclipse.
1. Android Tools
2. JBoos Hybrid Mobile tools</p>
<p>The following open source installed on my pc
1. Node Js
2. Cordova
3. Ripple emulator</p>
| 0 | 1,202 |
How to create dynamic routes with react-router-dom?
|
<p>I learn react and know, how to create static routes, but can't figure out with dynamic ones. Maybe someone can explain, I'll be very grateful. Let there be two components, one for rendering routes, and another as a template of a route. Maybe something wrong in the code, but hope You understand..</p>
<p>Here is the component to render routes:</p>
<pre><code>import React, { Component } from 'react';
import axios from 'axios';
import Hero from './Hero';
class Heroes extends Component {
constructor(props) {
super(props);
this.state = {
heroes: [],
loading: true,
error: false,
};
}
componentDidMount() {
axios.get('http://localhost:5555/heroes')
.then(res => {
const heroes = res.data;
this.setState({ heroes, loading: false });
})
.catch(err => { // log request error and prevent access to undefined state
this.setState({ loading: false, error: true });
console.error(err);
})
}
render() {
if (this.state.loading) {
return (
<div>
<p> Loading... </p>
</div>
)
}
if (this.state.error || !this.state.heroes) {
return (
<div>
<p> An error occured </p>
</div>
)
}
return (
<div>
<BrowserRouter>
//what should be here?
</BrowserRouter>
</div>
);
}
}
export default Heroes;
</code></pre>
<p>The requested JSON looks like this:</p>
<pre><code>const heroes = [
{
"id": 0,
"name": "John Smith",
"speciality": "Wizard"
},
{
"id": 1,
"name": "Crag Hack",
"speciality": "Viking"
},
{
"id": 2,
"name": "Silvio",
"speciality": "Warrior"
}
];
</code></pre>
<p>The route component (maybe there should be props, but how to do it in the right way):</p>
<pre><code>import React, { Component } from 'react';
class Hero extends Component {
render() {
return (
<div>
//what should be here?
</div>
);
}
}
export default Hero;
</code></pre>
<p>I need something like this in browser, and every route url should be differentiaie by it's id (heroes/1, heroes/2 ...):</p>
<p><strong>John Smith
Crag Hack
Silvio</strong></p>
<p><em>Each of them:</em></p>
<p><strong>John Smith.
Wizard.</strong></p>
<p><em>and so on...</em></p>
<p>Many thanks for any help!)</p>
| 0 | 1,068 |
What is the fastest way to get the value of π?
|
<p>I'm looking for the fastest way to obtain the value of π, as a personal challenge. More specifically, I'm using ways that don't involve using <code>#define</code> constants like <code>M_PI</code>, or hard-coding the number in.</p>
<p>The program below tests the various ways I know of. The inline assembly version is, in theory, the fastest option, though clearly not portable. I've included it as a baseline to compare against the other versions. In my tests, with built-ins, the <code>4 * atan(1)</code> version is fastest on GCC 4.2, because it auto-folds the <code>atan(1)</code> into a constant. With <code>-fno-builtin</code> specified, the <code>atan2(0, -1)</code> version is fastest.</p>
<p>Here's the main testing program (<code>pitimes.c</code>):</p>
<pre class="lang-c prettyprint-override"><code>#include <math.h>
#include <stdio.h>
#include <time.h>
#define ITERS 10000000
#define TESTWITH(x) { \
diff = 0.0; \
time1 = clock(); \
for (i = 0; i < ITERS; ++i) \
diff += (x) - M_PI; \
time2 = clock(); \
printf("%s\t=> %e, time => %f\n", #x, diff, diffclock(time2, time1)); \
}
static inline double
diffclock(clock_t time1, clock_t time0)
{
return (double) (time1 - time0) / CLOCKS_PER_SEC;
}
int
main()
{
int i;
clock_t time1, time2;
double diff;
/* Warmup. The atan2 case catches GCC's atan folding (which would
* optimise the ``4 * atan(1) - M_PI'' to a no-op), if -fno-builtin
* is not used. */
TESTWITH(4 * atan(1))
TESTWITH(4 * atan2(1, 1))
#if defined(__GNUC__) && (defined(__i386__) || defined(__amd64__))
extern double fldpi();
TESTWITH(fldpi())
#endif
/* Actual tests start here. */
TESTWITH(atan2(0, -1))
TESTWITH(acos(-1))
TESTWITH(2 * asin(1))
TESTWITH(4 * atan2(1, 1))
TESTWITH(4 * atan(1))
return 0;
}
</code></pre>
<p>And the inline assembly stuff (<code>fldpi.c</code>) that will only work for x86 and x64 systems:</p>
<pre class="lang-c prettyprint-override"><code>double
fldpi()
{
double pi;
asm("fldpi" : "=t" (pi));
return pi;
}
</code></pre>
<p>And a build script that builds all the configurations I'm testing (<code>build.sh</code>):</p>
<pre><code>#!/bin/sh
gcc -O3 -Wall -c -m32 -o fldpi-32.o fldpi.c
gcc -O3 -Wall -c -m64 -o fldpi-64.o fldpi.c
gcc -O3 -Wall -ffast-math -m32 -o pitimes1-32 pitimes.c fldpi-32.o
gcc -O3 -Wall -m32 -o pitimes2-32 pitimes.c fldpi-32.o -lm
gcc -O3 -Wall -fno-builtin -m32 -o pitimes3-32 pitimes.c fldpi-32.o -lm
gcc -O3 -Wall -ffast-math -m64 -o pitimes1-64 pitimes.c fldpi-64.o -lm
gcc -O3 -Wall -m64 -o pitimes2-64 pitimes.c fldpi-64.o -lm
gcc -O3 -Wall -fno-builtin -m64 -o pitimes3-64 pitimes.c fldpi-64.o -lm
</code></pre>
<p>Apart from testing between various compiler flags (I've compared 32-bit against 64-bit too because the optimizations are different), I've also tried switching the order of the tests around. But still, the <code>atan2(0, -1)</code> version still comes out on top every time.</p>
| 0 | 1,623 |
Set CultureInfo in Asp.net Core to have a . as CurrencyDecimalSeparator instead of ,
|
<p>I'm going mad. I just want the culture used in the entire Asp.net core application to be set to "en-US". But nothing seems to work. Where to I set the culture for the entire application? I'm not interested in client browser cultures and what not. The only thing that seems to change it is changing the language settings of Windows. I just want the culture to be determined from within the application itself, not by the client.</p>
<p>What I have tried so far:</p>
<ul>
<li>Set <code><system.web><globalization uiCulture="en" culture="en-US" /></system.web></code> in web.config</li>
<li>Set <code>System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;</code> and <code>CurrentUICulture</code> in Startup.Configure and even in the controller.</li>
<li><p>Use <code>app.UseRequestLocalization(..</code> as shown below</p>
<pre><code> var enUsCulture = new CultureInfo("en-US");
var localizationOptions = new RequestLocalizationOptions()
{
SupportedCultures = new List<CultureInfo>()
{
enUsCulture
},
SupportedUICultures = new List<CultureInfo>()
{
enUsCulture
},
DefaultRequestCulture = new RequestCulture(enUsCulture),
FallBackToParentCultures = false,
FallBackToParentUICultures = false,
RequestCultureProviders = null
};
app.UseRequestLocalization(localizationOptions);
</code></pre></li>
</ul>
<p>But nothing seems to change the CurrencyDecimalSeparator from (nl-NL) , to (en-US).</p>
<p>How can the culture be set?</p>
<p><strong>EDIT:</strong>
@soren
This is how the configure method looks like. I've put a breakpoint on <code>DetermineProviderCultureResult</code> but it is never hit while visiting the website.</p>
<pre><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, FinOsDbContext context)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
// Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
//TODO: Clean up
//var cultureInfo = new CultureInfo("en-US");
//System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
//System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;
app.UseRequestLocalization();
// UseCookieAuthentication..
// UseJwtBearerAuthentication..
//add userculture provider for authenticated user
var requestOpt = new RequestLocalizationOptions();
requestOpt.SupportedCultures = new List<CultureInfo>
{
new CultureInfo("en-US")
};
requestOpt.SupportedUICultures = new List<CultureInfo>
{
new CultureInfo("en-US")
};
requestOpt.RequestCultureProviders.Clear();
requestOpt.RequestCultureProviders.Add(new SingleCultureProvider());
app.UseRequestLocalization(requestOpt);
FinOsDbContext.Initialize(context);
FinOsDbContext.CreateTestData(context);
}
public class SingleCultureProvider : IRequestCultureProvider
{
public Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
return Task.Run(() => new ProviderCultureResult("en-US", "en-US"));
}
}
</code></pre>
| 0 | 1,576 |
macOS 10.12 brew install openssl issue
|
<p>Trying to install openssl on homebrew using:</p>
<pre><code>brew install openssl
</code></pre>
<p>Is giving the following error during make:</p>
<pre><code>clang -I. -Iinclude -fPIC -arch x86_64 -O3 -Wall -DL_ENDIAN -DOPENSSL_PIC -DOPENSSL_CPUID_OBJ -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DKECCAK1600_ASM -DRC4_ASM -DMD5_ASM -DAESNI_ASM -DVPAES_ASM -DGHASH_ASM -DECP_NISTZ256_ASM -DX25519_ASM -DPOLY1305_ASM -DOPENSSLDIR="\"/usr/local/etc/openssl@1.1\"" -DENGINESDIR="\"/usr/local/Cellar/openssl@1.1/1.1.1l/lib/engines-1.1\"" -D_REENTRANT -DNDEBUG -MMD -MF crypto/rand/randfile.d.tmp -MT crypto/rand/randfile.o -c -o crypto/rand/randfile.o crypto/rand/randfile.c
In file included from crypto/rand/rand_unix.c:38:
/usr/include/CommonCrypto/CommonRandom.h:35:9: error: unknown type name 'CCCryptorStatus'
typedef CCCryptorStatus CCRNGStatus;
^
crypto/rand/rand_unix.c:385:47: error: use of undeclared identifier 'kCCSuccess'
if (CCRandomGenerateBytes(buf, buflen) == kCCSuccess)
^
2 errors generated.
make[1]: *** [crypto/rand/rand_unix.o] Error 1
make[1]: *** Waiting for unfinished jobs....
make: *** [all] Error 2
Do not report this issue to Homebrew/brew or Homebrew/core!
</code></pre>
<p>Brew is trying to install openssl 1.1.1l:</p>
<pre><code>==> Downloading https://www.openssl.org/source/openssl-1.1.1l.tar.gz
Already downloaded: /Users/user/Library/Caches/Homebrew/downloads/b6ccc5a2a602c2af3480bbcf1656bd9844595974ba60501871ac12504508e818--openssl-1.1.1l.tar.gz
</code></pre>
<p>I need this dependency to install many other applications/tools, e.g., wget or python - and would like to use homebrew to do this.</p>
<p>The brew version I am using is:</p>
<pre><code>Homebrew 3.2.9
Homebrew/homebrew-core (git revision fa395c6627; last commit 2021-08-27)
Homebrew/homebrew-cask (git revision 606ed52390; last commit 2021-08-27)
</code></pre>
<p>macOS is: 10.12.6 (Sierra) and I am using a MacBook Pro (13-inch, Early 2011)</p>
<p>Is there any way I can get around this issue to install openssl? Or anyway I can install python specifying a different openssl to use as a dependency?</p>
<p>I was able to install openssl 1.0 using the following brew command:</p>
<pre><code>brew install rbenv/tap/openssl@1.0
</code></pre>
<p>However, python continually tries to use openssl 1.1.1l which is failing with the above error.</p>
| 0 | 1,053 |
Why do I get Gson builder error when starting a Spring Boot application?
|
<p>I have downloaded eclipse and installed the spring suit into it.
I have written a JPA based Rest application by following one of the spring.io guides. When I try to run it as spring boot application.
I get the following error.</p>
<pre><code>java.lang.NoSuchMethodError: com.google.gson.GsonBuilder.setLenient()Lcom/google/gson/GsonBuilder;
</code></pre>
<p>Why am I getting this error? How do I fix this error?</p>
<p>Here is the full output from the console.</p>
<pre><code> . ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.1.RELEASE)
2018-04-25 21:58:28.303 INFO 3574 --- [ main] .m.e.UserProfileEntityServiceApplication : Starting UserProfileEntityServiceApplication on Ajays-MBP.lan with PID 3574 (/Users/ajayamrite/workspaces/meghdoot_spring/UserProfileEntityService/target/classes started by ajayamrite in /Users/ajayamrite/workspaces/meghdoot_spring/UserProfileEntityService)
2018-04-25 21:58:28.306 INFO 3574 --- [ main] .m.e.UserProfileEntityServiceApplication : No active profile set, falling back to default profiles: default
2018-04-25 21:58:28.359 INFO 3574 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@3bd40a57: startup date [Wed Apr 25 21:58:28 BST 2018]; root of context hierarchy
2018-04-25 21:58:29.557 INFO 3574 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'httpRequestHandlerAdapter' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]]
2018-04-25 21:58:30.142 INFO 3574 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$8d2d15cf] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-04-25 21:58:30.553 INFO 3574 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-04-25 21:58:30.612 INFO 3574 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-04-25 21:58:30.612 INFO 3574 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.29
2018-04-25 21:58:30.617 INFO 3574 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/ajayamrite/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2018-04-25 21:58:30.716 INFO 3574 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-04-25 21:58:30.716 INFO 3574 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2360 ms
2018-04-25 21:58:30.826 INFO 3574 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-04-25 21:58:30.830 INFO 3574 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-04-25 21:58:30.831 INFO 3574 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-04-25 21:58:30.831 INFO 3574 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-04-25 21:58:30.831 INFO 3574 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-04-25 21:58:31.049 INFO 3574 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
Wed Apr 25 21:58:31 BST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2018-04-25 21:58:31.311 INFO 3574 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2018-04-25 21:58:31.373 INFO 3574 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
Wed Apr 25 21:58:31 BST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Wed Apr 25 21:58:31 BST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2018-04-25 21:58:31.443 INFO 3574 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
Wed Apr 25 21:58:31 BST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Wed Apr 25 21:58:31 BST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Wed Apr 25 21:58:31 BST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Wed Apr 25 21:58:31 BST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Wed Apr 25 21:58:31 BST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Wed Apr 25 21:58:31 BST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Wed Apr 25 21:58:31 BST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2018-04-25 21:58:31.674 INFO 3574 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.2.16.Final}
2018-04-25 21:58:31.675 INFO 3574 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2018-04-25 21:58:31.717 INFO 3574 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-04-25 21:58:31.854 INFO 3574 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2018-04-25 21:58:32.718 INFO 3574 --- [ main] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@294aba23'
2018-04-25 21:58:32.722 INFO 3574 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-04-25 21:58:33.709 INFO 3574 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-04-25 21:58:33.881 INFO 3574 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@3bd40a57: startup date [Wed Apr 25 21:58:28 BST 2018]; root of context hierarchy
2018-04-25 21:58:33.917 WARN 3574 --- [ main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2018-04-25 21:58:33.947 INFO 3574 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-04-25 21:58:33.947 INFO 3574 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-04-25 21:58:33.967 INFO 3574 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-04-25 21:58:33.967 INFO 3574 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-04-25 21:58:33.977 INFO 3574 --- [ main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in repositoryRestExceptionHandler
2018-04-25 21:58:34.103 WARN 3574 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'gsonBuilder' defined in class path resource [org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.google.gson.GsonBuilder]: Factory method 'gsonBuilder' threw exception; nested exception is java.lang.BootstrapMethodError: java.lang.NoSuchMethodError: com.google.gson.GsonBuilder.setLenient()Lcom/google/gson/GsonBuilder;
2018-04-25 21:58:34.103 INFO 3574 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2018-04-25 21:58:34.105 INFO 3574 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2018-04-25 21:58:34.106 INFO 3574 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2018-04-25 21:58:34.109 INFO 3574 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2018-04-25 21:58:34.110 INFO 3574 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-04-25 21:58:34.120 INFO 3574 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-04-25 21:58:34.128 ERROR 3574 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'gsonBuilder' defined in class path resource [org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.google.gson.GsonBuilder]: Factory method 'gsonBuilder' threw exception; nested exception is java.lang.BootstrapMethodError: java.lang.NoSuchMethodError: com.google.gson.GsonBuilder.setLenient()Lcom/google/gson/GsonBuilder;
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:541) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at co.uk.meghdoot.entity.UserProfileEntityServiceApplication.main(UserProfileEntityServiceApplication.java:12) [classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.google.gson.GsonBuilder]: Factory method 'gsonBuilder' threw exception; nested exception is java.lang.BootstrapMethodError: java.lang.NoSuchMethodError: com.google.gson.GsonBuilder.setLenient()Lcom/google/gson/GsonBuilder;
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
... 18 common frames omitted
Caused by: java.lang.BootstrapMethodError: java.lang.NoSuchMethodError: com.google.gson.GsonBuilder.setLenient()Lcom/google/gson/GsonBuilder;
at org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration$StandardGsonBuilderCustomizer.customize(GsonAutoConfiguration.java:96) ~[spring-boot-autoconfigure-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration.lambda$gsonBuilder$0(GsonAutoConfiguration.java:49) ~[spring-boot-autoconfigure-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at java.util.ArrayList.forEach(ArrayList.java:1249) ~[na:1.8.0_144]
at org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration.gsonBuilder(GsonAutoConfiguration.java:49) ~[spring-boot-autoconfigure-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration$$EnhancerBySpringCGLIB$$cbe82959.CGLIB$gsonBuilder$1(<generated>) ~[spring-boot-autoconfigure-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration$$EnhancerBySpringCGLIB$$cbe82959$$FastClassBySpringCGLIB$$6d1b6b91.invoke(<generated>) ~[spring-boot-autoconfigure-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration$$EnhancerBySpringCGLIB$$cbe82959.gsonBuilder(<generated>) ~[spring-boot-autoconfigure-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
... 19 common frames omitted
Caused by: java.lang.NoSuchMethodError: com.google.gson.GsonBuilder.setLenient()Lcom/google/gson/GsonBuilder;
at java.lang.invoke.MethodHandleNatives.resolve(Native Method) ~[na:1.8.0_144]
at java.lang.invoke.MemberName$Factory.resolve(MemberName.java:975) ~[na:1.8.0_144]
at java.lang.invoke.MemberName$Factory.resolveOrFail(MemberName.java:1000) ~[na:1.8.0_144]
at java.lang.invoke.MethodHandles$Lookup.resolveOrFail(MethodHandles.java:1394) ~[na:1.8.0_144]
at java.lang.invoke.MethodHandles$Lookup.linkMethodHandleConstant(MethodHandles.java:1750) ~[na:1.8.0_144]
at java.lang.invoke.MethodHandleNatives.linkMethodHandleConstant(MethodHandleNatives.java:477) ~[na:1.8.0_144]
... 33 common frames omitted
</code></pre>
| 0 | 7,665 |
Exception encountered during context initialization - Incompatible library?
|
<p>I follow <a href="http://websystique.com/springmvc/spring-4-mvc-and-hibernate4-integration-example-using-annotations/" rel="nofollow">this tutorial</a> but after all I get an error, and I don't understand why!!!</p>
<p>This is my pom.xml</p>
<pre><code><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">
<modelVersion>4.0.0</modelVersion>
<groupId>SpringExample</groupId>
<artifactId>SpringExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>5.0.0.GA</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>SpringExample</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</code></pre>
<p></p>
<p>this is my controller</p>
<pre><code>package org.dstech.examplespring.controller;
import java.util.List;
import java.util.Locale;
import javax.validation.Valid;
import org.dstech.examplespring.model.Employee;
import org.dstech.examplespring.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author franksisca
*c
*/
@Controller
@RequestMapping("/")
public class AppController {
@Autowired
EmployeeService service;
@Autowired
MessageSource messageSource;
/*
* This method will list all existing employees.
*/
@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
public String listEmployees(ModelMap model) {
List<Employee> employees = service.findAllEmployees();
model.addAttribute("employees", employees);
return "allemployees";
}
/*
* This method will provide the medium to add a new employee.
*/
@RequestMapping(value = { "/new" }, method = RequestMethod.GET)
public String newEmployee(ModelMap model) {
Employee employee = new Employee();
model.addAttribute("employee", employee);
model.addAttribute("edit", false);
return "registration";
}
/*
* This method will be called on form submission, handling POST request for
* saving employee in database. It also validates the user input
*/
@RequestMapping(value = { "/new" }, method = RequestMethod.POST)
public String saveEmployee(@Valid Employee employee, BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
return "registration";
}
/*
* Preferred way to achieve uniqueness of field [ssn] should be implementing custom @Unique annotation
* and applying it on field [ssn] of Model class [Employee].
*
* Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation
* framework as well while still using internationalized messages.
*
*/
if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){
FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn", new String[]{employee.getSsn()}, Locale.getDefault()));
result.addError(ssnError);
return "registration";
}
service.saveEmployee(employee);
model.addAttribute("success", "Employee " + employee.getName() + " registered successfully");
return "success";
}
/*
* This method will provide the medium to update an existing employee.
*/
@RequestMapping(value = { "/edit-{ssn}-employee" }, method = RequestMethod.GET)
public String editEmployee(@PathVariable String ssn, ModelMap model) {
Employee employee = service.findEmployeeBySsn(ssn);
model.addAttribute("employee", employee);
model.addAttribute("edit", true);
return "registration";
}
/*
* This method will be called on form submission, handling POST request for
* updating employee in database. It also validates the user input
*/
@RequestMapping(value = { "/edit-{ssn}-employee" }, method = RequestMethod.POST)
public String updateEmployee(@Valid Employee employee, BindingResult result,
ModelMap model, @PathVariable String ssn) {
if (result.hasErrors()) {
return "registration";
}
if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){
FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn", new String[]{employee.getSsn()}, Locale.getDefault()));
result.addError(ssnError);
return "registration";
}
service.updateEmployee(employee);
model.addAttribute("success", "Employee " + employee.getName() + " updated successfully");
return "success";
}
/*
* This method will delete an employee by it's SSN value.
*/
@RequestMapping(value = { "/delete-{ssn}-employee" }, method = RequestMethod.GET)
public String deleteEmployee(@PathVariable String ssn) {
service.deleteEmployeeBySsn(ssn);
return "redirect:/list";
}
}
</code></pre>
<p>and this is application initializer</p>
<pre><code>package org.dstech.examplespring.configuration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
/**
* @author franksisca
*
*/
public class HelloWorldInit implements WebApplicationInitializer{
/* (non-Javadoc)
* @see org.springframework.web.WebApplicationInitializer#onStartup(javax.servlet.ServletContext)
*/
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(HelloWorldConfig.class);
context.setServletContext(servletContext);
ServletRegistration.Dynamic servlet =
servletContext.addServlet
("dispatcher", new DispatcherServlet(context));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
</code></pre>
<p>and last, but not least, my console error when i start tomcat</p>
<pre><code>AVVERTENZA: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'appController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.dstech.exam
plespring.service.EmployeeService org.dstech.examplespring.controller.AppController.service; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [org.dstech.examplespring.service.EmployeeService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency
. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
mag 18, 2016 6:09:29 PM org.springframework.web.servlet.DispatcherServlet initServletBean
GRAVE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appController': Injection of autowired dependencies failed; nested exception is org.springfr
amework.beans.factory.BeanCreationException: Could not autowire field: org.dstech.examplespring.service.EmployeeService org.dstech.examplespring.controller.AppController.service; n
ested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.dstech.examplespring.service.EmployeeService] found for dependen
cy: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=tr
ue)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:666)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:538)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:492)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1090)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5231)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5518)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.dstech.examplespring.service.EmployeeService org.dstech.examplespring.controller.A
ppController.service; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.dstech.examplespring.service.EmployeeServ
ice] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotatio
n.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.dstech.examplespring.service.EmployeeService] found for dependency: expe
cted at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
... 28 more
</code></pre>
<p>Can anyone help me? I think it's a problem with jade.time library, but i don't know how to solve. If I use java.util.Date i get the same error.</p>
<hr>
<p>EDIT</p>
<p>Sorry, i forget my service</p>
<pre><code>public interface EmployeeService {
Employee findById(int id);
void saveEmployee(Employee employee);
void updateEmployee(Employee employee);
void deleteEmployeeBySsn(String ssn);
List<Employee> findAllEmployees();
Employee findEmployeeBySsn(String ssn);
boolean isEmployeeSsnUnique(Integer id, String ssn);
}
</code></pre>
<p>and this is my implementation</p>
<pre><code>@Service("employeeService")
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeDao dao;
public Employee findById(int id) {
return dao.findById(id);
}
public void saveEmployee(Employee employee) {
dao.saveEmployee(employee);
}
/*
* Since the method is running with Transaction, No need to call hibernate update explicitly.
* Just fetch the entity from db and update it with proper values within transaction.
* It will be updated in db once transaction ends.
*/
public void updateEmployee(Employee employee) {
Employee entity = dao.findById(employee.getId());
if(entity!=null){
entity.setName(employee.getName());
entity.setJoiningDate(employee.getJoiningDate());
entity.setSalary(employee.getSalary());
entity.setSsn(employee.getSsn());
}
}
public void deleteEmployeeBySsn(String ssn) {
dao.deleteEmployee(ssn);
}
public List<Employee> findAllEmployees() {
return dao.findAllEmployees();
}
public Employee findEmployeeBySsn(String ssn) {
return dao.findEmployeeBySsn(ssn);
}
public boolean isEmployeeSsnUnique(Integer id, String ssn) {
Employee employee = findEmployeeBySsn(ssn);
return ( employee == null || ((id != null) && (employee.getId() == id)));
}
}
</code></pre>
| 0 | 7,589 |
MongooseError: Cast to embedded failed for value
|
<p>I'm creating a mongoose Schema but I'm getting a <code>MongooseError</code>.</p>
<p>This is my Scheme:</p>
<pre><code>let RestaurantSchema = new Schema({
ratings: {
type: [{
id: Number,
value: Number,
_id: false
}],
default: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
{ id: 5, value: 0 }
]
},
menu: [{
ratings: {
type: [{
id: Number,
value: Number,
_id: false
}],
default: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
{ id: 5, value: 0 }
]
}
}]
})
</code></pre>
<p>And this is the error I'm getting: </p>
<pre><code>/var/app/node_modules/mongoose/lib/schema/documentarray.js:322
throw new CastError('embedded', valueInErrorMessage,
^
MongooseError: Cast to embedded failed for value "{ id: 5, value: 0 }" at path "rating"
at CastError (/var/app/node_modules/mongoose/lib/error/cast.js:26:11)
at DocumentArray.cast (/var/app/node_modules/mongoose/lib/schema/documentarray.js:322:19)
at DocumentArray.SchemaType.getDefault (/var/app/node_modules/mongoose/lib/schematype.js:616:23)
at EmbeddedDocument.Document.$__buildDoc (/var/app/node_modules/mongoose/lib/document.js:265:22)
at EmbeddedDocument.Document (/var/app/node_modules/mongoose/lib/document.js:61:20)
at EmbeddedDocument [as constructor] (/var/app/node_modules/mongoose/lib/types/embedded.js:31:12)
at new EmbeddedDocument (/var/app/node_modules/mongoose/lib/schema/documentarray.js:70:17)
at DocumentArray.SchemaArray [as constructor] (/var/app/node_modules/mongoose/lib/schema/array.js:67:21)
at new DocumentArray (/var/app/node_modules/mongoose/lib/schema/documentarray.js:31:13)
at Function.Schema.interpretAsType (/var/app/node_modules/mongoose/lib/schema.js:643:16)
at Schema.path (/var/app/node_modules/mongoose/lib/schema.js:563:29)
at Schema.add (/var/app/node_modules/mongoose/lib/schema.js:445:12)
at new Schema (/var/app/node_modules/mongoose/lib/schema.js:99:10)
at Object.<anonymous> (/var/app/models/restaurant.js:12:24)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/var/app/controllers/restaurant.js:6:18)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
</code></pre>
<p>What am I doing wrong?</p>
| 0 | 1,489 |
<input> tag validation for URL
|
<p>I am trying to validate an URL using JavaScript, but for some reason it's not working. When someone has not entered any URL, it shows message like:</p>
<blockquote>
<p>Please enter valid URL.(i.e. http://)</p>
</blockquote>
<p>I am trying to fix it, but can't make it working.</p>
<p>Is there any trick in HTML5 that allows to validate an URL?</p>
<pre><code>$(document).ready(function() {
$("#contactInfos").validate(
{ onfocusout: false, rules: {
phone: { number:true },
zipcode: { number:true },
website: { url:true }
},
messages: { phone: { number:"please enter digit only" },
zipcode: { number:"Plese enter digit only" },
website: { url: "Please enter valid URL.(i.e. http://)" }
}
});
</code></pre>
<p>Validate method for an URL:</p>
<pre><code>url: function(value, element) {
values=value.split(',');
for (x in values)
{
temp=values[x].trim();
temp1=this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(temp);
if(temp1!=true)
{
return false;
}
}
return true;
},
</code></pre>
| 0 | 1,433 |
MySQL Error - Commands out of sync; you can't run this command now
|
<p>I am using MySQL with PHP, Codeigniter. I had a question which was answered by bluefeet in the post <a href="https://stackoverflow.com/questions/16012098/mysql-show-data-in-pivot-view/16013046#16013046">here</a></p>
<p>I created a stored procedure for the second solution by bluefeet. It works perfect, however, while the procedure is called in the production environment, all the other users get the error </p>
<blockquote>
<p>Commands out of sync; you can't run this command now</p>
</blockquote>
<p>Not sure how can i overcome with this error. I also tried closing the connection after the procedure is called, however, Queries from other users are executed before the connection is closed. Any work-around for this issue?</p>
<p>Below is the stored procedure that i have used</p>
<pre><code>DROP PROCEDURE IF EXISTS mailbox.circle_pending_p;
CREATE PROCEDURE mailbox.`circle_pending_p`()
BEGIN
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'sum(CASE WHEN maildate = ''',
date_format(mailtime, '%e-%b'),
''' THEN 1 else 0 END) AS `',
date_format(mailtime, '%e-%b'), '`'
)
) INTO @sql
FROM circle_pending_temp
WHERE mailtime >= (select date_sub(max(mailtime), interval 8 DAY)
from circle_pending_temp);
SET @sql
= CONCAT('SELECT coalesce(email_Circle, ''Grand Total'') Circle,
max(`< 9 days`) `< 9 days`, ', @sql, ' ,
count(*) GrandTotal
from
(
select c.email_Circle,
date_format(c.mailtime, ''%e-%b'') maildate,
coalesce(o.`< 9 days`, 0) `< 9 days`
from circle_pending_temp c
left join
(
select email_Circle,
count(*) `< 9 days`
from circle_pending_temp
where mailtime <= (select date_sub(max(mailtime), interval 8 DAY)
from circle_pending_temp)
) o
on c.email_Circle = o.email_Circle
where c.mailtime >= (select date_sub(max(mailtime), interval 8 DAY)
from circle_pending_temp)
) d
group by email_Circle with rollup ');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
</code></pre>
<p>The PHP that i use for calling this procedure is</p>
<pre><code> $db = $this->load->database('mailbox',TRUE);
$res = $db->query('Call circle_pending_p()');
echo $db->_error_message();
$db->close();
$db = $this->load->database('mailbox',TRUE);
if ($res->num_rows() > 0) {
return $res->result_array();
} else {
return 0;
}
</code></pre>
| 0 | 1,276 |
Append Data in existing Excel file using apache poi in java
|
<p>I am trying to append data in existing excel file .But when i write on it it delete my previous data </p>
<p>File excelRead</p>
<pre><code>package Excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelRead {
static int passRowCount;
int rowCount;
Sheet guru99Sheet;
Workbook guru99Workbook = null;
public void readExcel(String filePath, String fileName, String sheetName) throws IOException, InterruptedException {
// Create a object of File class to open xlsx file
System.out.println(filePath + "\\" + fileName);
File file = new File(filePath + "\\" + fileName);
// Create an object of FileInputStream class to read excel file
FileInputStream inputStream = new FileInputStream(file);
// Find the file extension by spliting file name in substring and
// getting only extension name
String fileExtensionName = fileName.substring(fileName.indexOf("."));
// Check condition if the file is xlsx file
if (fileExtensionName.equals(".xlsx")) {
System.out.println("in xlsx");
// If it is xlsx file then create object of XSSFWorkbook class
guru99Workbook = new XSSFWorkbook(inputStream);
}
// Check condition if the file is xls file
else if (fileExtensionName.equals(".xls")) {
// If it is xls file then create object of XSSFWorkbook class
guru99Workbook = new HSSFWorkbook(inputStream);
}
// Read sheet inside the workbook by its name
guru99Sheet = guru99Workbook.getSheet(sheetName);
System.out.println("getFirstRowNum: " + guru99Sheet.getFirstRowNum());
Thread.sleep(1000);
// Find number of rows in excel file
rowCount = (guru99Sheet.getLastRowNum()) - (guru99Sheet.getFirstRowNum());
System.out.println("rowcount: " + rowCount);
setRowCount(rowCount);
// Create a loop over all the rows of excel file to read it
for (int i = 1; i < rowCount; i++) {
Thread.sleep(1000);
// System.out.println("i: " + i);
Row row = guru99Sheet.getRow(i);
// System.out.println("getLastCellNum : " + row.getLastCellNum());
// Create a loop to print cell values in a row
for (int j = 1; j < row.getLastCellNum(); j++) {
Thread.sleep(1000);
// System.out.println("j: " + j);
// Print excel data in console
System.out.print(row.getCell(j).getStringCellValue() + " ");
// System.out.println("\n");
}
System.out.println();
}
}
public void setRowCount(int rc) {
passRowCount = rc;
}
public int getRowCount() {
return passRowCount;
}
}
</code></pre>
<p>File MainFile</p>
<pre><code>package Excel;
import java.io.IOException;
public class MainFile {
public static void main(String[] args) throws IOException, InterruptedException {
ExcelRead objExcelFile = new ExcelRead();
// Prepare the path of excel file
String filePath = System.getProperty("user.dir") + "\\src\\Excel\\";
// Call read file method of the class to read data
objExcelFile.readExcel(filePath, "TestCase2.xlsx", "Java Books");
AppendDataInExcel appendData = new AppendDataInExcel();
appendData.append();
}
}
</code></pre>
<p>AppendDataInExcel</p>
<pre><code>package Excel;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class AppendDataInExcel {
ExcelRead excelRead = new ExcelRead();
public void append() {
int rowc = excelRead.getRowCount();
System.out.println("rowCountIn Append: " + rowc);
appendWrite(rowc);
}
public void appendWrite(int rowc) {
Object[][] bookData = { { "geography", "ali", "e" }, { "chemistry", "Joeloch", "f" }, { "Code", "rahul", "g" },
{ "phyysics", "banl", "h" }, };
for (Object[] aBook : bookData) {
Row row = s.createRow(++rowc);
System.out.println("Row: " + row.getRowNum());
int columnCount = 0;
for (Object field : aBook) {
Cell cell = row.createCell(++columnCount);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
try {
FileOutputStream outputStream = new FileOutputStream(
new File(System.getProperty("user.dir") + "\\src\\Excel\\TestCase2.xlsx"));
workbook.write(outputStream);
System.out.println("Wrote in Excel");
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
</code></pre>
<p>Sometime whole previous excel data deleted.Just wanted solution to append data at the end of the existing row.This concept is used for to log the execution of my testscript with timestamp.whenever I run script it will write in existing excel so that i can see all history of my execution.</p>
| 0 | 2,410 |
NullPointerException On Android.os.Bundle
|
<p>I have some problem with my code, when I need to transfer some data from one <code>Activity</code> to another one.
First <code>Activity</code> (<code>ViewCashflow</code>) and I want transfer some data from <code>ViewCashflow</code> to second <code>Activity</code> (<code>NewTransaction</code>). Here its working well with no error, the data transferred successfully. But, I don't know what's going on when I run the second <code>Activity</code> directly (not from first <code>Activity</code> like before when I transfer the data) I got null pointer exception on the method that I use to receive the data from first <code>Activity</code>.</p>
<p>I have tried to figure all things there, but still unsolved. In other <code>Activity</code> (<code>ViewCategory</code> and <code>AddCategory</code>) I'm doing the same things (transfer data from <code>ViewCategory</code> to <code>AddCategory</code>) its working well and there's no error when I run <code>AddCategory</code> directly but the code is exactly have same pattern with the two <code>Activity</code> which I got the error.</p>
<p>Please master help me.
Thanks before.</p>
<p>The error report gimme this one:</p>
<blockquote>
<p>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.Bundle.getBoolean(java.lang.String)' on a null object reference
at com.example.ever_ncn.cashflow.NewTransaction.onCreate(NewTransaction.java:68)</p>
</blockquote>
<p>NB. This my code for first <code>Activity</code> (<code>ViewCashflow</code>)</p>
<pre><code>public class ViewCashflow extends ActionBarActivity {
private SQLiteDatabase db;
private static Button BtnIAddCateg;
private static Button BtnICancelCateg;
private static final String TAG = CategorySetting.class.getSimpleName();
DatabaseHelper dBHelper = new DatabaseHelper (this);
private ListView list;
private ArrayList<String> arrTransId = new ArrayList<String>();
private ArrayList<String> arrTransName = new ArrayList<String>();
private ArrayList<String> arrTransAmount = new ArrayList<String>();
private ArrayList<String> arrTransType= new ArrayList<String>();
private ArrayList<String> arrTransDate= new ArrayList<String>();
private ArrayList<String> arrCategId= new ArrayList<String>();
private AlertDialog.Builder build;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_cashflow);
displayData();
}
//udah beres udah bisa show, tinggal action click udh bisa tp value blm pindah,,
//penggunaan Radio Button belum nanti di NewTrans
private void displayData() {
db = dBHelper.getReadableDatabase();
Cursor mCursor = db.rawQuery("SELECT * FROM " + dBHelper.TABLE_Trans_NAME, null);
list = (ListView)findViewById(android.R.id.list);
arrTransId.clear();
arrTransName.clear();
arrTransAmount.clear();
arrTransType.clear();
arrTransDate.clear();
arrCategId.clear();
if (mCursor.moveToFirst()) {
do {
arrTransId.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.TOL1)));
arrTransName.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.TOL2)));
arrTransAmount.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.TOL3)));
arrTransType.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.TOL4)));
arrTransDate.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.TOL5)));
arrCategId.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.TOL6)));
} while (mCursor.moveToNext());
}
DisplayAdapterTrans disadptr = new DisplayAdapterTrans(ViewCashflow.this, arrTransId, arrTransName,
arrTransAmount, arrTransType, arrTransDate, arrCategId);
list.setAdapter(disadptr);
mCursor.close();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//click to update data
// namanya blom diubah coeg
Intent i = new Intent(getApplicationContext(), NewTransaction.class);
i.putExtra("TransId", arrTransId.get(arg2));
i.putExtra("TransName", arrTransName.get(arg2));
i.putExtra("TransAmount", arrTransAmount.get(arg2));
i.putExtra("TransType", arrTransType.get(arg2));
i.putExtra("TransDate", arrTransDate.get(arg2));
i.putExtra("TransCategId", arrCategId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_view_cashflow, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p>And this one for second <code>Activity</code> (<code>NewTransaction</code>)</p>
<pre><code>public class NewTransaction extends ActionBarActivity {
Button btnIDate;
Button btnIAdd;
Button btnICancel;
RadioButton RdIncome;
RadioButton RdOutcome;
EditText txtAmount, txtCashflow, txtType;
DatabaseHelper dbHelper = new DatabaseHelper(this);
SQLiteDatabase db;
MainActivity mainAct = new MainActivity();
int year_x, month_x, day_x;
static final int DIALOG_ID=0;
public static long dateSelected;
public static Integer intAmount = null;
private boolean isUpdate;
private String id, transname, transamount, transtype, transdate, transcategid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_transaction);
txtAmount = (EditText)findViewById(R.id.txtAmount);
txtCashflow = (EditText)findViewById(R.id.txtCashflow);
txtType = (EditText)findViewById(R.id.txtType);
RdIncome = (RadioButton)findViewById(R.id.RdBtnIncome);
RdOutcome = (RadioButton)findViewById(R.id.RdBtnOutcome);
final Calendar cal = Calendar.getInstance();
year_x = cal.get(Calendar.YEAR);
month_x = cal.get(Calendar.MONTH);
day_x = cal.get(Calendar.DAY_OF_MONTH);
TextView lblIDate = (TextView)findViewById(R.id.lblDate);
lblIDate.setText("Date selected : " + year_x + "-" + month_x + "-" + day_x);
//EditText lbltxt = (EditText)findViewById(R.id.txtType);
dateSelected = (year_x+month_x+day_x);
String catSelected = mainAct.getCatSelected();
//kena null object dsni entah knapa
showDialogOnClick();
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("TransId");
transname=getIntent().getExtras().getString("TransName");
transamount=getIntent().getExtras().getString("TransAmount");
transtype=getIntent().getExtras().getString("TransType");
transdate=getIntent().getExtras().getString("CategDate");
transcategid=getIntent().getExtras().getString("CategCategId");
txtCashflow.setText(transname);
txtType.setText(transtype);
txtAmount.setText(transamount);
}
if(RdIncome.isChecked()){
txtType.setText("Income");
}else{
txtType.setText("Outcome");
}
onButtonClickButtonListener(dateSelected, catSelected);
}
public void showDialogOnClick(){
//TextView lblIDate = (TextView)findViewById(R.id.lblDate);
btnIDate = (Button)findViewById(R.id.btnDate);
btnIDate.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DIALOG_ID);
}
}
);
}
@Override
protected Dialog onCreateDialog(int id){
if (id == DIALOG_ID)
return new DatePickerDialog(this, dpickerListener , year_x, month_x, day_x);
return null;
}
public DatePickerDialog.OnDateSetListener dpickerListener
= new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
TextView lblIDate = (TextView)findViewById(R.id.lblDate);
year_x= year;
month_x = monthOfYear + 1;
day_x = dayOfMonth;
lblIDate.setText("Date selected : " + year_x + "-" + month_x + "-" + day_x);
Toast.makeText(NewTransaction.this, year_x + "/" + month_x + "/" + day_x, Toast.LENGTH_LONG).show();
//DateFormat.getDateInstance().format(myDatePicker.getCalendarView().getDate());
}
};
private void clearText(){
txtCashflow.clearComposingText();
txtAmount.clearComposingText();
txtType.clearComposingText();
}
public void onButtonClickButtonListener(final long dateSelected, final String catSelected){
btnIAdd = (Button)findViewById(R.id.btnAddTrans);
btnIAdd.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
/*if(RdIncome.isChecked()){
txtType.setText("Income");
}else{
txtType.setText("Outcome");
}*/
if (isUpdate) {
//update
Toast.makeText(NewTransaction.this, "Clicked", Toast.LENGTH_LONG).show();
intAmount = Integer.parseInt(txtAmount.getText().toString());
boolean isInserted = dbHelper.updateTransData(id, txtCashflow.getText().toString(),
intAmount, txtType.getText().toString(),
dateSelected, catSelected, null);
if (isInserted == true) {
Toast.makeText(NewTransaction.this, "Inserted", Toast.LENGTH_LONG).show();
clearText();
Intent intent = new Intent(
NewTransaction.this,
ViewCashflow.class
);
startActivity(intent);
} else
Toast.makeText(NewTransaction.this, "Not Inserted", Toast.LENGTH_LONG).show();
} else {
//insert
Toast.makeText(NewTransaction.this, "Clicked", Toast.LENGTH_LONG).show();
intAmount = Integer.parseInt(txtAmount.getText().toString());
boolean isInserted = dbHelper.insertTransData(txtCashflow.getText().toString(),
intAmount, txtType.getText().toString(),
dateSelected, catSelected, null);
if (isInserted == true) {
Toast.makeText(NewTransaction.this, "Inserted", Toast.LENGTH_LONG).show();
clearText();
Intent intent = new Intent(
NewTransaction.this,
ViewCashflow.class
);
startActivity(intent);
} else
Toast.makeText(NewTransaction.this, "Not Inserted", Toast.LENGTH_LONG).show();
}
}
});
btnICancel = (Button)findViewById(R.id.btnCancelTrans);
btnICancel.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(
NewTransaction.this,
MainActivity.class
);
startActivity(intent);
}
}
);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_new_transaction_, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p>here is my code for <code>CategorySetting</code>/<code>ViewCategory</code> (another <code>Activity</code> that work with this pattern of code) :</p>
<pre><code>public class CategorySetting extends Activity {
private SQLiteDatabase db;
private static Button BtnIAddCateg;
private static Button BtnICancelCateg;
private static final String TAG = CategorySetting.class.getSimpleName();
DatabaseHelper dBHelper = new DatabaseHelper (this);
private ListView list;
private ArrayList<String> arrCategId = new ArrayList<String>();
private ArrayList<String> arrCategName = new ArrayList<String>();
private ArrayList<String> arrCategNote = new ArrayList<String>();
private ArrayList<String> arrCategCurr = new ArrayList<String>();
private AlertDialog.Builder build;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_setting);
onButtonClickButtonListener();
//ListView list = getListView();
//showListView();
displayData();
onLongClickListener();
}
private void displayData() {
db = dBHelper.getReadableDatabase();
Cursor mCursor = db.rawQuery("SELECT * FROM " + dBHelper.TABLE_Categ_NAME, null);
list = (ListView)findViewById(android.R.id.list);
arrCategId.clear();
arrCategName.clear();
arrCategNote.clear();
arrCategCurr.clear();
if (mCursor.moveToFirst()) {
do {
arrCategId.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.COL1)));
arrCategName.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.COL2)));
arrCategNote.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.COL3)));
arrCategCurr.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.COL4)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(CategorySetting.this, arrCategId, arrCategName, arrCategId, arrCategCurr);
list.setAdapter(disadpt);
mCursor.close();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//click to update data
Intent i = new Intent(getApplicationContext(), AddCategory.class);
i.putExtra("CategId", arrCategId.get(arg2));
i.putExtra("CategName", arrCategName.get(arg2));
i.putExtra("CategNote", arrCategNote.get(arg2));
i.putExtra("CategCurr", arrCategCurr.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
}
private void onLongClickListener(){
ListView list = (ListView)findViewById(android.R.id.list);
list.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
build = new AlertDialog.Builder(CategorySetting.this);
build.setTitle("Delete " + arrCategName.get(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText( getApplicationContext(),
arrCategName.get(arg2) + " is deleted.", Toast.LENGTH_LONG).show();
db.delete(
dBHelper.TABLE_Categ_NAME, dBHelper.COL1 + "=" + arrCategId.get(arg2), null);
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
}
//ListView view = getListView();
//iew.addHeaderView(getLayoutInflater().inflate(R.layout.trans, null));
//db = dBHelper.getWritableDatabase();
//this.muat_ulang();
/*public void reload(){
try {
DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
db = dbHelper.getWritableDatabase();
Cursor c = db.rawQuery("SELECT CategName FROM " + tableName, null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String categName = c.getString(c.getColumnIndex("CategName"));
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (db != null)
db.execSQL("DELETE FROM " + tableName);
db.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.menu_category_setting, menu);
return true;
}
public void onButtonClickButtonListener(){
BtnIAddCateg = (Button)findViewById(R.id.btnAddNewCateg);
BtnIAddCateg.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intentAddCateg = new Intent ("com.example.ever_ncn.cashflow.AddCategory");
intentAddCateg.putExtra("update", false);
startActivity(intentAddCateg);
startActivity(intentAddCateg);
}
}
);
BtnICancelCateg = (Button)findViewById(R.id.btnCancelCateg);
BtnICancelCateg.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(
CategorySetting.this,
MainActivity.class
);
startActivity(intent);
}
}
);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p>and this one for <code>AddCategory</code>:</p>
<pre><code>public class AddCategory extends ActionBarActivity {
private static Button BtnIAdd;
private static Button BtnICancel;
EditText txtcategname, txtType;
Spinner selectCurrency;
ArrayAdapter<CharSequence> adapterCurrency;
DatabaseHelper DbHelper = new DatabaseHelper(this);
SQLiteDatabase db;
private boolean isUpdate;
private String id, categname, categnote, categcurr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
txtcategname = (EditText)findViewById(R.id.editText);
txtType = (EditText)findViewById(R.id.editText2);
BtnICancel = (Button)findViewById(R.id.btnCancel);
BtnIAdd = (Button)findViewById(R.id.btnAdd);
//spinner
selectCurrency = (Spinner) findViewById(R.id.spin_selectCurrency);
adapterCurrency = ArrayAdapter.createFromResource(this, R.array.CurrencyName,android.R.layout.simple_spinner_item );
adapterCurrency.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectCurrency.setAdapter(adapterCurrency);
selectCurrency.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_LONG).show();
String currencyValue = String.valueOf(parent.getSelectedItem());
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("CategId");
categname=getIntent().getExtras().getString("CategName");
categnote=getIntent().getExtras().getString("CategNote");
categcurr=getIntent().getExtras().getString("CategCurr");
txtcategname.setText(categname);
txtType.setText(categnote);
}
addCategData();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_add_category, menu);
return true;
}
public void addCategData(){
BtnIAdd.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(AddCategory.this, "Clicked", Toast.LENGTH_LONG).show();
db=DbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.COL2,categname );
values.put(DbHelper.COL3,categnote );
values.put(DbHelper.COL4,categcurr );
System.out.println("");
if(isUpdate)
{
//update database with new data
boolean isInserted = DbHelper.updateCategData(Integer.parseInt(id), txtcategname.getText().toString(),
txtType.getText().toString(), selectCurrency.getSelectedItem().toString(), null);
if (isInserted == true) {
Toast.makeText(AddCategory.this, "Updated", Toast.LENGTH_LONG).show();
//baru sampe dsni
Intent intent = new Intent(
AddCategory.this,
CategorySetting.class
);
startActivity(intent);
} else
Toast.makeText(AddCategory.this, "Not Inserted", Toast.LENGTH_LONG).show();
}
else
{
//insert data into database
boolean isInserted = DbHelper.insertCategData(txtcategname.getText().toString(),
txtType.getText().toString(), selectCurrency.getSelectedItem().toString(), null);
if (isInserted == true) {
Toast.makeText(AddCategory.this, "Inserted", Toast.LENGTH_LONG).show();
//baru sampe dsni
Intent intent = new Intent(
AddCategory.this,
CategorySetting.class
);
startActivity(intent);
} else
Toast.makeText(AddCategory.this, "Not Inserted", Toast.LENGTH_LONG).show();
}
//close database
db.close();
finish();
}
}
);
BtnICancel.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
}
);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
</code></pre>
| 0 | 11,452 |
How can i change the width/padding of a Flutter DropdownMenuItem in a DropdownButton?
|
<p>How can we change the width/padding of a Flutter DropdownMenuItem in a Dropdown?</p>
<pre><code>Row(
children: <Widget>[
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
LightText(
text: "Agent",
),
Padding(
padding: EdgeInsets.only(top: 3),
),
Container(
height: 27,
child: Row(
children: <Widget>[
DropdownButtonHideUnderline(
child: DropdownButton<Agent>(
// isExpanded: true,
hint: Text(
agentName == null ? "" : agentName,
style: TextStyle(
fontSize: MediaQuery.of(context).size.width * 0.035,
),
),
value: selectedAgent,
onChanged: (Agent value) async {
selectedAgent = value;
agentName = selectedAgent.getAgentName();
agentId = selectedAgent.getAgentId();
},
items: agentList.map((Agent agent) {
return DropdownMenuItem<Agent>(
value: agent,
child: SizedBox(
width: 25.0,
child: LightText(
text: agent.name,
textColor: Colors.black,
),
),
);
}).toList(),
),
),
],
),
decoration: ShapeDecoration(
shape: RoundedRectangleBorder(
side: BorderSide(width: 1.0, color: lightGrey),
borderRadius: BorderRadius.all(Radius.circular(3.0)),
),
),
),
],
),
),
SizedBox(
width: 30,
),
TextBoxData(
labelText: "% Commission",
controllerText: percentageCommision,
enableVal: true,
borderColor: lightGrey,
)
],
)
</code></pre>
| 0 | 1,383 |
Disable security for unit tests with spring boot
|
<p>I'm trying to create a simple spring boot web project with security. I can launch the application fine and the security is working fine. However, I have some components that I want to test without security (or test at all -- I cant get the test working at all).</p>
<p>I get an exception indicating that it can't find an ObjectPostProcessor and thus can't bring up the container. </p>
<p>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.config.annotation.ObjectPostProcessor] found for dependency</p>
<pre>
14:01:50.937 [main] ERROR o.s.boot.SpringApplication - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fmpdfApplication.ApplicationSecurity': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.setObjectPostProcessor(org.springframework.security.config.annotation.ObjectPostProcessor); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.config.annotation.ObjectPostProcessor] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) ~[spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) ~[spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686) ~[spring-boot-1.2.4.RELEASE.jar:1.2.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320) ~[spring-boot-1.2.4.RELEASE.jar:1.2.4.RELEASE]
at org.springframework.boot.test.SpringApplicationContextLoader.loadContext(SpringApplicationContextLoader.java:103) [spring-boot-1.2.4.RELEASE.jar:1.2.4.RELEASE]
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:68) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:86) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:72) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:200) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:259) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:261) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:219) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) [junit-rt.jar:na]
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) [junit-rt.jar:na]
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) [junit-rt.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_45]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_45]
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) [idea_rt.jar:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.setObjectPostProcessor(org.springframework.security.config.annotation.ObjectPostProcessor); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.config.annotation.ObjectPostProcessor] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:649) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 43 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.config.annotation.ObjectPostProcessor] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:606) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 45 common frames omitted
</pre>
<p>I'm not even trying to test anything related to web or security or anything. I'm just unit testing one of my components.
My Unit test (in groovy) is like:</p>
<pre class="lang-java prettyprint-override"><code>@RunWith(SpringJUnit4ClassRunner)
@SpringApplicationConfiguration(classes = FmpdfApplication)
@ActiveProfiles(["test", "mockstore"])
class PdfUpdaterTest {
@Resource PdfUpdater pdfUpdater
...
</code></pre>
<p>And my (relevant) gradle dependencies are:</p>
<pre><code>compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.boot:spring-boot-starter-security")
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-jdbc")
testCompile("org.springframework.boot:spring-boot-starter-test")
</code></pre>
<p>I have tried setting
management.security.enabled=false
security.basic.enabled=false
But that didn't help</p>
<p>One other relevant bit of info: I needed to customize the security so I followed the pattern to:</p>
<pre class="lang-java prettyprint-override"><code>@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
..
</code></pre>
<p>Is this part of the problem? Is there a way to make this @Lazy if that's related?</p>
<p>Update: If I mark the unit test as @WebIntegrationTest then everything works -- but it starts up an embedded tomcat server. How can I disable spring security for unit testing non web things?</p>
| 0 | 4,055 |
Call to undefined function App\Http\Controllers\categories() in Laravel
|
<p>Please I need help, I am working on a project in Laravel, I encounter a problem when T tried to use a pivot table in manay-to-many </p>
<p>In my <code>category model</code> <code>Category.php</code>, I have the function below</p>
<pre><code>public function users()
{
return $this->belongsToMany(user::class);
}
</code></pre>
<p>In my <code>user model</code> <code>User.php</code>, I have the function below</p>
<pre><code>public function authors()
{
return $this->belongsToMany(author::class);
}
</code></pre>
<p>In <code>web.php</code>, I have this</p>
<pre><code>Route::post('/onboarding', 'OnboardsController@categoryUser');
</code></pre>
<p>In my <code>onboarding view</code>, I have a form:</p>
<pre><code> <form action="{{ url('/onboarding') }}" method="POST">
@csrf
@foreach($categories as $category)
<div class="radio-item">
<input class="form control" name="category_id" type="checkbox" id="category_id" required>
<label for="name">{{ $category -> title }}</label>
</div>
@endforeach
<div class="form-row">
<div class="form-group col-md-12 text-center">
<button type="submit">Proceed to Authors</button>
</div>
</div>
</form>
</code></pre>
<p>In my <code>OnboardsController</code></p>
<p>I have this</p>
<pre><code>public function categoryUser (Request $request)
{
$user = User::findOrFail(Auth::user()->id);
$user = categories()->attach($request->input('category_id'));
return redirect ( route ('onboarding_author'));
}
</code></pre>
<p>This is the returned error:</p>
<blockquote>
<p>Call to undefined function App\Http\Controllers\categories()</p>
</blockquote>
<p>When I change the code in my controller to </p>
<pre><code>$category = Category::find($request->input('category_id'));
$user = User::where('user_id', Auth::id());
$category->users()->attach($user->id);
</code></pre>
<p>This is the returned error:</p>
<blockquote>
<p>Call to undefined function App\Http\Controllers\users()</p>
</blockquote>
<p>Here is my full <code>OnboardsController.php</code> code </p>
<pre><code><?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Author;
use App\User;
use App\Category;
class OnboardsController extends Controller
{
public function index()
{
//
return view('onboarding')
->with('categories', Category::all());
}
public function author()
{
//
return view('onboarding_author')
->with('authors', Author::all());
}
public function categoryUser (Request $request)
{
dd(request('category_id'));
Category::findOrFail(request('category_id'))
->users()
->attach(auth()->user()->id);
return redirect ( route ('onboarding_author'));
}
</code></pre>
<p>Please I am new to Laravel and I have been on this for 3 days, I don't know how to solve this. I need help.</p>
| 0 | 1,210 |
FFT on image with Python
|
<p>I have a problem with FFT implementation in Python. I have completely strange results.
Ok so, I want to open image, get value of every pixel in RGB, then I need to use fft on it, and convert to image again.</p>
<p>My steps:</p>
<p>1) I'm opening image with PIL library in Python like this</p>
<pre><code>from PIL import Image
im = Image.open("test.png")
</code></pre>
<p>2) I'm getting pixels</p>
<pre><code>pixels = list(im.getdata())
</code></pre>
<p>3) I'm seperate every pixel to r,g,b values</p>
<pre><code>for x in range(width):
for y in range(height):
r,g,b = pixels[x*width+y]
red[x][y] = r
green[x][y] = g
blue[x][y] = b
</code></pre>
<p>4). Let's assume that I have one pixel (111,111,111). And use fft on all red values like this</p>
<pre><code>red = np.fft.fft(red)
</code></pre>
<p>And then:</p>
<pre><code>print (red[0][0], green[0][0], blue[0][0])
</code></pre>
<p>My output is:</p>
<pre><code>(53866+0j) 111 111
</code></pre>
<p>It's completely wrong I think. My image is 64x64, and FFT from gimp is completely different. Actually, my FFT give me only arrays with huge values, thats why my output image is black.</p>
<p>Do you have any idea where is problem?</p>
<p>[EDIT]</p>
<p>I've changed as suggested to</p>
<pre><code>red= np.fft.fft2(red)
</code></pre>
<p>And after that I scale it</p>
<pre><code>scale = 1/(width*height)
red= abs(red* scale)
</code></pre>
<p>And still, I'm getting only black image.</p>
<p>[EDIT2]</p>
<p>Ok, so lets take one image. <a href="https://i.stack.imgur.com/H6Gp7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/H6Gp7.png" alt="test.png"></a></p>
<p>Assume that I dont want to open it and save as greyscale image. So I'm doing like this.</p>
<pre><code>def getGray(pixel):
r,g,b = pixel
return (r+g+b)/3
im = Image.open("test.png")
im.load()
pixels = list(im.getdata())
width, height = im.size
for x in range(width):
for y in range(height):
greyscale[x][y] = getGray(pixels[x*width+y])
data = []
for x in range(width):
for y in range(height):
pix = greyscale[x][y]
data.append(pix)
img = Image.new("L", (width,height), "white")
img.putdata(data)
img.save('out.png')
</code></pre>
<p>After this, I'm getting this image <a href="https://i.stack.imgur.com/t8LqJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/t8LqJ.png" alt="greyscale"></a>, which is ok. So now, I want to make fft on my image before I'll save it to new one, so I'm doing like this</p>
<pre><code>scale = 1/(width*height)
greyscale = np.fft.fft2(greyscale)
greyscale = abs(greyscale * scale)
</code></pre>
<p>after loading it. After saving it to file, I have <a href="https://i.stack.imgur.com/ZmHSR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZmHSR.png" alt="bad FFT"></a>. So lets try now open test.png with gimp and use FFT filter plugin. I'm getting this image, which is correct <a href="https://i.stack.imgur.com/etJgL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/etJgL.png" alt="good FFT"></a></p>
<p>How I can handle it?</p>
| 0 | 1,275 |
Button position in android
|
<p>I'm trying to make some "Chat view" with speech bubbles like on the SMS iPhone app.
This is a row I have done in the xml editor :</p>
<p><a href="http://img44.imageshack.us/i/xml.png/" rel="nofollow noreferrer">http://img44.imageshack.us/i/xml.png/</a></p>
<p>But when I launch my application, I get this :</p>
<p><a href="http://img59.imageshack.us/i/resultt.png/" rel="nofollow noreferrer">http://img59.imageshack.us/i/resultt.png/</a></p>
<p>I don't know why the button to answer is so far away from my Relative layout border! This is the xml code of the speech bubble:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:background="@drawable/bulle_chat"
android:layout_width="fill_parent">
<ImageView android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_height="40sp"
android:layout_width="40sp"
android:id="@+id/ImageViewPhoto"
android:scaleType="fitXY"
android:layout_margin="8sp"
android:src="@drawable/lady">
</ImageView>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/ImageViewPhoto"
android:layout_alignTop="@+id/ImageViewPhoto"
android:id="@+id/TextViewPseudo"
android:text="Pseudo"
android:textColor="#242424"
android:textStyle="bold">
</TextView>
<TextView android:layout_below="@id/TextViewPseudo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/TextViewDate"
android:text="Date"
android:layout_toRightOf="@+id/ImageViewPhoto">
</TextView>
<Button android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:id="@+id/ButtonAnswer"
android:layout_height="40sp"
android:layout_width="40sp"
android:layout_margin="8sp">
</Button>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ImageViewPhoto"
android:layout_alignLeft="@+id/ImageViewPhoto"
android:textColor="#000000"
android:text="BlbalblablbalbalbalbalbalablabalbalablaballabalbBlbalblablbalbalbalbalbalablabalbalablaballabalbalbalaBlbalblablbalbalbalbalbalablabalbalablaballabalbalbalablablaalbalabla"
android:id="@+id/TextViewMessage"
android:layout_alignRight="@+id/ButtonAnswer"
android:paddingBottom="15sp">
</TextView>
</RelativeLayout>
</code></pre>
<p>And this is the adapter getView() method (pseudo = nickname):</p>
<pre><code>public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = ctx.getLayoutInflater();
View v = inflater.inflate(R.layout.chat_row, null);
TextView pseudo = (TextView)v.findViewById(R.id.TextViewPseudo);
TextView date = (TextView)v.findViewById(R.id.TextViewDate);
TextView message = (TextView)v.findViewById(R.id.TextViewMessage);
ImageView icon = (ImageView)v.findViewById(R.id.ImageViewPhoto);
Button b = (Button)v.findViewById(R.id.ButtonAnswer);
b.setId(position);
b.setOnClickListener((OnClickListener) ctx);
pseudo.setText(listMessages.get(position).getPseudo());
pseudo.setTextColor(0xFF000000);
date.setText(listMessages.get(position).getDate());
date.setTextColor(0xFF000000);
message.setText(listMessages.get(position).getText());
message.setTextColor(0xFF000000);
message.setGravity(Gravity.CLIP_HORIZONTAL);
if (listMessages.get(position).getThumb()!=null){
icon.setImageBitmap(listMessages.get(position).getThumb());
} else {
icon.setImageResource(R.drawable.unknown);
}
return v;
}
</code></pre>
<p>As you can see, I set the layout alignment parent right and top to true but it doesn't work. Another problem: if I want to change the background of my button, this one disappears!</p>
<p>Thanks for your help!!</p>
| 0 | 2,017 |
How to create a dynamic report thorough jrxml?
|
<p>I am working on <em>jrxml</em> to create dynamic reports. I have parameterized the columns i.e. the <em>jrxml</em> for that report can be used to generate other reports as well. </p>
<p>However, I have not managed to make the fields flexible. That is, if the user selects 4 columns it would work but if 1 or 2 or 3 columns are selected, it gives an error since the field names are unidentified. </p>
<p>Please post a solution urgently if something like a default expression for fieldname can be created or a for loop/java script can be used.</p>
<p>Moreover, how can jasper designer be exactly used to achieve this? </p>
<p>The jrxml is as follows:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0"?>
<!DOCTYPE jasperReport
PUBLIC "-//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="report1">
<parameter name="reportTitle" class="java.lang.String"/>
<parameter name="author" class="java.lang.String"/>
<parameter name="startDate" class="java.lang.String"/>
<parameter name="C1" class="java.lang.String">
<defaultValueExpression>
new java.lang.String("")
</defaultValueExpression>
</parameter>
<parameter name="C2" class="java.lang.String">
<defaultValueExpression>
new java.lang.String("")
</defaultValueExpression>
</parameter>
<parameter name="C3" class="java.lang.String">
<defaultValueExpression>
new java.lang.String("")
</defaultValueExpression>
</parameter>
<parameter name="C4" class="java.lang.String">
<defaultValueExpression>
new java.lang.String("default parameter value")
</defaultValueExpression>
</parameter>
<field name="COLUMN_1" class="java.lang.Integer"/>
<field name="COLUMN_2" class="java.lang.Integer"/>
<field name="COLUMN_3" class="java.lang.Integer"/>
<field name="COLUMN_4" class="java.lang.Integer"/>
<title>
<band height="60">
<textField>
<reportElement x="0" y="10" width="500" height="40"/>
<textElement textAlignment="Center">
<font size="24"/>
</textElement>
<textFieldExpression class="java.lang.String">
<![CDATA[$P{reportTitle}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x="0" y="40" width="500" height="20"/>
<textElement textAlignment="Center"/>
<textFieldExpression class="java.lang.String">
<![CDATA["Run by: " + $P{author}
+ " on " + $P{startDate}]]>
</textFieldExpression>
</textField>
</band>
</title>
<columnHeader>
<band height="30">
<rectangle>
<reportElement x="0" y="0" width="500" height="25"/>
<graphicElement/>
</rectangle>
<textField>
<reportElement x="0" y="5" width="170" height="15"/>
<textFieldExpression class="java.lang.String">
<![CDATA[$P{C1}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x="70" y="5" width="170" height="15"/>
<textFieldExpression class="java.lang.String">
<![CDATA[$P{C2}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x="150" y="5" width="150" height="15"/>
<textFieldExpression class="java.lang.String">
<![CDATA[$P{C3}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x="300" y="5" width="150" height="15"/>
<textFieldExpression class="java.lang.String">
<![CDATA[$P{C4}]]>
</textFieldExpression>
</textField>
</band>
</columnHeader>
<detail>
<band height="20">
<textField>
<reportElement x="5" y="0" width="50" height="15"/>
<textElement/>
<textFieldExpression class="java.lang.Integer">
<![CDATA[$F{COLUMN_1}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x="90" y="0" width="150" height="15"/>
<textElement/>
<textFieldExpression class="java.lang.Integer">
<![CDATA[$F{COLUMN_2}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x="170" y="0" width="50" height="15"/>
<textElement/>
<textFieldExpression class="java.lang.Integer">
<![CDATA[$F{COLUMN_3}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x="320" y="0" width="150" height="15"/>
<textElement/>
<textFieldExpression class="java.lang.Integer">
<![CDATA[$F{COLUMN_4}]]>
</textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>
</code></pre>
| 0 | 3,249 |
Spring + Hibernate : a different object with the same identifier value was already associated with the session
|
<p>In my application, which uses Spring and Hibernate, I parse a CSV file and populate the db by calling <code>handleRow()</code> every time a record is read from the CSV file.</p>
<p>My domain model:</p>
<blockquote>
<p>'Family' has many 'SubFamily'</p>
<p>'SubFamily' has many 'Locus' </p>
<p>a 'Locus' belongs to a 'Species'</p>
</blockquote>
<p><code>Family <-> SubFamily <-> Locus</code> are all bi-directional mappings. </p>
<p>Code:</p>
<pre><code>public void handleRow(Family dummyFamily, SubFamily dummySubFamily, Locus dummyLocus) {
//Service method which access DAO layers
CommonService serv = ctx.getCommonService();
boolean newFamily=false;
Family family=serv.getFamilyByFamilyId(dummyFamily.getFamilyId());
if(family==null){
newFamily=true;
family=new Family();
family.setFamilyId(dummyFamily.getFamilyId());
family.setFamilyIPRId(dummyFamily.getFamilyIPRId());
family.setFamilyName(dummyFamily.getFamilyName());
family.setFamilyPattern(dummyFamily.getFamilyPattern());
family.setRifID(dummyFamily.getRifID());
}
SubFamily subFamily = family.getSubFamilyBySubFamilyId( dummySubFamily.getSubFamilyId() );
if(subFamily==null){
subFamily=new SubFamily();
subFamily.setRifID(dummySubFamily.getRifID());
subFamily.setSubFamilyId(dummySubFamily.getSubFamilyId());
subFamily.setSubFamilyIPRId(dummySubFamily.getSubFamilyIPRId());
subFamily.setSubFamilyName(dummySubFamily.getSubFamilyName());
subFamily.setSubFamilyPattern(dummySubFamily.getSubFamilyPattern());
family.addSubFamily(subFamily);
}
//use the save reference, to update from GFF handler
Locus locus = dummyLocus;
subFamily.addLocus(locus);
assignSpecies(serv,locus);
//Persist object
if(newFamily){
serv.createFamily(family);
} else {
serv.updateFamily(family);
}
}
</code></pre>
<p>a Species is assigned to a Locus using following method, which simply accesses the DAO layer:</p>
<pre><code>private void assignSpecies (CommonService serv, Locus locus) {
String locusId = locus.getLocusId();
String speciesId = CommonUtils.getLocusSpecies(locusId, ctx.getSpeciesList()).getSpeciesId();
//Simply get Species object from DAO
Species sp = serv.getSpeciesBySpeciesId(speciesId);
locus.setSpecies(sp);
}
</code></pre>
<p>Hibernate gives following error:</p>
<pre><code>[INFO] Starting scheduled refresh cache with period [5000ms]
Hibernate: insert into species (species_id, name) values (?, ?)
Hibernate: insert into species (species_id, name) values (?, ?)
Hibernate: insert into species (species_id, name) values (?, ?)
############################ROW#####################1
SubFamiyID#######RIF0005913
Hibernate: select this_.id as id1_0_, this_.family_id as family2_1_0_, this_.rif_iD as rif3_1_0_, this_.family_name as family4_1_0_, this_.family_ipr_id as family5_1_0_, this_.family_pattern as family6_1_0_ from family this_ where this_.family_id=?
Creating NEW SubFamiyID#######RIF0005913
Hibernate: select this_.id as id3_0_, this_.species_id as species2_3_0_, this_.name as name3_0_ from species this_ where this_.species_id=?
Hibernate: insert into family (family_id, rif_iD, family_name, family_ipr_id, family_pattern) values (?, ?, ?, ?, ?)
Hibernate: insert into subfamily (sub_family_id, rif_iD, sub_family_name, sub_family_ipr_id, sub_family_pattern, family_id, sub_family_index) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into locus (locus_id, refTrans_id, function, species_id, sub_family_id, sub_family_index) values (?, ?, ?, ?, ?, ?)
Hibernate: update species set species_id=?, name=? where id=?
Hibernate: update subfamily set family_id=?, sub_family_index=? where id=?
Hibernate: update locus set sub_family_id=?, sub_family_index=? where id=?
############################ROW#####################2
SubFamiyID#######RIF0005913
Hibernate: select this_.id as id1_0_, this_.family_id as family2_1_0_, this_.rif_iD as rif3_1_0_, this_.family_name as family4_1_0_, this_.family_ipr_id as family5_1_0_, this_.family_pattern as family6_1_0_ from family this_ where this_.family_id=?
Hibernate: select subfamilie0_.family_id as family7_1_, subfamilie0_.id as id1_, subfamilie0_.sub_family_index as sub8_1_, subfamilie0_.id as id0_0_, subfamilie0_.sub_family_id as sub2_0_0_, subfamilie0_.rif_iD as rif3_0_0_, subfamilie0_.sub_family_name as sub4_0_0_, subfamilie0_.sub_family_ipr_id as sub5_0_0_, subfamilie0_.sub_family_pattern as sub6_0_0_, subfamilie0_.family_id as family7_0_0_ from subfamily subfamilie0_ where subfamilie0_.family_id=?
Hibernate: select locuslist0_.sub_family_id as sub5_1_, locuslist0_.id as id1_, locuslist0_.sub_family_index as sub7_1_, locuslist0_.id as id2_0_, locuslist0_.locus_id as locus2_2_0_, locuslist0_.refTrans_id as refTrans3_2_0_, locuslist0_.function as function2_0_, locuslist0_.sub_family_id as sub5_2_0_, locuslist0_.species_id as species6_2_0_ from locus locuslist0_ where locuslist0_.sub_family_id=?
Hibernate: select species0_.id as id3_0_, species0_.species_id as species2_3_0_, species0_.name as name3_0_ from species species0_ where species0_.id=?
Hibernate: select this_.id as id1_0_, this_.family_id as family2_1_0_, this_.rif_iD as rif3_1_0_, this_.family_name as family4_1_0_, this_.family_ipr_id as family5_1_0_, this_.family_pattern as family6_1_0_ from family this_ where this_.family_id=?
Hibernate: select this_.id as id3_0_, this_.species_id as species2_3_0_, this_.name as name3_0_ from species this_ where this_.species_id=?
Exception in thread "main" [INFO] Closing Compass [compass]
org.springframework.orm.hibernate3.HibernateSystemException: a different object with the same identifier value was already associated with the session: [com.bigg.nihonbare.common.domain.Species#1]; nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.bigg.nihonbare.common.domain.Species#1]
Caused by: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.bigg.nihonbare.common.domain.Species#1]
at org.hibernate.engine.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:590)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:284)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:223)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:89)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)
at org.hibernate.engine.CascadingAction$5.cascade(CascadingAction.java:218)
at org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:268)
</code></pre>
<p>Any tips?</p>
| 0 | 2,554 |
Error when installing an R package from github: Could not find build tools necessary to build data.table
|
<p>From within RStudio I'm trying to install the data.table package from github following <a href="https://stackoverflow.com/a/9656182/4945268">these instructions</a>, and the package seems to download without a problem:</p>
<pre><code>> library(devtools)
> dev_mode(on=T)
Dev mode: ON
d> install_github("Rdatatable/data.table")
Downloading GitHub repo Rdatatable/data.table@master
from URL https://api.github.com/repos/Rdatatable/data.table/zipball/master
</code></pre>
<p>I then receive the following prompt:</p>
<blockquote>
<p>Building R package from source requires installation of additional
build tools. Do you want to install the additional tools now?</p>
</blockquote>
<p>Selecting "Yes" results in this error message:</p>
<pre><code>Error: Could not find build tools necessary to build data.table
</code></pre>
<p>Thinking this might be an RStudio problem, I tried installing the package in the standard R console, but this also resulted in an error:</p>
<pre><code>Downloading GitHub repo Rdatatable/data.table@master
from URL https://api.github.com/repos/Rdatatable/data.table/zipball/master
Installing data.table
"C:/PROGRA~1/R/R-33~1.0/bin/x64/R" --no-site-file --no-environ --no-save \
--no-restore --quiet CMD INSTALL \
"C:/Users/Robert/AppData/Local/Temp/RtmpOOKOKu/devtools246832c52ab/Rdatatable-data.table-4348ff4" \
--library="C:/Users/Robert/Documents/R-dev" --install-tests
* installing *source* package 'data.table' ...
** libs
c:/Rtools/mingw_64/bin/gcc -I"C:/PROGRA~1/R/R-33~1.0/include" -DNDEBUG -I"d:/Compiler/gcc-4.9.3/local330/include" -fopenmp -O2 -Wall -std=gnu99 -mtune=core2 -c assign.c -o assign.o
c:/Rtools/mingw_64/bin/gcc: not found
make: *** [assign.o] Error 127
Warning: running command 'make -f "Makevars" -f "C:/PROGRA~1/R/R-33~1.0/etc/x64/Makeconf" -f "C:/PROGRA~1/R/R-33~1.0/share/make/winshlib.mk" SHLIB="data.table.dll" WIN=64 TCLBIN=64 OBJECTS="assign.o bmerge.o chmatch.o dogroups.o fastmean.o fcast.o fmelt.o forder.o frank.o fread.o fwrite.o gsumm.o ijoin.o init.o openmp-utils.o quickselect.o rbindlist.o reorder.o shift.o subset.o transpose.o uniqlist.o vecseq.o wrappers.o"' had status 2
ERROR: compilation failed for package 'data.table'
* removing 'C:/Users/Robert/Documents/R-dev/data.table'
Error: Command failed (1)
d>
</code></pre>
<p>I found three related posts on SO:</p>
<p><a href="https://stackoverflow.com/questions/35096233/error-could-not-find-build-tools-necessary-to-build-dplyr">Error: Could not find build tools necessary to build dplyr</a></p>
<p><a href="https://stackoverflow.com/questions/35914339/error-could-not-find-build-tools-necessary-to-build">Error : Could not find build tools necessary to build</a></p>
<p><a href="https://stackoverflow.com/questions/36002510/could-not-find-build-tools-necessary-facing-error-with-devtools">Could not find build tools necessary . Facing error with devtools</a></p>
<p>The first two seem specific to Apple OS, and the third suggests an error specific to devtools, but I don't know if that's the source of the error I'm seeing.</p>
<p>Any help would be appreciated. I'm running R version 3.3.0 in Windows 10.</p>
| 0 | 1,166 |
How to use react-bootstrap in typescript project
|
<p>I am trying to make a nav bar using react-bootstrap I have installed the node-module which is <code>"@types/react-bootstrap": "^0.32.11",</code> and I want to use in my hello.tsx component but it shows compile error Module not found: Error: Can't resolve 'react-bootstrap' in:\Query Express\Portal\src\components' I don't understand why it is looking for react-bootstrap in component directory</p>
<pre><code>import * as React from "react";
import { Navbar, Nav, NavItem, NavDropdown, MenuItem } from "react-bootstrap";
export interface IHelloProps { compiler: string; framework: string; }
// 'helloProps' describes the shape of props.
// state is never set so we use the '{}' type.
export class Hello extends React.Component<IHelloProps, {}> {
render() {
return(
<div>
<Navbar inverse>
<Navbar.Header>
<Navbar.Brand>
<a href="#brand">React-Bootstrap</a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<NavItem eventKey={1} href="#">
Link
</NavItem>
<NavItem eventKey={2} href="#">
Link
</NavItem>
<NavDropdown eventKey={3} title="Dropdown" id="basic-nav-dropdown">
<MenuItem eventKey={3.1}>Action</MenuItem>
<MenuItem eventKey={3.2}>Another action</MenuItem>
<MenuItem eventKey={3.3}>Something else here</MenuItem>
<MenuItem divider />
<MenuItem eventKey={3.3}>Separated link</MenuItem>
</NavDropdown>
</Nav>
<Nav pullRight>
<NavItem eventKey={1} href="#">
Link Right
</NavItem>
<NavItem eventKey={2} href="#">
Link Right
</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
<h1>Hello from {this.props.compiler} and {this.props.framework}!</h1>;
</div>
)}
}
</code></pre>
<p>Index.html</p>
<pre><code> <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
<!-- Main -->
<link href="./src/css/lib/_bootstrap.min.css" rel="stylesheet"></link>
<script src="./dist/main.bundle.js"></script>
<script src="./dist/nodeModules.bundle.js"></script>
</body>
</html>
</code></pre>
| 0 | 1,387 |
How to Get JSON Array Within JSON Object?
|
<p>This is my JSON: </p>
<pre><code>{
"data": [
{
"id": 1,
"Name": "Choc Cake",
"Image": "1.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
},
{
"name": "1 Bag Beans"
}
]
},
{
"id": 2,
"Name": "Ice Cake",
"Image": "dfdsfdsfsdfdfdsf.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
}
]
}
]
}
</code></pre>
<p>And this is how I am getting the id and name, you can see this part works fine in returning JSON values that are not array values.</p>
<pre><code>//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
//loop to get all json objects from data json array
for(int i=0; i<length; i++)
{
JSONObject jObj = ja_data.getJSONObject(i);
Toast.makeText(this, jObj.getString("Name"), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jObj.getJSONArray("Ingredients");
int len = ja.length();
}
</code></pre>
<p>Now i'm trying to get the values from the ingredients array and I am not sure how to get them? This is what I have been trying thus far.</p>
<pre><code>//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
//loop to get all json objects from data json array
for(int i=0; i<length; i++)
{
JSONObject jObj = ja_data.getJSONObject(i);
Toast.makeText(this, jObj.getString("Name"), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jObj.getJSONArray("Ingredients");
int len = ja.length();
// getting json objects from Ingredients json array
for(int j=0; j<len; j++)
{
JSONObject json = ja.getJSONObject(j);
Toast.makeText(this, json.getString("name"), Toast.LENGTH_LONG).show();
}
}
</code></pre>
<p>But doing it this way is not working, how can I get it to work?</p>
| 0 | 1,092 |
Will larger batch size make computation time less in machine learning?
|
<p>I am trying to tune the hyper parameter i.e <strong>batch size</strong> in CNN.I have a computer of corei7,RAM 12GB and i am training a CNN network with CIFAR-10 dataset which can be found in this <a href="http://torch.ch/blog/2015/07/30/cifar.html" rel="nofollow noreferrer">blog</a>.<br><br><em>Now At first what i have read and learnt about batch size in machine learning:</em></p>
<blockquote>
<p>let's first suppose that we're doing online learning, i.e. that we're
using a minibatch size of 1. The obvious worry about online learning
is that using minibatches which contain just a single training
example will cause significant errors in our estimate of the gradient.
In fact, though, the errors turn out to not be such a problem. The
reason is that the individual gradient estimates don't need to be
superaccurate. All we need is an estimate accurate enough that our
cost function tends to keep decreasing. It's as though you are trying
to get to the North Magnetic Pole, but have a wonky compass that's
10-20 degrees off each time you look at it. Provided you stop to
check the compass frequently, and the compass gets the direction right
on average, you'll end up at the North Magnetic Pole just
fine.<br><br></p>
<p>Based on this argument, it sounds as though we should use online
learning. In fact, the situation turns out to be more complicated than
that.As we know we can use matrix techniques to compute the gradient
update for all examples in a minibatch simultaneously, rather than
looping over them. Depending on the details of our hardware and linear
algebra library this can make it quite a bit faster to compute the
gradient estimate for a minibatch of (for example) size 100 , rather
than computing the minibatch gradient estimate by looping over the
100 training examples separately. It might take (say) only 50 times as
long, rather than 100 times as long.Now, at first it seems as though
this doesn't help us that much.<br><br></p>
<p>With our minibatch of size 100 the learning rule for the weights
looks like:<a href="https://i.stack.imgur.com/QDhgB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QDhgB.png" alt="enter image description here"></a><br></p>
<p>where the sum is over training examples in the minibatch. This is
versus<a href="https://i.stack.imgur.com/X4CkK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X4CkK.png" alt="enter image description here"></a><br> for online learning.
Even if it only takes 50 times as long to do the minibatch update, it
still seems likely to be better to do online learning, because we'd be
updating so much more frequently. Suppose, however, that in the
minibatch case we increase the learning rate by a factor 100, so the
update rule becomes<br><a href="https://i.stack.imgur.com/KMnF1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KMnF1.png" alt="enter image description here"></a><br>
That's a lot like doing separate instances of online learning with a
learning rate of <code>η</code>. But it only takes 50 times as long as doing a
single instance of online learning. Still, it seems distinctly
possible that using the larger minibatch would speed things up.</p>
</blockquote>
<p><br><br></p>
<p>Now i tried with <code>MNIST digit dataset</code> and ran a sample program and set the batch size <code>1</code> at first.I noted down the training time needed for the full dataset.Then i increased the batch size and i noticed that it became faster.
<br>
But in case of training with this <a href="https://github.com/szagoruyko/cifar.torch/blob/master/models/vgg_bn_drop.lua" rel="nofollow noreferrer">code</a> and <a href="https://github.com/szagoruyko/cifar.torch" rel="nofollow noreferrer">github link</a> changing the batch size doesn't decrease the training time.It remained same if i use 30 or 128 or 64.They are saying that they got <code>92%</code> accuracy.After two or three epoch they have got above <code>40%</code> accuracy.But when i ran the code in my computer without changing anything other than the batch size i got worse result after 10 epoch like only 28% and test accuracy stuck there in the next epochs.Then i thought since they have used batch size of 128 i need to use that.Then i used the same but it became more worse only give 11% after 10 epoch and stuck in there.<strong>Why is that??</strong></p>
| 0 | 1,267 |
Jersey Tutorials from Basics
|
<p>I am using Jersey 1.8 and the tutorials that I am referring are quiet old. Nothing works. I am referring to the tutorial given <a href="http://www.vogella.de/articles/REST/article.html" rel="nofollow">here</a> </p>
<p>And get a class not found exception. as per the tutorial I made my Java Class as well as configured my web.xml. It shows me an exception and I am not getting a way to fix this. I would like to have a complete up to date tutorial for Jersey implementation. And if something is better than Jersey for REST implementation please suggest. I have rescently started with REST based web services and would appreciate if you can suggest me where to start from(I am only interested in REST). Below is the code that I wrote and compiled using eclipse.</p>
<p>Hello.java</p>
<pre><code>import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/hello")
public class Hello {
//This method prints the Plain Text
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello()
{
return "Hello Jersey";
}
//This is the XML request output
@GET
@Produces(MediaType.TEXT_XML)
public String sayXMLHello()
{
return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}
//This result is produced if HTML is requested
@GET
@Produces(MediaType.TEXT_HTML)
public String sayHTMLHello()
{
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}
}
</code></pre>
<p>web.xml is as follows</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<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">
<display-name>RESTFullApp</display-name>
<servlet>
<servlet-name>JerseyRESTService</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer;</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>RESTFullApp</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JerseyRESTService</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<!-- <welcome-file-list>-->
<!-- <welcome-file>index.html</welcome-file>-->
<!-- <welcome-file>index.htm</welcome-file>-->
<!-- <welcome-file>index.jsp</welcome-file>-->
<!-- <welcome-file>default.html</welcome-file>-->
<!-- <welcome-file>default.htm</welcome-file>-->
<!-- <welcome-file>default.jsp</welcome-file>-->
<!-- </welcome-file-list>-->
</web-app>
</code></pre>
<p>Noe the error I get while I try to run is </p>
<pre><code>exception
javax.servlet.ServletException: Servlet.init() for servlet JerseyRESTService threw exception
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
java.lang.Thread.run(Unknown Source)
root cause
com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
com.sun.jersey.server.impl.application.RootResourceUriRules.<init>(RootResourceUriRules.java:99)
com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1298)
com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:169)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:775)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:771)
com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:771)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:766)
com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:488)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:318)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:609)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:373)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:556)
javax.servlet.GenericServlet.init(GenericServlet.java:212)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
java.lang.Thread.run(Unknown Source)
</code></pre>
| 0 | 2,339 |
ASP.NET Charting Control - Dynamically Adding and Removing Series of Datapoints
|
<p>If you're familiar with ASP.NET's Charting controls, the Chart object contains a number of Series objects - which are series of datapoints that can be charted. Each series can be visualized in a different way (bar or point or line) on the same chart.</p>
<p>I have a custom control that I use to create and remove and modify lists of Series in a UI. Upon clicking a button, the chart is created using those Series. If I try to re-display the chart, however (even with identical Series) it blows up and throws a NullReferenceException. </p>
<p>Here's the relevant code - I've got an object wrapping Series (because I have some custom properties in there)</p>
<pre><code>public class DataSeries
{
private Series _series = new Series();
... (bunch of other properties)
public Series Series
{
get { return _series; }
set { _series = value; }
}
}
</code></pre>
<p>In the control itself, I store a list of these as a property(I only create the object during non-postbacks because I want the list to persist):</p>
<pre><code>private static List<DataSeries> seriesList;
public List<DataSeries> ListOfSeries
{
get { return seriesList; }
set { seriesList = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
seriesList = new List<DataSeries>();
}
}
</code></pre>
<p>Then I have some amalgam of controls that I can use to add new DataSeries, remove them, and modify their properties. That all works.</p>
<p>When they click 'Create Chart' on the page, this is the code that gets executed:</p>
<pre><code>protected void refreshChart(object sender, EventArgs e)
{
chart.Series.Clear();
foreach (DataSeries s in seriesControl.ListOfSeries)
{
string propertyName = s.YAxisProperty;
//List of data to display for this series
List<Sampled_Data> sampleList = Sample.GetSamplesById(s.ComponentId);
foreach (Sampled_Data dSample in sampleList)
{
//GetPropertyValue returns a float associated with the propertyname
//selected for displaying as the Y Value
s.Series.Points.AddY(BindingLib.GetPropertyValue(dSample, propertyName));
}
chart.Series.Add(s.Series);
}
}
</code></pre>
<p>The first time I execute that piece of code, it works like a charm.
The second time I click on the button that executes 'refreshChart,' I get a NullReferenceException because the value of 's.Series.Points' is null. And I can't create a new object of the type that the Points property is - its constructor is private or protected.</p>
<p>If I'm not manipulating the Points property between subsequent calls of this function, why is it becoming null? </p>
<p>There are maybe a few solutions I could think of - make DataSeries inherit series instead of have one - then likely I could new the Points property if the error still persists. I could also deep copy the ListOfSeries and see if that solves my problem. I could also perhaps shove all my custom attributes into the Series object - it has a customfields property (or something similarly named). If I'm not passing around an object wrapping another one, that might eliminate the issue.</p>
<p>Any ideas why this might be occurring and how it might be solved?</p>
| 0 | 1,114 |
Do I have to bind a UDP socket in my client program to receive data? (I always get WSAEINVAL)
|
<p>I am creating a UDP socket (<code>AF_INET</code>, <code>SOCK_DGRAM</code>, <code>IPPROTO_UDP</code>) via Winsock and trying to <code>recvfrom</code> on this socket, but it always returns -1 and I get WSAEINVAL (10022). Why?</p>
<p>When I <code>bind()</code> the port, that does not happen, but I have read that it is very lame to bind the client's socket.</p>
<p>I am sending data to my server, which answers, or at least, tries to.</p>
<pre><code>Inc::STATS CConnection::_RecvData(sockaddr* addr, std::string &strData)
{
int ret; // return code
int len; // length of the data
int fromlen; // sizeof(sockaddr)
char *buffer; // will hold the data
char c;
//recv length of the message
fromlen = sizeof(sockaddr);
ret = recvfrom(m_InSock, &c, 1, 0, addr, &fromlen);
if(ret != 1)
{
#ifdef __MYDEBUG__
std::stringstream ss;
ss << WSAGetLastError();
MessageBox(NULL, ss.str().c_str(), "", MB_ICONERROR | MB_OK);
#endif
return Inc::ERECV;
}
...
</code></pre>
<p>This is a working example I wrote a few moments ago, and it works without the call to <code>bind()</code> in the client:</p>
<pre><code>#pragma comment(lib, "Ws2_32.lib")
#define WIN32_LEAN_AND_MEAN
#include <WS2tcpip.h>
#include <Windows.h>
#include <iostream>
using namespace std;
int main()
{
SOCKET sock;
addrinfo* pAddr;
addrinfo hints;
sockaddr sAddr;
int fromlen;
const char czPort[] = "12345";
const char czAddy[] = "some ip";
WSADATA wsa;
unsigned short usWSAVersion = MAKEWORD(2,2);
char Buffer[22] = "TESTTESTTESTTESTTEST5";
int ret;
//Start WSA
WSAStartup(usWSAVersion, &wsa);
//Create Socket
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
//Resolve host address
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_protocol = IPPROTO_UDP;
hints.ai_socktype = SOCK_DGRAM;
if(getaddrinfo(czAddy, czPort, &hints, &pAddr))
{
std::cerr << "Could not resolve address...\n";
std::cin.get();
return 1;
}
//Start Transmission
while(1)
{
ret = sendto(sock, Buffer, sizeof(Buffer), 0, pAddr->ai_addr,
pAddr->ai_addrlen);
if(ret != sizeof(Buffer))
{
std::cerr << "Could not send data\n";
std::cin.get();
return 1;
}
fromlen = sizeof(SOCKADDR);
ret = recvfrom(sock, Buffer, sizeof(Buffer), 0, &sAddr, &fromlen);
if(ret != sizeof(Buffer))
{
std::cout << "Could not receive data - error: " <<
WSAGetLastError() << std::endl;
std::cin.get();
return 1;
}
Buffer[ret-1] = '\0';
std::cout << "Received: " << Buffer << std::endl;
}
return 0;
}
</code></pre>
| 0 | 1,456 |
ICommand in MVVM WPF
|
<p>I'm having a look at this MVVM stuff and I'm facing a problem.</p>
<p>The situation is pretty simple.</p>
<p>I have the following code in my index.xaml page</p>
<pre><code> <Grid>
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<view:MovieView ></view:MovieView>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</code></pre>
<p>and in my index.xaml.cs</p>
<p>...</p>
<p>InitializeComponent();
base.DataContext = new MovieViewModel(ent.Movies.ToList());
....</p>
<p>and here is my MoveViewModel </p>
<pre><code> public class MovieViewModel
{
readonly List<Movies> _m;
public ICommand TestCommand { get; set; }
public MovieViewModel(List<Movies> m)
{
this.TestCommand = new TestCommand(this);
_m = m;
}
public List<Movies> lm
{
get
{
return _m;
}
}
}
</code></pre>
<p>finally</p>
<p>here is my control xaml MovieView</p>
<pre><code> <Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label VerticalAlignment="Center" Grid.Row="0" Grid.Column="0">Title :</Label><TextBlock VerticalAlignment="Center" Grid.Row="0" Grid.Column="1" Text="{Binding Title}"></TextBlock>
<Label VerticalAlignment="Center" Grid.Row="1" Grid.Column="0">Director :</Label><TextBlock VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" Text="{Binding Director}"></TextBlock>
<Button Grid.Row="2" Height="20" Command="{Binding Path=TestCommand}" Content="Edit" Margin="0,4,5,4" VerticalAlignment="Stretch" FontSize="10"/>
</Grid>
</code></pre>
<p>So the problem I have is that if I set ItemsSource at Binding</p>
<p></p>
<p>it doesn't make anything</p>
<p>if I set ItemsSource="{Binding lm}"</p>
<p>it populates my itemsControl but the Command (Command="{Binding Path=TestCommand}" ) doesn't not work.</p>
<p>Of course it doesn't not work because TestCommand doesn't not belong to my entity object Movies.</p>
<p>So finally my question is,</p>
<p>what do I need to pass to the ItemsControl to make it working?</p>
<p>Thx in advance</p>
| 0 | 1,142 |
Inline-block display of divs with position relative
|
<p>I have a series of images each with his own overlay. How can I have them aligned like inline-blocks? I tried adding adding <code>display: inline-block;</code>to <code>.image-wrapper</code> but the images are always all positioned in the top left corner of the <code>div.container</code> (Here is a <a href="http://jsfiddle.net/klode/uhowp621/#base" rel="nofollow">jsfiddle</a>).</p>
<p>Here are the html and css</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>.container {
position: relative;
}
.image-wrapper {
position: relative;
display: inline-block;
}
.tweetty {
position: absolute;
overflow: auto;
top: 0;
left: 0;
}
.image-vest {
position: absolute;
top: 0;
left: 0;
background-color: #00f;
width: 220px;
height: 300px;
opacity: 0.4;
color: #fff;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="image-wrapper">
<div class="tweetty">
<img src="http://www.picgifs.com/clip-art/cartoons/tweety/clip-art-tweety-191375.jpg" />
</div>
<div class="image-vest">Tweetty-one</div>
</div>
<div class="image-wrapper">
<div class="tweetty">
<img src="http://www.picgifs.com/clip-art/cartoons/tweety/clip-art-tweety-191375.jpg" />
</div>
<div class="image-vest">Tweetty-two</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>EDIT:</p>
<p>revised css with dfsq suggestion to remove <code>position:absolute;</code> from <code>.tweetty</code>.</p>
<p>Quoting dfsq comment:
"Elements with position absolute don't contribute to the width and height of their parent container. So the image-wrapper divs just collapse as if they were empty if all children have <code>position:absolute;</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>.container {
position: relative;
}
.image-wrapper {
position: relative;
display: inline-block;
}
.tweetty {
overflow: auto;
top: 0;
left: 0;
}
.image-vest {
position: absolute;
top: 0;
left: 0;
background-color: #00f;
width: 220px;
height: 300px;
opacity: 0.4;
color: #fff;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="image-wrapper">
<div class="tweetty">
<img src="http://www.picgifs.com/clip-art/cartoons/tweety/clip-art-tweety-191375.jpg" />
</div>
<div class="image-vest">Tweetty-one</div>
</div>
<div class="image-wrapper">
<div class="tweetty">
<img src="http://www.picgifs.com/clip-art/cartoons/tweety/clip-art-tweety-191375.jpg" />
</div>
<div class="image-vest">Tweetty-two</div>
</div>
<div class="image-wrapper">
<div class="tweetty">
<img src="http://www.picgifs.com/clip-art/cartoons/tweety/clip-art-tweety-191375.jpg" />
</div>
<div class="image-vest">Tweetty-three</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| 0 | 1,426 |
Can't login to my custom login page in spring boot security
|
<p>My problem is: when I try to login on my custom login page it redirects me to login page again (it doesn't matter if I put right or wrong credentials). It's also weird that I don't reach my custom UserDetailService in debug, I think it means that spring doesn't even check user's credentials.</p>
<p>I have custom login form <code>/WEB-INF/jsp/login.jsp</code>:</p>
<pre><code>...
<form name='loginForm' action="<c:url value='j_spring_security_check' />" method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='j_username' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='j_password' /></td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"
value="submit" /></td>
</tr>
</table>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
...
</code></pre>
<p>This is configuration:</p>
<pre><code>@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().antMatchers("/", "/welcome", "/resources/**").permitAll()
.anyRequest().authenticated().and()
.formLogin().loginPage("/login").failureUrl("/login?error").permitAll().and()
.logout().logoutUrl("/login?logout").permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
</code></pre>
<p>And this is inside controller:</p>
<pre><code>@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout) {
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login");
return model;
}
</code></pre>
<p>In <code>src/main/resources/application.properties</code> I have:</p>
<pre><code>spring.view.prefix: /WEB-INF/jsp/
spring.view.suffix: .jsp
</code></pre>
| 0 | 1,278 |
Props in functional component are missing in props validation
|
<p>Eslint throwing eslint(react/prop-types) error despite already declared propTypes. I'm using <a href="https://github.com/Intellicode/eslint-plugin-react" rel="nofollow noreferrer">eslint-plugin-react</a></p>
<p>I've looked at a couple of other similar problems and as well as the <a href="https://github.com/Intellicode/eslint-plugin-react/blob/master/docs/rules/prop-types.md" rel="nofollow noreferrer">lint rule for the proptype</a> but they don't address my issue.</p>
<pre><code>import React from 'react';
import { View, Text, TouchableHighlight, StyleSheet } from 'react-native';
import PropTypes from 'prop-types';
const PASTEL_PINK = '#dea5a4';
const PASTEL_BLUE = '#779ecb';
const Buttons = ({ onPressStart, onPressPause, onPressReset, onGoing }) => (
<View >
<TouchableHighlight
onPress={onPressStart}
disabled={onGoing}
>
<Text >{START_TIMER}</Text>
</TouchableHighlight>
<TouchableHighlight
onPress={onPressPause}
disabled={!onGoing}
>
<Text >{PAUSE_TIMER}</Text>
</TouchableHighlight>
<TouchableHighlight onPress={onPressReset}>
<Text >{RESET_TIMER}</Text>
</TouchableHighlight>
</View>
);
Buttons.protoTypes = {
onPressStart: PropTypes.func.isRequired,
onPressPause: PropTypes.func.isRequired,
onPressReset: PropTypes.func.isRequired,
onGoing: PropTypes.bool.isRequired,
};
export default Buttons;
</code></pre>
<p>Parent component supplying the props</p>
<pre><code>import React from 'react';
import Buttons from './components/Buttons'
import Container from './components/Container';
import Timer from './components/Timer';
import Inputs from './components/Inputs';
import Logo from './components/Logo';
import Buttons from './components/Buttons'
import Header from './components/Header'
export default class Home extends React.Component {
constructor(props){
super(props)
this.state = {
initialMinute: '00',
initialSecond: '00',
minute: '00',
second: '00',
completed: false,
onGoing: false,
}
componentWillMount() {
this.setState({
minute: this.state.initialMinute,
second: this.state.initialSecond,
}
);
}
componentWillUnmount() {
clearInterval(this.interval);
}
startTimer = () => {
console.log("Timer Started")
this.setState(
(prevState) => (
{
completed: false,
onGoing: true,
}
)
)
// start the timer
this.interval = setInterval(
this.decrementTime,
1000
)
}
decrementTime = () => {
if (this.state.second > 0) {
console.log(`second: ${this.state.second}`)
this.setState(
(prevState) => (
{second: prevState.second - 1}
)
)
if (this.props.second < 10) {
this.setState({
second: '0'+this.state.second
});
}
}
else {
if (this.state.minute > 0) {
this.setState(
(prevState) => (
{
minute: prevState.minute - 1,
second: prevState.second + 59,
}
)
)
if (this.props.minute < 10) {
this.setState({
state: '0'+this.state.minute
});
}
}
else {
this.resetTimer();
this.timesUp(true);
}
}
}
pauseTimer = () => {
console.log("Timer stopped")
clearInterval(this.interval);
this.setState({
onGoing: false,
}
)
}
resetTimer = () => {
console.log("Timer is reset")
this.pauseTimer();
this.setState({
minute: this.state.initialMinute,
second: this.state.initialSecond,
}
);
}
timesUp = (bool) => {
this.setState(
(prevState) => (
{
completed: bool,
}
)
)
}
optionPressed = () => {
console.log("Header is pressed")
}
handleMinuteInput = (text) => {
// clamp minute between 0 and 60
// const number = helper.clamp(parseInt(text), 0, 60)
this.setState(
{
initialMinute: text,
}
)
}
handleSecondInput = (text) => {
// const number = helper.clamp(parseInt(text+''), 0, 60)
this.setState(
{
initialSecond: text,
}
)
}
render() {
return (
<Container>
<Header onPress={this.optionPressed}/>
<Logo
slogan={'Get studying, the Pomodoro way!'}
imageSource={'../../assets/pomo-timer-logo-small.png'}
/>
<Timer
minute={this.state.minute}
second={this.state.second}
completed={this.state.completed}
onGoing={this.state.onGoing}
/>
<Buttons
onPressStart={this.startTimer}
onPressPause={this.pauseTimer}
onPressReset={this.resetTimer}
onGoing={this.state.onGoing} // true when not onGoing
/>
<Inputs
inputType={'Work'}
labelColor={PASTEL_BLUE}
handleMinuteInput={this.handleMinuteInput}
handleSecondInput={this.handleSecondInput}
onGoing={this.state.onGoing}
/>
<Inputs
inputType={'Rest'}
labelColor={PASTEL_PINK}
// setTimer={this.setTimer}
handleMinuteInput={this.handleMinuteInput}
handleSecondInput={this.handleSecondInput}
onGoing={this.state.onGoing}
/>
</Container>
)
}
}
</code></pre>
<p>I don't expect these error to show up but it does.</p>
<p>'onPressStart' is missing in props validation
'onPressPause' is missing in props validation
'onPressReset' is missing in props validation
'onGoing' is missing in props validation</p>
| 0 | 2,784 |
Apache docker container - Invalid command 'RewriteEngine'
|
<p>I use docker compose. However, when I run "docker-compose up", I came across an error : /var/www/html/.htaccess: Invalid command 'RewriteEngine'.</p>
<p>Can you tell me where I fails ??</p>
<p>Project architecture :</p>
<pre><code>project-name /
/ docker-compose.yml
/ Dockerfile
/ apache.conf
/ php.ini
/ src /
/ index.php
/ .htaccess
</code></pre>
<p>docker-compose.yml :</p>
<pre><code>web:
build: .
ports:
- "80:80"
volumes:
- ./src:/var/www/html
- php.ini:/usr/local/etc/php/conf.d/30-custom.ini
- apache.conf:/etc/apache2/sites-enabled
environment:
- ALLOW_OVERRIDE=true
</code></pre>
<p>Dockerfile :</p>
<pre><code>FROM php:7.0-apache
RUN a2enmod rewrite
RUN service apache2 restart
ADD ./src /var/www/html
</code></pre>
<p>php.ini :</p>
<pre><code>display_errors=1
error_reporting=E_ALL
</code></pre>
<p>apache.conf (with my ip address) :</p>
<pre><code><VirtualHost *:80>
ServerName xxx.xxx.xx.xxx
DocumentRoot /var/www/html
</VirtualHost>
</code></pre>
<p>I type in the command line : </p>
<pre><code>docker@default:/blabla/project-name$ docker-compose up
</code></pre>
<p>it returns me :</p>
<pre><code>AH00558: apache2: Could not reliably determine the server's fully
qualified domain name, using xxx.xx.x.x. Set the 'ServerName' directive
globally to suppress this message
</code></pre>
<p>and</p>
<pre><code>/var/www/html/.htaccess: Invalid command 'RewriteEngine',
perhaps misspelled or defined by a module not included in the server
configuration
</code></pre>
<p>and in the browser, in my ip address (<a href="http://xxx.xxx.xx.xxx/" rel="noreferrer">http://xxx.xxx.xx.xxx/</a>) :</p>
<pre><code>500 Internal servor error
</code></pre>
<p>my .htaccess :</p>
<pre><code><files .htaccess>
Require all denied
</files>
Options +FollowSymlinks -Indexes -Multiviews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?p=$1 [L,QSA]
</code></pre>
<p>I'm on windows and i use Oracle VM Virtual Box.</p>
<p>Thank you in advance !</p>
<p>EDIT : I should say that if I delete rewrite rules, everything works.</p>
| 0 | 1,033 |
how to make a textview invisible
|
<p>this is my first android app so plese bear with me, and also, if you suggest a answer, alternative method of completeing a task, please specify how and also in detail...</p>
<p>Here is my problem, after doing some research, and trying it out, my app FC when I have the following line (specified by *)</p>
<pre><code>private TextView msg;
msg = (TextView) findViewById(R.id.txtviewOut) ;
* msg.setVisibility(View.INVISIBLE);
</code></pre>
<p>I have no idea why</p>
<p>here is the rest of all my code:</p>
<p>main.xml</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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=".MainActivity$PlaceholderFragment">
<EditText
android:id="@+id/textenter"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_below="@+id/lbledt1"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Name"
android:id="@+id/lbledt1"
android:layout_marginTop="26dp"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter your date of birth (e.g. xx July 19xx)"
android:id="@+id/textView"
android:layout_below="@+id/textenter"
android:layout_centerHorizontal="true"
android:layout_marginTop="57dp" />
<EditText
android:id="@+id/editText"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press this button"
android:id="@+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="You have been awesome since"
android:id="@+id/txtviewOut"
android:layout_marginTop="86dp"
android:textIsSelectable="false"
android:visibility="invisible"
android:layout_below="@+id/button"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/txtoutName"
android:textIsSelectable="false"
android:layout_alignBottom="@+id/txtviewOut"
android:layout_centerHorizontal="true"
android:layout_marginBottom="41dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/txtOutDate"
android:layout_marginTop="28dp"
android:textIsSelectable="false"
android:layout_below="@+id/txtviewOut"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</code></pre>
<p>and here is from MainActivity.java</p>
<pre><code>package com.example.helloandroidstudio;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private Button btnClick;
private EditText Name, Date;
private TextView msg, NameOut, DateOut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnClick = (Button) findViewById(R.id.button) ;
btnClick.setOnClickListener(this);
Name = (EditText) findViewById(R.id.textenter) ;
Date = (EditText) findViewById(R.id.editText) ;
msg = (TextView) findViewById(R.id.txtviewOut) ;
msg.setVisibility(View.INVISIBLE);
NameOut = (TextView) findViewById(R.id.txtoutName) ;
DateOut = (TextView) findViewById(R.id.txtOutDate) ;
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void onClick(View v)
{
if (v == btnClick)
{
if (Name.equals("") == false && Date.equals("") == false)
{
NameOut = Name;
DateOut = Date;
msg.setVisibility(View.VISIBLE);
}
else
{
msg.setText("Please complete both fields");
msg.setVisibility(View.VISIBLE);
}
}
return;
}
@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 boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
</code></pre>
<p>Any assistance would be appreciated</p>
| 0 | 2,873 |
Response already commited - java.lang.IllegalStateException: UT010019
|
<p>I am working on a web application with jsp and servlets. </p>
<p>My Servlet name is <code>ServletBulkCrdProm</code> and I redirect to jsp page in the method <code>doBulkCrdSelect()</code> which is called by Servlet's <code>doPost()</code> method.</p>
<p>In my servlet, I forward the request to a jsp page like this.</p>
<pre><code>dispatcher = getServletContext().getRequestDispatcher("/bulkPromotion/BulkPromCrdList.jsp");
dispatcher.forward(req, res);
return;
</code></pre>
<p>This works without any issue. I submit the jsp form like this.</p>
<pre><code> <form id="dataform" name="dataform" method="<%=WebConstants.HTML_FORM_SUMIT_METHOD%>" action="<%=ServletMapConst.SERVLET_NAME%>">
</code></pre>
<p>Problem is when I submit the jsp page again ( which contains a form and handled by the same servlet but a different method named <code>doBulkCrdUpload()</code> which again called by <code>doPost()</code> method of servlet) I get this error. </p>
<pre><code>java.lang.IllegalStateException: UT010019: Response already commited
at io.undertow.servlet.spec.ServletOutputStreamImpl.resetBuffer(ServletOutputStreamImpl.java:712)
at io.undertow.servlet.spec.HttpServletResponseImpl.resetBuffer(HttpServletResponseImpl.java:494)
at javax.servlet.ServletResponseWrapper.resetBuffer(ServletResponseWrapper.java:241)
at io.undertow.servlet.spec.RequestDispatcherImpl.forwardImpl(RequestDispatcherImpl.java:167)
at io.undertow.servlet.spec.RequestDispatcherImpl.forwardImplSetup(RequestDispatcherImpl.java:147)
at io.undertow.servlet.spec.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:111)
at bulkCrdProm.ServletBulkCrdProm.doBulkCrdSelect(ServletBulkCrdProm.java:401)
at bulkCrdProm.ServletBulkCrdProm.doPost(ServletBulkCrdProm.java:101)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at org.owasp.csrfguard.CsrfGuardFilter.doFilter(CsrfGuardFilter.java:90)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at sessionhandler.SessionFilter.doFilter(SessionFilter.java:610)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
</code></pre>
<p>What I am doing wrong here? Can someone please help me to solve the issue.A help is much appreciated.</p>
| 0 | 1,200 |
Fatal error: Call to undefined function finfo_open() in php
|
<p>I am new to php, i have created code for upload images to sql database and retrieve the image using php.</p>
<p>Here is my code:</p>
<pre><code><html>
<head><title>File Insert</title></head>
<body>
<h3>Please Choose a File and click Submit</h3>
<form enctype="multipart/form-data" action=
"<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<input name="userfile" type="file" />
<input type="submit" value="Submit" />
</form>
<?php
// check if a file was submitted
if(!isset($_FILES['userfile']))
{
echo '<p>Please select a file</p>';
}
else
{
try {
$msg= upload(); //this will upload your image
echo $msg; //Message showing success or failure.
}
catch(Exception $e) {
echo $e->getMessage();
echo 'Sorry, could not upload file';
}
}
// the upload function
function upload() {
include "mysqlconnect.php";
$maxsize = 10000000; //set to approx 10 MB
//check associated error code
if($_FILES['userfile']['error']==UPLOAD_ERR_OK) {
//check whether file is uploaded with HTTP POST
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
//checks size of uploaded image on server side
if( $_FILES['userfile']['size'] < $maxsize) {
//checks whether uploaded file is of image type
//if(strpos(mime_content_type($_FILES['userfile']['tmp_name']),"image")===0) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if(strpos(finfo_file($finfo, $_FILES['userfile']['tmp_name']),"image")===0) {
// prepare the image for insertion
$imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));
// put the image in the db...
// database connection
mysql_connect($host, $user, $pass) OR DIE (mysql_error());
// select the db
mysql_select_db ($db) OR DIE ("Unable to select db".mysql_error());
// our sql query
$sql = "INSERT INTO test_image
(image, name)
VALUES
('{$imgData}', '{$_FILES['userfile']['name']}');";
// insert the image
mysql_query($sql) or die("Error in Query: " . mysql_error());
$msg='<p>Image successfully saved in database with id ='. mysql_insert_id().' </p>';
}
else
$msg="<p>Uploaded file is not an image.</p>";
}
else {
// if the file is not less than the maximum allowed, print an error
$msg='<div>File exceeds the Maximum File limit</div>
<div>Maximum File limit is '.$maxsize.' bytes</div>
<div>File '.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].
' bytes</div><hr />';
}
}
else
$msg="File not uploaded successfully.";
}
else {
$msg= file_upload_error_message($_FILES['userfile']['error']);
}
return $msg;
}
// Function to return error message based on error code
function file_upload_error_message($error_code) {
switch ($error_code) {
case UPLOAD_ERR_INI_SIZE:
return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file was only partially uploaded';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk';
case UPLOAD_ERR_EXTENSION:
return 'File upload stopped by extension';
default:
return 'Unknown upload error';
}
}
?>
</body>
</html>
</code></pre>
<p>Now i got the error, Fatal error: Call to undefined function finfo_open() on this line </p>
<pre><code>$finfo = finfo_open(FILEINFO_MIME_TYPE); .
</code></pre>
<p>Can somebody help me to fix this.</p>
<p>Thanks in advance.</p>
| 0 | 2,176 |
java.lang.ClassNotFoundException: com.sun.faces.config.ConfigureListener when using MyFaces with WASCE/Geronimo
|
<p>I am trying to create a simple JSF web application using MyFaces v 2.1 with WebSphere Application Server Community Edition v3.0.0.1 and Eclipse Juno but when I try to run the application the following error is returned</p>
<pre><code> java.lang.ClassNotFoundException: com.sun.faces.config.ConfigureListener
org.apache.geronimo.common.DeploymentException: java.lang.ClassNotFoundException: com.sun.faces.config.ConfigureListener
at org.apache.geronimo.web25.deployment.AbstractWebModuleBuilder.createWebAppClassFinder(AbstractWebModuleBuilder.java:665)
at org.apache.geronimo.web25.deployment.AbstractWebModuleBuilder.configureBasicWebModuleAttributes(AbstractWebModuleBuilder.java:698)
at org.apache.geronimo.tomcat.deployment.TomcatModuleBuilder.addGBeans(TomcatModuleBuilder.java:469)
at org.apache.geronimo.j2ee.deployment.SwitchingModuleBuilder.addGBeans(SwitchingModuleBuilder.java:174)
at org.apache.geronimo.j2ee.deployment.EARConfigBuilder.buildConfiguration(EARConfigBuilder.java:764)
at org.apache.geronimo.deployment.Deployer.deploy(Deployer.java:255)
at org.apache.geronimo.deployment.Deployer.deploy(Deployer.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at org.apache.geronimo.gbean.runtime.ReflectionMethodInvoker.invoke(ReflectionMethodInvoker.java:34)
at org.apache.geronimo.gbean.runtime.GBeanOperation.invoke(GBeanOperation.java:131)
at org.apache.geronimo.gbean.runtime.GBeanInstance.invoke(GBeanInstance.java:883)
at org.apache.geronimo.kernel.basic.BasicKernel.invoke(BasicKernel.java:245)
at org.apache.geronimo.kernel.KernelGBean.invoke(KernelGBean.java:344)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at org.apache.geronimo.gbean.runtime.ReflectionMethodInvoker.invoke(ReflectionMethodInvoker.java:34)
at org.apache.geronimo.gbean.runtime.GBeanOperation.invoke(GBeanOperation.java:131)
at org.apache.geronimo.gbean.runtime.GBeanInstance.invoke(GBeanInstance.java:883)
at org.apache.geronimo.kernel.basic.BasicKernel.invoke(BasicKernel.java:245)
at org.apache.geronimo.system.jmx.MBeanGBeanBridge.invoke(MBeanGBeanBridge.java:172)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:848)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:773)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1438)
at javax.management.remote.rmi.RMIConnectionImpl.access$200(RMIConnectionImpl.java:83)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1276)
at java.security.AccessController.doPrivileged(AccessController.java:284)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1378)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:799)
at sun.reflect.GeneratedMethodAccessor73.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322)
at sun.rmi.transport.Transport$1.run(Transport.java:171)
at java.security.AccessController.doPrivileged(AccessController.java:284)
at sun.rmi.transport.Transport.serviceCall(Transport.java:167)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:547)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:802)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:661)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:897)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:919)
at java.lang.Thread.run(Thread.java:736)
Caused by: java.lang.ClassNotFoundException: com.sun.faces.config.ConfigureListener
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:513)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:429)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:417)
at org.apache.geronimo.hook.equinox.GeronimoClassLoader.loadClass(GeronimoClassLoader.java:85)
at java.lang.ClassLoader.loadClass(ClassLoader.java:626)
at org.eclipse.osgi.internal.loader.BundleLoader.loadClass(BundleLoader.java:345)
at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:229)
at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1207)
at org.apache.geronimo.web25.deployment.AbstractWebModuleBuilder.addClass(AbstractWebModuleBuilder.java:670)
at org.apache.geronimo.web25.deployment.AbstractWebModuleBuilder.createWebAppClassFinder(AbstractWebModuleBuilder.java:661)
... 45 more
</code></pre>
<p>Presumably the error is occurring because the MyFaces jar files are not in the class path however I cannot figure out where I’m going wrong as the build path in Eclipse contains the required jars. I’ve also tried copying the jar files into the WEB-INF/lib directory but to no avail.</p>
<p>The screenshot below shows the project structure along with the libraries.</p>
<p><img src="https://i.stack.imgur.com/Ab9gK.jpg" alt="Eclipse Project Structure"></p>
<p>Is there something specific I need to do either in Eclipse or WASCE to include the jar files or does the problem lie elsewhere?</p>
| 0 | 2,152 |
Why is processing a sorted array faster than processing an unsorted array?
|
<p>Here is a piece of C++ code that shows some very peculiar behavior. For some strange reason, sorting the data (<em>before</em> the timed region) miraculously makes the loop almost six times faster.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <algorithm>
#include <ctime>
#include <iostream>
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;
// !!! With this, the next loop runs faster.
std::sort(data, data + arraySize);
// Test
clock_t start = clock();
long long sum = 0;
for (unsigned i = 0; i < 100000; ++i)
{
for (unsigned c = 0; c < arraySize; ++c)
{ // Primary loop
if (data[c] >= 128)
sum += data[c];
}
}
double elapsedTime = static_cast<double>(clock()-start) / CLOCKS_PER_SEC;
std::cout << elapsedTime << '\n';
std::cout << "sum = " << sum << '\n';
}
</code></pre>
<ul>
<li>Without <code>std::sort(data, data + arraySize);</code>, the code runs in 11.54 seconds.</li>
<li>With the sorted data, the code runs in 1.93 seconds.</li>
</ul>
<p>(Sorting itself takes more time than this one pass over the array, so it's not actually worth doing if we needed to calculate this for an unknown array.)</p>
<hr />
<p>Initially, I thought this might be just a language or compiler anomaly, so I tried Java:</p>
<pre class="lang-java prettyprint-override"><code>import java.util.Arrays;
import java.util.Random;
public class Main
{
public static void main(String[] args)
{
// Generate data
int arraySize = 32768;
int data[] = new int[arraySize];
Random rnd = new Random(0);
for (int c = 0; c < arraySize; ++c)
data[c] = rnd.nextInt() % 256;
// !!! With this, the next loop runs faster
Arrays.sort(data);
// Test
long start = System.nanoTime();
long sum = 0;
for (int i = 0; i < 100000; ++i)
{
for (int c = 0; c < arraySize; ++c)
{ // Primary loop
if (data[c] >= 128)
sum += data[c];
}
}
System.out.println((System.nanoTime() - start) / 1000000000.0);
System.out.println("sum = " + sum);
}
}
</code></pre>
<p>With a similar but less extreme result.</p>
<hr />
<p>My first thought was that sorting brings the data into the <a href="https://en.wikipedia.org/wiki/CPU_cache" rel="noreferrer">cache</a>, but then I thought how silly that was because the array was just generated.</p>
<ul>
<li>What is going on?</li>
<li>Why is processing a sorted array faster than processing an unsorted array?</li>
</ul>
<p>The code is summing up some independent terms, so the order should not matter.</p>
<hr />
<p><strong>Related / followup Q&As</strong> about the same effect with different / later compilers and options:</p>
<ul>
<li><a href="https://stackoverflow.com/q/66521344">Why is processing an unsorted array the same speed as processing a sorted array with modern x86-64 clang?</a></li>
<li><a href="https://stackoverflow.com/q/28875325">gcc optimization flag -O3 makes code slower than -O2</a></li>
</ul>
| 0 | 1,360 |
Can't resolve symbol android.support.v4.util.Pools in react-native-gesture-handler
|
<p>I am working on react-native project.</p>
<p>After I update my modules by running 'npm install',</p>
<p>I cannot find class 'Pools' which located in 'android.support.v4.util' in 'react-native-gesture-handler'.</p>
<ol>
<li>Why Is this error occur?</li>
<li>How can I fix this?</li>
</ol>
<p>1.error (In case run "react-native run-android")
-cmd</p>
<pre><code>Task :react-native-gesture-handler:compileDebugJavaWithJavac FAILED
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerEvent.java:3: error: cannot find symbol
import android.support.v4.util.Pools;
^
symbol: class Pools
location: package android.support.v4.util
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerEvent.java:19: error: package Pools does not exist
private static final Pools.SynchronizedPool<RNGestureHandlerEvent> EVENTS_POOL =
^
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerStateChangeEvent.java:3: error: cannot find symbol
import android.support.v4.util.Pools;
^
symbol: class Pools
location: package android.support.v4.util
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerStateChangeEvent.java:18: error: package Pools does not exist
private static final Pools.SynchronizedPool<RNGestureHandlerStateChangeEvent> EVENTS_POOL =
^
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerEvent.java:20: error: package Pools does not exist
new Pools.SynchronizedPool<>(TOUCH_EVENTS_POOL_SIZE);
^
D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerStateChangeEvent.java:19: error: package Pools does not exist
new Pools.SynchronizedPool<>(TOUCH_EVENTS_POOL_SIZE);
^
Note:D:\weneepl\project_y-test2_t\project_y\node_modules\react-native-gesture-handler\android\src\main\java\com\swmansion\gesturehandler\react\RNGestureHandlerButtonViewManager.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
6 errors
</code></pre>
<p>2.React Native Environment Info:</p>
<pre><code>System:
OS: Windows 10
CPU: (4) x64 Intel(R) Core(TM) i5-7500 CPU @ 3.40GHz
Memory: 7.59 GB / 15.96 GB
Binaries:
Yarn: 1.15.2 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
npm: 6.9.0 - C:\Program Files\nodejs\npm.CMD
IDEs:
Android Studio: Version 3.4.0.0 AI-183.5429.30.34.5452501
</code></pre>
<p>3.package.json</p>
<pre><code>{
"name": "project_y",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "react-native run-android",
"gradle-clean": "cd android & gradlew clean",
"start-root": "react-native run-android --root",
"test": "jest",
"bundle": "react-native bundle --platform android --dev false --entry-file
index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/",
"build": "cd android & gradlew assembleDebug"
},
"dependencies": {
"axios": "^0.18.0",
"moment": "^2.24.0",
"prop-types": "^15.7.2",
"react": "16.6.3",
"react-native": "0.58.5",
"react-native-android-open-settings": "^1.3.0",
"react-native-custom-checkbox": "^1.5.2",
"react-native-gesture-handler": "^1.0.16",
"react-native-grid-list": "^1.0.9",
"react-native-image-resizer": "^1.0.1",
"react-native-kakao-logins": "^1.3.6",
"react-native-linear-gradient": "^2.5.3",
"react-native-picker-select": "^6.0.0",
"react-native-shadow": "^1.2.2",
"react-native-super-grid": "^3.0.3",
"react-native-svg": "^9.2.4",
"react-native-vector-icons": "^6.3.0",
"react-native-webview": "^5.5.0",
"react-navigation": "^3.3.2",
"react-redux": "^6.0.1",
"redux": "^4.0.1"
},
"devDependencies": {
"babel-core": "7.0.0-bridge.0",
"babel-jest": "24.1.0",
"jest": "24.1.0",
"metro-react-native-babel-preset": "0.52.0",
"react-test-renderer": "16.6.3",
"redux-devtools": "^3.5.0"
},
"jest": {
"preset": "react-native"
},
"rnpm": {
"assets": [
"./assets/fonts/",
"resources/fonts"
]
}
}
</code></pre>
<p>4.build.gradle(app/)</p>
<pre><code>apply plugin: "com.android.application"
import com.android.build.OutputFile
project.ext.react = [
entryFile: "index.js"
]
apply from: "../../node_modules/react-native/react.gradle"
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
applicationId "com.projecty.projecty"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 10
versionName "1.9"
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a"
}
}
buildTypes {
release {
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}
dependencies {
implementation 'com.google.android.gms:play-services-base:12.0.0'
implementation 'com.android.installreferrer:installreferrer:1.0'
implementation 'com.igaworks.adbrix:abx-common-rm:+'
implementation project(':react-native-webview')
implementation project(':react-native-android-open-settings')
implementation project(':react-native-kakao-logins')
implementation project(':react-native-svg')
implementation project(':react-native-linear-gradient')
implementation project(':react-native-vector-icons')
implementation project(':react-native-gesture-handler')
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "com.android.support:appcompat-
v7:${rootProject.ext.supportLibVersion}"
compile(name: 'IgawSSP_v2.0.6a', ext: 'aar')
repositories {
flatDir {
dirs 'libs'
}
}
implementation "com.facebook.react:react-native:+" // From node_modules
}
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
subprojects {
repositories {
mavenCentral()
maven { url
'http://devrepo.kakao.com:8088/nexus/content/groups/public/' }
}
}
</code></pre>
<p>5.build.gradle(android/)</p>
<pre><code>buildscript {
ext {
buildToolsVersion = "28.0.2"
minSdkVersion = 16
compileSdkVersion = 28
targetSdkVersion = 28
supportLibVersion = "28.0.0"
}
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
google()
jcenter()
flatDir {
dirs 'libs'
}
maven {
url 'https://dl.bintray.com/igaworks/AdbrixRmSDK'
}
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
mavenCentral()
maven {
url 'http://devrepo.kakao.com:8088/nexus/content/groups/public/'
}
}
}
task wrapper(type: Wrapper) {
gradleVersion = '4.7'
distributionUrl = distributionUrl.replace("bin", "all")
}
</code></pre>
<p>I expect the complete of build project.</p>
| 0 | 3,610 |
ASP.NET VB Page_Load Only Once or Alternative
|
<p>I'm a little stuck on what to do! I have a special form that allows my customers to request a quote for a specific product (defined by PID in url) The form is loaded inside a modal dialogue and within that a Iframe. The Iframe's src value is set from the onclick event of ahref on the product pages eg;</p>
<pre><code><div id='basic-modal'><p><br /><br /><a href='#' class='basic' onClick="document.getElementById('ifr').src='quote/Public/Default.aspx?PID=111'">CLICK ME</a></p></div>
<div id="basic-modal-content">
<iframe id="ifr" width="850px" height="600px" frameborder="0" scrolling="no"></iframe>
</code></pre>
<p></p>
<p>The form that I am loading does a SQL insert when Page_Load is fired. Also it is within
If Page.IsPostBack = False Then</p>
<p>For some strange reason the page is doing it twice when the page loads and another time when the page is closed.. I need the SQL insert on the first page load as the returned values are used by my form. Can anyone suggest a good way of making the code within Page_Load only fire up once?</p>
<p>Many thanks!</p>
<p>UPDATE, Full Code:</p>
<p>aspx page</p>
<pre><code><%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="Public_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="../quoteFront.css" rel="stylesheet" type="text/css" />
<title></title>
<style type="text/css">
.style1
{
width: 100%;
}
.style2
{
height: 26px;
}
.style5
{
width: 299px;
}
.style6
{
width: 174px;
}
.style7
{
height: 26px;
width: 174px;
}
.style8
{
width: 291px;
}
.style9
{
height: 26px;
width: 189px;
}
.style10
{
}
.style11
{
width: 189px;
}
.style12
{
width: 191px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" EnablePartialRendering="true" CombineScripts="false" >
</cc1:ToolkitScriptManager>
</div>
<asp:UpdatePanel ID="UpdatePanel3" runat="server"><ContentTemplate>
<asp:Panel ID="Panel2" runat="server">
<table class="style1">
<tr>
<td class="style12">
First name</td>
<td class="style5">
<asp:TextBox ID="txtFirstName" runat="server" Width="300px"
AutoCompleteType="FirstName"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtFirstName" ErrorMessage="* Required" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style12">
Last name</td>
<td class="style5">
<asp:TextBox ID="txtLastName" runat="server" Width="300px"
AutoCompleteType="LastName"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txtLastName" ErrorMessage="* Required" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style12">
Company name</td>
<td class="style5">
<asp:TextBox ID="txtCompanyName" runat="server" Width="300px"
AutoCompleteType="Company"></asp:TextBox>
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td class="style12">
Email address</td>
<td class="style5">
<asp:TextBox ID="txtEmailAddress" runat="server" Width="300px" AutoCompleteType="Email"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
ControlToValidate="txtEmailAddress" ErrorMessage="* Required"
ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="txtEmailAddress" ErrorMessage=" * Invalid email address"
ForeColor="Red"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="style12">
Phone number</td>
<td class="style5">
<asp:TextBox ID="txtPhoneNumber" runat="server" Width="300px" AutoCompleteType="BusinessPhone"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
ControlToValidate="txtPhoneNumber" ErrorMessage="* Required"
ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
</table>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div>
<table class="style1">
<tr>
<td class="style11">
Quantity required</td>
<td class="style6">
<asp:TextBox ID="txtQuantity1" runat="server" AutoPostBack="True"></asp:TextBox>
<cc1:FilteredTextBoxExtender ID="ftbe" runat="server" FilterType="Numbers"
TargetControlID="txtQuantity1" />
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
ControlToValidate="txtQuantity1"
ErrorMessage="* Please enter quantity required" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style11">
<asp:Label ID="lblDesigninfo" runat="server" Text="Printing info"></asp:Label>
</td>
<td class="style6">
<asp:DropDownList ID="drpDesignInfo1" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource1" DataTextField="PrintInfoDesc"
DataValueField="ID" AppendDataBoundItems="True">
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:quotingSystemConnectionString %>"
SelectCommand="SELECT [ID], [PrintInfoDesc] FROM [PrintInfo]">
</asp:SqlDataSource>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
ControlToValidate="drpDesignInfo1" ErrorMessage="* Please select"
ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style11">
<asp:Label ID="lblColoursSideOne1" runat="server"
Text="Colour options first side" Visible="True"></asp:Label>
</td>
<td class="style6">
<asp:DropDownList ID="drpColoursSideOne1" runat="server" Visible="True"
AutoPostBack="True">
</asp:DropDownList>
</td>
<td>
&nbsp;</td>
</tr>
<tr>
<td class="style9">
<asp:Label ID="lblColoursSideTwo1" runat="server"
Text="Colour options second side" Visible="false"></asp:Label>
</td>
<td class="style7">
<asp:DropDownList ID="drpColoursSideTwo1" runat="server" Visible="false">
</asp:DropDownList>
</td>
<td class="style2">
</td>
</tr>
</table>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtQuantity1" EventName="TextChanged" />
<asp:AsyncPostBackTrigger ControlID="drpDesignInfo1"
EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="drpColoursSideOne1"
EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel1" runat="server"><ContentTemplate>
<div style="text-align: center">Please fill in the above fields before uploading
artwork.
<br />
When the upload is complete you will get the option to upload additional
artwork.
<cc1:AsyncFileUpload ID="AsyncFileUpload1" runat="server"
CompleteBackColor="Lime" ErrorBackColor="Red"
OnClientUploadComplete="UploadComplete" OnClientUploadError="uploadError"
OnClientUploadStarted="StartUpload"
onuploadedcomplete="AsyncFileUpload1_UploadedComplete" ThrobberID="Throbber"
UploaderStyle="Modern" UploadingBackColor="#66CCFF" Width="100%"
ClientIDMode="Inherit" />
<asp:Label ID="Throbber" runat="server" Style="display: none">
<img src="../Images/indicator.gif" align="absmiddle" alt="loading" />
</asp:Label><asp:Label ID="lblStatus" runat="server"></asp:Label>
<br />
<div style="max-height:70px; overflow : auto; ">
<asp:Label ID="lblUploadList" runat="server" ForeColor="#006600"
Font-Size="Smaller"></asp:Label>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<table class="style1">
<tr>
<td class="style10">
Any aditional info<asp:TextBox ID="txtComments" runat="server" Height="111px"
TextMode="MultiLine" Width="100%"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style8">
<asp:Button ID="Button1" runat="server" Text="Send Request" Width="100%"
Height="45px" Font-Bold="False" />
</td>
</tr>
</table>
</asp:Panel>
<br />
<asp:Panel ID="Panel1" runat="server" Visible="False">
Thank you for requesting a quote. A member of our sales team will be in touch
shortly.<br />
<br />
<asp:Button ID="btnRequestAnother" runat="server"
Text="Request another quote for this product" CausesValidation="False"
Height="45px" Width="100%"/>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript" language="javascript">
function uploadError(sender, args) {
document.getElementById("lblStatus").innerHTML = "Failed to upload " + args.get_fileName() + ". Please try again. If problem persistes please email sales@thecleverbaggers.co.uk";
document.getElementById("Button1").innerHTML = 'Send Request';
}
function StartUpload(sender, args) {
document.getElementById("lblStatus").innerHTML = 'Uploading Started. Depending on your connection speed this can take a very long time. Please wait....';
document.getElementById("Button1").innerHTML = 'Uploading Started. Please Wait....';
}
function UploadComplete(sender, args) {
var filename = args.get_fileName();
var contentType = args.get_contentType();
var text = "Upload Complete, Press Select File to upload more. " //"Size of " + filename + " is " + args.get_length() + " bytes";
if (contentType.length > 0) {
text //+= " and content type is '" + contentType + "'.";
}
document.getElementById("lblStatus").innerHTML = text;
document.getElementById("lblUploadList").innerHTML = document.getElementById("lblUploadList").innerHTML + "<br />" + filename + " Uploaded Successfully";
document.getElementById("Button1").innerHTML = 'Send Request';
}
</script>
</form>
</body>
</code></pre>
<p></p>
<p>VB CODE:</p>
<pre><code>Imports System.Data
Imports System.IO
Imports System.Data.SqlClient
Partial Class Public_Default
Inherits System.Web.UI.Page
Dim ArtworkID As Integer
Dim customerIDDecrypt As String
Public QuoteID As Integer
Dim UploadedFileList As String
Dim productID As String
'Shared IsFirstTime As Boolean = False
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
productID = Request.QueryString("PID")
customerIDDecrypt = "0"
'If Not Page.IsPostBack AndAlso Not IsFirstTime Then
If Not Page.IsPostBack Then
Try
Dim sql As String = "INSERT INTO [Quote] (Status, CreationDate, CreationTime, CustomerID, ProductID, IP)" & _
"VALUES (@Status, @CreationDate, @CreationTime, @CustomerID, @ProductID, @IP) SELECT SCOPE_IDENTITY()"
Using cn As New SqlConnection(ConfigurationManager.AppSettings("quotingSystemConnectionString")), _
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("@Status", SqlDbType.NVarChar).Value = 1
cmd.Parameters.Add("@CreationDate", SqlDbType.Date).Value = Date.UtcNow.ToLocalTime
cmd.Parameters.Add("@CreationTime", SqlDbType.Time).Value = Date.UtcNow.ToLocalTime.TimeOfDay
cmd.Parameters.Add("@CustomerID", SqlDbType.Int).Value = customerIDDecrypt
cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID
cmd.Parameters.Add("@IP", SqlDbType.NVarChar).Value = CStr(Request.UserHostAddress())
cn.Open()
'//grab the ID of this insert.
QuoteID = Integer.Parse(cmd.ExecuteScalar().ToString())
cn.Close()
'IsFirstTime = True
End Using
Catch ex As Exception
'// do something with this error!
Response.Write(ex.Message)
End Try
End If
End Sub
Protected Sub txtQuantity1_TextChanged(sender As Object, e As System.EventArgs) Handles txtQuantity1.TextChanged
'//populate colours dependant on quantity
If txtQuantity1.Text > "" Then
If txtQuantity1.Text < "100" Then
'side one
drpColoursSideOne1.Items.Clear()
'drpColoursSideOne1.Enabled = True
drpColoursSideOne1.Items.Add(New ListItem("One colour", "1"))
drpColoursSideOne1.Items.Add(New ListItem("More than one colour", "full"))
drpColoursSideOne1.Items.Add(New ListItem("I don't know!", "help"))
drpColoursSideOne1.Visible = True
'side two
drpColoursSideTwo1.Items.Clear()
'drpColoursSideTwo1.Enabled = True
drpColoursSideTwo1.Items.Add(New ListItem("One colour", "1"))
drpColoursSideTwo1.Items.Add(New ListItem("More than one colour", "full"))
drpColoursSideTwo1.Items.Add(New ListItem("I don't know!", "help"))
drpColoursSideTwo1.Items.Add(New ListItem("na", "na"))
Else
'side one
drpColoursSideOne1.Items.Clear()
'drpColoursSideOne1.Enabled = True
drpColoursSideOne1.Items.Add(New ListItem("One colour", "1"))
drpColoursSideOne1.Items.Add(New ListItem("Two colours", "2"))
drpColoursSideOne1.Items.Add(New ListItem("Three colours", "3"))
drpColoursSideOne1.Items.Add(New ListItem("Four colours", "4"))
drpColoursSideOne1.Items.Add(New ListItem("Five colours", "5"))
drpColoursSideOne1.Items.Add(New ListItem("Full colour (eg, photo)", "full"))
drpColoursSideOne1.Items.Add(New ListItem("I don't know!", "help"))
'side two
drpColoursSideTwo1.Items.Clear()
'drpColoursSideTwo1.Enabled = True
drpColoursSideTwo1.Items.Add(New ListItem("One colour", "1"))
drpColoursSideTwo1.Items.Add(New ListItem("Two colours", "2"))
drpColoursSideTwo1.Items.Add(New ListItem("Three colours", "3"))
drpColoursSideTwo1.Items.Add(New ListItem("Four colours", "4"))
drpColoursSideTwo1.Items.Add(New ListItem("Five colours", "5"))
drpColoursSideTwo1.Items.Add(New ListItem("Full colour (eg, photo)", "full"))
drpColoursSideTwo1.Items.Add(New ListItem("I don't know!", "help"))
drpColoursSideTwo1.Items.Add(New ListItem("na", "na"))
End If
Else
'nothing
End If
End Sub
Protected Sub drpDesignInfo1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles drpDesignInfo1.SelectedIndexChanged
If drpDesignInfo1.SelectedValue = "1" And txtQuantity1.Text > "0" Then
lblColoursSideTwo1.Visible = False
lblColoursSideOne1.Visible = True
drpColoursSideOne1.Visible = True
drpColoursSideOne1.Enabled = True
drpColoursSideTwo1.Visible = False
drpColoursSideTwo1.Enabled = False
drpColoursSideTwo1.SelectedValue = "na"
' drpColoursSideTwo1.Items.Remove(New ListItem("Same as the first side", "same"))
ElseIf drpDesignInfo1.SelectedValue = "3" And txtQuantity1.Text > "0" Then
lblColoursSideOne1.Visible = True
drpColoursSideOne1.Visible = True
drpColoursSideOne1.Enabled = True
lblColoursSideTwo1.Visible = True
drpColoursSideTwo1.Visible = True
drpColoursSideTwo1.Enabled = True
' drpColoursSideTwo1.Items.Remove(New ListItem("Same as the first side", "same"))
ElseIf drpDesignInfo1.SelectedValue = "2" And txtQuantity1.Text > "0" Then
lblColoursSideOne1.Visible = True
drpColoursSideOne1.Visible = True
drpColoursSideOne1.Enabled = True
lblColoursSideTwo1.Visible = True
drpColoursSideTwo1.Visible = True
drpColoursSideTwo1.Enabled = False
' Dim tmpCount2 = drpColoursSideTwo1.Items.Count
' If tmpCount2 = 7 Or tmpCount2 = 3 Then
'drpColoursSideTwo1.Items.Add(New ListItem("Same as the first side", "same"))
'End If
drpColoursSideTwo1.SelectedValue = drpColoursSideOne1.SelectedValue
End If
End Sub
Protected Sub AsyncFileUpload1_UploadedComplete(sender As Object, e As AjaxControlToolkit.AsyncFileUploadEventArgs)
System.Threading.Thread.Sleep(3000)
If AsyncFileUpload1.HasFile Then
'Dim strPath As String = newPath + Path.GetFileName(e.FileName)
'AsyncFileUpload1.SaveAs(strPath)
Dim fileName = Path.GetFileName(e.FileName)
'Dim imageBytes(AsyncFileUpload1.PostedFile.InputStream.Length) As Byte
'AsyncFileUpload1.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.length)
Dim imageBytes = AsyncFileUpload1.FileBytes
'AsyncFileUpload1.FileBytes
'// now insert this into the database
Try
Dim sql As String = "INSERT INTO [UploadedFiles] (CustomerID, FileName, FileSize, FileContent, FileType, FileUploadDate, QuoteID)" & _
"VALUES (@CustomerID, @FileName, @FileSize, @FileContent, @FileType, @FileUploadDate, @QuoteID) SELECT SCOPE_IDENTITY()"
Using cn As New SqlConnection(ConfigurationManager.AppSettings("quotingSystemConnectionStringLargeTimeout")), _
cmd As New SqlCommand(sql, cn)
cmd.CommandTimeout = "3600"
cmd.Parameters.Add("@CustomerID", SqlDbType.Int).Value = 1
cmd.Parameters.Add("@FileName", SqlDbType.NVarChar).Value = fileName
cmd.Parameters.Add("@FileSize", SqlDbType.NVarChar).Value = AsyncFileUpload1.PostedFile.ContentLength
cmd.Parameters.Add("@FileContent", SqlDbType.VarBinary).Value = imageBytes
cmd.Parameters.Add("@FileType", SqlDbType.NVarChar, 50).Value = AsyncFileUpload1.PostedFile.ContentType
cmd.Parameters.Add("@FileUploadDate", SqlDbType.Date).Value = Date.UtcNow.ToLocalTime
cmd.Parameters.Add("@QuoteID", SqlDbType.Int).Value = QuoteID
cn.Open()
'//grab the ID of this insert.
ArtworkID = Integer.Parse(cmd.ExecuteScalar().ToString())
cn.Close()
End Using
Catch ex As Exception
'// do something with this error!
Response.Write(ex.Message)
End Try
End If
End Sub
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
'// Populate the database with remaining information
Button1.Text = "Please Wait... Sending Request"
Dim thisConnection As New SqlConnection(ConfigurationManager.AppSettings("quotingSystemConnectionString"))
'Create Command object
Dim nonqueryCommand As SqlCommand = thisConnection.CreateCommand()
Try
' Open Connection
thisConnection.Open()
' 1. Create Command
' Sql Update Statement
Dim updateSql As String = "UPDATE Quote " & _
"SET Status = '2', FirstName = @FirstName, LastName = @LastName, CompanyName = @CompanyName, Email = @Email, Phone = @Phone, Quantity = @Quantity, DesignInfo = @DesignInfo, CS1 = @CS1, CS2 = @CS2, Comments = @Comments " & _
"WHERE QuoteID = " & QuoteID
Dim UpdateCmd As New SqlCommand(updateSql, thisConnection)
' 2. Map Parameters
'UpdateCmd.Parameters.Add("@Status", SqlDbType.Int, "Status")
UpdateCmd.Parameters.Add("@FirstName", SqlDbType.NVarChar, 100, "FirstName")
UpdateCmd.Parameters.Add("@LastName", SqlDbType.NVarChar, 100, "LastName")
UpdateCmd.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 100, "CompanyName")
UpdateCmd.Parameters.Add("@Email", SqlDbType.NVarChar, 200, "Email")
UpdateCmd.Parameters.Add("@Phone", SqlDbType.NVarChar, 30, "Phone")
UpdateCmd.Parameters.Add("@Quantity", SqlDbType.Int, 20, "Quantity")
UpdateCmd.Parameters.Add("@DesignInfo", SqlDbType.NVarChar, 100, "DesignInfo")
UpdateCmd.Parameters.Add("@CS1", SqlDbType.NVarChar, 20, "CS1")
UpdateCmd.Parameters.Add("@CS2", SqlDbType.NVarChar, 20, "CS2")
UpdateCmd.Parameters.Add("@Comments", SqlDbType.NVarChar, 1000, "Comments")
''''''''''''''
'UpdateCmd.Parameters("@Status").Value = 2
UpdateCmd.Parameters("@FirstName").Value = txtFirstName.Text
UpdateCmd.Parameters("@LastName").Value = txtLastName.Text
UpdateCmd.Parameters("@CompanyName").Value = txtCompanyName.Text
UpdateCmd.Parameters("@Email").Value = txtEmailAddress.Text
UpdateCmd.Parameters("@Phone").Value = txtPhoneNumber.Text
UpdateCmd.Parameters("@Quantity").Value = txtQuantity1.Text
UpdateCmd.Parameters("@DesignInfo").Value = drpDesignInfo1.SelectedValue
UpdateCmd.Parameters("@CS1").Value = drpColoursSideOne1.SelectedValue
Dim CS2 As String
If drpDesignInfo1.SelectedValue = "1" Then
CS2 = "na"
Else
CS2 = drpColoursSideTwo1.SelectedValue
End If
UpdateCmd.Parameters("@CS2").Value = CS2
UpdateCmd.Parameters("@Comments").Value = txtComments.Text
'QuoteID
'''''''''''''''
UpdateCmd.ExecuteNonQuery()
Catch ex As SqlException
' Display error
Response.Write("FAIL: " & ex.Message)
Finally
' Close Connection
thisConnection.Close()
Panel1.Visible = True
Panel2.Visible = False
End Try
End Sub
Protected Sub btnRequestAnother_Click(sender As Object, e As System.EventArgs) Handles btnRequestAnother.Click
QuoteID = Nothing
Response.Redirect(Request.RawUrl)
Panel1.Visible = False
Panel2.Visible = True
'IsFirstTime = False
End Sub
Protected Sub drpColoursSideOne1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles drpColoursSideOne1.SelectedIndexChanged
If drpDesignInfo1.SelectedValue = "2" Then
drpColoursSideTwo1.SelectedValue = drpColoursSideOne1.SelectedValue
End If
End Sub
End Class
</code></pre>
<p>Please excuse my messy code...</p>
| 0 | 11,587 |
Uncaught exception in promise when when trying to use nested components
|
<p>I am getting this exception when trying to use nested components:</p>
<pre><code>EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot set property 'endSourceSpan' of null
XCEPTION: Error: Uncaught (in promise): TypeError: Cannot set property 'endSourceSpan' of nullBrowserDomAdapter.logError @ angular2.dev.js:23877BrowserDomAdapter.logGroup @ angular2.dev.js:23888ExceptionHandler.call @ angular2.dev.js:1317(anonymous function) @ angular2.dev.js:12763schedulerFn @ angular2.dev.js:13167SafeSubscriber.__tryOrUnsub @ Rx.js:10775SafeSubscriber.next @ Rx.js:10730Subscriber._next @ Rx.js:10690Subscriber.next @ Rx.js:10667Subject._finalNext @ Rx.js:11191Subject._next @ Rx.js:11183Subject.next @ Rx.js:11142EventEmitter.emit @ angular2.dev.js:13148NgZone._zoneImpl.ng_zone_impl_1.NgZoneImpl.onError @ angular2.dev.js:13566NgZoneImpl.inner.inner.fork.onHandleError @ angular2.dev.js:2128ZoneDelegate.handleError @ angular2-polyfills.js:336Zone.runGuarded @ angular2-polyfills.js:244drainMicroTaskQueue @ angular2-polyfills.js:495ZoneTask.invoke @ angular2-polyfills.js:434
angular2.dev.js:23877 STACKTRACE:BrowserDomAdapter.logError @ angular2.dev.js:23877ExceptionHandler.call @ angular2.dev.js:1319(anonymous function) @ angular2.dev.js:12763schedulerFn @ angular2.dev.js:13167SafeSubscriber.__tryOrUnsub @ Rx.js:10775SafeSubscriber.next @ Rx.js:10730Subscriber._next @ Rx.js:10690Subscriber.next @ Rx.js:10667Subject._finalNext @ Rx.js:11191Subject._next @ Rx.js:11183Subject.next @ Rx.js:11142EventEmitter.emit @ angular2.dev.js:13148NgZone._zoneImpl.ng_zone_impl_1.NgZoneImpl.onError @ angular2.dev.js:13566NgZoneImpl.inner.inner.fork.onHandleError @ angular2.dev.js:2128ZoneDelegate.handleError @ angular2-polyfills.js:336Zone.runGuarded @ angular2-polyfills.js:244drainMicroTaskQueue @ angular2-polyfills.js:495ZoneTask.invoke @ angular2-polyfills.js:434
angular2.dev.js:23877 Error: Uncaught (in promise): TypeError: Cannot set property 'endSourceSpan' of null
at resolvePromise (angular2-polyfills.js:543)
at angular2-polyfills.js:520
at ZoneDelegate.invoke (angular2-polyfills.js:332)
at Object.NgZoneImpl.inner.inner.fork.onInvoke (angular2.dev.js:2111)
at ZoneDelegate.invoke (angular2-polyfills.js:331)
at Zone.run (angular2-polyfills.js:227)
at angular2-polyfills.js:576
at ZoneDelegate.invokeTask (angular2-polyfills.js:365)
at Object.NgZoneImpl.inner.inner.fork.onInvokeTask (angular2.dev.js:2103)
at ZoneDelegate.invokeTask (angular2-polyfills.js:364)BrowserDomAdapter.logError @ angular2.dev.js:23877ExceptionHandler.call @ angular2.dev.js:1320(anonymous function) @ angular2.dev.js:12763schedulerFn @ angular2.dev.js:13167SafeSubscriber.__tryOrUnsub @ Rx.js:10775SafeSubscriber.next @ Rx.js:10730Subscriber._next @ Rx.js:10690Subscriber.next @ Rx.js:10667Subject._finalNext @ Rx.js:11191Subject._next @ Rx.js:11183Subject.next @ Rx.js:11142EventEmitter.emit @ angular2.dev.js:13148NgZone._zoneImpl.ng_zone_impl_1.NgZoneImpl.onError @ angular2.dev.js:13566NgZoneImpl.inner.inner.fork.onHandleError @ angular2.dev.js:2128ZoneDelegate.handleError @ angular2-polyfills.js:336Zone.runGuarded @ angular2-polyfills.js:244drainMicroTaskQueue @ angular2-polyfills.js:495ZoneTask.invoke @ angular2-polyfills.js:434
angular2-polyfills.js:469 Unhandled Promise rejection: Cannot set property 'endSourceSpan' of null ; Zone: angular ; Task: Promise.then ; Value: TypeError: Cannot set property 'endSourceSpan' of null(…)consoleError @ angular2-polyfills.js:469drainMicroTaskQueue @ angular2-polyfills.js:498ZoneTask.invoke @ angular2-polyfills.js:434
angular2-polyfills.js:471 Error: Uncaught (in promise): TypeError: Cannot set property 'endSourceSpan' of null(…)consoleError @ angular2-polyfills.js:471drainMicroTaskQueue @ angular2-polyfills.js:498ZoneTask.invoke @ angular2-polyfills.js:434
</code></pre>
<p>This is my code for the main component:</p>
<pre class="lang-html prettyprint-override"><code><base-menu [menu-items-list]="menuList" [menu-layer]="layer"
(select-menu-item)="selectMenuItem($event)"
(add-new-item)="addMenuItem($event)"></base-menu>
</code></pre>
<pre class="lang-js prettyprint-override"><code>import {BaseMenuComponent} from '../../../../components/menuComponent/baseMenuComponent/baseMenuComponent';
let applicationPath: string = '/app/pages/adminPage/categoriesPage/requestsPage';
@Component({
selector: 'companies-Page',
templateUrl: applicationPath + '/requestsPage.html',
styleUrls:[ applicationPath + '/requestsPage.css'],
providers:[RequestTypeService, HTTP_PROVIDERS],
directives:[BaseMenuComponent]
})
export class RequestsPage implements OnInit {
requestTypes:Array<RequestType> = new Array();
searchQuery: string = "";
menuList = [
{id:12, layer:0, name:'asd'},
{id:13, layer:0, name:'asda'},
{id:14, layer:0, name:'asdd'}];
layer = 0;
_requestTypeService:RequestTypeService
constructor(requestTypeService:RequestTypeService) {
this._requestTypeService = requestTypeService;
}
ngOnInit(){
//this.getRequestTypesWithFilters();
}
}
</code></pre>
<p>and this is the child component:</p>
<pre class="lang-js prettyprint-override"><code>import {Component, Input, Output, EventEmitter, OnInit} from 'angular2/core';
@Component({
selector: 'base-menu',
//templateUrl: '/app/components/menuComponent/baseMenuComponent/baseMenuComponent.html'
template:`
<div class="base-menu-component">
<ul class="nav nav-pills nav-stacked">
<li class="form-group row">
<input class="form-control" [(ngModel)]="newMenuItem"/>
<button class="btn btn-success" (click)="addMenuItem()">
<span class="glyphicon glyphicon-plus"></span>
</button>
<button class="btn btn-success" (click)="clearMenuItem()">
<span class="glyphicon glyphicon-remove"></span>
</button>
</li>
<li *ngFor="#item of menuItems" [class]="isItemSelected(item) ? 'active':''" (click)="selectItem(item)">
<a>{{item.name}}</a>
</li>
</ul>
</div>`
})
export class BaseMenuComponent implements OnInit {
@Input('menu-items-list') menuItemsList:Array<MenuItem>;
@Input('menu-layer') menuLayer:number;
@Output('select-menu-item') broadcastMenuItem: EventEmitter<MenuData> = new EventEmitter<MenuData>();
@Output('add-new-item') broadcastNewItem: EventEmitter<MenuData> = new EventEmitter<MenuData>();
selectedItem:MenuItem;
newMenuItem:string;
constructor() { }
ngOnInit(){
this.selectedItem = this.menuItemsList && this.menuItemsList.length > 0 ? this.menuItemsList[0] : null;
this.newMenuItem = "";
}
isItemSelected(menuItem){
return this.selectedItem == menuItem;
}
selectItem(menuItem){
this.selectedItem = menuItem;
this.broadcastMenuItem.emit({menuItem:menuItem, menuLayer:this.menuLayer});
}
addMenuItem(){
this.broadcastNewItem.emit({menuItem:this.newMenuItem, menuLayer:this.menuLayer});
this.clearMenuItem();
}
clearMenuItem(){
this.newMenuItem = "";
}
}
interface MenuItem{
id;
layer;
parentId;
name;
}
interface MenuData{
menuItem;
menuLayer;
}
</code></pre>
<p>Can someone explain me from where is this error and why it appears?<br>
To me, the html and both components look very clear.</p>
| 0 | 3,010 |
MVC4: On validation error, change the textbox color to red
|
<p>I have a form which has some text boxes, and when the textbox doesn't contain valid value I get the error message but the textbox color doesn't change to red.</p>
<p>This is what I have</p>
<p><strong>Model</strong></p>
<pre><code>public class AddCompany
{
public int Id { get; set; }
[Required(ErrorMessage = "*Name is required")]
public string Name { get; set; }
[Required(ErrorMessage = "*Address is required")]
[RegularExpression(@"^\(?([0-9]{4})\)?([A-Z]{2})",ErrorMessage = "*Not a valid Zip Code, Must be in format 1234AB")]
public string Address { get; set; }
[Required(ErrorMessage = "*Phone Number is required")]
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^\(?([0-9]{10})", ErrorMessage = "*Not a valid number, must be 10 numbers")]
public string Phone { get; set; }
[DataType(DataType.DateTime)]
public DateTime DateTimeAdded { get; set; }
public string Comment { get; set; }
}
</code></pre>
<p><strong>View</strong></p>
<pre><code>@model CrmTestProject.Models.ViewModels.AddCompany
@{
ViewBag.Title = "AddCompany";
Layout = "~/Views/shared/_BootstrapLayout.basic.cshtml";
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")"></script>
<h2>AddCompany</h2>
@Html.ValidationSummary(true)
<fieldset class="form-horizontal">
<legend>New Company <small>Add</small></legend>
@using (Html.BeginForm("AddCompany", "Company"))
{
<div class ="controls">
<label class="label">@Html.Label("Name")</label>
<div class="input-block-label">@Html.EditorFor(model=>model.Name)
@Html.ValidationMessageFor(model=>model.Name)
</div>
<br/>
<label class="label">@Html.Label("Address")</label>
<div class="input-block-level">@Html.EditorFor(model=>model.Address)
@Html.ValidationMessageFor(model=>model.Address)
</div>
<br/>
<label class="label">@Html.Label("Phone")</label>
<div class="input-block-level">@Html.EditorFor(model=>model.Phone)
@Html.ValidationMessageFor(model=>model.Phone)
</div>
<br/>
<div class="input-block-level">@Html.TextAreaFor(model=>model.Comment)</div>
</div>
<div class="form-actions" id="buttons">
<button type="submit" class="btn btn-primary" id="Submit">Save changes</button>
@Html.ActionLink("Cancel", "CompanyIndex", new { @class = "btn" })
</div>
}
</fieldset>
</code></pre>
<p><strong>Browser ScreenShot</strong>
<img src="https://i.stack.imgur.com/Qo5ZI.jpg" alt="enter image description here"></p>
<p>As you can see I get the error message but I also want the textbox and preferably error message color to be red. I don't know if it is due to bootstrap.
But when I check this <a href="http://weblogs.asp.net/imranbaloch/archive/2011/02/05/new-validation-attributes-in-asp-net-mvc-3-future.aspx" rel="nofollow noreferrer">blog for validation</a> things work perfectly here.
Can anyone give me some suggestion?</p>
| 0 | 1,512 |
OpenGL Rendering in a secondary thread
|
<p>I'm writing a 3D model viewer application as a hobby project, and also as a test platform to try out different rendering techniques. I'm using SDL to handle window management and events, and OpenGL for the 3D rendering. The first iteration of my program was single-threaded, and ran well enough. However, I noticed that the single-threaded program caused the system to become very sluggish/laggy. My solution was to move all of the rendering code into a different thread, thereby freeing the main thread to handle events and prevent the app from becoming unresponsive. </p>
<p>This solution worked intermittently, the program frequently crashed due to a changing (and to my mind bizarre) set of errors coming mainly from the X window system. This led me to question my initial assumption that as long as all of my OpenGL calls took place in the thread where the context was created, everything should still work out. After spending the better part of a day searching the internet for an answer, I am thoroughly stumped. </p>
<p>More succinctly: Is it possible to perform 3D rendering using OpenGL in a thread other than the main thread? Can I still use a cross-platform windowing library such as SDL or GLFW with this configuration? Is there a better way to do what I'm trying to do?</p>
<p>So far I've been developing on Linux (Ubuntu 11.04) using C++, although I am also comfortable with Java and Python if there is a solution that works better in those languages.</p>
<p><strong>UPDATE:</strong> As requested, some clarifications:</p>
<ul>
<li>When I say "The system becomes sluggish" I mean interacting with the desktop (dragging windows, interacting with the panel, etc) becomes much slower than normal. Moving my application's window takes time on the order of seconds, and other interactions are just slow enough to be annoying.</li>
<li>As for interference with a compositing window manager... I am using the GNOME shell that ships with Ubuntu 11.04 (staying away from Unity for now...) and I couldn't find any options to disable desktop effects such as there was in previous distributions. I assume this means I'm not using a compositing window manager...although I could be very wrong. </li>
<li>I believe the "X errors" are server errors due to the error messages I'm getting at the terminal. More details below. </li>
</ul>
<p>The errors I get with the multi-threaded version of my app:</p>
<blockquote>
<p>XIO: fatal IO error 11 (Resource temporarily unavailable) on X server ":0.0"
after 73 requests (73 known processed) with 0 events remaining.</p>
<p>X Error of failed request: BadColor (invalid Colormap parameter)
Major opcode of failed request: 79 (X_FreeColormap)
Resource id in failed request: 0x4600001
Serial number of failed request: 72
Current serial number in output stream: 73</p>
<p>Game: ../../src/xcb_io.c:140: dequeue_pending_request: Assertion `req == dpy->xcb->pending_requests' failed.
Aborted</p>
</blockquote>
<p>I always get one of the three errors above, which one I get varies, apparently at random, which (to my eyes) would appear to confirm that my issue does in fact stem from my use of threads. Keep in mind that I'm learning as I go along, so there is a very good chance that in my ignorance I've something rather stupid along the way.</p>
<p><strong>SOLUTION:</strong> For anyone who is having a similar issue, I solved my problem by moving my call to <code>SDL_Init(SDL_INIT_VIDEO)</code> to the rendering thread, and locking the context initialization using a mutex. This ensures that the context is created in the thread that will be using it, and it prevents the main loop from starting before initialization tasks have finished. A simplified outline of the startup procedure:</p>
<p>1) Main thread initializes <code>struct</code> which will be shared between the two threads, and which contains a mutex.<br>
2) Main thread spawns render thread and sleeps for a brief period (1-5ms), giving the render thread time to lock the mutex. After this pause, the main thread blocks while trying to lock the mutex.<br>
3) Render thread locks mutex, initializes SDL's video subsystem and creates OpenGL context.<br>
4) Render thread unlocks mutex and enters its "render loop".<br>
5) The main thread is no longer blocked, so it locks and unlocks the mutex before finishing its initialization step. </p>
<p>Be sure and read the answers and comments, there is a lot of useful information there. </p>
| 0 | 1,148 |
RecyclerView inside CoordinatorLayout,AppBarLayout Scrolling issue
|
<p>I have this xml code in fragment:</p>
<pre><code><CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/coordinatorLayout" android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="@+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme"
app:elevation="0dp">
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="300dp"
app:layout_scrollFlags="scroll"
android:id="@+id/collapsingToolbarLayout"
app:statusBarScrim="@color/bestColor">
<LinearLayout></LinearLayout> <!--this elements hide then appbar is collapsed-->
</android.support.design.widget.CollapsingToolbarLayout>
<LinearLayout>
<ImageButton>
android:id="@+id/profile_header_trophies"
</ImageButton><!-- this elements like a tab,visible if appbar collapsed-->
</LinearLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/profile_recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
</code></pre>
<p>in Java Class on Item set ClickListener: </p>
<pre><code>@OnClick(R.id.profile_header_trophies)
public void profile_header_trophies_clicked() {
if (myProfile != null) {
appBarLayout.setExpanded(false, false);
if (myProfile.getBests().size() == 0) {
profile_recyclerView.smoothScrollToPosition(3);
} else {
profile_recyclerView.smoothScrollToPosition(2 + 20);
}
}
</code></pre>
<p>When I click to <strong>ImageButton</strong>, my <strong>RecyclerView</strong> scrolls to position, everything looks fine.
But if I put finger on AppBarLayout section (ImageButton) which visible(sticky) on top, and drag to bottom I have a bad scrolling.
My appbar start expanded, while my Recycler have some elements on top (they are hidden when scrolled).</p>
<p><img src="https://i.stack.imgur.com/fL7oM.gif" alt="enter image description here"></p>
<p>I think this problem is setting behavoir. Because if I scrolling recycler first, AppBar doesnt start expanding, while Recycler not rich top of elements.</p>
<p>Thanks for your answers.</p>
| 0 | 1,275 |
How do I link glibc's implementation of iconv?
|
<p>The GNU C library provides an implementation of iconv - how do I use it?</p>
<p>Simple program:</p>
<pre><code>#include <iconv.h>
int main( int argc, char **argv ) {
iconv_t cd = iconv_open( "UTF-8", "ISO-8859-1" );
iconv_close( cd );
return 0;
}
</code></pre>
<p>Compile and link:</p>
<pre><code>$ gcc -Wall iconv.c -o iconv
/tmp/ccKAfXNg.o: In function `main':
iconv.c:(.text+0x19): undefined reference to `libiconv_open'
iconv.c:(.text+0x29): undefined reference to `libiconv_close'
collect2: ld returned 1 exit status
</code></pre>
<p>List the symbols to show they exist!</p>
<pre><code>$ nm -D /lib/libc-2.12.1.so | grep iconv
00017920 T iconv
00017ae0 T iconv_close
00017720 T iconv_open
</code></pre>
<p>If I install the GNU libiconv library to /usr/local and link with -liconv it works. How do I link with the glibc implementation of iconv?</p>
<p>EDIT: More information as requested from the comments:</p>
<p>List all iconv.h files in /usr (1 match)</p>
<pre><code>$ find /usr/ | grep "iconv\.h"
/usr/include/iconv.h
</code></pre>
<p>Reinstall libc6-dev to ensure the correct header is installed.</p>
<pre><code>$ dpkg -S /usr/include/iconv.h
libc6-dev: /usr/include/iconv.h
$ apt-get install --reinstall libc6-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 1 reinstalled, 0 to remove and 0 not upgraded.
Need to get 0B/4,910kB of archives.
After this operation, 0B of additional disk space will be used.
(Reading database ... 143458 files and directories currently installed.)
Preparing to replace libc6-dev 2.12.1-0ubuntu10.1 (using .../libc6-dev_2.12.1-0ubuntu10.1_i386.deb) ...
Unpacking replacement libc6-dev ...
Setting up libc6-dev (2.12.1-0ubuntu10.1) ...
</code></pre>
<p>Compile and link again with suggested preprocessor option:</p>
<pre><code>$ gcc -Wall -DLIBICONV_PLUG iconv.c -o iconv
/tmp/ccKAfXNg.o: In function `main':
iconv.c:(.text+0x19): undefined reference to `libiconv_open'
iconv.c:(.text+0x29): undefined reference to `libiconv_close'
collect2: ld returned 1 exit status
</code></pre>
<p>Output from gcc -H:</p>
<pre><code>$ gcc -H iconv.c
. /usr/include/iconv.h
.. /usr/include/features.h
... /usr/include/bits/predefs.h
... /usr/include/sys/cdefs.h
.... /usr/include/bits/wordsize.h
... /usr/include/gnu/stubs.h
.... /usr/include/bits/wordsize.h
.... /usr/include/gnu/stubs-32.h
.. /usr/lib/gcc/i686-linux-gnu/4.4.5/include/stddef.h
Multiple include guards may be useful for:
/usr/include/bits/predefs.h
/usr/include/gnu/stubs-32.h
/usr/include/gnu/stubs.h
/usr/lib/gcc/i686-linux-gnu/4.4.5/include/stddef.h
</code></pre>
<p><a href="http://pastebin.com/iQC1sBZq" rel="noreferrer">pastbin copy of /usr/include/iconv.h</a></p>
<p>Fixed: Reboot fixed the issue. I suspect a cached copy of libiconv was causing the conflicts, even though it was deleted from disk.</p>
| 0 | 2,835 |
How to use or annotate a dummy field in a JPA entity bean which is not supposed to be persisted in database
|
<p>I have this code for login validation using a Struts2 action class which calls an EJB for LDAP validation and then if (LDAP credentials) validated, querying the user database to get the rest of the user information using the JPA entity bean which also acts like a POJO. Unlike the username, userid and other user info, password is not stored in the database, but for the sake of the POJO getter and setter method I attempt to include a dummy password field - for serving the Struts2 action form. </p>
<p>The problem is after ldap authentication, an exception occurs stating that the column "password" does not exist in the database (which was never meant to be anyway!)</p>
<pre><code>Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'PASSWORD' in 'field list'
Error Code: 1054
Call: SELECT PERSON_ID, ACTIVE_USER, EMAIL, FIRSTNAME, SURNAME, PASSWORD, FULLNAME, EMPLOYEE_NUMBER FROM xxte_employees WHERE (ACTIVE_USER = ?)
bind => [john.doe]
Query: ReadAllQuery(name="XxteEmployees.validateLogin" referenceClass=XxteEmployees sql="SELECT PERSON_ID, ACTIVE_USER, EMAIL, FIRSTNAME, SURNAME, PASSWORD, FULLNAME, EMPLOYEE_NUMBER FROM xxte_employees WHERE (ACTIVE_USER = ?)")
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:333)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:687)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:530)
at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:529)
....
</code></pre>
<p>Here's the code from the entity bean:</p>
<pre><code>public class XxteEmployees implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "ACTIVE_USER")
private String activeUser;
@Column(name = "EMAIL")
private String email;
@Id
@Basic(optional = false)
@Column(name = "PERSON_ID")
private Double personId;
@Column(name = "EMPLOYEE_NUMBER")
private Double employeeNumber;
@Column(name = "FIRSTNAME")
private String firstname;
@Column(name = "SURNAME")
private String surname;
private String fullname;
private String password;
public XxteEmployees() {
}
public XxteEmployees(Double personId) {
this.personId = personId;
}
public String getActiveUser() {
return activeUser;
}
public void setActiveUser(String activeUser) {
this.activeUser = activeUser;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Double getPersonId() {
return personId;
}
public void setPersonId(Double personId) {
this.personId = personId;
}
public Double getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(Double employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
// BEGIN: objects not in db
public String getFullname() {
return firstname + ' ' + surname;
}
public void setFullname(String fullname) {
this.fullname = firstname + ' ' + surname;;
}
public String getPassword() {
return sifre;
}
public void setPassword(String password) {
this.password = password;
}
// END: objects not in db
</code></pre>
<p>Any workaround for this?</p>
| 0 | 1,420 |
Critical dependency: the request of a dependency is an expression -- react-universal-component
|
<p><strong>Warning:</strong></p>
<pre><code>[HMR] bundle has 2 warnings
client.js:189 ./node_modules/babel-plugin-universal-import/universalImport.js 33:18-37
Critical dependency: the request of a dependency is an expression
@ ./src/routes/index.js
@ ./src/app-root.js
@ multi babel-runtime/regenerator webpack-hot-middleware/client?reload=true ./src/app-root.js
./node_modules/react-universal-component/dist/utils.js 59:11-29
Critical dependency: the request of a dependency is an expression
@ ./node_modules/react-universal-component/dist/index.js
@ ./src/routes/index.js
@ ./src/app-root.js
@ multi babel-runtime/regenerator webpack-hot-middleware/client?reload=true ./src/app-root.js
</code></pre>
<p><strong>App-root.js</strong></p>
<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import Routes from './routes';
function render(Component) {
ReactDOM.render(
<AppContainer>
<Component />
</AppContainer>,
document.getElementById('react-root')
);
}
render(Routes);
if (module.hot) {
module.hot.accept('./routes/index.js', () => {
const NewRoutes = require('./routes/index.js').default;
render(NewRoutes);
});
}
</code></pre>
<p><strong>src/routes/index.js</strong></p>
<pre><code>import React from 'react';
import { hot } from 'react-hot-loader';
import universal from 'react-universal-component';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import { Switch } from 'react-router';
const UniversalComponent = universal(({ page }) =>
import(`../components/${page}`)
);
const Routes = () => (
<Router>
<div>
<Link to="/">Home</Link>
<Link to="/about">About Me</Link>
<Switch>
<Route exact path="/">
<UniversalComponent page="counter" />
</Route>
<Route exact path="/about">
<UniversalComponent page="about-me" />
</Route>
</Switch>
</div>
</Router>
);
export default hot(module)(Routes);
</code></pre>
<p><strong>webpack.dev.js</strong></p>
<pre><code>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
module.exports = {
mode: 'development',
devtool: 'source-map',
entry: {
// We want our client to reload in case a module doesn't recognise that it's parent changed
vendor: ['react', 'react-dom'],
main: [
'babel-runtime/regenerator',
'webpack-hot-middleware/client?reload=true',
'./src/app-root.js',
],
},
output: {
filename: '[name].bundle.js',
chunkFilename: '[name]-[hash:8].js',
path: path.resolve(__dirname, '../dist'),
publicPath: '/',
},
module: {
rules: [
{
test: /\.js/,
use: [
{
loader: 'babel-loader',
},
],
exclude: /node_modules/,
},
{
test: /\.css/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: true,
modules: true,
localIdentName: '[name]--[local]--[hash:base64:8]',
},
},
],
},
{
test: /\.scss/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: true,
modules: true,
},
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
},
},
],
},
{
test: /\.html/,
use: [
{
loader: 'html-loader',
options: {
attrs: ['img:src'],
},
},
],
},
{
test: /\.(jpg|gif|png)/,
use: [
{
loader: 'file-loader',
options: {
name: 'images/[name]-[hash:8].[ext]',
},
},
],
},
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html',
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('development'),
},
}),
// new BundleAnalyzerPlugin({
// generateStatsFile: true,
// }),
],
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
name: 'vendor',
chunks: 'initial',
minChunks: 2,
},
},
},
},
devServer: {
contentBase: 'dist',
overlay: true,
stats: {
colors: true,
},
hot: true,
},
};
</code></pre>
<p><strong>Versions</strong></p>
<pre><code>"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-plugin-universal-import": "^3.0.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"express": "^4.16.3",
"express-static-gzip": "^0.3.2",
"nodemon": "^1.18.3",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"react-universal-component": "^3.0.0",
"webpack": "^4.16.2",
"webpack-cli": "^3.1.0",
"webpack-dev-middleware": "^3.1.3",
"webpack-hot-middleware": "^2.22.3"
</code></pre>
<p>I have no clue why am I seeing this warning when I am using react-universal-component. I only see this when HMR is enabled and when I use react-universal-component.</p>
| 0 | 3,055 |
Jersey REST The ResourceConfig instance does not contain any root resource classes
|
<p>Although this is one ancient question, I still can not find the answer to make this work.
Please correct if you find any of my statement is not correct.</p>
<p>I have a Java Face app and use REST for the Web Services. I don't think Face has anything to do with my problem at all.
The web.xml is:</p>
<pre><code><servlet>
<servlet-name>NDREST</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.bi.nd.webservice</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>NDREST</servlet-name>
<url-pattern>/nd/*</url-pattern>
</servlet-mapping>
</code></pre>
<p>I have quite a few more servlets in the web.xml since is is a Face app with Trinidad, etc.</p>
<p>In the package com.bi.nd.webservice, my resource class is:</p>
<pre><code>import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Produces(MediaType.APPLICATION_XML)
@Path("/hello")
public class TransactionResource
{
public TransactionResource()
{
}
@GET
@Produces(MediaType.TEXT_PLAIN)
public String itWorks()
{
return "Get is OK";
}
}
</code></pre>
<p>The fact that my class has a @GET is enough to identify itself a resource class.<br>
Let alone all other complexities, I compiled my source code with Ant in Eclipse and I got this error in the catalina.out file:</p>
<pre><code>May 24, 2011 8:48:46 AM com.sun.jersey.api.core.PackagesResourceConfig init
INFO: Scanning for root resource and provider classes in the packages:
com.bi.nd.webservice
May 24, 2011 8:48:46 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.7 05/20/2011 11:04 AM'
May 24, 2011 8:48:46 AM com.sun.jersey.server.impl.application.RootResourceUriRules <init>
SEVERE: The ResourceConfig instance does not contain any root resource classes.
</code></pre>
<p>Some suggested that copy the asm.jar, jsr-api.jar, jersey-server.jar and jersey-core.jar into the app WEB-INF/lib. I did that and it still did not work.
I found the suggestion was a bit odd since WEB-INF/lib is a place where Eclipse will install all dependency libraries from the build path. It is not a place where we manually put libraries.</p>
<p>Some explained that this error had something to do with Java plug-in and the way Jersey was written. But that was years ago.</p>
<p>Can some one explains to me why I keep having this problem?</p>
<p>Followup:
Although from REST web site, resource class defined as Root resource classes are POJOs (Plain Old Java Objects) that are either annotated with@Path or have at least one method annotated with @Path or a request method designator such as @GET, @PUT, @POST, or @DELETE. Resource methods are methods of a resource class annotated with a request method designator. This section describes how to use Jersey to annotate Java objects to create RESTful web services.</p>
<p>I have to add @Path("/hello") to my class, and suddenly Jersey can find my resource class</p>
<p>Now the catalina.out file looks like:</p>
<pre><code>May 24, 2011 3:13:02 PM com.sun.jersey.api.core.PackagesResourceConfig init
INFO: Scanning for root resource and provider classes in the packages:
com.bi.nd.webservice
May 24, 2011 3:13:02 PM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
class com.bi.nd.webservice.TransactionResource
May 24, 2011 3:13:02 PM com.sun.jersey.api.core.ScanningResourceConfig init
INFO: No provider classes found.
May 24, 2011 3:13:02 PM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.7 05/20/2011 11:04 AM'
</code></pre>
<p>But the problem is far from over. I try to access the URL <code>http://localhost:8080/nd/hello</code> and I still get the 404 NOT FOUND. Is the Provider class NOT FOUND an important message?</p>
| 0 | 1,523 |
How to fillstyle with Images in canvas html5
|
<p>I am using this spin wheel </p>
<p><a href="http://tpstatic.com/_sotc/sites/default/files/1010/source/roulettewheel.html" rel="nofollow noreferrer">http://tpstatic.com/_sotc/sites/default/files/1010/source/roulettewheel.html</a></p>
<p>I want to change the background color to background images. I don't have a clue how to do it. If someone is kind enough to show me the path of adding images to canvas shapes /elements. I know it has something to do with fillStyle(). Here is the code:</p>
<pre><code><html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=windows-1252">
</head>
<body>
<input type="button" value="spin" onclick="spin();" style="float: left;">
<canvas id="wheelcanvas" width="600" height="600"></canvas>
<script type="application/javascript">
var colors = ["#B8D430", "#3AB745", "#029990", "#3501CB",
"#2E2C75", "#673A7E", "#CC0071", "#F80120",
"#F35B20", "#FB9A00", "#FFCC00", "#FEF200","#FEF200"];
var restaraunts = ["$10", "$20", "$30", "$40",
"$50", "$60", "$70", "$80",
"$90", "$100", "$120", "$150","HELLO"];
var startAngle = 0;
var arc = Math.PI / 6;
var spinTimeout = null;
var spinArcStart = 10;
var spinTime = 0;
var spinTimeTotal = 0;
var ctx;
function draw() {
drawRouletteWheel();
}
function drawRouletteWheel() {
var canvas = document.getElementById("wheelcanvas");
if (canvas.getContext) {
var outsideRadius = 200;
var textRadius = 160;
var insideRadius = 125;
ctx = canvas.getContext("2d");
ctx.clearRect(0,0,600,600);
ctx.strokeStyle = "green";
ctx.lineWidth = 1;
ctx.font = 'bold 14px sans-serif';
for(var i = 0; i < 14; i++) {
var angle = startAngle + i * arc;
ctx.fillStyle = colors[i];
ctx.beginPath();
ctx.arc(250, 250, outsideRadius, angle, angle + arc, false);
ctx.arc(250, 250, insideRadius, angle + arc, angle, true);
ctx.stroke();
ctx.fill();
ctx.save();
ctx.shadowOffsetX = -1;
ctx.shadowOffsetY = -1;
ctx.shadowBlur = 0;
ctx.shadowColor = "rgb(220,220,220)";
ctx.fillStyle = "black";
ctx.translate(250 + Math.cos(angle + arc / 2) * textRadius, 250 + Math.sin(angle + arc / 2) * textRadius);
ctx.rotate(angle + arc / 2 + Math.PI / 2);
var text = restaraunts[i];
ctx.fillText(text, -ctx.measureText(text).width /2, 2);
ctx.restore();
}
//Arrow
ctx.fillStyle = "green";
ctx.beginPath();
ctx.moveTo(250 - 4, 250 - (outsideRadius + 5));
ctx.lineTo(250 + 4, 250 - (outsideRadius + 5));
ctx.lineTo(250 + 4, 250 - (outsideRadius - 5));
ctx.lineTo(250 + 9, 250 - (outsideRadius - 5));
ctx.lineTo(250 + 0, 250 - (outsideRadius - 13));
ctx.lineTo(250 - 9, 250 - (outsideRadius - 5));
ctx.lineTo(250 - 4, 250 - (outsideRadius - 5));
ctx.lineTo(250 - 4, 250 - (outsideRadius + 5));
ctx.fill();
}
}
function spin() {
spinAngleStart = Math.random() * 10 + 10;
spinTime = 0;
spinTimeTotal = Math.random() * 3 + 4 * 1000;
rotateWheel();
}
function rotateWheel() {
spinTime += 30;
if(spinTime >= spinTimeTotal) {
stopRotateWheel();
return;
}
var spinAngle = spinAngleStart - easeOut(spinTime, 0, spinAngleStart, spinTimeTotal);
startAngle += (spinAngle * Math.PI / 180);
drawRouletteWheel();
spinTimeout = setTimeout('rotateWheel()', 30);
}
function stopRotateWheel() {
clearTimeout(spinTimeout);
var degrees = startAngle * 180 / Math.PI + 90;
var arcd = arc * 180 / Math.PI;
var index = Math.floor((360 - degrees % 360) / arcd);
ctx.save();
ctx.font = 'bold 30px sans-serif';
var text = restaraunts[index]
ctx.fillText(text, 250 - ctx.measureText(text).width / 2, 250 + 10);
ctx.restore();
}
function easeOut(t, b, c, d) {
var ts = (t/=d)*t;
var tc = ts*t;
return b+c*(tc + -3*ts + 3*t);
}
draw();
</script>
</body>
</html>
</code></pre>
<p>Here is the preview of an empty spin wheel. I want to put different images on each of them.<img src="https://i.stack.imgur.com/KlLRM.png" alt="Spin Wheel Image"></p>
| 0 | 1,694 |
FirebaseInstanceId: Token retrieval failed: SERVICE_NOT_AVAILABLE
|
<p>I'm making an app which can write to firebase database on button click.
The app is working on emulator but it's not working on my physical device.
The app was working fine last week but today started giving error.
Here's the main activity code:</p>
<pre><code>public class MainActivity extends AppCompatActivity {
private Firebase fled1;
Button on;
Button off;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
on= findViewById(R.id.on);
off= findViewById(R.id.off);
on.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DatabaseReference fled1 = FirebaseDatabase.getInstance().getReferenceFromUrl("https://testproject-tb.firebaseio.com/");
DatabaseReference fled1Child = fled1.child("Button1");
fled1Child.setValue("1");
}
});
off.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DatabaseReference fled1 = FirebaseDatabase.getInstance().getReferenceFromUrl("https://testproject-tb.firebaseio.com/");
DatabaseReference fled1Child = fled1.child("Button1");
fled1Child.setValue("0");
}
});
}
</code></pre>
<p>Here's my manifest file I have added all the permissions required: </p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lalitahuja.iotbutton">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name="com.example.lalitahuja.iotbutton.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
</code></pre>
<p>Here's the build Gradle file:</p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.lalitahuja.iotbutton"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-database:16.1.0'
implementation 'com.crashlytics.sdk.android:crashlytics:2.9.7'
implementation 'com.google.firebase:firebase-auth:16.2.0'
implementation 'com.firebase:firebase-client-android:2.5.2'
}
apply plugin: 'com.google.gms.google-services'
</code></pre>
<p>The error I'm getting:</p>
<p>E/FirebaseInstanceId: Token retrieval failed: SERVICE_NOT_AVAILABLE</p>
<p>Edit: I tried the solutions existing on internet but none of them is working.</p>
| 0 | 1,657 |
How can I build my C extensions with MinGW-w64 in Python?
|
<p>So I have a few Python C extensions I have previously built for and used in 32 bit Python running in Win7. I have now however switched to 64 bit Python, and I am having issues building the C extension with MinGW-w64.</p>
<p>I made the changes to distutils as per <a href="http://bugs.python.org/issue11723">this post</a>, but I am getting some weird errors suggesting something is wrong:</p>
<pre><code>$ python setup.py build
running build
running build_ext
building 'MyLib' extension
c:\MinGW64\bin\x86_64-w64-mingw32-gcc.exe -mdll -O -Wall -Ic:\Python27\lib\site-packages\numpy\core\include -Ic:\Python27\include -Ic:\Python27\PC -c MyLib.c -o build\temp.win-amd64-2.7\Release\mylib.o
MyLib.c: In function 'initMyLib':
MyLib.c:631:5: warning: implicit declaration of function 'Py_InitModule4_64' [-Wimplicit-function-declaration]
writing build\temp.win-amd64-2.7\Release\MyLib.def
c:\MinGW64\bin\x86_64-w64-mingw32-gcc.exe -shared -s build\temp.win-amd64-2.7\Release\mylib.o build\temp.win-amd64-2.7\Release\MyLib.def -Lc:\Python27\libs -Lc:\Python27\PCbuild\amd64 -lpython27 -o build\lib.win-amd64-2.7\MyLib.pyd
build\temp.win-amd64-2.7\Release\mylib.o:MyLib.c:(.text+0x13d): undefined reference to `__imp_PyExc_ValueError'
build\temp.win-amd64-2.7\Release\mylib.o:MyLib.c:(.text+0x1275): undefined reference to `__imp_PyExc_ValueError'
build\temp.win-amd64-2.7\Release\mylib.o:MyLib.c:(.text+0x1eef): undefined reference to `__imp_PyExc_ImportError'
build\temp.win-amd64-2.7\Release\mylib.o:MyLib.c:(.text+0x1f38): undefined reference to `__imp_PyExc_AttributeError'
build\temp.win-amd64-2.7\Release\mylib.o:MyLib.c:(.text+0x1f4d): undefined reference to `__imp_PyCObject_Type'
build\temp.win-amd64-2.7\Release\mylib.o:MyLib.c:(.text+0x1f61): undefined reference to `__imp_PyExc_RuntimeError'
build\temp.win-amd64-2.7\Release\mylib.o:MyLib.c:(.text+0x1fc7): undefined reference to `__imp_PyExc_RuntimeError'
build\temp.win-amd64-2.7\Release\mylib.o:MyLib.c:(.text+0x1ffe): undefined reference to `__imp_PyExc_RuntimeError'
build\temp.win-amd64-2.7\Release\mylib.o:MyLib.c:(.text+0x2042): undefined reference to `__imp_PyExc_RuntimeError'
build\temp.win-amd64-2.7\Release\mylib.o:MyLib.c:(.text+0x206c): undefined reference to `__imp_PyExc_RuntimeError'
build\temp.win-amd64-2.7\Release\mylib.o:MyLib.c:(.text+0x208a): more undefined references to `__imp_PyExc_RuntimeError' follow
build\temp.win-amd64-2.7\Release\mylib.o:MyLib.c:(.text+0x20a7): undefined reference to `__imp_PyExc_ImportError'
collect2.exe: error: ld returned 1 exit status
error: command 'x86_64-w64-mingw32-gcc' failed with exit status 1
</code></pre>
<p>I have googled around quite a bit to find information, but it's not easy to find a definite answer. Could someone shed some light on this? What further changes should I do to be able to successfully build C extensions for 64 bit Python in Win7?</p>
<p>EDIT:</p>
<p>After some helpful pointers in cgohlke's comments below I managed to generate <code>libpython27.a</code>. However after following the advice on <a href="https://groups.google.com/forum/?fromgroups#!topic/cython-users/r_0A5AHwiak">this post</a> (2nd to last) I still had a the <code>__imp_Py_InitModule4_64</code> error. After some serious Google-fu I managed to trip over <a href="http://deeplearning.net/software/theano/_sources/install.txt">this post</a> telling me to rename the <code>Py_InitModule4</code> line to <code>Py_InitModule4_64</code>. After that everything worked swimmingly.</p>
| 0 | 1,301 |
Modules are installed using pip on OSX but not found when importing
|
<p>I successfully install different modules using pip and they are shown in the </p>
<pre><code>pip list
</code></pre>
<p>such as:</p>
<pre><code>beautifulsoup4 (4.4.1)
requests (2.10.0)
Scrapy (1.1.0)
</code></pre>
<h3>From Terminal</h3>
<p>However, whenever I try to import it</p>
<p><code>import beautifulsoup4</code> / <code>import bs4</code> or <code>import Scrapy</code> or <code>import requests</code></p>
<p>the following error is shown:</p>
<pre><code>$ python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named requests
</code></pre>
<p><em>Update:</em> if I launch python when I am at the correct site-packages directory</p>
<pre><code>$ pwd
/usr/local/lib/python2.7/site-packages
$ python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
>>> import requests
>>> import bs4
>>> import scrapy
</code></pre>
<p>Then it works. This would solve the issue if writing directly on the Terminal. However, I have no clue about how to make it work inside a file.py, which will be the normal use.</p>
<p>As far as I know, I only have Python2.7 installed.</p>
<h3>From file.py</h3>
<p>If I have a file.py saved in some local folder. This contains, for instance</p>
<pre><code>import requests
from bs4 import BeautifulSoup
</code></pre>
<p>when I try</p>
<pre><code>python file.py
</code></pre>
<p>I get the same error.</p>
<h1>Approach</h1>
<p>Same happens with any other module from the list.
I would think pip is installing them in a directory that Python is not reading, but as per what I read, it is the correct one.</p>
<p>They are all installed here:</p>
<pre><code>/usr/local/lib/python2.7/site-packages
</code></pre>
<p>Output requested by Padraic Cunningham:</p>
<pre><code>$ which -a pip
/usr/local/bin/pip
$ which -a python
/usr/bin/python
/usr/local/bin/python
</code></pre>
<p>Output requested by leovp:</p>
<pre><code>$ pip -V
pip 8.1.2 from /usr/local/lib/python2.7/site-packages (python 2.7)
</code></pre>
<h3>Threads already checked</h3>
<p>I have checked the following threads, but unfortunately they did not help me to solve the issue:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/33899996/installing-pyside-using-pip-nmake-not-found">installing pyside using PIP - nmake not found</a></li>
<li><a href="https://stackoverflow.com/questions/10569846/pip-installs-but-module-is-not-found">PIp installs but module is not found</a> ==> might have provided the right answer, but the links given do not work anymore</li>
<li><a href="https://stackoverflow.com/questions/28802358/google-protobuf-installed-but-module-not-found">google.protobuf installed, but module not found</a></li>
<li><a href="https://stackoverflow.com/questions/15052206/python-pip-install-module-is-not-found-how-to-link-python-to-pip-location">Python pip install module is not found. How to link python to pip location?</a></li>
</ul>
<p>Any ideas of what the problem is?</p>
| 0 | 1,189 |
reading a .bmp file in c++
|
<p>I'm trying to load a bmp file for reusing it in opengl.
I've found some code via google on how to load a bmp file.
I took this code and put in a class Bitmap in my project.
The class is far away from being finished but already the reading of the file headers goes wrong. After reading the bytes for INFOHEADER and FILEHEADER there aren't the right values in my structs.
Some ideas?</p>
<pre><code>//
// Bitmap.h
//
#ifndef LaserMaze_Bitmap_h
#define LaserMaze_Bitmap_h
typedef struct /**** BMP file header structure ****/
{
unsigned short bfType; /* Magic number for file */
unsigned int bfSize; /* Size of file */
unsigned short bfReserved1; /* Reserved */
unsigned short bfReserved2; /* ... */
unsigned int bfOffBits; /* Offset to bitmap data */
} BITMAPFILEHEADER;
# define BF_TYPE 0x4D42 /* "MB" */
typedef struct /**** BMP file info structure ****/
{
unsigned int biSize; /* Size of info header */
int biWidth; /* Width of image */
int biHeight; /* Height of image */
unsigned short biPlanes; /* Number of color planes */
unsigned short biBitCount; /* Number of bits per pixel */
unsigned int biCompression; /* Type of compression to use */
unsigned int biSizeImage; /* Size of image data */
int biXPelsPerMeter; /* X pixels per meter */
int biYPelsPerMeter; /* Y pixels per meter */
unsigned int biClrUsed; /* Number of colors used */
unsigned int biClrImportant; /* Number of important colors */
} BITMAPINFOHEADER;
/*
* Constants for the biCompression field...
*/
# define BI_RGB 0 /* No compression - straight BGR data */
# define BI_RLE8 1 /* 8-bit run-length compression */
# define BI_RLE4 2 /* 4-bit run-length compression */
# define BI_BITFIELDS 3 /* RGB bitmap with RGB masks */
typedef struct /**** Colormap entry structure ****/
{
unsigned char rgbBlue; /* Blue value */
unsigned char rgbGreen; /* Green value */
unsigned char rgbRed; /* Red value */
unsigned char rgbReserved; /* Reserved */
} RGBQUAD;
class Bitmap {
public:
Bitmap(const char* filename);
~Bitmap();
RGBQUAD* pixels;
BITMAPFILEHEADER fh;
BITMAPINFOHEADER ih;
private:
};
#endif
</code></pre>
<p>the cpp</p>
<pre><code>// Bitmap.cpp
//
#include <iostream>
#include <stdio.h>
#include "Bitmap.h"
Bitmap::Bitmap(const char* filename) {
FILE* file;
file = fopen(filename, "rb");
std::cout << sizeof(BITMAPFILEHEADER) << std::endl;
if(file != NULL) { // file opened
BITMAPFILEHEADER h;
size_t x = fread(&h, sizeof(BITMAPFILEHEADER), 1, file); //reading the FILEHEADER
std::cout << x;
fread(&this->ih, sizeof(BITMAPINFOHEADER), 1, file);
fclose(file);
}
}
</code></pre>
| 0 | 1,337 |
LernaJS Typescript cannot find module
|
<p>I'm trying to use LernaJS with typescript and I have some problems. When I try to run my package-1 which has package-2 as dependency I get the error:</p>
<pre>
module.js:549
throw err;
^
Error: Cannot find module 'package-2'
at Function.Module._resolveFilename (module.js:547:15)
at Function.Module._load (module.js:474:25)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object. (/home/gabriel/Documentos/projetos/nodejs/lerna-t2/packages/package-1/dist/index.js:3:19)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
</pre>
<p>I've followed the following steps:</p>
<ol>
<li>I've created a directory and ran the command 'lerna init'</li>
<li>I've created 2 folders inside (package-1, package-2) 'packages' folder</li>
</ol>
<pre>
.
├── lerna.json
├── node_modules
├── package.json
├── package-lock.json
└── packages
├── package-1
└── package-2
</pre>
<ol start="3">
<li>I've ran 'npm init' in both (package-1, package-2)</li>
<li>I've created a basic 'tsconfig.json' in both packages:</li>
</ol>
<pre>
{
"compilerOptions": {
"outDir": "dist",
"target": "es5",
"module": "commonjs"
}
}
</pre>
<ol start="5">
<li>I've ran 'lerna bootstrap' in the root folder</li>
<li>I've use 'lerna add package-2 --scope=package-1'</li>
<li>I've ran also 'npm i' in root folder, package-1 and package-2</li>
<li>I've ran 'tsc -w' in package-1 and package-2 and 'node dist/index.js' in package-1</li>
</ol>
<p><strong>FILE TREE</strong></p>
<p>My 'package-1' file tree:</p>
<pre>
.
├── dist
│ └── index.js
├── index.ts
├── node_modules
│ ├── package-2 -> ../../package-2
│ └── typescript
├── package.json
├── package-lock.json
└── tsconfig.json
</pre>
<p>My 'package-2' file tree:</p>
<pre>
.
├── dist
│ ├── index.js
│ └── lib
│ └── teste.js
├── index.ts
├── lib
│ └── teste.ts
├── package.json
├── package-lock.json
└── tsconfig.json
</pre>
<p><strong>CODE</strong></p>
<p><strong>package-1</strong>:</p>
<ul>
<li>index.ts:</li>
</ul>
<pre>
import { Teste } from 'package-2'
new Teste().printHello()
</pre>
<p><strong>package-2</strong>:</p>
<ul>
<li>lib/teste.ts:</li>
</ul>
<pre>
export class Teste {
printHello() {
console.log('Hello!')
}
}
</pre>
<ul>
<li>index.ts:</li>
</ul>
<pre>
export { Teste } from './lib/teste'
</pre>
| 0 | 1,307 |
Why do my Twitter Bootstrap form fields overflow their well using fluid container?
|
<p>UPDATE: Demo of problem here: <a href="http://jsfiddle.net/fdB5Q/embedded/result/" rel="nofollow noreferrer">http://jsfiddle.net/fdB5Q/embedded/result/</a></p>
<p>From about 767px to 998px, the form fields are wider than the containing well.</p>
<p>Smaller than 767px and the entire form area shifts to a new line. The page rendered when the browser window is about 200px wide displays perfectly. The form fields shrink as you would expect.</p>
<p>For a visual, look at this very similar question:
<a href="https://stackoverflow.com/questions/11706019/twitter-bootstrap-css-static-fluid-form-positioning">Twitter Bootstrap CSS static-fluid form positioning</a></p>
<p>Here's everything in the Head:</p>
<pre><code><link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" />
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</code></pre>
<p>Here's everything in the Body:</p>
<pre><code><div class="container-fluid">
<div class="row-fluid">
<div class="span8">
<p>Some Content.</p>
</div>
<div class="span4">
<div class="well">
<div class="control-group">
<label class="control-label" for="name">Your Name</label>
<div class="controls">
<input type="text" class="input-xlarge" name="name" id="name" maxlength="100" />
</div>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p><strong>I think I am misunderstanding some part of the framework. Should I not be using a fluid container? What am I doing wrong?</strong> I could throw together something to fix this, but I think the problem may be that I am doing something wrong big picture.</p>
<p>I tried changing my spans to 7 and 5 and still had the same error. I tried 6 and 6, but at that point the page started to look ridiculous. The rest of the answers didn't make sense to me.</p>
<p>I changed the input class to large instead of xlarge. It still had a width range where it overflowed, and I really would like wider form fields if there is room on the display.</p>
<p>I want to avoid the horizontal scroll bar, and I want the page text to be the same size in landscape or portait mode on my smartphone. </p>
<p>UPDATE: Pictures</p>
<p><strong>My problem page:</strong></p>
<p><img src="https://i.stack.imgur.com/isXAj.png" alt="problem page"></p>
<p><strong>Simplified version:</strong></p>
<p><img src="https://i.stack.imgur.com/GdhGp.png" alt="simple version"></p>
<p><strong>Simplified version at 200 px browser width:</strong></p>
<p><img src="https://i.stack.imgur.com/csxCL.png" alt="simple version at 200px width"></p>
| 0 | 1,048 |
How to set Container height fit to screen
|
<p><strong>Note</strong>: <em>This widget is child of another Column</em></p>
<p><br>
I need to use ListView.builder inside Column but to use it inside Column i need to wrap it with Container not only that i need to set the height,<br>here i used MediaQuery.of(context).size.height and it works,<Br> but with one issue,it is showing that <em>A RenderFlex overflowed by 226 pixels on the bottom.</em> <br>How to avoid it ?</p>
<pre><code> Column(
children: <Widget>[
getTopWidget(),
Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: ListView.builder(
itemCount: shapShot.data.length,
itemBuilder: (context,index){
return EventCard(
title: shapShot.data[index].title,
details: shapShot.data[index].details,
imageUrl: shapShot.data[index].imageUrl,
);
}),
),
],
);
</code></pre>
<p><br></p>
<p>I tried with Flexible and it not worked
<br>
When in try with <code>Expanded</code> it makes below error
<br><a href="https://i.stack.imgur.com/8oLGu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8oLGu.png" alt="enter image description here"></a>
<br>
App screenshot<br><a href="https://i.stack.imgur.com/ftaiS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ftaiS.png" alt="enter image description here"></a>
<br></p>
<blockquote>
<p>RenderBox was not laid out: RenderRepaintBoundary#76ded NEEDS-LAYOUT
NEEDS-PAINT 'package:flutter/src/rendering/box.dart': Failed
assertion: line 1695 pos 12: 'hasSize'
<br><br><br></p>
</blockquote>
<p>The parent class code<br><br></p>
<pre><code>import 'dart:collection';
import 'package:devaayanam/DevaayanamApp/devaayanam_app_communities.dart';
import 'package:devaayanam/DevaayanamApp/devaayanam_app_home_page.dart';
import 'package:devaayanam/DevaayanamApp/devaayanam_app_temples_listing.dart';
import 'package:devaayanam/DevaayanamApp/devaayanam_app_videos.dart';
import 'package:flutter/material.dart';
import '../GradientAppBar.dart';
import 'temples_listing_with_tab_mode.dart';
class DevaayanamAppFramePage extends StatefulWidget {
DevaayanamAppFramePage({Key key}) : super(key: key);
@override
_DevaayanamAppFramePageState createState() => _DevaayanamAppFramePageState();
}
class _DevaayanamAppFramePageState extends State<DevaayanamAppFramePage> {
int _selectedIndex = 0;
ListQueue<Widget> page1,page2,page3,page4;
_DevaayanamAppFramePageState(){
page1=ListQueue();
page1.add(DevaayanamAppHomePage());
page2=ListQueue();
page2.add(DevaayanamAppTemplesListing());
page3=ListQueue();
page3.add(DevaayanamAppCommunities());
page4=ListQueue();
page4.add(DevaayanamAppVideos());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: null,
bottomNavigationBar: BottomNavigationBar(
onTap: _onItemTapped,
unselectedItemColor: Colors.grey,
selectedItemColor: Colors.grey,
currentIndex: _selectedIndex,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(
Icons.home,
color: Colors.grey,
),
title: Text(
"Home",
style: TextStyle(color: Colors.grey),
)),
BottomNavigationBarItem(
icon: Icon(Icons.assessment),
title: Text(
"Temples",
style: TextStyle(color: Colors.grey),
)),
BottomNavigationBarItem(
icon: Icon(Icons.comment),
title: Text(
"Communities",
style: TextStyle(color: Colors.grey),
)),
BottomNavigationBarItem(
icon: Icon(Icons.play_arrow),
title: Text(
"Videos",
style: TextStyle(color: Colors.grey),
)),
]),
body: Container(
child: Column(
children: <Widget>[GradientAppBar(),getBody()],
),
),
);
}
Widget getBody(){
switch(_selectedIndex){
case 0:
return page1.last;
case 1:
return page2.last;
case 2:
return page3.last;
case 3:
return page4.last;
}
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
}
</code></pre>
<p><br><br></p>
| 0 | 2,369 |
installing mongodb in a docker container
|
<p>I am trying to create a docker image for mongodb. I am followed the installation instructions from the official mongodb installation to the letter without success. I have tried every single blog and installation instruction out there but without any success. Any help will be greatly appreciated. </p>
<p>My dockerfile contents :</p>
<pre><code>FROM ubuntu:16.04
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6
RUN echo "deb [ arch=amd64 ] http://repo.mongodb.org/apt/ubuntu/ xenial/mongodb-org/3.4 multiverse" | tee /etc/apt/sources.list.d/mongodb-3.4.list
RUN apt-get update && apt-get install -y mongodb-org
RUN mkdir -p /data/db
RUN chown -R mongodb:mongodb /data/db
ADD mongodb.conf /etc/mongodb.conf
ADD mongodb.pem /etc/ssl/certs/mongodb.pem
VOLUME ["/data/db"]
EXPOSE 27017
ENTRYPOINT ["/usr/bin/mongod", "--config", "/etc/mongodb.conf"]
</code></pre>
<p>I am using the follwing command :</p>
<pre><code>sudo docker image build -t mongodb .
</code></pre>
<p>Everytime I am trying to build the image, I get the following:</p>
<pre><code>Sending build context to Docker daemon 7.68kB
Step 1/11 : FROM ubuntu:16.04
---> 14f60031763d
Step 2/11 : RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6
---> Using cache
---> 97a851663e60
Step 3/11 : RUN echo "deb [ arch=amd64 ] http://repo.mongodb.org/apt/ubuntu/ xenial/mongodb-org/3.4 multiverse" | tee /etc/apt/sources.list.d/mongodb-3.4.list
---> Using cache
---> 122a2fad0021
Step 4/11 : RUN apt-get update && apt-get install -y mongodb-org
---> Running in 014e7918e156
Get:1 http://security.ubuntu.com/ubuntu xenial-security InRelease [102 kB]
Ign:2 http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 InRelease
Get:3 http://archive.ubuntu.com/ubuntu xenial InRelease [247 kB]
Get:4 http://archive.ubuntu.com/ubuntu xenial-updates InRelease [102 kB]
Get:5 http://archive.ubuntu.com/ubuntu xenial-backports InRelease [102 kB]
Get:6 http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 Release [3457 B]
Get:7 http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 Release.gpg [801 B]
Get:8 http://security.ubuntu.com/ubuntu xenial-security/universe Sources [42.0 kB]
Get:9 http://security.ubuntu.com/ubuntu xenial-security/main amd64 Packages [394 kB]
Get:10 http://security.ubuntu.com/ubuntu xenial-security/restricted amd64 Packages [12.8 kB]
Get:11 http://security.ubuntu.com/ubuntu xenial-security/universe amd64 Packages [184 kB]
Get:12 http://security.ubuntu.com/ubuntu xenial-security/multiverse amd64 Packages [2931 B]
Get:13 http://archive.ubuntu.com/ubuntu xenial/universe Sources [9802 kB]
Get:14 http://alert.scansafe.net/alert/process?a=-3-BW4R_eLtf_R7PUTnlOeb6kHjw5kMPDH4n_j9vuji99G7a0CHJtXpeYpzGHZPC0wRr52uECxiceRo23F5y5nJqQ&b=iDw6Hli7TPC7hodjxRcdBj9i1UevoPI4aXCTkM2htEe16EENN3K7sUkicBLWMmbvQJHy5RccSqbLlHU4Q23W8w7vzekV399jAw6NbyJsJBJPm_U3VdYSosJyHFldLABeOaw16L56ass0uQ-KDLgyWadENbyoiMwzO-1nwE6QYwf1NcLI1073TBf9mObvKXGE7lL2-OpA1MA6dI2cdh6AETyP3g0OipJUm4fag2-7TI5j_BImQOsvvEVlzZ7ilSFaUVOlMbWBWuuU822y_f0ph82C3dG_kBenckmPWso5ln9ShKoiCmjbcSZjT76_j3Hwh3nSYYv1AqX8Kj8gFD4k1MI2Li7WNMs9rnq4vUa9eeaN_ivffMClQHK6I88vPaR4FQr61U5ecOwl0KmVyhP3FLDF-4KpOGg3Kf7kVRCnLpQZwXnsrrTt3enSpjn66IzlCgG3PmNrVhdqOTBQFh5PfWtgdGG68Ir6hZIBt170nqGSMhgFmlTMTMbO5EGkA-uyPz8worv7RSc&blockedUrl=http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4/multiverse amd64 Packages [5870 B]
Err:14 http://alert.scansafe.net/alert/process?a=-3-BW4R_eLtf_R7PUTnlOeb6kHjw5kMPDH4n_j9vuji99G7a0CHJtXpeYpzGHZPC0wRr52uECxiceRo23F5y5nJqQ&b=iDw6Hli7TPC7hodjxRcdBj9i1UevoPI4aXCTkM2htEe16EENN3K7sUkicBLWMmbvQJHy5RccSqbLlHU4Q23W8w7vzekV399jAw6NbyJsJBJPm_U3VdYSosJyHFldLABeOaw16L56ass0uQ-KDLgyWadENbyoiMwzO-1nwE6QYwf1NcLI1073TBf9mObvKXGE7lL2-OpA1MA6dI2cdh6AETyP3g0OipJUm4fag2-7TI5j_BImQOsvvEVlzZ7ilSFaUVOlMbWBWuuU822y_f0ph82C3dG_kBenckmPWso5ln9ShKoiCmjbcSZjT76_j3Hwh3nSYYv1AqX8Kj8gFD4k1MI2Li7WNMs9rnq4vUa9eeaN_ivffMClQHK6I88vPaR4FQr61U5ecOwl0KmVyhP3FLDF-4KpOGg3Kf7kVRCnLpQZwXnsrrTt3enSpjn66IzlCgG3PmNrVhdqOTBQFh5PfWtgdGG68Ir6hZIBt170nqGSMhgFmlTMTMbO5EGkA-uyPz8worv7RSc&blockedUrl=http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4/multiverse amd64 Packages
Hash Sum mismatch
Get:15 http://archive.ubuntu.com/ubuntu xenial/main amd64 Packages [1558 kB]
Get:16 http://archive.ubuntu.com/ubuntu xenial/restricted amd64 Packages [14.1 kB]
Get:17 http://archive.ubuntu.com/ubuntu xenial/universe amd64 Packages [9827 kB]
Get:18 http://archive.ubuntu.com/ubuntu xenial/multiverse amd64 Packages [176 kB]
Get:19 http://archive.ubuntu.com/ubuntu xenial-updates/universe Sources [208 kB]
Get:20 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 Packages [756 kB]
Get:21 http://archive.ubuntu.com/ubuntu xenial-updates/restricted amd64 Packages [13.3 kB]
Get:22 http://archive.ubuntu.com/ubuntu xenial-updates/universe amd64 Packages [645 kB]
Get:23 http://archive.ubuntu.com/ubuntu xenial-updates/multiverse amd64 Packages [17.5 kB]
Get:24 http://archive.ubuntu.com/ubuntu xenial-backports/main amd64 Packages [4930 B]
Get:25 http://archive.ubuntu.com/ubuntu xenial-backports/universe amd64 Packages [6237 B]
Fetched 24.2 MB in 7s (3158 kB/s)
Reading package lists...
E: Failed to fetch http://alert.scansafe.net/alert/process?a=-3-BW4R_eLtf_R7PUTnlOeb6kHjw5kMPDH4n_j9vuji99G7a0CHJtXpeYpzGHZPC0wRr52uECxiceRo23F5y5nJqQ&b=iDw6Hli7TPC7hodjxRcdBj9i1UevoPI4aXCTkM2htEe16EENN3K7sUkicBLWMmbvQJHy5RccSqbLlHU4Q23W8w7vzekV399jAw6NbyJsJBJPm_U3VdYSosJyHFldLABeOaw16L56ass0uQ-KDLgyWadENbyoiMwzO-1nwE6QYwf1NcLI1073TBf9mObvKXGE7lL2-OpA1MA6dI2cdh6AETyP3g0OipJUm4fag2-7TI5j_BImQOsvvEVlzZ7ilSFaUVOlMbWBWuuU822y_f0ph82C3dG_kBenckmPWso5ln9ShKoiCmjbcSZjT76_j3Hwh3nSYYv1AqX8Kj8gFD4k1MI2Li7WNMs9rnq4vUa9eeaN_ivffMClQHK6I88vPaR4FQr61U5ecOwl0KmVyhP3FLDF-4KpOGg3Kf7kVRCnLpQZwXnsrrTt3enSpjn66IzlCgG3PmNrVhdqOTBQFh5PfWtgdGG68Ir6hZIBt170nqGSMhgFmlTMTMbO5EGkA-uyPz8worv7RSc&blockedUrl=http://repo.mongodb.org/apt/ubuntu/dists/xenial/mongodb-org/3.4/multiverse/binary-amd64/Packages.gz Hash Sum mismatch
E: Some index files failed to download. They have been ignored, or old ones used instead.
The command '/bin/sh -c apt-get update && apt-get install -y mongodb-org' returned a non-zero code: 100
</code></pre>
| 0 | 3,069 |
Excel VBA: Move items from one array to another array
|
<p>I'm trying to speed up an application that is designed to assign human resources to locations, using listboxes that are bound to ranges. That works quite well - the ugly part is moving items from one data range to one or more ranges using find, copy & paste.</p>
<p>I could gain great speed by using a function to print arrays to ranges when I retrieve the data from webservices, but I couldn't figure out how to replace the find/cut/paste logic yet.</p>
<p>I have now updated my previous post to include my latest tries. In a way that now works as intended, but it surely does not look smart:</p>
<h3>Updated sample</h3>
<p>The ranges look like this (data in Col B-E is not relevant, A contains the key).
Day0_lbUsers is A1:E5, Day1_lbUsers is A28:E30.</p>
<pre><code> A B C D E
1 15 Foo Bar Bas Nono
2 18 Foo Bar Bas Nono
3 19 Foo Bar Bas Nono
4 196 Foo Bar Bas Nono
5 33 Foo Bar Bas Nono
...
28 32 Foo Bar Bas Nono
29 46 Foo Bar Bas Nono
30 52 Foo Bar Bas Nono
</code></pre>
<p>In this example, I want to move the row with the key 18 from Day0_lbUsers to Day1_lbUsers.
In the sample, I have hardcoded the source and not written back to the ranges, but that's not the hard part. I'm rather interested whether there is a better way to transfer the arrays contents.</p>
<pre><code>Sub TestRemoveFromArray()
Dim vSourceArray() As Variant ' source
Dim vNewSourceArray() As Variant ' source, one key removed
Dim vTargetArray() As Variant ' target
Dim vNewTargetArray() As Variant ' target, one item added
Dim rowSearch As Long, row As Long, col As Long, search As Long, blnFound As Boolean
search = 18
vSourceArray = shData.Names("Day0_lbUsers").RefersToRange.Value2 ' 27 rows, 5 columns, key in col 1
' loop source to find the row that contains the search key
For rowSearch = LBound(vSourceArray) To UBound(vSourceArray)
' look into col 1 for the key
If vSourceArray(rowSearch, 1) = search Then
blnFound = True
Exit For
End If
Next rowSearch
If Not blnFound Then
Exit Sub
End If
' we've found the row, so let's get the target
vTargetArray = shData.Names("Day1_lbUsers").RefersToRange.Value2
' a1 needs to be 1 short of a, b1 must be b +1
ReDim vNewSourceArray(LBound(vSourceArray) To UBound(vSourceArray) - 1, 1 To 5)
ReDim vNewTargetArray(LBound(vTargetArray) To UBound(vTargetArray) + 1, 1 To 5)
' copy original target to new target
For row = LBound(vTargetArray) To UBound(vTargetArray)
For col = LBound(vTargetArray, 2) To UBound(vTargetArray, 2)
vNewTargetArray(row, col) = vTargetArray(row, col)
Next col
Next row
' reset blnFound
blnFound = False
For row = LBound(vSourceArray) To UBound(vSourceArray)
If row = rowSearch Then
For col = LBound(vSourceArray, 2) To UBound(vSourceArray, 2)
vNewTargetArray(UBound(vNewTargetArray), col) = vSourceArray(row, col)
Next col
blnFound = True
Else
For col = LBound(vSourceArray, 2) To UBound(vSourceArray, 2)
' if blnFound was found before, write to the key -1
vNewSourceArray(IIf(blnFound, row - 1, row), col) = vSourceArray(row, col)
Next col
End If
NextRow:
Next row
'assign new arrays (return later)
vSourceArray = vNewSourceArray
Erase vNewSourceArray
vTargetArray = vNewTargetArray
Erase vNewTargetArray
End Sub
</code></pre>
<h3>original post, out-of-date</h3>
<p>All the data ranges have the same number of columns (5) and are named. This is what I have so far; at some point I had to stop programming and use pseudo-code instead to illustrate. The source and target arrays are created with e.g. </p>
<pre><code>vSourceArray = shData.Names("Day0_A").RefersToRange.Value2 ' (1 to 27, 1 to 5)
Private Function MoveUserId(ByRef vSourceArray() As Variant, ByRef vTargetArray() As Variant, lngUserId As Long) As Boolean
Dim lSearchKey As Long, blnFound As Boolean, col As Long
Dim vTempArray() As Variant, vRow() As Variant
For lSearchKey = LBound(vSourceArray) To UBound(vSourceArray)
If vSourceArray(lSearchKey, 1) = lngUserId Then
blnFound = True
Exit For
End If
Next lSearchKey
If blnFound = False Then
MoveUserId = False
Exit Function
End If
' extract the row found
ReDim vRow(1 To 1) As Variant
vRow(1) = Application.WorksheetFunction.index(vSourceArray, lSearchKey)
' now, add an item to targetarray and populate using a function from http://www.cpearson.com
vTargetArray = CombineTwoDArrays(vTargetArray, vRow) ' does not work
' now delete the key in source array
' help!
End Function
</code></pre>
<p>Apart from the search function, this does not really work. The first thing would be to extract a row and copy it to a new, re-dimensioned target array. Easiest would be to redim the target to elements + 1; and then do something like (pseudo-code) pushing it to the end:</p>
<pre><code>vTargetArray(addedIndex) = vSourceArray(searchIndex)
</code></pre>
<p>The second thing which does not appear to be easy is deleting a key, but I haven't investigates web resources that much yet.</p>
<p>I would very much appreciate if you could show me the light.
Thanks in advance,
Stefan</p>
| 0 | 2,141 |
How to solve java.lang.IllegalArgumentException: Width (-1) and height (-1) cannot be <= 0?
|
<p>I've been spending the last hours trying to solve the stack trace below. With major research on here SO and also through Google, I understand the exception can mean several things:</p>
<ul>
<li><p>the program can't find the requested images with the provided path;</p></li>
<li><p>the images are being rendered <strong>after</strong> the width and the height are generated, reason why it equals 0...</p></li>
</ul>
<p>Am I missing something? I can't figure out how to solve this... </p>
<p>Stack</p>
<blockquote>
<p>Exception in thread "main" java.lang.IllegalArgumentException: Width
(-1) and height (-1) cannot be <= 0 at
java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1016)
at java.awt.image.BufferedImage.(BufferedImage.java:331) at
tp6.Interface.toBufferedImage(Interface.java:157) at
tp6.Interface.(Interface.java:36) at
tp6.Interface.main(Interface.java:171)</p>
</blockquote>
<p>tp6.Interface.toBufferedImage(Interface.java:157):</p>
<pre><code>public BufferedImage toBufferedImage(Image image) {
if( image instanceof BufferedImage ) {
return( (BufferedImage)image );
} else {
image = new ImageIcon(image).getImage();
BufferedImage bufferedImage = new BufferedImage(
image.getWidth(null),
image.getHeight(null),
BufferedImage.TYPE_INT_RGB );
Graphics g = bufferedImage.createGraphics();
g.drawImage(image,0,0,null);
g.dispose();
return( bufferedImage );
}
}
</code></pre>
<p>tp6.Interface.(Interface.java:36)</p>
<pre><code>//IMAGE JPANEL
Image map=new ImageIcon("images/main.gif").getImage();
Image digi=new ImageIcon("images/digits.gif").getImage();
BufferedImage mapmodifiable= toBufferedImage(map);
BufferedImage digits= toBufferedImage(digi);
</code></pre>
<p>tp6.Interface.main(Interface.java:171)</p>
<pre><code>public static void main(String[] args)
{
Window windowintro = new Window( 440, 400, 1);
//INTERFACE GRAPHIC
Interface graphic=new Interface();
graphic.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
}
</code></pre>
| 0 | 1,117 |
Can't install jdk on Fedora with yum nor with rpm
|
<p>Help! I can't figure out how to install a jdk!</p>
<pre><code>[/usr/lib/jvm]$ su -c "yum install java-1.7.0-openjdk-devel"
Loaded plugins: langpacks, presto, refresh-packagekit
No package java-1.7.0-openjdk-devel available.
Error: Nothing to do
[/usr/lib/jvm]$ su -c "yum install java-1.7.0-openjdk"
Loaded plugins: langpacks, presto, refresh-packagekit
No package java-1.7.0-openjdk available.
Error: Nothing to do
[/usr/lib/jvm]$ su -c "yum install java-1.6.0-openjdk-devel"
Loaded plugins: langpacks, presto, refresh-packagekit
No package java-1.6.0-openjdk-devel available.
Error: Nothing to do
[/usr/lib/jvm]$ su -c "yum install java-1.6.0-openjdk"
Loaded plugins: langpacks, presto, refresh-packagekit
No package java-1.6.0-openjdk available.
Error: Nothing to do
</code></pre>
<p>Here I've manually downloaded some rpm's, the last one from oracle's website:</p>
<pre><code>[~]$ rpm -ivh java-1.7.0-openjdk-devel-1.7.0.19-2.3.9.3.fc20.x86_64.rpm
error: Failed dependencies:
java-1.7.0-openjdk = 1:1.7.0.19-2.3.9.3.fc20 is needed by java-1.7.0-openjdk-devel-1:1.7.0.19-2.3.9.3.fc20.x86_64
[~]$ sudo rpm -ivh java-1.7.0-openjdk-1.7.0.19-2.3.9.3.fc20.x86_64.rpm
Preparing... ################################# [100%]
file /usr/lib/jvm-exports/jre-1.7.0-openjdk.x86_64 from install of java-1.7.0-openjdk-1:1.7.0.19-2.3.9.3.fc20.x86_64 conflicts with file from package java-1.7.0-openjdk-1:1.7.0.9-2.3.7.0.fc18.x86_64
file /usr/lib/jvm/jre-1.7.0-openjdk.x86_64 from install of java-1.7.0-openjdk-1:1.7.0.19-2.3.9.3.fc20.x86_64 conflicts with file from package java-1.7.0-openjdk-1:1.7.0.9-2.3.7.0.fc18.x86_64
[~]$ sudo rpm -ivh jdk-7u21-linux-x64.rpm
Preparing... ################################# [100%]
file /etc/init.d/jexec from install of jdk-2000:1.7.0_21-fcs.x86_64 conflicts with file from package jdk-2000:1.6.0_38-fcs.x86_64
</code></pre>
<h2>Debug</h2>
<p>Here's some debug information:</p>
<pre><code>[/usr/lib/jvm]$ yum search jdk
Loaded plugins: langpacks, presto, refresh-packagekit
=========================================================== N/S Matched: jdk ============================================================
java-1.7.0-openjdk-javadoc.noarch : OpenJDK API Documentation
jdk.x86_64 : Java(TM) Platform Standard Edition Development Kit
ldapjdk.noarch : The Mozilla LDAP Java SDK
Name and summary matches only, use "search all" for everything.
</code></pre>
<p>.</p>
<pre><code>[/usr/lib/jvm]$ yum list java*
Loaded plugins: langpacks, presto, refresh-packagekit
Installed Packages
java-1.5.0-gcj.x86_64
</code></pre>
<p>.</p>
<pre><code>[/usr/lib/jvm]$ cat /etc/fedora-release
Fedora release 18 (Spherical Cow)
</code></pre>
<h2>Requirements</h2>
<p>I <em>must</em> have "<strong>jni.h</strong>", "<strong>libjava.so</strong>", "<strong>libhpi.so</strong>", "<strong>lipverify.so</strong>" and "<strong>libjvm.so</strong>" included.</p>
<p>So far I've found out that these DO NOT have what I need:</p>
<ul>
<li>Undesired Versions (for sure):
<ul>
<li>jdk1.7.0_06 <-- <em>I'm surprised about this one, but it doesn't have libjvm nor libhpi</em></li>
<li>java-1.7.0 </li>
<li>java-openjdk </li>
<li>java-1.7.0-openjdk-1.7.0.9.x86_64</li>
<li>java-1.5.0-gcj-4.4</li>
<li>java-1.6.0-openjdk</li>
<li>java-1.7.0-openjdk.x86_64</li>
<li>jre-1.5.0-gcj</li>
<li>jre-1.7.0-openjdk.x86_64</li>
<li>jre-openjdk </li>
<li>jre-1.7.0</li>
<li>jre-7u11-linux-x64.rpm java-1.5.0-gcj-1.5.0.0</li>
<li>jre-1.5.0</li>
<li>jre1.7.0_11</li>
<li>jre-gcj</li>
</ul></li>
</ul>
<p>And these do:</p>
<ul>
<li>Desired Versions (that I know of, there could be more):
<ul>
<li><strong>jdk1.6.0_34-x86</li>
<li>jdk1.5.0_22-x86</li>
<li>java-6-openjdk</strong></li>
</ul></li>
</ul>
<p>Can someone help me install jdk1.6 or java-6-openjdk please?</p>
| 0 | 1,839 |
javax.net.ssl.SSLPeerUnverifiedException: No peer certificate while trying to connect using https with .bks keystore
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/5594189/javax-net-ssl-sslexception-not-trusted-server-certificate">javax.net.ssl.SSLException: Not trusted server certificate</a> </p>
</blockquote>
<p>I am trying to connect to server using "https" scheme with .bks keystore but i am unable to connect due to this issue.</p>
<p>Can any one tell me what's the reason for this and how to solve this.</p>
<p>Here is my code</p>
<pre><code>public String httpRestGetCallwithCertificate(String url, String payLoad) {
String result = null;
DefaultHttpClient httpClient = null;
KeyStore trustStore = null;
try {
httpClient = new DefaultHttpClient(getHttpParams());
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
HttpHost targetHost = new HttpHost("hostname","portno","https");
httpClient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username","password"));
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream instream = mContext.getResources().openRawResource(R.raw.truststore);
try {
trustStore.load(instream, "password".toCharArray());
} finally {
try { instream.close(); } catch (Exception ignore) {}
}
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
Scheme sch = new Scheme("https", socketFactory, 443);
registry.register(sch);
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
httpClient.getConnectionManager().getSchemeRegistry().register(sch);
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpClient.execute(httpget);
if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return "success"
}
} catch (UnsupportedEncodingException exception) {
exception.printStackTrace();
} catch (ConnectTimeoutException exception) {
Log.e(TAG, "Network connetcion is not available");
exception.printStackTrace();
}catch(SocketTimeoutException exception){
Log.e(TAG, "Socket timed out.");
exception.printStackTrace();
} catch (IOException exception) {
Log.v("IO Exception", exception.toString());
exception.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} finally {
if (httpClient.getConnectionManager() != null) {
httpClient.getConnectionManager().shutdown();
}
httpPost = null;
}
return "fail";
}
</code></pre>
<p>and below is my stack trace</p>
<pre><code>03-06 16:53:50.460: W/System.err(1655): javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
03-06 16:53:50.460: W/System.err(1655): at org.apache.harmony.xnet.provider.jsse.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:137)
03-06 16:53:50.470: W/System.err(1655): at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:93)
03-06 16:53:50.470: W/System.err(1655): at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:381)
03-06 16:53:50.470: W/System.err(1655): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:165)
03-06 16:53:50.470: W/System.err(1655): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-06 16:53:50.470: W/System.err(1655): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-06 16:53:50.470: W/System.err(1655): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-06 16:53:50.480: W/System.err(1655): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-06 16:53:50.480: W/System.err(1655): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-06 16:53:50.480: W/System.err(1655): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
</code></pre>
<p>And i am getting the exception while executing below line</p>
<p>HttpResponse response = httpClient.execute(httpget);</p>
| 0 | 2,111 |
How to implement real time data for a web page
|
<p>(This is intended as a Q/A style question, intended to be a go-to resource for people that ask similar questions. A lot of people seem to stumble on the best way of doing this because they don't know all the options. Many of the answers will be ASP.NET specific, but AJAX and other techniques do have equivalents in other frameworks, such as <a href="http://socket.io/" rel="noreferrer">socket.io</a> and SignalR.)</p>
<p>I have a table of data that I have implemented in ASP.NET. I want to display changes to this underlying data on the page in real time or near real time. How do I go about it?</p>
<p>My Model:</p>
<pre><code>public class BoardGame
{
public int Id { get; set;}
public string Name { get; set;}
public string Description { get; set;}
public int Quantity { get; set;}
public double Price { get; set;}
public BoardGame() { }
public BoardGame(int id, string name, string description, int quantity, double price)
{
Id=id;
Name=name;
Description=description;
Quantity=quantity;
Price=price;
}
}
</code></pre>
<p>In lieu of an actual database for this example, I'm just going to store the data in the Application variable. I'm going to seed it in my <code>Application_Start</code> function of my Global.asax.cs.</p>
<pre><code>var SeedData = new List<BoardGame>(){
new BoardGame(1, "Monopoly","Make your opponents go bankrupt!", 76, 15),
new BoardGame(2, "Life", "Win at the game of life.", 55, 13),
new BoardGame(3, "Candyland", "Make it through gumdrop forrest.", 97, 11)
};
Application["BoardGameDatabase"] = SeedData;
</code></pre>
<p>If I were using Web Forms, I'd display the data with a repeater.</p>
<pre><code><h1>Board Games</h1>
<asp:Repeater runat="server" ID="BoardGameRepeater" ItemType="RealTimeDemo.Models.BoardGame">
<HeaderTemplate>
<table border="1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Description</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#: Item.Id %></td>
<td><%#: Item.Name %></td>
<td><%#: Item.Description %></td>
<td><%#: Item.Quantity %></td>
<td><%#: Item.Price %></td>
</tr>
</ItemTemplate>
<FooterTemplate></table></FooterTemplate>
</asp:Repeater>
</code></pre>
<p>And load that data in the code behind:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
BoardGameRepeater.DataSource = Application["BoardGameDatabase"];
BoardGameRepeater.DataBind();
}
</code></pre>
<p>If this were MVC using Razor, it's just a simple foreach over the model:</p>
<pre><code>@model IEnumerable<RealTimeDemo.Models.BoardGame>
<h1>Board Games</h1>
<table border="1">
<tr>
<th>
@Html.DisplayNameFor(model => model.Id)
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th>
@Html.DisplayNameFor(model => model.Quantity)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.Quantity)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
</tr>
}
</table>
</code></pre>
<p>Let's use Web Forms to have a little page for adding data so we can then watch the data update in real time. I recommend you create two browser windows so you can see the form and table at the same time.</p>
<pre><code><h1>Create</h1>
<asp:Label runat="server" ID="Status_Lbl" /><br />
Id: <asp:TextBox runat="server" ID="Id_Tb" /><br />
Name: <asp:TextBox runat="server" ID="Name_Tb" /><br />
Description: <asp:TextBox runat="server" ID="Description_Tb" /><br />
Quantity: <asp:TextBox runat="server" ID="Quantity_Tb" /><br />
Price: <asp:TextBox runat="server" ID="Price_Tb" /><br />
<asp:Button runat="server" ID="SubmitBtn" OnClick="SubmitBtn_Click" Text="Submit" />
</code></pre>
<p>And the code behind:</p>
<pre><code>protected void SubmitBtn_Click(object sender, EventArgs e)
{
var game = new BoardGame();
game.Id = Int32.Parse(Id_Tb.Text);
game.Name = Name_Tb.Text;
game.Description = Description_Tb.Text;
game.Quantity = Int32.Parse(Quantity_Tb.Text);
game.Price = Int32.Parse(Price_Tb.Text);
var db = (List<BoardGame>)Application["BoardGameDatabase"];
db.Add(game);
Application["BoardGameDatabase"] = db;
//only for SignalR
/*var context = GlobalHost.ConnectionManager.GetHubContext<GameHub>();
context.Clients.All.addGame(game); */
}
</code></pre>
| 0 | 2,797 |
How to get child view from RecyclerView?
|
<p>I am trying to get child view by position. I could get view when one item is clicked: </p>
<pre><code>rvSellRecords.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
((MainActivity) getActivity()).showSellRecordFragment(position, view);
}
}));
</code></pre>
<p>Now I cannot get child view, without click - let's say by position for example:</p>
<pre><code>rvSellRecords.someMagicalMethodWhichReturnsViewByPosition(5);
</code></pre>
<p>Question: <strong>How to get child view from RecyclerView?</strong></p>
<p><strong>EDIT FOR BOUNTY</strong>:</p>
<p><a href="https://i.stack.imgur.com/Uv2pb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Uv2pb.png" alt="enter image description here"></a></p>
<p>I have <code>RecyclerView</code> to show products list. When I click on it, I am adding new Fragment where I show product information. While opening I am updating toolbar with view from <code>RecyclerView</code> - this is working perfectly:</p>
<pre><code> rvSellRecords.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
sellPresenter.onSellRecordSelected(position, view);
}
}));
When I click blue button with "+", I am incrementing quantity by 1.
public void onIncrementButtonClicked(){
sellRecord.setCount(sellRecord.getCount() + 1);
showQuantity();
bus.post(new SellRecordChangedEvent(sellRecord, sellRecordPosition));
}
Then I am posting updated sellRecord to first fragment using EventBus. There I am updating list data. I supposed that updating value(sell) automatically updates adapter. Now I am getting view from adapter using custom method(getView) which was created by me(you can find it below).
@Subscribe
public void onEvent(SellRecordChangedEvent event){
sell.getSellRecords().set(event.getSellRecordPosition(), event.getSellRecord());
sell.recalculate();
int position = event.getSellRecordPosition();
View view = adapter.getView(position);
bus.post(new TransactionTitleChangedEvent(null, view));
}
This is my adapter class - I changed adapter little bit to collect view in list and added method which returns view for respective position:
public class SellRecordsAdapter extends RecyclerView.Adapter<SellRecordsAdapter.ViewHolder> {
.....
.....
.....
List<View> viewList;
public SellRecordsAdapter(List<SellRecord> sellRecordList) {
.....
viewList = new ArrayList<>();
}
.....
.....
.....
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
.....
.....
.....
viewList.add(i, viewHolder.itemView);
}
public View getView(int position){
return viewList.get(position);
}
}
</code></pre>
<p><strong>My problem</strong>: when I updating view in toolbar, I am getting old view. When quantity is 3, I am getting view with 2. When quantity 10 - view is with 9.</p>
<p><strong>My question</strong>: how to get view from recycler view using position of item(without on click listener)?</p>
<p><a href="https://i.stack.imgur.com/BKsX5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BKsX5.png" alt="enter image description here"></a></p>
| 0 | 1,331 |
What are the common causes for high CPU usage?
|
<p><strong>Background:</strong></p>
<p>In my application written in C++, I have created 3 threads:</p>
<ul>
<li>AnalysisThread (or Producer) : it reads an input file, parses it, and generates patterns, and enqueue them into <code>std::queue</code><sup>1</sup>.</li>
<li>PatternIdRequestThread (or Consumer) : it deque patterns from the queue, and sends them, one by one, to database through a client (written in C++), which returns pattern <em>uid</em> which is then assigned to the corresponding pattern.</li>
<li>ResultPersistenceThread : it does few more things, talks to database, and it works fine as expected, as far as CPU usage is concerned.</li>
</ul>
<p>First two threads take 60-80% of CPU usage, each takes 35% on average.</p>
<p><strong>Question:</strong></p>
<p>I don't understand why some threads take high CPU usage.</p>
<p>I analyse it as follows : if it is the OS who makes decisions like <a href="http://en.wikipedia.org/wiki/Context_switch" rel="noreferrer">context-switch</a>, <a href="http://en.wikipedia.org/wiki/Interrupt" rel="noreferrer">interrupt</a>, and <a href="http://en.wikipedia.org/wiki/Scheduling_%28computing%29" rel="noreferrer">scheduling</a> as to which thread should be given access to system resources, such as CPU time, then how come <em>some</em> threads in a process happen to use more CPU than the others? It looks like <em>some</em> threads forcefully takes CPU from the OS <em>at gunpoint</em>, or the OS has a real soft spot for some threads and so it is biased towards them from the very beginning, giving them all the resources it has. Why can't it be impartial and give them all equally?</p>
<p>I know that it is naive. But I get confused more if I think along this line : the OS gives access to CPU to a thread, based on the amount of work to be done by the thread, but how does the OS compute or predict the amount of work <em>before</em> executing it completely?</p>
<p>I wonder what are the causes for high CPU usage? How can we identify them? Is it possible to identify them just by looking at the code? What are the tools?</p>
<p>I'm using Visual Studio 2010.</p>
<p><sup>1. I've my doubt about <code>std::queue</code> as well. I know that standard containers aren't thread safe. But if exactly one thread enqueue items to queue, then is it safe if exactly one thread deque items from it? I imagine it be like a pipe, on one side you insert data, on the other, you remove data, then why would it be unsafe if its done simultenously? But that is not the real question in this topic, however, you can add a note in your answer, addressing this.</sup></p>
<p><strong>Updates:</strong></p>
<p>After I realized that my consumer-thread was using busy-spin which I've fixed with <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms686298%28v=vs.85%29.aspx" rel="noreferrer">Sleep</a> for 3 seconds. This fix is temporary, and soon I will use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms682400%28v=vs.85%29.aspx" rel="noreferrer">Event</a> instead. But even with <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms686298%28v=vs.85%29.aspx" rel="noreferrer">Sleep</a>, the CPU usage has dropped down to 30-40%, and occasionally it goes up to 50% which doesn't seem to be desirable from the usability point of view, as the system doesn't respond to other applications which the user is currently working with.</p>
<p>Is there any way that I can still improve on the high CPU usage? As said earlier, the producer thread (which now uses most of the CPU cycles) reads a file, parses packets (of some format) in it, and generates patterns out of them. If I use sleep, then the CPU usage would decrease but would it be a good idea? What are the common ways to solve it?</p>
| 0 | 1,094 |
How to deal with "[Errno 122] Disk quota exceeded" problem when creating new environment by anaconda?
|
<p>I am trying to create a new environment for Python through Anaconda. But the error keeps coming out saying :</p>
<pre><code>Solving environment: failed
# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<
OSError: [Errno 122] Disk quota exceeded
</code></pre>
<p>I am using the sentence below to create the new environment: </p>
<pre><code>conda create --name cpost python=2.7 numpy=1.9
</code></pre>
<p>I understand that this might be related to the working directory, which is really limited in disk quota. So I copied the Anaconda directory fully to a larger disk-quota directory, and tried to create again. The same error came out. As I checked the error information, I noticed the following lines:</p>
<pre><code>$ /nuist/u/home/liangxz/anaconda3/bin/conda create --name cpost python=2.7 numpy=1.9`
environment variables:
CIO_TEST=<not set>
CONDA_ROOT=/nuist/u/home/liangxz/anaconda3
MODULEPATH=/nuist/p/public/app/Modules/modulefiles/app:/nuist/p/public/app/Module
s/modulefiles/compiler:/nuist/p/public/app/Modules/modulefiles/lib:/nu
ist/p/public/app/Modules/modulefiles/mpi
PATH=/nuist/u/home/liangxz/anaconda3/bin:/nuist/p/public/intel/compilers_an
d_libraries_2018.0.128/linux/bin/intel64:/nuist/p/public/intel/compile
rs_and_libraries_2018.0.128/linux/mpi/intel64/bin:/nuist/p/public/pgi/
linux86-64/17.10/bin:/nuist/p/public/pgi/linux86-64/17.10/bin:/opt/xca
t/bin:/opt/xcat/sbin:/opt/xcat/share/xcat/tools:/usr/lib64/qt-3.3/bin:
/opt/confluent/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/
opt/ibutils/bin:/usr/lpp/mmfs/bin:/root/bin:/opt/pbs/default/bin:/nuis
t/u/home/liangxz/.local/bin:/nuist/u/home/liangxz/bin
REQUESTS_CA_BUNDLE=<not set>
SSL_CERT_FILE=<not set>
active environment : None
user config file : /nuist/u/home/liangxz/.condarc
populated config files :
conda version : 4.5.4
conda-build version : 3.10.5
python version : 3.6.5.final.0
base environment : /nuist/u/home/liangxz/anaconda3 (writable)
channel URLs : https://repo.anaconda.com/pkgs/main/linux-64
https://repo.anaconda.com/pkgs/main/noarch
https://repo.anaconda.com/pkgs/free/linux-64
https://repo.anaconda.com/pkgs/free/noarch
https://repo.anaconda.com/pkgs/r/linux-64
https://repo.anaconda.com/pkgs/r/noarch
https://repo.anaconda.com/pkgs/pro/linux-64
https://repo.anaconda.com/pkgs/pro/noarch
package cache : /nuist/u/home/liangxz/anaconda3/pkgs
/nuist/u/home/liangxz/.conda/pkgs
envs directories : /nuist/u/home/liangxz/anaconda3/envs
/nuist/u/home/liangxz/.conda/envs
platform : linux-64
user-agent : conda/4.5.4 requests/2.18.4 CPython/3.6.5 Linux/3.10.0-514.el7.x86_64 centos/7 glibc/2.17
UID:GID : 1135:1135
netrc file : None
offline mode : False
</code></pre>
<p>I realized that the "user config file" is <code>/nuist/u/home/liangxz/.condarc</code>, and the "base environment" is <code>"/nuist/u/home/liangxz/anaconda3 (writable)"</code>, which means even I copied an anaconda to a larger quota directory, the "writable directory" did not change and remained the small quota directory.(<code>/nuist/u/home/liangxz/</code> is the small quota directory)</p>
<p>So my question here is how can I change the "base environments" and "envs directories" to the desired larger quota directory? Can I change it directly through some fixings? Or I must install Anaconda again in the bigger directory?</p>
| 0 | 2,087 |
Modal dialog with fixed header and footer and scrollable content
|
<p>I'm trying to create a modal dialog that has an fixed header and footer and that the content (in this case list of users) inside the modal dialog is scrollable...</p>
<p>My best attempt so far gave me the result on the image:</p>
<p><a href="https://i.stack.imgur.com/cJzqe.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/cJzqe.jpg" alt="my best"></a></p>
<p>I assume that after seeing the image I dont have to describe what the problem is... and I also assume that you will know what the solution has to look like... :)</p>
<p>But just to be sure I'll write it anyway... The modal dialog needs to have a fixed header (Area where the title "Edit board" "Board name" and "Board type" are located) and footer (Area where the "SAVE" button is located) haveto be fixed/unscrolable... the only thing that has to be scrollable is the list of users...</p>
<p><strong>CODE:</strong></p>
<p><strong>Html:</strong></p>
<pre><code><div id="addBoardModal" class="modal modal-fixed-footer">
<form class="Boards_new" autocomplete="off">
<div class="modal-header">
<h5>{{title}}</h5>
<div class="input-field">
<!--INPUT FORM-->
<div class="BoadType">
<!--RADIAL BUTTON THING-->
<div class="modal-content">
<div class="shareMembers" style="margin-top:18px;">
<div class="row">
<h5 class="left">Share</h5>
<!--LIST OF USERS !!!THIS HAS TO BE SCROLLABLE!!!-->
</div>
</div>
<div class="modal-footer">
<!--JSUT THIS SAVE BUTTON-->
</div>
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>.modal {
@extend .z-depth-4;
display: none;
position: fixed;
left: 0;
right: 0;
background-color: #fafafa;
padding: 0;
max-height: 70%;
width: 55%;
margin: auto;
//overflow-y: auto;
border-radius: 2px;
will-change: top, opacity;
@media #{$medium-and-down} {
width: 80%; }
h1,h2,h3,h4 {
margin-top: 0; }
.modal-header{
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
width: 100%;
height: 15rem;
padding:24px;
}
.modal-header > .input-field{width:100%;}
.modal-content {
padding: 24px;
position: absolute;
width: 100%;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
.modal-close {cursor: pointer;}
.modal-footer {
border-radius: 0 0 2px 2px;
border-top: 1px solid rgba(0, 0, 0, 0.1);
background-color: #fafafa;
padding: 4px 6px;
height: 56px;
width: 100%;
.btn, .btn-flat {
float: right;
margin: 6px 0;
}
}
}
</code></pre>
<p>So if anyone could please tell me what am I doing wrong in my code or if I should be doing something diferently that would be nice...</p>
<p>I used these examples to code this...<a href="http://codepen.io/stuntbox/pen/lEdpq" rel="noreferrer">Example no.1</a> & <a href="https://gist.github.com/nate-strauser/530e40ee3bb9b5bb35d366b26e5e1331" rel="noreferrer">Example no.2</a></p>
<p><strong>NOTE:</strong> I'm using the Materialize framework</p>
| 0 | 1,378 |
C# - Cannot create an instance of the abstract class or interface
|
<p>I am getting the error <code>Cannot create an instance of the abstract class or interface</code> in a C# tutorial.</p>
<p>It is failing on this line: <code>result = new Account(nameText, addressText, balance);</code></p>
<p>Here is my class:</p>
<pre><code>public abstract class Account : IAccount
{
//---------------------------------------------------------------
// Constructor
//---------------------------------------------------------------
public Account(string inName, string inAddress, decimal inBalance)
{
name = inName;
address = inAddress;
balance = inBalance;
}
public Account(string inName, string inAddress) :
this(inName, inAddress, 0) // 'this ties this alternate constructor back to the original constructor (directly above)
{
}
public Account(string inName) : // 'this ties this alternate constructor back to the original constructor (directly above)
this(inName, "Not Supplied", 0)
{
}
//---------------------------------------------------------------
// Properties
//---------------------------------------------------------------
// * * * * * * * *
//global account constraints
private static decimal minIncome = 10000;
private static int minAge = 18;
// * * * * * * * *
//personal details
private string name;
private string address;
// * * * * * * * *
//account details
public int AccountNumber;
public static decimal InterestRateCharged;
public AccountState State;
private decimal balance = 0;
public int Overdraft;
//---------------------------------------------------------------
// Methods
//---------------------------------------------------------------
// loads the account
public static Account Load(string filename)
{
Account result = null;
System.IO.TextReader textIn = null;
try
{
textIn = new System.IO.StreamReader(filename);
string nameText = textIn.ReadLine();
string addressText = textIn.ReadLine();
string balanceText = textIn.ReadLine();
decimal balance = decimal.Parse(balanceText);
result = new Account(nameText, addressText, balance);
}
catch
{
return null;
}
finally
{
if (textIn != null) textIn.Close();
}
return result;
}
};
</code></pre>
<p>Here is my interface:</p>
<pre><code>public interface IAccount
{
// account info
int GetAccountNumber();
string GetName();
decimal GetBalance();
// account actions
void PayInFunds(decimal amount);
bool WithdrawFunds(decimal amount);
string RudeLetterString();
}
</code></pre>
| 0 | 1,100 |
Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing
|
<p>I had an interesting job interview experience a while back. The question started really easy:</p>
<blockquote>
<p><strong>Q1</strong>: We have a bag containing numbers <code>1</code>, <code>2</code>, <code>3</code>, …, <code>100</code>. Each number appears exactly once, so there are 100 numbers. Now one number is randomly picked out of the bag. Find the missing number.</p>
</blockquote>
<p>I've heard this interview question before, of course, so I very quickly answered along the lines of:</p>
<blockquote>
<p><strong>A1</strong>: Well, the sum of the numbers <code>1 + 2 + 3 + … + N</code> is <code>(N+1)(N/2)</code> (see <a href="http://en.wikipedia.org/wiki/Arithmetic_sum#Sum" rel="noreferrer">Wikipedia: sum of arithmetic series</a>). For <code>N = 100</code>, the sum is <code>5050</code>.</p>
<p>Thus, if all numbers are present in the bag, the sum will be exactly <code>5050</code>. Since one number is missing, the sum will be less than this, and the difference is that number. So we can find that missing number in <code>O(N)</code> time and <code>O(1)</code> space.</p>
</blockquote>
<p>At this point I thought I had done well, but all of a sudden the question took an unexpected turn:</p>
<blockquote>
<p><strong>Q2</strong>: That is correct, but now how would you do this if <em>TWO</em> numbers are missing?</p>
</blockquote>
<p>I had never seen/heard/considered this variation before, so I panicked and couldn't answer the question. The interviewer insisted on knowing my thought process, so I mentioned that perhaps we can get more information by comparing against the expected product, or perhaps doing a second pass after having gathered some information from the first pass, etc, but I really was just shooting in the dark rather than actually having a clear path to the solution.</p>
<p>The interviewer did try to encourage me by saying that having a second equation is indeed one way to solve the problem. At this point I was kind of upset (for not knowing the answer before hand), and asked if this is a general (read: "useful") programming technique, or if it's just a trick/gotcha answer.</p>
<p>The interviewer's answer surprised me: you can generalize the technique to find 3 missing numbers. In fact, you can generalize it to find <em>k</em> missing numbers.</p>
<blockquote>
<p><strong>Qk</strong>: If exactly <em>k</em> numbers are missing from the bag, how would you find it efficiently?</p>
</blockquote>
<p>This was a few months ago, and I still couldn't figure out what this technique is. Obviously there's a <code>Ω(N)</code> time lower bound since we must scan all the numbers at least once, but the interviewer insisted that the <em>TIME</em> and <em>SPACE</em> complexity of the solving technique (minus the <code>O(N)</code> time input scan) is defined in <em>k</em> not <em>N</em>.</p>
<p>So the question here is simple:</p>
<ul>
<li>How would you solve <strong>Q2</strong>?</li>
<li>How would you solve <strong>Q3</strong>?</li>
<li>How would you solve <strong>Qk</strong>?</li>
</ul>
<hr />
<h3>Clarifications</h3>
<ul>
<li>Generally there are <em>N</em> numbers from 1..<em>N</em>, not just 1..100.</li>
<li>I'm not looking for the obvious set-based solution, e.g. using a <a href="http://en.wikipedia.org/wiki/Bit_array" rel="noreferrer">bit set</a>, encoding the presence/absence each number by the value of a designated bit, therefore using <code>O(N)</code> bits in additional space. We can't afford any additional space proportional to <em>N</em>.</li>
<li>I'm also not looking for the obvious sort-first approach. This and the set-based approach are worth mentioning in an interview (they are easy to implement, and depending on <em>N</em>, can be very practical). I'm looking for the Holy Grail solution (which may or may not be practical to implement, but has the desired asymptotic characteristics nevertheless).</li>
</ul>
<p>So again, of course you must scan the input in <code>O(N)</code>, but you can only capture small amount of information (defined in terms of <em>k</em> not <em>N</em>), and must then find the <em>k</em> missing numbers somehow.</p>
| 0 | 1,222 |
Didn't find class "android.support.v7.widget.RecyclerView
|
<p>I'm getting this exception when running: </p>
<p>android.view.InflateException: Binary XML file line #8: Error inflating class android.support.v7.widget.RecyclerView<br>
<strong>Caused by: java.lang.ClassNotFoundException:
Didn't find class "android.support.v7.widget.RecyclerView" on path: /data/app/my.package.location-1.apk</strong></p>
<p>There are some questions concerning this error, from which I've learned to:<br>
- specify exactly the <code>support.v7</code> RecyclerView, in the xml and Java code.<br>
- in Eclipse, I added this jar file as a library to the project:<br>
<em>adt-bundle-windows-x86_64-20140321\sdk\extras\android\support\v7\recyclerview\libs\android-support-v7-recyclerview.jar</em><br>
- in Eclipse, import the existing project TestActivity in *adt-bundle-windows-x86_64-20140321\sdk\extras\android\support\v7\recyclerview*
and then added that project to the Java Build Path of my own project. </p>
<p>Project Build Target is Android 5.1.1/API 22</p>
<p>All to no effect.
What else is there?</p>
<p>from MyFragment.java</p>
<pre><code>import android.support.v7.widget.RecyclerView;
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
final Activity thisActivity = getActivity();
final RecyclerView recyclerView = (RecyclerView)thisActivity.findViewById(R.id.my_listview);
final List<String> list = Arrays.asList(HEADERS);
final MyRecyclerAdapter adapter = new MyRecyclerAdapter(list);
recyclerView.setAdapter(adapter);
}
</code></pre>
<p>MyRecyclerAdapter.java</p>
<pre><code>import android.support.v7.widget.RecyclerView;
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder> {
private ArrayList<String> mDataset;
// Provide a suitable constructor (depends on the kind of dataset)
public MyRecyclerAdapter(List<String> list) {
mDataset = (ArrayList<String>) list;
}
// Create new views (invoked by the layout manager)
@Override
public MyRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final String name = mDataset.get(position);
holder.txtId.setText(mDataset.get(position));
holder.txtId.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
remove(name);
}
});
holder.txtType.setText("Footer: " + mDataset.get(position));
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDataset.size();
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView txtId;
public TextView txtType;
public TextView txtName;
public ViewHolder(View v) {
super(v);
txtId = (TextView) v.findViewById(R.id.id);
txtType = (TextView) v.findViewById(R.id.type);
txtName = (TextView) v.findViewById(R.id.name);
}
}
public void add(int position, String item) {
mDataset.add(position, item);
notifyItemInserted(position);
}
public void remove(String item) {
int position = mDataset.indexOf(item);
mDataset.remove(position);
notifyItemRemoved(position);
}
}
</code></pre>
<p>fragment.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#000000" >
<android.support.v7.widget.RecyclerView
android:id="@+id/my_listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</code></pre>
<p>row_layout.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/id"
android:textColor="#FFFFFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp" >
</TextView>
<TextView
android:id="@+id/type"
android:textColor="#FFFFFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp" >
</TextView>
<TextView
android:id="@+id/name"
android:textColor="#FFFFFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp" >
</TextView>
</LinearLayout>
</code></pre>
<p>Edit: As suggested by Arman Kabir, I checked "Is Library". This does indeed fix the <code>ClassNotFoundException</code>. It does result in a slightly different error, but this is another problem.</p>
<pre><code>android.view.InflateException: Binary XML file line #8: Error inflating class android.support.v7.widget.RecyclerView
at android.view.LayoutInflater.createView(LayoutInflater.java:613)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at android.view.LayoutInflater.createView(LayoutInflater.java:587)
... 44 more
Caused by: java.lang.NoClassDefFoundError: android.support.v4.util.Pools$SimplePool
at android.support.v7.widget.AdapterHelper.<init>(AdapterHelper.java:56)
at android.support.v7.widget.AdapterHelper.<init>(AdapterHelper.java:71)
at android.support.v7.widget.RecyclerView.initAdapterManager(RecyclerView.java:455)
at android.support.v7.widget.RecyclerView.<init>(RecyclerView.java:339)
... 47 more
</code></pre>
| 0 | 2,792 |
Cannot build react-native project from Android-Studio
|
<p>I can run my react-native project. It works fine. I have tested by running using react-native. But when I'm trying to run it with Android studio I get the following error.</p>
<pre><code>*FAILURE: Build failed with an exception.
* Where:
Script 'D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\@react-native-community\cli-platform-android\native_modules.gradle' line: 195
* What went wrong:
A problem occurred evaluating settings 'employeeMobile'.
> Unable to determine the current character, it is not a string, number, array, or object
The current character read is 'E' with an int value of 69
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 0
Error: EPERM: operation not permitted, scandir 'D:/EmployeeApp/EmployeeMobileAppGit/employeemobile-app/android/app/build/intermediates/signing_config/debug/out/signing-config.json' at Object.readdirSync (fs.js:790:3) at GlobSync._readdir (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:288:41) at GlobSync._readdirInGlobStar (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:267:20) at GlobSync._readdir (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:276:17) at GlobSync._processReaddir (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:137:22) at GlobSync._process (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:132:10) at GlobSync._processGlobStar (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:380:10) at GlobSync._process (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:130:10) at GlobSync._processGlobStar (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:383:10) at GlobSync._process (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:130:10)
^
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 3s
Unable to determine the current character, it is not a string, number, array, or object
The current character read is 'E' with an int value of 69
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 0
Error: EPERM: operation not permitted, scandir 'D:/EmployeeApp/EmployeeMobileAppGit/employeemobile-app/android/app/build/intermediates/signing_config/debug/out/signing-config.json' at Object.readdirSync (fs.js:790:3) at GlobSync._readdir (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:288:41) at GlobSync._readdirInGlobStar (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:267:20) at GlobSync._readdir (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:276:17) at GlobSync._processReaddir (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:137:22) at GlobSync._process (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:132:10) at GlobSync._processGlobStar (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:380:10) at GlobSync._process (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:130:10) at GlobSync._processGlobStar (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:383:10) at GlobSync._process (D:\EmployeeApp\EmployeeMobileAppGit\employeemobile-app\node_modules\glob\sync.js:130:10)
^
10:38:38 AM: Task execution finished.*
</code></pre>
<p>My project Gradle file is as follows.</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = "28.0.3"
minSdkVersion = 16
compileSdkVersion = 28
targetSdkVersion = 28
supportLibVersion = "28.0.0"
}
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
google()
jcenter()
}
}
</code></pre>
<p>My app/Gradle file is as follows.</p>
<pre><code>apply plugin: "com.android.application"
import com.android.build.OutputFile
project.ext.react = [
entryFile: "index.js",
enableHermes: false, // clean and rebuild if changing
]
apply from: "../../node_modules/react-native/react.gradle"
/**
* Set this to true to create two separate APKs instead of one:
* - An APK that only works on ARM devices
* - An APK that only works on x86 devices
* The advantage is the size of the APK is reduced by about 4MB.
* Upload all the APKs to the Play Store and people will download
* the correct one based on the CPU architecture of their device.
*/
def enableSeparateBuildPerCPUArchitecture = false
/**
* Run Proguard to shrink the Java bytecode in release builds.
*/
def enableProguardInReleaseBuilds = false
/**
* The preferred build flavor of JavaScriptCore.
*
* For example, to use the international variant, you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'org.webkit:android-jsc:+'
/**
* Whether to enable the Hermes VM.
*
* This should be set on project.ext.react and mirrored here. If it is not set
* on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
* and the benefits of using Hermes will therefore be sharply reduced.
*/
def enableHermes = project.ext.react.get("enableHermes", false);
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "com.employeemobile"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
release {
if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {
storeFile file(MYAPP_UPLOAD_STORE_FILE)
storePassword MYAPP_UPLOAD_STORE_PASSWORD
keyAlias MYAPP_UPLOAD_KEY_ALIAS
keyPassword MYAPP_UPLOAD_KEY_PASSWORD
}
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://facebook.github.io/react-native/docs/signed-apk-android.
signingConfig signingConfigs.debug
signingConfig signingConfigs.release
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
packagingOptions {
pickFirst '**/armeabi-v7a/libc++_shared.so'
pickFirst '**/x86/libc++_shared.so'
pickFirst '**/arm64-v8a/libc++_shared.so'
pickFirst '**/x86_64/libc++_shared.so'
pickFirst '**/x86/libjsc.so'
pickFirst '**/armeabi-v7a/libjsc.so'
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "com.facebook.react:react-native:+" // From node_modules
if (enableHermes) {
def hermesPath = "../../node_modules/hermesvm/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
}
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
</code></pre>
| 0 | 3,864 |
org.hibernate.exception.ConstraintViolationException: could not insert
|
<p>When I try to add into <code>TDEPOFAZLA</code> table, I get the following error: </p>
<blockquote>
<p>org.springframework.dao.DataIntegrityViolationException: could not insert: [tr.gov.tcmb.pgmtems.model.DepoFazla]; SQL [insert into PGMTEMS.TDEPOFAZLA (ID, FAZLABULUNDURMAORANI, GRUP) values (default, ?, ?)]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not insert: [tr.gov.tcmb.pgmtems.model.DepoFazla]</p>
</blockquote>
<p>Here is my <strong>JUnit</strong> test function:</p>
<pre><code> @Test
public void testSaveDepoFazla() {
DepoTur depoTur = new DepoTur("my tür", 5);
depoTurService.saveDepoTur(depoTur);
List<DepoTur> list = depoTurService.getDepoTurList();
assertNotNull(list.get(0));
BigDecimal fazlaBulundurmaOrani = new BigDecimal(6000);
DepoFazla depoFazla = new DepoFazla(1, list.get(0), fazlaBulundurmaOrani);
depoFazlaService.saveDepoFazla(depoFazla);
}
</code></pre>
<p>Here is my <strong>DepoFazla.java</strong>:</p>
<pre><code>@Entity
@Table(schema = "PGMTEMS", name = "TDEPOFAZLA")
public class DepoFazla implements Serializable {
private static final long serialVersionUID = -2800365387332643658L;
@Id
@GeneratedValue
@Column(name = "ID", nullable = false, updatable = false)
private Long id;
@Column(name = "GRUP", nullable = false, columnDefinition = "INTEGER")
private Integer grup;
@ManyToOne(fetch = FetchType.LAZY, targetEntity = DepoTur.class)
@JoinColumn(name = "ID", insertable = false, updatable = false)
@NotNull
private DepoTur depoTur;
@Column(name = "FAZLABULUNDURMAORANI", nullable = false, columnDefinition = "DECIMAL(6, 2)")
private BigDecimal fazlaBulundurmaOrani;
public DepoFazla() {
super();
}
public DepoFazla(Integer grup, DepoTur depoTur, BigDecimal fazlaBulundurmaOrani) {
super();
this.grup = grup;
this.depoTur = depoTur;
this.fazlaBulundurmaOrani = fazlaBulundurmaOrani;
}
//GETTER AND SETTER METHODS
}
</code></pre>
<p>Here is <strong>DepoTur.java</strong>:</p>
<pre><code>@Entity
@Table(schema = "PGMTEMS", name = "TDEPOTUR")
public class DepoTur implements Serializable {
private static final long serialVersionUID = 6203672609079710060L;
@Id
@GeneratedValue
@Column(name = "ID", nullable = false, updatable = false)
@Index(name = "XUTDEPOTURP", columnNames = { "id" })
private Long id;
@Column(name = "ACIKLAMA", nullable = false)
private String aciklama;
@Column(name = "BLOKESIRASI", nullable = false)
private Integer blokeSirasi; //
@Column(name = "DEPOCINSI")
private String depoCinsi;
public DepoTur() {
super();
}
public DepoTur(String aciklama, Integer blokeSirasi, String depoCinsi) {
super();
this.aciklama = aciklama;
this.depoCinsi = depoCinsi;
this.blokeSirasi = blokeSirasi;
}
public DepoTur(String aciklama, Integer blokeSirasi) {
super();
this.aciklama = aciklama;
this.blokeSirasi = blokeSirasi;
}
//GETTER AND SETTER METHODS
</code></pre>
<p>When I debug the JUnit test, I get this error:</p>
<blockquote>
<p>Error: DB2 SQL Error: SQLCODE=-407, SQLSTATE=23502, SQLERRMC=TBSPACEID=2, TABLEID=75, COLNO=2, DRIVER=3.50.152 SQLState: 23502 ErrorCode: -407</p>
</blockquote>
<p>When I search the error, I find that I try to insert NULL but I can't figure out where I add null value. </p>
<p>This is how I create <strong>TDEPOFAZLA</strong> table:</p>
<pre><code> CREATE TABLE TDEPOFAZLA
(
ID decimal(20,0) PRIMARY KEY NOT NULL,
GRUP int NOT NULL,
DEPOTUR decimal(20,0) NOT NULL,
FAZLABULUNDURMAORANI decimal(6,2) NOT NULL
);
CREATE UNIQUE INDEX XUTDEPOFAZLAP ON TDEPOFAZLA(ID);
</code></pre>
<p>This is how I create <strong>TDEPOTUR</strong> table:</p>
<pre><code>CREATE TABLE TDEPOTUR
(
ID decimal(20,0) PRIMARY KEY NOT NULL,
ACIKLAMA varchar(100) NOT NULL,
DEPOCINSI char(1),
BLOKESIRASI int NOT NULL
);
CREATE UNIQUE INDEX XUTDEPOTURP ON TDEPOTUR(ID);
</code></pre>
<p>Any ideas on what I should do?</p>
| 0 | 1,755 |
mySQL MATCH across multiple tables
|
<p>I have a set of 4 tables that I want to search across. Each has a full text index. Can a query make use of every index?</p>
<pre><code>CREATE TABLE `categories` (
`id` int(5) unsigned NOT NULL auto_increment,
`display_order` int(5) unsigned default NULL,
`name` varchar(64) default NULL,
`last_modified` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `order` (`display_order`),
FULLTEXT KEY `full_name` (`name`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
CREATE TABLE `host_types` (
`id` int(5) unsigned NOT NULL auto_increment,
`category_id` int(5) unsigned default NULL,
`display_order` int(5) unsigned default NULL,
`name` varchar(64) default NULL,
`last_modified` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `order` (`category_id`,`display_order`),
FULLTEXT KEY `full_name` (`name`)
) ENGINE=MyISAM AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;
CREATE TABLE `hosts` (
`id` int(5) unsigned NOT NULL auto_increment,
`host_id` int(5) unsigned default NULL,
`display_order` int(5) unsigned default NULL,
`name` varchar(64) default NULL,
`last_modified` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `order` (`host_id`,`display_order`),
FULLTEXT KEY `full_name` (`name`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
CREATE TABLE `products` (
`id` int(11) unsigned NOT NULL auto_increment,
`host_id` int(5) unsigned default NULL,
`display_order` int(5) unsigned default NULL,
`uid` varchar(10) default NULL,
`name` varchar(128) default NULL,
`keywords` text,
`description` text,
`price` decimal(10,2) default NULL,
`quantity` int(11) unsigned default NULL,
`last_modified` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
FULLTEXT KEY `full_name` (`name`,`keywords`,`description`,`uid`)
) ENGINE=MyISAM AUTO_INCREMENT=14 DEFAULT CHARSET=latin1;
</code></pre>
<p>Here is my query;</p>
<pre><code>SELECT categories.name AS category,
categories.id AS category_id,
host_types.name AS host_type,
host_types.id AS host_type_id,
hosts.name AS host,
hosts.id AS host_id,
products.name as name,
products.id AS product_id,
products.keywords as keywords,
products.description AS description,
products.quantity AS quantity,
products.price AS price,
products.uid as catalogue,
MATCH(categories.name, host_types.name, hosts.name, products.name,
products.keywords, products.description, products.uid)
AGAINST('search term') as score
FROM products
LEFT JOIN hosts ON products.host_id = hosts.id
LEFT JOIN host_types ON hosts.host_id = host_types.id
LEFT JOIN categories ON host_types.category_id = categories.id
WHERE MATCH(categories.name, host_types.name, hosts.name, products.name,
products.keywords, products.description, products.uid)
AGAINST('search term')
ORDER BY score DESC;
</code></pre>
<ul>
<li>categories.name == FULLTEXT - 1</li>
<li>host_types.name == FULLTEXT - 2</li>
<li>hosts.name == FULLTEXT - 3</li>
<li>products.name, products.keywords, products.description, products.uid == FULLTEXT - 4</li>
</ul>
<hr>
<p>Here is my SQL structure, and I used the above Query.</p>
<pre><code>SELECT
categories.name AS category,
categories.id AS category_id,
host_types.name AS host_type,
host_types.id AS host_type_id,
hosts.name AS host,
hosts.id AS host_id,
products.name as name,
products.id AS product_id,
products.keywords as keywords,
products.description AS description,
products.quantity AS quantity,
products.price AS price,
products.uid as catalgue
MATCH(categories.name) AGAINST('search term') as cscore,
MATCH(host_types.name) AGAINST('search term') as htscore,
MATCH(hosts.name) AGAINST('search term') as hscore,
MATCH(products.name, products.keywords, products.description, products.uid)
AGAINST('search term') as score
FROM products
LEFT JOIN hosts ON products.host_id = hosts.id
LEFT JOIN host_types ON hosts.host_id = host_types.id
LEFT JOIN categories ON host_types.category_id = categories.id
WHERE
MATCH(categories.name) AGAINST('search term') OR
MATCH(host_types.name) AGAINST('search term') OR
MATCH(hosts.name) AGAINST('search term') OR
MATCH(products.name, products.keywords, products.description, products.uid)
AGAINST('search term')
ORDER BY score DESC
CREATE TABLE `categories` (
`id` int(5) unsigned NOT NULL auto_increment,
`display_order` int(5) unsigned default NULL,
`name` varchar(64) default NULL,
`last_modified` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `order` (`display_order`),
FULLTEXT KEY `full_name` (`name`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
CREATE TABLE `host_types` (
`id` int(5) unsigned NOT NULL auto_increment,
`category_id` int(5) unsigned default NULL,
`display_order` int(5) unsigned default NULL,
`name` varchar(64) default NULL,
`last_modified` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `order` (`category_id`,`display_order`),
FULLTEXT KEY `full_name` (`name`)
) ENGINE=MyISAM AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;
CREATE TABLE `hosts` (
`id` int(5) unsigned NOT NULL auto_increment,
`host_id` int(5) unsigned default NULL,
`display_order` int(5) unsigned default NULL,
`name` varchar(64) default NULL,
`last_modified` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `order` (`host_id`,`display_order`),
FULLTEXT KEY `full_name` (`name`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
CREATE TABLE `products` (
`id` int(11) unsigned NOT NULL auto_increment,
`host_id` int(5) unsigned default NULL,
`display_order` int(5) unsigned default NULL,
`uid` varchar(10) default NULL,
`name` varchar(128) default NULL,
`keywords` text,
`description` text,
`price` decimal(10,2) default NULL,
`quantity` int(11) unsigned default NULL,
`last_modified` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
FULLTEXT KEY `full_name` (`name`,`keywords`,`description`,`uid`)
) ENGINE=MyISAM AUTO_INCREMENT=14 DEFAULT CHARSET=latin1;
</code></pre>
| 0 | 2,393 |
log4j2 config file is not being recognized
|
<p>I'm trying to get log4j2 setup in my Geb framework. For the life of me I can't figure out how to put this together. I have a log4j2.xml (not log4j.xml) file setup with the logger "Selenium". In DefaultPage I try to get the Logger with the name Selenium from the config file <code>LogManager.getLogger("Selenium")</code>.</p>
<p>log4j2.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<Configuration status="TRACE">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss,SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="Selenium" level="TRACE">
<AppenderRef ref="Console"/>
</Logger>
<Root level="TRACE">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
</code></pre>
<p>DefaultPage.groovy</p>
<pre><code>class DefaultPage extends geb.Page {
static content = {
pageId(wait: true) { $("meta", name: "pageId").getAttribute("content") }
pageHeading(wait: true) { $("meta", name: "heading").getAttribute("content") }
}
static final Logger logger = LogManager.getLogger("Selenium")
/**
* Uses jquery to create a mouseover on an element
* @param element The jquery element created in the page object.
*/
static def mouseOver(element) {
logger.error("Hovering over ${element}")
element.jquery.mouseover()
}
}
</code></pre>
<p>The test executes and output is written to STDERR, which is expected because I have logger.error. However, it doesn't hold format for the date. Additionally I have other classes calling this logger with .info and those are not seen in STDOUT. When I debug the level of the logger is ERROR, not TRACE.</p>
<p>Here's my file structure:</p>
<pre><code>functional
|
--src
|
|--test
|
|--groovy
| |
| |--com.x.functional
| |
| |--pages
| |
| |--DefaultPage.groovy
| |--Other classes that want to use log4j2.
|
|--resources
|
|--log4j2.xml
</code></pre>
<p>Thank you.</p>
<p><strong>EDIT</strong>
Changing log4j to log4j2. Adding Configuration status = TRACE. Modified date format for milliseconds with ',' instead of '.'</p>
| 0 | 1,031 |
Django forms: how to dynamically create ModelChoiceField labels
|
<p>I would like to create dynamic labels for a forms.ModelChoiceField and I'm wondering how to do that. I have the following form class:</p>
<pre><code>class ProfileForm(forms.ModelForm):
def __init__(self, data=None, ..., language_code='en', family_name_label='Family name', horoscope_label='Horoscope type', *args, **kwargs):
super(ProfileForm, self).__init__(data, *args, **kwargs)
self.fields['family_name'].label = family_name_label
.
.
self.fields['horoscope'].label = horoscope_label
self.fields['horoscope'].queryset = Horoscope.objects.all()
class Meta:
model = Profile
family_name = forms.CharField(widget=forms.TextInput(attrs={'size':'80', 'class': 'contact_form'}))
.
.
horoscope = forms.ModelChoiceField(queryset = Horoscope.objects.none(), widget=forms.RadioSelect(), empty_label=None)
</code></pre>
<p>The default labels are defined by the <strong>unicode</strong> function specified in the Profile definition. However the labels for the radio buttons created by the ModelChoiceField need to be created dynamically.</p>
<p>First I thought I could simply override ModelChoiceField as described in the Django documentation. But that creates static labels. It allows you to define any label but once the choice is made, that choice is fixed.</p>
<p>So I think I need to adapt add something to <strong>init</strong> like:</p>
<pre><code>class ProfileForm(forms.ModelForm):
def __init__(self, data=None, ..., language_code='en', family_name_label='Family name', horoscope_label='Horoscope type', *args, **kwargs):
super(ProfileForm, self).__init__(data, *args, **kwargs)
self.fields['family_name'].label = family_name_label
.
.
self.fields['horoscope'].label = horoscope_label
self.fields['horoscope'].queryset = Horoscope.objects.all()
self.fields['horoscope'].<WHAT>??? = ???
</code></pre>
<p>Anyone having any idea how to handle this? Any help would be appreciated very much.</p>
<hr>
<p>I found something but I don't know if it's the best solution. I add something to the <strong>init</strong> part of class ProfileForm as follows:</p>
<pre><code>class ProfileForm((forms.ModelForm):
def __init__(self, data=None, ..., language_code='en', family_name_label='Family name', horoscope_label='Horoscope type', *args, **kwargs):
super(ProfileForm, self).__init__(data, *args, **kwargs)
# this function is added
def get_label(self, language_code):
"""
returns the label in the designated language, from a related object (table)
"""
return HoroscopeLanguage.objects.get(horoscope=obj, language__language_code=language_code).horoscope_type_language
self.fields['family_name'].label = family_name_label
.
.
self.fields['horoscope'].queryset = Horoscope.objects.all()
self.fields['horoscope'].label_from_instance = lambda obj: "%s: Euro %.2f" % (HoroscopeLanguage.objects.get(horoscope=obj, language__language_code=language_code).horoscope_type_language, obj.price)
.
.
"""
The next code also works, the lambda function without the get_label function
"""
self.fields['horoscope'].label_from_instance = lambda obj: "%s: Euro %.2f" % (obj.horoscope_type, obj.price)
.
.
"""
But this code doesn't work. Anyone?
"""
self.fields['horoscope'].label_from_instance = get_label(obj, language_code)
</code></pre>
| 0 | 1,304 |
Using AsyncTask to load images into a custom adapter
|
<p>Although there are many tutorials out there, I've found it really difficult to implement an AsyncTask to load images from URI's (obtained from a content provider) into a custom adapter.</p>
<p>I get the basic gist, which is to have a class containing an AsyncTask, do the bitmap creation in the 'doInBackground', and then set the ImageView in the onPostExecute.</p>
<p>The problem for me, being new to android & programming, is that I don't know how to pass in my Uri's to the AsyncTask for each item, how to create the bitmap, and how to return it to the adapter.</p>
<p>I've only gotten this far with the actual AsyncTask class (ImageLoader):</p>
<pre><code>package another.music.player;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.widget.ImageView;
public class ImageLoader extends AsyncTask<String, String, Bitmap> {
private ImageView imageView;
private Bitmap bitmap = null;
@Override
protected Bitmap doInBackground(String... uri) {
// Create bitmap from passed in Uri here
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null && imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
</code></pre>
<p>And my custom adapter looks like this:</p>
<pre><code>package another.music.player;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.MediaStore.Audio.AlbumColumns;
import android.provider.MediaStore.Audio.AudioColumns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
class AlbumAdapter extends CursorAdapter {
public AlbumAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
private static Uri currentSongUri;
@Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView albumArt = (ImageView) view.getTag(R.id.albumArt);
TextView text1 = (TextView) view.getTag(R.id.artistTitle);
TextView text2 = (TextView) view.getTag(R.id.albumTitle);
TextView text3 = (TextView) view.getTag(R.id.totalSongs);
albumArt.setImageBitmap(null);
text1.setText(cursor.getString(cursor
.getColumnIndex(AudioColumns.ARTIST)));
text2.setText(cursor.getString(cursor
.getColumnIndex(AudioColumns.ALBUM)));
text3.setText(cursor.getString(cursor
.getColumnIndex(AlbumColumns.NUMBER_OF_SONGS)));
String currentAlbumId = cursor.getString(cursor
.getColumnIndex(BaseColumns._ID));
Integer currentAlbumIdLong = Integer.parseInt(currentAlbumId);
Uri artworkUri = Uri.parse("content://media/external/audio/albumart");
currentSongUri = ContentUris.withAppendedId(artworkUri,
currentAlbumIdLong);
//Run ImageLoader AsyncTask here, and somehow retrieve the ImageView & set it.
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.albumitem, null);
view.setTag(R.id.albumArt, view.findViewById(R.id.albumArt));
view.setTag(R.id.artistTitle, view.findViewById(R.id.artistTitle));
view.setTag(R.id.albumTitle, view.findViewById(R.id.albumTitle));
view.setTag(R.id.totalSongs, view.findViewById(R.id.totalSongs));
return view;
}
}
</code></pre>
<p>I would be very grateful if somebody could show me how to proceed with this.</p>
<p>Thanks.</p>
| 0 | 1,431 |
Calculating angles between line segments (Python) with math.atan2
|
<p>I am working on a spatial analysis problem and part of this workflow is to calculate the angle between connected line segments.</p>
<p>Each line segment is composed of only two points, and each point has a pair of XY coordinates (Cartesian). Here is the image from GeoGebra. <strong>I am always interested in getting a positive angle in 0 to 180 range</strong>. However, I get all kind of angles depending on the order of vertices in input line segments.</p>
<p><img src="https://i.stack.imgur.com/iSNAq.png" alt="enter image description here"></p>
<p>The input data I work with is provided as tuples of coordinates. Depending on the vertex creation order, the last/end point for each line segment can be different. Here are some of the cases in Python code. The order of line segments in which I get them is random, but in a tuple of tuples, the first element is the start point and the second one is the end point. <code>DE</code> line segment, for instance, would have <code>((1,1.5),(2,2))</code> and the <code>(1,1.5)</code> is the start point because it has the first position in the tuple of coordinates.</p>
<p>I however need to make sure I will get the same angle between <code>DE,DF</code> and <code>ED,DF</code> and so forth.</p>
<pre><code>vertexType = "same start point; order 1"
#X, Y X Y coords
lineA = ((1,1.5),(2,2)) #DE
lineB = ((1,1.5),(2.5,0.5)) #DF
calcAngle(lineA, lineB,vertexType)
#flip lines order
vertexType = "same start point; order 2"
lineB = ((1,1.5),(2,2)) #DE
lineA = ((1,1.5),(2.5,0.5)) #DF
calcAngle(lineA, lineB,vertexType)
vertexType = "same end point; order 1"
lineA = ((2,2),(1,1.5)) #ED
lineB = ((2.5,0.5),(1,1.5)) #FE
calcAngle(lineA, lineB,vertexType)
#flip lines order
vertexType = "same end point; order 2"
lineB = ((2,2),(1,1.5)) #ED
lineA = ((2.5,0.5),(1,1.5)) #FE
calcAngle(lineA, lineB,vertexType)
vertexType = "one line after another - down; order 1"
lineA = ((2,2),(1,1.5)) #ED
lineB = ((1,1.5),(2.5,0.5)) #DF
calcAngle(lineA, lineB,vertexType)
#flip lines order
vertexType = "one line after another - down; order 2"
lineB = ((2,2),(1,1.5)) #ED
lineA = ((1,1.5),(2.5,0.5)) #DF
calcAngle(lineA, lineB,vertexType)
vertexType = "one line after another - up; line order 1"
lineA = ((1,1.5),(2,2)) #DE
lineB = ((2.5,0.5),(1,1.5)) #FD
calcAngle(lineA, lineB,vertexType)
#flip lines order
vertexType = "one line after another - up; line order 2"
lineB = ((1,1.5),(2,2)) #DE
lineA = ((2.5,0.5),(1,1.5)) #FD
calcAngle(lineA, lineB,vertexType)
</code></pre>
<p>I have written a tiny function that takes combinations of the lines as args and calculates the angle between them. I am using the <code>math.atan2</code> which seemed to be best suited for this. </p>
<pre><code>def calcAngle(lineA,lineB,vertexType):
line1Y1 = lineA[0][1]
line1X1 = lineA[0][0]
line1Y2 = lineA[1][1]
line1X2 = lineA[1][0]
line2Y1 = lineB[0][1]
line2X1 = lineB[0][0]
line2Y2 = lineB[1][1]
line2X2 = lineB[1][0]
#calculate angle between pairs of lines
angle1 = math.atan2(line1Y1-line1Y2,line1X1-line1X2)
angle2 = math.atan2(line2Y1-line2Y2,line2X1-line2X2)
angleDegrees = (angle1-angle2) * 360 / (2*math.pi)
print angleDegrees, vertexType
</code></pre>
<p>The output I get is:</p>
<pre><code>> -299.744881297 same start point; order 1
> 299.744881297 same start point; order 2
> 60.2551187031 same end point; order 1
> -60.2551187031 same end point; order 2
> -119.744881297 one line after another - down; order 1
> 119.744881297 one line after another - down; order 2
> -119.744881297 one line after another - up; line order 1
> 119.744881297 one line after another - up; line order 2
</code></pre>
<p>As you can see, I am getting different values depending on the order of vertices in a line segment and line segments order. I have tried to post-process the angles by finding out what kind of relation the source line had and flipping the lines, editing the angle etc. I've ended with a dozen of such cases and at some point they start to overlap and I cannot any longer find out whether -119.744 should become 60.255 (acute angle) or be left as 119.744 (obtuse angle) etc.</p>
<p><strong>Is there any discrete way to process the output angle values I receive from <code>math.atan2</code> to get only a positive value in 0 to 180 range?</strong> <strong>If not, what kind of other approach should I take?</strong></p>
| 0 | 1,663 |
Hook ZwTerminateProcess in x64 Driver (Without SSDT)
|
<p>I found and read this question but I didn't found my answer <a href="https://stackoverflow.com/questions/11597888/ssdt-hooking-alternative-in-x64-systems"><strong>SSDT hooking alternative in x64 systems</strong></a></p>
<p>I want to protect my application against termination by other programs. In the 32Bit version of windows I used the <code>SSDT hooking</code> for hooking <code>ZwTerminateProcess</code> or <code>ZwOpenProcess</code>. I've to upgrade my program to using in 64Bit version of windows now.
And unfortunately in the 64bit windows we can't use <code>SSDT</code> hook (<a href="http://msdn.microsoft.com/en-us/windows/hardware/gg487353.aspx" rel="nofollow noreferrer"><strong>Because Patch Guard (KPP)</strong></a>), Notice that I don't want to Bypassing PG in this case and I've to use only kernel-mode hooking. For example, I don't want to my program begin terminated (Even )by the following code :</p>
<pre><code>NTSTATUS drvTerminateProcess( ULONG ulProcessID )
{
NTSTATUS ntStatus = STATUS_SUCCESS;
HANDLE hProcess;
OBJECT_ATTRIBUTES ObjectAttributes;
CLIENT_ID ClientId;
DbgPrint( "drvTerminateProcess( %u )", ulProcessID );
InitializeObjectAttributes( &ObjectAttributes, NULL, OBJ_INHERIT, NULL, NULL );
ClientId.UniqueProcess = (HANDLE)ulProcessID;
ClientId.UniqueThread = NULL;
__try
{
ntStatus = ZwOpenProcess( &hProcess, PROCESS_ALL_ACCESS, &ObjectAttributes, &ClientId );
if( NT_SUCCESS(ntStatus) )
{
ntStatus = ZwTerminateProcess( hProcess, 0 );
if( !NT_SUCCESS(ntStatus) )
DbgPrint( "ZwTerminateProcess failed with status : %08X\n", ntStatus );
ZwClose( hProcess );
}
else
DbgPrint( "ZwOpenProcess failed with status : %08X\n", ntStatus );
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
ntStatus = STATUS_UNSUCCESSFUL;
DbgPrint( "Exception caught in drvTerminateProcess()" );
}
return ntStatus;
}
</code></pre>
<p>To do this work I used the following function (<code>NewZwOpenProcess</code>) and replace it with the original <code>ZwOpenProcess</code> in SSDT but in x64 windows I don't know what should I do :( :</p>
<pre><code>NTSTATUS NewZwOpenProcess(
OUT PHANDLE ProcessHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN PCLIENT_ID ClientId OPTIONAL)
{
HANDLE ProcessId;
__try
{
ProcessId = ClientId->UniqueProcess;
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
return STATUS_INVALID_PARAMETER;
}
if (ProcessId == (HANDLE)11) //Check if the PID matches our protected process PID (My programm)
{
return STATUS_ACCESS_DENIED;
}
else
return OldZwOpenProcess(ProcessHandle, DesiredAccess,ObjectAttributes, ClientId);
}
</code></pre>
<p>Any idea ??</p>
<p>(Excuse me if my English is bad )</p>
| 0 | 1,222 |
AngularJS: lazy loading controllers and content
|
<p>In this simplified scenario, I have two files: index.htm, lazy.htm.</p>
<p>index.htm:</p>
<pre><code>var myApp = angular.module('myApp', []);
myApp.controller('embed',function($scope){
$scope.embed = 'Embedded Controller';
});
<div ng-controller="embed">{{embed}}</div>
<div ng-include="'lazy.htm'"></div>
</code></pre>
<p>lazy.htm</p>
<pre><code>myApp.controller('lazy',function($scope){
$scope.lazy = 'Lazy Controller';
});
<div ng-controller="lazy">
{{lazy}}
</div>
</code></pre>
<p>The result is an error: "Argument 'lazy' is not a function, got undefined"</p>
<p>Using a function instead</p>
<p>lazy.htm</p>
<pre><code>function lazy($scope) {
$scope.lazy = 'Lazy Controller';
}
<div ng-controller="lazy">
{{lazy}}
</div>
</code></pre>
<p>This works until version 1.3 beta 14. In beta 15 was removed the global controller functions: <a href="https://github.com/angular/angular.js/issues/8296" rel="noreferrer">https://github.com/angular/angular.js/issues/8296</a></p>
<p>So now, what is the better way to get angularized contents of lazy.htm dynamically?</p>
<p><strong>UPDATE:</strong></p>
<p>In this article (<a href="http://ify.io/lazy-loading-in-angularjs" rel="noreferrer">http://ify.io/lazy-loading-in-angularjs</a>) I found another possible solution. The $controllerProvider allow us to register new controllers after angular bootstrap. Works like a charm. Tested in <strong>v1.3.0-beta.18</strong></p>
<p>index.htm:</p>
<pre><code>var myApp = angular.module('myApp', [])
.controller('embed',function($scope){
$scope.embed = 'Embedded Controller';
})
.config(function($controllerProvider) {
myApp.cp = $controllerProvider;
});
<div ng-controller="embed">{{embed}}</div>
<div ng-include="'lazy.htm'"></div>
</code></pre>
<p>lazy.htm</p>
<pre><code>myApp.cp.register('lazy',function($scope){
$scope.lazy = 'Lazy Controller';
});
<div ng-controller="lazy">
{{lazy}}
</div>
</code></pre>
<p><strong>UPDATE 2:</strong></p>
<p>Two other alternatives that works are:</p>
<p>lazy.htm</p>
<pre><code>_app = $('[ng-app]').scope();
_app.lazy = function($scope) {
$scope.lazy = 'Lazy Controller';
};
</code></pre>
<p>OR</p>
<pre><code>var $rootScope = $('[ng-app]').injector().get('$rootScope');
$rootScope.lazy = function($scope) {
$scope.lazy = 'Lazy Controller';
};
</code></pre>
<p>But I believe these last two examples should not be used in production.</p>
| 0 | 1,032 |
Unknown Entity namespace alias in symfony2
|
<p>Hey I have two bundles in my symfony2 project. one is Bundle and the other one is PatentBundle. </p>
<p>My app/config/route.yml file is </p>
<pre><code>MunichInnovationGroupPatentBundle:
resource: "@MunichInnovationGroupPatentBundle/Controller/"
type: annotation
prefix: /
defaults: { _controller: "MunichInnovationGroupPatentBundle:Default:index" }
MunichInnovationGroupBundle:
resource: "@MunichInnovationGroupBundle/Controller/"
type: annotation
prefix: /v1
defaults: { _controller: "MunichInnovationGroupBundle:Patent:index" }
login_check:
pattern: /login_check
logout:
pattern: /logout
</code></pre>
<p>inside my controller i have </p>
<pre><code><?php
namespace MunichInnovationGroup\PatentBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use JMS\SecurityExtraPatentBundle\Annotation\Secure;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Security\Core\SecurityContext;
use MunichInnovationGroup\PatentBundle\Entity\Log;
use MunichInnovationGroup\PatentBundle\Entity\UserPatent;
use MunichInnovationGroup\PatentBundle\Entity\PmPortfolios;
use MunichInnovationGroup\PatentBundle\Entity\UmUsers;
use MunichInnovationGroup\PatentBundle\Entity\PmPatentgroups;
use MunichInnovationGroup\PatentBundle\Form\PortfolioType;
use MunichInnovationGroup\PatentBundle\Util\SecurityHelper;
use Exception;
/**
* Portfolio controller.
* @Route("/portfolio")
*/
class PortfolioController extends Controller {
/**
* Index action.
*
* @Route("/", name="v2_pm_portfolio")
* @Template("MunichInnovationGroupPatentBundle:Portfolio:index.html.twig")
*/
public function indexAction(Request $request) {
$portfolios = $this->getDoctrine()
->getRepository('MunichInnovationGroupPatentBundle:PmPortfolios')
->findBy(array('user' => '$user_id'));
// rest of the method
}
</code></pre>
<p><strong>Edit:</strong> </p>
<p>My Entity Class</p>
<pre><code><?php
namespace MunichInnovationGroup\PatentBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* MunichInnovationGroup\PatentBundle\Entity\PmPortfolios
*
* @ORM\Table(name="pm_portfolios")
* @ORM\Entity
*/
class PmPortfolios
{
/**
* @var string $id
*
* @ORM\Column(name="id", type="string", length=36, nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="UUID")
*/
private $id;
/**
* @var string $portfolioName
*
* @ORM\Column(name="portfolio_name", type="string", length=255, nullable=false)
*/
private $portfolioName;
/**
* @var text $description
*
* @ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* @var string $permalink
*
* @ORM\Column(name="permalink", type="string", length=255, nullable=false)
*/
private $permalink;
/**
* @var string $sharingCode
*
* @ORM\Column(name="sharing_code", type="string", length=255, nullable=false)
*/
private $sharingCode;
/**
* @var boolean $shared
*
* @ORM\Column(name="shared", type="boolean", nullable=false)
*/
private $shared;
/**
* @var integer $sharedPortfolioCalls
*
* @ORM\Column(name="shared_portfolio_calls", type="integer", nullable=true)
*/
private $sharedPortfolioCalls;
/**
* @var boolean $isDefault
*
* @ORM\Column(name="is_default", type="boolean", nullable=false)
*/
private $isDefault;
/**
* @var UmUsers
*
* @ORM\ManyToOne(targetEntity="UmUsers")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
* })
*/
private $user;
/**
* Get id
*
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* Set portfolioName
*
* @param string $portfolioName
*/
public function setPortfolioName($portfolioName)
{
$this->portfolioName = $portfolioName;
}
/**
* Get portfolioName
*
* @return string
*/
public function getPortfolioName()
{
return $this->portfolioName;
}
/**
* Set description
*
* @param text $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* @return text
*/
public function getDescription()
{
return $this->description;
}
/**
* Set permalink
*
* @param string $permalink
*/
public function setPermalink($permalink)
{
$this->permalink = $permalink;
}
/**
* Get permalink
*
* @return string
*/
public function getPermalink()
{
return $this->permalink;
}
/**
* Set sharingCode
*
* @param string $sharingCode
*/
public function setSharingCode($sharingCode)
{
$this->sharingCode = $sharingCode;
}
/**
* Get sharingCode
*
* @return string
*/
public function getSharingCode()
{
return $this->sharingCode;
}
/**
* Set shared
*
* @param boolean $shared
*/
public function setShared($shared)
{
$this->shared = $shared;
}
/**
* Get shared
*
* @return boolean
*/
public function getShared()
{
return $this->shared;
}
/**
* Set sharedPortfolioCalls
*
* @param integer $sharedPortfolioCalls
*/
public function setSharedPortfolioCalls($sharedPortfolioCalls)
{
$this->sharedPortfolioCalls = $sharedPortfolioCalls;
}
/**
* Get sharedPortfolioCalls
*
* @return integer
*/
public function getSharedPortfolioCalls()
{
return $this->sharedPortfolioCalls;
}
/**
* Set isDefault
*
* @param boolean $isDefault
*/
public function setIsDefault($isDefault)
{
$this->isDefault = $isDefault;
}
/**
* Get isDefault
*
* @return boolean
*/
public function getIsDefault()
{
return $this->isDefault;
}
/**
* Set user
*
* @param MunichInnovationGroup\PatentBundle\Entity\UmUsers $user
*/
public function setUser(\MunichInnovationGroup\PatentBundle\Entity\UmUsers $user)
{
$this->user = $user;
}
/**
* Get user
*
* @return MunichInnovationGroup\PatentBundle\Entity\UmUsers
*/
public function getUser()
{
return $this->user;
}
</code></pre>
<p>}</p>
<p>My bundle main class: MunichInnovationGroupPatentBundle.php</p>
<pre><code> <?php
namespace MunichInnovationGroup\PatentBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class MunichInnovationGroupPatentBundle extends Bundle
{
}
</code></pre>
<p>when i try to load localhost/web/app_dev.php/portfolio</p>
<p>It says</p>
<pre><code> Unknown Entity namespace alias 'MunichInnovationGroupPatentBundle'.
</code></pre>
<p>I am unable to figure out this error
please help me if anyone has any idea I googled it a lot :(</p>
<p>Thanks in advance
500 Internal Server Error - ORMException</p>
| 0 | 2,445 |
PHP: Illegal string-offset
|
<p>My <a href="http://www.github.com/audith/Persephone" rel="nofollow">open-source project</a> was working just fine, until I started to work on it after 6 month of break. Updated to latest XAMPP, and start getting tons of weird errors, one of which is as:</p>
<p>I have Input class, with a caller method as:</p>
<pre><code><?php
class Input
{
public function __call ( $name , $arguments )
{
if ( !in_array( $name, array( "post", "get", "cookie", "request", "server", "env" ) ) )
{
throw new Exception( "Input::" . $name . "() not declared!" );
}
$_name_of_superglobal = "_" . strtoupper( $name );
$_max_iteration_level_for_cleanup = in_array( $name, array( "server", "env" ) ) ? 1 : 10;
# $arguments[0] is the index of the value, to be fetched from within the array.
if ( !empty( $arguments[0] ) and array_key_exists( $arguments[0], $this->$name ) )
{
return $this->$name[ $arguments[0] ];
}
elseif ( !empty( $arguments[0] ) and array_key_exists( $arguments[0], $GLOBALS[ $_name_of_superglobal ] ) )
{
return $this->$name[ $this->clean__makesafe_key( $arguments[0] ) ] = $this->clean__makesafe_value( $GLOBALS[ $_name_of_superglobal ][ $arguments[0] ], array(), true );
}
elseif ( !empty( $arguments[0] ) and !array_key_exists( $arguments[0], $GLOBALS[ $_name_of_superglobal ] ) )
{
return null;
}
else
{
if ( $this->_is_cleanup_done_for[ $name ] === true )
{
return $this->$name;
}
$this->_is_cleanup_done_for[ $name ] = true;
return $this->$name = $this->clean__makesafe_recursively( $GLOBALS[ $_name_of_superglobal ], $_max_iteration_level_for_cleanup );
}
}
?>
</code></pre>
<p>This piece of code, works like this: you ask certain superglobal value from it, and it returns clean version of it, on-demand:</p>
<pre><code><?php
$input = new Input();
$server_name = $input->server("SERVER_NAME");
?>
</code></pre>
<p>Easy right? Well, after I updated PHP with XAMPP, it just doesn't work [edit: it works, with the Warning message] - error is:</p>
<pre><code>PHP Warning: Illegal string offset 'SERVER_NAME' in S:\...\kernel\input.php on line 159
</code></pre>
<p>line, which corresponds to line of code:</p>
<pre><code>return $this->$name[ $this->clean__makesafe_key( $arguments[0] ) ] = $this->clean__makesafe_value( $GLOBALS[ $_name_of_superglobal ][ $arguments[0] ], array(), true );
</code></pre>
<p>which is stupid: <code>$_name_of_superglobal</code> = "_SERVER" there, and <code>$arguments[0]</code> = "SERVER_NAME" and overall assignment is string which gets cleaned.</p>
<p>WHAT MIGHT BE THE PROBLEM THERE? I am totally lost here!</p>
| 0 | 1,238 |
How to copy a file in C/C++ with libssh and SFTP
|
<p>I want to copy a file from a client to a remote server, but I don't understand how to do it with the libssh library SFTP API.</p>
<p>The situation is that: The SSH session is open and the SFTP session is open too, I can create a file and write in it from the client to the server with the integrated function of libssh.</p>
<p>I did not find an easy way to copy a file from the client to the server with a simple function like <strong>sftp_transfer(sourceFile(like c:\my document\hello world.txt),RemoteFile(/home/user/hello world.txt),right(read and write))</strong> ?</p>
<p>With what I have understood from the tutorial it is first creating a file in the remote location (server) then it is opening this file with this line of code:</p>
<pre><code>file = sftp_open(sftp, "/home/helloworld.txt",access_type,1);
</code></pre>
<p>After that the file is created on the server, and then it is writing into this created file with a buffer:</p>
<pre><code>const char *helloworld = "Hello, World!\n";
int length = strlen(helloworld);
nwritten = sftp_write(file, helloworld, length);
</code></pre>
<p>My question is now if I have a file for example a .doc file and I want to transfer/upload that file from <code>c:\mydocument\document.doc</code> to remote the remote server <code>/home/user/document.doc</code>, how can I do it with this method ?</p>
<p>How can I put this file into the <code>sftp_write()</code> function to send it like the <a href="http://api.libssh.org/master/libssh_tutor_sftp.html" rel="nofollow noreferrer">helloworld in the sample function</a>?</p>
<p>I may be not good enough in programming to understand, but I really tried to understand it and I'm stuck with it.</p>
<p>Thanks in advance for your help</p>
<p>See below a sample of the code I used to test:</p>
<pre><code>// Set variable for the communication
char buffer[256];
unsigned int nbytes;
//create a file to send by SFTP
int access_type = O_WRONLY | O_CREAT | O_TRUNC;
const char *helloworld = "Hello, World!\n";
int length = strlen(helloworld);
//Open a SFTP session
sftp = sftp_new(my_ssh_session);
if (sftp == NULL)
{
fprintf(stderr, "Error allocating SFTP session: %s\n",
ssh_get_error(my_ssh_session));
return SSH_ERROR;
}
// Initialize the SFTP session
rc = sftp_init(sftp);
if (rc != SSH_OK)
{
fprintf(stderr, "Error initializing SFTP session: %s.\n",
sftp_get_error(sftp));
sftp_free(sftp);
return rc;
}
//Open the file into the remote side
file = sftp_open(sftp, "/home/helloworld.txt",access_type,1);
if (file == NULL)
{
fprintf(stderr, "Can't open file for writing: %s\n",ssh_get_error(my_ssh_session));
return SSH_ERROR;
}
//Write the file created with what's into the buffer
nwritten = sftp_write(file, helloworld, length);
if (nwritten != length)
{
fprintf(stderr, "Can't write data to file: %s\n",
ssh_get_error(my_ssh_session));
sftp_close(file);
return SSH_ERROR;
}
</code></pre>
| 0 | 1,089 |
Setting Icon for PyInstaller Application
|
<p>I have been all over Google, Reddit, StackOverflow, PyInstaller docs, I can't figure this out.</p>
<p>I'm trying to set my icon for my application, but it will not work. The icon is applied to the main exe, however, the icon does not show in the taskbar when it is open for Windows.</p>
<p>The icon is being included. I have set the value icon in EXE directly to the icon path. I have used <strong>Resource Hacker</strong>, I have used <strong>RCEDIT</strong>, which by the way, kills my application entirely. I, for the life of me, <strong>CANNOT</strong> get the icon of the application to show correctly.</p>
<p>I have tried Windows 10 and Windows 7.</p>
<p>Even when I run Pyinstaller without -F, it still won't load the icon. I'm 100% certain my file is an .ico file, and includes multiple acceptable sizes, Resource Hacker showed all acceptable sizes for the .ico.</p>
<hr>
<ul>
<li><a href="https://i.stack.imgur.com/BSVpM.png" rel="noreferrer">Title Bar of the App</a> </li>
<li><a href="https://i.stack.imgur.com/qwfB6.png" rel="noreferrer">App with the right icon, in the directory</a> </li>
<li><a href="https://i.stack.imgur.com/11xvw.png" rel="noreferrer">App icon on the taskbar</a></li>
</ul>
<hr>
<p>Here is the powershell command I'm using:</p>
<pre><code>pyinstaller -F -i C:\aNote\theme\anoteicon.ico --clean anotemain.spec
</code></pre>
<p>Here is my .spec</p>
<pre><code># -*- mode: python -*-
block_cipher = None
a = Analysis(['anotemain.py'],
pathex=['C:\\aNote'],
binaries=[],
datas=[('c:\\aNote\\theme\\anoteicon.png','theme'),
('c:\\aNote\\theme\\kabook.png','theme'),
('c:\\aNote\\theme\\Python.svg.png','theme'),
('c:\\aNote\\theme\\anoteicon.ico','.'),
('c:\\aNote\\anoteui.py','.'),
('c:\\aNote\\version.txt','.')],
hiddenimports=["PyQt5.sip", "QtGui", "QtWidgets", "pyperclip", "webbrowser", "csv"],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name='aNote',
debug=False,
strip=False,
upx=False,
clean=True,
runtime_tmpdir=None,
console=False,
icon='c:\\aNote\\theme\\anoteicon.ico',
version='version.txt')
</code></pre>
| 0 | 1,162 |
RPM build errors:Bad exit status from /var/tmp/rpm-tmp.32XJLX (%install)
|
<p>Im trying to create a simple rpm package on centos 6.5.. But i cannot finish it as its giving me errors.. I have already followed these two threads.. <a href="https://stackoverflow.com/questions/21595748/bad-exit-status-from-var-tmp-rpm-tmp-b1dgat-build">Bad exit status from /var/tmp/rpm-tmp.b1DgAt (%build)</a> and <a href="https://stackoverflow.com/questions/9283380/bad-exit-status-from-var-tmp-rpm-tmp-ajkra4-prep">Bad exit status from /var/tmp/rpm-tmp.ajKra4 (%prep)</a> .. yet no luck... </p>
<p>I cannot figure out what i'm missing here.. please help me to fix this.. </p>
<p>this is my </p>
<pre><code>Name: test
Version: 1.0
Release: 1%{?dist}
Summary: A test package
Group: Testing
License: GPL
URL: http://www.yahoo.com
Source0: test-1.0.tar.gz
BuildRoot: %(mktemp -ud %{_tmppath}/%{name}-%{version}-%{release}-XXXXXX)
BuildRequires: /bin/rm, /bin/mkdir, /bin/cp
Requires: /bin/bash, /bin/date
%description
this is the test package build for rhche
%prep
%setup -q
%build
./configure
%install
rm -rf $RPM_BUILD_ROOT
make -p $RPM_BUILD_ROOT/usr/local/bin
cp myscriptdate $RPM_BUILD_ROOT/usr/local/bin
%clean
rm -rf $RPM_BUILD_ROOT
%files
%defattr(-,root,root,-)
%attr(0755,root,root)/usr/local/bin/myscriptdate
%changelog
* Thu Dec 09 2010 Forrest <forrest@redhat.com> 1.0-1
-Initial RPM
-Added /usr/local/bin/myscript
</code></pre>
<p>Source directory is /test1</p>
<pre><code>[ara@catshit test1]$ pwd
/test1
[ara@catshit test1]$ ls -ls
total 12
4 drwxrwxrwx. 2 ara ara 4096 Dec 7 00:02 test-1.0
4 -rw-rw-r--. 1 ara ara 210 Dec 7 00:09 test-1.0.tar.gz
4 -rwxrwxrwx. 1 ara ara 742 Dec 7 00:17 test.spec
[ara@catshit test1]$
</code></pre>
<p>test-1.0 is compressed as test-1.0.tar.gz.
Inside test-1.0 I have script called myscriptdate which is having following simple code.. </p>
<p>'#!/bin/bash</p>
<p>date</p>
<p>when i try <code>rpmbuild -ba test.spec</code> it gives me </p>
<pre><code># Not a target:
.f:
# Implicit rule search has not been done.
# Modification time never checked.
# File has not been updated.
# commands to execute (built-in):
$(LINK.f) $^ $(LOADLIBES) $(LDLIBS) -o $@
# Not a target:
.f.o:
# Implicit rule search has not been done.
# Modification time never checked.
# File has not been updated.
# commands to execute (built-in):
$(COMPILE.f) $(OUTPUT_OPTION) $<
# files hash-table stats:
# Load=70/1024=7%, Rehash=0, Collisions=278/1660=17%
# VPATH Search Paths
# No `vpath' search paths.
# No general (`VPATH' variable) search path.
# # of strings in strcache: 0
# # of strcache buffers: 0
# strcache size: total = 0 / max = 0 / min = 4096 / avg = 0
# strcache free: total = 0 / max = 0 / min = 4096 / avg = 0
# Finished Make data base on Sun Dec 7 00:51:01 2014
error: Bad exit status from /var/tmp/rpm-tmp.ZFlmeu (%install)
RPM build errors:
Bad exit status from /var/tmp/rpm-tmp.ZFlmeu (%install)
</code></pre>
<p>/var/tmp/rpm-tmp.ZFlmeu content is below </p>
<pre><code>#!/bin/sh
RPM_SOURCE_DIR="/home/ara/rpmbuild/SOURCES"
RPM_BUILD_DIR="/home/ara/rpmbuild/BUILD"
RPM_OPT_FLAGS="-O2 -g"
RPM_ARCH="x86_64"
RPM_OS="linux"
export RPM_SOURCE_DIR RPM_BUILD_DIR RPM_OPT_FLAGS RPM_ARCH RPM_OS
RPM_DOC_DIR="/usr/share/doc"
export RPM_DOC_DIR
RPM_PACKAGE_NAME="test"
RPM_PACKAGE_VERSION="1.0"
RPM_PACKAGE_RELEASE="1.el6"
export RPM_PACKAGE_NAME RPM_PACKAGE_VERSION RPM_PACKAGE_RELEASE
LANG=C
export LANG
unset CDPATH DISPLAY ||:
RPM_BUILD_ROOT="/home/ara/rpmbuild/BUILDROOT/test-1.0-1.el6.x86_64"
export RPM_BUILD_ROOT
PKG_CONFIG_PATH="/usr/lib64/pkgconfig:/usr/share/pkgconfig"
export PKG_CONFIG_PATH
set -x
umask 022
cd "/home/ara/rpmbuild/BUILD"
cd 'test-1.0'
rm -rf $RPM_BUILD_ROOT
make -p $RPM_BUILD_ROOT/usr/local/bin
cp myscriptdate $RPM_BUILD_ROOT/usr/local/bin
/usr/lib/rpm/brp-compress
/usr/lib/rpm/brp-strip
/usr/lib/rpm/brp-strip-static-archive
/usr/lib/rpm/brp-strip-comment-note
</code></pre>
| 0 | 1,724 |
Correct way for parsing JSON objects containing arrays in Java Servlets (with Gson for example)
|
<p>I know this is a topic much talked about, but I still wasn't able to find a correct and clear answer to my specific problem.</p>
<p>I've got a JSON that looks like this:</p>
<pre><code>var myData = { "gameID" : gameID,
"nrOfPlayers" : 2,
"playerUIDs" : [123, 124]
};
</code></pre>
<p>The Question I have is exactly what is the correct way (or best way, style wise) to parse this in a Java servlet (using GSON for example)? First I send this JSON to the server using jQuery ajax method like this:</p>
<pre><code>jQuery.ajax({
url : path,
data : myData,
success : successFunction,
error : function(data) {
console.log("Error: ", data);
} ,
type : "post",
timeout : 30000
});
</code></pre>
<p>Now in the servlet I've learned that I should have been able to parse that JSON like this:</p>
<pre><code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
String gameID = gson.fromJson(request.getParameter("gameID"), String.class);
String nrOfPlayers = gson.fromJson(request.getParameter("nrOfPlayers"), String.class);
String[] playerUIDs = gson.fromJson(request.getParameter("playerUIDs"), String[].class);
log.info(gameID);
log.info(nrOfPlayers);
log.info(playerUIDs[0] +" "+ playerUIDs[1]);
}
</code></pre>
<p><strong>But the playerUIDs variable IS NULL and of course playerUIDs[0] throws an exception!</strong></p>
<p>Digging deeper I found that when looping over the request parameter names, it contained a <strong>parameter named "playerUIDs[]"</strong> with the <strong>value of only 123</strong> (the first int in the array). This was strange cause I didn't seem to be able to access the next values at all.</p>
<p>Then I read that JSON objects should be stringifyed before POST-ing so I added JSON.stringify(myData), but now the request parameter names only <strong>contained ONE name</strong> which was the JSON object itself in a stringified state:</p>
<pre><code>INFO: Parameter name = {"gameID":"b6a51aabb8364b04bce676eafde1bc87","nrOfPlayers":2,"playerUIDs":[123,124]}
</code></pre>
<p>The only way I seemed to get this to work was by creating a inner class:</p>
<pre><code>class GameStart {
protected String gameID;
protected int nrOfPlayers;
protected int[] playerUIDs;
}
</code></pre>
<p>And parsing the JSON from the request parameter name, like this:</p>
<pre><code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
Enumeration en = request.getParameterNames();
GameStart start = null;
while (en.hasMoreElements()) {
start = gson.fromJson((String) en.nextElement(), GameStart.class);
}
log.info(start.gameID);
log.info(String.valueOf(start.nrOfPlayers));
log.info(start.playerUIDs[0] +" "+ start.playerUIDs[1]);
}
</code></pre>
<p>Now all values are there, but this seems more like a hack (reading JSON from request parameter name) than an elegant solution, so I thought I'd ask you guys what exactly would be the "correct" way of doing this? Am I missing something obvious?</p>
<p>Thanks in advance!</p>
| 0 | 1,221 |
warning:Multiple versions of scala libraries detected?
|
<p>My project is maven+intellij.
And I develop in windows system.
firstly I use the lastest scala libray version 2.12.2.For getting the class SQLContext and so on,I have to import spark jar:
<a href="https://i.stack.imgur.com/bn0hG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bn0hG.png" alt="enter image description here"></a></p>
<p>but then I was told that if I want to use this spark jar,I have to lower my scala version,So I delete the libiray and changed to 2.10....but now when I mvn_clean_install.I got this :</p>
<pre><code>[WARNING] Expected all dependencies to require Scala version: 2.11.7
[WARNING] com.twitter:chill_2.11:0.5.0 requires scala version: 2.11.7
[WARNING] com.typesafe.akka:akka-remote_2.11:2.3.11 requires scala version: 2.11.7
[WARNING] com.typesafe.akka:akka-actor_2.11:2.3.11 requires scala version: 2.11.7
[WARNING] com.typesafe.akka:akka-slf4j_2.11:2.3.11 requires scala version: 2.11.7
[WARNING] org.apache.spark:spark-core_2.11:1.6.1 requires scala version: 2.11.7
[WARNING] org.json4s:json4s-jackson_2.11:3.2.10 requires scala version: 2.11.7
[WARNING] org.json4s:json4s-core_2.11:3.2.10 requires scala version: 2.11.7
[WARNING] org.json4s:json4s-ast_2.11:3.2.10 requires scala version: 2.11.7
[WARNING] org.json4s:json4s-core_2.11:3.2.10 requires scala version: 2.11.0
[WARNING] Multiple versions of scala libraries detected!
[INFO] E:\...\src\main\scala:-1: info: compiling
[INFO] Compiling 4 source files to E:\...\target\classes at 1491813951772
[ERROR] E:\...\qubole\mapreduce\ConvertToParquetFormat.scala:2: error: object sql is not a member of package org.apache.spark
[ERROR] import org.apache.spark.sql.SQLContext
[ERROR] ^
[ERROR] E:\...\qubole\mapreduce\ConvertToParquetFormat.scala:15: error: not found: type SQLContext
[ERROR] val sqlContext = new SQLContext(sc)
[ERROR] ^
[ERROR] E:\...\mapreduce\ConvertToParquetFormat.scala:24: error: value toDF is not a member of org.apache.spark.rdd.RDD[....qubole.mapreduce.ConvertToParquetFormat.OmnitureHit]
[ERROR] possible cause: maybe a semicolon is missing before `value toDF'?
[ERROR] .toDF().write.parquet ("file:///C:/Users/Desktop/456")
[ERROR] ^
[ERROR] three errors found
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 03:00 min
[INFO] Finished at: 2017-04-10T16:45:58+08:00
[INFO] Final Memory: 33M/360M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal net.alchim31.maven:scala-maven-plugin:3.2.0:compile (scala-compile-first) on project packages-omniture-qubole-mapreduce: wrap: org.apache.commons.exec.ExecuteException: Process exited with an er
ror: 1 (Exit value: 1) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
E:\github\mia\packages-omniture-qubole-mapreduce>
</code></pre>
<p>so I delete the scala 10 version ,and it told me I do not have one scala libray.then I add a scala 2.11.since it looks like some jars need 2.11 version still <code>Multiple versions of scala libraries detected?</code></p>
<p>But when I ctrl+left_cilck the word SQLContext, I can go to the page ,but it is anonymous.</p>
<p><a href="https://i.stack.imgur.com/pnFko.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/pnFko.jpg" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/MJa8i.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/MJa8i.jpg" alt="enter image description here"></a>
Is that because I forget to delete something about the old jar or libary?
and this is my left dependence list:
<a href="https://i.stack.imgur.com/1mfhb.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/1mfhb.jpg" alt="enter image description here"></a><a href="https://i.stack.imgur.com/9JLhJ.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/9JLhJ.jpg" alt="enter image description here"></a><a href="https://i.stack.imgur.com/Uw1Xi.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Uw1Xi.jpg" alt="enter image description here"></a></p>
<p>this is my pom.xml:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.company.www</groupId>
<artifactId>packages-omniture-qubole-mapreduce</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>com.company.www.platform</groupId>
<artifactId>platform-parent-spark</artifactId>
<version>0.1.41</version>
</parent>
<properties>
<spark.mapreduce.mainclass>com.company.www.packages.omniture.qubole.mapreduce.SampleMapReduceJob</spark.mapreduce.mainclass>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_${scala.major.minor.version}</artifactId>
<version>${spark.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.company.www.commons</groupId>
<artifactId>commons-spark</artifactId>
<version>[1.0.17, ]</version>
</dependency>
<dependency>
<groupId>com.company.www</groupId>
<artifactId>exp-user-interaction-messages-v1</artifactId>
<version>[1.4,]</version>
</dependency>
<dependency>
<groupId>org.scalaj</groupId>
<artifactId>scalaj-http_${scala.major.minor.version}</artifactId>
<version>1.1.4</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.parboiled</groupId>
<artifactId>parboiled-java</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>packages-omniture-qubole-mapreduce</finalName>
<shadedArtifactAttached>false</shadedArtifactAttached>
<artifactSet>
<includes>
<include>*:*</include>
</includes>
</artifactSet>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>reference.conf</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
<resource>log4j.properties</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>${spark.mapreduce.mainclass}</mainClass>
</transformer>
</transformers>
<relocations>
<relocation>
<pattern>org.eclipse.jetty</pattern>
<shadedPattern>org.spark-project.jetty</shadedPattern>
<includes>
<include>org.eclipse.jetty.**</include>
</includes>
</relocation>
<relocation>
<pattern>com.google.common</pattern>
<shadedPattern>org.spark-project.guava</shadedPattern>
<excludes>
<exclude>com/google/common/base/Absent*</exclude>
<exclude>com/google/common/base/Function</exclude>
<exclude>com/google/common/base/Optional*</exclude>
<exclude>com/google/common/base/Present*</exclude>
<exclude>com/google/common/base/Supplier</exclude>
</excludes>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
</code></pre>
| 0 | 5,988 |
Why I am getting "Not Implemented Error: Database objects do not implement truth value testing or bool()." while running makemigration cmd in django
|
<p>I am trying to connect Django with MongoDB using Djongo. I have changed the Database parameter but I am getting this error <em>Not Implemented Error: Database objects do not implement truth value testing or bool().</em> when I am running makemigration command.</p>
<p>Please can anybody explain why I am getting this error and how to resolve it?</p>
<p>I have include settings.py file, error log and mongodb compass setup image.</p>
<p><strong>settings.py</strong></p>
<pre><code>"""
Django settings for Chatify project.
Generated by 'django-admin startproject' using Django 3.2.9.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-1k4mo05el_0112guspx^004n-i&3h#u4gyev#27u)tkb8t82_%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api.apps.ApiConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Chatify.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'Chatify.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
# }
# }
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'users',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
</code></pre>
<p><strong>Error Log</strong></p>
<pre><code>File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 367, in run_from_argv
connections.close_all()
File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\utils.py", line 213, in close_all
connection.close()
File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\asyncio.py", line 33, in inner
return func(*args, **kwargs)
File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\base\base.py", line 294, in close
self._close()
File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\djongo\base.py", line 208, in _close
if self.connection:
File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\pymongo\database.py", line 829, in __bool__
raise NotImplementedError("Database objects do not implement truth "
NotImplementedError: Database objects do not implement truth value testing or bool(). Please compare with None instead: database is not None
</code></pre>
<p><strong>MongoDBCompass</strong>
<a href="https://i.stack.imgur.com/OSNPV.png" rel="noreferrer">MongoDB Local Database Image</a></p>
| 0 | 2,337 |
How to make GET requests to other Feign clients inside of a POST request?
|
<p>I have a REST API endpoint that makes use of several Feign clients to perform validation and processing. The endpoint in question accepts a POST request, but the Feign clients used for validation accept GET requests. When I make a POST request to my API endpoint I get the error below from the Feign clients that require a GET. I have my Feign clients methods annotated with <code>@GetMapping</code>, but it seems the request is still being sent as a POST. How do I make GET requests to Feign clients inside a POST request?</p>
<pre><code>feign.FeignException: status 405 reading ValidationClient#checkData(String); content:
{"timestamp":"2018-08-06T14:43:45.998+0000","status":405,"error":"Method Not Allowed","message":"Request method 'POST' not supported","path":"/"}
at feign.FeignException.errorStatus(FeignException.java:62) ~[feign-core-9.5.1.jar:na]
at feign.codec.ErrorDecoder$Default.decode(ErrorDecoder.java:91) ~[feign-core-9.5.1.jar:na]
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:138) ~[feign-core-9.5.1.jar:na]
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76) ~[feign-core-9.5.1.jar:na]
at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103) ~[feign-core-9.5.1.jar:na]
at com.sun.proxy.$Proxy129.checkFormat(Unknown Source) ~[na:na]
at com.example.datainput.DataInputController.acceptData(DataInputController.java:20) ~[classes/:na]
at sun.reflect.GeneratedMethodAccessor126.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:45005) ~[na:1.8.0_172]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_172]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.StandardContextValve.__invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:40002) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471) [tomcat-embed-core-8.5.32.jar:8.5.32]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.32.jar:8.5.32]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_172]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_172]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.32.jar:8.5.32]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_172]
</code></pre>
<p><strong>Edit:</strong></p>
<p>Feign Client</p>
<pre><code>@FeignClient("validation")
public interface ValidationClient {
@GetMapping("/")
boolean checkFormat(String data);
}
</code></pre>
<p>The controller of the client</p>
<pre><code>@RestController
public class ValidationController {
@Autowired
ValidationProperties properties;
@GetMapping("/")
public boolean isValidFormat(@RequestParam String inputData) {
return inputData.matches(properties.getValidFormat());
}
</code></pre>
<p>}</p>
<p>The REST endpoint that uses the client</p>
<pre><code>@RestController
public class DataInputController {
@Autowired
ValidationClient validationClient;
@PostMapping("/")
public String saveData(@RequestParam(name = "inputData") String inputData) {
if (!validationClient.checkFormat(inputData)) {
return "Invalid Format";
}
// save data here
return "Input Success";
}
}
</code></pre>
<p>I am using version FINCHLEY.SR1</p>
<p><strong>Edit 2:</strong></p>
<p>I've noticed that my Feign clients in my controller seem to be misconfigured.
They are of type <code>HardCodedTarget</code> and the url property just <code>http://<service-name></code> (in this case <code>http://validation</code>), it doesnt actually point to the real service the client is supposed to be using. </p>
<p><strong>Edit 3:</strong>
I added Ribbon</p>
<pre><code><dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
</code></pre>
<p>to my service applications and to my api that is using the Feign clients. Unfortunately I am still having the same issue. I have refreshed and rebuilt everything.</p>
<p><strong>Edit 4:</strong>
I have created a GitHub project for this question. </p>
<p><a href="https://github.com/zero01alpha/spring-cloud-demo" rel="nofollow noreferrer">https://github.com/zero01alpha/spring-cloud-demo</a></p>
<p>the input-entry module uses the input-format and input-parse modules as Feign clients to validate the length and parse/print items of an input string. I have been using the alphabet as input so the minimum length for the input parameter is set to 26. input-format runs on port 8080, input-parse on 8081, and input-entry on 8082, all using the default path <code>/</code> as their only endpoint and requiring a request param named <code>input</code>. So to recreate the issue I'm having</p>
<ol>
<li>Start Config server</li>
<li>Start Eureka Server</li>
<li>Start input-format service</li>
<li>Start input-parse service</li>
<li>Start input-entry service</li>
</ol>
<p>Then, send a POST request to <code>localhost:8082</code> with a request param of <code>input</code> that is at least 26 characters. When I do this I get this response body.</p>
<pre><code>{
"timestamp": "2018-08-09T13:29:34.536+0000",
"status": 500,
"error": "Internal Server Error",
"message": "status 405 reading InputFormatClient#checkFormat(String); content:\n{\"timestamp\":\"2018-08-09T13:29:34.504+0000\",\"status\":405,\"error\":\"Method Not Allowed\",\"message\":\"Request method 'POST' not supported\",\"path\":\"/\"}",
"path": "/"
}
</code></pre>
| 0 | 4,565 |
How to create and update a file in a Github repository with PHP and Github API?
|
<p>I am trying to build PHP functions to create and update files within a Github repository, using PHP through the Github API. </p>
<p><em>The PHP files are being run from a standard shared hosting account. Therefore using frameworks that depend on installing Composer or other libraries is not an option for me. So for example, this <a href="https://github.com/KnpLabs/php-github-api" rel="noreferrer">https://github.com/KnpLabs/php-github-api</a> is not an option.</em></p>
<p><strong>So far</strong></p>
<p>I have managed to access and list files using PHP, using the info given here:</p>
<p><a href="https://stackoverflow.com/questions/14390090/github-api-list-all-repositories-and-repos-content">Github API List all repositories and repo's content</a></p>
<p>I used a combination of the 2nd and 6th answer (2nd starts with <em>Here is a nice way just with the curl.</em> by flesheater and 6th answer with <em>When you say "display a repo and its contents"</em> by Ivan Zuzak).</p>
<p>Both list clearly the code and steps needed to list files and get contents (thank you @flesheater and @Ivan Zuzak)</p>
<p>I searched for help or solutions for this. So far I have not found any example, working or otherwise, using PHP.</p>
<p><strong>Git API documentation</strong></p>
<p>Git Data API info (<a href="https://developer.github.com/v3/git/" rel="noreferrer">https://developer.github.com/v3/git/</a>) says this:</p>
<blockquote>
<p>As an example, if you wanted to commit a change to a file in your
repository, you would:</p>
<pre><code>get the current commit object
retrieve the tree it points to
retrieve the content of the blob object that tree has for that particular file path
change the content somehow and post a new blob object with that new content, getting a blob SHA back
post a new tree object with that file path pointer replaced with your new blob SHA getting a tree SHA back
create a new commit object with the current commit SHA as the parent and the new tree SHA, getting a commit SHA back
update the reference of your branch to point to the new commit SHA
</code></pre>
</blockquote>
<p>However there are no code examples of how this is done, and I am not sure if 'commit' is what i need (if I understand correctly, this is not creating a file, only content).</p>
<p>Git Repository API info (<a href="https://developer.github.com/v3/repos/contents/#create-a-file" rel="noreferrer">https://developer.github.com/v3/repos/contents/#create-a-file</a>):</p>
<p>The part 'Create a File' shows a method for doing this, but without code examples. I am usure how to or if this can be used prgrammatically.</p>
<h2><a href="https://i.stack.imgur.com/oi5eZ.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/oi5eZ.jpg" alt="Github API Update a File"></a></h2>
<p><strong>Similar threads</strong></p>
<p>In my opinion none are offering enough clarity or information to provide a solution, due to either the questions or answers. Therefore I don't think this is a duplicate.</p>
<p><a href="https://stackoverflow.com/questions/11801983/how-to-create-a-commit-and-push-into-repo-with-github-api-v3">How to create a commit and push into repo with GitHub API v3?</a></p>
<p>This thread has two answers. One is just a link to the Github API which does not give code examples. The other is a Pearl solution (it would seem), but is using a separate Pearlframework.So even trying to convert the Pearl shown is not practical.</p>
<p><a href="https://stackoverflow.com/questions/23152702/how-to-create-github-repository-and-upload-files-from-php">How to create github Repository and upload files from PHP?</a></p>
<p>The answer only repeats the other thread, that a blob should be created. But this is only the very start of what seems to be needed to actually create / update a file through Github API. This thread has a Python example, but that example needs a separate Pearl framework.</p>
<p><a href="https://stackoverflow.com/questions/6668283/github-api-write-to-repo/7506554">GitHub API - write to repo</a></p>
<p>This is the thread linked to. It's answered by user who posted a not very clear question, but without any details or clarity.</p>
| 0 | 1,264 |
Parsing nested XML with ElementTree
|
<p>I have the following XML format, and I want to pull out the values for name, region, and status using python's xml.etree.ElementTree module.</p>
<p>However, my attempt to get this information has been unsuccessful so far.</p>
<pre><code><feed>
<entry>
<id>uuid:asdfadsfasdf123123</id>
<title type="text"></title>
<content type="application/xml">
<NamespaceDescription xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Name>instancename</Name>
<Region>US</Region>
<Status>Active</Status>
</NamespaceDescription>
</content>
</entry>
<entry>
<id>uuid:asdfadsfasdf234234</id>
<title type="text"></title>
<content type="application/xml">
<NamespaceDescription xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Name>instancename2</Name>
<Region>US2</Region>
<Status>Active</Status>
</NamespaceDescription>
</content>
</entry>
</feed>
</code></pre>
<p>My code attempt:</p>
<pre><code>NAMESPACE = '{http://www.w3.org/2005/Atom}'
root = et.fromstring(XML_STRING)
entry_root = root.findall('{0}entry'.format(NAMESPACE))
for child in entry_root:
content_node = child.find('{0}content'.format(NAMESPACE))
for content in content_node:
for desc in content.iter():
print desc.tag
name = desc.find('{0}Name'.format(NAMESPACE))
print name
</code></pre>
<p>desc.tag is giving me the nodes I want to access, but name is returning None. Any ideas what's wrong with my code?</p>
<p>Output of desc.tag:</p>
<pre><code>{http://schemas.microsoft.com/netservices/2010/10/servicebus/connect}Name
{http://schemas.microsoft.com/netservices/2010/10/servicebus/connect}Region
{http://schemas.microsoft.com/netservices/2010/10/servicebus/connect}Status
</code></pre>
| 0 | 1,062 |
NotificationChannel issue in Android O
|
<p>I am getting a toast saying "Developer warning for package com.google.android.apps.messaging" when sending an MMS using Android Messages ver 2.3.063.</p>
<p>In logs</p>
<pre><code>08-12 16:57:52.368 7661 7682 W Notification: Use of stream types is deprecated for operations other than volume control
08-12 16:57:52.368 7661 7682 W Notification: See the documentation of setSound() for what to use instead with android.media.AudioAttributes to qualify your playback use case
08-12 16:57:52.369 1604 3146 E NotificationService: No Channel found for pkg=com.google.android.apps.messaging, channelId=miscellaneous, id=5, tag=null, opPkg=com.google.android.apps.messaging, callingUid=10130, userId=0, incomingUserId=0, notificationUid=10130, notification=Notification(channel=miscellaneous pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x8 color=0xff2a56c6 vis=PRIVATE)
08-12 16:57:52.375 1604 3094 D CompatibilityInfo: mCompatibilityFlags - 0
08-12 16:57:52.375 1604 3094 D CompatibilityInfo: applicationDensity - 480
08-12 16:57:52.375 1604 3094 D CompatibilityInfo: applicationScale - 1.0
08-12 16:57:52.378 7661 7682 I BugleNotifications: Notifying for tag = null, type = RESIZING_NOTIFICATION_ID, notification = Notification(channel=miscellaneous pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x8 color=0xff2a56c6 vis=PRIVATE)
08-12 16:57:52.381 7661 8893 W Notification: Use of stream types is deprecated for operations other than volume control
08-12 16:57:52.381 7661 8893 W Notification: See the documentation of setSound() for what to use instead with android.media.AudioAttributes to qualify your playback use case
08-12 16:57:52.384 1604 1618 E NotificationService: No Channel found for pkg=com.google.android.apps.messaging, channelId=miscellaneous, id=5, tag=null, opPkg=com.google.android.apps.messaging, callingUid=10130, userId=0, incomingUserId=0, notificationUid=10130, notification=Notification(channel=miscellaneous pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x8 color=0xff2a56c6 vis=PRIVATE)
08-12 16:57:52.384 880 1657 W StreamHAL: Error from HAL stream in function get_presentation_position: Operation not permitted
08-12 16:57:52.387 7661 8893 I BugleNotifications: Notifying for tag = null, type = RESIZING_NOTIFICATION_ID, notification = Notification(channel=miscellaneous pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x8 color=0xff2a56c6 vis=PRIVATE)
08-12 16:57:52.390 1604 1647 E NotificationService: No Channel found for pkg=com.google.android.apps.messaging, channelId=miscellaneous, id=5, tag=null, opPkg=com.google.android.apps.messaging, callingUid=10130, userId=0, incomingUserId=0, notificationUid=10130, notification=Notification(channel=miscellaneous pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x48 color=0xff2a56c6 vis=PRIVATE)
</code></pre>
<p>Google Play services ver 11.3.02<br>
Android Messages 2.3.063<br>
Android 8.0.0<br></p>
<p>Anyone up there to help me ? <a href="https://i.stack.imgur.com/Uwmdy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Uwmdy.png" alt="Screenshot"></a></p>
| 0 | 1,055 |
Struts2: How to pass a values from one action to another action. Or from one JSP to another JSP. Without using session
|
<p>Hi I am building a project using Struts2. However during the development I am facing many issues. The biggest issue is Session management in Struts2. There is very limited information related to this.</p>
<p>I have hunt for the solution to my problem but got only limited information that does not satisfy my needs.</p>
<p>I do not wish to use container's session (Apache Tomcat 7) as it will become an overhead when multiple user would try to use the application.</p>
<p>I have created 2 Action classes and 2 JSPs.
The values entered in JSP1 (Login.jsp and LoginAction.java POJO) should be used in another action (HomeAction.java POJO) and later they should display in subsequent JSPs (Home.jsp).</p>
<p>I am using tiles as well.</p>
<p>I have tried using tag but I cannot able to set a value to it.</p>
<p>In Struts2,
How could I pass an object on a JSP1/Action to another Action/JSP2 ?</p>
<p>A small Login page example would be appreciated.
e.g. A username entered in a text field should display to another JSP page using 2 different Action classes.</p>
<p><strong>struts.xml</strong></p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<constant name="struts.custom.i18n.resources" value="ApplicationResources" />
<package name="default" extends="struts-default">
<result-types>
<result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<action name="login" class="org.myaction.LoginAction" method="validateLoginCredentials">
<result name="autheticatedUser" type="redirect" >homePage</result>
<result name="fail" >/jsp/Login.jsp</result>
</action>
<action name="homePage" class="org.myaction.HomeAction" method="execute">
<result name="responseOK" type="tiles" >/tile.NextPage</result>
<result name="error" type="tiles" >/tile.HomePage</result>
</action>
</package>
</struts>
</code></pre>
<p><strong>LoginAction.java</strong></p>
<pre><code> public class LoginAction extends ActionSupport {
//private static final String SUCCESS = "success";
private static final String FAIL = "fail";
private String userName;
private String password;
public String getUserName() { return userName; }
public void setUserName(String userName) { this.userName = userName; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public String validateLoginCredentials() {
if(this.userName.equals("admin")
&& this.password.equals("allow")) {
return "autheticatedUser";
}
addActionError(getText("error.login"));
return FAIL;
}
}
</code></pre>
<p><strong>web.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Login</display-name>
<context-param>
<param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>
<listener>
<listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>/jsp/Login.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
</code></pre>
<p>My question is,
In Struts2,
How could I pass the <strong>userName</strong> from <strong>Login.jsp/LoginAction.java</strong> to <strong>Home.jsp/HomeAction.java</strong> ? </p>
<p>Note: Storing into session is not preferred option but could use if there is no other way to maintain the user state in Struts2.</p>
<p>A small Login page example would be appreciated.
e.g. A username entered in a text field should display to another JSP page using 2 different Action classes.</p>
<p><strong>Edited</strong></p>
<p>Hi thank you! I really appreciate your reply. I presume this would work. There is one more thing I forgot to mention.
An another class(JavaBean) property is present in LoginAction.java class. </p>
<pre><code>public class LoginAction extends ActionSupport {
private UserData userData;
public void setUserData(UserData userData) {
this.userData = userData;
}
public String getUserData() {
return userData;
}
}
</code></pre>
<p>UserData.java</p>
<pre><code>public class UserData {
private String userName;
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
}
</code></pre>
<p>how can I set the userName property of UserData object which is in
LoginAction.java ?</p>
<p>I've tried this</p>
<pre><code><s:hidden name="userData.userName" value="userName" />
</code></pre>
<p>but it's not working....</p>
<p>Do you know what mistake I am making here?</p>
| 0 | 2,390 |
PHP Sort Array By SubArray Value
|
<p>I have the following array structure:</p>
<pre><code>Array
(
[0] => Array
(
[configuration_id] => 10
[id] => 1
[optionNumber] => 3
[optionActive] => 1
[lastUpdated] => 2010-03-17 15:44:12
)
[1] => Array
(
[configuration_id] => 9
[id] => 1
[optionNumber] => 2
[optionActive] => 1
[lastUpdated] => 2010-03-17 15:44:12
)
[2] => Array
(
[configuration_id] => 8
[id] => 1
[optionNumber] => 1
[optionActive] => 1
[lastUpdated] => 2010-03-17 15:44:12
)
)
</code></pre>
<p>What is the best way to order the array in an incremental way, based on the <code>optionNumber</code>?</p>
<p>So the results look like:</p>
<pre><code>Array
(
[0] => Array
(
[configuration_id] => 8
[id] => 1
[optionNumber] => 1
[optionActive] => 1
[lastUpdated] => 2010-03-17 15:44:12
)
[1] => Array
(
[configuration_id] => 9
[id] => 1
[optionNumber] => 2
[optionActive] => 1
[lastUpdated] => 2010-03-17 15:44:12
)
[2] => Array
(
[configuration_id] => 10
[id] => 1
[optionNumber] => 3
[optionActive] => 1
[lastUpdated] => 2010-03-17 15:44:12
)
)
</code></pre>
| 0 | 1,379 |
tarfile compressionerror bz2 module is not available
|
<p>I'm trying to install twisted
pip install <a href="https://pypi.python.org/packages/18/85/eb7af503356e933061bf1220033c3a85bad0dbc5035dfd9a97f1e900dfcb/Twisted-16.2.0.tar.bz2#md5=8b35a88d5f1a4bfd762a008968fddabf" rel="nofollow">https://pypi.python.org/packages/18/85/eb7af503356e933061bf1220033c3a85bad0dbc5035dfd9a97f1e900dfcb/Twisted-16.2.0.tar.bz2#md5=8b35a88d5f1a4bfd762a008968fddabf</a></p>
<p>This is for a <code>django-channels</code> project and I'm having the following error problem</p>
<pre><code>Exception:
Traceback (most recent call last):
File "/home/petarp/.virtualenvs/ErasmusCloneFromGitHub/lib/python3.5/tarfile.py", line 1655, in bz2open
import bz2
File "/usr/local/lib/python3.5/bz2.py", line 22, in <module>
from _bz2 import BZ2Compressor, BZ2Decompressor
ImportError: No module named '_bz2'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/petarp/.virtualenvs/CloneFromGitHub/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main
status = self.run(options, args)
File "/home/petarp/.virtualenvs/ErasmusCloneFromGitHub/lib/python3.5/site-packages/pip/commands/install.py", line 310, in run
wb.build(autobuilding=True)
File "/home/petarp/.virtualenvs/ErasmusCloneFromGitHub/lib/python3.5/site-packages/pip/wheel.py", line 750, in build
self.requirement_set.prepare_files(self.finder)
File "/home/petarp/.virtualenvs/ErasmusCloneFromGitHub/lib/python3.5/site-packages/pip/req/req_set.py", line 370, in prepare_files
ignore_dependencies=self.ignore_dependencies))
File "/home/petarp/.virtualenvs/ErasmusCloneFromGitHub/lib/python3.5/site-packages/pip/req/req_set.py", line 587, in _prepare_file
session=self.session, hashes=hashes)
File "/home/petarp/.virtualenvs/ErasmusCloneFromGitHub/lib/python3.5/site-packages/pip/download.py", line 810, in unpack_url
hashes=hashes
File "/home/petarp/.virtualenvs/ErasmusCloneFromGitHub/lib/python3.5/site-packages/pip/download.py", line 653, in unpack_http_url
unpack_file(from_path, location, content_type, link)
File "/home/petarp/.virtualenvs/ErasmusCloneFromGitHub/lib/python3.5/site-packages/pip/utils/__init__.py", line 605, in unpack_file
untar_file(filename, location)
File "/home/petarp/.virtualenvs/ErasmusCloneFromGitHub/lib/python3.5/site-packages/pip/utils/__init__.py", line 538, in untar_file
tar = tarfile.open(filename, mode)
File "/home/petarp/.virtualenvs/ErasmusCloneFromGitHub/lib/python3.5/tarfile.py", line 1580, in open
return func(name, filemode, fileobj, **kwargs)
File "/home/petarp/.virtualenvs/ErasmusCloneFromGitHub/lib/python3.5/tarfile.py", line 1657, in bz2open
raise CompressionError("bz2 module is not available")
tarfile.CompressionError: bz2 module is not available
</code></pre>
<p>Clearly I'm missing <code>bz2</code> module, so I've tried to installed it manually, but that didn't worked out for <code>python 3.5</code>, so how can I solved this?</p>
<p>I've did what @e4c5 suggested but I did it for <code>python3.5.1</code>, the output is</p>
<pre><code>➜ ~ python3.5
Python 3.5.1 (default, Apr 19 2016, 22:45:11)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import bz2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/bz2.py", line 22, in <module>
from _bz2 import BZ2Compressor, BZ2Decompressor
ImportError: No module named '_bz2'
>>>
[3] + 18945 suspended python3.5
➜ ~ dpkg -S /usr/local/lib/python3.5/bz2.py
dpkg-query: no path found matching pattern /usr/local/lib/python3.5/bz2.py
</code></pre>
<p>I am on Ubuntu 14.04 LTS and I have installed python 3.5 from source.</p>
| 0 | 1,579 |
Howto publish private projects to Sinopia (npm adduser for private registry fails)
|
<p>Ok so I finally managed to get a private npm registry using Sinopia. <strong>But I cannot publish anything to it.</strong></p>
<blockquote>
<p>TL;DR: Sinopia does not support <em>npm adduser</em>, but has its own user
management. Also npm needs a valid user created before <em>npm publish</em>
through <em>npm adduser</em>, which fails because the internal Sinopia server
throws an error at the unsupported command....</p>
</blockquote>
<h3>How does one use Sinopia as a private registry with proper users and passwords</h3>
<ol>
<li>create a global user in npmjs.org, and then another with the same password in Sinopia? </li>
<li>Or is there an easier way to tell npm to just use a fixed user/pass. </li>
<li>Or even better prompt me somehow for username and password?</li>
<li>something else?</li>
</ol>
<hr>
<p>Synopsis: </p>
<p>Sinopia does not depend on Couch.DB and will hapilly fetch packages it does not already have from a master (default is the global npmjs.org).</p>
<p>Sinopia starts perfectly and is configured to listen on all interfaces. It works wonders in serving packages to </p>
<pre><code>npm install
</code></pre>
<p>I even configured ~/.npmrc to always point to the internal registry.</p>
<p>All projects' package.json file is set to </p>
<pre><code> ....
"publishConfig" : {
"registry" : "http://internal-npm:4873"
},
....
</code></pre>
<p>Also I managed to add custom users in sinopia by manipulating the config.yaml with the help of js-yaml</p>
<pre><code>crypto.createHash('sha1').update('theBigPassword').digest('hex')
</code></pre>
<p>Now I am stuck at </p>
<pre><code>npm --registry=http://internal-npm:4873 --ca=null publish
</code></pre>
<p>After a long wait I get:</p>
<pre><code>npm ERR! need auth auth and email required for publishing
npm ERR! need auth You need to authorize this machine using `npm adduser`
npm ERR! System Linux 3.11.0-18-generic
npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "--registry=http://internal-npm:4873" "--ca=null" "publish"
npm ERR! cwd /home/ciprian/workspace/netop-npm
npm ERR! node -v v0.10.15
npm ERR! npm -v 1.2.18
npm ERR! code ENEEDAUTH
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /home/ciprian/workspace/netop-npm/npm-debug.log
npm ERR! not ok code 0
</code></pre>
<p>The business end of the log file tells me that the user is not optional</p>
<pre><code>86 error need auth auth and email required for publishing
86 error need auth You need to authorize this machine using `npm adduser`
87 error System Linux 3.11.0-18-generic
88 error command "/usr/bin/nodejs" "/usr/bin/npm" "--registry=http://internal-npm:4873" "--ca=null" "publish"
89 error cwd /home/ciprian/workspace/netop-npm
90 error node -v v0.10.15
91 error npm -v 1.2.18
92 error code ENEEDAUTH
93 verbose exit [ 1, true ]
</code></pre>
<p>Now, the <strong>chicken and egg</strong> issue is that Sinopia does not support <code>npm adduser</code>, but has its own user management like I mentioned above. Also npm needs a valid user created through <code>npm adduser</code>, which fails because the internal Sinopia server throws an error at the unsupported command.</p>
| 0 | 1,088 |
Best way solving optimization with multiple variables in Matlab?
|
<p>I am trying to compute numerically the solutions for a system of many equations and variables (100+). I tried so far three things: </p>
<ol>
<li>I now that the vector of p(i) (which contains most of the endogenous variables) is decreasing. Thus I gave simply some starting points, and then was increasing(decreasing) my guess when I saw that the specific p was too low(high). Of course this was always conditional on the other being fixed which is not the case. This should eventually work, but it is neither efficient, nor obvious that I reach a solution in finite time. It worked when reducing the system to 4-6 variables though. </li>
<li>I could create 100+ loops around each other and use bisection for each loop. This would eventually lead me to the solution, but take ages both to program (as I have no idea how to create n loops around each other without actually having to write the loops - which is also bad as I would like to increase/decrease the amount of variables easily) and to execute. </li>
<li>I was trying fminsearch, but as expected for that wast amount of variables - no way! </li>
</ol>
<p>I would appreciate any ideas... Here is the code (this one the fminsearch I tried):</p>
<p><strong>This is the run file</strong>:</p>
<pre><code>clear all
clc
% parameter
z=1.2;
w=20;
lam=0.7;
tau=1;
N=1000;
t_min=1;
t_max=4;
M=6;
a_min=0.6;
a_max=0.8;
t=zeros(1,N);
alp=zeros(1,M);
p=zeros(1,M);
p_min=2;
p_max=1;
for i=1:N
t(i)= t_min + (i-1)*(t_max - t_min)/(N-1);
end
for i=1:M
alp(i)= a_min + (i-1)*(a_max - a_min)/(M-1);
p(i)= p_min + (i-1)*(p_max - p_min)/(M-1);
end
fun=@(p) david(p ,z,w,lam,tau,N,M,t,alp);
p0=p;
fminsearch(fun,p0)
</code></pre>
<p><strong>And this is the program-file</strong>:</p>
<pre><code>function crit=david(p, z,w,lam,tau,N,M,t,alp)
X = zeros(M,N);
pi = zeros(M,N);
C = zeros(1,N);
Xa=zeros(1,N);
Z=zeros(1,M);
rl=0.01;
rh=1.99;
EXD=140;
while (abs(EXD)>100)
r1=rl + 0.5*(rh-rl);
for i=1:M
for j=1:N
X(i,j)=min(w*(1+lam), (alp(i) * p(i) / r1)^(1/(1-alp(i))) * t(j)^((z-alp(i))/(1-alp(i))));
pi(i,j)=p(i) * t(j)^(z-alp(i)) * X(i,j)^(alp(i)) - r1*X(i,j);
end
end
[C,I] = max(pi);
Xa(1)=X(I(1),1);
for j=2:N
Xa(j)=X(I(j),j);
end
EXD=sum(Xa)- N*w;
if (abs(EXD)>100 && EXD>0)
rl=r1;
elseif (abs(EXD)>100 && EXD<0)
rh=r1;
end
end
Ya=zeros(M,N);
for j=1:N
Ya(I(j),j)=t(j)^(z-alp(I(j))) * X(I(j),j)^(alp(I(j)));
end
Yi=sum(Ya,2);
if (Yi(1)==0)
Z(1)=-50;
end
for j=2:M
if (Yi(j)==0)
Z(j)=-50;
else
Z(j)=(p(1)/p(j))^tau - Yi(j)/Yi(1);
end
end
zz=sum(abs(Z))
crit=(sum(abs(Z)));
</code></pre>
| 0 | 1,373 |
maven-resources-plugin error using copy-resources goal: 'resources', 'outputDirectory' missing or invalid
|
<p>I'm trying to use the maven-resources-plugin to do some filtering using the copy-resources goal, and ran into the following error: </p>
<pre><code>Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.5:copy-resources (default-cli) on project bar: The parameters 'resources', 'outputDirectory' for goal org.apache.maven.plugins:maven-resources-plugin:2.5:copy-resources are missing or invalid
</code></pre>
<p>To isolate the problem, I created a very simple pom.xml, copied pretty nearly verbatim from <a href="http://maven.apache.org/plugins/maven-resources-plugin/examples/copy-resources.html">http://maven.apache.org/plugins/maven-resources-plugin/examples/copy-resources.html</a>, ran it, and got the same error. </p>
<p>I'm invoking it with </p>
<pre><code>mvn resources:copy-resources
</code></pre>
<p>Any ideas? Here's the test pom.xml. </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>foo</groupId>
<artifactId>bar</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<executions>
<execution>
<id>copy-resources</id>
<!-- here the phase you need -->
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/extra-resources</outputDirectory>
<resources>
<resource>
<directory>src/non-packaged-resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</code></pre>
<p></p>
| 0 | 1,181 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.