title stringlengths 13 150 | body stringlengths 749 64.2k | label int64 0 3 | token_count int64 1.02k 28.5k |
|---|---|---|---|
urllib2.HTTPError: HTTP Error 403: SSL is required , even with pip upgraded and --index option used | <p>I've already read <a href="https://stackoverflow.com/questions/46962577/cannot-install-distribute-pypi-python-org-rejecting-http">Cannot install distribute: pypi.python.org rejecting http</a> and <a href="https://stackoverflow.com/questions/46967488/getting-error-403-while-installing-package-with-pip">Getting error 403 while installing package with pip</a> but the work around are not workig</p>
<p>while trying to do </p>
<p><code>pip install --upgrade pyls --index-url=https://pypi.python.org/simple</code> I got :</p>
<pre><code>Collecting pyls
Using cached pyls-0.1.3.zip
Complete output from command python setup.py egg_info:
Downloading http://pypi.python.org/packages/source/d/distribute/distribute-0.6.14.tar.gz
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-PHBndM/pyls/setup.py", line 31, in <module>
main()
File "/tmp/pip-build-PHBndM/pyls/setup.py", line 11, in main
distribute_setup.use_setuptools()
File "setup_utils/distribute_setup.py", line 145, in use_setuptools
return _do_download(version, download_base, to_dir, download_delay)
File "setup_utils/distribute_setup.py", line 124, in _do_download
to_dir, download_delay)
File "setup_utils/distribute_setup.py", line 193, in download_setuptools
src = urlopen(url)
File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 435, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 548, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 473, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 407, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 556, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: SSL is required
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-hdpX4y/pyls/
</code></pre>
<p>my python version is 2.7, and my pip version is </p>
<p><code>pip 9.0.2 from /usr/local/lib/python2.7/dist-packages (python 2.7)</code></p>
<p>to reproduce : </p>
<p>spin this docker instance <code>https://hub.docker.com/r/allansimon/allan-docker-dev-python</code> and launch the command in it (with user <code>vagrant</code> ) </p> | 0 | 1,065 |
Why is The navigation property '' declared on type '' has been configured with conflicting multiplicities. error show up? | <p>I have an <code>Asp_Users</code> table and a <code>Resource</code> tables. In the Entity Framework world, I have a <code>Asp_Users</code> POCO and a <code>Resource</code> POCO. Moreover, the <code>Resource</code> POCO is abstract and is part of a Table-per-Hierarchy model. The Table-per-Hierarchy model has the abstract <code>Resource</code> POCO and several <code>Concrete</code> POCOs like <code>ILCResource</code> POCO and <code>SectionResource</code> POCO. There is a one-to-many (1 to 0…*) relationship from <code>Asp_Users</code> POCO (one-side) to <code>Resource</code> POCO (many-side). </p>
<p>Here's the relevant part of my aspnet_Users POCO:</p>
<pre><code>public partial class aspnet_Users
{
public aspnet_Users() { }
public virtual System.Guid ApplicationId { get; set; }
public virtual System.Guid UserId { get; set; }
public virtual string UserName { get; set; }
public virtual string LoweredUserName { get; set; }
public virtual string MobileAlias { get; set; }
public virtual bool IsAnonymous { get; set; }
public virtual System.DateTime LastActivityDate { get; set; }
public virtual ICollection<Resource> associatedResources { get; set; }
}
</code></pre>
<p>Here is my mapping configuration for Asp_Users</p>
<pre><code>public class Aspnet_UsersMap : EntityTypeConfiguration<PerlsData.Domain.aspnet_Users>
{
public Aspnet_UsersMap()
{
this.ToTable("aspnet_Users", schemaName: "dbo");
this.HasKey(u => u.UserId);
this.Property(u => u.UserId)
.HasColumnName("UserId")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.HasOptional(u => u.associatedResources);
}
}
</code></pre>
<p>Here's the relevant part of my abstract Resource POCO class:</p>
<pre><code>public abstract class Resource
{
public Resource(){
// associatedPerspectives = new HashSet<Perspective>();
}
public virtual System.Guid ResourceDatabaseID { get; set; }
public virtual string ResourceName { get; set; }
public virtual string DescriptionOfResource { get; set; }
public virtual System.Guid UserId { get; set; }
public virtual Nullable<System.Guid> DepartmentDatabaseID { get; set; }
public virtual string ResourceStatus { get; set; }
public virtual Nullable<short> isRemoved { get; set; }
public virtual Department Department { get; set; }
public virtual System.Guid UserId { get; set; }
public virtual aspnet_Users aspnet_Users { get; set; }
public virtual ICollection<ResourceOverToILCResourcesBridge> associatedResourceOverToILCResourcesBridgeEntry { get; set; }
}
</code></pre>
<p>Here is my mapping configuration for Resource:</p>
<pre><code>public class ResourceMap : EntityTypeConfiguration<Resource>
{
public ResourceMap()
{
this.ToTable("Resources", schemaName: "dbo");
this.Property(r => r.ResourceDatabaseID)
.HasColumnName("ResourceDatabaseID");
this.HasKey(r => r.ResourceDatabaseID);
this.Property(x => x.ResourceDatabaseID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
// .StoreGeneratedPattern = StoreGeneratedPattern.Identity;
this.Property(r => r.ResourceName)
.HasColumnName("ResourceName");
this.Map<PerlsData.Domain.OtherItem>(m => m.Requires("discriminator").HasValue("otheritems"))
.Map<PerlsData.Domain.Audioitem>(m => m.Requires("discriminator").HasValue("audioitems"))
.Map<PerlsData.Domain.Imageitem>(m => m.Requires("discriminator").HasValue("imageitems"))
.Map<PerlsData.Domain.Videoitem>(m => m.Requires("discriminator").HasValue("videoitems"))
.Map<PerlsData.Domain.UriItem>(m => m.Requires("discriminator").HasValue("uriitems"))
.Map<PerlsData.Domain.Documentitem>(m => m.Requires("discriminator").HasValue("documentitems"))
.Map<PerlsData.Domain.DatabaseFileItem>(m => m.Requires("discriminator").HasValue("databasefileitems"));
this.HasOptional(res => res.associatedResourceOverToILCResourcesBridgeEntry);
this.HasRequired(res => res.aspnet_Users)
.WithMany(u => u.associatedResources)
.HasForeignKey(res => res.UserId);
}
}
</code></pre>
<p>Could you please tell me why I am getting the following error?</p>
<blockquote>
<p>The navigation property 'associatedResources' declared on type
'PerlsData.Domain.aspnet_Users' has been configured with conflicting
multiplicities.</p>
</blockquote>
<p>Please Explain Why it's still NULL after I created the mapping in the POCO class.</p>
<p><img src="https://i.stack.imgur.com/fPXG0.png" alt="enter image description here"></p> | 0 | 1,792 |
why JPA can save my entity but It can't delete the entity? | <p>In my JSF2-JPA2-Spring3 project, I can insert new entities but can't remove entities. This is the error message: java.lang.IllegalArgumentException: Removing a detached instance entity.Entity#8</p>
<p>This is my persistence.xml:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
</code></pre>
<p>http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0"></p>
<pre><code><persistence-unit name="myPersistenceUnit"
transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</code></pre>
<p></p>
<p>This is my service:</p>
<pre><code>@Service("myService")
</code></pre>
<p>public class MyServiceImpl implements MyService {</p>
<pre><code>@Resource(name="MyRepository")
MyDAO myDao;
@Transactional
public void deleteEntity(Entity entity) throws DAOException {
myDao.delete(entity);
}
</code></pre>
<p>This is my dao:</p>
<pre><code>@Repository("MyRepository")
</code></pre>
<p>public class UserDAO{</p>
<pre><code>private EntityManager entityManager;
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public void delete(Entity entity) throws Exception {
try {
entityManager.remove(entity);
} catch (DataAccessException e) {
throw new Exception(e);
}
}
</code></pre>
<p>This is applicationContext.xml:</p>
<pre><code><bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" >
</bean>
</property>
<property name="dataSource" ref="myDataSource" />
<property name="persistenceUnitName" value="myPersistenceUnit"/>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:advice id="transactionInterceptor" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" rollback-for="Throwable" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:advisor pointcut=" execution(* service.*Service.*(..))"
advice-ref="transactionInterceptor" />
</aop:config>
</code></pre>
<p>I try to remove an entity from a list that feed using this method in dao:</p>
<pre><code>public List<Entity> getAll() throws Exception {
List<Entity> list = null;
try {
list = entityManager.createQuery("Select e from Entity e").getResultList();
} catch (DataAccessException e) {
throw new Exception(e);
}
return list;
}
</code></pre> | 0 | 1,315 |
Doctrine2 Update Caused AnnotationRegistry registerLoader Error in Zend Framework 3 | <p>I'm working on a CMS based on Zend Framework 3.0 to manage a DB I with Doctrine. What is my problem when managing packages with composer? Recently, I updated all the packages to newest versions and sent it to server, nothing was changed in other files. After the update my site displayed the following error:</p>
<blockquote>
<p>Fatal error: Uncaught TypeError: Return value of Doctrine\Common\Annotations\AnnotationRegistry::registerLoader() must be an instance of Doctrine\Common\Annotations\void, none returned in /home/platne/serwer18346/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php:117 Stack trace: #0 /home/platne/serwer18346/vendor/doctrine/doctrine-module/src/DoctrineModule/Module.php(57): Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(Object(Closure)) #1 /home/platne/serwer18346/vendor/zendframework/zend-modulemanager/src/Listener/InitTrigger.php(33): DoctrineModule\Module->init(Object(Zend\ModuleManager\ModuleManager)) #2 /home/platne/serwer18346/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Zend\ModuleManager\Listener\InitTrigger->__invoke(Object(Zend\ModuleManager\ModuleEvent)) #3 /home/platne/serwer18346/vendor/zendframework/zend-eventmanager/src/EventManager.php(171): Zend\EventManager\EventManager->triggerListeners(Object(Zend\ModuleManager\ModuleEvent)) #4 /home/p in /home/platne/serwer18346/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php on line 117</p>
</blockquote>
<p>Some application code if needed:<br/>
modules:</p>
<pre><code>return [
'Zend\Router',
'Zend\Validator',
'DoctrineModule',
'DoctrineORMModule',
'Core',
];
</code></pre>
<p>development.local(developer mode is active):</p>
<pre><code>'doctrine' => [
'connection' => [
'orm_default' => [
'driverClass' => Doctrine\DBAL\Driver\PDOMySql\Driver::class,
'params' => [
'host' => '******',
'user' => '*******',
'password' => '******',
'dbname' => '*******',
'charset' => 'utf8'
]
]
]
]
</code></pre>
<p>module.config:</p>
<pre><code>'doctrine' => [
'driver' => [
__NAMESPACE__ . '_driver' => [
'class' => AnnotationDriver::class,
'cache' => 'array',
'paths' => [__DIR__.'/../src/Model']
],
'orm_default' => [
'drivers' => [
__NAMESPACE__ . '\Model' => __NAMESPACE__ . '_driver'
]
]
]
]
</code></pre>
<p>Controller Factory:</p>
<pre><code>public function __invoke(ContainerInterface $container,$requestedName, array $options = null)
{
$controllerInstance = null;
switch($requestedName){
case 'Core\Controller\IndexController': $controllerInstance = $this->_invokeIndex($container); break;
case 'Core\Controller\PagesController': $controllerInstance = $this->_invokePages($container); break;
}
return $controllerInstance;
}
protected function _invokeIndex(ContainerInterface $container)
{
return new Controller\IndexController(
$container->get('doctrine.entitymanager.orm_default')
);
}
protected function _invokePages(ContainerInterface $container)
{
return new Controller\PagesController(
$container->get('doctrine.entitymanager.orm_default')
);
}
</code></pre>
<p>Controller Parent:</p>
<pre><code> protected $_entityManager;
/**
* AppController constructor.
* @param EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager)
{
$this->_entityManager = $entityManager;
}
/**
* @return EntityManager
*/
public function getEntityManager()
{
return $this->_entityManager;
}
</code></pre>
<p>As I said this code worked before update. After update it show me that error, what is more after uploading previous versions the error remains. I triead rewriting code but with the same effect.</p>
<p>Composer(without project data):</p>
<pre><code>"require": {
"zendframework/zend-mvc": "*",
"zendframework/zend-developer-tools": "*",
"zendframework/zend-session": "*",
"zendframework/zend-authentication": "*",
"zfcampus/zf-development-mode": "*",
"doctrine/doctrine-orm-module": "*"
},
"autoload": {
"psr-4": {
"Core\\": "module/Core/src/"
}
}
</code></pre> | 0 | 1,915 |
Show Message Box if TextBox is Blank or Empty using C# | <p>I am trying to check first if users don not enter either User ID or Password, if either text box is blank or empty then I want to show message box, if they enter both user id and password then I want to execute some other codes. The problem I am having with the code is that the message does not show at all but the good thing is that it does not execute the other code. So I would like to see the message box to show up if both text boxes are empty. I am not sure why the message box is not showing up even though I have used this same code in other functions and it worked. thanks
here is my button code for the ASPX</p>
<pre><code> <asp:Panel ID="Panel1" runat="server" BorderStyle="Groove" Height="109px" Visible="false"
Width="870px" BackColor="#FFFFE1">
<asp:Label ID="Label2" runat="server" Text="DIGITAL SIGNATURE" Font-Bold="True"
ForeColor="#FF3300"></asp:Label>
<br />
<br />
<asp:Label ID="lblUID" runat="server" Text="User ID:"></asp:Label>
<asp:TextBox ID="txtUID" runat="server" Height="22px" Width="145px"></asp:TextBox> &nbsp;&nbsp;
&nbsp;&nbsp;
<asp:Label ID="lblPass" runat="server" Text="Password:"></asp:Label>
<asp:TextBox ID="txtPass" runat="server" Height="23px" TextMode="Password" style="margin-top: 0px"></asp:TextBox>
<br />
<br />
&nbsp;<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="183px"
onclick="btnSubmit_Click"
OnClientClick="return confirm('Are you sure you want to submit?');"
Font-Bold="False" Font-Size="Medium" Height="30px"
style="margin-right: 1px" />
<br />
</asp:Panel>
</code></pre>
<p>code behind:</p>
<pre><code>protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtUID.Text.Length == 0 || txtPass.Text.Length == 0)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Please type your User ID and Password correctly and click Submit button again. Thanks", true);
}
else
{
//execute some code here
}
}
</code></pre> | 0 | 1,037 |
Codeigniter pass value from controller to view with ajax request | <p>I new in CI and want to pass json encode value to view for further processing, please see below,</p>
<p>Jquery post:</p>
<pre><code>$('#btn_reset_password').click(function(){
var parameters = $('#reset_password_form').serialize();
//alert(parameters);
$.ajax({
url: baseurl + 'site/check_email_exist',
type: 'POST',
data: parameters,
dataType: 'json',
success: function(output_str){
if(output_str.flag == "true"){
// redirect to change password page
window.location.replace(baseurl + 'site/change_user_password');
}else if(output_str == "false"){
$('#result_msg').html("Your email is not in our database");
}else{
$('#result_msg').html(output_str);
}
}
});
});
</code></pre>
<p>controller:</p>
<pre><code>class Site extends CI_Controller {
public function change_user_password() {
$this->load->view('header');
$this->load->view('change_user_password');
$this->load->view('footer');
}
public function check_email_exist(){
$email = $this->input->post('email');
if(!empty($email)){
$query = $this->db->query('SELECT * FROM users WHERE email="'.$email.'"');
if($query->num_rows() > 0){
$row = $query->row();
$output_str = array('email' => $row->email,
'flag' => 'true'
);
//$this->load->view('change_user_password', $output_str);
//$output_str = "true";
}else{
$output_str = "false";
}
}else{
$output_str = "Email cannot leave blank";
}
echo json_encode($output_str);
}
}
</code></pre>
<p>View file 'change_user_password.php':</p>
<pre><code><?php
//$obj = json_decode($output_str);
echo $email;
?>
<p><div id="result_msg"></div></p>
<p>
<form id="reset_password_form">
<label><b>New Password: </b></label>
<input type="password" name="new_password" style="width:250px;" />
<input type="button" id="btn_change" name="" value="Change" /><br />
</form>
</p>
</code></pre>
<p>How could I pass / retrive the email value which is in array $output_str to view 'change_user_password.php'? I had try many way but still never clear out this issue, please help and many thanks.</p>
<p><strong>Added:</strong></p>
<p>Is it Codeigniter couldn't accept url pass parameters in this way => page?email=abc@xyz.com?</p> | 0 | 1,233 |
Tomcat v9.0 Server at localhost failed to start in Eclipse | <p>I have a problem with Tomcat, it stopped working. I installed Tomcat 3 weeks ago and I have made more than 50 web dynamic projects, maven projects and everythings worked great. And today Tomcat stopped working. For example I make a project in Eclipse and when I try to run it I get this error: Server Tomcat v9.0 Server at localhost failed to start. </p>
<p>I can start Tomcat from Windows services, and I can open <a href="http://localhost:8080/" rel="nofollow noreferrer">http://localhost:8080/</a> page in browser, but I can't start Tomcat in eclipse. Not just for one project, for all projects isn't working. The problem is with Tomcat not with all the apps. I uninstalled and installed it again and do not work. What should I do? Any feedback will be apreciated!</p>
<p><a href="https://i.stack.imgur.com/g0v9h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g0v9h.png" alt="enter image description here"></a></p>
<p>And I get this message in the console:</p>
<pre><code>INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jun 25, 2018 5:14:32 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/LoginRegister]]
at java.base/java.util.concurrent.FutureTask.report(Unknown Source)
at java.base/java.util.concurrent.FutureTask.get(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:949)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:839)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1427)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1417)
at java.base/java.util.concurrent.FutureTask.run(Unknown Source)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.base/java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:943)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:258)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:770)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.startup.Catalina.start(Catalina.java:682)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:350)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:492)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/LoginRegister]]
at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:441)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1427)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1417)
at java.base/java.util.concurrent.FutureTask.run(Unknown Source)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.base/java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:943)
... 21 more
Caused by: java.lang.IllegalArgumentException: The servlets named [LoginRegisterServlet] and [login.register.LoginRegisterServlet] are both mapped to the url-pattern [/loginRegister] which is not permitted
at org.apache.tomcat.util.descriptor.web.WebXml.addServletMappingDecoded(WebXml.java:329)
at org.apache.tomcat.util.descriptor.web.WebXml.addServletMapping(WebXml.java:322)
at org.apache.catalina.startup.ContextConfig.processAnnotationWebServlet(ContextConfig.java:2418)
at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2095)
at org.apache.catalina.startup.ContextConfig.processAnnotationsWebResource(ContextConfig.java:1981)
at org.apache.catalina.startup.ContextConfig.processAnnotationsWebResource(ContextConfig.java:1975)
at org.apache.catalina.startup.ContextConfig.processAnnotationsWebResource(ContextConfig.java:1975)
at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1146)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:765)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:299)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:123)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4989)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
... 27 more
Jun 25, 2018 5:14:32 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: A child container failed during start
at java.base/java.util.concurrent.FutureTask.report(Unknown Source)
at java.base/java.util.concurrent.FutureTask.get(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:949)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:258)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:770)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.startup.Catalina.start(Catalina.java:682)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:350)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:492)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:958)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:839)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1427)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1417)
at java.base/java.util.concurrent.FutureTask.run(Unknown Source)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.base/java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:943)
... 13 more
Jun 25, 2018 5:14:32 PM org.apache.catalina.startup.Catalina start
SEVERE: The required Server component failed to start so Tomcat is unable to start.
org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:958)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:258)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:770)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.startup.Catalina.start(Catalina.java:682)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:350)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:492)
Jun 25, 2018 5:14:32 PM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-nio-8080"]
Jun 25, 2018 5:14:32 PM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["ajp-nio-8009"]
Jun 25, 2018 5:14:32 PM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service [Catalina]
Jun 25, 2018 5:14:32 PM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["http-nio-8080"]
Jun 25, 2018 5:14:32 PM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["ajp-nio-8009"]
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.catalina.loader.WebappClassLoaderBase (file:/C:/Program%20Files/Apache%20Software%20Foundation/Tomcat%209.0/lib/catalina.jar) to field java.io.ObjectStreamClass$Caches.localDescs
WARNING: Please consider reporting this to the maintainers of org.apache.catalina.loader.WebappClassLoaderBase
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Jun 25, 2018 5:14:33 PM org.apache.catalina.deploy.NamingResourcesImpl cleanUp
WARNING: Failed to retrieve JNDI naming context for container [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/LoginRegister]] so no cleanup was performed for that container
javax.naming.NamingException: No naming context bound to this class loader
at org.apache.naming.ContextBindings.getClassLoader(ContextBindings.java:268)
at org.apache.catalina.deploy.NamingResourcesImpl.cleanUp(NamingResourcesImpl.java:994)
at org.apache.catalina.deploy.NamingResourcesImpl.stopInternal(NamingResourcesImpl.java:977)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:257)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5327)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:257)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:293)
at org.apache.catalina.core.ContainerBase.removeChild(ContainerBase.java:844)
at org.apache.catalina.core.ContainerBase.destroyInternal(ContainerBase.java:1046)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:322)
at org.apache.catalina.core.ContainerBase.removeChild(ContainerBase.java:844)
at org.apache.catalina.core.ContainerBase.destroyInternal(ContainerBase.java:1046)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:322)
at org.apache.catalina.core.StandardService.destroyInternal(StandardService.java:553)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:322)
at org.apache.catalina.core.StandardServer.destroyInternal(StandardServer.java:860)
at org.apache.catalina.util.LifecycleBase.destroy(LifecycleBase.java:322)
at org.apache.catalina.startup.Catalina.start(Catalina.java:686)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:350)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:492)
</code></pre> | 0 | 4,312 |
Why is 0dp considered a performance enhancement? | <p>An <strong>answer</strong> at the end of this question has been filled out, combining remarks and solutions.</p>
<h2>Question</h2>
<p>I searched around but haven't found anything that really explains why <em>Android Lint</em> as well as some <em>Eclipse</em> hints suggest replacing some <code>layout_height</code> and <code>layout_width</code> values with <code>0dp</code>.</p>
<p>For example, I have a <code>ListView</code> that was suggested to be changed</p>
<p><strong>Before</strong></p>
<pre><code><ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</ListView>
</code></pre>
<p><strong>After</strong></p>
<pre><code><ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</ListView>
</code></pre>
<p>Similarly, it suggested changes to a <em>ListView item</em>. These all look the same before and after the changes, but I'm interested in understanding why these are performance boosters.</p>
<p>Anyone have an explanation of why? If it helps, here is general layout with the <code>ListView</code>.</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/logo_splash"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ImageView>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@color/background"
android:layout_below="@id/logo_splash">
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</ListView>
<TextView
android:id="@android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/no_upcoming" />
</LinearLayout>
</RelativeLayout>
</code></pre>
<h2>Answer</h2>
<p>I'm putting in an answer here because it's really a combination of answers and referenced links below. If I'm wrong on something, do let me know.</p>
<p>From <a href="https://stackoverflow.com/questions/7220404/what-is-the-trick-with-0dip-layout-height-or-layouth-width">What is the trick with 0dip layout_height or layouth_width?</a></p>
<p>There are 3 general layout attributes that work with <em>width</em> and <em>height</em></p>
<ol>
<li><code>android:layout_height</code></li>
<li><code>android:layout_width</code></li>
<li><code>android:layout_weight</code></li>
</ol>
<p>When a <code>LinearLayout</code> is <em>vertical</em>, then the <code>layout_weight</code> will effect the <em>height</em> of the child <code>View</code>s (<code>ListView</code>). Setting the <code>layout_height</code> to <code>0dp</code> will cause this attribute to be ignored.</p>
<p><strong>Example</strong></p>
<pre><code><LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</ListView>
</LinearLayout>
</code></pre>
<p>When a <code>LinearLayout</code> is <em>horizontal</em>, then the <code>layout_weight</code> will effect the <em>width</em> of the child <code>View</code>s (<code>ListView</code>). Setting the <code>layout_width</code> to <code>0dp</code> will cause this attribute to be ignored.</p>
<p><strong>Example</strong></p>
<pre><code><LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<ListView
android:id="@android:id/list"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
</ListView>
</LinearLayout>
</code></pre>
<p>The reason to want to ignore the attribute is that if you didn't ignore it, it would be used to calculate the layout which uses more CPU time. </p>
<p>Additionally this prevents any confusion over what the layout should look like when using a combination of the three attributes. This is highlighted by <em>@android developer</em> in an answer below.</p>
<p>Also, <em>Android Lint</em> and <em>Eclipse</em> both say to use <code>0dip</code>. From that answer below, you can use <code>0dip</code>, <code>0dp</code>, <code>0px</code>, etc since a zero size is the same in any of the units.</p>
<p><strong>Avoid wrap_content on ListView</strong></p>
<p>From <a href="https://stackoverflow.com/questions/4270278/layout-width-of-a-listview/4270471#4270471">Layout_width of a ListView</a></p>
<p>If you've ever wondered why <code>getView(...)</code> is called so many times like I have, it turns out to be related to <code>wrap_content</code>.</p>
<p>Using <code>wrap_content</code> like I was using above will cause all child <code>View</code>s to be measured which will cause further CPU time. This measurement will cause your <code>getView(...)</code> to be called. I've now tested this and the number of times <code>getView(...)</code> is called is reduced dramatically.</p>
<p>When I was using <code>wrap_content</code> on two <code>ListView</code>s, <code>getView(...)</code> was called 3 times for each row on one <code>ListView</code> and 4 times for each row on the other.</p>
<p>Changing this to the recommended <code>0dp</code>, <code>getView(...)</code> was called only once for each row. This is quite an improvement, but has more to do with avoiding <code>wrap_content</code> on a <code>ListView</code> than it does the <code>0dp</code>.</p>
<p>However the suggestion of <code>0dp</code> does substantially improve performance because of this.</p> | 0 | 2,276 |
In-Place Radix Sort | <p>This is a long text. Please bear with me. Boiled down, the question is: <strong>Is there a workable in-place radix sort algorithm</strong>?</p>
<hr>
<h2>Preliminary</h2>
<p>I've got a huge number of <em>small fixed-length</em> strings that only use the letters “A”, “C”, “G” and “T” (yes, you've guessed it: <a href="https://en.wikipedia.org/wiki/DNA" rel="noreferrer">DNA</a>) that I want to sort.</p>
<p>At the moment, I use <code>std::sort</code> which uses <a href="https://en.wikipedia.org/wiki/Introsort" rel="noreferrer">introsort</a> in all common implementations of the <a href="https://en.wikipedia.org/wiki/Standard_Template_Library" rel="noreferrer">STL</a>. This works quite well. However, I'm convinced that <a href="https://en.wikipedia.org/wiki/Radix_sort" rel="noreferrer">radix sort</a> fits my problem set perfectly and should work <strong>much</strong> better in practice.</p>
<h2>Details</h2>
<p>I've tested this assumption with a very naive implementation and for relatively small inputs (on the order of 10,000) this was true (well, at least more than twice as fast). However, runtime degrades abysmally when the problem size becomes larger (<em>N</em> > 5,000,000).</p>
<p>The reason is obvious: radix sort requires copying the whole data (more than once in my naive implementation, actually). This means that I've put ~ 4 GiB into my main memory which obviously kills performance. Even if it didn't, I can't afford to use this much memory since the problem sizes actually become even larger.</p>
<h2>Use Cases</h2>
<p>Ideally, this algorithm should work with any string length between 2 and 100, for DNA as well as DNA5 (which allows an additional wildcard character “N”), or even DNA with <a href="https://en.wikipedia.org/wiki/International_Union_of_Pure_and_Applied_Chemistry" rel="noreferrer">IUPAC</a> <a href="https://en.wikipedia.org/wiki/Nucleic_acid_notation" rel="noreferrer">ambiguity codes</a> (resulting in 16 distinct values). However, I realize that all these cases cannot be covered, so I'm happy with any speed improvement I get. The code can decide dynamically which algorithm to dispatch to.</p>
<h2>Research</h2>
<p>Unfortunately, the <a href="https://en.wikipedia.org/wiki/Radix_sort" rel="noreferrer">Wikipedia article on radix sort</a> is useless. The section about an in-place variant is complete rubbish. The <a href="http://xlinux.nist.gov/dads/HTML/radixsort.html" rel="noreferrer">NIST-DADS section on radix sort</a> is next to nonexistent. There's a promising-sounding paper called <a href="https://www.mii.vu.lt/informatica/pdf/INFO562.pdf" rel="noreferrer">Efficient Adaptive In-Place Radix Sorting</a> which describes the algorithm “MSL”. Unfortunately, this paper, too, is disappointing.</p>
<p>In particular, there are the following things.</p>
<p>First, the algorithm contains several mistakes and leaves a lot unexplained. In particular, it doesn’t detail the recursion call (I simply assume that it increments or reduces some pointer to calculate the current shift and mask values). Also, it uses the functions <code>dest_group</code> and <code>dest_address</code> without giving definitions. I fail to see how to implement these efficiently (that is, in O(1); at least <code>dest_address</code> isn’t trivial).</p>
<p>Last but not least, the algorithm achieves in-place-ness by swapping array indices with elements inside the input array. This obviously only works on numerical arrays. I need to use it on strings. Of course, I could just screw strong typing and go ahead assuming that the memory will tolerate my storing an index where it doesn’t belong. But this only works as long as I can squeeze my strings into 32 bits of memory (assuming 32 bit integers). That's only 16 characters (let's ignore for the moment that 16 > log(5,000,000)).</p>
<p>Another paper by one of the authors gives no accurate description at all, but it gives MSL’s runtime as sub-linear which is flat out wrong.</p>
<p><strong>To recap</strong>: Is there any hope of finding a working reference implementation or at least a good pseudocode/description of a working in-place radix sort that works on DNA strings?</p> | 0 | 1,205 |
Object reference not set to an instance of an object in Html.Partial MVC when load data | <p>I have _layout.cshtml page in mvc project that call partial view with this code</p>
<blockquote>
<p>@Html.Partial("_MenuForAdmin")</p>
</blockquote>
<p><strong>The code for MenuModel</strong> :</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace i_insurance.Models
{
public class MenuModel
{
public List<string> li { get; set; }
}
}
</code></pre>
<p><strong>The code for MenuController</strong> :</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using i_insurance.Models;
using i_insurance.DataAccess;
using System.Data;
namespace i_insurance.Controllers
{
public class MenuController : Controller
{
public ActionResult Index()
{
MenuModel model = new MenuModel();
model.li = LoadUl();
return View(model);
}
public List<string> LoadUl()
{
List<string> list = new List<string>();
list.Add("Testing");
list.Add("MCV");
list.Add("Project");
return list;
}
}
}
</code></pre>
<p><strong>The code for partial view _MenuForAdmin.cshtml</strong> :</p>
<blockquote>
<p>@model i_insurance.Models.MenuModel</p>
<pre><code>@foreach (var item in Model.li) {
<text>
item
</text> }
</code></pre>
</blockquote>
<p><strong>The code for Index.cshtml inside home folder</strong> :</p>
<pre><code>@{
ViewBag.Title = "Home Page";
}
@section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>@ViewBag.Message</h2>
</hgroup>
</div>
</section>
}
<h3>We suggest the following:</h3>
<ol class="round">
<li class="one">
<h5>Getting Started</h5>
ASP.NET MVC gives you a powerful
</li>
</ol>
</code></pre>
<p>and when i run this project in browser it show "Object reference not set to an instance of an object" , here is the </p>
<blockquote>
<pre><code>Source Error:
Line 1: @model i_insurance.Models.MenuModel
Line 2:
Line 3: @foreach (var item in Model.li)
Line 4: {
Line 5: <text>
Source File: d:\Projects\VS2012\Website\i_insurance\i_insurance\Views\Shared\_MenuForAdmin.cshtml
</code></pre>
<p>Line: 3</p>
</blockquote>
<p><strong>Stack Trace</strong>:</p>
<pre><code>[NullReferenceException: Object reference not set to an instance of an object.]
ASP._Page_Views_Shared__MenuForAdmin_cshtml.Execute() in d:\Projects\VS2012\Website\i_insurance\i_insurance\Views\Shared\_MenuForAdmin.cshtml:3
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +103
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +88
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
System.Web.Mvc.HtmlHelper.RenderPartialInternal(String partialViewName, ViewDataDictionary viewData, Object model, TextWriter writer, ViewEngineCollection viewEngineCollection) +277
System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData) +91
System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName) +32
ASP._Page_Views_Home_Index_cshtml.Execute() in d:\Projects\VS2012\Website\i_insurance\i_insurance\Views\Home\Index.cshtml:24
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +103
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +62
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +22
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +176
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +75
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +99
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9634212
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
</code></pre>
<p>my question is why this happen ? and how to solve it ?</p> | 0 | 2,720 |
How to structure JSON and build HTML via jQuery | <p>Beginner here trying to figure out best way to structure some JSON and output the below nested <ul></p>
<p>Each of the bolded items below are the values in the JSON. How might I structure the JSON and then how to build the DOM structure with jQuery? Any help greatly appreciated.</p>
<p><code><pre><ul>
<li><strong>Topic 1</strong>
<ul>
<li id="<strong>foo_item1a</strong>">
<a href="<strong>destination_Item1a</strong>">
<strong><strong>Lorem</strong></strong>
<span><strong>Item 1a</strong></span>
<em><strong>Ipsum</strong></em>
</a>
</li>
<li id="<strong>foo_item1b</strong>">
<a href="<strong>destination_Item1b</strong>">
<strong><strong>Dolor</strong></strong>
<span><strong>Item 1b</strong></span>
<em><strong>Sit</strong></em>
</a>
</li>
</ul>
</li>
<li><strong>Topic 2</strong>
<ul>
<li id="<strong>foo_item2a</strong>">
<a href="<strong>destination_Item2a</strong>">
<strong><strong>Lorem</strong></strong>
<span><strong>Item 2a</strong></span>
<em><strong>Ipsum</strong></em>
</a>
</li>
<li id="<strong>foo_item2b</strong>">
<a href="<strong>destination_Item2b</strong>">
<strong><strong>Dolor</strong></strong>
<span><strong>Item 2b</strong></span>
<em><strong>Sit</strong></em>
</a>
</li>
</ul>
</li>
</ul></p>
<p></pre></code></p> | 0 | 1,218 |
Bootstrap datepicker expands up but not down | <p>I am using bootstrap. When I click my <code>date picker</code> it expands up and goes under my navigation bar. How do I fix it? - I would like it to be expanded into visible page area. </p>
<p><img src="https://i.stack.imgur.com/0m5Gt.png" alt="enter image description here"></p>
<p>This is my html/css:</p>
<pre><code><html ng-app="fly">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="css/main.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="js/bootstrap-datepicker.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="app.js"></script>
</head>
<div ng-controller="myController">
<nav class="navbar navbar-inverse navbar-static-top">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand logo" href="#">
<span class="glyphicon glyphicon-plane"> </span>
<a href="#" class="navbar-text ffly">FLY</a>
</a>
</div>
</div>
</nav>
<div class="container well well-md searchDialog">
<form role="search">
<div class="row searchRow">
<div class="col-md-4 col-md-offset-4 col-sm-4 col-sm-offset-4 col-xs-12">
<label for="searchBox">From</label>
<input type="text" class="form-control" id="searchBox"placeholder="Search">
</div>
</div>
<div class="row dateRow">
<div class='col-md-4 col-md-offset-2 col-sm-4 col-sm-offset-2 col-xs-6'>
<div class="form-group">
<label for="depart">Depart</label>
<div class='input-group date' id='datetimepicker6'>
<input type='text' id="depart" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<div class='col-md-4 col-md-offset-0 col-sm-4 col-sm-offset-0 col-xs-6'>
<div class="form-group">
<label for="return">Return</label>
<div class='input-group date' id='datetimepicker7'>
<input type='text' id="return"class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker6').datepicker();
$('#datetimepicker7').datepicker();
$("#datetimepicker6").on("dp.change", function (e) {
$('#datetimepicker7').data("DateTimePicker").minDate(e.date);
});
$("#datetimepicker7").on("dp.change", function (e) {
$('#datetimepicker6').data("DateTimePicker").maxDate(e.date);
});
});
</script>
</form>
</div>
</div>
</body>
</html>
</html>
</code></pre>
<p>css:</p>
<pre><code>.navbar-brand{
height: 60px;
}
.logo {
font-size: 35px;
}
.fridayfly{
font-size: 25px;
}
a.ffly:link { color: #FFFFFF; text-decoration: none}
a.ffly:visited { text-decoration: none}
a.ffly:hover { color: #FFFFFF; text-decoration: none}
a.ffly:active { color: #FFFFFF; text-decoration: none}
.dateRow{
margin-top: 20px;
}
</code></pre> | 0 | 2,804 |
IIS7.5 Gives 500 Internal Server Error when trying to use DELETE verb | <p>I am trying to issue a <code>DELETE</code> to an IIS7.5 resource:</p>
<pre><code>DELETE http://198.252.206.16:48251/Test/foo.ashx HTTP/1.1
Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
Host: 198.252.206.16:48251
Content-Length: 0
Connection: Keep-Alive
Pragma: no-cache
</code></pre>
<p>And the server responds with:</p>
<pre><code>HTTP/1.1 500 Internal Server Error
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Wed, 12 Feb 2014 01:01:30 GMT
Content-Length: 0
</code></pre>
<p>The damnedest thing is:</p>
<ul>
<li>it works fine inside Cassini (the .NET based web-server used by Visual Studio)</li>
<li>nothing is logged in the Windows Event log</li>
<li>Custom errors are off in the site's <code>web.config</code></li>
<li>No verbs are being filtered (or all verbs are being included)</li>
<li>WebDAV module is disabled</li>
<li>LiveStreamingHandler module is not installed</li>
</ul>
<p>Why does IIS not work?</p>
<h1>Steps to reproduce</h1>
<p>Create a web-site with the generic handler:</p>
<p><strong>Foo.ashx</strong></p>
<pre><code><%@ WebHandler Language="C#" Class="Foo" %>
using System;
using System.Web;
public class Foo : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
}
public bool IsReusable { get { return false; } }
}
</code></pre>
<p>and then issue a <code>DELETE</code> verb to the resource. You can use Fiddler to compose the request, if you like:</p>
<p><img src="https://i.stack.imgur.com/G1dg7.png" alt="enter image description here"></p>
<h1>What about other verbs you ask?</h1>
<p>You didn't try to reproduce it, did you? Well, i'll show you the results here:</p>
<ul>
<li><strong><code>GET</code></strong>: <em>works</em></li>
<li><strong><code>POST</code></strong>: <em>works</em></li>
<li><strong><code>PUT</code></strong>: <em>works</em></li>
<li><strong><code>HEAD</code></strong>: <em>works</em></li>
<li><strong><code>TRACE</code></strong>: <code>501 Not Implemented</code></li>
<li><strong><code>DELETE</code></strong>: <code>500 Internal Server Error</code></li>
<li><strong><code>SEARCH</code></strong>: <code>405 Method Not Allowed</code></li>
<li><strong><code>PROPFIND</code></strong>: <code>500 Internal Server Error</code></li>
<li><strong><code>PROPPATCH</code></strong>: <code>500 Internal Server Error</code></li>
<li><strong><code>PATCH</code></strong>: <code>405 Method Not Allowed</code></li>
<li><strong><code>MKCOL</code></strong>: <code>405 Method Not Allowed</code></li>
<li><strong><code>COPY</code></strong>: <code>500 Internal Server Error</code></li>
<li><strong><code>MOVE</code></strong>: <code>500 Internal Server Error</code></li>
<li><strong><code>LOCK</code></strong>: <code>500 Internal Server Error</code></li>
<li><strong><code>UNLOCK</code></strong>: <code>500 Internal Server Error</code></li>
<li><strong><code>OPTIONS</code></strong>: <code>200 OK</code></li>
<li><strong><code>IISUCKSFOO</code></strong> <code>405 Method Not Allowed</code></li>
</ul>
<p>And just to be anal retentive, a snippet of the relevant portions from <code>web.config</code>:</p>
<pre><code><?xml version="1.0"?>
<configuration>
<system.web>
<httpRuntime/>
<!-- IISFIX: By default IIS hides errors-->
<customErrors mode="Off"/>
<!-- IISFIX: By default IIS ignores the browser's culture -->
<globalization culture="auto" uiCulture="auto"/>
<!--Doesn't work for ASP.net web-sites, only ASP.net applications-->
<trace enabled="true" requestLimit="40" localOnly="false" />
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.DirectoryServices.AccountManagement, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
</system.web>
<!-- ASP.net web-sites do not support WebPageTraceListener (only ASP.net web-applications)
So this section doesn't work; and does nothing.
But if Microsoft ever fixes IIS, we will start working automagically. -->
<system.diagnostics>
<trace>
<listeners>
<add name="WebPageTraceListener" type="System.Web.WebPageTraceListener, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</listeners>
</trace>
</system.diagnostics>
<system.webServer>
<!-- IISFIX: By default IIS ignores custom error pages -->
<httpErrors existingResponse="PassThrough"/>
<defaultDocument>
<files>
<clear/>
<add value="Default.htm"/>
<add value="Default.asp"/>
<add value="index.htm"/>
<add value="index.html"/>
<add value="iisstart.htm"/>
<add value="default.aspx"/>
<add value="test.htm"/>
</files>
</defaultDocument>
<!--IISFIX: By default IIS doesn't understand HTTP protocol-->
<security>
<requestFiltering>
<verbs>
<add verb="OPTIONS" allowed="true" />
<add verb="GET" allowed="true" />
<add verb="HEAD" allowed="true" />
<add verb="POST" allowed="true" />
<add verb="PUT" allowed="true" />
<add verb="TRACE" allowed="true" />
<add verb="DELETE" allowed="true" />
</verbs>
</requestFiltering>
</security>
<modules runAllManagedModulesForAllRequests="true">
<!--IISFIX: Whatever this is, it causes 405 Method Not Allowed errors on IIS when using PUT. (Microsoft's broken by defult)-->
<remove name="WebDAVModule"/>
</modules>
</system.webServer>
</configuration>
</code></pre>
<p><strong>Edit</strong> - forgot the screenshot of verbs:</p>
<p><img src="https://i.stack.imgur.com/6Zglp.png" alt="enter image description here"></p>
<p>The question was sufficiently asked in the title. The rest of the post is just filler to make it look like it shows research effort; which means you have to upvote it - the tooltip on the upvote arrow says so!</p> | 0 | 3,039 |
HTTP Status 404 Servlet-The requested resource is not available | <p>I am making one simple program to take few fields as input and then after clicking on confirm button confirm.jsp will appear. </p>
<p>I have created Controller.java servlet to identify the button clicked and then open the jsp.
Controller.java is stored in directory WEB-INF/classes/ch2/servletController and submit.jsp,register.jsp,confirm.jsp are stored in /ch2/servletController directory. </p>
<p>Whenever i click on confirm button, i get below error. WebApplication is the name of my project. I am using netBeans IDE. </p>
<p>HTTP Status 404 - /WebApplication/ch2/servletController/Controller </p>
<p>type Status report </p>
<p>message /WebApplication/ch2/servletController/Controller </p>
<p>description The requested resource is not available. </p>
<p>Please find below web.xml,servlet and all the jsp files.. </p>
<p><strong>register.jsp</strong> </p>
<pre><code><?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Register</title>
</head>
<body>
<form method="get" action="Controller">
<p><b>E-store</b></p>
<br>
<br>
<p>Enter First Name: <input type="text" name="FirstName" value="${param.FirstName}"></p>
<p>Enter Last Name: <input type="text" name="LastName" value="${param.LastName}"></p>
<p>Enter Mail-id: <input type="text" name="MailId" value="${param.MailId}"></p>
<p>Enter PhoneNo: <input type="text" name="PhoneNo" value="${param.PhoneNo}"></p>
<p><input type="submit" name="confirmButton" value="confirm"></p>
</form>
</body>
</html>
</code></pre>
<p><strong>confirm.jsp</strong> </p>
<pre><code><?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Confirm Details</title>
</head>
<body>
<form method="get" action="Controller" >
<p><b>E-store</b></p>
<br>
<br>
<p>First Name: ${param.FirstName}<input type="hidden" name="FirstName" value="${param.FirstName}"></input></p>
<p>Last Name: ${param.LastName}<input type="hidden" name="LastName" value="${param.LastName}"></input></p>
<p>Mail-id: ${param.MailId}<input type="hidden" name="MailId" value="${param.MailId}"></input></p>
<p>PhoneNo: ${param.PhoneNo}<input type="hidden" name="PhoneNo" value="${param.PhoneNo}"></input></p>
<input type="submit" name="EditButton" value="Edit">
<input type="submit" name="Submitbutton" value="Submit">
</form>
</body>
</html>
</code></pre>
<p><strong>submit.jsp</strong></p>
<pre><code><?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Confirm Details</title>
</head>
<body>
<form>
<p><b>E-store</b></p>
<br>
<br>
<p>Thank You for the registration. Your details have been submitted as follows-</p>
<p>First Name: ${param.FirstName}<input type="hidden" name="FirstName" value="${param.FirstName}"></input></p>
<p>Last Name: ${param.LastName}<input type="hidden" name="LastName" value="${param.LastName}"></input></p>
<p>Mail-id: ${param.MailId}<input type="hidden" name="MailId" value="${param.MailId}"></input></p>
<p>PhoneNo: ${param.PhoneNo}<input type="hidden" name="PhoneNo" value="${param.PhoneNo}"></input></p>
</form>
</body>
</html>
</code></pre>
<p><strong>Controller.java</strong></p>
<pre><code>package ch2.servletController;
import java.io.IOException;
import javax.servlet.http.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
public class Controller extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
String address=null;
if(request.getParameter("confirmButton")!= null)
{
address="confirm.jsp";
}
else if(request.getParameter("EditButton")!= null)
{
address="register.jsp";
}
else if(request.getParameter("Submitbutton")!=null)
{
address="submit.jsp";
}
RequestDispatcher Dispatcher=request.getRequestDispatcher(address);
Dispatcher.forward(request, response);
}
}
</code></pre>
<p><strong>web.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>FirstController</servlet-name>
<servlet-class>ch2.servletController.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstController</servlet-name>
<url-pattern>/Controller</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
</code></pre>
<p><strong>index.jsp</strong></p>
<pre><code><?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>First JSP</title>
</head>
<body>
<form>
<p><b>Welcome to E-store</b></p>
<br>
<br>
<p>Click to <a href="ch2/servletController/register.jsp">Register</a></p>
</form>
</body>
</html>
</code></pre>
<p>I'd be grateful if anyone can help me to solve this problem. </p>
<p>Many Thanks in Advance.</p> | 0 | 3,478 |
Laravel 5.4 Class 'form' not found | <p>I'm facing problem <strong>'Class 'form' not found'</strong> I'm currently using laravel 5.4. I already have tried maximum efforts to solve.</p>
<p>Thanks</p>
<blockquote>
<p>Error is : Whoops, looks like something went wrong.</p>
</blockquote>
<p>1/1</p>
<blockquote>
<p>FatalErrorException in d0b19e04e5a1f8a5507d8ca427362b23807103ca.php line 23:
Class 'Form' not found
in d0b19e04e5a1f8a5507d8ca427362b23807103ca.php line 23</p>
</blockquote>
<p>Here is my Comp</p>
<pre><code>{
"require": {
"php": ">=5.6.4",
"laravel/framework": "5.4.*",
"laravel/tinker": "~1.0",
"laravelcollective/html": "^5.4"
},
}
</code></pre>
<p>I run the composer update command.</p>
<p>Here is my app.php </p>
<pre><code>'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
'Collective\Html\HtmlServiceProvider',
/*
* Package Service Providers...
*/
Laravel\Tinker\TinkerServiceProvider::class,
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
'FORM' => 'Collective\Html\FormFacade',
'HTML' => 'Collective\Html\HtmlFacade',
],
];
</code></pre>
<p>using form in formupload.blade.php</p>
<p></p>
<pre><code>@if(isset($success))
<div class="alert alert-success"> {{$success}} </div>
@endif
{!! Form::open(['action'=>'ImageController@store', 'files'=>true]) !!}
<div class="form-group">
{!! Form::label('title', 'Title:') !!}
{!! Form::text('title', null, ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('description', 'Description:') !!}
{!! Form::textarea('description', null, ['class'=>'form-control', 'rows'=>5] ) !!}
</div>
<div class="form-group">
{!! Form::label('image', 'Choose an image') !!}
{!! Form::file('image') !!}
</div>
<div class="form-group">
{!! Form::submit('Save', array( 'class'=>'btn btn-danger form-control' )) !!}
</div>
{!! Form::close() !!}
<div class="alert-warning">
@foreach( $errors->all() as $error )
<br> {{ $error }}
@endforeach
</div>
</div>
</code></pre> | 0 | 2,396 |
Fast and responsive interactive charts/graphs: SVG, Canvas, other? | <p>I am trying to choose the right technology to use for updating a project that basically renders thousands of points in a zoomable, pannable graph. The current implementation, using Protovis, is underperformant. Check it out here:</p>
<p><a href="http://www.planethunters.org/classify" rel="noreferrer">http://www.planethunters.org/classify</a></p>
<p>There are about 2000 points when fully zoomed out. Try using the handles on the bottom to zoom in a bit, and drag it to pan around. You will see that it is quite choppy and your CPU usage probably goes up to 100% on one core unless you have a really fast computer. Each change to the focus area calls a redraw to protovis which is pretty darn slow and is worse with more points drawn.</p>
<p>I would like to make some updates to the interface as well as change the underlying visualization technology to be more responsive with animation and interaction. From the following article, it seems like the choice is between another SVG-based library, or a canvas-based one:</p>
<p><a href="http://www.sitepoint.com/how-to-choose-between-canvas-and-svg/" rel="noreferrer">http://www.sitepoint.com/how-to-choose-between-canvas-and-svg/</a></p>
<p><a href="http://d3js.org/" rel="noreferrer">d3.js</a>, which grew out of Protovis, is SVG-based and is <a href="http://mbostock.github.com/d3/tutorial/protovis.html" rel="noreferrer">supposed to be better at rendering animations</a>. However, I'm dubious as to how much better and what its performance ceiling is. For that reason, I'm also considering a more complete overhaul using a canvas-based library like <a href="http://www.kineticjs.com/" rel="noreferrer">KineticJS</a>. However, before I get too far into using one approach or another, I'd like to hear from someone who has done a similar web application with this much data and get their opinion.</p>
<p>The most important thing is performance, with a secondary focus on ease of adding other interaction features and programming the animation. There will probably be no more than 2000 points at once, with those small error bars on each one. <strong>Zooming in, out, and panning around need to be smooth.</strong> If the most recent SVG libraries are decent at this, then perhaps the ease of using d3 will outweigh the increased setup for KineticJS, etc. But if there is a huge performance advantage to using a canvas, especially for people with slower computers, then I would definitely prefer to go that way.</p>
<p>Example of app made by the NYTimes that uses SVG, but still animates acceptably smoothly:
<a href="http://www.nytimes.com/interactive/2012/05/17/business/dealbook/how-the-facebook-offering-compares.html" rel="noreferrer">http://www.nytimes.com/interactive/2012/05/17/business/dealbook/how-the-facebook-offering-compares.html</a> . If I can get that performance and not have to write my own canvas drawing code, I would probably go for SVG.</p>
<p>I noticed that some users have used a hybrid of <a href="https://stackoverflow.com/questions/12098286/canvas-tooltip-to-appear-outside-canvas">d3.js manipulation combined with canvas rendering</a>. However, I can't find much documentation about this online or get in contact with the OP of that post. If anyone has any experience doing this kind of DOM-to-Canvas (<a href="http://bl.ocks.org/1276463" rel="noreferrer">demo</a>, <a href="https://gist.github.com/1276463" rel="noreferrer">code</a>) implementation, I would like to hear from you as well. It seems to be a good hybrid of being able to manipulate data and having custom control over how to render it (and therefore performance), but I'm wondering if having to load everything into the DOM is still going to slow things down.</p>
<p>I know that there are some existing questions that are similar to this one, but none of them exactly ask the same thing. Thanks for your help.</p>
<p><strong>Follow-up</strong>: the implementation I ended up using is at <a href="https://github.com/zooniverse/LightCurves" rel="noreferrer">https://github.com/zooniverse/LightCurves</a></p> | 0 | 1,128 |
flutter: ListTile how to adapt leading margins and title/subtitle style? | <p>I am building a form made up various Widgets and I would like to align them all.</p>
<p>In the following example, I am using a TextFormField, a ListTile among others.</p>
<p>The problem is related to the alignment of both TextFormField > decoration > icon and the ListTile > leading.</p>
<p>As you can see the ListTile > leading is absolutely not aligned with the TextFormField > decoration > icon.</p>
<p>In the documentation, I could not find any explanation on how to adapt the ListTile > leading "margin left"</p>
<p><em>Sub-question</em>: How can I style both ListTile title and subtitle so that it looks like the TextFormField?</p>
<p>Any help is more than welcome.</p>
<p>Source code extract:</p>
<pre><code>_buildBody() {
return new SafeArea(
top: false,
bottom: false,
child: new Form(
key: _formKey,
autovalidate: false,
child: new SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
/* -- Profile Picture -- */
const SizedBox(height: 24.0),
_buildProfilePicture(),
/* -- Alias -- */
new TextFormField(
decoration: const InputDecoration(
border: const UnderlineInputBorder(),
filled: true,
icon: const Icon(Icons.person),
hintText: 'Enter an alias',
labelText: 'Alias *',
),
onSaved: (String value) {
profile.alias = value;
},
validator: _validateAlias,
),
const SizedBox(height: 24.0),
/* -- Gender -- */
_buildGender(context),
const SizedBox(height: 24.0),
/* -- Self description -- */
new TextFormField(
decoration: const InputDecoration(
border: const OutlineInputBorder(),
hintText: 'Tell us about yourself',
labelText: 'Describe yourself',
),
maxLines: 5,
),
const SizedBox(height: 24.0),
/* -- Save Button -- */
new Center(
child: new RaisedButton(
child: const Text('Save'),
onPressed: _handleSave,
),
),
const SizedBox(height: 24.0),
],
),
),
),
);
}
_buildGender(BuildContext context) {
return new GestureDetector(
child: new ListTile(
leading: new Container(width: 24.0, height: 24.0, color: Colors.red),//const Icon(Icons.casino),
title: const Text('Gender'),
subtitle: new Text(profile.gender),
trailing: const Icon(Icons.arrow_drop_down),
dense: true,
),
onTap: () async {
await showModalBottomSheet<void>(
context: context,
builder: (BuildContext context){
return _buildGenderBottomPicker();
},
);
}
);
}
</code></pre>
<p>Snapshot:
(I have marked the misalignment)
<a href="https://i.stack.imgur.com/mgCSU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mgCSU.png" alt="enter image description here"></a></p> | 0 | 1,662 |
Client network socket disconnected before secure TLS connection was established Node.js v13.0.1 | <p>When id add exports.create=functions.https.onRequest((req,res)=> and run command firebase deploy shows this result</p>
<pre><code>functions: Finished running predeploy script.
i functions: ensuring necessary APIs are enabled...
+ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (40.37 KB) for uploading
! functions: Upload Error: Server Error. Client network socket disconnected before secure TLS connection was established
Error: Server Error. Client network socket disconnected before secure TLS connection was established
</code></pre>
<p>please check the code below.....</p>
<pre><code>const firebase = require('firebase-admin');
var config = {
apiKey: "AIzaSyAzf0Y4k7qvkWSWkwgsYjH9mrnFa_P9xt4",
authDomain: "fir-test-dc973.firebaseapp.com",
databaseURL: "https://fir-test-dc973.firebaseio.com/",
storageBucket: "gs://fir-test-dc973.appspot.com/"
};
firebase.initializeApp(config);
exports.create=functions.https.onRequest((req,res)=>{
var data=JSON.parse(req.body);
var user_id=data.user_id;
var language_id=data.language_id;
firebase.database().ref("game_room/").orderByChild("availability").equalTo(1).limitToFirst(1).once('value', ((snapshot)=> {
console.log("user_id ",user_id);
if (snapshot.val() !== null) {
console.log("available");
var childKey = Object.keys(snapshot.val());
console.log("gameroom ", childKey);
const userQuery = firebase.database().ref(`game_room/${childKey}`).once('value');
const language_id1 = userQuery.val().language_id;
if (language_id === language_id1) {
firebase.database().ref(`game_room/${childKey}/${user_id}`).update({
"status": true,
"right": 0,
"wrong": 0,
"que_no": 0,
"sel_ans": "",
});
firebase.database().ref(`game_room/${childKey}`).update({
"availability": 2,
});
}else{
createGameRoom();
}
console.log(snapshot.val());
}
else
{
createGameRoom();
}
}));
function createGameRoom() {
console.log("not available");
var ref=firebase.database().ref('game_room/').push({
"availability":1,
"language_id":language_id,
});
console.log(ref.key);
var key=ref.key;
console.log(key);
var ref1= firebase.database().ref(`game_room/${key}/${user_id}`).update({//.push({
//ref.set({
"status":true,
"right":0,
"wrong":0,
"que_no":0,
"sel_ans":"",
});
}
res.send({"code":user_id});
});```
log is here
[debug] [2020-01-03T13:50:53.722Z] <<< HTTP RESPONSE 200
[debug] [2020-01-03T13:50:53.725Z] >>> HTTP REQUEST PUT https://storage.googleapis.com/gcf-upload-us-central1-46ce5050-804a-4464-a2b2-569f0e4aaa93/75a761e4-936f-4b66-8f59-bb043b386f8d.zip?GoogleAccessId=service-853915451227@gcf-admin-robot.iam.gserviceaccount.com&Expires=1578061220&Signature=KBV5Gmv3OObNlC8%2BuCwYptBWjPI%2BhGblYX644ugU15FPwwFITQ3VDSIM7%2F9xsK2UqjFhdjx8s2inymbffxoemRmN1mKqPbHGP0ZFCy%2FDQUAHR%2FUccF%2FtRBiG2EQ0oaU5m9T7NoTs1NnVmDNhGz25mIGNdkO0efv8ZOqfXCYOSLV1jbgQtUGv%2FB%2ButjsTB3b6nxBOwHj7HbsFt1pB4uqGmVitGxj0JvxOhSAK6pCWXrsbWgL%2FnnoktYhhyMWFt9YgTSdWB36OeigQCdVldRVIodpaa3aShfDwMRPQCktgQQWZX0tAPsScs62i5Y11PLvSk2VeGxFFZgAyEA1XrzPjyg%3D%3D
<request body omitted>
[warn] ! functions: Upload Error: Server Error. Client network socket disconnected before secure TLS connection was established
[debug] [2020-01-03T13:51:04.100Z] Error: Client network socket disconnected before secure TLS connection was established
at connResetException (internal/errors.js:575:14)
at TLSSocket.onConnectEnd (_tls_wrap.js:1361:19)
at Object.onceWrapper (events.js:299:28)
at TLSSocket.emit (events.js:215:7)
at TLSSocket.EventEmitter.emit (domain.js:478:20)
at endReadableNT (_stream_readable.js:1198:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
[error]
[error] Error: Server Error. Client network socket disconnected before secure TLS connection was established
</code></pre> | 0 | 2,331 |
show data from database to listView Android | <p>I am trying to show all my data from my database into the listview</p>
<p>Code to create database:</p>
<p>DataHander.java</p>
<pre><code>package com.example.testingforstack;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataHandler {
public static final String NAME = "name";
public static final String EMAIL = "email";
public static final String TABLE_NAME = "mytable";
public static final String DATA_BASE_NAME = "mydatabase";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_CREATE = "create table mytable (name text not null, email text not null);";
DataBaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx){
this.ctx = ctx;
dbhelper = new DataBaseHelper(ctx);
}
public static class DataBaseHelper extends SQLiteOpenHelper{
public DataBaseHelper(Context ctx) {
super(ctx, DATA_BASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db){
try{
db.execSQL(TABLE_CREATE);
}catch (SQLException e){
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
//db.execSQL("DROP TABLE IF EXISTS mytable");
onCreate(db);
}
}
public DataHandler open(){
db = dbhelper.getReadableDatabase();
return this;
}
public void close(){
dbhelper.close();
}
public long insertData(String name, String email){
ContentValues content = new ContentValues();
content.put(NAME, name);
content.put(EMAIL, email);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor returnData(){
return db.query(TABLE_NAME, new String[] {NAME, EMAIL}, null, null, null, null, null);
}
}
</code></pre>
<p>mainActivity.java</p>
<pre><code>package com.example.testingforstack;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button save, load;
EditText name, email;
DataHandler handler;
String getName, getEmail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save = (Button) findViewById(R.id.save);
load = (Button) findViewById(R.id.load);
name = (EditText) findViewById(R.id.name);
email = (EditText) findViewById(R.id.email);
save.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getName = name.getText().toString();
String getEmail = email.getText().toString();
handler = new DataHandler(getBaseContext());
handler.open();
long id = handler.insertData(getName, getEmail);
insertSuccess();
//Toast.makeText(getBaseContext(), "Data inserted", Toast.LENGTH_LONG).show();
handler.close();
}
});
load.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getName = "";
getEmail = "";
handler = new DataHandler(getBaseContext());
handler.open();
Cursor C = handler.returnData();
if(C.moveToFirst()){
do{
getName = C.getString(0);
getEmail = C.getString(1);
}while(C.moveToNext());
}
handler.close();
loadSuccess();
//Toast.makeText(getBaseContext(), "Name: "+getName+", Email: "+getEmail, Toast.LENGTH_LONG).show();
}
});
}
public void insertSuccess()
{
AlertDialog.Builder insertData = new AlertDialog.Builder(this);
insertData.setTitle("Info");
insertData.setMessage("Data Inserted");
insertData.setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int value) {
// TODO Auto-generated method stub
arg0.dismiss();
}
});
insertData.show();
}
public void loadSuccess()
{
AlertDialog.Builder loadData = new AlertDialog.Builder(this);
loadData.setTitle("Info");
loadData.setMessage("Name: "+getName+" & your email: "+getEmail);
loadData.setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int value) {
// TODO Auto-generated method stub
arg0.dismiss();
}
});
loadData.show();
}
@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;
}
}
</code></pre>
<p>I have two button <code>save</code> and <code>load</code>. I have successfully implemented the save button to save the user name and email. However, I don't really know to load the data into the listview. How to do that?</p> | 0 | 2,579 |
Gtest: test compiling error | <p>I'm trying to test a motor control lib I've wrote with googletest but I'm not been to compile the test's codes.
The test are in a file named test.cpp such as the following:</p>
<pre><code>#include <gtest/gtest.h>
#include "../motor.hpp"
TEST(constructorTest, contructorDefault)
{
}
</code></pre>
<p>And I've put a the tests main function in an other file named main.cpp.</p>
<pre><code>#include <gtest/gtest.h>
#include "../motor.hpp"
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc,argv);
RUN_ALL_TESTS();
}
</code></pre>
<p>To compile I've excecuted the following line:</p>
<pre><code>g++ main.cpp test.cpp ../motor.cpp -o test
</code></pre>
<p>The result I get is:</p>
<pre><code>main.cpp:8:17: warning: ignoring return value of ‘int RUN_ALL_TESTS()’, declared with attribute warn_unused_result [-Wunused-result]
RUN_ALL_TESTS();
^
/tmp/ccZ5BaBH.o: In function `main':
main.cpp:(.text+0x1e): undefined reference to `testing::InitGoogleTest(int*, char**)'
/tmp/ccZ5BaBH.o: In function `RUN_ALL_TESTS()':
main.cpp:(.text._Z13RUN_ALL_TESTSv[_Z13RUN_ALL_TESTSv]+0x5): undefined reference to `testing::UnitTest::GetInstance()'
main.cpp:(.text._Z13RUN_ALL_TESTSv[_Z13RUN_ALL_TESTSv]+0xd): undefined reference to `testing::UnitTest::Run()'
/tmp/ccFuAMp3.o: In function `__static_initialization_and_destruction_0(int, int)':
test.cpp:(.text+0x5c): undefined reference to `testing::internal::GetTestTypeId()'
test.cpp:(.text+0x84): undefined reference to `testing::internal::MakeAndRegisterTestInfo(char const*, char const*, char const*, char const*, void const*, void (*)(), void (*)(), testing::internal::TestFactoryBase*)'
/tmp/ccFuAMp3.o: In function `constructorTest_contructorDefault_Test::constructorTest_contructorDefault_Test()':
test.cpp:(.text._ZN38constructorTest_contructorDefault_TestC2Ev[_ZN38constructorTest_contructorDefault_TestC5Ev]+0x14): undefined reference to `testing::Test::Test()'
/tmp/ccFuAMp3.o:(.rodata._ZTV38constructorTest_contructorDefault_Test[_ZTV38constructorTest_contructorDefault_Test]+0x20): undefined reference to `testing::Test::SetUp()'
/tmp/ccFuAMp3.o:(.rodata._ZTV38constructorTest_contructorDefault_Test[_ZTV38constructorTest_contructorDefault_Test]+0x28): undefined reference to `testing::Test::TearDown()'
/tmp/ccFuAMp3.o: In function `constructorTest_contructorDefault_Test::~constructorTest_contructorDefault_Test()':
test.cpp:(.text._ZN38constructorTest_contructorDefault_TestD2Ev[_ZN38constructorTest_contructorDefault_TestD5Ev]+0x1f): undefined reference to `testing::Test::~Test()'
/tmp/ccFuAMp3.o:(.rodata._ZTI38constructorTest_contructorDefault_Test[_ZTI38constructorTest_contructorDefault_Test]+0x10): undefined reference to `typeinfo for testing::Test'
collect2: error: ld returned 1 exit status
</code></pre>
<p>If I remove the test.cpp of the compiling line I get this other result:</p>
<pre><code>main.cpp: In function ‘int main(int, char**)’:
main.cpp:8:17: warning: ignoring return value of ‘int RUN_ALL_TESTS()’, declared with attribute warn_unused_result [-Wunused-result]
RUN_ALL_TESTS();
^
/tmp/cc61r6NU.o: In function `main':
main.cpp:(.text+0x1e): undefined reference to `testing::InitGoogleTest(int*, char**)'
/tmp/cc61r6NU.o: In function `RUN_ALL_TESTS()':
main.cpp:(.text._Z13RUN_ALL_TESTSv[_Z13RUN_ALL_TESTSv]+0x5): undefined reference to `testing::UnitTest::GetInstance()'
main.cpp:(.text._Z13RUN_ALL_TESTSv[_Z13RUN_ALL_TESTSv]+0xd): undefined reference to `testing::UnitTest::Run()'
collect2: error: ld returned 1 exit status
</code></pre>
<p>What am I doing wrong?</p>
<p><strong>EDIT</strong></p>
<p>Look like What @RippeR says is right, but now I getting the following error:</p>
<pre><code>/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../../lib/libgtest.so: undefined reference to `pthread_key_create'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../../lib/libgtest.so: undefined reference to `pthread_getspecific'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../../lib/libgtest.so: undefined reference to `pthread_key_delete'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../../lib/libgtest.so: undefined reference to `pthread_setspecific'
</code></pre>
<p>Do I have to include something else?</p>
<p><strong>Solution</strong>
The problem was solve adding the -lpthread flag to compile the test.</p> | 0 | 1,648 |
entitymanager persist does not save to database | <p>I'm currently facing a problem when trying to save to my database using the persist method from an entitymanager. When executing it, it does not produce an exception but it doesn't save the object to my database. Reading objects that were inserted manually does work. </p>
<p><strong>GenericDAOImpl</strong></p>
<pre><code>package be.greg.PaymentDatabase.DAO;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
public abstract class GenericDaoImpl<T> implements GenericDao<T> {
@PersistenceContext
protected EntityManager em;
private Class<T> type;
String entity;
@SuppressWarnings({ "unchecked", "rawtypes" })
public GenericDaoImpl() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
type = (Class) pt.getActualTypeArguments()[0];
}
@Override
public long countAll(final Map<String, Object> params) {
final StringBuffer queryString = new StringBuffer(
"SELECT count(o) from ");
queryString.append(type.getSimpleName()).append(" o ");
// queryString.append(this.getQueryClauses(params, null));
final Query query = this.em.createQuery(queryString.toString());
return (Long) query.getSingleResult();
}
@Override
@Transactional
public T create(final T t) {
this.em.persist(t);
return t;
}
@Override
public void delete(final Object id) {
this.em.remove(this.em.getReference(type, id));
}
@Override
public T find(final Object id) {
return (T) this.em.find(type, id);
}
@Override
public T update(final T t) {
return this.em.merge(t);
}
@SuppressWarnings("unchecked")
@Override
@Transactional
public List<T> findAll() {
Query query = em.createQuery("select x from " + getEntityName() + " x");
return (List<T>) query.getResultList();
}
public String getEntityName() {
if (entity == null) {
Entity entityAnn = (Entity) type.getAnnotation(Entity.class);
if (entityAnn != null && !entityAnn.name().equals("")) {
entity = entityAnn.name();
} else {
entity = type.getSimpleName();
}
}
return entity;
}
}
</code></pre>
<p><strong>AuthorizationV2DAOImpl</strong></p>
<pre><code> package be.greg.PaymentDatabase.DAO;
import org.springframework.stereotype.Repository;
import be.greg.PaymentDatabase.model.Authorization;
@Repository
public class AuthorizationV2DAOImpl extends GenericDaoImpl<Authorization>
implements AuthorizationV2DAO {
}
</code></pre>
<p><strong>AuthorizationService</strong></p>
<pre><code>package be.greg.PaymentDatabase.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import be.greg.PaymentDatabase.DAO.AuthorizationV2DAOImpl;
import be.greg.PaymentDatabase.model.Authorization;
@Service
public class AuthorizationService {
@Autowired
private AuthorizationV2DAOImpl authorizationDAO;
public Authorization getAuthorization(int id){
return authorizationDAO.find(id);
}
public List<Authorization> getAllAuthorizations(){
return authorizationDAO.findAll();
}
public void createAuthorization(Authorization authorization)
{
authorizationDAO.create(authorization);
}
}
</code></pre>
<p><strong>Authorization</strong></p>
<pre><code>package be.greg.PaymentDatabase.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "authorization")
public class Authorization {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(length = 32, nullable = false)
private String clientId;
@Column(length = 32, nullable = false)
private String acquiringInstitutionId;
@Column(length = 32, nullable = false)
private String cardAcceptorTerminalId;
@Column(length = 32, nullable = false)
private String merchantTransactionTimestamp;
@Column(length = 32, nullable = false)
private String industry;
@Column(length = 32, nullable = false)
private String accountNumber;
@Column(nullable = false)
private boolean maskedAccount;
@Column(length = 11, nullable = false)
private int expiryMonth;
@Column(length = 11, nullable = false)
private int expiryYear;
@Column(length = 32, nullable = false)
private String securityCode;
@Column(length = 32, nullable = false)
private String line1;
@Column(length = 32, nullable = true)
private String line2;
@Column(length = 32, nullable = true)
private String city;
@Column(length = 32, nullable = true)
private String countrySubdivision;
@Column(length = 32, nullable = false)
private String postalCode;
@Column(length = 32, nullable = false)
private String country;
@Column(length = 32, nullable = false)
private String clientReference;
@Column(length = 32, nullable = false)
private String currency;
@Column(length = 11, nullable = false)
private int value;
@Column(length = 32, nullable = false)
private String ecommerceIndicator;
@Column(length = 32, nullable = false)
private String transactionId;
@Column(length = 32, nullable = false)
private String token;
Constructor, getters and setters ...
</code></pre>
<p><strong>spring-context.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:component-scan base-package="be.greg.PaymentDatabase" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="jdbcPropertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:project.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
p:username="${jdbc.username}" />
<bean id="persistenceUnitManager"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
<property name="defaultDataSource" ref="dataSource" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="entityManager" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
</code></pre>
<p><strong>persistance.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="entityManager"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<validation-mode>NONE</validation-mode>
<class>be.greg.PaymentDatabase.model.Authorization</class>
<class>be.greg.PaymentDatabase.model.AuthorizationResponse</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
</code></pre>
<p><strong>hibernate.cfg.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/paymentdatabase?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="be.greg.PaymentDatabase.model.Authorization" />
<mapping class="be.greg.PaymentDatabase.model.AuthorizationResponse" />
</session-factory>
</hibernate-configuration>
</code></pre>
<p><strong>runnable main class</strong></p>
<pre><code>package be.greg.PaymentDatabase.Tests;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import be.greg.PaymentDatabase.model.Authorization;
import be.greg.PaymentDatabase.service.AuthorizationService;
@Component
public class HibernateDatabaseTest {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext(
"/spring-context.xml");
HibernateDatabaseTest p = context.getBean(HibernateDatabaseTest.class);
Authorization authorization = new Authorization("000091095650", "1340",
"001", "2012-01-06T09:30:47Z", "MOTO", "4417122900000002",
false, 12, 12, "382", "100", null, null, null, "33606", "USA",
"12345678901234567", "USD", 1540, "5",
"Q0JLSkIyODlWMVBaTDRURFhYV0Y=", "Q0JLSkIyODlWMVBaTDRURFhYV0Y=");
p.start(authorization);
}
@Autowired
private AuthorizationService authorizationService;
private void start(Authorization authorization) {
authorizationService.createAuthorization(authorization);
List<Authorization> list = authorizationService.getAllAuthorizations();
for (Authorization authorizations : list) {
System.out.println(authorizations.getClientId());
}
}
}
</code></pre>
<p>When I add em.flush in the GenericDaoImpl class right after the persist, it gives following exception </p>
<pre><code>Exception in thread "main" javax.persistence.TransactionRequiredException: no transaction is in progress
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.checkTransactionNeeded(AbstractEntityManagerImpl.java:1171)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:1332)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:366)
at com.sun.proxy.$Proxy24.flush(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:241)
at com.sun.proxy.$Proxy20.flush(Unknown Source)
at be.greg.PaymentDatabase.DAO.GenericDaoImpl.create(GenericDaoImpl.java:50)
at be.greg.PaymentDatabase.service.AuthorizationService.createAuthorization(AuthorizationService.java:35)
at be.greg.PaymentDatabase.Tests.HibernateDatabaseTest.start(HibernateDatabaseTest.java:36)
at be.greg.PaymentDatabase.Tests.HibernateDatabaseTest.main(HibernateDatabaseTest.java:27)
</code></pre>
<p>So I assume it has to do something with the transaction or perhaps the fact that one hasn't been made. But I have not found the cause for this problem yet</p>
<p>Thanks in advance!</p>
<p><em>Edit</em></p>
<p>These are the dependencies for Spring and Hibernate that I use</p>
<pre><code> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.4.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
</code></pre> | 0 | 6,424 |
Custom Events in Xamarin Page c# | <p>I currently am facing the following issue:</p>
<p>I am trying to fire an event when a user entered valid credentials so that I can switch page and so on.</p>
<p>The Issue is I am unable to hook into the event for some reason (altho I'm pretty sure it will be something stupid).</p>
<p>The Class firing the event:</p>
<pre><code>namespace B2B
{
public partial class LoginPage : ContentPage
{
public event EventHandler OnAuthenticated;
public LoginPage ()
{
InitializeComponent ();
}
void onLogInClicked (object sender, EventArgs e)
{
loginActivity.IsRunning = true;
errorLabel.Text = "";
RestClient client = new RestClient ("http://url.be/api/");
var request = new RestRequest ("api/login_check", Method.POST);
request.AddParameter("_username", usernameText.Text);
request.AddParameter("_password", passwordText.Text);
client.ExecuteAsync<Account>(request, response => {
Device.BeginInvokeOnMainThread ( () => {
loginActivity.IsRunning = false;
if(response.StatusCode == HttpStatusCode.OK)
{
if(OnAuthenticated != null)
{
OnAuthenticated(this, new EventArgs());
}
}
else if(response.StatusCode == HttpStatusCode.Unauthorized)
{
errorLabel.Text = "Invalid Credentials";
}
});
});
}
}
}
</code></pre>
<p>And in the 'main class'</p>
<pre><code>namespace B2B
{
public class App : Application
{
public App ()
{
// The root page of your application
MainPage = new LoginPage();
MainPage.OnAuthenticated += new EventHandler (Authenticated);
}
static void Authenticated(object source, EventArgs e) {
Console.WriteLine("Authed");
}
}
}
</code></pre>
<p>When I try to build the application I get:</p>
<p><strong>Type 'Xamarin.Forms.Page' does not containt a definition for 'OnAuthenticated' and no extension method OnAuthenticated</strong></p>
<p>I've tried adding a delegate inside the LoginPage class, outside of it but it doesn't help.</p>
<p>Could anyone be so kind to point me out what <em>stupid</em> mistake I am making ?</p> | 0 | 1,147 |
Using RVM on Ubuntu 12.04 to use Rails. The program 'rails' is currently not installed | <p>I installed RVM from scratch following the installation guide on the official website. I installed Rails, created a dummy app and everything worked fine.</p>
<p>I shut off my machine.</p>
<p>The next morning, I turned on the machine again (cold boot) and the tried running "<code>rails -v</code>" from the console, but I get the following error message:</p>
<blockquote>
<p>sergio@Sergio-work ~ $ rails -v </p>
<p>The program 'rails' is currently not
installed. You can install it by typing: sudo apt-get install rails</p>
</blockquote>
<p>I can run <code>ruby -v</code> just fine, and get the following message:</p>
<blockquote>
<p>sergio@Sergio-work ~ $ ruby -v</p>
<p>ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]</p>
</blockquote>
<p>I can also run <code>gem list</code> just fine, output:</p>
<pre><code>sergio@Sergio-work ~ $ gem list
*** LOCAL GEMS ***
actionmailer (3.2.3)
actionpack (3.2.3)
activemodel (3.2.3)
activerecord (3.2.3)
activeresource (3.2.3)
activesupport (3.2.3)
arel (3.0.2)
builder (3.0.0)
bundler (1.1.4)
coffee-rails (3.2.2)
coffee-script (2.2.0)
coffee-script-source (1.3.3)
erubis (2.7.0)
execjs (1.4.0)
faraday (0.8.0)
google_drive (0.3.0)
hike (1.2.1)
httpauth (0.1)
i18n (0.6.0)
journey (1.0.3)
jquery-rails (2.0.2)
json (1.7.3)
libv8 (3.3.10.4 x86_64-linux)
mail (2.4.4)
mime-types (1.18)
multi_json (1.3.6, 1.3.5)
multipart-post (1.1.5)
mysql2 (0.3.11)
nokogiri (1.5.0)
oauth (0.4.6)
oauth2 (0.7.1)
polyglot (0.3.3)
rack (1.4.1)
rack-cache (1.2)
rack-ssl (1.3.2)
rack-test (0.6.1)
rails (3.2.3)
railties (3.2.3)
rake (0.9.2.2)
rdoc (3.12)
rubygems-bundler (1.0.2)
rvm (1.11.3.3)
sass (3.1.19, 3.1.18)
sass-rails (3.2.5)
sprockets (2.1.3)
sqlite3 (1.3.6)
therubyracer (0.10.1)
thor (0.14.6)
tilt (1.3.3)
treetop (1.4.10)
tzinfo (0.3.33)
uglifier (1.2.4)
</code></pre>
<p>Why doesn't my <code>rails -v</code> command work anymore? I used to have this "hack" where I would need to run a command in terminal, "<code>source something something</code>" once, before rails would be "recognized" as an actual command. I had to this once per terminal, meaning if I closed a terminal I had to re-run this after opening a new window terminal.</p>
<p>I can't seem to find this command anymore on the Help section for RVM (where I originally found it) and since I'm kind of new to Linux, these advanced configurations are complex to me.</p>
<p>Any ideas?</p> | 0 | 1,077 |
How to debug EXC_BAD_ACCESS that occurs only on release target for an iPhone app? | <p>I'm developing an iPhone application. I have an <code>EXC_BAD_ACCESS</code> that occurs only in the release target; when I build the debug target the exception does not occur. However, when I set the <code>NSZombieEnabled</code> environment variable to <code>YES</code>, I still get the <code>EXC_BAD_ACCESS</code> with no further information. Is it even possible for <code>NSZombieEnabled</code> to work when executing the release target? I don't see why not, since gdb is running in both cases...</p>
<p><strong>Update</strong>: here is a printout of the top of the stack:</p>
<pre><code>#0 0x33369ebc in objc_msgSend ()
#1 0x3144f968 in -[EAInputStream _streamEventTrigger] ()
#2 0x3144fe78 in __streamEventTrigger ()
#3 0x338ae3a6 in CFRunLoopRunSpecific ()
#4 0x338adc1e in CFRunLoopRunInMode ()
#5 0x32ed6966 in -[NSRunLoop(NSRunLoop) runMode:beforeDate:] ()
#6 0x00005b06 in -[IOStreamDelegate removeMsg:] (self=0x142cc0, _cmd=<value temporarily unavailable, due to optimizations>, message=0x2fffe544) at /Users/robertmoretti/Documents/XXXXXXX/IOStreamDelegate.m:191
</code></pre>
<p>Here is a gdb session from inside the objc_msgSend call at the top:</p>
<pre><code>(gdb) p/x $r0
$6 = 0x3100000
(gdb) x/s $r1
0x32d7cff8: "release"
(gdb) disassemble $pc
Dump of assembler code for function objc_msgSend:
0x33369ea8 <objc_msgSend+0>: teq r0, #0 ; 0x0
0x33369eac <objc_msgSend+4>: moveq r1, #0 ; 0x0
0x33369eb0 <objc_msgSend+8>: bxeq lr
0x33369eb4 <objc_msgSend+12>: push {r3, r4, r5, r6}
0x33369eb8 <objc_msgSend+16>: ldr r4, [r0]
0x33369ebc <objc_msgSend+20>: ldr r5, [r4, #8]
0x33369ec0 <objc_msgSend+24>: ldr r6, [r5]
0x33369ec4 <objc_msgSend+28>: add r3, r5, #8 ; 0x8
0x33369ec8 <objc_msgSend+32>: and r5, r6, r1, lsr #2
0x33369ecc <objc_msgSend+36>: ldr r4, [r3, r5, lsl #2]
0x33369ed0 <objc_msgSend+40>: teq r4, #0 ; 0x0
0x33369ed4 <objc_msgSend+44>: add r5, r5, #1 ; 0x1
0x33369ed8 <objc_msgSend+48>: beq 0x33369efc <objc_msgSend+84>
0x33369edc <objc_msgSend+52>: ldr r12, [r4]
0x33369ee0 <objc_msgSend+56>: teq r1, r12
0x33369ee4 <objc_msgSend+60>: and r5, r5, r6
0x33369ee8 <objc_msgSend+64>: bne 0x33369ecc <objc_msgSend+36>
0x33369eec <objc_msgSend+68>: ldr r12, [r4, #8]
0x33369ef0 <objc_msgSend+72>: teq r4, r4
0x33369ef4 <objc_msgSend+76>: pop {r3, r4, r5, r6}
0x33369ef8 <objc_msgSend+80>: bx r12
0x33369efc <objc_msgSend+84>: pop {r3, r4, r5, r6}
0x33369f00 <objc_msgSend+88>: b 0x33369f04 <objc_msgSend_uncached>
End of assembler dump.
(gdb) p/x *$r0
$9 = 0x0
</code></pre>
<p>The exception occurs on the line <code>0x33369ebc <objc_msgSend+20>: ldr r5, [r4, #8]</code>. <code>r4</code> has just been given the value pointed to by <code>r0</code>, which happens to be 0. I am wondering what is supposed to be in the memory region of <code>0x3100000</code>. Here's a memory dump of that area:</p>
<pre><code>(gdb) x/256w 0x3100000
0x3100000: 0x00000000 0x0000a293 0xaa650505 0x00000000
0x3100010: 0x0000a294 0xaa670505 0x00000000 0x0000a295
0x3100020: 0xaa690505 0x00000000 0x0000a296 0xaa6b0505
0x3100030: 0x00000000 0x0000a297 0xaa6d0505 0x00000000
0x3100040: 0x0000a298 0xaa6f0505 0x00000000 0x0000a299
0x3100050: 0xaa710505 0x00000000 0x0000a29a 0xaa730505
0x3100060: 0x00000000 0x0000a29b 0xaa750505 0x00000000
0x3100070: 0x0000a29c 0xaa770505 0x00000000 0x0000a29d
0x3100080: 0xaa790505 0x00000000 0x0000a29e 0xaa7b0505
0x3100090: 0x00000000 0x0000a29f 0xaa7d0505 0x00000000
0x31000a0: 0x0000a2a0 0xaa7f0505 0x00000000 0x0000a2a1
0x31000b0: 0xaa810505 0x00000000 0x0000a2a2 0xaa830505
0x31000c0: 0x00000000 0x0000a2a3 0xaa850505 0x00000000
0x31000d0: 0x0000a2a4 0xaa870505 0x00000000 0x0000a2a5
0x31000e0: 0xaa890505 0x00000000 0x0000a2a6 0xaa8b0505
0x31000f0: 0x00000000 0x0000a2a7 0xaa8d0505 0x00000000
0x3100100: 0x0000a2a8 0xaa8f0505 0x00000000 0x0000a2a9
0x3100110: 0xaa910505 0x00000000 0x0000a2aa 0xaa930505
0x3100120: 0x00000000 0x0000a2ab 0xaa950505 0x00000000
0x3100130: 0x0000a2ac 0xaa970505 0x00000000 0x0000a2ad
0x3100140: 0xaa990505 0x00000000 0x0000a2ae 0xaa9b0505
0x3100150: 0x00000000 0x0000a2af 0xaa9d0505 0x00000000
0x3100160: 0x0000a2b0 0xaa9f0505 0x00000000 0x0000a2b1
0x3100170: 0xaaa10505 0x00000000 0x0000a2b2 0xaaa30505
0x3100180: 0x00000000 0x0000a2b3 0xaaa50505 0x00000000
0x3100190: 0x0000a2b4 0xaaa70505 0x00000000 0x0000a2b5
0x31001a0: 0xaaa90505 0x00000000 0x0000a2b6 0xaaab0505
0x31001b0: 0x00000000 0x0000a2b7 0xaaad0505 0x00000000
0x31001c0: 0x0000a2b8 0xaaaf0505 0x00000000 0x0000a2b9
0x31001d0: 0xaab10505 0x00000000 0x0000a2ba 0xaab30505
0x31001e0: 0x00000000 0x0000a2bb 0xaab50505 0x00000000
0x31001f0: 0x0000a2bc 0xaab70505 0x00000000 0x0000a2bd
0x3100200: 0xaab90505 0x00000000 0x0000a2be 0xaabb0505
0x3100210: 0x00000000 0x0000a2bf 0xaabd0505 0x00000000
0x3100220: 0x0000a2c0 0xaabf0505 0x00000000 0x0000a2c1
0x3100230: 0xaac10505 0x00000000 0x0000a2c2 0xaac30505
0x3100240: 0x00000000 0x0000a2c3 0xaac50505 0x00000000
0x3100250: 0x0000a2c4 0xaac70505 0x00000000 0x0000a2c5
0x3100260: 0xaac90505 0x00000000 0x0000a2c6 0xaacb0505
0x3100270: 0x00000000 0x0000a2c7 0xaacd0505 0x00000000
0x3100280: 0x0000a2c8 0xaacf0505 0x00000000 0x0000a2c9
0x3100290: 0xaad10505 0x00000000 0x0000a2ca 0xaad30505
0x31002a0: 0x00000000 0x0000a2cb 0xaad50505 0x00000000
0x31002b0: 0x0000a2cc 0xaad70505 0x00000000 0x0000a2cd
0x31002c0: 0xaad90505 0x00000000 0x0000a2ce 0xaadb0505
0x31002d0: 0x00000000 0x0000a2cf 0xaadd0505 0x00000000
0x31002e0: 0x0000a2d0 0xaadf0505 0x00000000 0x0000a2d1
0x31002f0: 0xaae10505 0x00000000 0x0000a2d2 0xaae30505
0x3100300: 0x00000000 0x0000a2d3 0xaae50505 0x00000000
0x3100310: 0x0000a2d4 0xaae70505 0x00000000 0x0000a2d5
0x3100320: 0xaae90505 0x00000000 0x0000a2d6 0xaaeb0505
0x3100330: 0x00000000 0x0000a2d7 0xaaed0505 0x00000000
0x3100340: 0x0000a2d8 0xaaef0505 0x00000000 0x0000a2d9
0x3100350: 0xaaf10505 0x00000000 0x0000a2da 0xaaf30505
0x3100360: 0x00000000 0x0000a2db 0xaaf50505 0x00000000
0x3100370: 0x0000a2dc 0xaaf70505 0x00000000 0x0000a2dd
0x3100380: 0xaaf90505 0x00000000 0x0000a2de 0xaafb0505
0x3100390: 0x00000000 0x0000a2df 0xaafd0505 0x00000000
0x31003a0: 0x0000a2e0 0xab050505 0x00000000 0x0000a2e1
0x31003b0: 0xab070505 0x00000000 0x0000a2e2 0xab090505
0x31003c0: 0x00000000 0x0000a2e3 0xab0b0505 0x00000000
0x31003d0: 0x0000a2e4 0xab0d0505 0x00000000 0x0000a2e5
0x31003e0: 0xab0f0505 0x00000000 0x0000a2e6 0xab110505
0x31003f0: 0x00000000 0x0000a2e7 0xab130505 0x00000000
</code></pre>
<p>I don't really know what else to try; hopefully someone with more iphone experience will be able to recognize this memory as something meaningful.</p>
<p><strong>Update 2:</strong> I just discovered that the problem only occurs when compiling with -O2, -O3, and -Os. Not sure what that implies.</p> | 0 | 3,600 |
Mockito verify unit test - Wanted but not invoked. Actually, there were zero interactions with this mock | <p>At first I want to sorry for my english.</p>
<p>I started to make some unit tests (i've never done this before, i'm a new guy in programming). </p>
<p>I have to test simple adding product to database (DynamoDB) method using mockito.verify but I have </p>
<pre><code>"Wanted but not invoked. Actually, there were zero interactions with this mock."
</code></pre>
<p>Error and I don't know what to do.</p>
<p>This is my method code (in KitchenService class): </p>
<pre><code>public Product addProduct(Product content) {
ObjectMapper objectMapper = new ObjectMapper();
String mediaJSON = null;
String authorJSON = null;
String productKindsJSON = null;
try {
mediaJSON = objectMapper.writeValueAsString(content.getMedia());
authorJSON = objectMapper.writeValueAsString(content.getAuthor());
productKindsJSON = objectMapper.writeValueAsString(content.getProductKinds());
} catch (JsonProcessingException e) {
logger.log(e.getMessage());
}
Item item = new Item()
.withPrimaryKey("id", UUID.randomUUID().toString())
.with("name", content.getName())
.with("calories", content.getCalories())
.with("fat", content.getFat())
.with("carbo", content.getCarbo())
.with("protein", content.getProtein())
.with("productKinds", productKindsJSON)
.with("author", authorJSON)
.with("media", mediaJSON)
.with("approved", content.getApproved());
Item save = databaseController.saveProduct(PRODUCT_TABLE, item);
logger.log(save + " created");
return content;
}
</code></pre>
<p>And this is test code:</p>
<pre><code>@Test
public void addProduct() throws Exception {
KitchenService instance = mock(KitchenService.class);
Product expectedProduct = new Product();
expectedProduct.setName("kaszanka");
expectedProduct.setCalories(1000);
expectedProduct.setFat(40.00);
expectedProduct.setCarbo(20.00);
expectedProduct.setProtein(40.00);
expectedProduct.setProductKinds(Collections.singletonList(ProductKind.MEAT));
expectedProduct.setApproved(false);
Author expectedAuthor = new Author();
expectedAuthor.setId("testID");
expectedAuthor.setName("Endrju Golota");
expectedProduct.setAuthor(expectedAuthor);
Media expectedMedia = new Media();
expectedMedia.setMediaType(MediaType.IMAGE);
expectedMedia.setName("dupajasia");
expectedMedia.setUrl("http://blabla.pl");
expectedProduct.setMedia(expectedMedia);
verify(instance, times(1)).addProduct(expectedProduct);
}
</code></pre>
<p>This is what I got after test:</p>
<pre><code>Wanted but not invoked:
kitchenService.addProduct(
model.kitchen.Product@a0136253
);
-> at service.kitchen.KitchenServiceTest.addProduct(KitchenServiceTest.java:80)
Actually, there were zero interactions with this mock.
</code></pre>
<p>Can someone tell me what im doing wrong?</p> | 0 | 1,090 |
OpenCV's calcOpticalFlowPyrLK throws exception | <p>I have been trying to form a small optical flow example with OpenCV for a while now. Everything works except the function call calcOpticalFlowPyrLK, which prints the following failed assertion in the console window:</p>
<blockquote>
<p>OpenCV Error: Assertion failed (mytype == typ0 || (CV_MAT_CN(mytype) == CV_MAT_CV(type0) && ((1 << type0) & fixedDepthMask) != 0)) in unknown function, file ......\src\opencv\modules\core\src\matrix.cpp, line 1421</p>
</blockquote>
<p>The video that I'm parsing is separated into 300 images, labelled as "caml00000.jpeg", "caml00001.jpeg", ..., "caml00299.jpeg". Here is the code I wrote:</p>
<pre><code>#include <cv.h>
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
using namespace std;
int main( int argc, char** argv ){
char buff[100];
int numFrames=300;
char fileFormat[]="images/caml%05d.jpeg";
string winname="Test Window";
vector<Mat> imgVec(numFrames);
auto itrImg=begin(imgVec);
auto itrEnd=end(imgVec);
vector<Point2f> featuresPrevious;
vector<Point2f> featuresCurrent;
namedWindow( winname, CV_WINDOW_AUTOSIZE );
int fileNum=0;
while(itrImg!=itrEnd){
Mat& imgRef=*itrImg; //get this frame's Mat from the vector iterator
//Calculate the name of the file;
sprintf(buff,fileFormat,fileNum);
string fileName=buff;
//string fileName="kitty.jpg"; //attempted using a static picture as well
cout << fileName << endl;
Mat cImage=imread(fileName, CV_LOAD_IMAGE_GRAYSCALE);
cImage.convertTo(imgRef, CV_8U); //also tried CV_8UC1
featuresPrevious=std::move(featuresCurrent);
goodFeaturesToTrack(imgRef,featuresCurrent,30, 0.01, 30); //calculate the features for use in next iteration
if(!imgRef.data){ //this never executes, so there isn't a problem reading the files
cout << "File I/O Problem!" << endl;
getchar();
return 1;
}
if(fileNum>0){
Mat& lastImgRef=*(itrImg-1); //get the last frame's image
vector<Point2f> featuresNextPos;
vector<char> featuresFound;
vector<int> err;
calcOpticalFlowPyrLK(lastImgRef,imgRef,featuresPrevious,featuresNextPos,featuresFound,err); //problem line
//Draw lines connecting previous position and current position
for(size_t i=0; i<featuresNextPos.size(); i++){
if(featuresFound[i]){
line(imgRef,featuresPrevious[i],featuresNextPos[i],Scalar(0,0,255));
}
}
}
imshow(winname, imgRef);
waitKey(1000/60); //not perfect, but it'll do
++itrImg;
++fileNum;
}
waitKey(0);
return 0;
}
</code></pre>
<p>The only thing I've read about this exception is that it is caused when Mats are in different formats, however I've tried reading a static image (see code above regarding "kitty.jpg") and I still get the same failed assertion. Any ideas?</p> | 0 | 1,318 |
Spring WebClient - how to access response body in case of HTTP errors (4xx, 5xx)? | <p>I want to re-throw my exception from my "Database" REST API to my "Backend" REST API but I lose the original exception's message.</p>
<p>This is what i get from my "Database" REST API via Postman:</p>
<pre><code>{
"timestamp": "2020-03-18T15:19:14.273+0000",
"status": 400,
"error": "Bad Request",
"message": "I'm DatabaseException (0)",
"path": "/database/api/vehicle/test/0"
}
</code></pre>
<p>This part is ok.</p>
<p>This is what i get from my "Backend" REST API via Postman:</p>
<pre><code>{
"timestamp": "2020-03-18T15:22:12.801+0000",
"status": 400,
"error": "Bad Request",
"message": "400 BAD_REQUEST \"\"; nested exception is org.springframework.web.reactive.function.client.WebClientResponseException$BadRequest: 400 Bad Request from GET http://localhost:8090/database/api/vehicle/test/0",
"path": "/backend/api/vehicle/test/0"
}
</code></pre>
<p>As you can see the original "message" field is lost.</p>
<p>I use:</p>
<ul>
<li>Spring boot 2.2.5.RELEASE</li>
<li>spring-boot-starter-web</li>
<li>spring-boot-starter-webflux</li>
</ul>
<p>Backend and Database start with Tomcat (<a href="https://stackoverflow.com/questions/51377675/does-not-the-spring-boot-starter-web-and-spring-boot-starter-webflux-work-togeth">web and webflux in the same application</a>).</p>
<p>This is Backend:</p>
<pre><code> @GetMapping(path = "/test/{id}")
public Mono<Integer> test(@PathVariable String id) {
return vehicleService.test(id);
}
</code></pre>
<p>With vehicleService.test:</p>
<pre><code> public Mono<Integer> test(String id) {
return WebClient
.create("http://localhost:8090/database/api")
.get()
.uri("/vehicle/test/{id}", id)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Integer.class);
}
</code></pre>
<p>This is Database:</p>
<pre><code> @GetMapping(path = "/test/{id}")
public Mono<Integer> test(@PathVariable String id) throws Exception {
if (id.equals("0")) {
throw new DatabaseException("I'm DatabaseException (0)");
}
return Mono.just(Integer.valueOf(2));
}
</code></pre>
<p>I also tried with <code>return Mono.error(new DatabaseException("I'm DatabaseException (0)"));</code></p>
<p>And DatabaseException:</p>
<pre><code>public class DatabaseException extends ResponseStatusException {
private static final long serialVersionUID = 1L;
public DatabaseException(String message) {
super(HttpStatus.BAD_REQUEST, message);
}
}
</code></pre>
<p>It seems my Backend transforms the response and can't find any answer on internet.</p> | 0 | 1,094 |
Eclipse Git (EGit) unable to clone Git repository | <p>Basically, I can't find a workable URI for the EGit Clone Git Repository dialog.</p>
<p><img src="https://i.stack.imgur.com/r7HSD.png" alt="One attempt"></p>
<p>Using protocol git, just as from my command-line clone operation, I've tried various URIs with unsatisfactory results. Sometimes, I can't click the Next button:</p>
<pre><code>git://af-blackpearl.site
git:af-blackpearl.site:myproject
</code></pre>
<p>In other cases, I try (and I can click the Next button):</p>
<pre><code>git:af-blackpearl.site/myproject[.git] (with or without extension)
</code></pre>
<p>but, I get:</p>
<pre><code>Cannot list the available branches.
Reason:
git:af-blackpearl.site/rest-server:ProxyHTTP: java.io.IOException:
proxy error: Service Unavailable
</code></pre>
<p>When I try:</p>
<pre><code>git://af-blackpearl.site/myproject[.git] (with or without extension)
git://af-blackpearl.site/
</code></pre>
<p>I always get something like:</p>
<pre><code>Cannot list the available branches.
Reason:
git://af-blackpearl.site/myproject: Connection refused
</code></pre>
<p>Many thanks for any suggestion to follow up on.</p>
<p><strong>Useful Background</strong></p>
<ul>
<li>Git administrated using <em>gitolite</em></li>
<li>Git remote(s) on Linux host</li>
<li>My "client" host, Linux, is running Eclipse Helios</li>
<li>Been using Git via command line; works great</li>
</ul>
<p>This question is specifically about using the EGit (Eclipse plug-in) dialog. It is not about Git, using Git or even installing the plug-in--all of which do not seem troublesome. Simply, I've long been using Git from the command line and am just trying to use the Eclipse-Git integration now.</p>
<p>In <em>/etc/hosts</em>, I have a line:</p>
<pre><code>xxx.xxx.xxx.xxx af-blackpearl.site
</code></pre>
<p>for our local Git remote repository. Though I administer Git via a <em>gitolite-admin</em> project, the (physical, filesystem) path to the project I'd like to clone on af-blackpearl.site is</p>
<p><strong><em>/home/git/repositories/myproject.git</em></strong></p>
<p>From the command line, I'm used to cloning it from origin thus with consistent success:</p>
<pre><code>$ git clone git:af-blackpearl.site:myproject
</code></pre>
<p>Despite looking at the EGit (Google-hosted) documentation and much Googling, I'm having trouble adapting this to the EGit Clone Git Repository dialog (reached thus):</p>
<pre><code>File -> Import... -> Git -> Projects from Git -> Clone
</code></pre>
<p>Connection to remote:</p>
<pre><code>russ@russ-elite-book:~> ssh git@af-blackpearl.site
PTY allocation request failed on channel 0
hello russ, the gitolite version here is v2.0.1-2-g836faf9
the gitolite config gives you the following access:
R W NavigationServlet
R W gitolite-admin
R W ivysample
R W myproject
R W seam-catch
Connection to af-blackpearl.site closed.
</code></pre> | 0 | 1,044 |
Unable to open asset URL: file:///android_asset/www/cordova_plugins.json error android | <p>i am trying to create an android application using cordova. i followed the steps given in the documentation creating an android application using cordova but when i build, i get the following error:</p>
<pre><code>Unable to open asset URL: file:///android_asset/www/cordova_plugins.json
</code></pre>
<p>my config.xml file is as follows:</p>
<pre><code><widget xmlns = "http://www.w3.org/ns/widgets"
id = "io.cordova.helloCordova"
version = "2.0.0">
<name>Hello Cordova</name>
<description>
A sample Apache Cordova application that responds to the deviceready event.
</description>
<content src="index.html" />
<preference name="loglevel" value="DEBUG" />
<!--
<preference name="splashscreen" value="resourceName" />
<preference name="backgroundColor" value="0xFFF" />
<preference name="loadUrlTimeoutValue" value="20000" />
<preference name="InAppBrowserStorageEnabled" value="true" />
<preference name="disallowOverscroll" value="true" />
-->
<feature name="App">
<param name="android-package" value="org.apache.cordova.App"/>
</feature>
<feature name="Geolocation">
<param name="android-package" value="org.apache.cordova.GeoBroker"/>
</feature>
<feature name="Device">
<param name="android-package" value="org.apache.cordova.Device"/>
</feature>
<feature name="Accelerometer">
<param name="android-package" value="org.apache.cordova.AccelListener"/>
</feature>
<feature name="Compass">
<param name="android-package" value="org.apache.cordova.CompassListener"/>
</feature>
<feature name="Media">
<param name="android-package" value="org.apache.cordova.AudioHandler"/>
</feature>
<feature name="Camera">
<param name="android-package" value="org.apache.cordova.CameraLauncher"/>
</feature>
<feature name="Contacts">
<param name="android-package" value="org.apache.cordova.ContactManager"/>
</feature>
<feature name="File">
<param name="android-package" value="org.apache.cordova.FileUtils"/>
</feature>
<feature name="NetworkStatus">
<param name="android-package" value="org.apache.cordova.NetworkManager"/>
</feature>
<feature name="Notification">
<param name="android-package" value="org.apache.cordova.Notification"/>
</feature>
<feature name="Storage">
<param name="android-package" value="org.apache.cordova.Storage"/>
</feature>
<feature name="FileTransfer">
<param name="android-package" value="org.apache.cordova.FileTransfer"/>
</feature>
<feature name="Capture">
<param name="android-package" value="org.apache.cordova.Capture"/>
</feature>
<feature name="Battery">
<param name="android-package" value="org.apache.cordova.BatteryListener"/>
</feature>
<feature name="SplashScreen">
<param name="android-package" value="org.apache.cordova.SplashScreen"/>
</feature>
<feature name="Echo">
<param name="android-package" value="org.apache.cordova.Echo"/>
</feature>
<feature name="Globalization">
<param name="android-package" value="org.apache.cordova.Globalization"/>
</feature>
<feature name="InAppBrowser">
<param name="android-package" value="org.apache.cordova.InAppBrowser"/>
</feature>
<!-- Deprecated plugins element. Remove in 3.0 -->
<plugins>
<plugin name="PushPlugin" value="com.plugin.gcm.PushPlugin" />
<plugin name="HttpRequest" value="com.packagename.HttpRequestPlugin" />
</plugins>
</widget>
</code></pre>
<p>what may be the issue for this?</p> | 0 | 1,768 |
Error consuming webservice, content type "application/xop+xml" does not match expected type "text/xml" | <p>I'm having a weird issue when consuming a webservice for a product that my company has bought. The product is called Campaign Commander and it's made by a company called Email Vision. We're trying to use the "Data Mass Update SOAP API".</p>
<p>Whenever I try to call any of the methods on the webservice, the call actually succeeds but the client fails when processing the response and I get an exception.</p>
<p>The details of the errors are below, thanks for any help you guys can offer.</p>
<h2>Error using Web Reference (old style webservice client)</h2>
<p>When consume the service as a Web Reference I get an <code>InvalidOperationException</code> for any call that I make, with the following message:</p>
<pre><code>Client found response content type of 'multipart/related; type="application/xop+xml"; boundary="uuid:170e63fa-183c-4b18-9364-c62ca545a6e0"; start="<root.message@cxf.apache.org>"; start-info="text/xml"', but expected 'text/xml'.
The request failed with the error message:
--
--uuid:170e63fa-183c-4b18-9364-c62ca545a6e0
Content-Type: application/xop+xml; charset=UTF-8; type="text/xml";
Content-Transfer-Encoding: binary
Content-ID: <root.message@cxf.apache.org>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:openApiConnectionResponse xmlns:ns2="http://api.service.apibatchmember.emailvision.com/" xmlns:ns3="http://exceptions.service.apibatchmember.emailvision.com/">
<return>DpKTe-9swUeOsxhHH9t-uLPeLyg-aa2xk3-aKe9oJ5S9Yymrnuf1FxYnzpaFojsQSkSCbJsZmrZ_d3v2-7Hj</return>
</ns2:openApiConnectionResponse>
</soap:Body>
</soap:Envelope>
--uuid:170e63fa-183c-4b18-9364-c62ca545a6e0--
--.
</code></pre>
<p>As you can see, the response soap envelope looks valid (this is a valid response and the call succeeded), but the client seems to have a problem with the content type and generates an exception.</p>
<h2>Error using Service Reference (WCF client)</h2>
<p>When I consume the service as a Service Reference I get a <code>ProtocolException</code> for any call that I make, with the following message:</p>
<pre><code>The content type multipart/related; type="application/xop+xml"; boundary="uuid:af66440a-012e-4444-8814-895c843de5ec"; start="<root.message@cxf.apache.org>"; start-info="text/xml" of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 648 bytes of the response were: '
--uuid:af66440a-012e-4444-8814-895c843de5ec
Content-Type: application/xop+xml; charset=UTF-8; type="text/xml";
Content-Transfer-Encoding: binary
Content-ID: <root.message@cxf.apache.org>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:openApiConnectionResponse xmlns:ns2="http://api.service.apibatchmember.emailvision.com/" xmlns:ns3="http://exceptions.service.apibatchmember.emailvision.com/">
<return>Dqaqb-MJ9V_eplZ8fPh4tdHUbxM-ZtuZsDG6GalAGZSfSzyxgtuuIxZc3aSsnhI4b0SCbJsZmrZ_d3v2-7G8</return>
</ns2:openApiConnectionResponse>
</soap:Body>
</soap:Envelope>
--uuid:af66440a-012e-4444-8814-895c843de5ec--'.
</code></pre>
<p>Just like with the previous example; we've got a valid soap response and the call was successful, but the client seems to have a problem with the content type and has generated an exception.</p>
<p>Are there any options I can set so the client doesn't have a problem with the response type? I've done some Google searches, but nothing that I've found has helped me so far.</p> | 0 | 1,384 |
Caching URL view/state with parameters | <p>I'm making a mobile app using Cordova and AngularJS. Currently I have installed ui-router for routing but I'm open to any other alternative for routing.</p>
<p>My desire: I want to cache certain views bound with parameters. In other words I want to cache paths (or pages).</p>
<p>Example situation: let's say that we see some dashboard page, click on some book cover which redirects to the path <code>book/2</code>. This path is being loaded for the first time into app. Router redirects from <code>HomeController</code> to <code>BooksController</code> (whatever the name). Now the <code>BooksController</code> loads data for given <code>$stateParams</code> (book id = 2) and creates view filled with info about chosen book.</p>
<p>What I want in this situation:</p>
<ol>
<li>I go back to the dashboard page - it is already loaded (cached?)</li>
<li>I choose book #2 again</li>
<li>Controller or router notices that data about this book is already loaded</li>
<li>The view isn't being recreated, instead it's being fetched from cache</li>
</ol>
<p>Actually, it would be best to cache everything what I visit based on path. Preloading would be cool too.</p>
<p>Reason: performance. When I open some list of books then I want it to show fast. When view is being created every time, then animation of page change looks awful (it's not smooth).</p>
<p>Any help would be appreciated.</p>
<h1>EDIT:</h1>
<p>First of all, since I believe it's a common problem for many mobile HTML app programmers, I'd like to precise some information:</p>
<ol>
<li>I'm not looking for hacks but a clear solution <em>if</em> possible.</li>
<li>Data in the views uses AngularJS, so YES, there <em>are</em> things like <code>ng-bind</code>, <code>ng-repeat</code> and so on.</li>
<li><strong>Caching</strong> is needed for <em>both</em> <strong>data</strong> and <strong>DOM elements</strong>. As far as I know, browser's layout operation is not as expensive as recreating whole DOM tree. And repaint is not what we can omit.</li>
<li>Having separate controllers is a natural thing. Since I could leave without it I cannot imagine how it would work anyway.</li>
</ol>
<p>I've got some semi-solutions but I'm gonna be strict about my desire.</p>
<h2>Solution 1.</h2>
<p>Put all views into one file (I may do it using gulp builder) and use <code>ng-show</code>. That's the simplest solution and I don't believe that anyone knowing AngularJS would not think about it.</p>
<p>A <strong>nice trick</strong> (from @DmitriZaitsev) is to create a helper function to show/hide element based on current location path.</p>
<p>Advantages:</p>
<ol>
<li>It's easy.</li>
<li>KIND OF preload feature.</li>
</ol>
<p>Disadvantages:</p>
<ol>
<li>all views have to be in a single file. Don't ask why it's not convenient.</li>
<li>Since it's all about mobile devices, sometimes I'd like to "clear" memory. The only way I can think of is to remove those children from DOM. Dirty but ok.</li>
<li>I cannot easily cache /book/2 and /book/3 at the same time. I would have to dynamically create DOM children on top of some templates for each view bound with parameters.</li>
</ol>
<h2>Solution 2.</h2>
<p>Use Sticky States AND Future States from <a href="http://christopherthielen.github.io/ui-router-extras/">ui-router-extras</a> which is awesome.</p>
<p>Advantages:</p>
<ol>
<li>Separated views.</li>
<li>Very clear usage, very simple since it's just a plugin for <code>ui-router</code>.</li>
<li>Can create dynamic substates. So it would be possible to cache <code>book1</code>, <code>book2</code> but I'm not sure about <code>book/1</code> and <code>book/2</code></li>
</ol>
<p>Disadvantages:</p>
<ol>
<li>Again, I'm not sure but I didn't found an example with caching a <em>pair</em>/tuple <code>(view, parameters)</code>. Other than that it looks cool.</li>
</ol> | 0 | 1,191 |
Making ArrayList of custom objects parcelable | <p>I have two classes which create Objects I need to pass through intents, I am currently attempting to implement Parcelable to do this.</p>
<pre><code>import android.os.Parcel;
import android.os.Parcelable;
public class Item implements Parcelable {
private String name;
private double price;
private int buyerCount = 0;
public Item(String name, double price) {
this.name = name;
this.price = price;
}
private Item(Parcel in) {
name = in.readString();
price = in.readDouble();
}
public static final Parcelable.Creator<Item> CREATOR = new Parcelable.Creator<Item>() {
public Item createFromParcel(Parcel in) {
return new Item(in);
}
public Item[] newArray(int size) {
return new Item[size];
}
};
@Override
public int describeContents() {
return 0;
}
public double getPrice() {
return price;
}
public int getBuyerCount() {
return buyerCount;
}
public void incrementBuyerCount() {
buyerCount += 1;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeDouble(price);
}
}
</code></pre>
<p>From testing so far my Item object seems to transfer information correctly when I bundle it.</p>
<p>However my second class Diner contains an ArrayList of objects Item and I'm unsure how to correctly implement Parcelable in this class, specifically in the parts where I have commented. I see there is a readParsableArray() method but nothing for ArrayLists.</p>
<pre><code>import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
public class Diner implements Parcelable {
private String name;
private ArrayList<Item> itemList = new ArrayList<Item>();
public Diner(String name) {
this.name = name;
}
private Diner(Parcel in) {
name = in.readString();
// How to read in ArrayList itemList of item objects?
itemList = in.readParcelableArray();
}
public static final Parcelable.Creator<Diner> CREATOR = new Parcelable.Creator<Diner>() {
public Diner createFromParcel(Parcel in) {
return new Diner(in);
}
public Diner[] newArray(int size) {
return new Diner[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
// How to write ArrayList itemList of item objects?
dest.writeParcelableArray(itemList);
}
public void addItem(Item foodItem) {
itemList.add(foodItem);
foodItem.incrementBuyerCount();
}
public double getPrice() {
double total = 0;
for(Item item : itemList) {
total += item.getPrice() / item.getBuyerCount();
}
return total;
}
public String toString() {
return name;
}
}
</code></pre> | 0 | 1,228 |
parse xml with jquery ajax request | <p>I have this xml document:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<root>
<chapter>
<lesson>message 1</lesson>
<lesson>message 2</lesson>
<lesson>message 3</lesson>
<lesson>message 4</lesson>
<lesson>message 5</lesson>
<lesson>message 6</lesson>
<lesson>message 7</lesson>
<lesson>message 8</lesson>
<lesson>message 9</lesson>
<lesson>message 10</lesson>
<lesson>message 11</lesson>
</chapter>
</root>
</code></pre>
<p>This is my code:</p>
<pre><code><!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "numbers.xml",
dataType: "xml",
success: parseXml
});
function parseXml(xml) {
$(xml).find("chapter").each(function() {
$(this).find("lesson").each(function() {
$("#dropdownlist").val($(this).text());
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).val().text() + " ";
});
$("#dropdownlist").val(str);
})
.change();
});
});
}
});
</script>
</head>
<body>
<div>
<form id="myform" name="form1" action="" method="get">
<input style="border-style: inset" maxlength="70" size="90" type="text" id="dropdownlist" />
</form>
</div>
<table>
<p style="font-family: 'Monotype Corsiva'" align="right">
chapter
<select style="width: 100px" name="lessons" id="dropdownlist">
<option>lesson_1</option>
<option>lesson_2</option>
<option>lesson_3</option>
<option>lesson_4</option>
<option>lesson_5</option>
<option>lesson_6</option>
<option>lesson_7</option>
<option>lesson_8</option>
<option>lesson_9</option>
<option>lesson_10</option>
<option>lesson_11</option>
</select>
</p>
</table>
</body>
</html>
</code></pre>
<p>My problem is that the code stack and show me only the first result from xml parse. When i choose the first choice from dropdown menu everything it is ok, but when i choose the others options stack and show me the first again. Any suggestions? </p> | 0 | 1,398 |
Argument is of length zero in if statement | <p>I am having a little problem with R and I am not sure why. It is telling me that this line: <code>if(temp > data[[k]][[k2]]) {</code> is of argument length 0. Here is the block which is not that big:</p>
<pre><code>for(k in 1:length(data)) {
temp <- 0
for(k2 in 3:length(data[[k]])) {
print(data[[k]][[k2]])
if(temp > data[[k]][[k2]]) {
temp <- data[[k]][[k2]]
}
fMax[k] <- temp
k2 <- k2 + 1
}
k <- k + 1
}
</code></pre>
<p>example of what is in data[[k]][[k2]]:</p>
<pre><code>[1] "3050"
[1] "3051"
[1] "3054"
[1] "3054"
[1] "3052"
[1] "3053"
[1] "3059"
[1] "3059"
[1] "3057"
[1] "3060"
[1] "3063"
[1] "3060"
[1] "3068"
[1] "3067"
[1] "3079"
[1] "3085"
[1] "3094"
[1] "3107"
[1] "3121"
[1] "3135"
[1] "3147"
[1] "3161"
[1] "3200"
[1] "3237"
[1] "3264"
[1] "3274"
[1] "3284"
[1] "3289"
[1] "3292"
[1] "3300"
[1] "3301"
[1] "3303"
[1] "3306"
[1] "3310"
[1] "3312"
[1] "3313"
[1] "3319"
[1] "3314"
[1] "3318"
[1] "3318"
[1] "3320"
[1] "3322"
[1] "3322"
[1] "3322"
[1] "3328"
[1] "3332"
[1] "3338"
[1] "3350"
[1] "3358"
[1] "3378"
[1] "3395"
[1] "3402"
[1] "3875"
[1] "3950"
[1] "3988"
[1] "4018"
[1] "4039"
[1] "4048"
[1] "4057"
[1] "4062"
[1] "4067"
[1] "4076"
[1] "4082"
[1] "4085"
[1] "4092"
[1] "4098"
[1] "4099"
[1] "4101"
[1] "4107"
[1] "4119"
[1] "4139"
[1] "4164"
[1] "4231"
[1] "4347"
[1] "4559"
</code></pre> | 0 | 1,371 |
Visual Studio 2015 RTM Cordova project won't debug/deploy to Android, Windows, Windows Phone | <p>I've got a feeling I upgraded to Visual Studio 2015 RTM too early. Visual Studio Emulator for Android would no longer launch, claiming that the pre-release version had expired.</p>
<p>I ran the RTM installer, allowing it to replace Release Candidate components as needed. The process ran smoothly, but now after upgrading, Cordova projects will no longer deploy or debug. </p>
<p>With the Release Candidate, the toolbar's green Start button had a dropdown for choice of device. Now with RTM version, this button is just labelled "Start" and its dropdown provides no options for device selection. Instead, the only option in the dropdown is "Start". As I change the selection in the "Solution Platform" dropdown, located left of this Start button, the Start button still provides no choices. See images below.</p>
<p>Solution Platform: Android
<a href="https://i.stack.imgur.com/eC7qo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eC7qo.png" alt="Cordova-Android"></a></p>
<p>Solution Platform: Windows-AnyCPU
<a href="https://i.stack.imgur.com/FKy14.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FKy14.png" alt="Cordova-Windows"></a></p>
<p>Solution Platform: Windows Phone 8
<a href="https://i.stack.imgur.com/7Qzmd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Qzmd.png" alt="Cordova-WP"></a></p>
<p>The Debug menu's "Start Debugging" item is disabled. If I click the Start toolbar button, I get this message: "The debugger cannot continue running the process. Unable to start debugging." </p>
<p>I've confirmed that Visual Studio Emulator for Android is functional. I've got the profile '5" Lollipop (5.0) XXHDPI Phone' working.</p>
<p>For a comparison, I've also added a new Windows Phone 8.1 project to my solution and confirmed that project allows selecting a Debug Target. In the toolbar, the word Start is replaced with "Emulator 8.1 WVGA 4 inch 512MB". With this project as the Startup Project, the Debug menu now has "Start Debugging" enabled. This project starts as expected.</p>
<p><a href="https://i.stack.imgur.com/FvcFO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FvcFO.png" alt="C#-WP81"></a></p>
<p>Since the Visual Studio Emulator for Android is functional, and Visual Studio successfully targets the Windows Phone emulator, it seems there's a misconfiguration related to Visual Studio's Cordova project type. The linkage between a VS2015 Cordova project and its "device" targets is missing.</p>
<p>Any ideas?</p>
<p><strong>UPDATE:</strong> See also: <a href="https://stackoverflow.com/questions/31530014/unable-to-start-debugging-in-visual-studio-rtm-for-cordova-app">Unable to start debugging in Visual Studio RTM for cordova app</a></p>
<p><strong>UPDATE 2:</strong> I've made several adjustments:</p>
<ol>
<li><p>Tools for Apache Cordova's Dependency checker found missing Android SDK components. I've added these, satisfying Dependency Checker. </p></li>
<li><p>Tools for Apache Cordova's Environment Variable Overrides showed no path to ADT_HOME. I've set it to "C:\Program Files (x86)\Android\android-sdk".</p></li>
<li><p>My build output showed "[taskdef] could not load definitions from resource emma_ant.properties. it could not be found." I added a system environment variable ANT_HOME pointing to "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Apps\apache-ant-1.9.3", and added ";%ANT_HOME%\bin" to the PATH. Still "emma_ant.properties" message remains, but it is not up to the level of a warning or error.</p></li>
</ol>
<p>With Solution Platform set to Android, my current build output is:</p>
<pre><code>1>------ Rebuild All started: Project: BlankCordovaApp2, Configuration: Debug Android ------
1> Buildfile: C:\Users\billvo\Documents\Visual Studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\build.xml
1> [taskdef] Could not load definitions from resource emma_ant.properties. It could not be found.
1>
1> -check-env:
1> [checkenv] Android SDK Tools Revision 23.0.0
1> [checkenv] Installed at C:\Program Files (x86)\Android\android-sdk
1>
1> -setup:
1> [echo] Project Name: MainActivity
1> [gettype] Project Type: Application
1>
1> -pre-clean:
1>
1> clean:
1> [getlibpath] Library dependencies:
1> [getlibpath]
1> [getlibpath] ------------------
1> [getlibpath] Ordered libraries:
1> [taskdef] Could not load definitions from resource emma_ant.properties. It could not be found.
1>
1> nodeps:
1>
1> -check-env:
1> [checkenv] Android SDK Tools Revision 23.0.0
1> [checkenv] Installed at C:\Program Files (x86)\Android\android-sdk
1>
1> -setup:
1> [echo] Project Name: MainActivity
1> [gettype] Project Type: Android Library
1>
1> -pre-clean:
1>
1> clean:
1>
1> BUILD SUCCESSFUL
1> Total time: 0 seconds
1> Your environment has been set up for using Node.js 0.12.2 (ia32) and npm.
1> ------ Ensuring correct global installation of package from source package directory: C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\ApacheCordovaTools\packages\vs-tac
1> ------ Name from source package.json: vs-tac
1> ------ Version from source package.json: 1.0.0
1> ------ Package not currently installed globally.
1> ------ Installing globally from source package. This could take a few minutes...
1> > edge@0.10.1 install C:\Users\billvo\AppData\Roaming\npm\node_modules\vs-tac\node_modules\edge
1> > node tools/install.js
1> Success: platform check for edge.js: node.js ia32 v0.12.2
1> npm WARN engine npm@1.3.4: wanted: {"node":">=0.6","npm":"1"} (current: {"node":"0.12.2","npm":"2.7.4"})
1> npm WARN engine cordova-js@3.6.2: wanted: {"node":"~0.10.x"} (current: {"node":"0.12.2","npm":"2.7.4"})
1> npm WARN installMany normalize-package-data was bundled with npm@1.3.4, but bundled package wasn't found in unpacked tree
1> C:\Users\billvo\AppData\Roaming\npm\vs-tac-cli -> C:\Users\billvo\AppData\Roaming\npm\node_modules\vs-tac\vs-tac-cli.cmd
1> vs-tac@1.0.0 C:\Users\billvo\AppData\Roaming\npm\node_modules\vs-tac
1> ├── rimraf@2.2.6
1> ├── ncp@0.5.1
1> ├── mkdirp@0.3.5
1> ├── q@1.0.1
1> ├── semver@2.3.1
1> ├── adm-zip@0.4.4
1> ├── fstream@0.1.28 (inherits@2.0.1, graceful-fs@3.0.8)
1> ├── optimist@0.6.1 (wordwrap@0.0.3, minimist@0.0.10)
1> ├── tar@0.1.20 (inherits@2.0.1, block-stream@0.0.8)
1> ├── elementtree@0.1.6 (sax@0.3.5)
1> ├── request@2.36.0 (forever-agent@0.5.2, aws-sign2@0.5.0, qs@0.6.6, oauth-sign@0.3.0, tunnel-agent@0.4.1, json-stringify-safe@5.0.1, mime@1.2.11, node-uuid@1.4.3, tough-cookie@2.0.0, http-signature@0.10.1, hawk@1.0.0, form-data@0.1.4)
1> ├── ripple-emulator@0.9.30 (connect-xcors@0.5.2, colors@0.6.0-1, open@0.0.3, accounting@0.4.1, request@2.12.0, moment@1.7.2, express@3.1.0)
1> ├── edge@0.10.1 (edge-cs@0.2.7, nan@1.8.4)
1> └── plugman@0.22.4 (q@0.9.7, underscore@1.4.4, nopt@1.0.10, rc@0.3.0, cordova-lib@0.21.6, npm@1.3.4)
1> ------ npm install of vs-tac@1.0.0 from C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\ApacheCordovaTools\packages\vs-tac completed.
1> ------ Installing Cordova tools cordova@4.3.1 for project from npm. This could take a few minutes...
1> npm WARN engine npm@1.3.4: wanted: {"node":">=0.6","npm":"1"} (current: {"node":"0.12.2","npm":"2.7.4"})
1> npm WARN engine cordova-js@3.8.0: wanted: {"node":"~0.10.x"} (current: {"node":"0.12.2","npm":"2.7.4"})
1> npm WARN engine xmlbuilder@2.2.1: wanted: {"node":"0.8.x || 0.10.x"} (current: {"node":"0.12.2","npm":"2.7.4"})
1> npm WARN installMany normalize-package-data was bundled with npm@1.3.4, but bundled package wasn't found in unpacked tree
1> cordova@4.3.1 node_modules\cordova
1> ├── underscore@1.7.0
1> ├── q@1.0.1
1> ├── nopt@3.0.1 (abbrev@1.0.7)
1> └── cordova-lib@4.3.1 (valid-identifier@0.0.1, osenv@0.1.0, properties-parser@0.2.3, bplist-parser@0.0.6, mime@1.2.11, unorm@1.3.3, semver@2.0.11, dep-graph@1.1.0, shelljs@0.3.0, rc@0.5.2, through2@0.6.3, npmconf@0.1.16, xcode@0.6.7, elementtree@0.1.5, d8@0.4.4, request@2.47.0, glob@4.0.6, tar@1.0.2, init-package-json@1.7.1, plist@1.1.0, cordova-js@3.8.0, npm@1.3.4)
1> ------ npm install of cordova@4.3.1 from npm completed.
1> ------ Build Settings:
1> ------ Build Settings:
1> ------ platformConfigurationBldDir: C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\bld\Android\Debug
1> ------ platformConfigurationBinDir: C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\bin\Android\Debug
1> ------ buildCommand: prepare
1> ------ platform: Android
1> ------ cordovaPlatform: android
1> ------ configuration: Debug
1> ------ cordovaConfiguration: Debug
1> ------ projectName: BlankCordovaApp2
1> ------ projectSourceDir: C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2
1> ------ npmInstallDir: C:\Users\billvo\AppData\Roaming\npm
1> ------ language: en-US
1> ------ Platform android already exists
1> ------ Updating plugins
1> ------ Currently installed plugins:
1> ------ Currently installed dependent plugins:
1> ------ Currently configured plugins:
1> ------ Preparing platform: android
1> Generating config.xml from defaults for platform "android"
1> Calling plugman.prepare for platform "android"
1> Preparing android project
1> Processing configuration changes for plugins.
1> Iterating over installed plugins: []
1> Writing out cordova_plugins.js...
1> Wrote out Android application name to "BlankCordovaApp2"
1> deleted: C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-land-hdpi\screen.png
1> deleted: C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-land-ldpi\screen.png
1> deleted: C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-land-mdpi\screen.png
1> deleted: C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-land-xhdpi\screen.png
1> deleted: C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-port-hdpi\screen.png
1> deleted: C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-port-ldpi\screen.png
1> deleted: C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-port-mdpi\screen.png
1> deleted: C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-port-xhdpi\screen.png
1> splash screens: [{"src":"res/screens/android/screen-hdpi-landscape.png","density":"land-hdpi","platform":"android"},{"src":"res/screens/android/screen-ldpi-landscape.png","density":"land-ldpi","platform":"android"},{"src":"res/screens/android/screen-mdpi-landscape.png","density":"land-mdpi","platform":"android"},{"src":"res/screens/android/screen-xhdpi-landscape.png","density":"land-xhdpi","platform":"android"},{"src":"res/screens/android/screen-hdpi-portrait.png","density":"port-hdpi","platform":"android"},{"src":"res/screens/android/screen-ldpi-portrait.png","density":"port-ldpi","platform":"android"},{"src":"res/screens/android/screen-mdpi-portrait.png","density":"port-mdpi","platform":"android"},{"src":"res/screens/android/screen-xhdpi-portrait.png","density":"port-xhdpi","platform":"android"}]
1> copying image from C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\res\screens\android\screen-hdpi-landscape.png to C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-land-hdpi\screen.png
1> copying image from C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\res\screens\android\screen-ldpi-landscape.png to C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-land-ldpi\screen.png
1> copying image from C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\res\screens\android\screen-mdpi-landscape.png to C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-land-mdpi\screen.png
1> copying image from C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\res\screens\android\screen-xhdpi-landscape.png to C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-land-xhdpi\screen.png
1> copying image from C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\res\screens\android\screen-hdpi-portrait.png to C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-port-hdpi\screen.png
1> copying image from C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\res\screens\android\screen-ldpi-portrait.png to C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-port-ldpi\screen.png
1> copying image from C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\res\screens\android\screen-mdpi-portrait.png to C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-port-mdpi\screen.png
1> copying image from C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\res\screens\android\screen-xhdpi-portrait.png to C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-port-xhdpi\screen.png
1> deleted: C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-hdpi\icon.png
1> deleted: C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-ldpi\icon.png
1> deleted: C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-mdpi\icon.png
1> deleted: C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-xhdpi\icon.png
1> copying image from C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\res\icons\android\icon-36-ldpi.png to C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-ldpi\icon.png
1> copying image from C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\res\icons\android\icon-48-mdpi.png to C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-mdpi\icon.png
1> copying image from C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\res\icons\android\icon-72-hdpi.png to C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-hdpi\icon.png
1> copying image from C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\res\icons\android\icon-96-xhdpi.png to C:\Users\billvo\documents\visual studio 2015\Projects\BlankCordovaApp2\BlankCordovaApp2\platforms\android\res\drawable-xhdpi\icon.png
1> Wrote out Android package name to "io.cordova.myapp2a20d4"
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========
</code></pre>
<p>I'm still not able to select the target device for debugging, regardless of whether I build for Android, Windows-AnyCPU, or Windows Phone 8.</p>
<p><strong>UPDATE 3:</strong> The images below show the Visual Studio 2015 components installed. I tried adding Visual C++ Mobile Development, but saw no change in Cordova, so I removed it.</p>
<p><a href="https://i.stack.imgur.com/UwGrF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UwGrF.png" alt="Add/Remove 1"></a></p>
<p><a href="https://i.stack.imgur.com/R47yl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R47yl.png" alt="Add/Remove 2"></a></p>
<p><a href="https://i.stack.imgur.com/LBgLg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LBgLg.png" alt="Add/Remove 3"></a></p>
<p><a href="https://i.stack.imgur.com/0vJSI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0vJSI.png" alt="Add/Remove 4"></a></p>
<p><strong>UPDATE 4:</strong> When I logged into a new local user account, I'm able to debug against the Visual Studio Emulator for Android. This tells me that the problem is likely specific to my primary Windows account's profile. I could probably fix this by deleting my profile and starting fresh. </p> | 0 | 6,511 |
Using Java to extract data from google Weather API | <p>Edit: 2020 update -- Please disregard the question below as Google's weather API is no longer able to be used. If you are interested in using a weather API, Darksky is the defacto that most people use: <a href="https://darksky.net/dev" rel="nofollow noreferrer">https://darksky.net/dev</a></p>
<p>If you use Java, the normal way to parse the JSON is using org.json: <a href="https://devqa.io/java/how-to-parse-json-in-java" rel="nofollow noreferrer">https://devqa.io/java/how-to-parse-json-in-java</a></p>
<p>--</p>
<p>Original question below.</p>
<hr>
<p>I've been playing around with xml documents and java a bit recently, but I've had absolutely no luck using the google weather API.</p>
<p>Let's assume that I'm trying to do a simple object to store current temp, and forecast temp for just tomorrow, how would I do this?</p>
<p><a href="http://www.google.com/ig/api?weather=02110" rel="nofollow noreferrer">http://www.google.com/ig/api?weather=02110</a> Is the working example for my home city.</p>
<p>Thanks</p>
<p>Using this code:</p>
<pre><code>public static final String[] xmlLoader(){
String xmlData[] = new String[2];
try {
URL googleWeatherXml = new URL("http://www.google.com/ig/api?weather=02110");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(googleWeatherXml.openStream());
// normalize text representation
doc.getDocumentElement ().normalize ();
NodeList listOfWeek = doc.getElementsByTagName("");
Node firstWeekNode = listOfWeek.item(dateCounter-1);
int totalWeeks = listOfWeek.getLength();
//Break xml file into parts, then break those parts down int an array by passing individual elements to srtings
if(firstWeekNode.getNodeType() == Node.ELEMENT_NODE){
Element firstWeekElement = (Element)firstWeekNode;
//-------
NodeList dateList = firstWeekElement.getElementsByTagName("date");
Element dateElement = (Element)dateList.item(0);
NodeList textDateList = dateElement.getChildNodes();
xmlData[0]= (((Node)textDateList.item(0)).getNodeValue().trim()).toString();
//-------
NodeList riddleList = firstWeekElement.getElementsByTagName("riddle");
Element riddleElement = (Element)riddleList.item(0);
NodeList textRiddleList = riddleElement.getChildNodes();
xmlData[1]= (((Node)textRiddleList.item(0)).getNodeValue().trim()).toString();
//----
NodeList lWSList = firstWeekElement.getElementsByTagName("lastWeekSolution");
Element ageElement = (Element)lWSList.item(0);
NodeList textLWSList = ageElement.getChildNodes();
xmlData[2]= (((Node)textLWSList.item(0)).getNodeValue().trim()).toString();
//------
}//end of if clause
}
catch(MalformedURLException f){System.err.println(f.getMessage()); }
catch(NullPointerException npe){
System.out.println("The Weather Data you searched for is incorrect or does not yet exist, try again. ");
String s[] = {" ", " "};
main(s);
}
catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line "
+ err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());
}
catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();
}catch (Throwable t) {
t.printStackTrace ();
}
return xmlData;
}
</code></pre>
<p>Getting tons of null pointers, no matter what I do.</p> | 0 | 1,519 |
Send data from TableView to DetailView Swift | <p>I'm trying to do maybe one of the simplest and more confusing things for me until now
I wanna develop my own App , and in order to do it I need to be able to passing some information depending of which row user click (it's Swift lenguage)</p>
<p>We have a RootViewController(table view) and a DetailViewController (with 1 label and 1 image)
<img src="https://i.stack.imgur.com/BcQpW.jpg" alt="enter image description here"></p>
<p>(our view)</p>
<p>Here is the code: </p>
<pre><code>@IBOutlet weak var tableView: UITableView!
var vehicleData : [String] = ["Ferrari 458" , "Lamborghini Murcielago" , "Bugatti Veyron", "Mercedes Benz Biome"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var nib = UINib(nibName: "TableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return vehicleData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:TableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as TableViewCell
cell.lblCarName.text = vehicleData[indexPath.row]
cell.imgCar.image = UIImage(named: vehicleData[indexPath.row])
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("DetailView", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "DetailView") {
var vc = segue.destinationViewController as DetailViewController
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
</code></pre>
<p>Custom TableViewCell class (has a xib File with cell)</p>
<pre><code>class TableViewCell: UITableViewCell {
@IBOutlet weak var lblCarName: UILabel!
@IBOutlet weak var imgCar: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
class DetailViewController: UIViewController {
@IBOutlet weak var lblDetail: UILabel!
@IBOutlet weak var imgDetail: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
</code></pre>
<p>The question is: </p>
<p>if user click Ferrari 458 , the lblDetail in DetailViewController would show: Ferrari 458 is a super car which is able to reach 325 km/ h ...... (whatever we want)
and imgDetail would be able to show an image (whatever we want) of the car</p>
<p>If user click Bugatti Veyron now the lblDetail show us: Bugatti Veyron is a perfect and super sport machine. It's one of the fastest car in the world....</p>
<p>imgDetail show us an image of this car</p>
<p>Same thing with all cars depending which row we have clicked</p>
<p>I know the work is around prepareForSegue func in first View Controller but i was trying a lot of different ways to make it possible and anything runs ok</p>
<p>How we can do this???</p> | 0 | 1,104 |
Is the max value of size_t (SIZE_MAX) defined relative to the other integer types? | <p>I'm writing a library of functions that will safely convert between various numeric types or die trying.
My intent is roughly equal parts create-useful-library and learn-C-edge-cases.</p>
<p>My <code>int</code>-to-<code>size_t</code> function is triggering a GCC <code>-Wtype-limits</code> warning that claims I shouldn't test if an <code>int</code> is greater than <code>SIZE_MAX</code>, because it will never be true.
(Another function that converts <code>int</code> to <code>ssize_t</code> produces an identical warning about <code>SSIZE_MAX</code>.)</p>
<p>My MCVE, with extra comments and baby steps, is:</p>
<pre><code>#include <stdint.h> /* SIZE_MAX */
#include <stdlib.h> /* exit EXIT_FAILURE size_t */
extern size_t i2st(int value) {
if (value < 0) {
exit(EXIT_FAILURE);
}
// Safe to cast --- not too small.
unsigned int const u_value = (unsigned int) value;
if (u_value > SIZE_MAX) { /* Line 10 */
exit(EXIT_FAILURE);
}
// Safe to cast --- not too big.
return (size_t) u_value;
}
</code></pre>
<h2>The Compiler Warnings</h2>
<p>I'm getting similar warnings from GCC 4.4.5 on Linux 2.6.34:</p>
<pre class="lang-none prettyprint-override"><code>$ gcc -std=c99 -pedantic -Wall -Wextra -c -o math_utils.o math_utils.c
math_utils.c: In function ‘i2st’:
math_utils.c:10: warning: comparison is always false due to limited range of data type
</code></pre>
<p>...and also from GCC 4.8.5 on Linux 3.10.0:</p>
<pre class="lang-none prettyprint-override"><code>math_utils.c: In function ‘i2st’:
math_utils.c:10:5: warning: comparison is always false due to limited range of data type [-Wtype-limits]
if (u_value > SIZE_MAX) { /* Line 10 */
^
</code></pre>
<p>These warnings don't appear justified to me, at least not in the general case.
(I don't deny that the comparison might be
"always false"
on some particular combination of hardware and compiler.)</p>
<h2>The C Standard</h2>
<p>The C 1999 standard does not appear to rule out an <code>int</code> being greater than <code>SIZE_MAX</code>.</p>
<p>Section
"6.5.3.4 The <code>sizeof</code> operator"
doesn't address <code>size_t</code> at all, except to describe it as
"defined in <code><stddef.h></code> (and other headers)".</p>
<p>Section
"7.17 Common definitions <code><stddef.h></code>"
defines <code>size_t</code> as
"the unsigned integer type of the result of the <code>sizeof</code> operator".
(Thanks, guys!)</p>
<p>Section
"7.18.3 Limits of other integer types"
is more helpful ---
it defines
"limit of <code>size_t</code>" as:</p>
<blockquote>
<p><code>SIZE_MAX</code> <code>65535</code></p>
</blockquote>
<p>...meaning <code>SIZE_MAX</code> could be as <em>small</em> as 65535.
An <code>int</code>
(signed or unsigned)
could be much greater than that, depending on the hardware and compiler.</p>
<h2>Stack Overflow</h2>
<p>The accepted answer to
"<a href="https://stackoverflow.com/questions/131803"><code>unsigned int</code> vs. <code>size_t</code></a>"
seems to support my interpretation
(emphasis added):</p>
<blockquote>
<p>The <code>size_t</code> type may be bigger than, equal to, <strong>or smaller than</strong> an <code>unsigned int</code>, and your compiler might make assumptions about it for optimization.</p>
</blockquote>
<p>This answer cites the same
"Section 7.17"
of the C standard that I've already quoted.</p>
<h2>Other Documents</h2>
<p>My searches turned up the Open Group's paper
"<a href="http://www.unix.org/whitepapers/64bit.html" rel="noreferrer">Data Size Neutrality and 64-bit Support</a>",
which claims under
"64-bit Data Models"
(emphasis added):</p>
<blockquote>
<p>ISO/IEC 9899:1990, Programming Languages - C (ISO C)
left the definition of the <code>short int</code>, the <code>int</code>, the <code>long int</code>, and the <code>pointer</code> deliberately vague
[...]
The only constraints were that <code>int</code>s must be no smaller than <code>short</code>s, and <code>long</code>s must be no smaller than <code>int</code>s, and <strong><code>size_t</code> must represent the largest unsigned type supported by an implementation</strong>.
[...]
The relationship between the fundamental data types can be expressed as:</p>
<blockquote>
<p><code>sizeof(char)</code> <= <code>sizeof(short)</code> <= <code>sizeof(int)</code> <= <strong><code>sizeof(long)</code> = <code>sizeof(size_t)</code></strong></p>
</blockquote>
</blockquote>
<p>If this is true, then testing an <code>int</code> against <code>SIZE_MAX</code> is indeed futile...
but this paper doesn't cite chapter-and-verse, so I can't tell how its authors reached their conclusion.
Their own
"Base Specification Version 7"
<a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_types.h.html" rel="noreferrer"><code>sys/types.h</code> docs</a>
don't address this either way.</p>
<h2>My Question</h2>
<p>I understand that <code>size_t</code> is unlikely to be narrower than an <code>int</code>, but <strong>does the C standard guarantee</strong> that comparing <code>some_unsigned_int > SIZE_MAX</code> will <em>always</em> be false?
If so, where?</p>
<h2>Not-Duplicates</h2>
<p>There are two semi-duplicates of this question, but they are both asking more general questions about what <code>size_t</code> is supposed to represent and when it should / should-not be used.</p>
<ul>
<li><p>"<a href="https://stackoverflow.com/questions/2550774">What is <code>size_t</code> in C?</a>"
does not address the relationship between <code>size_t</code> and the other integer types.
Its accepted answer is just a quote from Wikipedia, which doesn't provide any information beyond what I've already found.</p></li>
<li><p>"<a href="https://stackoverflow.com/questions/32286535">What is the correct definition of <code>size_t</code>?</a>"
starts off nearly a duplicate of my question, but then veers off course, asking
when <code>size_t</code> should be used and why it was introduced.
It was closed as a duplicate of the previous question.</p></li>
</ul> | 0 | 2,115 |
Write records into text file from database using java | <p>I want to store database records to text file. for that I used the ResultSet, I have selected the whole table using sql select query and store the data in the ArrayList. But this code doesn't work properly. my database name is test and table is employee. what should I do? this is what I have tried.</p>
<pre><code>import java.io.*;
import java.sql.*;
import java.util.*;
public class ResultSetWriteInToTextFile {
public static void main(String[] args) {
List data = new ArrayList();
try {
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("Select * from employee");
while (rs.next()) {
String id = rs.getString("emp_id");
String name = rs.getString("emp_name");
String address = rs.getString("emp_address");
String contactNo = rs.getString("contactNo");
data.add(id + " " + name + " " + address + " " + contactNo);
}
writeToFile(data, "Employee.txt");
rs.close();
st.close();
} catch (Exception e) {
System.out.println(e);
}
}
private static void writeToFile(java.util.List list, String path) {
BufferedWriter out = null;
try {
File file = new File(path);
out = new BufferedWriter(new FileWriter(file, true));
for (String s : list) {
out.write(s);
out.newLine();
}
out.close();
} catch (IOException e) {
}
}
</code></pre>
<p>}</p> | 0 | 1,051 |
m2eclipse will not download any dependencies | <p>I was hoping someone might be able to help. </p>
<p>On a brand new windows machine. I've downloaded and installed java jdk before downloading and running the latest version of eclipse (indigo). </p>
<p>From there I have installed the maven integration plugin from the marketplace and created a new maven projected. </p>
<p>The project has a ton of errors mainly to do with missing dependencies or life cycle management. </p>
<p>When I do maven-clean I get the following error message:</p>
<pre><code>[ERROR] Plugin org.apache.maven.plugins:maven-clean-plugin:2.4.1 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-clean-plugin:jar:2.4.1: Could not transfer artifact org.apache.maven.plugins:maven-clean-plugin:pom:2.4.1 from/to central (http://repo1.maven.org/maven2): Invalid argument: getsockname to http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-clean-plugin/2.4.1/maven-clean-plugin-2.4.1.pom -> [Help 1]
</code></pre>
<p>I am not behind a firewall and I do not use a proxy. My maven settings.xml is completely default as is my maven project. No classes added, nothing added to the pom.</p>
<p>Can anyone help?</p>
<p>All the best.</p>
<p>p.s here are the errors shown in the pom:</p>
<p>1:</p>
<pre><code>CoreException: Could not calculate build plan: Plugin org.apache.maven.plugins:maven-compiler-plugin:2.3.2 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-compiler-plugin:jar:2.3.2: ArtifactResolutionException: Failure to transfer org.apache.maven.plugins:maven-compiler-plugin:pom:2.3.2 from http://repo1.maven.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.apache.maven.plugins:maven-compiler-plugin:pom:2.3.2 from/to central (http://repo1.maven.org/maven2): Invalid argument: getsockname to http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-compiler-plugin/2.3.2/maven-compiler-plugin-2.3.2.pom
</code></pre>
<p>2:</p>
<pre><code>Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-compiler-plugin:2.3.2:testCompile (execution: default-testCompile, phase: test-compile)
</code></pre>
<p>3:</p>
<pre><code>Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (execution: default-compile, phase: compile)
</code></pre>
<p>4:</p>
<pre><code>Failure to transfer org.apache.maven.plugins:maven-resources-plugin:pom:2.4.3 from http://repo1.maven.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.apache.maven.plugins:maven-resources-plugin:pom:2.4.3 from/to central (http://repo1.maven.org/maven2): Invalid argument: getsockname to http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-resources-plugin/2.4.3/maven-resources-plugin-2.4.3.pom
</code></pre> | 0 | 1,055 |
Android ImageAdapter with Gridview in Fragment | <p>I have an adapter with gridview that works as an Activity. I am trying to place it in a Fragment now and converted things but it does not work. When I include the IconFragmentSystem in my Activity I get a force close when I try to open the Activity. </p>
<p>I know the Activity works because I can use other Fragments and everything is okay so I know my issue lies within this file.</p>
<pre><code>package com.designrifts.ultimatethemeui;
import com.designrifts.ultimatethemeui.R;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import java.util.ArrayList;
public class IconFragmentSystem extends Fragment implements AdapterView.OnItemClickListener{
private static final String RESULT_OK = null;
public Uri CONTENT_URI;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, container, false);
super.onCreate(savedInstanceState);
int iconSize=getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);
GridView gridview = (GridView) getActivity().findViewById(R.id.icon_grid);
gridview.setAdapter(new IconAdapter(this, iconSize));
gridview.setOnItemClickListener(this);
CONTENT_URI=Uri.parse("content://"+iconsProvider.class.getCanonicalName());
return view;
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String icon=adapterView.getItemAtPosition(i).toString();
Intent result = new Intent(null, Uri.withAppendedPath(CONTENT_URI,icon));
setResult(RESULT_OK, result);
finish();
}
private void setResult(String resultOk, Intent result) {
// TODO Auto-generated method stub
}
private void finish() {
// TODO Auto-generated method stub
}
private class IconAdapter extends BaseAdapter{
private Context mContext;
private int mIconSize;
public IconAdapter(Context mContext, int iconsize) {
super();
this.mContext = mContext;
this.mIconSize = iconsize;
loadIcon();
}
public IconAdapter(IconFragmentSystem iconssystem, int iconSize) {
// TODO Auto-generated constructor stub
}
@Override
public int getCount() {
return mThumbs.size();
}
@Override
public Object getItem(int position) {
return mThumbs.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(mIconSize, mIconSize));
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbs.get(position));
return imageView;
}
private ArrayList<Integer> mThumbs;
////////////////////////////////////////////////
private void loadIcon() {
mThumbs = new ArrayList<Integer>();
final Resources resources = getResources();
final String packageName = getActivity().getApplication().getPackageName();
addIcon(resources, packageName, R.array.systemicons);
}
private void addIcon(Resources resources, String packageName, int list) {
final String[] extras = resources.getStringArray(list);
for (String extra : extras) {
int res = resources.getIdentifier(extra, "drawable", packageName);
if (res != 0) {
final int thumbRes = resources.getIdentifier(extra,"drawable", packageName);
if (thumbRes != 0) {
mThumbs.add(thumbRes);
}
}
}
}
}
}
</code></pre>
<p>I have tried different ways to implement this but all have failed and I could really use help pointing me in the right direction.</p>
<p>This is my xml in layout</p>
<pre><code> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<GridView
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</RelativeLayout>
</code></pre> | 0 | 1,835 |
getHeight returns 0 for all Android UI objects | <p>I'm building a UI, and it's all static defined in the XML. All of it has weights all over the place, and while it looks right, I wanted to see that things actually have the right height and all. The problem is that no matter where I call .getHeight() for my format layout I got 0. I tried in both onCreate() and onStart(). Same thing. Happens for all UI objects too. Any idea?</p>
<pre><code>package com.app.conekta;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;
public class Conekta extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onResume() {
super.onResume();
FrameLayout fl1 = (FrameLayout) findViewById(R.id.headerFrameLayout);
FrameLayout fl2 = (FrameLayout) findViewById(R.id.footerFrameLayout);
Button b=(Button) findViewById(R.id.searchButton);
Log.d("CONEKTA", String.valueOf(b.getHeight()));
}
}
</code></pre>
<p>XML:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/headerFrameLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.05"
android:background="#597eAA" >
<ImageView
android:id="@+id/logoImage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#7ba1d1"
android:src="@drawable/logo_conekta" />
</FrameLayout>
<LinearLayout
android:id="@+id/bodyLinearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.7"
android:background="#f3f3f3"
android:orientation="horizontal" >
<FrameLayout
android:id="@+id/leftBlankFrameLayout"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.15"
android:background="#f3f3f3" >
</FrameLayout>
<LinearLayout
android:id="@+id/centerVerticalLayout"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.7"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/topCenterFrameLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.35" >
</FrameLayout>
<TextView
android:id="@+id/venueLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.025"
android:text="What are you looking for?"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000" />
<EditText
android:id="@+id/venueTextField"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.025" >
<requestFocus />
</EditText>
<FrameLayout
android:id="@+id/middleCenterFrameLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.05" >
</FrameLayout>
<TextView
android:id="@+id/locationLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.025"
android:text="Where?"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000" />
<AutoCompleteTextView
android:id="@+id/locationTextField"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.025"
android:text="" />
<LinearLayout
android:id="@+id/buttonLinearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.05"
android:background="#f3f3f3"
android:orientation="horizontal" >
<FrameLayout
android:id="@+id/leftButtonLinearLayout"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.1" >
</FrameLayout>
<Button
android:id="@+id/searchButton"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.8"
android:background="#6fa8dc"
android:text="Search" />
<FrameLayout
android:id="@+id/rightButtonLinearLayout"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.1" >
</FrameLayout>
</LinearLayout>
<FrameLayout
android:id="@+id/bottomCenterFrameLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.35" >
</FrameLayout>
</LinearLayout>
<FrameLayout
android:id="@+id/rightBlankFrameLayout"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.15"
android:background="#f3f3f3" >
</FrameLayout>
</LinearLayout>
<FrameLayout
android:id="@+id/footerFrameLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.15"
android:background="#7ba1d1" >
</FrameLayout>
</LinearLayout>
</code></pre> | 0 | 3,476 |
using tor as a SOCKS5 proxy with python urllib2 or mechanize | <p>My goal is to use python's mechanize with a tor SOCKS proxy.</p>
<p>I am not using a GUI with the following Ubuntu version:
Description: Ubuntu 12.04.1 LTS
Release: 12.04
Codename: precise</p>
<p>Tor is installed and is listening on port 9050 according to the nmap scan:</p>
<pre><code> Starting Nmap 5.21 ( http://nmap.org ) at 2013-01-22 00:50 UTC
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000011s latency).
Not shown: 996 closed ports
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
3306/tcp open mysql
9050/tcp open tor-socks
</code></pre>
<p>I also thought it reasonable to see if I could telnet to port 9050, which I can:</p>
<pre><code> telnet 127.0.0.1 9050
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
quit
Connection closed by foreign host.
</code></pre>
<p>I had high hopes for the suggestion in this post to get tor working with urllib2:
<a href="https://stackoverflow.com/questions/2317849/how-can-i-use-a-socks-4-5-proxy-with-urllib2">How can I use a SOCKS 4/5 proxy with urllib2?</a></p>
<p>So I tried the following script in python:</p>
<pre><code> import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
import urllib2
print urllib2.urlopen('http://icanhazip.com').read()
</code></pre>
<p>The script just hangs with no response.</p>
<p>I thought that since mechanize seems to be related to urllib2 that the following script might work:</p>
<pre><code> import socks
import socket
import mechanize
from mechanize import Browser
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
br = Browser()
print br.open('http://icanhazip.com').read()
</code></pre>
<p>I get the same result as above with the urllib2 script.</p>
<p>I am very new to python and networking, so I need a second opinion on how to make the python urllib2 use tor as a SOCKS on a non-GUI Ubuntu server.</p>
<p>I ran this script and received an expected response. I did not use the tor proxy:</p>
<pre><code> In [1]: import urllib2
In [2]: print urllib2.urlopen('http://icanhazip.com').read()
xxxx:xxxx:xxxx:512:13b2:ccd5:ff04:c5f4
</code></pre>
<p>Thanks.</p>
<p>I found something that works! I have no idea why it works, but it does. I found it here:
<a href="https://stackoverflow.com/questions/5148589/python-urllib-over-tor?rq=1">Python urllib over TOR?</a></p>
<pre><code> import socks
import socket
def create_connection(address, timeout=None, source_address=None):
sock = socks.socksocket()
sock.connect(address)
return sock
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
# patch the socket module
socket.socket = socks.socksocket
socket.create_connection = create_connection
import urllib2
print urllib2.urlopen('http://icanhazip.com').read()
import mechanize
from mechanize import Browser
br = Browser()
print br.open('http://icanhazip.com').read()
</code></pre> | 0 | 1,267 |
Loading Youtube video through iframe in Android webview | <p>I want to load youtube video to Android webview using iframe</p>
<p>here is my layout Xml</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white"
android:id="@+id/mainLayout">
<WebView
android:background="@android:color/white"
android:id="@+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
</code></pre>
<p>My code is:</p>
<pre><code>public class WebTube extends Activity {
private WebView wv;
String html = "<iframe class=\"youtube-player\" style=\"border: 0; width: 100%; height: 95%; padding:0px; margin:0px\" id=\"ytplayer\" type=\"text/html\" src=\"http://www.youtube.com/embed/WBYnk3zR0os"
+ "?fs=0\" frameborder=\"0\">\n"
+ "</iframe>";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView)findViewById(R.id.webView);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadDataWithBaseURL("", html , "text/html", "UTF-8", "");
}
}
</code></pre>
<p>Also I provide <code><uses-permission android:name="android.permission.INTERNET"/></code></p>
<p>& <code>android:hardwareAccelerated="true"</code></p>
<p>when I run this I didn't get any result its just showing a black screen </p>
<p>I tried <a href="https://stackoverflow.com/questions/11117720/play-video-file-from-youtube-in-android?answertab=active#tab-top">this</a> .but this provide me video on <code>.3gp Quality</code> . but I need the videos from youtube on original quality. That's why I am using <code>iframe</code>.</p>
<p>I try code using <code><object></object></code> and <code><video></video></code> instead of <code>iframe</code>. but it didn't solve my issue.</p>
<p>when I run this code on emulator it shows</p>
<p>Before Pressing Play Button</p>
<p><img src="https://i.stack.imgur.com/Q1tmQ.jpg" alt="iframe result on emulator"></p>
<p>After Pressing Play button on video</p>
<p><img src="https://i.stack.imgur.com/SU3pm.jpg" alt="iframe result on emulator on play button click"></p>
<p>I think we cannot stream videos on emulator since it is a virtual device</p>
<p>But when I run this on phone it's not even showing this result. </p>
<p>I try iframe with a document attach to it works fine on phone as well as emulator </p>
<pre><code>String customHtml = "<iframe src='http://docs.google.com/viewer?url=http://www.iasted.org/conferences/formatting/presentations-tips.ppt&embedded=true' width='100%' height='100%' style='border: none;'></iframe>";
</code></pre>
<p>So please help me to load videos to this frame.</p>
<p>(I run it on phone). What's the problem?
also will iframe work on Android 2.1?</p>
<p>did any one tried <a href="https://developers.google.com/youtube/android/player/downloads/" rel="nofollow noreferrer">Youtube Api</a> ? </p> | 0 | 1,170 |
Automatically map an Excel XmlMap to a worksheet in VBA without knowing the schema XPaths | <p>I am building an Excel file that downloads from an API.</p>
<p>It can automatically generate the XmlMap from the URL schema metadata. However I then need to map the XmlMap elements to ListObjects in order to pull the data and put on a worksheet.</p>
<p>The code to do this is <code>range.Xpath.SetValue map xPath</code> for each item (from <a href="https://msdn.microsoft.com/en-us/vba/excel-vba/articles/xpath-setvalue-method-excel" rel="nofollow noreferrer">MSDN</a>):</p>
<pre class="lang-vb prettyprint-override"><code>Sub CreateXMLList()
Dim mapContact As XmlMap
Dim strXPath As String
Dim lstContacts As ListObject
Dim objNewCol As ListColumn
' Specify the schema map to use.
Set mapContact = ActiveWorkbook.XmlMaps("Contacts")
' Create a new list.
Set lstContacts = ActiveSheet.ListObjects.Add
' Specify the first element to map.
strXPath = "/Root/Person/FirstName"
' Map the element.
lstContacts.ListColumns(1).XPath.SetValue mapContact, strXPath
' Specify the second element to map.
strXPath = "/Root/Person/LastName"
' Add a column to the list.
Set objNewCol = lstContacts.ListColumns.Add
' Map the element.
objNewCol.XPath.SetValue mapContact, strXPath
strXPath = "/Root/Person/Address/Zip"
Set objNewCol = lstContacts.ListColumns.Add
objNewCol.XPath.SetValue mapContact, strXPath
End Sub
</code></pre>
<p>Here's the schema output:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<xsd:element name="root" nillable="true" >
<xsd:complexType>
<xsd:sequence minOccurs="0">
<xsd:element minOccurs="0" maxOccurs="unbounded" nillable="true" name="list-item" form="unqualified">
<xsd:complexType>
<xsd:sequence minOccurs="0">
<xsd:element name="data_source_organization"
minOccurs="0"
nillable="true"
type="xsd:string"
form="unqualified"
/>
<xsd:element name="survey_name"
minOccurs="0"
nillable="true"
type="xsd:string"
form="unqualified"
/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
</code></pre>
<p>Here's the data (from which Excel automatically gets the schema and creates the XmlMap, if using the GUI):</p>
<pre class="lang-xml prettyprint-override"><code><root xsi:noNamespaceSchemaLocation="/api/domain/schema/?format=xml">
<list-item>
<data_source_organization>An org</data_source_organization>
<survey_name>A Survey</survey_name>
</list-item>
<list-item>
<data_source_organization>An org</data_source_organization>
<survey_name>Another Survey</survey_name>
</list-item>
</root>
</code></pre>
<p>However I don't want to specify the XPath strings - I want Excel to get everything from the schema metadata, just like it does if you use the GUI functionality (Data, Get External Data, From Other Sources, XML, paste a URL) - this automatically creates an XML map, creates a ListObject on the worksheet, maps every column in the source data, and grabs and displays the data. (If you record a macro doing this, it skips the mapping step.)</p>
<ul>
<li>Can I point an XmlMap to a cell, range or ListObject?</li>
<li>Can I iterate the XmlMap and retrieve every list-item XPath?</li>
<li>Some other way?</li>
</ul>
<p>To experiment/reproduce, save the above XML as files, then create a sub as follows:</p>
<pre class="lang-vb prettyprint-override"><code>Set currentMap = ActiveWorkbook.XmlMaps.Add("C:\path\to\schema.xml", "root")
currentMap.DataBinding.LoadSettings "path\to\data.xml"
' Do something to map the XmlMap elements to cells in the spreadsheet
' eg, objNewCol.XPath.SetValue currentMap, "root/data_source_organization"
' But some method that does not involve naming the Xml paths but iterates the schema
currentMap.DataBinding.Refresh
</code></pre>
<p>If the XmlMap is mapped to cells, those cells will populate with data.</p> | 0 | 2,099 |
Twitter Bootstrap and jQuery Validation Plugin - use class="control-group error" | <p>I've created a form using the Twitter Bootstrap framework and have integrated the jQuery Validation Plugin. I have one form with a series of yes/no questions with radio buttons that I validate to ensure each question is not empty - this is working well.</p>
<p>I would like to leverage the Bootstrap class="control-group error" to make the error text appear in red so it stands out to the user - currently the "This field is required" text is in black and it's hard to locate.</p>
<p>There's an example of how I would like the error text to appear here:</p>
<p><a href="http://twitter.github.io/bootstrap/base-css.html#forms" rel="nofollow">http://twitter.github.io/bootstrap/base-css.html#forms</a></p>
<p>at the end of this section under "Validation states". Here's the specific example that shows a red message after the input field (I only want the error to appear after they have clicked the Submit button):</p>
<pre><code><div class="control-group error">
<label class="control-label" for="inputError">Input with error</label>
<div class="controls">
<input type="text" id="inputError">
<span class="help-inline">Please correct the error</span>
</div>
</div>
</code></pre>
<p>Here's my form showing one question:</p>
<pre><code><form class="form-horizontal" method="post" id="inputForm">
<input type="hidden" name="recid" value="1">
<table class="table table-condensed table-hover table-bordered">
<h2>Input Form</h2>
<tr>
<td>Question 1.</td>
<td>
<div class="controls">
<label class="radio inline">
<input type="radio" name="q1" value="Yes" required>Yes </label>
<label class="radio inline">
<input type="radio" name="q1" value="No" required>No </label>
<label for="q1" class="error"></label>
</div>
</td>
<td>Please answer Yes or No</td>
</tr>
</table>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Continue</button>
<button type="reset" class="btn">Reset</button>
</div>
</div>
</form>
</code></pre>
<p>I can't work out how to combine the example with my form so that if they submit the form and they haven't answered a question the alert appears in red.</p>
<p>I've setup a jsFiddle <a href="http://jsfiddle.net/fmdataweb/F28PF/" rel="nofollow">here</a> that shows this is action if that helps.</p> | 0 | 1,200 |
cpp - valgrind - Invalid read of size 8 | <p>I'm getting mad understanding that valgrind error. I've got a template class called Matrix that has some overloaded operators etc... to do some mathematical operations. Matrixes are used inside a class called ExtendedKalmanFilter. </p>
<p>Here is the valgrind trace:</p>
<pre><code>==3352== Invalid read of size 8
==3352== at 0x804CC8F: BOViL::math::Matrix<double>::operator*(BOViL::math::Matrix<double> const&) const (Matrix.h:285)
==3352== by 0x8051F91: BOViL::algorithms::ExtendedKalmanFilter::forecastStep(double) (ExtendedKalmanFilter.cpp:48)
==3352== by 0x8051F25: BOViL::algorithms::ExtendedKalmanFilter::stepEKF(BOViL::math::Matrix<double> const&, double) (ExtendedKalmanFilter.cpp:39)
==3352== by 0x804B98F: testSegmentation() (TestSegmentation.cpp:53)
==3352== by 0x805266D: main (main.cpp:16)
==3352== Address 0x6a8b3c0 is 0 bytes after a block of size 48 alloc'd
==3352== at 0x402B454: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3352== by 0x804C986: BOViL::math::Matrix<double>::operator=(BOViL::math::Matrix<double> const&) (Matrix.h:224)
==3352== by 0x8051C62: BOViL::algorithms::ExtendedKalmanFilter::setUpEKF(BOViL::math::Matrix<double>, BOViL::math::Matrix<double>, BOViL::math::Matrix<double>) (ExtendedKalmanFilter.cpp:23)
==3352== by 0x804B74F: testSegmentation() (TestSegmentation.cpp:37)
==3352== by 0x805266D: main (main.cpp:16)
==3352==
==3352== Invalid write of size 8
==3352== at 0x804CC12: BOViL::math::Matrix<double>::operator*(BOViL::math::Matrix<double> const&) const (Matrix.h:283)
==3352== by 0x8051F91: BOViL::algorithms::ExtendedKalmanFilter::forecastStep(double) (ExtendedKalmanFilter.cpp:48)
==3352== by 0x8051F25: BOViL::algorithms::ExtendedKalmanFilter::stepEKF(BOViL::math::Matrix<double> const&, double) (ExtendedKalmanFilter.cpp:39)
==3352== by 0x804B98F: testSegmentation() (TestSegmentation.cpp:53)
==3352== by 0x805266D: main (main.cpp:16)
==3352== Address 0x6a8d210 is 0 bytes after a block of size 48 alloc'd
==3352== at 0x402B454: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3352== by 0x804CBD8: BOViL::math::Matrix<double>::operator*(BOViL::math::Matrix<double> const&) const (Matrix.h:279)
==3352== by 0x8051F91: BOViL::algorithms::ExtendedKalmanFilter::forecastStep(double) (ExtendedKalmanFilter.cpp:48)
==3352== by 0x8051F25: BOViL::algorithms::ExtendedKalmanFilter::stepEKF(BOViL::math::Matrix<double> const&, double) (ExtendedKalmanFilter.cpp:39)
==3352== by 0x804B98F: testSegmentation() (TestSegmentation.cpp:53)
==3352== by 0x805266D: main (main.cpp:16)
==3352==
==3352== Invalid read of size 8
==3352== at 0x804CC55: BOViL::math::Matrix<double>::operator*(BOViL::math::Matrix<double> const&) const (Matrix.h:285)
==3352== by 0x8051F91: BOViL::algorithms::ExtendedKalmanFilter::forecastStep(double) (ExtendedKalmanFilter.cpp:48)
==3352== by 0x8051F25: BOViL::algorithms::ExtendedKalmanFilter::stepEKF(BOViL::math::Matrix<double> const&, double) (ExtendedKalmanFilter.cpp:39)
==3352== by 0x804B98F: testSegmentation() (TestSegmentation.cpp:53)
==3352== by 0x805266D: main (main.cpp:16)
==3352== Address 0x6a8d210 is 0 bytes after a block of size 48 alloc'd
==3352== at 0x402B454: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3352== by 0x804CBD8: BOViL::math::Matrix<double>::operator*(BOViL::math::Matrix<double> const&) const (Matrix.h:279)
==3352== by 0x8051F91: BOViL::algorithms::ExtendedKalmanFilter::forecastStep(double) (ExtendedKalmanFilter.cpp:48)
==3352== by 0x8051F25: BOViL::algorithms::ExtendedKalmanFilter::stepEKF(BOViL::math::Matrix<double> const&, double) (ExtendedKalmanFilter.cpp:39)
==3352== by 0x804B98F: testSegmentation() (TestSegmentation.cpp:53)
==3352== by 0x805266D: main (main.cpp:16)
==3352==
==3352== Invalid write of size 8
==3352== at 0x804CC95: BOViL::math::Matrix<double>::operator*(BOViL::math::Matrix<double> const&) const (Matrix.h:285)
==3352== by 0x8051F91: BOViL::algorithms::ExtendedKalmanFilter::forecastStep(double) (ExtendedKalmanFilter.cpp:48)
==3352== by 0x8051F25: BOViL::algorithms::ExtendedKalmanFilter::stepEKF(BOViL::math::Matrix<double> const&, double) (ExtendedKalmanFilter.cpp:39)
==3352== by 0x804B98F: testSegmentation() (TestSegmentation.cpp:53)
==3352== by 0x805266D: main (main.cpp:16)
==3352== Address 0x6a8d210 is 0 bytes after a block of size 48 alloc'd
==3352== at 0x402B454: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3352== by 0x804CBD8: BOViL::math::Matrix<double>::operator*(BOViL::math::Matrix<double> const&) const (Matrix.h:279)
==3352== by 0x8051F91: BOViL::algorithms::ExtendedKalmanFilter::forecastStep(double) (ExtendedKalmanFilter.cpp:48)
==3352== by 0x8051F25: BOViL::algorithms::ExtendedKalmanFilter::stepEKF(BOViL::math::Matrix<double> const&, double) (ExtendedKalmanFilter.cpp:39)
==3352== by 0x804B98F: testSegmentation() (TestSegmentation.cpp:53)
==3352== by 0x805266D: main (main.cpp:16)
==3352==
--3352-- VALGRIND INTERNAL ERROR: Valgrind received a signal 11 (SIGSEGV) - exiting
--3352-- si_code=1; Faulting address: 0x6F666562; sp: 0x6800fa88
valgrind: the 'impossible' happened:
Killed by fatal signal
==3352== at 0x380C0AD4: ??? (in /usr/lib/valgrind/memcheck-x86-linux)
==3352== by 0x380C12C5: ??? (in /usr/lib/valgrind/memcheck-x86-linux)
==3352== by 0x38040A63: ??? (in /usr/lib/valgrind/memcheck-x86-linux)
==3352== by 0x38040B36: ??? (in /usr/lib/valgrind/memcheck-x86-linux)
==3352== by 0x3803EA4B: ??? (in /usr/lib/valgrind/memcheck-x86-linux)
==3352== by 0x74206572: ???
sched status:
running_tid=1
Thread 1: status = VgTs_Runnable
==3352== at 0x402B454: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3352== by 0x804BD52: BOViL::math::Matrix<double>::Matrix(double const*, int, int) (Matrix.h:118)
==3352== by 0x804CCF3: BOViL::math::Matrix<double>::operator*(BOViL::math::Matrix<double> const&) const (Matrix.h:290)
==3352== by 0x8051F91: BOViL::algorithms::ExtendedKalmanFilter::forecastStep(double) (ExtendedKalmanFilter.cpp:48)
==3352== by 0x8051F25: BOViL::algorithms::ExtendedKalmanFilter::stepEKF(BOViL::math::Matrix<double> const&, double) (ExtendedKalmanFilter.cpp:39)
==3352== by 0x804B98F: testSegmentation() (TestSegmentation.cpp:53)
==3352== by 0x805266D: main (main.cpp:16)
</code></pre>
<p>And here fragments of the code:</p>
<p>--> Matrix interface</p>
<pre><code> template <typename type_>
class Matrix{
public: // Main interface
Matrix(); // Default constructor
Matrix(int _cols, int _rows); // Empty matrix constructor
Matrix(const type_* _mat, int _rows, int _cols); // Full-defined matrix constructor
Matrix(const Matrix& _mat); // Copy constructor
Matrix(Matrix&& _mat); // Move constructor c++11
~Matrix(); // De-constructor
type_* getMatrixPtr() const;
int getWidth() const;
int getHeight() const;
void showMatrix() const;
public: // Overloaded Operators
std::string operator<<(const Matrix<type_>& _mat) const; // Operator for cout 666 TODO:
type_& operator[](int _index);
Matrix operator=(const Matrix& _mat); // Assignement operator
Matrix operator+(const Matrix& _mat) const; // Add operator
Matrix operator-(const Matrix& _mat) const; // Sub operator
Matrix operator*(const Matrix& _mat) const; // Mul operator
Matrix operator*(const type_ _scalar) const; // Scalar operator
Matrix operator^(const double _exp) const; // Pow operator 666 TODO:
public: // Other operations 666 TODO: Change names
Matrix operator&(const Matrix& _mat) const; // Projection operator._mat is projected to this
Matrix transpose(); // Transpose operator
type_ determinant(); // Determinant operator
public: // Various algorithms
double norm();
bool decompositionLU(Matrix& _L, Matrix& _U);
bool decompositionCholesky(Matrix& _L, Matrix& _Lt);
bool decompositionLDL(Matrix& _L, Matrix& _D, Matrix& _Lt);
bool decompositionQR_GR(Matrix& _Q, Matrix& _R); // QR decomposition using Householder reflexions algorithm.
Matrix inverse(); // Using QR algorithm
private: // Private interface
int mCols, mRows;
type_* mPtr;
};
</code></pre>
<p>-->And here is where matrix crash:</p>
<pre><code>void ExtendedKalmanFilter::forecastStep(const double _incT){
updateJf(_incT);
mXfk = mJf * mXak; <<<----- HERE CRASH, inside operator*
mP = mJf * mP * mJf.transpose() + mQ;
}
</code></pre>
<p>To be precise, it crash inside the constructor matrix(type_* ptr, int _cols, int _rows); while initializing the pointer</p>
<pre><code>template<typename type_>
Matrix<type_> Matrix<type_>::operator* (const Matrix<type_>& _mat) const{
if(mCols !=_mat.mRows)
assert(false);
type_* ptr = new type_[mRows*_mat.mCols];
for(int i = 0; i < mRows ; i ++ ){
for(int j = 0 ; j < mCols ; j ++){
ptr[_mat.mCols * i + j] = 0;
for(int k = 0 ; k < _mat.mRows ; k ++){
ptr[_mat.mCols * i + j] += mPtr[mCols * i + k] * _mat.mPtr[_mat.mCols * k + j];
}
}
}
Matrix<type_> mat(ptr, mRows, _mat.mCols); <<< ----- HERE
delete[] ptr;
return mat;
}
template<typename type_>
Matrix<type_>::Matrix(const type_* _matPtr, int _rows, int _cols): mPtr(new type_[_cols*_rows]),
mCols(_cols),
mRows(_rows)
{ <<<---- CRASH before getting into (So I suppose that crash in the new type_[_cols*_rows]
for(int i = 0; i < _cols*_rows ; i ++){
mPtr[i] = _matPtr[i];
}
}
</code></pre>
<p>Finally, the destructor of the class is:</p>
<pre><code>template<typename type_>
Matrix<type_>::~Matrix(){
if(mPtr)
delete[] mPtr;
}
</code></pre>
<p>Can anyone help me? I cant find the trouble I tryed debugging with Visual Studio in windows and with valgrind in linux.</p>
<p>Thanks in advance</p> | 0 | 4,818 |
Spring IllegalStateException: A JTA EntityManager cannot use getTransaction() | <p>So after a big refactoring project, I am left with this exception and am unsure as how to correct it. It's dealing with some code that I did not write and I am unfamiliar with how it all works. There are other questions out there dealing with this exception, but none seem to fit my situation.</p>
<p>The class which uses <code>EntityManager</code> is <code>SpecialClaimsCaseRepositoryImpl</code>:</p>
<pre><code>package com.redacted.sch.repository.jpa;
//Imports
@Repository
public class SpecialClaimsCaseRepositoryImpl extends SimpleJpaRepository<SpecialClaimsCaseDto, SpecialClaimsCaseDto.Id> implements SpecialClaimsCaseRepository{
@PersistenceContext(unitName = "schManager")
private EntityManager em;
//Some autogenerated methods
public void setEntityManager(EntityManager em) {
this.em = em;
}
public EntityManager getEntityManager() {
return em;
}
}
</code></pre>
<p>Persistence.xml:</p>
<pre><code><persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="schManager">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/SCH_DS</jta-data-source>
<class>com.redacted.sch.domain.model.SpecialClaimsCaseDto</class>
<properties>
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.WebSphereExtendedJTATransactionLookup" />
<property name="hibernate.cache.region.factory_class" value="net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory" />
<property name="hibernate.cache.use_query_cache" value="true" />
<property name="hibernate.cache.use_second_level_cache" value="true" />
<property name="hibernate.dialect" value="com.bcbsks.hibernate.dialect.DB2Dialect" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.generate_statistics" value="false" />
<property name="hibernate.jdbc.use_scrollable_resultset" value="true" />
</properties>
</persistence-unit>
</persistence>
</code></pre>
<p>sch_model_spring.xml:</p>
<pre><code><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.redacted.repository.jpa,
com.redacted.sch.domain.model,
com.redacted.sch.repository.jpa,
com.redacted.sch.service,
com.redacted.sch.service.impl"/>
<tx:annotation-driven />
<tx:jta-transaction-manager />
<!-- Data source used for testing -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
<property name="url" value="jdbc:db2:redacted.redacted.com" />
<property name="username" value="redacted" />
<property name="password" value="redacted" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="schManager" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
</code></pre>
<p>And here's my project structure:</p>
<p><img src="https://i.stack.imgur.com/l1Rb9.png" alt="enter image description here"></p>
<p>></p>
<p>Here's a portion of the stack trace, with the full trace at this <a href="http://fpaste.org/117413/14051058/" rel="nofollow noreferrer">fpaste</a></p>
<pre><code>Caused by: java.lang.IllegalStateException: A JTA EntityManager cannot use getTransaction()
at org.hibernate.ejb.AbstractEntityManagerImpl.getTransaction(AbstractEntityManagerImpl.java:985)
at org.springframework.orm.jpa.DefaultJpaDialect.beginTransaction(DefaultJpaDialect.java:67)
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380)
... 80 more
</code></pre>
<p>I'm a total noob here, so if any other information is needed just ask and I'll update.</p>
<p>Thanks for all the help!</p> | 0 | 2,185 |
Settings fragment crash on click android studio | <p>I used the template "Settings Activity" in android studio, I created my own settings Fragment, added the code to the Java file.</p>
<pre><code>@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class LocationServicesPreferenceFragment extends PreferenceFragment{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_location_services);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("location_services"));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p>And I edited this method</p>
<pre><code>protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| GeneralPreferenceFragment.class.getName().equals(fragmentName)
|| DataSyncPreferenceFragment.class.getName().equals(fragmentName)
|| NotificationPreferenceFragment.class.getName().equals(fragmentName)
|| LocationServicesPreferenceFragment.class.getName().equals(fragmentName);
}
</code></pre>
<p>This is the result rendered</p>
<p><img src="https://i.stack.imgur.com/xFaj4.png" alt="Settings"></p>
<p>but this is what happens when I click my option, Other 3 options work perfectly</p>
<p><img src="https://i.stack.imgur.com/ljlGG.png" alt="Crash"></p>
<p>Any ideas to fix this problem??</p>
<p>LogCat</p>
<pre><code> 03-17 11:36:44.582 4178-4178/com.example.devandrin.myapplication I/art: Not late-enabling -Xcheck:jni (already on)
03-17 11:36:44.583 4178-4178/com.example.devandrin.myapplication W/art: Unexpected CPU variant for X86 using defaults: x86
03-17 11:36:44.708 4178-4178/com.example.devandrin.myapplication W/System: ClassLoader referenced unknown path: /data/app/com.example.devandrin.myapplication-1/lib/x86
03-17 11:36:44.713 4178-4178/com.example.devandrin.myapplication I/InstantRun: Starting Instant Run Server for com.example.devandrin.myapplication
03-17 11:36:45.392 4178-4178/com.example.devandrin.myapplication W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
03-17 11:36:45.791 4178-4207/com.example.devandrin.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
03-17 11:36:45.791 4178-4207/com.example.devandrin.myapplication D/OpenGLRenderer: Swap behavior 1
03-17 11:36:45.791 4178-4207/com.example.devandrin.myapplication W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
03-17 11:36:45.791 4178-4207/com.example.devandrin.myapplication D/OpenGLRenderer: Swap behavior 0
03-17 11:36:45.916 4178-4178/com.example.devandrin.myapplication W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
03-17 11:37:31.093 4178-4207/com.example.devandrin.myapplication D/OpenGLRenderer: endAllActiveAnimators on 0x9b4fe900 (RippleDrawable) with handle 0xa1f03f20
03-17 11:37:34.305 4178-4207/com.example.devandrin.myapplication W/OpenGLRenderer: Points are too far apart 4.000001
03-17 11:37:36.027 4178-4207/com.example.devandrin.myapplication W/OpenGLRenderer: Points are too far apart 4.000001
03-17 11:37:49.258 4178-4183/com.example.devandrin.myapplication I/art: Do partial code cache collection, code=29KB, data=29KB
03-17 11:37:49.265 4178-4183/com.example.devandrin.myapplication I/art: After code cache collection, code=22KB, data=26KB
03-17 11:37:49.265 4178-4183/com.example.devandrin.myapplication I/art: Increasing code cache capacity to 128KB
03-17 11:37:49.274 4178-4178/com.example.devandrin.myapplication D/AndroidRuntime: Shutting down VM
03-17 11:37:49.276 4178-4178/com.example.devandrin.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.devandrin.myapplication, PID: 4178
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.devandrin.myapplication/com.example.devandrin.myapplication.SettingsActivity}: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:225)
at com.example.devandrin.myapplication.SettingsActivity.bindPreferenceSummaryToValue(SettingsActivity.java:122)
at com.example.devandrin.myapplication.SettingsActivity.access$000(SettingsActivity.java:38)
at com.example.devandrin.myapplication.SettingsActivity$LocationServicesPreferenceFragment.onCreate(SettingsActivity.java:250)
at android.app.Fragment.performCreate(Fragment.java:2336)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:949)
at android.app.BackStackRecord.setLastIn(BackStackRecord.java:860)
at android.app.BackStackRecord.calculateFragments(BackStackRecord.java:900)
at android.app.BackStackRecord.run(BackStackRecord.java:728)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
at android.app.FragmentController.execPendingActions(FragmentController.java:371)
at android.app.Activity.performStart(Activity.java:6695)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2628)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code></pre>
<p>Code </p>
<pre><code>public class SettingsActivity extends AppCompatPreferenceActivity {
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
/*
For all other preferences, set the summary to the value's
simple string representation.
*/
preference.setSummary(stringValue);
}
return true;
}
};
/**
* Helper method to determine if the device has an extra-large screen. For
* example, 10" tablets are extra-large.
*/
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* @see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
/*
Trigger the listener immediately with the preference's
current value.
*/
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
}
/**
* Set up the {@link android.app.ActionBar}, if the API is available.
*/
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if (!super.onMenuItemSelected(featureId, item)) {
NavUtils.navigateUpFromSameTask(this);
}
return true;
}
return super.onMenuItemSelected(featureId, item);
}
/**
* {@inheritDoc}
*/
@Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
/**
* {@inheritDoc}
*/
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
/**
* This method stops fragment injection in malicious applications.
* Make sure to deny any unknown fragments here.
*/
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| GeneralPreferenceFragment.class.getName().equals(fragmentName)
|| DataSyncPreferenceFragment.class.getName().equals(fragmentName)
|| NotificationPreferenceFragment.class.getName().equals(fragmentName)
|| LocationServicesPreferenceFragment.class.getName().equals(fragmentName);
}
/**
* This fragment shows general preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
/**
* This fragment shows notification preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class LocationServicesPreferenceFragment extends PreferenceFragment{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_location_services);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("location_services"));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
/**
* This fragment shows data and sync preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class DataSyncPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_data_sync);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("sync_frequency"));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
</code></pre> | 0 | 9,953 |
Java code for dealing cards from a deck | <p>I am trying to write a method to remove the specified number of cards from the top of the deck and return them as an array.</p>
<p>This is what i have done so far. A method to create the deck, copy the deck, a method to return the card that is at the specified position in the array, a method to returns the size of the array of Cards, shuffle, and cut the deck (not sure if these are correct). Here is the card class</p>
<pre><code>public class Card {
private final int suit; // 0, 1, 2, 3 represent Spades, Hearts, Clubs,
// Diamonds, respectively
private final int value; // 1 through 13 (1 is Ace, 11 is jack, 12 is
// queen, 13 is king)
/*
* Strings for use in toString method and also for identifying card images
*/
private final static String[] suitNames = { "s", "h", "c", "d" };
private final static String[] valueNames = { "Unused", "A", "2", "3", "4",
"5", "6", "7", "8", "9", "10", "J", "Q", "K" };
/**
* Standard constructor.
*
* @param value
* 1 through 13; 1 represents Ace, 2 through 10 for numerical
* cards, 11 is Jack, 12 is Queen, 13 is King
* @param suit
* 0 through 3; represents Spades, Hearts, Clubs, or Diamonds
*/
public Card(int value, int suit) {
if (value < 1 || value > 13) {
throw new RuntimeException("Illegal card value attempted. The "
+ "acceptable range is 1 to 13. You tried " + value);
}
if (suit < 0 || suit > 3) {
throw new RuntimeException("Illegal suit attempted. The "
+ "acceptable range is 0 to 3. You tried " + suit);
}
this.suit = suit;
this.value = value;
}
/**
* "Getter" for value of Card.
*
* @return value of card (1-13; 1 for Ace, 2-10 for numerical cards, 11 for
* Jack, 12 for Queen, 13 for King)
*/
public int getValue() {
return value;
}
/**
* "Getter" for suit of Card.
*
* @return suit of card (0-3; 0 for Spades, 1 for Hearts, 2 for Clubs, 3 for
* Diamonds)
*/
public int getSuit() {
return suit;
}
/**
* Returns the name of the card as a String. For example, the 2 of hearts
* would be "2 of h", and the Jack of Spades would be "J of s".
*
* @return string that looks like: value "of" suit
*/
public String toString() {
return valueNames[value] + " of " + suitNames[suit];
}
/**
* [STUDENTS SHOULD NOT BE CALLING THIS METHOD!] Used for finding the image
* corresponding to this Card.
*
* @return path of image file corresponding to this Card.
*/
public String getImageFileName() {
String retValue;
retValue = suitNames[suit];
if (value <= 10)
retValue += value;
else if (value == 11)
retValue += "j";
else if (value == 12)
retValue += "q";
else if (value == 13)
retValue += "k";
else
retValue += "Unknown!";
return "images/" + retValue + ".gif";
}
}
</code></pre>
<p>The Deck method is the one that I need help on</p>
<pre><code>public class Deck {
private Card[] cards;
public Deck() {
cards = new Card[52];
int numberOfCard = 0;
for (int suit = 0; suit <= 3; suit++) {
for (int value = 1; value <= 13; value++) {
cards[numberOfCard] = new Card(value, suit);
numberOfCard++;
}
}
}
public Deck(Deck other) {
cards = new Card[other.cards.length];
for (int i = 0; i < other.cards.length; i++) {
cards[i] = other.cards[i];
}
}
public Card getCardAt(int position) {
if (position >= cards.length) {
throw new IndexOutOfBoundsException("Values are out of bounds");
} else {
return cards[position];
}
}
public int getNumCards() {
return cards.length;
}
public void shuffle() {
int temp = 0;
for (int row = 0; row < cards.length; row++) {
int random = (int) (Math.random() * ((cards.length - row) + 1));
Deck.this.cards[temp] = this.getCardAt(row);
cards[row] = cards[random];
cards[random] = cards[temp];
}
}
public void cut(int position) {
Deck tempDeck = new Deck();
int cutNum = tempDeck.getNumCards() / 2;
for (int i = 0; i < cutNum; i++) {
tempDeck.cards[i] = this.cards[52 - cutNum + i];
}
for (int j = 0; j < 52 - cutNum; j++) {
tempDeck.cards[j + cutNum] = this.cards[j];
}
this.cards = tempDeck.cards;
}
public Card[] deal(int numCards) {
return cards;
}
}
</code></pre> | 0 | 2,243 |
Django REST: Uploading and serializing multiple images | <p>I have 2 models <code>Task</code> and <code>TaskImage</code> which is a collection of images belonging to <code>Task</code> object.</p>
<p>What I want is to be able to add multiple images to my <code>Task</code> object, but I can only do it using 2 models. Currently, when I add images, it doesn't let me upload them and save new objects.</p>
<p><strong>settings.py</strong></p>
<pre><code>MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
</code></pre>
<p><strong>serializers.py</strong> </p>
<pre><code>class TaskImageSerializer(serializers.ModelSerializer):
class Meta:
model = TaskImage
fields = ('image',)
class TaskSerializer(serializers.HyperlinkedModelSerializer):
user = serializers.ReadOnlyField(source='user.username')
images = TaskImageSerializer(source='image_set', many=True, read_only=True)
class Meta:
model = Task
fields = '__all__'
def create(self, validated_data):
images_data = validated_data.pop('images')
task = Task.objects.create(**validated_data)
for image_data in images_data:
TaskImage.objects.create(task=task, **image_data)
return task
</code></pre>
<p><strong>models.py</strong></p>
<pre><code>class Task(models.Model):
title = models.CharField(max_length=100, blank=False)
user = models.ForeignKey(User)
def save(self, *args, **kwargs):
super(Task, self).save(*args, **kwargs)
class TaskImage(models.Model):
task = models.ForeignKey(Task, on_delete=models.CASCADE)
image = models.FileField(blank=True)
</code></pre>
<p>However, when I do a post request:</p>
<p><a href="https://i.stack.imgur.com/NndxK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NndxK.png" alt="enter image description here"></a></p>
<p>I get the following traceback:</p>
<blockquote>
<p>File
"/Applications/Anaconda/anaconda/envs/godo/lib/python3.6/site-packages/django/core/handlers/exception.py"
in inner
41. response = get_response(request)</p>
<p>File
"/Applications/Anaconda/anaconda/envs/godo/lib/python3.6/site-packages/django/core/handlers/base.py"
in _get_response
187. response = self.process_exception_by_middleware(e, request)</p>
<p>File
"/Applications/Anaconda/anaconda/envs/godo/lib/python3.6/site-packages/django/core/handlers/base.py"
in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)</p>
<p>File
"/Applications/Anaconda/anaconda/envs/godo/lib/python3.6/site-packages/django/views/decorators/csrf.py"
in wrapped_view
58. return view_func(*args, **kwargs)</p>
<p>File
"/Applications/Anaconda/anaconda/envs/godo/lib/python3.6/site-packages/rest_framework/viewsets.py"
in view
95. return self.dispatch(request, *args, **kwargs)</p>
<p>File
"/Applications/Anaconda/anaconda/envs/godo/lib/python3.6/site-packages/rest_framework/views.py"
in dispatch
494. response = self.handle_exception(exc)</p>
<p>File
"/Applications/Anaconda/anaconda/envs/godo/lib/python3.6/site-packages/rest_framework/views.py"
in handle_exception
454. self.raise_uncaught_exception(exc)</p>
<p>File
"/Applications/Anaconda/anaconda/envs/godo/lib/python3.6/site-packages/rest_framework/views.py"
in dispatch
491. response = handler(request, *args, **kwargs)</p>
<p>File
"/Applications/Anaconda/anaconda/envs/godo/lib/python3.6/site-packages/rest_framework/mixins.py"
in create
21. self.perform_create(serializer)</p>
<p>File "/Users/gr/Desktop/PycharmProjects/godo/api/views.py" in
perform_create
152. serializer.save(user=self.request.user)</p>
<p>File
"/Applications/Anaconda/anaconda/envs/godo/lib/python3.6/site-packages/rest_framework/serializers.py"
in save
214. self.instance = self.create(validated_data)</p>
<p>File "/Users/gr/Desktop/PycharmProjects/godo/api/serializers.py" in
create
67. images_data = validated_data.pop('images')</p>
<p>Exception Type: KeyError at /api/tasks/ Exception Value: 'images'</p>
</blockquote> | 0 | 1,745 |
How come I can't migrate in laravel | <p>Migration files in laravel is used to create the tables in the database, right? But when ever I try to migrate it gives me this error:</p>
<blockquote>
<p>C:\xampp\htdocs\app>php artisan migrate</p>
<p>[Illuminate\Database\QueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists (SQL: create table <code>users</code> (<code>
id</code> int unsigned not null auto_increment primary key, <code>name</code> varchar(255) not null, <code>email</code> varchar(255) not null,
<code>password</code> varchar(255) not null, <code>remember_token</code> varchar(100) null, <code>created_at</code> timestamp null, <code>updated_at</code> tim
estamp null) default character set utf8mb4 collate utf8mb4_unicode_ci)</p>
<p>[PDOException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists</p>
</blockquote>
<hr>
<p>and I created a new migration file and it's called test. I know users already exist but I want create the new table I created which is called test. </p>
<p>here is the migration file i am going to use to create my table but wont create:</p>
<pre><code> <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTestsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tests', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tests');
}
}
</code></pre>
<p>here is the users migration file that tells me it exist:</p>
<pre><code><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
</code></pre>
<p>here is the password migration file:</p>
<pre><code><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePasswordResetsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('password_resets', function (Blueprint $table) {
$table->string('email')->index();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('password_resets');
}
}
</code></pre>
<p>here is the dummies migration file i have that i didn't talk about because i thought it is not the problem: </p>
<pre><code><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDummiesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('dummies', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('body');
$table->timestamp('date'); //if you dont put name for the timestamp it will create: create_at and update_at fields.
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('dummies');
}
}
</code></pre>
<p>and sorry for keeping you guys waiting it took me long to find the edit button and fix the spacing of my code. It is my first time using stack over flow.</p> | 0 | 1,814 |
How can I list all my Amazon EC2 instances using Node.js in AWS Lambda? | <p>I'm on AWS and using <a href="https://aws.amazon.com/sdk-for-node-js/" rel="noreferrer">AWS SDK for JavaScript in Node.js</a>. I'm trying to build an AWS Lambda function and inside I want to get a list of all my Amazon EC2 instances, but I just can't seem to get it working. Can anyone spot what I'm doing wrong?</p>
<p>Here is my Lambda function code:</p>
<pre><code>var AWS = require('aws-sdk');
AWS.config.region = 'us-west-1';
exports.handler = function(event, context) {
console.log("\n\nLoading handler\n\n");
var ec2 = new AWS.EC2();
ec2.describeInstances( function(err, data) {
console.log("\nIn describe instances:\n");
if (err) console.log(err, err.stack); // an error occurred
else console.log("\n\n" + data + "\n\n"); // successful response
});
context.done(null, 'Function Finished!');
};
</code></pre>
<p>And this is my policy (I think it's correct?)</p>
<pre><code>{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:*"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:*"
],
"Resource": "arn:aws:ec2:*"
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::*"
]
}
]
}
</code></pre>
<p>And if I do a console.log on 'ec2' I get:</p>
<pre><code>{ config:
{ credentials:
{ expired: false,
expireTime: null,
accessKeyId: 'XXXXXXXXXXXXXXXXXX',
sessionToken: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
envPrefix: 'AWS' },
credentialProvider: { providers: [Object] },
region: 'us-west-1',
logger: null,
apiVersions: {},
apiVersion: null,
endpoint: 'ec2.us-west-1.amazonaws.com',
httpOptions: { timeout: 120000 },
maxRetries: undefined,
maxRedirects: 10,
paramValidation: true,
sslEnabled: true,
s3ForcePathStyle: false,
s3BucketEndpoint: false,
computeChecksums: true,
convertResponseTypes: true,
dynamoDbCrc32: true,
systemClockOffset: 0,
signatureVersion: 'v4' },
isGlobalEndpoint: false,
endpoint:
{ protocol: 'https:',
host: 'ec2.us-west-1.amazonaws.com',
port: 443,
hostname: 'ec2.us-west-1.amazonaws.com',
pathname: '/',
path: '/',
href: 'https://ec2.us-west-1.amazonaws.com/' } }
</code></pre> | 0 | 1,115 |
Getting error "Get http://localhost:9443/metrics: dial tcp 127.0.0.1:9443: connect: connection refused" | <p>I'm trying to configure Prometheus and Grafana with my Hyperledger fabric v1.4 network to analyze the peer and chaincode mertics. I've mapped peer container's port <code>9443</code> to my host machine's port <code>9443</code> after following this <a href="https://hyperledger-fabric.readthedocs.io/en/latest/operations_service.html#peer" rel="noreferrer">documentation</a>. I've also changed the <code>provider</code> entry to <code>prometheus</code> under <code>metrics</code> section in <code>core.yml</code> of peer. I've configured prometheus and grafana in <code>docker-compose.yml</code> in the following way.</p>
<pre><code> prometheus:
image: prom/prometheus:v2.6.1
container_name: prometheus
volumes:
- ./prometheus/:/etc/prometheus/
- prometheus_data:/prometheus
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--storage.tsdb.path=/prometheus'
- '--web.console.libraries=/etc/prometheus/console_libraries'
- '--web.console.templates=/etc/prometheus/consoles'
- '--storage.tsdb.retention=200h'
- '--web.enable-lifecycle'
restart: unless-stopped
ports:
- 9090:9090
networks:
- basic
labels:
org.label-schema.group: "monitoring"
grafana:
image: grafana/grafana:5.4.3
container_name: grafana
volumes:
- grafana_data:/var/lib/grafana
- ./grafana/datasources:/etc/grafana/datasources
- ./grafana/dashboards:/etc/grafana/dashboards
- ./grafana/setup.sh:/setup.sh
entrypoint: /setup.sh
environment:
- GF_SECURITY_ADMIN_USER={ADMIN_USER}
- GF_SECURITY_ADMIN_PASSWORD={ADMIN_PASS}
- GF_USERS_ALLOW_SIGN_UP=false
restart: unless-stopped
ports:
- 3000:3000
networks:
- basic
labels:
org.label-schema.group: "monitoring"
</code></pre>
<p>When I <code>curl 0.0.0.0:9443/metrics</code> on my remote centos machine, I get all the list of metrics. However, when I run Prometheus with the above configuration, it throws the error <code>Get http://localhost:9443/metrics: dial tcp 127.0.0.1:9443: connect: connection refused</code>. This is what my <code>prometheus.yml</code> looks like.</p>
<pre><code>global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: 'prometheus'
scrape_interval: 10s
static_configs:
- targets: ['localhost:9090']
- job_name: 'peer_metrics'
scrape_interval: 10s
static_configs:
- targets: ['localhost:9443']
</code></pre>
<p>Even, when I go to endpoint <code>http://localhost:9443/metrics</code> in my browser, I get all the metrics. What am I doing wrong here. How come Prometheus metrics are being shown on its interface and not peer's?</p> | 0 | 1,055 |
Why is subprocess.run output different from shell output of same command? | <p>I am using <code>subprocess.run()</code> for some automated testing. Mostly to automate doing:</p>
<pre><code>dummy.exe < file.txt > foo.txt
diff file.txt foo.txt
</code></pre>
<p>If you execute the above redirection in a shell, the two files are always identical. But whenever <code>file.txt</code> is too long, the below Python code does not return the correct result.</p>
<p>This is the Python code:</p>
<pre class="lang-python3 prettyprint-override"><code>import subprocess
import sys
def main(argv):
exe_path = r'dummy.exe'
file_path = r'file.txt'
with open(file_path, 'r') as test_file:
stdin = test_file.read().strip()
p = subprocess.run([exe_path], input=stdin, stdout=subprocess.PIPE, universal_newlines=True)
out = p.stdout.strip()
err = p.stderr
if stdin == out:
print('OK')
else:
print('failed: ' + out)
if __name__ == "__main__":
main(sys.argv[1:])
</code></pre>
<p>Here is the C++ code in <code>dummy.cc</code>:</p>
<pre class="lang-c++ prettyprint-override"><code>#include <iostream>
int main()
{
int size, count, a, b;
std::cin >> size;
std::cin >> count;
std::cout << size << " " << count << std::endl;
for (int i = 0; i < count; ++i)
{
std::cin >> a >> b;
std::cout << a << " " << b << std::endl;
}
}
</code></pre>
<p><code>file.txt</code> can be anything like this:</p>
<pre class="lang-none prettyprint-override"><code>1 100000
0 417
0 842
0 919
...
</code></pre>
<p>The second integer on the first line is the number of lines following, hence here <code>file.txt</code> will be 100,001 lines long. </p>
<p><strong>Question:</strong> Am I misusing subprocess.run() ? </p>
<p><strong>Edit</strong></p>
<p>My exact Python code after comment (newlines,rb) is taken into account:</p>
<pre><code>import subprocess
import sys
import os
def main(argv):
base_dir = os.path.dirname(__file__)
exe_path = os.path.join(base_dir, 'dummy.exe')
file_path = os.path.join(base_dir, 'infile.txt')
out_path = os.path.join(base_dir, 'outfile.txt')
with open(file_path, 'rb') as test_file:
stdin = test_file.read().strip()
p = subprocess.run([exe_path], input=stdin, stdout=subprocess.PIPE)
out = p.stdout.strip()
if stdin == out:
print('OK')
else:
with open(out_path, "wb") as text_file:
text_file.write(out)
if __name__ == "__main__":
main(sys.argv[1:])
</code></pre>
<p>Here is the first diff:</p>
<p><a href="https://i.stack.imgur.com/Fk2IW.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Fk2IW.jpg" alt="enter image description here"></a></p>
<p>Here is the input file: <a href="https://drive.google.com/open?id=0B--mU_EsNUGTR3VKaktvQVNtLTQ" rel="noreferrer">https://drive.google.com/open?id=0B--mU_EsNUGTR3VKaktvQVNtLTQ</a></p> | 0 | 1,331 |
NPM install express. Error: No compatible version found | <p>My OS is Ubuntu 13.04, 32 bit.</p>
<p>I am trying to install express with this command:</p>
<pre><code>$ npm install express
</code></pre>
<p>And this is the error I get:</p>
<pre><code>npm http GET https://registry.npmjs.org/express
npm http GET https://registry.npmjs.org/express
npm http 304 https://registry.npmjs.org/express
npm ERR! Error: No compatible version found: express@'>=4.0.0-0'
npm ERR! Valid install targets:
npm ERR! ["0.14.0","0.14.1","1.0.0","1.0.1","1.0.2","1.0.3","1.0.4","1.0.5","1.0.6","1.0.7","1.0.8","2.0.0","2.1.0","2.1.1","2.2.0","2.2.1","2.2.2","2.3.0","2.3.1","2.3.2","2.3.3","2.3.4","2.3.5","2.3.6","2.3.7","2.3.8","2.3.9","2.3.10","2.3.11","2.3.12","2.4.0","2.4.1","2.4.2","2.4.3","2.4.4","2.4.5","2.4.6","2.4.7","2.5.0","2.5.1","2.5.2","2.5.3","2.5.4","2.5.5","2.5.6","2.5.7","2.5.8","2.5.9","2.5.10","2.5.11","3.0.0","3.0.1","3.0.2","3.0.3","3.0.4","3.0.5","3.0.6","3.1.0","3.1.1","3.1.2","3.2.0","3.2.1","3.2.2","3.2.3","3.2.4","3.2.5","3.2.6","3.3.0","3.3.1","3.3.2","3.3.3","3.3.4","3.3.5","3.3.6","1.0.0-beta","1.0.0-beta2","1.0.0-rc","1.0.0-rc2","1.0.0-rc3","1.0.0-rc4","2.0.0-beta","2.0.0-beta2","2.0.0-beta3","2.0.0-rc","2.0.0-rc2","2.0.0-rc3","3.0.0-alpha1","3.0.0-alpha2","3.0.0-alpha3","3.0.0-alpha4","3.0.0-alpha5","3.0.0-beta1","3.0.0-beta2","3.0.0-beta3","3.0.0-beta4","3.0.0-beta6","3.0.0-beta7","3.0.0-rc1","3.0.0-rc2","3.0.0-rc3","3.0.0-rc4","3.0.0-rc5","3.3.7"]
npm ERR! at installTargetsError (/home/admin/.nodes/0.10.17/lib/node_modules/npm/lib/cache.js:719:10)
npm ERR! at next (/home/admin/.nodes/0.10.17/lib/node_modules/npm/lib/cache.js:698:17)
npm ERR! at /home/admin/.nodes/0.10.17/lib/node_modules/npm/lib/cache.js:675:5
npm ERR! at saved (/home/admin/.nodes/0.10.17/lib/node_modules/npm/node_modules/npm-registry-client/lib/get.js:142:7)
npm ERR! at /home/admin/.nodes/0.10.17/lib/node_modules/npm/node_modules/graceful-fs/polyfills.js:133:7
npm ERR! at Object.oncomplete (fs.js:107:15)
npm ERR! If you need help, you may report this log at:
npm ERR! <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR! <npm-@googlegroups.com>
npm ERR! System Linux 3.8.0-29-generic
npm ERR! command "/home/admin/.nodes/current/bin/node" "/home/admin/.nodes/current/bin/npm" "install" "express"
npm ERR! cwd /home/admin/M101JS/Week 2/hw2/hw2-3/blog
npm ERR! node -v v0.10.17
npm ERR! npm -v 1.3.8
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /home/admin/M101JS/Week 2/hw2/hw2-3/blog/npm-debug.log
npm ERR! not ok code 0
</code></pre>
<p>I am new to NodeJS and NPM, so I don't understand the response.
Does anyone have an idea how I can fix it?</p> | 0 | 1,465 |
Android Studio: Try-catch exception crashes application | <p>I was testing some vulnerabilities inside of my code and trying to fix them by throwing an exception when the user has an invalid input. Now when I implement a try-catch and run the application on my phone, it crashes when I put in that invalid input. </p>
<p>I assume my code doesn't catch the exception from the addData method. Is there another way to implement exceptions or how can I make it possible to catch the exception from the addData method?</p>
<pre><code>package com.odisee.photoboothapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.EditText;
import android.widget.Toast;
import com.odisee.photoboothapp.fontchanger.FontChangeTextView;
public class Form_Database extends AppCompatActivity {
DatabaseHelper myDb;
int selectedId;
RadioGroup test;
RadioButton editEducation;
EditText editName, editSurname, editEmail;
Button btnAddData;
@Override
protected void onCreate(Bundle savedInstanceState) throws IllegalArgumentException {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_form__database);
myDb = new DatabaseHelper(this);
test = (RadioGroup)findViewById(R.id.radioButtonChoice);
editName = (EditText)findViewById(R.id.edit_Name);
editSurname = (EditText)findViewById(R.id.edit_Surname);
editEmail = (EditText)findViewById(R.id.edit_Email);
btnAddData = (Button)findViewById(R.id.btnSend);
try {
addData();
}
catch(IllegalArgumentException e) {
Toast.makeText(Form_Database.this,"Data not inserted" + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
public void addData() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if(editName.getText().toString().contains("DROP")) {
throw new IllegalArgumentException("SQL Exceptie!");
}
else {
selectedId = test.getCheckedRadioButtonId();
editEducation = (RadioButton)findViewById(selectedId);
boolean isInserted = myDb.insertData(editName.getText().toString(), editSurname.getText().toString(), editEmail.getText().toString(), editEducation.getText().toString());
sendEmail();
if(isInserted == true) {
Toast.makeText(Form_Database.this,"Data inserted",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(Form_Database.this,"Data not inserted",Toast.LENGTH_LONG).show();
}
}
}
}
);
}
public void sendEmail() {
//Getting content for email
String email = editEmail.getText().toString();
String subject = "testberichtje voor lorenzo";
String message = "testberichtje voor lorenzo";
//Creating SendMail object
SendMail sm = new SendMail(this, email, subject, message);
//Executing sendmail to send email
sm.execute();
}
}
</code></pre>
<blockquote>
<p>05-01 17:58:17.021 30232-30232/com.odisee.photoboothapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.odisee.photoboothapp, PID: 30232
java.lang.IllegalArgumentException: SQL Exceptie!
at com.odisee.photoboothapp.Form_Database$1.onClick(Form_Database.java:55)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10826)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)</p>
</blockquote> | 0 | 2,755 |
Bank Account Program: Rejecting Deposit or Withdrawal | <p>I have been working on making a program to simulate bank transactions. I have to ask the user if they want to deposit, withdrawal, or transfer. Right now I am working on the deposit and withdrawal options of the account.</p>
<p>When the user selects a transaction (for example deposit) and enters a number, I made it so the program asks "Would you like to continue this transaction. Obviously, if yes the program will continue with the transaction and if no, it will not deposit the number the user entered.</p>
<p>My problem is, I have no clue what I need to put in the no option. I don't know if to reject the transaction means I have to exit the loop or what but at the moment if I hit no, the transaction will still go through. Below is a visual of what happens when I enter a transaction but dont want to continue:</p>
<p><img src="https://i.stack.imgur.com/FyL6O.jpg" alt="enter image description here"></p>
<p>below is my entire code. the part of code I don't know what to put has ** by it
It probably don't help my organization I am sorry for that!</p>
<pre><code>import java.util.Scanner;
public class BankTransactions {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num;
double balance = 0;
double checkingBalance= 0, savingsBalance =0;
do {
double amount;
System.out.println("------------------------");
System.out.println("Select a Transaction by typing number");
System.out.println("1. Deposit");
System.out.println("2. Withdrawal");
System.out.println("3. Balance");
System.out.println("4. Exit");
System.out.println("------------------------");
num = scan.nextInt();
if (num == 1) { //if DEPOSIT is selected
//ask to deposit from checking or savings
System.out.println("------------------------");
System.out.println("Would you like to deposit in checking or savings?");
System.out.println("1. Checking");
System.out.println("2. Savings");
System.out.println("------------------------");
num = scan.nextInt();
if (num == 1) { //if CHECKING is selected
//enter amount to be deposited
System.out.println("------------------------");
System.out.println("Enter amount to deposit in checking account: ");
System.out.println("------------------------");
amount = scan.nextDouble();
//ask if they want to continue with transaction
System.out.println("------------------------");
System.out.println("Would you like to continue this transaction?");
System.out.println("1. Yes");
System.out.println("2. No");
System.out.println("------------------------");
num = scan.nextInt();
// Add the amount to the checking balance
checkingBalance += amount;
System.out.println("------------------------");
System.out.println("Your checking account's balance is " + checkingBalance);
System.out.println("------------------------");
} else if (num == 2) { //if SAVINGS is selected
//enter amount to be deposited
System.out.println("------------------------");
System.out.println("Enter amount to deposit in savings account: ");
System.out.println("------------------------");
amount = scan.nextDouble();
//ask if they want to continue with transaction
System.out.println("------------------------");
System.out.println("Would you like to continue this transaction?");
System.out.println("1. Yes");
System.out.println("2. No");
System.out.println("------------------------");
num = scan.nextInt();
if (num == 1) {
// Add the amount entered to the savings balance
savingsBalance += amount;
System.out.println("------------------------");
System.out.println("Your savings account's balance is " + savingsBalance);
System.out.println("------------------------");
**} else if (num == 2) {
//EMPTY NEEDS CODE
}**
}
} else if (num == 2) { //if withdrawal is selected
//ask to withdrawal from checking or savings
System.out.println("------------------------");
System.out.println("Would you like to withdrawal from checking or savings?");
System.out.println("1. Checking");
System.out.println("2. Savings");
System.out.println("------------------------");
num = scan.nextInt();
if (num == 1) { //if checking is selected
//enter amount to be withdrawn
System.out.println("------------------------");
System.out.println("Enter amount to withdrawal: ");
System.out.println("------------------------");
amount = scan.nextDouble();
//ask if they want to continue with transaction
System.out.println("------------------------");
System.out.println("Would you like to continue this transaction?");
System.out.println("1. Yes");
System.out.println("2. No");
System.out.println("------------------------");
num = scan.nextInt();
if (num == 1) { //if you say yes to continuing
// Remove the amount from the balance
checkingBalance -= amount;
System.out.println("------------------------");
System.out.println("Your checking account's balance is " + checkingBalance);
System.out.println("------------------------");
} else if (num == 2) { //if you say no to continuing
//Do not remove amount from savings balance
//EMPTY NEEDS CODE
}
} else if (num == 2) { //if savings is selected
//enter amount to be withdrawn
System.out.println("------------------------");
System.out.println("Enter amount to withdrawal: ");
System.out.println("------------------------");
amount = scan.nextDouble();
//ask if they want to continue with transaction
System.out.println("------------------------");
System.out.println("Would you like to continue this transaction?");
System.out.println("1. Yes");
System.out.println("2. No");
System.out.println("------------------------");
num = scan.nextInt();
if (num == 1) { //if you say yes to continuing
// Remove the amount from the savings balance
savingsBalance -= amount;
System.out.println("------------------------");
System.out.println("Your savings account's balance is " + savingsBalance);
System.out.println("------------------------");
} else if (num == 2) { //if you say no to continuing
//Do not remove amount from savings balance
//EMPTY NEEDS CODE
}
}
} else if (num == 3) { //if balance is selected
//ask to see balance of checking or savings
System.out.println("------------------------");
System.out.println("Your Checking balance is " + checkingBalance);
System.out.println("Your Savings balance is " + savingsBalance);
System.out.println("------------------------");
num = scan.nextInt();
//needs to return to transaction options
}
} while (num != 4);
System.out.println("------------------------");
System.out.println("Good Bye!");
System.out.println("------------------------");
}
</code></pre>
<p>}</p>
<p>I am stuck and I want to figure it out. Please don't post the entire code corrected. I want to fix it myself and learn!</p> | 0 | 4,006 |
How to fix 'failed to find any PEM data in key input' error? | <p>I'm setting up Traefik with provided certificates for HTTPS using docker Swarm and it doesn't load them failing with <code>failed to find any PEM data in key input</code></p>
<p>I've tried to set it up with relative and absolute paths (see <a href="https://github.com/containous/traefik/issues/2001" rel="noreferrer">https://github.com/containous/traefik/issues/2001</a> ) but it doesn't seem to solve the issue.</p>
<p>The certificates I'm using are self signed but they're perfectly working with Nginx.</p>
<p>Traefik configuration in compose:</p>
<pre><code>version: "3.6"
services:
traefik:
image: traefik
command:
- "--defaultentrypoints=http,https"
- "--docker"
- "--docker.swarmMode"
- "--docker.exposedByDefault=false"
- "--docker.domain=sdb.it"
- "--docker.watch"
- "--entryPoints='Name:http Address::80 Redirect.EntryPoint:https'"
- "--entryPoints='Name:https Address::443 TLS:/etc/ssl/certs/sonarqube.crt,/etc/ssl/certs/sonarqube.key'"
- "--loglevel=DEBUG"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
ports:
- 80:80
- 443:443
networks:
- traefik
secrets:
- source: sdbit-sonarqube-docker.sdb.it.crt
target: /etc/ssl/certs/sonarqube.crt
mode: 644
- source: sdbit-sonarqube-docker.sdb.it.key
target: /etc/ssl/certs/sonarqube.key
mode: 644
deploy:
placement:
constraints:
- node.role == manager
volumes:
certificates:
external: true
networks:
traefik:
external: true
secrets:
sdbit-sonarqube-docker.sdb.it.crt:
external: true
sdbit-sonarqube-docker.sdb.it.key:
external: true
</code></pre>
<p>And this is the Traefik log:</p>
<pre><code>time="2019-02-15T17:57:51Z" level=info msg="No tls.defaultCertificate given for : using the first item in tls.certificates as a fallback.",
time="2019-02-15T17:57:51Z" level=info msg="Traefik version v1.7.9 built on 2019-02-11_11:36:32AM",
time="2019-02-15T17:57:51Z" level=debug msg="Global configuration loaded {\"LifeCycle\":{\"RequestAcceptGraceTimeout\":0,\"GraceTimeOut\":10000000000},\"GraceTimeOut\":0,\"Debug\":false,\"CheckNewVersion\":true,\"SendAnonymousUsage\":false,\"AccessLogsFile\":\"\",\"AccessLog\":null,\"TraefikLogsFile\":\"\",\"TraefikLog\":null,\"Tracing\":null,\"LogLevel\":\"DEBUG\",\"EntryPoints\":{\"\":{\"Address\":\":443\",\"TLS\":{\"MinVersion\":\"\",\"CipherSuites\":null,\"Certificates\":[{\"CertFile\":\"certs/sonarqube.crt\",\"KeyFile\":\"certs/sonarqube.key'\"}],\"ClientCAFiles\":null,\"ClientCA\":{\"Files\":null,\"Optional\":false},\"DefaultCertificate\":{\"CertFile\":\"certs/sonarqube.crt\",\"KeyFile\":\"certs/sonarqube.key'\"},\"SniStrict\":false},\"Redirect\":null,\"Auth\":null,\"WhitelistSourceRange\":null,\"WhiteList\":null,\"Compress\":false,\"ProxyProtocol\":null,\"ForwardedHeaders\":{\"Insecure\":true,\"TrustedIPs\":null}}},\"Cluster\":null,\"Constraints\":[],\"ACME\":null,\"DefaultEntryPoints\":[\"http\",\"https\"],\"ProvidersThrottleDuration\":2000000000,\"MaxIdleConnsPerHost\":200,\"IdleTimeout\":0,\"InsecureSkipVerify\":false,\"RootCAs\":null,\"Retry\":null,\"HealthCheck\":{\"Interval\":30000000000},\"RespondingTimeouts\":null,\"ForwardingTimeouts\":null,\"AllowMinWeightZero\":false,\"KeepTrailingSlash\":false,\"Web\":null,\"Docker\":{\"Watch\":true,\"Filename\":\"\",\"Constraints\":null,\"Trace\":false,\"TemplateVersion\":2,\"DebugLogGeneratedTemplate\":false,\"Endpoint\":\"unix:///var/run/docker.sock\",\"Domain\":\"sdb.it\",\"TLS\":null,\"ExposedByDefault\":false,\"UseBindPortIP\":false,\"SwarmMode\":true,\"Network\":\"\",\"SwarmModeRefreshSeconds\":15},\"File\":null,\"Marathon\":null,\"Consul\":null,\"ConsulCatalog\":null,\"Etcd\":null,\"Zookeeper\":null,\"Boltdb\":null,\"Kubernetes\":null,\"Mesos\":null,\"Eureka\":null,\"ECS\":null,\"Rancher\":null,\"DynamoDB\":null,\"ServiceFabric\":null,\"Rest\":null,\"API\":null,\"Metrics\":null,\"Ping\":null,\"HostResolver\":null}",
time="2019-02-15T17:57:51Z" level=info msg="\nStats collection is disabled.\nHelp us improve Traefik by turning this feature on :)\nMore details on: https://docs.traefik.io/basics/#collected-data\n",
time="2019-02-15T17:57:51Z" level=error msg="failed to load X509 key pair: tls: failed to find any PEM data in certificate input",
time="2019-02-15T17:57:51Z" level=info msg="Preparing server &{Address::443 TLS:0xc000283290 Redirect:<nil> Auth:<nil> WhitelistSourceRange:[] WhiteList:<nil> Compress:false ProxyProtocol:<nil> ForwardedHeaders:0xc000512540} with readTimeout=0s writeTimeout=0s idleTimeout=3m0s",
time="2019-02-15T17:57:51Z" level=error msg="Unable to add a certificate to the entryPoint \"\" : unable to generate TLS certificate : tls: failed to find any PEM data in certificate input",
time="2019-02-15T17:57:51Z" level=info msg="Starting provider configuration.ProviderAggregator {}",
time="2019-02-15T17:57:51Z" level=info msg="Starting server on :443",
time="2019-02-15T17:57:51Z" level=info msg="Starting provider *docker.Provider {\"Watch\":true,\"Filename\":\"\",\"Constraints\":null,\"Trace\":false,\"TemplateVersion\":2,\"DebugLogGeneratedTemplate\":false,\"Endpoint\":\"unix:///var/run/docker.sock\",\"Domain\":\"sdb.it\",\"TLS\":null,\"ExposedByDefault\":false,\"UseBindPortIP\":false,\"SwarmMode\":true,\"Network\":\"\",\"SwarmModeRefreshSeconds\":15}",
time="2019-02-15T17:57:51Z" level=debug msg="Provider connection established with docker 18.09.0 (API 1.39)",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container prometheus_alertmanager.1",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container portainer_portainer.1",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container prometheus_cadvisor.02f9e4aqq9h8p5wxtvebrpdmi",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container prometheus_cadvisor.3wjdodinomlez4o034htgxq4f",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container prometheus_cadvisor.6qextrzc6c3mli99sl5qs8sj7",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container prometheus_cadvisor.epwzjchzyldg35bp7zh83h2l8",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container prometheus_cadvisor.fex6ncwmfhrs4mp8g3iwk2yxb",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container prometheus_prometheus.1",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container sonarqube-glf-dev_sonarqube.1",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container sonarqube-glf-dev_db.1",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container portainer_agent.dm14e8f833zvl3iov8c7ejlui",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container portainer_agent.f61gqjypxiepukygmba1kjwi1",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container portainer_agent.iei6yqpdqfqm6okwmp54pbdt8",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container portainer_agent.oej5oojf7vhp17hi0h0notgjd",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container portainer_agent.oxa7l6ahqpo4mu5j0zoh4puf9",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container prometheus_node-exporter.hzarmo2gu75r0mrmwtfeitbok",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container prometheus_node-exporter.igb6gb1yb313gky7j3t9idc8k",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container prometheus_node-exporter.oyr1umf2pp7bdkvuez7nz8m54",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container prometheus_node-exporter.v7q6iugofokx59254h537tvnz",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container prometheus_node-exporter.v9d4wnwgvlcfytgk4de1ys1k6",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container prometheus_grafana.1",
time="2019-02-15T17:57:51Z" level=debug msg="Filtering disabled container gitlab-runner_gitlab-runner.1",
time="2019-02-15T17:57:51Z" level=debug msg="Configuration received from provider docker: {}",
time="2019-02-15T17:57:51Z" level=error msg="failed to load X509 key pair: tls: failed to find any PEM data in certificate input",
time="2019-02-15T17:57:51Z" level=info msg="Server configuration reloaded on :443",
</code></pre> | 0 | 3,189 |
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Too many connections | <p>My simple web-app sometimes crashes when navigating around the site, the error message I've gotten from the logs are found below. I have absolutely no idea of what is causing this and would be very thankful for any tips that'll lead me in the right direction.</p>
<pre><code>HTTP Status 500 - org.hibernate.exception.JDBCConnectionException: Cannot open connection
</code></pre>
<p>type Exception report</p>
<pre><code>message org.hibernate.exception.JDBCConnectionException: Cannot open connection
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: org.hibernate.exception.JDBCConnectionException: Cannot open connection
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
</code></pre>
<p>root cause</p>
<pre><code>org.hibernate.exception.JDBCConnectionException: Cannot open connection
org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:97)
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52)
org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449)
org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:161)
org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1573)
org.hibernate.loader.Loader.doQuery(Loader.java:696)
org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
org.hibernate.loader.Loader.doList(Loader.java:2228)
org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2125)
org.hibernate.loader.Loader.list(Loader.java:2120)
org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:118)
org.hibernate.impl.SessionImpl.list(SessionImpl.java:1596)
org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:306)
com.html.XmlSetting.getListOfhtml_connect(XmlSetting.java:55)
com.html.XmlSetting.removeXml(XmlSetting.java:121)
com.html.MarginSetting.removeXml(MarginSetting.java:291)
org.apache.jsp.check_jsp._jspService(check_jsp.java:183)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
</code></pre>
<p>root cause</p>
<pre><code>com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Too many connections
sun.reflect.GeneratedConstructorAccessor153.newInstance(Unknown Source)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:532)
com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
com.mysql.jdbc.Util.getInstance(Util.java:381)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:985)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3376)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:894)
com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3808)
com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1256)
com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2032)
com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:729)
com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
sun.reflect.GeneratedConstructorAccessor145.newInstance(Unknown Source)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:532)
com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
java.sql.DriverManager.getConnection(DriverManager.java:620)
java.sql.DriverManager.getConnection(DriverManager.java:169)
org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:133)
org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:161)
org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1573)
org.hibernate.loader.Loader.doQuery(Loader.java:696)
org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
org.hibernate.loader.Loader.doList(Loader.java:2228)
org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2125)
org.hibernate.loader.Loader.list(Loader.java:2120)
org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:118)
org.hibernate.impl.SessionImpl.list(SessionImpl.java:1596)
org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:306)
com.html.XmlSetting.getListOfhtml_connect(XmlSetting.java:55)
com.html.XmlSetting.removeXml(XmlSetting.java:121)
com.html.MarginSetting.removeXml(MarginSetting.java:291)
org.apache.jsp.check_jsp._jspService(check_jsp.java:183)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
</code></pre>
<p>I m using Apache Tomcat 7</p>
<p><strong>hibernate.cfg.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/htmlcleaner</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.zeroDateTimeBehavior">convertToNull</property>
<property name="connection.pool_size">1000</property>
<!-- <property name="show_sql">true</property> -->
<mapping class="com.model.html_connect"/>
</session-factory>
</hibernate-configuration>
</code></pre> | 0 | 3,035 |
CSS Drop Down Menu Not working | <p>i'm learning the basic of CSS and trying to create a dropdown menu, i tried creating a dropdown menu using plain CSS, but it's not working.</p>
<p>So far I tried this code:</p>
<p><strong>CSS</strong></p>
<pre><code><!-- because of the * default code it takes out all margin and padding or idententation -->
*{
margin: 0px;
padding: 0px;}
body
{
font-family: verdana;
background-color: ABC;
padding: 50px;
}
h1
{
text-align: center;
border-bottom: 2px solid #009;
margin-bottom: 50px;
}
/*rules for navigation menu */
/*============================================*/
ul#navmenu, ul.sub1
{
list-style-type: none;<!-- sets bullets to none -->
}
ul#navmenu li
{
outline: 1px solid red;
width: 125px;
text- align: center;
position: relative;
float: left;
margin-right: 4px;
}
ul#navmenu a
{
text-decoration: none;
display: block; <!-- this code makes the link a button instead pointing specifically on the link -->
width: 125px;
height: 25px;
line-height: 25px;
background-color: #FFF;
border: 1px solid #CCC;
border-radius: 5px;
}
ul#navmenu .sub1 li
{
}
ul#navmenu .sub1 a
{
margin-top: 0px;
}
ul#navmenu li:hover > a
{
background-color: #CFC; <!-- sets all link color when hovering to yellow -->
}
ul#navmenu li:hover a: hover
{
background-color: #FF0; <!-- sets all link color when hovering to yellow -->
}
ul#navmenu ul.sub1
{
display: none;
position: absolute;
top: 26px;
left: 0px;
}
ul#navmenu li:hover .sub1
{
display: block;
}
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><h1>Navigation Menu</h1>
<ul id="navmenu">
<li><a href="#">Hyperlink 1</a></li>
<li><a href="#">Hyperlink 2</a></li>
<ul id="sub1">
<li><a href="#">Hyperlink 2.1</a></li>
<li><a href="#">Hyperlink 2.2</a></li>
</ul>
<li><a href="#">Hyperlink 3</a></li>
<li><a href="#">Hyperlink 4</a></li>
</ul>
</body>
</html>
</code></pre>
<p>The dropdown menu is not working, it's not hiding the sub menus, i don't know why.</p>
<p>Here is the picture screenshot using Internet Explorer:</p>
<p><a href="http://s23.postimg.org/jrzexl21n/z_IEs.png" rel="nofollow">IE</a></p>
<p>While using Google Chrome:</p>
<p><a href="http://s11.postimg.org/qbo08ftlv/zchromes.png" rel="nofollow">Chrome</a></p>
<p>I can't move on:( Any suggestion why dropdown menu is not working and why it's showing differently using other browsers?
Is there a way on how to code CSS dropdown menu where it will show the same on any browser? Thanks in advance.</p> | 0 | 1,215 |
Ionic Uncaught (in promise): invalid link | <p>I have probably a problem with <code>this.nav.push</code> in Ionic. I have done a login/registration page but when I login, I get this error message. I have to add some code in login.ts and e.g home.ts (which is the main page) ?</p>
<blockquote>
<p>Runtime Error <br>
Uncaught (in promise): invalid link: HomePage</p>
</blockquote>
<hr>
<blockquote>
<p>Error: Uncaught (in promise): invalid link: HomePage
at d (<a href="http://localhost:8100/build/polyfills.js:3:3991" rel="nofollow noreferrer">http://localhost:8100/build/polyfills.js:3:3991</a>)
at l (<a href="http://localhost:8100/build/polyfills.js:3:3244" rel="nofollow noreferrer">http://localhost:8100/build/polyfills.js:3:3244</a>)
at Object.reject (<a href="http://localhost:8100/build/polyfills.js:3:2600" rel="nofollow noreferrer">http://localhost:8100/build/polyfills.js:3:2600</a>)
at NavControllerBase._fireError (<a href="http://localhost:8100/build/main.js:45465:16" rel="nofollow noreferrer">http://localhost:8100/build/main.js:45465:16</a>)
at NavControllerBase._failed (<a href="http://localhost:8100/build/main.js:45453:14" rel="nofollow noreferrer">http://localhost:8100/build/main.js:45453:14</a>)
at <a href="http://localhost:8100/build/main.js:45508:59" rel="nofollow noreferrer">http://localhost:8100/build/main.js:45508:59</a>
at t.invoke (<a href="http://localhost:8100/build/polyfills.js:3:11562" rel="nofollow noreferrer">http://localhost:8100/build/polyfills.js:3:11562</a>)
at Object.onInvoke (<a href="http://localhost:8100/build/main.js:4622:37" rel="nofollow noreferrer">http://localhost:8100/build/main.js:4622:37</a>)
at t.invoke (<a href="http://localhost:8100/build/polyfills.js:3:11502" rel="nofollow noreferrer">http://localhost:8100/build/polyfills.js:3:11502</a>)
at n.run (<a href="http://localhost:8100/build/polyfills.js:3:6468" rel="nofollow noreferrer">http://localhost:8100/build/polyfills.js:3:6468</a>)
at <a href="http://localhost:8100/build/polyfills.js:3:3767" rel="nofollow noreferrer">http://localhost:8100/build/polyfills.js:3:3767</a>
at t.invokeTask (<a href="http://localhost:8100/build/polyfills.js:3:12256" rel="nofollow noreferrer">http://localhost:8100/build/polyfills.js:3:12256</a>)
at Object.onInvokeTask (<a href="http://localhost:8100/build/main.js:4613:37" rel="nofollow noreferrer">http://localhost:8100/build/main.js:4613:37</a>)
at t.invokeTask (<a href="http://localhost:8100/build/polyfills.js:3:12177" rel="nofollow noreferrer">http://localhost:8100/build/polyfills.js:3:12177</a>)
at n.runTask (<a href="http://localhost:8100/build/polyfills.js:3:7153" rel="nofollow noreferrer">http://localhost:8100/build/polyfills.js:3:7153</a>)</p>
</blockquote>
<p>@edit: The problem occurs when I want login to my app. Here is the code to login.</p>
<p>login.ts</p>
<pre><code>public login() {
this.showLoading()
this.auth.login(this.registerCredentials).subscribe(allowed => {
if (allowed) {
this.nav.push('HomePage');
} else {
this.showError("Access Denied");
}
},
error => {
this.showError(error);
});
}
</code></pre>
<hr>
<p>auth-service.ts ( here is public function which executes my login and where I have password and email which I need to type in login ) </p>
<pre><code> public login(credentials) {
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
return Observable.create(observer => {
// At this point make a request to your backend to make a real check!
let access = (credentials.password === "pass" && credentials.email === "email");
this.currentUser = new User('Simon', 'saimon@devdactic.com');
observer.next(access);
observer.complete();
});
}
}
</code></pre>
<p>I don't know why this code is wrong. My home page in my app is home.ts and class is HomePage</p> | 0 | 1,620 |
Convert to UNICODE in C# | <pre><code>public string DecodeFromUtf8(string utf8String)
{
// copy the string as UTF-8 bytes.
byte[] utf8Bytes = new byte[utf8String.Length];
for (int i = 0; i < utf8String.Length; ++i)
{
//Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255,
//"the char must be in byte's range");
utf8Bytes[i] = (byte)utf8String[i];
}
return Encoding.UTF8.GetString(utf8Bytes, 0, utf8Bytes.Length);
}
</code></pre>
<p>this code doesn't work for me
do you have any good ideas?</p>
<p>i need the unicode array for russian fonts like this</p>
<pre><code> public static readonly ReadOnlyCollection<char> Unicodes = Array.AsReadOnly(new char[]
{
'\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007',
'\u0008', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F',
'\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
'\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D', '\u001E', '\u001F',
'\u0020', '\u0021', '\u0022', '\u0023', '\u0024', '\u0025', '\u0026', '\u0027',
'\u0028', '\u0029', '\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037',
'\u0038', '\u0039', '\u003A', '\u003B', '\u003C', '\u003D', '\u003E', '\u003F',
'\u0040', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047',
'\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F',
'\u0050', '\u0051', '\u0052', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057',
'\u0058', '\u0059', '\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F',
'\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067',
'\u0068', '\u0069', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F',
'\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077',
'\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D', '\u007E', '\u007F',
'\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD',
'\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD',
'\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD',
'\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD', '\uFFFD',
'\u00A0', '\u058E', '\u0587', '\u0589', '\u0029', '\u0028', '\u00BB', '\u00AB',
'\u2015', '\u00B7', '\u055D', '\u002C', '\u2010', '\u058A', '\u2026', '\u055C',
'\u055B', '\u055E', '\u0531', '\u0561', '\u0532', '\u0562', '\u0533', '\u0563',
'\u0534', '\u0564', '\u0535', '\u0565', '\u0536', '\u0566', '\u0537', '\u0567',
'\u0538', '\u0568', '\u0539', '\u0569', '\u053A', '\u056A', '\u053B', '\u056B',
'\u053C', '\u056C', '\u053D', '\u056D', '\u053E', '\u056E', '\u053F', '\u056F',
'\u0540', '\u0570', '\u0541', '\u0571', '\u0542', '\u0572', '\u0543', '\u0573',
'\u0544', '\u0574', '\u0545', '\u0575', '\u0546', '\u0576', '\u0547', '\u0577',
'\u0548', '\u0578', '\u0549', '\u0579', '\u054A', '\u057A', '\u054B', '\u057B',
'\u054C', '\u057C', '\u054D', '\u057D', '\u054E', '\u057E', '\u054F', '\u057F',
'\u0550', '\u0580', '\u0551', '\u0581', '\u0552', '\u0582', '\u0553', '\u0583',
'\u0554', '\u0584', '\u0555', '\u0585', '\u0556', '\u0586', '\u055A', '\uFFFD' });
</code></pre> | 0 | 2,155 |
Fill histograms (array reduction) in parallel with OpenMP without using a critical section | <p>I would like to fill histograms in parallel using OpenMP. I have come up with two different methods of doing this with OpenMP in C/C++. </p>
<p>The first method <code>proccess_data_v1</code> makes a private histogram variable <code>hist_private</code> for each thread, fills them in prallel, and then sums the private histograms into the shared histogram <code>hist</code> in a <code>critical</code> section. </p>
<p>The second method <code>proccess_data_v2</code> makes a shared array of histograms with array size equal to the number of threads, fills this array in parallel, and then sums the shared histogram <code>hist</code> in parallel. </p>
<p>The second method seems superior to me since it avoids a critical section and sums the histograms in parallel. However, it requires knowing the number of threads and calling <code>omp_get_thread_num()</code>. I generally try to avoid this. Is there better way to do the second method without referencing the thread numbers and using a shared array with size equal to the number of threads?</p>
<pre><code>void proccess_data_v1(float *data, int *hist, const int n, const int nbins, float max) {
#pragma omp parallel
{
int *hist_private = new int[nbins];
for(int i=0; i<nbins; i++) hist_private[i] = 0;
#pragma omp for nowait
for(int i=0; i<n; i++) {
float x = reconstruct_data(data[i]);
fill_hist(hist_private, nbins, max, x);
}
#pragma omp critical
{
for(int i=0; i<nbins; i++) {
hist[i] += hist_private[i];
}
}
delete[] hist_private;
}
}
void proccess_data_v2(float *data, int *hist, const int n, const int nbins, float max) {
const int nthreads = 8;
omp_set_num_threads(nthreads);
int *hista = new int[nbins*nthreads];
#pragma omp parallel
{
const int ithread = omp_get_thread_num();
for(int i=0; i<nbins; i++) hista[nbins*ithread+i] = 0;
#pragma omp for
for(int i=0; i<n; i++) {
float x = reconstruct_data(data[i]);
fill_hist(&hista[nbins*ithread], nbins, max, x);
}
#pragma omp for
for(int i=0; i<nbins; i++) {
for(int t=0; t<nthreads; t++) {
hist[i] += hista[nbins*t + i];
}
}
}
delete[] hista;
}
</code></pre>
<p><strong>Edit:</strong>
Based on a suggestion by @HristoIliev I have created an improved method called <code>process_data_v3</code></p>
<pre><code>#define ROUND_DOWN(x, s) ((x) & ~((s)-1))
void proccess_data_v2(float *data, int *hist, const int n, const int nbins, float max) {
int* hista;
#pragma omp parallel
{
const int nthreads = omp_get_num_threads();
const int ithread = omp_get_thread_num();
int lda = ROUND_DOWN(nbins+1023, 1024); //1024 ints = 4096 bytes -> round to a multiple of page size
#pragma omp single
hista = (int*)_mm_malloc(lda*sizeof(int)*nthreads, 4096); //align memory to page size
for(int i=0; i<nbins; i++) hista[lda*ithread+i] = 0;
#pragma omp for
for(int i=0; i<n; i++) {
float x = reconstruct_data(data[i]);
fill_hist(&hista[lda*ithread], nbins, max, x);
}
#pragma omp for
for(int i=0; i<nbins; i++) {
for(int t=0; t<nthreads; t++) {
hist[i] += hista[lda*t + i];
}
}
}
_mm_free(hista);
}
</code></pre> | 0 | 1,607 |
No MaterialLocalizations found - MyApp widgets require MaterialLocalizations to be provided by a Localizations widget ancestor | <p>I was just trying to create an app with button which shows an alert message when the button is pressed. </p>
<p>But it gives me this error(Mentioned below).</p>
<p>I wrote this code by taking reference of <a href="https://www.youtube.com/watch?v=h2U7S-3_rPc&list=PLlxmoA0rQ-Lw6tAs2fGFuXGP13-dWdKsB&index=13" rel="noreferrer">this</a> video. </p>
<p>I am running the application on a live android phone using adb connect</p>
<p>Please help..! </p>
<p>Code</p>
<pre><code>import 'package:flutter/material.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Test",
home: Scaffold(
appBar: AppBar(title: Text("Test")),
body: Container(
child: Center(
child: RaisedButton(
color: Colors.redAccent,
textColor: Colors.white,
onPressed: (){testAlert(context);},
child: Text("PressMe"),
),
),
),
),
);
}
void testAlert(BuildContext context){
var alert = AlertDialog(
title: Text("Test"),
content: Text("Done..!"),
);
showDialog(
context: context,
builder: (BuildContext context){
return alert;
}
);
}
}
</code></pre>
<p>This is the code that i wrote. I also tried inserting the contents of testAlert() function directly into onPressed but doesn't work.</p>
<p>Error</p>
<pre><code>Performing hot reload...
Syncing files to device ZUK Z2131...
Reloaded 0 of 419 libraries in 1,929ms.
I/flutter (18652): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter (18652): The following assertion was thrown while handling a gesture:
I/flutter (18652): No MaterialLocalizations found.
I/flutter (18652): MyApp widgets require MaterialLocalizations to be provided by a Localizations widget ancestor.
I/flutter (18652): Localizations are used to generate many different messages, labels,and abbreviations which are used
I/flutter (18652): by the material library.
I/flutter (18652): To introduce a MaterialLocalizations, either use a MaterialApp at the root of your application to
I/flutter (18652): include them automatically, or add a Localization widget with a MaterialLocalizations delegate.
I/flutter (18652): The specific widget that could not find a MaterialLocalizations ancestor was:
I/flutter (18652): MyApp
I/flutter (18652): The ancestors of this widget were:
I/flutter (18652): [root]
I/flutter (18652):
I/flutter (18652): When the exception was thrown, this was the stack:
I/flutter (18652): #0 debugCheckHasMaterialLocalizations.<anonymous closure> (package:flutter/src/material/debug.dart:124:7)
I/flutter (18652): #1 debugCheckHasMaterialLocalizations (package:flutter/src/material/debug.dart:127:4)
I/flutter (18652): #2 showDialog (package:flutter/src/material/dialog.dart:635:10)
I/flutter (18652): #3 MyApp.testAlert (package:flutter_app/main.dart:33:5)
I/flutter (18652): #4 MyApp.build.<anonymous closure> (package:flutter_app/main.dart:19:29)
I/flutter (18652): #5 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:507:14)
I/flutter (18652): #6 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:562:30)
I/flutter (18652): #7 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
I/flutter (18652): #8 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
I/flutter (18652): #9 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7)
I/flutter (18652): #10 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:315:9)
I/flutter (18652): #11 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
I/flutter (18652): #12 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
I/flutter (18652): #13 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:180:19)
I/flutter (18652): #14 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:158:22)
I/flutter (18652): #15 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:138:7)
I/flutter (18652): #16 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
I/flutter (18652): #17 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
I/flutter (18652): #18 _invoke1 (dart:ui/hooks.dart:168:13)
I/flutter (18652): #19 _dispatchPointerDataPacket (dart:ui/hooks.dart:122:5)
I/flutter (18652):
I/flutter (18652): Handler: onTap
I/flutter (18652): Recognizer:
I/flutter (18652): TapGestureRecognizer#d5d82(debugOwner: GestureDetector, state: possible, won arena, finalPosition:
I/flutter (18652): Offset(220.2, 406.1), sent tap down)
I/flutter (18652): ════════════════════════════════════════════════════════════════════════════════════════════════════
W/ActivityThread(18652): handleWindowVisibility: no activity for token android.os.BinderProxy@59b4e8d
I/ViewRootImpl(18652): CPU Rendering VSync enable = true
</code></pre> | 0 | 2,216 |
XStream fromXML() exception | <p>I am trying to deserialize a string in Java using the XStream package. The XStream package can serialize my class fine. I get the XML (cannot change format of XML) from a server and try to save its node information to the corresponding variables in a certain class. My function is at the bottom and I tried to register a new converter for the XStream object (thinking that it was because one variable is a byte array) but still no luck. Can anyone shed some light on these exceptions? Do i need to register "MyClass" and write my own converter for XStream to handle deserializing my class? Thanks in advance.</p>
<p>Exception if a string or StringReader object are passed into fromXML() as input:</p>
<blockquote>
<p>[Fatal Error] :1:1: Content is not allowed in prolog.<br>
com.thoughtworks.xstream.io.StreamException: : Content is not allowed in prolog.<br>
at com.thoughtworks.xstream.io.xml.DomDriver.createReader(DomDriver.java:86)<br>
at com.thoughtworks.xstream.io.xml.DomDriver.createReader(DomDriver.java:66)<br>
at com.thoughtworks.xstream.XStream.fromXML(XStream.java:853) </p>
</blockquote>
<p>Exception if ByteArrayInputStream is used as input to fromXML():</p>
<blockquote>
<p>com.thoughtworks.xstream.converters.ConversionException: ByteSize : ByteSize : ByteSize : ByteSize<br>
---- Debugging information ----<br>
message : ByteSize : ByteSize<br>
cause-exception : com.thoughtworks.xstream.mapper.CannotResolveClassException<br>
cause-message : ByteSize : ByteSize<br>
class : MyClass<br>
required-type : MyClass<br>
path : /MyClass/ByteSize<br>
at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:89)<br>
at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:63)<br>
at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:76)<br>
at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:60)<br>
at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:137)<br>
at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:33)<br>
at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:923)<br>
at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:909)<br>
at com.thoughtworks.xstream.XStream.fromXML(XStream.java:861) </p>
</blockquote>
<pre><code>static Object fromXmlString(String xml)
{
XStream xStream = new XStream(new DomDriver());
xStream.registerConverter(new EncodedByteArrayConverter());
//tried all 3 below
//return xStream.fromXML(new StringReader(xml));
//return xStream.fromXML(new ByteArrayInputStream(xml.getBytes()));
return xStream.fromXML(xml);
}
</code></pre> | 0 | 1,061 |
Getting error while creating rest service using apache camel | <p>Since i am prety much new to Apache camel and especially Rest DSL, I thought of trying a sample of Rest DSL.</p>
<p>So i created a camel-config.xml as:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<!-- use camel-metrics route policy to gather metrics for all routes -->
<!-- bean id="metricsRoutePolicyFactory" class="org.apache.camel.component.metrics.routepolicy.MetricsRoutePolicyFactory"/-->
<!-- a rest service which uses binding to/from pojos -->
<bean id="userRoutes" class="org.apache.camel.example.rest.UserRouteBuilder"/>
<!-- a bean for user services -->
<bean id="userService" class="org.apache.camel.example.rest.UserService"/>
<camelContext id="myCamel" xmlns="http://camel.apache.org/schema/spring">
<routeBuilder ref="userRoutes"/>
</camelContext>
</beans>
</code></pre>
<p>and my route class is :</p>
<pre><code>package org.apache.camel.example.rest;
import org.apache.camel.builder.RouteBuilder;
/**
* Define REST services using the Camel REST DSL
*/
public class UserRouteBuilder extends RouteBuilder {
public void configure() throws Exception {
rest("/say").get("/hello").to("direct:hello").get("/bye")
.consumes("application/json").to("direct:bye").post("/bye")
.to("mock:update");
from("direct:hello").transform().constant("Hello World");
from("direct:bye").transform().constant("Bye World");
}
}
</code></pre>
<p>and my web.xml is :</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" 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>My Camel Rest Application</display-name>
<!-- location of Camel Spring xml files -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- to use Java DSL -->
<param-value>classpath:camel-config.xml</param-value>
<!-- to use XML DSL, then enable me, and disable Java DSL above
<param-value>classpath:camel-config-xml.xml</param-value>
-->
</context-param>
<!-- the listener that kick-starts Spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- to setup Camel Servlet -->
<servlet>
<display-name>Camel Http Transport Servlet</display-name>
<servlet-name>CamelServlet</servlet-name>
<servlet-class>org.apache.camel.component.servlet.CamelHttpTransportServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- START SNIPPET: e1 -->
<!-- to setup Camel Swagger api servlet -->
<servlet>
<servlet-name>ApiDeclarationServlet</servlet-name>
<servlet-class>org.apache.camel.component.swagger.DefaultCamelSwaggerServlet</servlet-class>
<init-param>
<!-- we specify the base.path using relative notation, that means the actual path will be calculated at runtime as
http://server:port/contextpath/rest -->
<param-name>base.path</param-name>
<param-value>rest</param-value>
</init-param>
<init-param>
<!-- we specify the api.path using relative notation, that means the actual path will be calculated at runtime as
http://server:port/contextpath/api-docs -->
<param-name>api.path</param-name>
<param-value>api-docs</param-value>
</init-param>
<init-param>
<param-name>api.version</param-name>
<param-value>1.2.3</param-value>
</init-param>
<init-param>
<param-name>api.title</param-name>
<param-value>User Services</param-value>
</init-param>
<init-param>
<param-name>api.description</param-name>
<param-value>Camel Rest Example with Swagger that provides an User REST service</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- swagger api declaration -->
<servlet-mapping>
<servlet-name>ApiDeclarationServlet</servlet-name>
<url-pattern>/api-docs/*</url-pattern>
</servlet-mapping>
<!-- END SNIPPET: e1 -->
<!-- define that url path for the Camel Servlet to use -->
<servlet-mapping>
<servlet-name>CamelServlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<!-- START SNIPPET: e2 -->
<!-- enable CORS filter so people can use swagger ui to browse and test the apis -->
<filter>
<filter-name>RestSwaggerCorsFilter</filter-name>
<filter-class>org.apache.camel.component.swagger.RestSwaggerCorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RestSwaggerCorsFilter</filter-name>
<url-pattern>/api-docs/*</url-pattern>
<url-pattern>/rest/*</url-pattern>
</filter-mapping>
<!-- END SNIPPET: e2 -->
<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
</web-app>
</code></pre>
<p>Now i have created a war file of my restProject and i deployed it on tomcat. Provided all the neccessary jars in the lib folder of tomcat. I am using camel 2.14.</p>
<p>Now when i start my tomcat, During startup i get error as :</p>
<pre><code>SEVERE: Context initialization failed
org.apache.camel.RuntimeCamelException: java.lang.IllegalStateException: Cannot find RestConsumerFactory in Registry or
as a Component to use
at org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException(ObjectHelper.java:1364)
at org.apache.camel.spring.SpringCamelContext.onApplicationEvent(SpringCamelContext.java:122)
at org.apache.camel.spring.CamelContextFactoryBean.onApplicationEvent(CamelContextFactoryBean.java:327)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMult
icaster.java:96)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:3
34)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:
948)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389
)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:618)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1100)
at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1618)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.IllegalStateException: Cannot find RestConsumerFactory in Registry or as a Component to use
at org.apache.camel.component.rest.RestEndpoint.createConsumer(RestEndpoint.java:238)
at org.apache.camel.impl.EventDrivenConsumerRoute.addServices(EventDrivenConsumerRoute.java:65)
at org.apache.camel.impl.DefaultRoute.onStartingServices(DefaultRoute.java:80)
at org.apache.camel.impl.RouteService.warmUp(RouteService.java:134)
at org.apache.camel.impl.DefaultCamelContext.doWarmUpRoutes(DefaultCamelContext.java:2379)
at org.apache.camel.impl.DefaultCamelContext.safelyStartRouteServices(DefaultCamelContext.java:2309)
at org.apache.camel.impl.DefaultCamelContext.doStartOrResumeRoutes(DefaultCamelContext.java:2091)
at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:1951)
at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:1777)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61)
at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:1745)
at org.apache.camel.spring.SpringCamelContext.maybeStart(SpringCamelContext.java:254)
at org.apache.camel.spring.SpringCamelContext.onApplicationEvent(SpringCamelContext.java:120)
... 22 more
</code></pre>
<p>I am trying to figure out for the past two days, Why i am getting this error.
Really looking forward to your solutions. Thanks in advance..</p> | 0 | 4,105 |
Create breadcrumbs dynamically on client side using javascript | <p>I want to create <strong>breadcrumbs dynamically on client side using java script</strong>. The breadcrumbs will be the <strong>path followed by user</strong> while navigation as:
<strong>Home > about us > our history..</strong></p>
<p>The anchor tags will be generated on each page in the sequence in which the user navigate.</p>
<p>Now I can create these breadcrumbs using server side technology easily but I want to generate it dynamically on each page on client side.
Now I don't know exactly how to implement it.</p>
<p>Some logic in my mind is as: </p>
<ol>
<li><p>Create an <strong>object type variable</strong> in java script with a <strong>name</strong>
and <strong>value pair</strong> where <strong>name</strong> is the <strong>name of current</strong> page
and <strong>value</strong> is the <strong>url of that page</strong>. </p></li>
<li><p>Now pass this object
variable using <strong>query string</strong> while navigating from one page to
other.</p></li>
<li><p>Then in the second page get that object variable from query string
and extract the name and value pair from that object and then using
that create the anchor and add it to targeted div (place holder). </p></li>
<li><p>Again when user goes to another page <strong>add the name and value pairs</strong>
for all the <strong>previous pages</strong> along with the <strong>name and value pair</strong> for current page at the last in the <strong>object variable</strong> and pass it to next page
using <strong>query string</strong>. </p></li>
<li><p>Now in next page <strong>do the same</strong> and create anchors.</p></li>
</ol>
<p>Some what similar I got <a href="http://jsfiddle.net/JcZun/1/" rel="noreferrer">here</a> using html5 client side storage as:
<strong>html:</strong></p>
<pre><code><ul id="navigation_links">
<li>Page1</li>
<li>Page2</li>
<li>Page3</li>
</ul>
</code></pre>
<p><strong>js:</strong></p>
<pre><code>$(document).ready(function(){
bindEventToNavigation();
});
function bindEventToNavigation(){
$.each($("#navigation_links > li"), function(index, element){
$(element).click(function(event){
breadcrumbStateSaver($(event.currentTarget).html());
showBreadCrumb();
});
});
}
function breadcrumbStateSaver(text){
//here we'll check if the browser has storage capabilities
if(typeof(Storage) != "undefined"){
if(sessionStorage.breadcrumb){
//this is how you retrieve the breadcrumb from the storage
var breadcrumb = sessionStorage.breadcrumb;
sessionStorage.breadcrumb = breadcrumb + " >> "+text;
} else {
sessionStorage.breadcrumb = ""+text;
}
}
//if not you can build in a failover with cookies
}
function showBreadCrumb(){
$("#breadcrumb").html(sessionStorage.breadcrumb);
}
<div id="breadcrumb"></div>
</code></pre>
<p>but here instead of creating hyperlinked anchors it is creating simple text, whereas I want the breadcrumbs to be anchors and hyperlinked to their respective pages.</p>
<p>I am new to java script and don't know how to implement this.
If you have any better logic and solution for this please tell me.</p>
<p>thanks in advance.</p> | 0 | 1,129 |
React rendering variable with html characters escaped | <p>I am learning React and have run into the following situation:</p>
<p>I have a string variable that I am passing as a prop to different components to be rendered by JSX.</p>
<p>When the component and its sub-components are rendered, the string does not render html special characters, instead rendering the character code as text.</p>
<p>How can I get the variable to render as html?</p>
<p>Here is the code for a component that works completely, except that the <code>tempUnitString</code> variable renders as <code>&deg; K</code>, while the <code><th></code> below renders its units as ° K.</p>
<pre><code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import Chart from '../components/chart';
import GoogleMap from '../components/google_map'
class WeatherList extends Component {
renderWeather(cityData, tempUnits){
const name = cityData.city.name;
const id = cityData.city.id;
const humidity = cityData.list.map(weather => weather.main.humidity);
const pressure = cityData.list.map(weather => weather.main.pressure);
const { lon, lat } = cityData.city.coord;
let temp = cityData.list.map(weather => weather.main.temp);
if (tempUnits === "K"){
temp = cityData.list.map(weather => weather.main.temp);
} else if (tempUnits === "F"){
temp = cityData.list.map(weather => weather.main.temp * 9/5 - 459.67);
} else {
temp = cityData.list.map(weather => weather.main.temp - 273.15);
}
let tempUnitString = "&deg; " + tempUnits;
return (
<tr key={ id }>
<td><GoogleMap lat={ lat } lon={ lon } /></td>
<td>
<Chart color="red" data={ temp } units={ tempUnitString } />
</td>
<td>
<Chart color="green" data={ pressure } units=" hPa" />
</td>
<td>
<Chart color="orange" data={ humidity } units="%" />
</td>
</tr>);
}
render() {
const tempUnits = this.props.preferences.length > 0 ? this.props.preferences[0].tempUnits : "K";
return (
<table className="table table-hover">
<thead>
<tr>
<th>City</th>
<th>Temperature (&deg; { tempUnits })</th>
<th>Pressure (hPa)</th>
<th>Humidity (%)</th>
</tr>
</thead>
<tbody>
{ this.props.weather.map( item => this.renderWeather(item,tempUnits) ) }
</tbody>
</table>
);
}
}
function mapStateToProps({ weather, preferences }){// { weather } is shorthand for passing state and { weather:state.weather } below
return { weather, preferences }; // === { weather:weather }
}
export default connect(mapStateToProps)(WeatherList);
</code></pre>
<p><strong>UPDATE</strong></p>
<p>Using the documentation passed to me by @James Ganong I set up a boolean prop on the subcomponent <code>isTemp</code> and based on that created a JSX variable.</p>
<p>The subcomponent (minus includes and func definitions) looks like this:</p>
<pre><code>export default (props) => {
let tempDeg = '';
if (props.isTemp){
tempDeg = <span>&deg;</span>;
}
return (
<div>
<Sparklines height={ 120 } width={ 100 } data={ props.data }>
<SparklinesLine color={ props.color } />
<SparklinesReferenceLine type="avg" />
</Sparklines>
<div>{ average(props.data)} { tempDeg }{ props.units }</div>
</div>
);
}
</code></pre>
<p>The call to it looks like this:</p>
<p><code><Chart color="red" data={ temp } units={ tempUnits } isTemp={ true } /></code></p> | 0 | 1,618 |
Javascript: How to update a progress bar in a 'for' loop | <p>I am have an issue with a JS script I am trying to put together. I have an HTML table with somewhere in the neighborhood of 300 rows in it. I have made a sort function that will make the table headers clickable and launch my sort function. I would like to integrate a progress bar because in larger tables (500 - 1000 rows) after a header is clicked the table takes a bit of time to sort (IE is a big offender). The progress bar would tell them how much time remains before the sort is complete. The method I had in mind was a div element that I would resize based on the progression of the sort loop. The problem is that I can't seem to figure out how to integrate such a routine into my loop. </p>
<p>I've researched the issue and taken note of this: <a href="https://stackoverflow.com/questions/14774245/how-to-change-progress-bar-in-loop">How to change progress bar in loop?</a>
and this: <a href="https://stackoverflow.com/questions/7690465/using-settimeout-to-update-progress-bar-when-looping-over-multiple-variables">Using setTimeout to update progress bar when looping over multiple variables</a></p>
<p>The second topic has a few demos that do essentially what I would like to do as far as the progress bar goes. However, anytime I try to implement the solutions shown in those two posts I either:</p>
<p>A - Crash the browser</p>
<p>B - Progress bar appears to work, but goes from 0 - 100% instantly, not progressively.</p>
<p>I am hoping someone can lead me in the right direction on what to do. This table sort progress indicator must be done using native JS because the contents must be available offline, hence I can't include any jQuery libraries via CDN and bloating the document with the entire jQuery library isn't desired.</p>
<p>I've created a JS fiddle with my code in it. I've stripped out what I had for progress bar code because I kept crashing the browser so all that is there as far as scripts go is the sorting-related code. <a href="http://jsfiddle.net/jnBmp/3/" rel="noreferrer">jsfiddle</a></p>
<p>Here is the JS itself:
<code></p>
<pre><code>//Change this variable to match the "id" attribute of the
//table that is going to be operated on.
var tableID = "sortable";
/**
* Attach click events to all the <th> elements in a table to
* call the tableSort() function. This function assumes that cells
* in the first row in a table are <th> headers tags and that cells
* in the remaining rows are <td> data tags.
*
* @param table The table element to work with.
* @return void
*/
function initHeaders(table) {
//Get the table element
table = document.getElementById(table);
//Get the number of cells in the header row
var l = table.rows[0].cells.length;
//Loop through the header cells and attach the events
for(var i = 0; i < l; i++) {
if(table.rows[0].cells[i].addEventListener) { //For modern browsers
table.rows[0].cells[i].addEventListener("click", tableSort, false);
} else if(table.rows[0].cells[i].attachEvent) { //IE specific method
table.rows[0].cells[i].attachEvent("onclick", tableSort);
}
}
}
/**
* Compares values in a column of a table and then sorts the table rows.
* Subsequent calls to this function will toggle a row between ascending
* and descending sort directions.
*
* @param e The click event passed in from the browser.
* @return mixed No return value if operation completes successfully, FALSE on error.
*/
function tableSort(e) {
/**
* Checks to see if a value is numeric.
*
* @param n The incoming value to check.
* @return bool TRUE if value is numeric, FALSE otherwise.
*/
tableSort.isNumeric = function (n) {
var num = false;
if(!isNaN(n) && isFinite(n)) {
num = true;
}
return num;
}
//Get the element from the click event that was passed.
if(e.currentTarget) { //For modern browsers
e = e.currentTarget;
} else if(window.event.srcElement) { //IE specific method
e = window.event.srcElement;
} else {
console.log("Unable to determine source event. Terminating....");
return false;
}
//Get the index of the cell, will be needed later
var ndx = e.cellIndex;
//Toggle between "asc" and "desc" depending on element's id attribute
if(e.id == "asc") {
e.id = "desc";
} else {
e.id = "asc";
}
//Move up from the <th> that was clicked and find the parent table element.
var parent = e.parentElement;
var s = parent.tagName;
while(s.toLowerCase() != "table") {
parent = parent.parentElement;
s = parent.tagName;
}
/*
Executes two different loops. A "for" loop to control how many
times the table rows are passed looking for values to sort and a
"while" loop that does the actual comparing of values. The "for"
loop also controls how many times the embedded "while" loop will
run since each iteration with force at least one table row into
the correct position.
*/
//var interval = setInterval( function () { progress.updateProgress() } , 100);
var rows = parent.tBodies[0].rows.length; //Isolate and count rows only in the <tbody> element.
if(rows > 1) { //Make sure there are enough rows to bother with sorting
var v1; //Value 1 placeholder
var v2; //Value 2 placeholder
var tbody = parent.tBodies[0]; //Table body to manipulate
//Start the for loop (controls amount of table passes)
for(i = 0; i < rows; i++) {
var j = 0; //Counter for swapping routine
var offset = rows - i - 1; //Stops next loop from overchecking
// WANT TO UPDATE PROGRESS BAR HERE
//Start the while loop (controls number of comparisons to make)
while(j < offset) {
//Check to make sure values can be extracted before proceeding
if(typeof tbody.rows[j].cells[ndx].innerHTML !== undefined && typeof tbody.rows[j + 1].cells[ndx].innerHTML !== undefined) {
//Get cell values and compare
v1 = tbody.rows[j].cells[ndx].innerHTML;
v2 = tbody.rows[j + 1].cells[ndx].innerHTML;
if(tableSort.isNumeric(v1) && tableSort.isNumeric(v2)) {
//Dealing with two numbers
v1 = new Number(v1);
v2 = new Number(v2);
if(v1 > v2) {
if(e.id == "asc") { //v1 moves down
tbody.insertBefore(tbody.rows[j + 1], tbody.rows[j]);
}
} else {
if(e.id == "desc") { //v1 moves down
tbody.insertBefore(tbody.rows[j + 1], tbody.rows[j]);
}
}
} else if(tableSort.isNumeric(v1) && !tableSort.isNumeric(v2)) {
//v2 is a string, v1 is a number and automatically wins
if(e.id == "asc") { //v1 moves down
tbody.insertBefore(tbody.rows[j + 1], tbody.rows[j]);
}
} else if(!tableSort.isNumeric(v1) && tableSort.isNumeric(v2)) {
//v1 is a string, v2 is a number and automatically wins
if(e.id == "desc") { //v1 moves down
tbody.insertBefore(tbody.rows[j + 1], tbody.rows[j]);
}
} else {
//Both v1 and v2 are strings, use localeCompare()
if(v1.localeCompare(v2) > 0) {
if(e.id == "asc") { //v1 moves down
tbody.insertBefore(tbody.rows[j + 1], tbody.rows[j]);
}
} else {
if(e.id == "desc") { //v1 moves down
tbody.insertBefore(tbody.rows[j + 1], tbody.rows[j]);
}
}
}
j++;
} else {
console.log("One of the values turned up undefined");
}
}
}
}
}
//Wait until DOM is ready and then initialize the table headers.
window.onload = function () {
initHeaders(tableID);
}
</code></pre>
<p></code></p>
<p>Thanks in advance to anyone who can point me in the right direction.</p>
<p><strong>-----
EDIT:
-----</strong> Okay so after reading the answers here and making some hefty modifications to how I was going about things I have come up with a much better solution. The progress bar isn't exactly what I wanted, but it is close. (Although I believe that it is showing up on the page just as the sorting is getting ready to finish up.)</p>
<p>I modified my loop to do a O(n log n) quick sort and instead of modifying the DOM directly I instead isolate the table rows to sort and copy them into an array. I then do the sort directly on the array and once it is finished I rebuild the rows and then remove the old rows and append the new ones in. The sort time has been reduced significantly.</p>
<p>Have a look: <a href="http://jsfiddle.net/jnBmp/5/" rel="noreferrer">http://jsfiddle.net/jnBmp/5/</a></p>
<p>And here is the new JS code:</p>
<pre><code>//Change this variable to match the "id" attribute of the
//table that is going to be operated on.
var tableID = "sortable";
/**
* Attach click events to all the <th> elements in a table to
* call the tableSort() function. This function assumes that cells
* in the first row in a table are <th> headers tags and that cells
* in the remaining rows are <td> data tags.
*
* @param table The table element to work with.
* @return void
*/
function initHeaders(table) {
//Get the table element
table = document.getElementById(table);
//Get the number of cells in the header row
var l = table.rows[0].cells.length;
//Loop through the header cells and attach the events
for(var i = 0; i < l; i++) {
if(table.rows[0].cells[i].addEventListener) { //For modern browsers
table.rows[0].cells[i].addEventListener("click", tableSort, false);
} else if(table.rows[0].cells[i].attachEvent) { //IE specific method
table.rows[0].cells[i].attachEvent("onclick", tableSort);
}
}
}
function tableSort(e) {
var runs = 0;
var pix = 0;
var ndx = 0;
var dir = "right";
var interval = false;
//Get the element from the click event that was passed.
if(e.currentTarget) { //For modern browsers
e = e.currentTarget;
} else if(window.event.srcElement) { //IE specific method
e = window.event.srcElement;
} else {
console.log("Unable to determine source event. Terminating....");
return false;
}
//Get the index of the cell, will be needed later
ndx = e.cellIndex;
//Toggle between "asc" and "desc" depending on element's id attribute
if(e.id == "asc") {
e.id = "desc";
} else {
e.id = "asc";
}
//Move up from the <th> that was clicked and find the parent table element.
var parent = e.parentElement;
var s = parent.tagName;
while(s.toLowerCase() != "table") {
parent = parent.parentElement;
s = parent.tagName;
}
//Get the rows to operate on as an array
var rows = document.getElementById("replace").rows;
var a = new Array();
for(i = 0; i < rows.length; i++) {
a.push(rows[i]);
}
//Show progress bar ticker
document.getElementById("progress").style.display = "block";
/**
* Show the progress bar ticker animation
*
* @param pix The current pixel count to set the <div> margin at.
*/
function updateTicker(pix) {
var tick = document.getElementById("progressTicker");
document.getElementById("progressText").style.display = "block";
document.getElementById("progressText").innerHTML = "Sorting table...please wait";
if(dir == "right") {
if(pix < 170) {
pix += 5;
tick.style.marginLeft = pix + "px";
} else {
dir = "left";
}
} else {
if(pix > 0) {
pix -= 5;
tick.style.marginLeft = pix + "px";
} else {
dir = "left";
}
}
interval = window.setTimeout( function () { updateTicker(pix); }, 25);
}
updateTicker(pix);
/**
* Checks to see if a value is numeric.
*
* @param n The incoming value to check.
* @return bool TRUE if value is numeric, FALSE otherwise.
*/
isNumeric = function (n) {
var num = false;
if(!isNaN(n) && isFinite(n)) {
num = true;
}
return num;
}
/**
* Compares two values and determines which one is "bigger".
*
* @param x A reference value to check against.
* @param y The value to be determined bigger or smaller than the reference.
* @return TRUE if y is greater or equal to x, FALSE otherwise
*/
function compare(x, y) {
var bigger = false;
x = x.cells[ndx].textContent;
y = y.cells[ndx].textContent;
//console.log(e.id);
if(isNumeric(x) && isNumeric(y)) {
if(y >= x) {
bigger = (e.id == "asc") ? true : false;
} else {
bigger = (e.id == "desc") ? true : false;
}
} else {
if(y.localeCompare(x) >= 0) {
bigger = (e.id == "asc") ? true : false;
} else {
bigger = (e.id == "desc") ? true : false;
}
}
return bigger;
}
/**
* Performs a quicksort O(n log n) on an array.
*
* @param array The array that needs sorting
* @return array The sorted array.
*/
function nlognSort(array) {
runs++
if(array.length > 1) {
var big = new Array();
var small = new Array();
var pivot = array.pop();
var l = array.length;
for(i = 0; i < l; i++) {
if(compare(pivot,array[i])) {
big.push(array[i]);
} else {
small.push(array[i]);
}
}
return Array.prototype.concat(nlognSort(small), pivot, nlognSort(big));
} else {
return array;
}
}
//Run sort routine
b = nlognSort(a);
//Rebuild <tbody> and replace new with the old
var tbody = document.createElement("tbody");
var l = b.length;
for(i = 0; i < l; i++) {
tbody.appendChild(b.shift());
}
parent.removeChild(document.getElementById("replace"));
parent.appendChild(tbody);
tbody.setAttribute("id","replace");
setTimeout(function () {
document.getElementById("progress").style.display = "none";
document.getElementById("progressText").style.display = "none";
clearTimeout(interval);
},1500);
}
window.onload = function() {
initHeaders(tableID);
}
</code></pre>
<p>Thanks again everyone!!</p> | 0 | 6,790 |
Getting 'Consent Required' error despite successful permission grant using Oauth URL | <p>I am using the example from <a href="https://github.com/docusign/docusign-python-client" rel="nofollow noreferrer">https://github.com/docusign/docusign-python-client</a> (docusign python SDK). Despite granting access by logging in using the URL given by oauth_login_url below, the subsequent "api_client.configure_jwt_authorization_flow" call always results in 'consent_required' error. The corresponding integrator key is set up with right redirect URI and key pair (of which I use the private key as private_key_filename below). Note that the account is not associated to any Organization yet. I am not yet there. But I would expect this basic flow to work as is. Any idea what could be causing this error?</p>
<pre><code>oauth_login_url = api_client.get_jwt_uri(integrator_key, redirect_uri, oauth_base_url)
print(oauth_login_url)
https://account-d.docusign.com/oauth/auth?response_type=code&client_id=<integrator_key>&scope=signature%2Bimpersonation&redirect_uri=https%3A%2F%2Fwww.docusign.com%2Fapi
integrator_key = "<My INTEGRATOR_KEY1 from Docusign>"
redirect_uri = "https://www.docusign.com/api" <== same as in the Integrator Key
oauth_base_url = "account-d.docusign.com"
private_key_filename = "/Users/myname/Desktop/private.key"
user_id = "46933ecb-9aec-4fe3-8efe-7d5777ac9b54" <== Silly me, anonymized:) but to indicate I am not using email
api_client.configure_jwt_authorization_flow(private_key_filename, oauth_base_url, integrator_key, user_id, 3600)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/userme/projects/docudocu/lib/python2.7/site-packages/docusign_esign/api_client.py", line 118, in configure_jwt_authorization_flow
post_params=self.sanitize_for_serialization({"assertion": assertion, "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer"}))
File "/Users/userme/projects/docudocu/lib/python2.7/site-packages/docusign_esign/api_client.py", line 418, in request body=body)
File "/Users/userme/projects/docudocu/lib/python2.7/site-packages/docusign_esign/rest.py", line 244, in POST body=body)
File "/Users/userme/projects/docudocu/lib/python2.7/site-packages/docusign_esign/rest.py", line 200, in request
raise ApiException(http_resp=r)
docusign_esign.rest.ApiException: (400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'X-DocuSign-Node': 'CH1DFE2', 'Content-Length': '28', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload', 'X-Content-Type-Options': 'nosniff', 'Content-Type': 'application/json; charset=utf-8', 'Expires': '-1', 'Content-Security-Policy-Report-Only': "script-src 'unsafe-inline' 'unsafe-eval' 'self';style-src 'unsafe-inline' 'self';img-src https://docucdn-a.akamaihd.net/ 'self';font-src 'self';connect-src 'self';object-src 'none';media-src 'none';frame-src 'none';frame-ancestors 'none';report-uri /client-errors/csp", 'X-XSS-Protection': '1; mode=block', 'X-DocuSign-TraceToken': 'b009b0a6-19ad-4e58-844e-76fc5b509cbb', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'Date': 'Wed, 29 Nov 2017 22:52:10 GMT', 'X-Frame-Options': 'SAMEORIGIN', 'X-AspNetMvc-Version': '5.2'})
HTTP response body: {"error":"consent_required"}
</code></pre> | 0 | 1,230 |
Using BottomSheetBehavior with a inner CoordinatorLayout | <p>The design support library <code>v. 23.2</code> introduced <code>BottomSheetBehavior</code>, which allows childs of a coordinator to act as bottom sheets (views draggable from the bottom of the screen).</p>
<p>What I’d like to do is to have, <strong>as a bottom sheet view</strong>, the following view (the typical coordinator + collapsing stuff):</p>
<pre><code><CoordinatorLayout
app:layout_behavior=“@string/bottom_sheet_behavior”>
<AppBarLayout>
<CollapsingToolbarLayout>
<ImageView />
</CollapsingToolbarLayout>
</AppBarLayout>
<NestedScrollView>
<LinearLayout>
< Content ... />
</LinearLayout>
</NestedScrollView>
</CoordinatorLayout>
</code></pre>
<p>Unfortunately, bottom sheet views should implement nested scrolling, or they won’t get scroll events. If you try with a main activity and then load this view as a bottom sheet, you’ll see that scroll events only act on the “sheet” of paper, with some strange behavior, as you can see if you keep reading.</p>
<p>I am pretty sure that this can be handled by subclassing <code>CoordinatorLayout</code>, or even better by subclassing <code>BottomSheetBehavior</code>. Do you have any hint?</p>
<h2>Some thoughts</h2>
<ul>
<li><p><code>requestDisallowInterceptTouchEvent()</code> should be used, to steal events from the parent in some conditions:</p>
<ul>
<li>when the <code>AppBarLayout</code> offset is > 0</li>
<li>when the <code>AppBarLayout</code> offset is == 0, but we are scrolling up (think about it for a second and you’ll see)</li>
</ul></li>
<li><p>the first condition can be obtained by setting an <code>OnOffsetChanged</code> to the inner app bar;</p></li>
<li><p>the second requires some event handling, for example:</p>
<pre><code>switch (MotionEventCompat.getActionMasked(event)) {
case MotionEvent.ACTION_DOWN:
startY = event.getY();
lastY = startY;
userIsScrollingUp = false;
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
userIsScrollingUp = false;
break;
case MotionEvent.ACTION_MOVE:
lastY = event.getY();
float yDeltaTotal = startY - lastY;
if (yDeltaTotal > touchSlop) { // Moving the finger up.
userIsScrollingUp = true;
}
break;
}
</code></pre></li>
</ul>
<h2>Issues</h2>
<p>Needless to say, I can’t make this work right now. I am not able to catch the events when the conditions are met, and not catch them in other cases. In the image below you can see what happens with a standard CoordinatorLayout:</p>
<ul>
<li><p>The sheet is dismissed if you scroll down on the appbar, but not if you scroll down on the nested content. It seems that nested scroll events are not propagated to the Coordinator behavior;</p></li>
<li><p>There is also a problem with the inner appbar: the nested scroll content does not follow the appbar when it is being collapsed..</p></li>
</ul>
<p><a href="https://i.stack.imgur.com/nZBle.gif"><img src="https://i.stack.imgur.com/nZBle.gif" alt="enter image description here"></a></p>
<p>I have setup a <a href="https://github.com/miav/BottomSheetCoordinatorLayout">sample project on github</a> that shows these issues.</p>
<h2>Just to be clear, desired behavior is:</h2>
<ul>
<li><p>Correct behavior of appbars/scroll views inside the sheet;</p></li>
<li><p>When sheet is expanded, it can collapse on scroll down, but <strong>only if the inner appbar is fully expanded too</strong>. Right now it does collapse with no regards to the appbar state, and only if you drag the appbar;</p></li>
<li><p>When sheet is collapsed, scroll up gestures will expand it (with no effect on the inner appbar).</p></li>
</ul>
<p>An example from the contacts app (which probably does not use BottomSheetBehavior, but this is what I want):</p>
<p><a href="https://i.stack.imgur.com/WWLcN.gif"><img src="https://i.stack.imgur.com/WWLcN.gif" alt="enter image description here"></a></p> | 0 | 1,424 |
CSS Multiple Animations on single element, no javascript | <p>I am trying to create an image slideshow using only CSS and no Javascript.</p>
<p>I have an ALMOST working example here: <a href="http://codepen.io/k/pen/Dkhei" rel="noreferrer">http://codepen.io/k/pen/Dkhei</a> .
The problem is that the animation for the 'Previous' functionality won't pause when I stop hovering over its element. </p>
<p>I am defining two animations on a single element, whose class name is 'imageContainer'. I am curious to know whether my syntax is wrong or if what I am trying to do is not possible. </p>
<p>HTML:</p>
<pre><code><div class='carouselContainer'>
<div class='directionSelector previous'>Previous</div>
<div class='directionSelector next'>Next</div>
<div class='imagesContainer'>
<img class='visible' src='http://ibmsmartercommerce.sourceforge.net/wp-content/uploads/2012/09/Roses_Bunch_Of_Flowers.jpeg'/>
<img class='hidden' src='http://houseoflowers.com/wp-content/uploads/2013/03/Splendid-flowers-wallpaper-wallpapers-1920x1200-mrwallpaper-com.jpg'/>
<img class='hidden test' src='http://wallzpoint.com/wp-content/gallery/flower-4/flower-flowers-31723005-1600-1200.jpg'/>
<img class='hidden' src='http://images2.layoutsparks.com/1/179204/no-idea-t5-flowers.jpg'/>
<img class='hidden' src='http://3.bp.blogspot.com/-Ca_H0XQYQI4/UQFMSauQxTI/AAAAAAAABik/WHzskd_HqqU/s1600/flowers.jpg'/>
</div>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>.carouselContainer{
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
border: 1px solid grey;
width: 450px;
height: 300px;
position: relative;
background-color: grey;
margin: auto;
overflow: hidden;
}
.directionSelector{
width: 60px;
height: 1.5em;
line-height: 1.5em;
top: 150px !important;
position: absolute;
cursor: pointer;
background-color: rgba(1,1,1,.7);
color: white;
text-align: center;
border-radius: 5px;
}
.previous{
top: 0;
left: 5px;
}
.next{
top: 0;
right: 5px;
}
img{
width: 100%;
height: 300px;
float: left;
}
.imagesContainer{
width: 100%;
background-color: yellow;
-webkit-animation-name: showImagesPrev,showImagesNext;
-webkit-animation-duration: 5s,5s;
-webkit-animation-play-state: paused,paused;
-webkit-animation-fill-mode: forwards,forwards;
-moz-animation-name: showImagesPrev,showImagesNext;
-moz-animation-duration: 5s,5s;
-moz-animation-play-state: paused,paused;
-moz-animation-fill-mode: forwards,backwards;
animation-name: showImagesPrev,showImagesNext;
animation-duration: 5s,5s;
animation-play-state: paused,paused;
animation-fill-mode: forwards,backwards;
}
.previous:hover ~ div.imagesContainer{
-webkit-animation-name: showImagesPrev;
-webkit-animation-play-state: running;
-moz-animation-name: showImagesPrev;
-moz-animation-play-state: running;
animation-name: showImagesPrev;
animation-play-state: running;
}
.next:hover ~ div.imagesContainer{
-webkit-animation-name: showImagesNext;
-webkit-animation-play-state: running;
-moz-animation-name: showImagesNext;
-moz-animation-play-state: running;
animation-name: showImagesNext;
animation-play-state: running;
}
@-webkit-keyframes showImagesPrev{
from{
margin-top: 0px;
}
to{
margin-top: -1200px;
}
}
@-moz-keyframes showImagesPrev{
from{
margin-top: 0px;
}
to{
margin-top: -1200px;
}
}
@keyframes showImagesPrev{
from{
margin-top: 0px;
}
to{
margin-top: -1200px;
}
}
@-webkit-keyframes showImagesNext{
from{
margin-top: -1200px;
}
to{
margin-top: 0px;
}
}
@-moz-keyframes showImagesNext{
from{
margin-top: -1200px;
}
to{
margin-top: 0px;
}
}
@keyframes showImagesNext{
from{
margin-top: -1200px;
}
to{
margin-top: 0px;
}
}
</code></pre>
<p>Thank you for your help :)</p> | 0 | 1,541 |
URL of a Jersey Application using ResourceConfig without web.xml | <p>I migrated from web.xml to totally Java configuration using ResourceConfig with Jersey 2.7 and deploying on Tomcat 7. After that I am not able to reach the services anymore by using the same urls that I was using with the web.xml approach. I don't understand how the ResourceConfig is affecting the paths.</p>
<p>My previous 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://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"
version="3.0">
<servlet>
<servlet-name>my.app</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.mypackage.resource,com.mypackage.providers</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.scanning.recursive</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.filter.LoggingFilter</param-value>
</init-param>
<init-param>
<param-name>org.glassfish.jersey.server.ServerProperties.BV_SEND_ERROR_IN_RESPONSE</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>my.app</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</code></pre>
<p> </p>
<p>My configuration class that extends ResourceConfig is:</p>
<p>MyRESTAPIApp.java</p>
<pre><code>@ApplicationPath("")
public class MyRESTAPIApp extends ResourceConfig{
public MyRESTAPIApp () {
packages("com.mypackage.resource", "com.mypackage.providers");
register(org.glassfish.jersey.filter.LoggingFilter.class);
property("jersey.config.beanValidation.enableOutputValidationErrorEntity.server", "true");
}
}
</code></pre>
<p>one of my resources is:</p>
<p>FlagResource.java</p>
<pre><code>@Path("my-resource")
public class FlagResource {
private MyService myService = new MyService();
@GET
@Produces(MediaType.APPLICATION_JSON)
public FlagResource getFlagResource(@NotNull @QueryParam("level") Long level) {
FlagResource flagResource = myService.getFlagResource(level);
return flagResource;
}
</code></pre>
<p>}</p>
<p>The war that I am generating is called: my.app.war.</p>
<p>Tomcat was taking the web context root path from the name of the war file as usual, but I don't know if that changes when using Java code based configuration.</p>
<pre><code>GET http://localhost:8080/my.app/my-resource?level=1
</code></pre>
<p>Returns a 404</p> | 0 | 1,313 |
Select2 with Twitter Bootstrap 3 / Dropdown wrong width | <p>I want to use select2.js in combination with twitter bootstrap 3.
Everything works fine so far, except the fact, that the Drop-Down container has not the same width as the select container itself.</p>
<p>By resizing the window this phenomen appears and disappears.</p>
<p>Here is a picture that shows the issue <img src="https://i.stack.imgur.com/xtOoT.png" alt="width issue"></p>
<p>And here is the jsfiddle where you can try the resizing. (Tested it with IE 11 and FF 26)
<a href="http://jsfiddle.net/AgwA4/" rel="noreferrer">jsfiddle</a></p>
<p>And here also the code:</p>
<pre><code><link rel="stylesheet" href="http://getbootstrap.com/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="http://cdn.jsdelivr.net/select2/3.4.5/select2.css">
<div class="container">
<div class="row">
<div class="col-xs-3">
<select style="width:100%" class="select2">
<optgroup label="Test-group">
<option>test1</option>
<option>test2</option>
</optgroup>
</select>
</div>
<div class="col-xs-3">
<select style="width:100%" class="select2">
<optgroup label="Test-group">
<option>test1</option>
<option>test2</option>
</optgroup>
</select>
</div>
<div class="col-xs-3">
<select style="width:100%" class="select2">
<optgroup label="Test-group">
<option>test1</option>
<option>test2</option>
</optgroup>
</select>
</div>
</div>
</div>
</code></pre>
<p>I tried to find a solution for hours now, but I can't find a solution for that issue.</p>
<p>Thank you and best regards</p> | 0 | 1,047 |
crystal report Unable to connect: incorrect log on parameters | <p>Hi friend I've created a crystal report with parameter,its running successfully in while executing in source code but it does not load in while i config after IIS its shows the error like unable to connect log on parameters. Please check my code and correct me.</p>
<p>hi frinds if i comment the oStream = (MemoryStream)reportdocument.ExportToStream(ExportFormatType.PortableDocFormat); this line and Response.BinaryWrite(oStream.ToArray()); this report is generate in IIS but i not get in proper pdf formate pls help me i want to generate in pdf formate pls guide me</p>
<pre><code>public partial class frm_MRPrint : System.Web.UI.Page
{
SqlConnection Con = new SqlConnection(ConfigurationManager.AppSettings["conn"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
mr();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
MemoryStream oStream;
Response.Clear();
Response.Buffer = true;
ReportDocument reportdocument = new ReportDocument();
reportdocument.Load(Server.MapPath("MR.rpt"));
reportdocument.SetDatabaseLogon("sa", "Admin123", "vivek", "PURCHASE");
reportdocument.SetParameterValue("MRNO", ddlmrno.SelectedItem.Text);
CrystalReportViewer1.ReportSource = reportdocument;
oStream = (MemoryStream)reportdocument.ExportToStream(ExportFormatType.PortableDocFormat);
Response.ContentType = "application/pdf";
try
{
//write report to the Response stream
Response.BinaryWrite(oStream.ToArray());
Response.End();
}
catch (Exception ex)
{
Label2.Visible = true;
Label2.Text = "ERROR:" + Server.HtmlEncode(ex.Message.ToString());
}
finally
{
//clear stream
oStream.Flush();
oStream.Close();
oStream.Dispose();
}
//in case you want to export it as an attachment use the line below
//crReport.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "Your Exported File Name");
}
public void mr()
{
ddlmrno.Items.Clear();
ListItem frstitem = new ListItem();
frstitem.Text = "- Select -";
ddlmrno.Items.Add(frstitem);
ddlmrno.SelectedIndex = 0;
Con.Open();
string sql = "";
sql = "select distinct(MRNO) from dbo.tbl_KKSMR where status=1 order by MRNO asc";
SqlCommand cmd = new SqlCommand(sql, Con);
SqlDataReader rdr;
try
{
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
ListItem newItem = new ListItem();
newItem.Text = rdr["MRNO"].ToString().Trim();
newItem.Value = rdr["MRNO"].ToString().Trim();
ddlmrno.Items.Add(newItem);
}
rdr.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
cmd.Dispose();
} Con.Close();
}
}
</code></pre> | 0 | 1,401 |
POST to WCF from Fiddler succeeds but passes null values | <p>I've followed <a href="http://channel9.msdn.com/shows/Endpoint/Endpoint-Screencasts-Hosting-WCF-Services-in-IIS/" rel="nofollow noreferrer">this video series on WCF</a> and have the demo working. It involves building a WCF service that manages student evaluation forms, and implements CRUD operations to operate on a list of those evaluations. I've modified my code a little according to <a href="http://msdn.microsoft.com/en-us/library/dd203052.aspx" rel="nofollow noreferrer">this guide</a> so it will return JSON results to a browser or Fiddler request. My goal is to figure out how to use the service by building my own requests in Fiddler, and then use that format to consume the service from an app on a mobile device.</p>
<p>I'm having trouble using the <code>SubmitEval</code> method (save an evaluation) from Fiddler. The call works, but all the fields of <code>Eval</code> are null (or default) except <code>Id</code>, which is set in the service itself.</p>
<p>Here is my <code>Eval</code> declaration (using properties instead of fields as per <a href="https://stackoverflow.com/questions/7058942/how-to-call-wcf-restful-service-from-fiddler-by-json-request">this question</a>):</p>
<pre><code>[DataContract]
public class Eval //Models an evaluation
{
[DataMember]
public string Id { get; set; }
[DataMember]
public string Submitter { get; set; }
[DataMember]
public string Comment { get; set; }
[DataMember]
public DateTime TimeSubmitted { get; set; }
}
</code></pre>
<p>And here is the relevant part of <code>IEvalService</code>:</p>
<pre><code>[ServiceContract]
public interface IEvalService
{
...
[OperationContract]
[WebInvoke(RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json, UriTemplate = "eval")]
void SubmitEval(Eval eval);
}
</code></pre>
<p>And <code>EvalService</code>:</p>
<pre><code>[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
class EvalService : IEvalService
{
...
public void SubmitEval(Eval eval)
{
eval.Id = Guid.NewGuid().ToString();
Console.WriteLine("Received eval");
evals.Add(eval);
}
}
</code></pre>
<p>In Fiddler's Request Builder, I set the Method to POST and the address to <code>http://localhost:49444/EvalServiceSite/Eval.svc/eval</code>. I added the header <code>Content-Type: application/json; charset=utf-8</code> to the default headers. The request body is:</p>
<pre><code>{"eval":{"Comment":"testComment222","Id":"doesntMatter",
"Submitter":"Tom","TimeSubmitted":"11/10/2011 4:00 PM"}}
</code></pre>
<p>The response I get from sending that request is <code>200</code>, but when I then look at the Evals that have been saved, the one I just added has a valid <code>Id</code>, but <code>Comment</code> and <code>Submitter</code> are both null, and <code>TimeSubmitted</code> is <code>1/1/0001 12:00:00 AM</code>.</p>
<p>It seems like WCF is getting the request, but is not deserializing the object correctly. But if that's the case, I don't know why it's not throwing some sort of exception. Does it look like I'm doing this right, or am I missing something?</p>
<p>UPDATE: Here is the endpoint declaration in App.config:</p>
<pre><code> <endpoint binding="webHttpBinding" behaviorConfiguration="webHttp"
contract="EvalServiceLibrary.IEvalService" />
</code></pre>
<p>And the endpoint behavior referred to:</p>
<pre><code><behavior name="webHttp">
<webHttp defaultOutgoingResponseFormat="Json"/>
</behavior>
</code></pre> | 0 | 1,176 |
Why does the Contains() operator degrade Entity Framework's performance so dramatically? | <p>UPDATE 3: According to <a href="http://blogs.msdn.com/b/adonet/archive/2012/12/10/ef6-alpha-2-available-on-nuget.aspx" rel="noreferrer">this announcement</a>, this has been addressed by the EF team in EF6 alpha 2.</p>
<p>UPDATE 2: I've created a suggestion to fix this problem. To vote for it, <a href="http://data.uservoice.com/forums/72025-ado-net-entity-framework-ef-feature-suggestions/suggestions/2598644-improve-the-performance-of-the-contains-operator" rel="noreferrer">go here</a>.</p>
<p>Consider a SQL database with one very simple table.</p>
<pre><code>CREATE TABLE Main (Id INT PRIMARY KEY)
</code></pre>
<p>I populate the table with 10,000 records.</p>
<pre><code>WITH Numbers AS
(
SELECT 1 AS Id
UNION ALL
SELECT Id + 1 AS Id FROM Numbers WHERE Id <= 10000
)
INSERT Main (Id)
SELECT Id FROM Numbers
OPTION (MAXRECURSION 0)
</code></pre>
<p>I build an EF model for the table and run the following query in LINQPad (I am using "C# Statements" mode so LINQPad doesn't create a dump automatically).</p>
<pre><code>var rows =
Main
.ToArray();
</code></pre>
<p>Execution time is ~0.07 seconds. Now I add the Contains operator and re-run the query.</p>
<pre><code>var ids = Main.Select(a => a.Id).ToArray();
var rows =
Main
.Where (a => ids.Contains(a.Id))
.ToArray();
</code></pre>
<p>Execution time for this case is <strong>20.14 seconds</strong> (288 times slower)!</p>
<p>At first I suspected that the T-SQL emitted for the query was taking longer to execute, so I tried cutting and pasting it from LINQPad's SQL pane into SQL Server Management Studio.</p>
<pre><code>SET NOCOUNT ON
SET STATISTICS TIME ON
SELECT
[Extent1].[Id] AS [Id]
FROM [dbo].[Primary] AS [Extent1]
WHERE [Extent1].[Id] IN (1,2,3,4,5,6,7,8,...
</code></pre>
<p>And the result was</p>
<pre><code>SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 88 ms.
</code></pre>
<p>Next I suspected LINQPad was causing the problem, but performance is the same whether I run it in LINQPad or in a console application.</p>
<p>So, it appears that the problem is somewhere within Entity Framework.</p>
<p>Am I doing something wrong here? This is a time-critical part of my code, so is there something I can do to speed up performance?</p>
<p>I am using Entity Framework 4.1 and Sql Server 2008 R2.</p>
<p>UPDATE 1:</p>
<p>In the discussion below there were some questions about whether the delay occurred while EF was building the initial query or while it was parsing the data it received back. To test this I ran the following code,</p>
<pre><code>var ids = Main.Select(a => a.Id).ToArray();
var rows =
(ObjectQuery<MainRow>)
Main
.Where (a => ids.Contains(a.Id));
var sql = rows.ToTraceString();
</code></pre>
<p>which forces EF to generate the query without executing it against the database. The result was that this code required ~20 secords to run, so it appears that almost all of the time is taken in building the initial query.</p>
<p>CompiledQuery to the rescue then? Not so fast ... CompiledQuery requires the parameters passed into the query to be fundamental types (int, string, float, and so on). It won't accept arrays or IEnumerable, so I can't use it for a list of Ids.</p> | 0 | 1,076 |
GStreamer installation is missing a plug-in | <p>I hope that someone can help with this problem, been searching for a solution for the past 2 days.</p>
<p>To describe the problem in short: I'm trying to make a simple qt5.7 application that will stream an m3u8 (using Qt Creator (community). But when I try to run it I get a </p>
<pre><code>Warning: "No decoder available for type 'application/x-hls'."
Error: "Your GStreamer installation is missing a plug-in."
</code></pre>
<p>"gst-inspect | grep hls"
returns: typefindfunctions: application/x-hls: m3u8</p>
<p>At this point I have no idea which plugin can I even miss as I have gone trough the complete GStreamer plugin list and put one after another.
As far as my search went some got the fix by installing the bad/ugly plugins. Some say that the QT5 still uses gstreamer0.10, but new linux versions use the 1.0 (lost at this point). I tried to set a flag to force the GST_VERSION=1.0, did not work, or I did something wrong (I used the qmake GST_VERSION=1.0 command). Also, I am able to play the video in vlc.
I am completely stuck, and don't know what to do anymore.</p>
<p>the app code: </p>
<pre><code>import QtQuick 2.7
import QtQuick.Window 2.2
import QtMultimedia 5.7
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Item {
width: 640
height: 480
MediaPlayer {
id: player
source: "http://playertest.longtailvideo.com/adaptive/wowzaid3/chunklist_w249832652.m3u8"
}
VideoOutput {
anchors.fill: parent
source: player
}
Component.onCompleted: {
player.play();
}
}
}
</code></pre>
<p>OS: </p>
<pre><code>DISTRIB_ID=LinuxMint
DISTRIB_RELEASE=18
DISTRIB_CODENAME=sarah
DISTRIB_DESCRIPTION="Linux Mint 18 Sarah"
NAME="Linux Mint"
VERSION="18 (Sarah)"
ID=linuxmint
ID_LIKE=ubuntu
PRETTY_NAME="Linux Mint 18"
VERSION_ID="18"
HOME_URL="http://www.linuxmint.com/"
SUPPORT_URL="http://forums.linuxmint.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/linuxmint/"
UBUNTU_CODENAME=xenial
</code></pre>
<p>list of gstreamer plugins:</p>
<pre><code>ii gir1.2-gstreamer-0.10 0.10.36-1.5ubuntu1 amd64 Description: GObject introspection data for the GStreamer library
ii gir1.2-gstreamer-1.0 1.8.2-1~ubuntu1 amd64 GObject introspection data for the GStreamer library
ii gstreamer-qapt 3.0.2-0ubuntu1.1 amd64 GStreamer plugin to install codecs using QApt
ii gstreamer-tools 0.10.36-1.5ubuntu1 amd64 Tools for use with GStreamer
ii gstreamer0.10-alsa:amd64 0.10.36-2 amd64 GStreamer plugin for ALSA
ii gstreamer0.10-doc 0.10.36-1.5ubuntu1 all GStreamer core documentation and manuals
ii gstreamer0.10-ffmpeg:amd64 0.10.13-5ubuntu1~wily amd64 FFmpeg plugin for GStreamer
ii gstreamer0.10-ffmpeg-dbg:amd64 0.10.13-5ubuntu1~wily amd64 FFmpeg plugin for GStreamer (debug symbols)
ii gstreamer0.10-gconf:amd64 0.10.31-3+nmu4ubuntu2~gcc5.1 amd64 GStreamer plugin for getting the sink/source information from GConf
ii gstreamer0.10-gnomevfs:amd64 0.10.36-2 amd64 GStreamer plugin for GnomeVFS
ii gstreamer0.10-nice:amd64 0.1.13-0ubuntu2 amd64 ICE library (GStreamer 0.10 plugin)
ii gstreamer0.10-plugins-base:amd64 0.10.36-2 amd64 GStreamer plugins from the "base" set
ii gstreamer0.10-plugins-base:i386 0.10.36-2 i386 GStreamer plugins from the "base" set
ii gstreamer0.10-plugins-base-apps 0.10.36-2 amd64 GStreamer helper programs from the "base" set
ii gstreamer0.10-plugins-base-dbg:amd64 0.10.36-2 amd64 GStreamer plugins from the "base" set
ii gstreamer0.10-plugins-base-doc 0.10.36-2 all GStreamer documentation for plugins from the "base" set
ii gstreamer0.10-plugins-good:amd64 0.10.31-3+nmu4ubuntu2~gcc5.1 amd64 GStreamer plugins from the "good" set
ii gstreamer0.10-plugins-good:i386 0.10.31-3+nmu4ubuntu2~gcc5.1 i386 GStreamer plugins from the "good" set
ii gstreamer0.10-plugins-good-dbg:amd64 0.10.31-3+nmu4ubuntu2~gcc5.1 amd64 GStreamer plugins from the "good" set
ii gstreamer0.10-plugins-good-doc 0.10.31-3+nmu4ubuntu2~gcc5.1 all GStreamer documentation for plugins from the "good" set
ii gstreamer0.10-pulseaudio:amd64 0.10.31-3+nmu4ubuntu2~gcc5.1 amd64 GStreamer plugin for PulseAudio
ii gstreamer0.10-qapt 3.0.2-0ubuntu1.1 all transitional dummy package
ii gstreamer0.10-tools 0.10.36-1.5ubuntu1 amd64 Tools for use with GStreamer
ii gstreamer0.10-x:amd64 0.10.36-2 amd64 GStreamer plugins for X11 and Pango
ii gstreamer0.10-x:i386 0.10.36-2 i386 GStreamer plugins for X11 and Pango
ii gstreamer1.0-alsa:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer plugin for ALSA
ii gstreamer1.0-clutter 2.0.18-1 amd64 Clutter PLugin for GStreamer 1.0
ii gstreamer1.0-clutter-3.0 3.0.18-1 amd64 Clutter PLugin for GStreamer 1.0
ii gstreamer1.0-crystalhd 1:0.0~git20110715.fdd2f19-11build1 amd64 Crystal HD Video Decoder (GStreamer plugin)
ii gstreamer1.0-doc 1.8.2-1~ubuntu1 all GStreamer core documentation and manuals
ii gstreamer1.0-dvswitch 0.1.1-1 amd64 GStreamer plugin source from DVswitch
ii gstreamer1.0-espeak 0.4.0-1 amd64 GStreamer plugin for eSpeak speech synthesis
ii gstreamer1.0-fluendo-mp3:amd64 0.10.32.debian-1 amd64 Fluendo mp3 decoder GStreamer 1.0 plugin
ii gstreamer1.0-hybris:i386 1.8.2-1ubuntu0.1 i386 GStreamer plugins from hybris
ii gstreamer1.0-libav:amd64 1.8.2-1~ubuntu1 amd64 libav plugin for GStreamer
ii gstreamer1.0-libav-dbg:amd64 1.8.2-1~ubuntu1 amd64 libav plugin for GStreamer (debug symbols)
ii gstreamer1.0-nice:amd64 0.1.13-0ubuntu2 amd64 ICE library (GStreamer plugin)
ii gstreamer1.0-packagekit 0.8.17-4ubuntu6~gcc5.4ubuntu1.1 amd64 GStreamer plugin to install codecs using PackageKit
ii gstreamer1.0-plugins-bad:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer plugins from the "bad" set
ii gstreamer1.0-plugins-bad-dbg:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer plugins from the "bad" set (debug symbols)
ii gstreamer1.0-plugins-bad-doc 1.8.2-1ubuntu0.1 all GStreamer documentation for plugins from the "bad" set
ii gstreamer1.0-plugins-bad-faad:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer faad plugin from the "bad" set
ii gstreamer1.0-plugins-bad-videoparsers:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer videoparsers plugin from the "bad" set
ii gstreamer1.0-plugins-base:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer plugins from the "base" set
ii gstreamer1.0-plugins-base-apps 1.8.2-1ubuntu0.1 amd64 GStreamer helper programs from the "base" set
ii gstreamer1.0-plugins-base-dbg:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer plugins from the "base" set
ii gstreamer1.0-plugins-base-doc 1.8.2-1ubuntu0.1 all GStreamer documentation for plugins from the "base" set
ii gstreamer1.0-plugins-good:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer plugins from the "good" set
ii gstreamer1.0-plugins-good-dbg:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer plugins from the "good" set
ii gstreamer1.0-plugins-good-doc 1.8.2-1ubuntu0.1 all GStreamer documentation for plugins from the "good" set
ii gstreamer1.0-plugins-ugly:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer plugins from the "ugly" set
ii gstreamer1.0-plugins-ugly-amr:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer plugins from the "ugly" set
ii gstreamer1.0-plugins-ugly-dbg:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer plugins from the "ugly" set (debug symbols)
ii gstreamer1.0-plugins-ugly-doc 1.8.2-1ubuntu0.1 all GStreamer documentation for plugins from the "ugly" set
ii gstreamer1.0-pocketsphinx:amd64 0.8.0+real5prealpha-1ubuntu2 amd64 Speech recognition tool - gstreamer plugin
ii gstreamer1.0-pulseaudio:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer plugin for PulseAudio
ii gstreamer1.0-tools 1.8.2-1~ubuntu1 amd64 Tools for use with GStreamer
ii gstreamer1.0-vaapi:amd64 1.8.2-1~ubuntu2 amd64 VA-API plugins for GStreamer
ii gstreamer1.0-vaapi-doc 1.8.2-1~ubuntu2 all GStreamer VA-API documentation and manuals
ii gstreamer1.0-x:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer plugins for X11 and Pango
ii libcanberra-gstreamer:amd64 0.30-2.1ubuntu1 amd64 GStreamer backend for libcanberra
ii libgstreamer-ocaml 0.2.0-2build2 amd64 OCaml interface to the gstreamer library -- runtime files
ii libgstreamer-ocaml-dev 0.2.0-2build2 amd64 OCaml interface to the gstreamer library -- development files
ii libgstreamer-plugins-bad1.0-0:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer development files for libraries from the "bad" set
ii libgstreamer-plugins-bad1.0-0:i386 1.8.2-1ubuntu0.1 i386 GStreamer development files for libraries from the "bad" set
ii libgstreamer-plugins-bad1.0-dev 1.8.2-1ubuntu0.1 amd64 GStreamer development files for libraries from the "bad" set
ii libgstreamer-plugins-base0.10-0:amd64 0.10.36-2 amd64 GStreamer libraries from the "base" set
ii libgstreamer-plugins-base0.10-0:i386 0.10.36-2 i386 GStreamer libraries from the "base" set
ii libgstreamer-plugins-base0.10-dev 0.10.36-2 amd64 GStreamer development files for libraries from the "base" set
ii libgstreamer-plugins-base1.0-0:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer libraries from the "base" set
ii libgstreamer-plugins-base1.0-0:i386 1.8.2-1ubuntu0.1 i386 GStreamer libraries from the "base" set
ii libgstreamer-plugins-base1.0-dev 1.8.2-1ubuntu0.1 amd64 GStreamer development files for libraries from the "base" set
ii libgstreamer-plugins-good1.0-0:amd64 1.8.2-1ubuntu0.1 amd64 GStreamer development files for libraries from the "good" set
ii libgstreamer-plugins-good1.0-dev 1.8.2-1ubuntu0.1 amd64 GStreamer development files for libraries from the "good" set
ii libgstreamer0.10-0:amd64 0.10.36-1.5ubuntu1 amd64 Core GStreamer libraries and elements
ii libgstreamer0.10-0:i386 0.10.36-1.5ubuntu1 i386 Core GStreamer libraries and elements
ii libgstreamer0.10-0-dbg:amd64 0.10.36-1.5ubuntu1 amd64 Core GStreamer libraries and elements
ii libgstreamer0.10-dev 0.10.36-1.5ubuntu1 amd64 GStreamer core development files
ii libgstreamer1.0-0:amd64 1.8.2-1~ubuntu1 amd64 Core GStreamer libraries and elements
ii libgstreamer1.0-0:i386 1.8.2-1~ubuntu1 i386 Core GStreamer libraries and elements
ii libgstreamer1.0-0-dbg:amd64 1.8.2-1~ubuntu1 amd64 Core GStreamer libraries and elements
ii libgstreamer1.0-dev 1.8.2-1~ubuntu1 amd64 GStreamer core development files
ii libgstreamermm-1.0-0v5:amd64 1.4.3+dfsg-5 amd64 C++ wrapper library for GStreamer (shared libraries)
ii libgstreamermm-1.0-dev:amd64 1.4.3+dfsg-5 amd64 C++ wrapper library for GStreamer (development files)
ii libqt5gstreamer-1.0-0:amd64 1.2.0-3 amd64 C++ bindings library for GStreamer with a Qt-style API - Qt 5 build
ii libqt5gstreamer-dev 1.2.0-3 amd64 Development headers for QtGStreamer - Qt 5 build
ii libqt5gstreamerquick-1.0-0:amd64 1.2.0-3 amd64 QtGStreamerQuick library - Qt 5 build
ii libqt5gstreamerui-1.0-0:amd64 1.2.0-3 amd64 QtGStreamerUi library - Qt 5 build
ii libqt5gstreamerutils-1.0-0:amd64 1.2.0-3 amd64 QtGStreamerUtils library - Qt 5 build
ii libqtgstreamer-1.0-0:amd64 1.2.0-3 amd64 C++ bindings library for GStreamer with a Qt-style API
ii libqtgstreamer-dev 1.2.0-3 amd64 Development headers for QtGStreamer
ii libqtgstreamerui-1.0-0:amd64 1.2.0-3 amd64 QtGStreamerUi library
ii libqtgstreamerutils-1.0-0:amd64 1.2.0-3 amd64 QtGStreamerUtils library
ii libreoffice-avmedia-backend-gstreamer 1:5.1.4-0ubuntu1 amd64 GStreamer backend for LibreOffice
ii liquidsoap-plugin-gstreamer 1.1.1-7.1 amd64 audio streaming language -- GStreamer plugin
ii phonon-backend-gstreamer:amd64 4:4.8.2-0ubuntu2 amd64 Phonon GStreamer 1.0 backend
ii phonon-backend-gstreamer-common:amd64 4:4.8.2-0ubuntu2 amd64 Phonon GStreamer 1.0.x backend icons
ii phonon4qt5-backend-gstreamer:amd64 4:4.8.2-0ubuntu2 amd64 Phonon Qt5 GStreamer 1.0 backend
ii qml-module-qtgstreamer:amd64 1.2.0-3 amd64 QML plugins from QtGStreamer - Qt 5 build
ii qt5gstreamer-dbg:amd64 1.2.0-3 amd64 Debug symbols for QtGStreamer - Qt 5 build
ii qtgstreamer-dbg:amd64 1.2.0-3 amd64 Debug symbols for QtGStreamer
ii qtgstreamer-declarative:amd64 1.2.0-3 amd64 QML plugins from QtGStreamer
ii qtgstreamer-plugins:amd64 1.2.0-3 amd64 GStreamer plugins from QtGStreamer
ii qtgstreamer-plugins-qt5:amd64 1.2.0-3 amd64 GStreamer plugins from QtGStreamer - Qt 5 build
</code></pre> | 0 | 9,978 |
Android: Resizing Bitmaps without losing quality | <p>i've really searched through over the entire web before posting. My problem is that i cannot resize bitmap without losing the quality of the image (the quality is really bad and pixelated).</p>
<p>I take the bitmap from camera and then i have to downscale it, so i can upload it to the server much faster.</p>
<p>This is the function that does the sampling</p>
<pre><code>public Bitmap resizeBitmap(Bitmap bitmap){
Canvas canvas = new Canvas();
Bitmap resizedBitmap = null;
if (bitmap !=null) {
int h = bitmap.getHeight();
int w = bitmap.getWidth();
int newWidth=0;
int newHeight=0;
if(h>w){
newWidth = 600;
newHeight = 800;
}
if(w>h){
newWidth = 800;
newHeight = 600;
}
float scaleWidth = ((float) newWidth) / w;
float scaleHeight = ((float) newHeight) / h;
Matrix matrix = new Matrix();
// resize the bit map
matrix.preScale(scaleWidth, scaleHeight);
resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawBitmap(resizedBitmap, matrix, paint);
}
return resizedBitmap;
</code></pre>
<p>and this is how i get the image from activity result</p>
<pre><code> protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if(resultCode != RESULT_CANCELED){
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
getContentResolver().notifyChange(mImageUri, null);
ContentResolver cr = this.getContentResolver();
try
{
b = android.provider.MediaStore.Images.Media.getBitmap(cr, mImageUri);
Log.d("foto", Integer.toString(b.getWidth()));
Log.d("foto", Integer.toString(b.getHeight()));
addPhoto.setImageBitmap(b);
}
catch (Exception e)
{
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
Log.d("TAG", "Failed to load", e);
}
}
}
</code></pre>
<p>I'm starting to think that the best way to get a small picture size is to set the camera resolution. Anyone else can help?</p> | 0 | 1,429 |
Using RecyclerView with Fragments | <p>I built the RecycleView widget with CardView from this tutorial: </p>
<p><a href="http://www.treyrobinson.net/blog/android-l-tutorials-part-3-recyclerview-and-cardview/" rel="noreferrer">Android L Tutorials (Part 3) - RecyclerView and CardView</a></p>
<p>Now Im trying to show it as a Fragment.</p>
<p>Here is my FragmentActivity:</p>
<pre><code>public class FragmentActivity extends Fragment {
private RecyclerView mRecyclerView;
private CountryAdapter mAdapter;
private LinearLayoutManager layoutManager;
public FragmentActivity(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.card_layout, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.list);
layoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter = new CountryAdapter(CountryManager.getInstance().getCountries(), R.layout.card_layout, getActivity());
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
</code></pre>
<p>MainActivity where I call my fragment:
public class MainActivity extends Activity {</p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentActivity fragment = new FragmentActivity();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.container_list, fragment).commit();
}
</code></pre>
<p>Here is my activity_main layout:</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"
tools:context=".CountryActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CountryActivity"
/>
</RelativeLayout>
</code></pre>
<p>My card_layout</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_margin="5dp"
card_view:cardCornerRadius="5dp"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/countryImage"
android:layout_width="match_parent"
android:layout_height="100dp"
android:scaleType="centerCrop"
android:tint="@color/photo_tint"
android:layout_centerInParent="true"
/>
<TextView
android:id="@+id/countryName"
android:gravity="center"
android:background="?android:selectableItemBackground"
android:focusable="true"
android:clickable="true"
android:layout_width="match_parent"
android:layout_height="100dp"
android:textSize="24sp"
android:layout_centerInParent="true"
android:textColor="@android:color/white"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</code></pre>
<p>and frame_layout :</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/container_list">
</FrameLayout>
</code></pre>
<p>The app crashes when it calls the fragment.
Your help will be appreciated guys.</p> | 0 | 1,736 |
Setting disable-output-escaping="yes" for every xsl:text tag in the xml | <p>say I have the following xml:</p>
<pre><code><?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/*">
<display>
<xsl:for-each select="logline_t">
<xsl:text disable-output-escaping="yes">&lt;</xsl:text> <xsl:value-of select="./line_1" <xsl:text disable-output-escaping="yes">&gt;</xsl:text>
<xsl:text disable-output-escaping="yes">&lt;</xsl:text> <xsl:value-of select="./line_2" <xsl:text disable-output-escaping="yes">&gt;</xsl:text>
<xsl:text disable-output-escaping="yes">&lt;</xsl:text> <xsl:value-of select="./line_3" <xsl:text disable-output-escaping="yes">&gt;</xsl:text>
</xsl:for-each>
</display>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>Is there a way to set disable-output-escaping="yes" to all of the xsl:text that appear in the document?</p>
<p>I know there is an option to put
< xsl:output method="text"/ >
and every time something like
& lt;
appears, a < will appear, but the thing is that sometimes in the values of line_1, line_2 or line_3, there is a "$lt;" that I don't want changed (this is, I only need whatever is between to be changed)</p>
<p>This is what I'm trying to accomplish. I have this xml:</p>
<pre><code><readlog_l>
<logline_t>
<hora>16:01:09</hora>
<texto>Call-ID: 663903&lt;hola&gt;396@127.0.0.1</texto>
</logline_t>
</readlog_l>
</code></pre>
<p>And this translation:</p>
<pre><code><?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/*">
<display>
&lt;screen name="<xsl:value-of select="name(.)"/>"&gt;
<xsl:for-each select="logline_t">
&lt; field name="<xsl:for-each select="*"><xsl:value-of select="."/></xsl:for-each>" value="" type="label"/&gt;
</xsl:for-each>
&lt;/screen&gt;
</display>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>I want this to be the output:</p>
<pre><code><?xml version="1.0"?>
<display>
<screen name="readlog_l">
<field name="16:01:09 Call-ID: 663903&lt;hola&gt;396@127.0.0.1 " value="" type="label">
</screen>
</display>
</code></pre>
<p>Note that I need the "<" inside the field name not to be escaped, this is why I can't use output method text.</p>
<p>Also, note that this is an example and the translations are much bigger, so this is why I'm trying to find out how not to write disable-output-escaping for every '<' or '>' I need.</p>
<p>Thanks!</p> | 0 | 1,321 |
Sencha Touch - Redirect to another view | <p>I am building a Sencha Touch application and struggling with redirecting or changing another view after login. After login i need to take it to Home Page. But my below <strong><em>code in Login Controller's authenticateUser()not working</em></strong>.</p>
<p>Tried with Ext.Viewport.push(homePanel) , Ext.Viewport.setActiveItem(homePanel) also. But nothing works.</p>
<p><strong>LoginView</strong></p>
<pre><code>Ext.define("Mobile.view.LoginView", {
extend: "Ext.form.FormPanel",
alias: "widget.mylogin",
id: 'loginFormPanel',
config: {
name: 'loginform',
frame: true,
url: 'login/Authenticate',
title: 'Login',
items: [
{
xtype: 'fieldset',
itemId: 'LoginFieldset',
margin: '10 auto 0 auto ',
title: '',
items: [
{
//User Name field def
},
{
//Pwd Field Def
}
]
},
{
xtype: 'button',
id: 'loginButton',
text: 'Login',
action: 'login'
}
]
}
});
</code></pre>
<p><strong>Login Controller</strong></p>
<pre><code>Ext.define("Mobile.controller.LoginController", {
extend: "Ext.app.Controller",
views: ['LoginView', 'HomeView'],
models: ['UserModel'],
config: {
refs: {
loginForm: "#loginFormPanel"
},
control: {
'button[action=login]': {
tap: "authenticateUser"
}
}
},
authenticateUser: function (button) {
loginForm.submit({
method: 'POST',
success: function (form, result) {
//THIS IS NOT WORKING
Ext.Viewport.add(Ext.create('Mobile.view.HomeView'));
},
failure: function (form, result) {
console.log('Error');
Ext.Msg.alert('Check the logic for login and redirect');
}
});
}
});
</code></pre>
<p><strong>Home View</strong></p>
<pre><code>Ext.define('Mobile.view.HomeView', {
extend: 'Ext.Container',
id: 'homescreen',
alias: "widget.homepanel",
config: {
layout: {
type: 'card',
animation: {
type: 'flip'
}
},
items: [
{
xtype: 'toolbar',
docked: 'bottom',
id: 'Toolbar',
title: 'My App',
items: [
{
id: 'settingsBtn',
xtype: 'button',
iconCls: 'settings',
ui: 'plain',
iconMask: true
}
]
},
{
xclass: 'Mobile.view.ActionListView'
}
]
},
});
</code></pre>
<p><strong>App.JS</strong></p>
<pre><code>Ext.application({
name: "Mobile",
controllers: ["LoginController", "HomeController"],
views: ['LoginView', 'HomeView', 'ActionListView'],
models: ['UserModel', 'OrganizationModel', 'ActionModel'],
stores: ['OrganizationStore', 'ActionStore'],
launch: function () {
var loginPanel = Ext.create('Ext.Panel', {
layout: 'fit',
items: [
{
xtype: 'mylogin'
}
]
});
Ext.Viewport.add(loginPanel);
}
});
</code></pre>
<p>Any one have any idea?
Already referred <a href="https://stackoverflow.com/questions/10944351/load-another-view-after-login-with-sencha-touch-2-0">Load another view after login with sencha touch 2.0</a> . But there is no answer . Please help</p> | 0 | 1,778 |
Attribute 'textAdjust' is not allowed to appear in element 'textField' JasperReports 6.11.0 | <p>I have a textfield in my rreport which I am using with my SpringBoot Maven application. The textfield is populated and the content is variable in size and I want a dynamic size textBox. I am using JasperSoft designer to build the report and the JasperReports version is 6.11.0. </p>
<p>Following is the code segment for the textBox</p>
<pre><code><textField textAdjust="StretchHeight">
<reportElement x="160" y="92" width="330" height="18" uuid="3d60c5f2-9fca-4c15-af62-0753befg4ad6"/>
<textElement markup="rtf"/>
<textFieldExpression><![CDATA[$F{instructions}]]></textFieldExpression>
</textField>
</code></pre>
<p>Following is the pom.xml </p>
<pre><code><dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.11.0</version>
</dependency>
</code></pre>
<p>and the error </p>
<pre><code>2020-01-03 14:16:20.403 INFO 11516 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat-1].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-01-03 14:16:20.403 INFO 11516 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-01-03 14:16:20.408 INFO 11516 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 5 ms
2020-01-03 14:16:20.450 ERROR 11516 --- [nio-8080-exec-1] org.apache.commons.digester.Digester : Parse Error at line 262 column 42: cvc-complex-type.3.2.2: Attribute 'textAdjust' is not allowed to appear in element 'textField'.
org.xml.sax.SAXParseException: cvc-complex-type.3.2.2: Attribute 'textAdjust' is not allowed to appear in element 'textField'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203) ~[na:1.8.0_211]
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134) ~[na:1.8.0_211]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:284) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(XMLSchemaValidator.java:453) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(XMLSchemaValidator.java:3231) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.processAttributes(XMLSchemaValidator.java:2708) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:2051) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:741) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:374) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2784) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:842) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:771) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213) [na:1.8.0_211]
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:643) [na:1.8.0_211]
at org.apache.commons.digester.Digester.parse(Digester.java:1892) [commons-digester-2.1.jar:2.1]
at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:298) [jasperreports-6.4.0.jar:6.4.0]
at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:285) [jasperreports-6.4.0.jar:6.4.0]
at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:274) [jasperreports-6.4.0.jar:6.4.0]
at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:248) [jasperreports-6.4.0.jar:6.4.0]
</code></pre>
<p><a href="https://i.stack.imgur.com/UlDpm.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/UlDpm.jpg" alt=""></a></p>
<p>The maven dependencies does contain the jasperreports-6.11.0.jar.</p>
<p>Please suggest what could be wrong here.</p> | 0 | 2,312 |
matDialog doesn't open as dialog | <p>Instead of opening as a layover popup, it opens as a block on the bottom of the page left aligned.</p>
<p>I searched for similar problems, found this <a href="https://stackoverflow.com/questions/41941481/angular2-mddialog-is-not-appearing-as-a-popup">angular2 MdDialog is not appearing as a popup</a> but also doesn't work.</p>
<p>Made a clean page, maybe it was some of my other css that interfered, but nope.</p>
<pre><code> <div>
<h4 mat-dialog-title>New consultant</h4>
</div>
<mat-dialog-content>
<div *ngIf="!allFieldsAreFilledIn()" class="alert alert-info">
<strong>{{ getAddFeedback('emptyFields') }}</strong>
</div>
<div ngbDropdown class="d-inline-block">
<button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>{{ currentNewConsultant.user ? currentNewConsultant.user.lastName + " " + currentNewConsultant.user.firstName : activeUsers[0].lastName
+ " " + activeUsers[0].firstName }}</button>
<div ngbDropdownMenu aria-labelledby="dropdownBasic1">
<button class="dropdown-item" *ngFor="let user of activeUsers" (click)="updateNewConsultantProperty(user, 'user')">{{user.lastName + " " + user.firstName}}</button>
</div>
</div>
<div ngbDropdown class="d-inline-block">
<button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>{{ currentNewConsultant.unitManager != null ? currentNewConsultant.unitManager.lastName + " " + currentNewConsultant.unitManager.firstName
: unitManagers[0].lastName + " " + unitManagers[0].firstName }}</button>
<div ngbDropdownMenu aria-labelledby="dropdownBasic1">
<button class="dropdown-item" *ngFor="let um of unitManagers" (click)="updateNewConsultantProperty(um, 'unitManager')">{{um.lastName + " " + um.firstName}}</button>
</div>
</div>
<div ngbDropdown class="d-inline-block">
<button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle> {{ currentNewConsultant.profile ? currentNewConsultant.profile.name : userRoles[0].name}}</button>
<div ngbDropdownMenu aria-labelledby="dropdownBasic1">
<button class="dropdown-item" *ngFor="let profile of userRoles" (click)="updateNewConsultantProperty(profile, 'profile')">{{profile.name}}</button>
</div>
</div>
<!-- Selecting Internal -->
<div class="crudElement">
<label class="crudLabel" style="padding-top: 7px;">Internal?:</label>
<div class="btn-group crudEditElement" dropdown>
<button type="button" class="btn green-button dropdown-margin-min-width" dropdownToggle>
{{ currentNewConsultant.internal ? 'Internal' : 'External' }}
<span class="caret"></span>
</button>
<ul *dropdownMenu role="menu" aria-labelledby="single-button" class="dropdownItems dropdown-menu dropdown-margin-min-width">
<li role="menuitem" (click)="updateNewConsultantProperty('Internal', 'internal')">
<a class="dropdown-item">Internal</a>
</li>
<li role="menuitem" (click)="updateNewConsultantProperty('External', 'internal')">
<a class="dropdown-item">External</a>
</li>
</ul>
</div>
</div>
<div class="form-group">
<label for="hometown">Hometown:</label>
<input type="text" class="form-control" name="hometown" [(ngModel)]="currentNewConsultant.hometown" required>
</div>
<div class="form-group">
<label for="skills">Skills:</label>
<input type="text" class="form-control" name="skills" [(ngModel)]="currentNewConsultant.skills" required>
</div>
<div class="form-group">
<label for="comment">Comment:</label>
<textarea class="form-control" name="comment" [(ngModel)]="currentNewConsultant.comment" required></textarea>
</div>
<div class="form-group">
<label for="individualCost">Individual Cost:</label>
<input type="number" class="form-control" name="individualCost" step="0.5" [(ngModel)]="currentNewConsultant.individualCost"
required>
</div>
<!--ADDING / SAVING-->
<div *ngIf="activeUsers && allFieldsAreFilledIn()">
<button [ngStyle]="{'display' : (addConfirming ? 'none' : '')}" type="button" class="btn btn-success" (click)="save()">Add
</button>
<div [ngStyle]="{'display' : (addConfirming ? '' : 'none')}">
<div>
Are you certain you want to add the new Consultant {{ currentNewConsultant.user.lastName + ' ' + currentNewConsultant.user.firstName
}}?
</div>
<button style="margin-right: 5px; margin-top: 10px;" type="submit" class="btn btn-danger " (click)="cancel()">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
<button style="margin-top: 10px;" type="button" class="btn btn-success" (click)="save()">
<span class="glyphicon glyphicon-check" aria-hidden="true"></span>
</button>
</div>
</div>
<div *ngIf="!activeUsers" class="alert alert-danger text-center" style="margin-top: 20px;">
<strong>{{ getAddFeedback() }}</strong>
</div>
</mat-dialog-content>
</code></pre>
<p>Styles.scss</p>
<pre><code>@import '~@angular/material/prebuilt-themes/purple-green.css';
</code></pre>
<p>Open the dialog</p>
<pre><code>private openDialog(): void {
let dialogRef = this.dialog.open(CreateConsultantModalComponent, {
});
}
</code></pre>
<p>dialog component</p>
<pre><code> import { Component, OnInit, Output } from '@angular/core';
import { ConsultantService } from '../../../service/consultant.service';
import { UnitService } from '../../../service/unit.service';
import { ProfileService } from '../../../service/profile.service';
import { UserService } from '../../../service/user.service';
import { Consultant } from 'app/model/consultant.model';
import { Unit } from '../../../model/unit.model';
import { Profile } from 'app/model/profile.model';
import { User } from 'app/model/user.model';
@Component({
selector: 'r-create-consultant-modal',
templateUrl: './create-consultant-modal.component.html',
styleUrls: ['./create-consultant-modal.component.scss'],
providers: [ConsultantService, UnitService, ProfileService, UserService]
})
export class CreateConsultantModalComponent implements OnInit {
public consultants: Consultant[] = [];
public consultantsFilteredList: Consultant[] = [];
public currentNewConsultant: Consultant = null;
public units: Unit[] = [];
public unitList: string[] = [];
public userRoles: Profile[] = [];
public unitManagers: User[] = [];
public activeUsers: User[] = [];
constructor(private consultantService: ConsultantService,
private unitService: UnitService,
private profileService: ProfileService,
private userService: UserService) {
this.getAllConsultants();
this.getAllUnits();
this.getAllRoles();
this.getAllFreeAndActiveUsers();
this.getAllUnitManagers();
this.currentNewConsultant = new Consultant(null, null, null, null, null, true, 0, null, null, null, true, null);
this.currentNewConsultant.unitManager = null;
}
ngOnInit() {
}
private getAddFeedback(emptyFields?: string): string {
if (!emptyFields) {
let message = "Can't add a Consultant without a ";
if (!this.activeUsers) message += 'User';
return message += '!';
}
return 'All fields are required!'
}
private updateNewConsultantProperty($event: any, property: string): void {
switch (property) {
case 'user':
this.currentNewConsultant.user = $event;
break;
case 'internal':
this.currentNewConsultant.internal = $event == 'Internal';
break;
case 'unitManager':
this.currentNewConsultant.unitManager = $event;
break;
case 'profile':
this.currentNewConsultant.profile = $event;
break;
default:
console.log('NOT IMPLEMENTED for updateProperty on NEW Consultant');
}
}
public cancel(){}
private allFieldsAreFilledIn() {
let c = this.currentNewConsultant;
return c.user
&& c.internal
&& c.hometown
&& c.skills
&& c.comment
&& c.individualCost;
}
public save() {
if (this.activeUsers) {
this.currentNewConsultant.profile = new Profile(this.userRoles[0].id, this.userRoles[0].name, this.userRoles[0].rate);
this.currentNewConsultant.user = this.activeUsers[0];
}
if (this.unitManagers) {
let max = this.activeUsers.length;
while (--max) {
if (this.activeUsers[max].role.toUpperCase() == 'UM') {
let um = this.activeUsers[max];
this.currentNewConsultant.unitManager = new User(um.id, um.unit, um.userActivityLogs, um.email, um.password,
um.firstName, um.lastName, um.shortName, um.employeeNumber, um.role, um.active);
}
}
}
}
private getAllConsultants() {
this.consultantService.getConsultants().subscribe(
consultantList => {
consultantList.forEach(c => this.consultants.push(
new Consultant(
c.id, c.user,
c.profile, c.proposition,
c.availableFrom, c.internal, c.individualCost,
c.hometown, c.skills, c.comment, c.active, c.plannings, c.unitManager)
)
);
},
error => {
console.log("Failed to get consultants data. Error message: " + error.message);
}
);
}
private getAllUnits() {
this.unitService.findAllUnits().subscribe(
unitList => {
let unitNames = ['All'];
unitList.forEach(unit => unitNames.push(unit.name));
this.unitList = unitNames;
this.units = unitList;
},
error => {
console.log("Failed to get units data. Error message: " + error.message);
}
);
}
private getAllRoles() {
this.profileService.findAllProfiles().subscribe(roles => {
this.userRoles = roles;
})
}
private getAllUnitManagers() {
this.userService.findAllUnitManagers().subscribe(ums => {
this.unitManagers = ums;
})
}
private getAllFreeAndActiveUsers() {
// Should be done in the backend but lack of time :'(, my apologies
this.userService.findAllActiveUsers().subscribe(users => {
const amountOfConsultants = this.consultants.length;
const amountOfUsers = users.length;
for (let j = 0; j < amountOfConsultants; j++) {
for (let i = 0; i < amountOfUsers; i++) {
const user = users[i];
if (user && user.email === this.consultants[j].user.email && user.role === 'Admin') {
users[i] = null;
}
}
}
for (let k = 0; k < amountOfUsers; k++) {
const user = users[k];
if (user) { this.activeUsers.push(user); }
}
})
}
}
</code></pre> | 0 | 4,738 |
Calling functions from a c++ DLL in Delphi | <p>I created a new c++ DLL project in VS2010 that exposes 1 function </p>
<pre><code>#include "stdafx.h"
#define DllImport extern "C" __declspec( dllimport )
#define DllExport extern "C" __declspec( dllexport )
DllExport int DoMath( int a, int b) {
return a + b ;
}
</code></pre>
<p>I then created a C++ application with VS2010 to test this DLL. The test application build in VS2010 could call the c++ DLL and get the expected result. </p>
<pre><code>#include "stdafx.h"
#include <windows.h>
typedef int (*DoMath)(int, int) ;
int _tmain(int argc, _TCHAR* argv[])
{
HMODULE hMod = LoadLibrary ("exampleDLL.dll");
if (NULL != hMod) {
DoMath mf1 = (DoMath) GetProcAddress(hMod,"DoMath");
if( mf1 != NULL ) {
printf ("DoMath(8,7)==%d \n", mf1(8,7) );
} else {
printf ("GetProcAddress Failed \n");
}
FreeLibrary(hMod);
} else {
printf ("LoadLibrary failed\n");
return 1;
}
return 0;
}
</code></pre>
<p>Next I attempted to build a new project in Delphi 7 to call this C++ DLL. I used <a href="http://www.drbob42.com/delphi/headconv.htm" rel="noreferrer">this tutorial</a> to help me build the new project. </p>
<pre><code>unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TmyFunction = function(X,Y: Integer):Integer;
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
procedure FormShow(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
hDll: THandle;
end;
var
Form1: TForm1;
fDoMath : TmyFunction;
implementation
{$R *.dfm}
procedure TForm1.FormShow(Sender: TObject);
begin
hDll := LoadLibrary('exampleDLL.dll');
if HDll >= 32 then { success }
begin
fDoMath := GetProcAddress(hDll, 'DoMath');
end
else
MessageDlg('Error: could not find exampleDLL.DLL', mtError, [mbOk], 0)
end;
procedure TForm1.Button1Click(Sender: TObject);
var i: Integer;
begin
i := fDoMath(2,3);
edit1.Text := IntToStr(i);
end;
end.
</code></pre>
<p>The result from the Delphi 7 project is <em>6155731</em> When I expected <em>5</em>. I checked the binary of the result thinking it might have something to do with a data type but it looks random to me. When I recompile/rerun the application it gets the same result every time. </p>
<p>I do not know a lot about Delphi this is the first time I have deal with it and i find it confusing. </p>
<p>Any suggestion on what to check next?</p> | 0 | 1,051 |
The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied) | <p>I Installed SSRS 2008 R2 on Win Server 2008 R2. Every thing is all right, I can open Report Manager and it's Security link to define new users. I can open Report Server page, but when I want to publish my reports on Report Server I faced with this problem:</p>
<pre><code>C:\CalibrationReports>C:
C:\CalibrationReports>cd\CalibrationReports\
C:\CalibrationReports>rs.exe -i publishreports.rss -s http://ndcalibration:8080/ReportServer_SQL2008
</code></pre>
<blockquote>
<p>rsAccessDenied400The permissions granted to user 'NDCALIBRATION\admin' are insufficient for performing this operation.http://go.microsoft.com/fwlink/?LinkId=20476&EvtSrc=Microsoft.ReportingServices.Diagnostics.Utilities.ErrorStrings&EvtID=rsAccessDenied&ProdName=Microsoft%20SQL%20Server%20Reporting%20Services&ProdVer=10.50.1600.1Microsoft SQL Server Reporting Services10.50.1600.1127OsIndependent1033ReportingServicesLibraryThe permissions granted to user 'NDCALIBRATION\admin' are insufficient for performing this operation.
System.Web.Services.Protocols.SoapException: The permissions granted to user 'NDCALIBRATION\admin' are insufficient for performing this operation. ---> Microsoft.ReportingServices.Diagnostics.Utilities.AccessDeniedException: The permissions granted to user 'NDCALIBRATION\admin' are insufficient for performing this operation.
at Microsoft.ReportingServices.WebServer.ReportingService2005Impl.CreateFolder(String Folder, String Parent, Property[] Properties)
at Microsoft.ReportingServices.WebServer.ReportingService2005.CreateFolder(String Folder, String Parent, Property[] Properties)
System.Web.Services.Protocols.SoapException: The item '/CalibrationReports' cannot be found. ---> Microsoft.ReportingServices.Diagnostics.Utilities.ItemNotFoundException: The item '/CalibrationReports' cannot be found.
at Microsoft.ReportingServices.WebServer.ReportingService2005Impl.CreateDataSource(String DataSource, String Parent, Boolean Overwrite, DataSourceDefinition Definition, Property[] Properties)
at Microsoft.ReportingServices.WebServer.ReportingService2005.CreateDataSource(String DataSource, String Parent, Boolean Overwrite, DataSourceDefinition Definition, Property[] Properties)
System.Web.Services.Protocols.SoapException: The item '/CalibrationReports' cannot be found. ---> Microsoft.ReportingServices.Diagnostics.Utilities.ItemNotFoundException: The item '/CalibrationReports' cannot be found.
at Microsoft.ReportingServices.WebServer.ReportingService2005Impl.CreateReport(String Report, String Parent, Boolean Overwrite, Byte[] Definition, Property[] Properties, Warning[]& Warnings)
at Microsoft.ReportingServices.WebServer.ReportingService2005.CreateReport(String Report, String Parent, Boolean Overwrite, Byte[] Definition, Property[] Properties, Warning[]& Warnings)
System.Web.Services.Protocols.SoapException: The item '/CalibrationReports' cannot be found. ---> Microsoft.ReportingServices.Diagnostics.Utilities.ItemNotFoundException: The item '/CalibrationReports' cannot be found.
at Microsoft.ReportingServices.WebServer.ReportingService2005Impl.CreateReport(String Report, String Parent, Boolean Overwrite, Byte[] Definition, Property[] Properties, Warning[]& Warnings)
at Microsoft.ReportingServices.WebServer.ReportingService2005.CreateReport(String Report, String Parent, Boolean Overwrite, Byte[] Definition, Property[] Properties, Warning[]& Warnings)
System.Web.Services.Protocols.SoapException: The item '/CalibrationReports' cannot be found. ---> Microsoft.ReportingServices.Diagnostics.Utilities.ItemNotFoundException: The item '/CalibrationReports' cannot be found.
at Microsoft.ReportingServices.WebServer.ReportingService2005Impl.CreateReport(String Report, String Parent, Boolean Overwrite, Byte[] Definition, Property[] Properties, Warning[]& Warnings)
at Microsoft.ReportingServices.WebServer.ReportingService2005.CreateReport(String Report, String Parent, Boolean Overwrite, Byte[] Definition, Property[] Properties, Warning[]& Warnings)
System.Web.Services.Protocols.SoapException: The item '/CalibrationReports' cannot be found. ---> Microsoft.ReportingServices.Diagnostics.Utilities.ItemNotFoundException: The item '/CalibrationReports' cannot be found.
at Microsoft.ReportingServices.WebServer.ReportingService2005Impl.CreateReport(String Report, String Parent, Boolean Overwrite, Byte[] Definition, Property[] Properties, Warning[]& Warnings)
at Microsoft.ReportingServices.WebServer.ReportingService2005.CreateReport(String Report, String Parent, Boolean Overwrite, Byte[] Definition, Property[] Properties, Warning[]& Warnings)
System.Web.Services.Protocols.SoapException: The item '/CalibrationReports' cannot be found. ---> Microsoft.ReportingServices.Diagnostics.Utilities.ItemNotFoundException: The item '/CalibrationReports' cannot be found.
at Microsoft.ReportingServices.WebServer.ReportingService2005Impl.CreateReport(String Report, String Parent, Boolean Overwrite, Byte[] Definition, Property[] Properties, Warning[]& Warnings)
at Microsoft.ReportingServices.WebServer.ReportingService2005.CreateReport(String Report, String Parent, Boolean Overwrite, Byte[] Definition, Property[] Properties, Warning[]& Warnings)
System.Web.Services.Protocols.SoapException: The item '/CalibrationReports' cannot be found. ---> Microsoft.ReportingServices.Diagnostics.Utilities.ItemNotFoundException: The item '/CalibrationReports' cannot be found.
at Microsoft.ReportingServices.WebServer.ReportingService2005Impl.CreateReport(String Report, String Parent, Boolean Overwrite, Byte[] Definition, Property[] Properties, Warning[]& Warnings)
at Microsoft.ReportingServices.WebServer.ReportingService2005.CreateReport(String Report, String Parent, Boolean Overwrite, Byte[] Definition, Property[] Properties, Warning[]& Warnings)
System.Web.Services.Protocols.SoapException: The item '/CalibrationReports' cannot be found. ---> Microsoft.ReportingServices.Diagnostics.Utilities.ItemNotFoundException: The item '/CalibrationReports' cannot be found.
at Microsoft.ReportingServices.WebServer.ReportingService2005Impl.CreateReport(String Report, String Parent, Boolean Overwrite, Byte[] Definition, Property[] Properties, Warning[]& Warnings)
at Microsoft.ReportingServices.WebServer.ReportingService2005.CreateReport(String Report, String Parent, Boolean Overwrite, Byte[] Definition, Property[] Properties, Warning[]& Warnings)
The command completed successfully</p>
</blockquote>
<p>Does anyone know the reason?</p> | 0 | 1,722 |
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object in Android passing ArrayList object | <p>I want to pass my ArrayList object to another activity, using a DataWrapper that implements <code>Serializable</code>. <br/>
I followed the answer provided here: <a href="https://stackoverflow.com/q/15747727/3879470">Pass arraylist of user defined objects to Intent android</a>.<br/>
I am starting the another Activity from <code>MPAndroidChart</code> library <code>PieChart</code>'s <code>OnChartGestureListener()</code>. This is how I passed my ArrayList object <code>threadList</code>:</p>
<pre><code>mChart.setOnChartGestureListener(new OnChartGestureListener() {
@Override
public void onChartSingleTapped(MotionEvent me) {
Intent intent = new Intent(MainActivity.this, TextersSmsActivity.class);
intent.putExtra("threadList", new DataWrapper(threadList));
MainActivity.this.startActivity(intent);
}
//.....
}
</code></pre>
<p>I implemented the DataWrapper class like this:</p>
<pre><code>public class DataWrapper implements Serializable {
private static final long serialVersionUID = 100L;
private ArrayList<OneThread> threadList;
public DataWrapper(ArrayList<OneThread> threadList) {
this.threadList = threadList;
}
public ArrayList<OneThread> getThreadList() {
return threadList;
}
}
</code></pre>
<p>And getting the <code>Parcelable encountered IOException writing serializable object</code> error.
Here is my Logcat:</p>
<pre><code>11-29 21:12:09.919: E/MessageQueue-JNI(21550): java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.myproj.DataWrapper)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.os.Parcel.writeSerializable(Parcel.java:1316)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.os.Parcel.writeValue(Parcel.java:1264)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.os.Parcel.writeArrayMapInternal(Parcel.java:618)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.os.Bundle.writeToParcel(Bundle.java:1692)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.os.Parcel.writeBundle(Parcel.java:636)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.content.Intent.writeToParcel(Intent.java:7013)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:2076)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1419)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.app.Activity.startActivityForResult(Activity.java:3424)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.app.Activity.startActivityForResult(Activity.java:3385)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:817)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.app.Activity.startActivity(Activity.java:3627)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.app.Activity.startActivity(Activity.java:3595)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at com.myproj.MainActivity$11.onChartSingleTapped(MainActivity.java:967)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at com.github.mikephil.charting.listener.PieRadarChartTouchListener.onSingleTapUp(PieRadarChartTouchListener.java:89)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.GestureDetector.onTouchEvent(GestureDetector.java:595)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at com.github.mikephil.charting.listener.PieRadarChartTouchListener.onTouch(PieRadarChartTouchListener.java:40)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at com.github.mikephil.charting.charts.PieRadarChartBase.onTouchEvent(PieRadarChartBase.java:56)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.View.dispatchTouchEvent(View.java:7706)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2068)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1515)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.app.Activity.dispatchTouchEvent(Activity.java:2458)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.support.v7.app.ActionBarActivityDelegateICS$WindowCallbackWrapper.dispatchTouchEvent(ActionBarActivityDelegateICS.java:268)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2016)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.View.dispatchPointerEvent(View.java:7886)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:3947)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3826)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3392)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3442)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3411)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3518)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3419)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3575)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3392)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3442)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3411)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3419)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3392)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5532)
11-29 21:12:09.919: E/MessageQueue-JNI(21550): at android.view.ViewRootImpl.doP
</code></pre>
<p>I followed the answer (to pass array list objects) in the link above but getting the Error, what is causing the error and how to remove it?</p> | 0 | 3,084 |
"src/common.hpp:52:32: fatal error: boost/shared_ptr.hpp: No such file or directory" when building websocket++ | <p>I know next to nothing about linux or c++.</p>
<p>I generally followed these instructions to build boost on ubuntu 12.10 <a href="http://piyushparkash.blogspot.com/2012/10/installing-boost-150-in-ubuntu-1210.html" rel="nofollow noreferrer">http://piyushparkash.blogspot.com/2012/10/installing-boost-150-in-ubuntu-1210.html</a>. I downloaded 1.53.0.</p>
<p>I followed the advice of at the end of 1.2.2 and did <code>./bootstrap.sh --exec-prefix=/usr/local</code> because I wanted all libraries.</p>
<p>I get this error <code>src/common.hpp:52:32: fatal error: boost/shared_ptr.hpp: No such file or directory</code> when I <code>make</code> outlined here <a href="https://github.com/zaphoyd/websocketpp/wiki/Build-Library" rel="nofollow noreferrer">https://github.com/zaphoyd/websocketpp/wiki/Build-Library</a>.</p>
<p>When I <code>find / -name 'shared_ptr.hpp'</code>, it lists </p>
<blockquote>
<p>/root/boost_1_53_0/boost/asio/detail/shared_ptr.hpp
/root/boost_1_53_0/boost/interprocess/smart_ptr/shared_ptr.hpp
/root/boost_1_53_0/boost/smart_ptr/shared_ptr.hpp
/root/boost_1_53_0/boost/serialization/shared_ptr.hpp
/root/boost_1_53_0/boost/shared_ptr.hpp</p>
</blockquote>
<p>Shouldn't they have been installed to the default and specified directories as explained in the first link?</p>
<p>How can I resolve this error?</p>
<p>(I did this to get "all" libs <a href="https://askubuntu.com/questions/259590/libapache2-mod-fastcgi-not-available">https://askubuntu.com/questions/259590/libapache2-mod-fastcgi-not-available</a>)</p>
<p><strong><code>apt-cache libboost-all-dev</code></strong></p>
<p>1.49</p>
<p><strong><code>apt-cache search boost | grep dev</code></strong></p>
<pre><code>libboost-date-time-dev - set of date-time libraries based on generic programming concepts (default version)
libboost-date-time1.49-dev - set of date-time libraries based on generic programming concepts
libboost-dev - Boost C++ Libraries development files (default version)
libboost-iostreams-dev - Boost.Iostreams Library development files (default version)
libboost-iostreams1.49-dev - Boost.Iostreams Library development files
libboost-program-options-dev - program options library for C++ (default version)
libboost-program-options1.49-dev - program options library for C++
libboost-python-dev - Boost.Python Library development files (default version)
libboost-python1.49-dev - Boost.Python Library development files
libboost-regex-dev - regular expression library for C++ (default version)
libboost-regex1.49-dev - regular expression library for C++
libboost-serialization-dev - serialization library for C++ (default version)
libboost-serialization1.49-dev - serialization library for C++
libboost-test-dev - components for writing and executing test suites (default version)
libboost-test1.49-dev - components for writing and executing test suites
libboost1.49-dev - Boost C++ Libraries development files
libasio-dev - cross-platform C++ library for network programming
libboost-all-dev - Boost C++ Libraries development files (ALL) (default version)
libboost-chrono-dev - C++ representation of time duration, time point, and clocks (default version)
libboost-chrono1.49-dev - C++ representation of time duration, time point, and clocks
libboost-chrono1.50-dev - C++ representation of time duration, time point, and clocks
libboost-date-time1.50-dev - set of date-time libraries based on generic programming concepts
libboost-exception1.50-dev - set of date-time libraries based on generic programming concepts
libboost-filesystem-dev - filesystem operations (portable paths, iteration over directories, etc) in C++ (default version)
libboost-filesystem1.49-dev - filesystem operations (portable paths, iteration over directories, etc) in C++
libboost-filesystem1.50-dev - filesystem operations (portable paths, iteration over directories, etc) in C++
libboost-graph-dev - generic graph components and algorithms in C++ (default version)
libboost-graph-parallel-dev - generic graph components and algorithms in C++ (default version)
libboost-graph-parallel1.49-dev - generic graph components and algorithms in C++
libboost-graph-parallel1.50-dev - generic graph components and algorithms in C++
libboost-graph1.49-dev - generic graph components and algorithms in C++
libboost-graph1.50-dev - generic graph components and algorithms in C++
libboost-iostreams1.50-dev - Boost.Iostreams Library development files
libboost-locale-dev - C++ facilities for localization (default version)
libboost-locale1.49-dev - C++ facilities for localization
libboost-locale1.50-dev - C++ facilities for localization
libboost-math-dev - Boost.Math Library development files (default version)
libboost-math1.49-dev - Boost.Math Library development files
libboost-math1.50-dev - Boost.Math Library development files
libboost-mpi-dev - C++ interface to the Message Passing Interface (MPI) (default version)
libboost-mpi-python-dev - C++ interface to the Message Passing Interface (MPI), Python Bindings (default version)
libboost-mpi-python1.49-dev - C++ interface to the Message Passing Interface (MPI), Python Bindings
libboost-mpi-python1.50-dev - C++ interface to the Message Passing Interface (MPI), Python Bindings
libboost-mpi1.49-dev - C++ interface to the Message Passing Interface (MPI)
libboost-mpi1.50-dev - C++ interface to the Message Passing Interface (MPI)
libboost-program-options1.50-dev - program options library for C++
libboost-python1.50-dev - Boost.Python Library development files
libboost-random-dev - Boost Random Number Library (default version)
libboost-random1.49-dev - Boost Random Number Library
libboost-random1.50-dev - Boost Random Number Library
libboost-regex1.50-dev - regular expression library for C++
libboost-serialization1.50-dev - serialization library for C++
libboost-signals-dev - managed signals and slots library for C++ (default version)
libboost-signals1.49-dev - managed signals and slots library for C++
libboost-signals1.50-dev - managed signals and slots library for C++
libboost-system-dev - Operating system (e.g. diagnostics support) library (default version)
libboost-system1.49-dev - Operating system (e.g. diagnostics support) library
libboost-system1.50-dev - Operating system (e.g. diagnostics support) library
libboost-test1.50-dev - components for writing and executing test suites
libboost-thread-dev - portable C++ multi-threading (default version)
libboost-thread1.49-dev - portable C++ multi-threading
libboost-thread1.50-dev - portable C++ multi-threading
libboost-timer-dev - C++ wall clock and CPU process timers (default version)
libboost-timer1.49-dev - C++ wall clock and CPU process timers
libboost-timer1.50-dev - C++ wall clock and CPU process timers
libboost-wave-dev - C99/C++ preprocessor library (default version)
libboost-wave1.49-dev - C99/C++ preprocessor library
libboost-wave1.50-dev - C99/C++ preprocessor library
libboost1.49-all-dev - Boost C++ Libraries development files (ALL)
libboost1.50-all-dev - Boost C++ Libraries development files (ALL)
libboost1.50-dev - Boost C++ Libraries development files
libjson-spirit-dev - C++ JSON Parser/Generator implemented with Boost Spirit
libmapnik-dev - C++/Python toolkit for developing GIS applications (dummy)
libmapnik2-2.0 - C++/Python toolkit for developing GIS applications (libraries)
libmapnik2-dev - C++/Python toolkit for developing GIS applications (devel)
libpion-common-dev - lightweight HTTP interface library - common development files
libpion-net-dev - lightweight HTTP interface library - development files
libroot-tmva-dev - Toolkit for multivariate data analysis - development files
libtorch3-dev - State of the art machine learning library - development files
mapnik-doc - C++/Python toolkit for developing GIS applications (doc)
mapnik-utils - C++/Python toolkit for developing GIS applications (utilities)
python-mapnik2 - C++/Python toolkit for developing GIS applications (Python)
</code></pre> | 0 | 2,366 |
How to post a message via Slack-App from c#, as a user not App, with attachment, in a specific channel | <p>I can not for the life of me post a message to another channel than the one I webhooked. And I can not do it as myself(under my slackID), just as the App. </p>
<p>Problem is I have to do this for my company, so we can integrate slack to our own Software. I just do not understand what the "payload" for JSON has to look like (actually I'm doing it exactly like it says on Slack's Website, but it doesn't work at all - it always ignores things like "token", "user", "channel" etc.).</p>
<p>I also do not understand how to use the url-methods like "<a href="https://slack.com/api/chat.postMessage" rel="noreferrer">https://slack.com/api/chat.postMessage</a>" - where do they go? As you might see in my code I only have the webhookurl, and if I don't use that one I can not post to anything. Also I do not understand how to use arguments like a token, specific userId, a specific channel... - if I try to put them in the Payload they are just ignored, it seems.</p>
<p>Okay, enough whining! I'll show you now what I got so far. This is from someone who posted this online! But I changed and added a few things:</p>
<pre><code>public static void Main(string[] args)
{
Task.WaitAll(IntegrateWithSlackAsync());
}
private static async Task IntegrateWithSlackAsync()
{
var webhookUrl = new Uri("https://hooks.slack.com/services/TmyHook");
var slackClient = new SlackClient(webhookUrl);
while (true)
{
Console.Write("Type a message: ");
var message = Console.ReadLine();
Payload testMessage = new Payload(message);
var response = await slackClient.SendMessageAsync(testMessage);
var isValid = response.IsSuccessStatusCode ? "valid" : "invalid";
Console.WriteLine($"Received {isValid} response.");
Console.WriteLine(response);
}
}
}
}
public class SlackClient
{
private readonly Uri _webhookUrl;
private readonly HttpClient _httpClient = new HttpClient {};
public SlackClient(Uri webhookUrl)
{
_webhookUrl = webhookUrl;
}
public async Task<HttpResponseMessage> SendMessageAsync(Payload payload)
{
var serializedPayload = JsonConvert.SerializeObject(payload);
var stringCont = new StringContent(serializedPayload, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await _httpClient.PostAsync(_webhookUrl, stringCont);
return response;
}
}
}
</code></pre>
<p>I made this class so I can handle the Payload as an Object:</p>
<pre><code> public class Payload
{
public string token = "my token stands here";
public string user = "my userID";
public string channel = "channelID";
public string text = null;
public bool as_user = true;
public Payload(string message)
{
text = message;
}
}
</code></pre>
<p>I would be so appreciative for anyone who could post a complete bit of code that really shows how I would have to handle the payload. And/or what the actual URL would look like that gets send to slack... so I maybe can understand what the hell is going on :) </p> | 0 | 1,231 |
How to authenticate nginx with ldap? | <p>I follow this reference <a href="https://github.com/kvspb/nginx-auth-ldap/blob/master/README.md" rel="nofollow noreferrer">https://github.com/kvspb/nginx-auth-ldap/blob/master/README.md</a> and try to integrate nginx and LDAP.</p>
<p>my nginx.conf setting:</p>
<pre><code>user nginx;
worker_processes 4;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
ldap_server ldap_local {
url "ldap://localhost/cn=Manager,dc=xinhua?uid?sub?(objectClass=posixAccount)";
binddn "cn=Manager,dc=xinhua,dc=org";
binddn_passwd "xxxxxx";
require group "cn=config,ou=People,dc=xinhua,dc=org";
group_attribute "memberUid";
group_attribute_is_dn off;
require valid_user;
satisfy all;
}
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
</code></pre>
<p>conf.d/default.conf</p>
<pre><code>server {
listen 8000;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
auth_ldap "Forbidden";
auth_ldap_servers ldap_local;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
</code></pre>
<p>My question is how to authenticate the username and password which are in LDAP.
<img src="https://user-images.githubusercontent.com/19474557/42205680-b4fabe92-7ed7-11e8-9979-643dce5bcd66.png" /></p>
<p><img src="https://user-images.githubusercontent.com/19474557/42205713-c4a15f9a-7ed7-11e8-947d-429e85632d10.png" /></p>
<p>This is my first time to use LDAP.</p>
<p>Now, I don't know what is the username and password.</p>
<p>When I try the username and password in <code>.htpasswd</code>. It doesn't work.</p> | 0 | 1,073 |
Spring Transactions and hibernate.current_session_context_class | <p>I have a Spring 3.2 application that uses Hibernate 4 and Spring Transactions. All the methods were working great and I could access correctly the database to save or retrieve entities.
Then, I introduced some multithreading, and since each thread was accessing to db I was getting the following error from Hibernate:</p>
<pre><code>org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
</code></pre>
<p>I read from the web that I've to add <code><prop key="hibernate.current_session_context_class">thread</prop></code> to my Hibernate configuration, but now every time I try to access the db I get: </p>
<pre><code>org.hibernate.HibernateException: saveOrUpdate is not valid without active transaction
</code></pre>
<p>However my service methods are annotated with <code>@Transactional</code>, and all was working fine before the add of <code><prop key="hibernate.current_session_context_class">thread</prop></code>.</p>
<p>Why there is no transaction although the methods are annotated with @Transactional? How can I solve this problem?</p>
<p>Here is my Hibernate configuration (including the session context property):</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- Hibernate session factory -->
<bean
id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
<property name="dataSource" >
<ref bean="dataSource" />
</property>
<property name="hibernateProperties" >
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.dialect" >org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
<property name="annotatedClasses" >
<list>
...
</list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</code></pre>
<p></p> | 0 | 1,093 |
Java Canvas Draw Image from BufferedImage | <p>I am currently working on my personal project. The idea is to import a picture and crop it into n-pieces of bufferedimage then draw them with random sequence to a java canvas. After that save the canvas to image file. Right now iam stuck at saving the canvas and i have searching for the solutions but none of them work. Here my save procedure.
Please help, thanks in advance</p>
<pre><code> private void save() {
int r = jFileChooser1.showSaveDialog(this);
File file2 = null;
if(r == jFileChooser1.APPROVE_OPTION){
file2 = jFileChooser1.getSelectedFile();
Graphics g2d = canvas.getGraphics();
BufferedImage bi = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();
canvas.paint(g2);
g2.dispose();
g2d.dispose();
try
{
ImageIO.write(bi, "jpg", file2);
}
catch (Exception ex) {
System.out.println("Error saving");
}
}
}
</code></pre>
<p>Update :
Now i get it, after using paintComponents now i can save the picture. Thanks @madProgrammer</p>
<pre><code>public class CaptureImage extends javax.swing.JFrame {
MyPanel canvas;
BufferedImage[] processedImage;
public CaptureImage(BufferedImage[] proc) {
processedImage = proc;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private void createAndShowGUI() {
System.out.println("Created GUI on EDT? "
+ SwingUtilities.isEventDispatchThread());
JFrame f = new JFrame("Output Picture");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
save();
System.exit(0);//cierra aplicacion
}
});
canvas = new MyPanel(processedImage);
f.add(canvas);
f.setSize(400, 400);
f.setVisible(true);
}
public void save() {
JFileChooser jFileChooser1 = new JFileChooser();
int r = jFileChooser1.showSaveDialog(this);
File file2 = null;
if (r == jFileChooser1.APPROVE_OPTION) {
file2 = jFileChooser1.getSelectedFile();
BufferedImage bi = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();
canvas.print(g2);
try {
ImageIO.write(bi, "jpg", file2);
g2.dispose();
} catch (Exception ex) {
System.out.println("Error saving");
}
}
}
}
class MyPanel extends JPanel {
private Image[] processedImage;
public MyPanel(Image[] processedImage) {
this.processedImage = processedImage;
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
repaint();
}
});
}
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int loopj = 10;
int loopi = 10;
int l = 0;
int jPieces = 100;
int[] r = new int[jPieces];
int rand = 0;
for (int i = 0; i < r.length; i++) {
rand = (int) (Math.random() * (r.length));
if (Arrays.binarySearch(r, 0, r.length, rand) <= -1) {
r[i] = rand;
}
}
Graphics2D g2d = (Graphics2D) g;
for (int i = 0; i < loopi; i++) {
for (int j = 0; j < loopj; j++) {
g2d.drawImage(processedImage[r[l]], i * 30, j * 30, this);
l++;
}
}
}
}
</code></pre> | 0 | 1,487 |
Too many redirects error while trying to configure rails application as SSL using nginx and unicorn | <p>I am trying to configure a Rails application with SSL, using Nginx and Unicorn.
I am trying to set it up locally. For that I first created a self-signed certificate using OpenSSL for Nginx. I followed the <a href="https://www.digitalocean.com/community/articles/how-to-create-a-ssl-certificate-on-nginx-for-ubuntu-12-04" rel="noreferrer">document</a> for creating self-signed certificates. After that I configured my <code>nginx.conf</code> as below, inside the <code>http</code> block:</p>
<pre><code>upstream unicorn_myapp {
# This is the socket we configured in unicorn.rb
server unix:root_path/tmp/sockets/unicorn.sock fail_timeout=0;
}
server {
listen 80;
server_name dev.myapp.com;
rewrite ^/(.*) http://dev.myapp.com/$1 permanent;
}
server {
listen 80;
listen 443 ssl;
server_name dev.myapp.com;
ssl on;
ssl_certificate /etc/nginx/ssl/server.pem;
ssl_certificate_key /etc/nginx/ssl/server.key;
ssl_protocols SSLv3 TLSv1;
ssl_ciphers ALL:-ADH:+HIGH:+MEDIUM:-LOW:-SSLv2:-EXP;
ssl_session_cache shared:SSL:10m;
root root_path/public;
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
if (!-f $request_filename) {
proxy_pass http://unicorn_myapp;
break;
}
}
}
</code></pre>
<p>I tried to set it up locally, and started Unicorn locally. I mapped <code>127.0.0.1</code> to <code>dev.myapp.com</code> in <code>/etc/hosts</code>. But after starting the server, when I tried to ping the app, it gave the below error in Chrome:</p>
<pre><code>This webpage has a redirect loop
Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects.
</code></pre>
<p>and the following error in Firefox:</p>
<pre><code>The page isn't redirecting properly
</code></pre>
<p>The <code>nginix.access.log</code> shows the following result:</p>
<pre><code>127.0.0.1 - - [18/Feb/2013:12:56:16 +0530] "GET / HTTP/1.1" 301 5 "-" "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"
127.0.0.1 - - [18/Feb/2013:12:56:16 +0530] "-" 400 0 "-" "-"
127.0.0.1 - - [18/Feb/2013:12:56:16 +0530] "GET / HTTP/1.1" 301 5 "-" "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"
127.0.0.1 - - [18/Feb/2013:12:56:16 +0530] "-" 400 0 "-" "-"
127.0.0.1 - - [18/Feb/2013:12:56:16 +0530] "GET / HTTP/1.1" 301 5 "-" "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"
127.0.0.1 - - [18/Feb/2013:12:56:43 +0530] "-" 400 0 "-" "-"
127.0.0.1 - - [18/Feb/2013:12:56:43 +0530] "-" 400 0 "-" "-"
127.0.0.1 - - [18/Feb/2013:12:56:43 +0530] "-" 400 0 "-" "-"
127.0.0.1 - - [18/Feb/2013:12:56:43 +0530] "-" 400 0 "-" "-"
127.0.0.1 - - [18/Feb/2013:12:56:43 +0530] "GET / HTTP/1.1" 301 5 "-" "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"
127.0.0.1 - - [18/Feb/2013:12:56:43 +0530] "-" 400 0 "-" "-"
127.0.0.1 - - [18/Feb/2013:12:56:43 +0530] "GET / HTTP/1.1" 301 5 "-" "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"
127.0.0.1 - - [18/Feb/2013:12:56:43 +0530] "-" 400 0 "-" "-"
127.0.0.1 - - [18/Feb/2013:12:56:43 +0530] "GET / HTTP/1.1" 301 5 "-" "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"
127.0.0.1 - - [18/Feb/2013:12:56:43 +0530] "-" 400 0 "-" "-"
127.0.0.1 - - [18/Feb/2013:12:56:43 +0530] "GET / HTTP/1.1" 301 5 "-" "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"
127.0.0.1 - - [18/Feb/2013:12:56:43 +0530] "-" 400 0 "-" "-"
127.0.0.1 - - [18/Feb/2013:12:56:43 +0530] "GET / HTTP/1.1" 301 5 "-" "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"
127.0.0.1 - - [18/Feb/2013:12:56:43 +0530] "-" 400 0 "-" "-"
</code></pre>
<p>Can any one please help me out to find the solution?</p> | 0 | 1,962 |
Object detection with OpenCV Feature Matching with a threshold/similarity score - Java/C++ | <p>I am in the process of creating a small program which detects objects(small image) in the large image and I am using OpenCV java.
As I have to consider rotation and scaling I have used FeatureDetector.BRISK and DescriptorExtractor.BRISK. </p>
<p>Following approach is used to filter the match results to get the best matches only.</p>
<p>I have two questions</p>
<ol>
<li>Is there a way to find the below min_dist and max_dist with the loop I have used?</li>
<li>Most important question - Now the problem is I need to use these matches to determine whether the object(template) found or not. Would be great if some one help me here.</li>
</ol>
<p>Thanks in advance.</p>
<pre><code> FeatureDetector fd = FeatureDetector.create(FeatureDetector.BRISK);
final MatOfKeyPoint keyPointsLarge = new MatOfKeyPoint();
final MatOfKeyPoint keyPointsSmall = new MatOfKeyPoint();
fd.detect(largeImage, keyPointsLarge);
fd.detect(smallImage, keyPointsSmall);
System.out.println("keyPoints.size() : "+keyPointsLarge.size());
System.out.println("keyPoints2.size() : "+keyPointsSmall.size());
Mat descriptorsLarge = new Mat();
Mat descriptorsSmall = new Mat();
DescriptorExtractor extractor = DescriptorExtractor.create(DescriptorExtractor.BRISK);
extractor.compute(largeImage, keyPointsLarge, descriptorsLarge);
extractor.compute(smallImage, keyPointsSmall, descriptorsSmall);
System.out.println("descriptorsA.size() : "+descriptorsLarge.size());
System.out.println("descriptorsB.size() : "+descriptorsSmall.size());
MatOfDMatch matches = new MatOfDMatch();
DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMINGLUT);
matcher.match(descriptorsLarge, descriptorsSmall, matches);
System.out.println("matches.size() : "+matches.size());
MatOfDMatch matchesFiltered = new MatOfDMatch();
List<DMatch> matchesList = matches.toList();
List<DMatch> bestMatches= new ArrayList<DMatch>();
Double max_dist = 0.0;
Double min_dist = 100.0;
for (int i = 0; i < matchesList.size(); i++)
{
Double dist = (double) matchesList.get(i).distance;
if (dist < min_dist && dist != 0)
{
min_dist = dist;
}
if (dist > max_dist)
{
max_dist = dist;
}
}
System.out.println("max_dist : "+max_dist);
System.out.println("min_dist : "+min_dist);
double threshold = 3 * min_dist;
double threshold2 = 2 * min_dist;
if (threshold2 >= max_dist)
{
threshold = min_dist * 1.1;
}
else if (threshold >= max_dist)
{
threshold = threshold2 * 1.4;
}
System.out.println("Threshold : "+threshold);
for (int i = 0; i < matchesList.size(); i++)
{
Double dist = (double) matchesList.get(i).distance;
System.out.println(String.format(i + " match distance best : %s", dist));
if (dist < threshold)
{
bestMatches.add(matches.toList().get(i));
System.out.println(String.format(i + " best match added : %s", dist));
}
}
matchesFiltered.fromList(bestMatches);
System.out.println("matchesFiltered.size() : " + matchesFiltered.size());
</code></pre>
<hr>
<h2>Edit</h2>
<p>Edited my code as follows.I know still it's not the best way to come to a conclusion whether the object found or not based on no of best matches.
So please share your views.</p>
<pre><code> System.out.println("max_dist : "+max_dist);
System.out.println("min_dist : "+min_dist);
if(min_dist > 50 )
{
System.out.println("No match found");
System.out.println("Just return ");
return false;
}
double threshold = 3 * min_dist;
double threshold2 = 2 * min_dist;
if (threshold > 75)
{
threshold = 75;
}
else if (threshold2 >= max_dist)
{
threshold = min_dist * 1.1;
}
else if (threshold >= max_dist)
{
threshold = threshold2 * 1.4;
}
System.out.println("Threshold : "+threshold);
for (int i = 0; i < matchesList.size(); i++)
{
Double dist = (double) matchesList.get(i).distance;
if (dist < threshold)
{
bestMatches.add(matches.toList().get(i));
//System.out.println(String.format(i + " best match added : %s", dist));
}
}
matchesFiltered.fromList(bestMatches);
System.out.println("matchesFiltered.size() : " + matchesFiltered.size());
if(matchesFiltered.rows() >= 1)
{
System.out.println("match found");
return true;
}
else
{
return false;
}
</code></pre> | 0 | 1,903 |
npm package.json scripts not being called | <p>I have the following scripts section in my projects package.json:</p>
<pre><code>"scripts": {
"seed": "node bin/seed",
"test": "echo \"Error: no test specified\" && exit 1"
},
</code></pre>
<p>If i run <code>$ npm test</code> I get this:</p>
<pre><code>>npm test
> node-mongo-seeds@0.0.1 test C:\Users\m089269\WebstormProjects\node-mongo-seeds
> echo "Error: no test specified" && exit 1
"Error: no test specified"
npm ERR! Test failed. See above for more details.
npm ERR! not ok code 0
</code></pre>
<p>If i run <code>$ npm seed</code>, I get this:</p>
<pre><code>npm seed
Usage: npm <command>
where <command> is one of:
add-user, adduser, apihelp, author, bin, bugs, c, cache,
completion, config, ddp, dedupe, deprecate, docs, edit,
explore, faq, find, find-dupes, get, help, help-search,
home, i, info, init, install, isntall, issues, la, link,
list, ll, ln, login, ls, outdated, owner, pack, prefix,
prune, publish, r, rb, rebuild, remove, repo, restart, rm,
root, run-script, s, se, search, set, show, shrinkwrap,
star, stars, start, stop, submodule, tag, test, tst, un,
uninstall, unlink, unpublish, unstar, up, update, v,
version, view, whoami
npm <cmd> -h quick help on <cmd>
npm -l display full usage info
npm faq commonly asked questions
npm help <term> search for help on <term>
npm help npm involved overview
Specify configs in the ini-formatted file:
C:\Users\m089269\.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config
npm@1.4.3 C:\Program Files\nodejs\node_modules\npm
</code></pre>
<p>Why does it recognize my <code>test</code> script but not my <code>seed</code> script?</p>
<p><strong>EDIT</strong></p>
<p>When I try <code>npm run-script seed</code> I get this error which is expected because I don't pass in a <code>-d</code> param:</p>
<pre><code>$ npm run-script seed
> node-mongo-seeds@0.0.1 seed C:\Users\m089269\WebstormProjects\node-mongo-seeds
> node bin/seed
Populate mongo from a set of .json files.
Usage: $ node seed
Options:
-d The path to your mongo db [required]
Missing required arguments: d
npm ERR! node-mongo-seeds@0.0.1 seed: `node bin/seed`
npm ERR! Exit status 1
...
</code></pre>
<p>When I try <code>npm run-script seed -d "localhost/ease"</code> I get this error. </p>
<pre><code>npm run-script seed -d localhost/ease-dev
npm info it worked if it ends with ok
npm info using npm@1.4.3
npm info using node@v0.10.26
npm ERR! Error: ENOENT, open 'C:\Users\m089269\WebstormProjects\node-mongo-seeds\node_modules\seed\package.json'
...
</code></pre>
<p>Why is it looking for a package.json in node_modules\seed? Seed is not even a dependency.</p> | 0 | 1,111 |
Expected 2D array, got 1D array instead, Reshape Data | <p>I'm really stuck on this problem. I'm trying to use OneHotEncoder to encode my data into a matrix after using LabelEncoder but getting this error: Expected 2D array, got 1D array instead.</p>
<p>At the end of the error message(included below) it said to "Reshape my data" which I thought I did but it's still not working. If I understand Reshaping, is that just when you want to literally reshape some data into a different matrix size? For example, if I want to change a 3 x 2 matrix into a 4 x 6? </p>
<p>My code is failing on these 2 lines:</p>
<pre><code>X = X.reshape(-1, 1) # I added this after I saw the error
X[:, 0] = onehotencoder1.fit_transform(X[:, 0]).toarray()
</code></pre>
<p>Here is the code I have so far:</p>
<pre><code># Data Preprocessing
# Import Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import Dataset
dataset = pd.read_csv('Data2.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 5].values
df_X = pd.DataFrame(X)
df_y = pd.DataFrame(y)
# Replace Missing Values
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)
imputer = imputer.fit(X[:, 3:5 ])
X[:, 3:5] = imputer.transform(X[:, 3:5])
# Encoding Categorical Data "Name"
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_x = LabelEncoder()
X[:, 0] = labelencoder_x.fit_transform(X[:, 0])
# Transform into a Matrix
onehotencoder1 = OneHotEncoder(categorical_features = [0])
X = X.reshape(-1, 1)
X[:, 0] = onehotencoder1.fit_transform(X[:, 0]).toarray()
# Encoding Categorical Data "University"
from sklearn.preprocessing import LabelEncoder
labelencoder_x1 = LabelEncoder()
X[:, 1] = labelencoder_x1.fit_transform(X[:, 1])
</code></pre>
<p>Here is the full error message:</p>
<pre><code> File "/Users/jim/anaconda3/lib/python3.6/site-packages/sklearn/preprocessing/data.py", line 1809, in _transform_selected
X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES)
File "/Users/jim/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py", line 441, in check_array
"if it contains a single sample.".format(array))
ValueError: Expected 2D array, got 1D array instead:
array=[ 2.00000000e+00 7.00000000e+00 3.20000000e+00 2.70000000e+01
2.30000000e+03 1.00000000e+00 6.00000000e+00 3.90000000e+00
2.80000000e+01 2.90000000e+03 3.00000000e+00 4.00000000e+00
4.00000000e+00 3.00000000e+01 2.76700000e+03 2.00000000e+00
8.00000000e+00 3.20000000e+00 2.70000000e+01 2.30000000e+03
3.00000000e+00 0.00000000e+00 4.00000000e+00 3.00000000e+01
2.48522222e+03 5.00000000e+00 9.00000000e+00 3.50000000e+00
2.50000000e+01 2.50000000e+03 5.00000000e+00 1.00000000e+00
3.50000000e+00 2.50000000e+01 2.50000000e+03 0.00000000e+00
2.00000000e+00 3.00000000e+00 2.90000000e+01 2.40000000e+03
4.00000000e+00 3.00000000e+00 3.70000000e+00 2.77777778e+01
2.30000000e+03 0.00000000e+00 5.00000000e+00 3.00000000e+00
2.90000000e+01 2.40000000e+03].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
</code></pre>
<p>Any help would be great.</p> | 0 | 1,309 |
Search a word in a text string in Excel sheet using openpyxl | <p>I'm trying to search for a word in a cell that has a text string that looks like this (Energy;Green Buildings;High Performance Buildings). Here is the code I wrote, I get a syntax error</p>
<pre><code>for row in ws.iter_rows('D2:D11'):
for cell in row:
if 'Energy' in ws.cell.value :
Print 'yes'
</code></pre>
<p>Obviously, I don't want to print yes, this was to test the search function.</p>
<p>Additionally, I want to get the cell location, and then tell openpyxl to assign a color to a cell in the same row under column E. here is a snap shot of my Excel sheet.
I know how to assign a color using this command</p>
<p><code>c.fill = PatternFill(start_color='FFFFE0', end_color='FFFFE0'
fill_type='solid'</code>)</p>
<p>I just need help getting the cell location (the cell that has a matching text) and assign its row number to another cell in column E</p>
<p><a href="https://i.stack.imgur.com/osYZG.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/osYZG.jpg" alt="enter image description here"></a></p>
<p>UPDATE: I wrote this code below that is working fine for me:</p>
<pre><code>import xml.etree.ElementTree as ET
fhand = open ('My_Collection')
tree =ET.parse('My_Collection.xml')
data= fhand.read()
root = tree.getroot()
tree = ET.fromstring(data)
title_list= ['Title']
year_list = ['Year']
author_list= ['Author']
label_list = ['Label']
for child in tree:
for children in child:
if children.find('.//title')is None :
t='N'
else:
t=children.find('.//title').text
title_list.append(t)
print title_list
print len(title_list)
for child in tree:
for children in child:
if children.find('.//year')is None :
y='N'
else:
y=children.find('.//year').text
year_list.append(y)
print year_list
print len(year_list)
for child in tree:
for children in child:
if children.find('.//author')is None :
a='N'
else:
a=children.find('.//author').text
author_list.append(a)
print author_list
print len(author_list)
for child in tree:
for children in child:
if children.find('label')is None :
l='N'
else:
l=children.find('label').text
label_list.append(l)
print label_list
print len(author_list)
Modified_label_list=list()
import re
for labels in label_list:
all_labels=labels.split(';')
for a_l in all_labels:
if a_l not in Modified_label_list:
Modified_label_list.append(a_l)
else:
continue
print Modified_label_list
print len(Modified_label_list)
label_list_for_col_header= Modified_label_list[1:]
print label_list_for_col_header
print len(label_list_for_col_header)
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
for row in zip(title_list, year_list, author_list, label_list):
ws.append(row)
r = 5
for N in label_list_for_col_header:
ws.cell(row=1, column=r).value = str(N)
r += 1
from openpyxl.styles import PatternFill
general_lst= list()
COLOR_INDEX = ['FF000000', 'FFFFFFFF', 'FFFF0000', 'FF00FF00', 'FF0000FF',
'FFFFFF00', 'FFFF00FF', 'FF00FFFF', 'FF800000', 'FF008000', 'FF000080',
'FF808000', 'FF800080', 'FF008080', 'FFC0C0C0', 'FF808080', 'FF9999FF',
'FF993366', 'FFFFFFCC', 'FFCCFFFF', 'FF660066', 'FFFF8080', 'FF0066CC',
'FFCCCCFF', 'FF000080', 'FFFF00FF', 'FFFFFF00', 'FF00FFFF', 'FF800080',
'FF800000', 'FF008080', 'FF0000FF', 'FF00CCFF', 'FFCCFFFF', 'FFCCFFCC',
'FFFFFF99', 'FF99CCFF', 'FFFF99CC', 'FFCC99FF', 'FFFFCC99', 'FF3366FF',
'FF33CCCC', 'FF99CC00', 'FFFFCC00', 'FFFF9900', 'FFFF6600', 'FF666699',
'FF969696', 'FF003366', 'FF339966', 'FF003300', 'FF333300', 'FF993300',
'FF993366', 'FF333399', 'FF333333']
import random
color_lst= random.sample(COLOR_INDEX, len(label_list_for_col_header))
print color_lst
print int(label_list_for_col_header.index(label_list_for_col_header[0]))
h= len(title_list)
m= 0
for lbls in label_list_for_col_header:
j= int(label_list_for_col_header.index(lbls))+5
for row in ws.iter_rows('D2:D11'):
for cell in row:
if lbls in cell.value :
general_lst.append(cell.row)
for items in range(len(general_lst)):
ws.cell(row = general_lst[items], column = j).fill = PatternFill(start_color=str(color_lst[m]), end_color=str(color_lst[m]) , fill_type='solid')
general_lst = []
m +=1
ws.column_dimensions['A'].width = 70
ws.column_dimensions['C'].width = 23
ws.column_dimensions['B'].width = 5
wb.save("Test61.xlsx")
</code></pre>
<p><a href="https://i.stack.imgur.com/98kJI.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/98kJI.jpg" alt="enter image description here"></a> </p> | 0 | 2,231 |
'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync | <blockquote>
<p>.Net Core 1.0.0 - SDK Preview 2 (x64)</p>
<p>.Net Core 1.0.0 - VS "15" Preview 2 (x64)</p>
<p>.Net Core 1.0.0 - Runtime (x64)</p>
</blockquote>
<p>So, we updated an RC1 app to the latest versions above. After many hours of switching references, it's running. However, when logging in (AccountController/Login), I am getting an error at:</p>
<pre><code>public class AccountController : BaseController
{
public UserManager<ApplicationUser> UserManager { get; private set; }
public SignInManager<ApplicationUser> SignInManager { get; private set; }
private readonly IEmailSender EmailSender;
public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender)
{
UserManager = userManager;
SignInManager = signInManager;
EmailSender = emailSender;
}
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(ViewModels.Account.LoginViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
// Errs this next line
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false); // <-- ERRS HERE '.PasswordSignInAsync'
if (result.Succeeded)
return RedirectToLocal(returnUrl);
ModelState.AddModelError("", "Invalid email or password.");
return View(model);
}
// If we got this far, something failed, redisplay form
return View(model);
}
</code></pre>
<p>It blows up with the following error message:</p>
<blockquote>
<p>InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.</p>
</blockquote>
<p>Here is the Startup.cs:</p>
<pre><code>public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
// Add EF services to the services container.
services.AddEntityFrameworkSqlServer()
.AddDbContext<LogManagerContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:Connectionstring"]));
services.AddSingleton(c => Configuration);
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<LogManagerContext>()
.AddDefaultTokenProviders();
// Add MVC services to the services container.
services.AddMvc();
services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
//Add all SignalR related services to IoC. - Signal R not ready yet - Chad
//services.AddSignalR();
//Add InMemoryCache
services.AddMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = System.TimeSpan.FromHours(1);
options.CookieName = ".LogManager";
});
// Uncomment the following line to add Web API servcies which makes it easier to port Web API 2 controllers.
// You need to add Microsoft.AspNet.Mvc.WebApiCompatShim package to project.json
// services.AddWebApiConventions();
// Register application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
}
// Configure is called after ConfigureServices is called.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseSession();
// Configure the HTTP request pipeline.
// Add the console logger.
//loggerFactory.MinimumLevel = LogLevel.Information; - moved to appsettings.json -chad
loggerFactory.AddConsole();
loggerFactory.AddDebug();
loggerFactory.AddNLog();
// Add the following to the request pipeline only in development environment.
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
//app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
}
else
{
// Add Error handling middleware which catches all application specific errors and
// sends the request to the following path or controller action.
app.UseExceptionHandler("/Home/Error");
}
env.ConfigureNLog("NLog.config");
// Add static files to the request pipeline.
app.UseStaticFiles();
// Add cookie-based authentication to the request pipeline.
app.UseIdentity();
//SignalR
//app.UseSignalR();
// Add MVC to the request pipeline.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" }
);
// Uncomment the following line to add a route for porting Web API 2 controllers.
// routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
});
}
</code></pre>
<p>And here's the Context:</p>
<pre><code>public class ApplicationUser : IdentityUser
{
// Add Custom Profile Fields
public string Name { get; set; }
}
public class LogManagerContext : IdentityDbContext<ApplicationUser>
{
public DbSet<LogEvent> LogEvents { get; set; }
public DbSet<Client> Clients { get; set; }
public DbSet<LogEventsHistory> LogEventsHistory { get; set; }
public DbSet<LogEventsLineHistory> LogEventsLineHistory { get; set; }
public DbSet<LogRallyHistory> LogRallyHistory { get; set; }
public DbSet<Flag> Flags { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<LogEvent>().HasKey(x => x.LogId);
builder.Entity<LogEvent>().ToTable("LogEvents");
builder.Entity<Client>().HasKey(x => x.ClientId);
builder.Entity<Client>().ToTable("Clients");
builder.Entity<LogEventsHistory>().HasKey(x => x.HistoryId);
builder.Entity<Flag>().HasKey(x => x.FlagId);
builder.Entity<Flag>().ToTable("Flags");
builder.Entity<LogRallyHistory>().HasKey(x => x.HistoryId);
builder.Entity<LogEventsLineHistory>().HasKey(x => x.LineHistoryId);
base.OnModelCreating(builder);
}
</code></pre> | 0 | 2,916 |
ClassNotFound exception when loading applet in Chrome | <p>I'm having a hard time getting a Java applet to run in Chrome. The class loader can't find the class, even though the it works fine in Firefox, Opera and Safari.</p>
<p>Here's my test applet class (I even took out the package declaration to keep it simple):</p>
<pre><code>import java.awt.Graphics;
import java.applet.Applet;
public class Test extends Applet
{
public void init() { repaint(); }
public void paint( Graphics g ) {
g.drawOval(10, 10, 30, 50);
g.drawLine(15, 30, 22, 32);
g.fillOval(28, 28, 7, 5);
g.drawArc(15, 20, 20, 35, 210, 120);
}
}
</code></pre>
<p>Here's the minimalistic test page:</p>
<pre><code><!doctype html>
<html><head>
<meta charset="utf-8"/>
<title>Test</title>
</head><body>
<p>
<object type="application/x-java-applet" width="50" height="70">
<param name="code" value="Test" />
Test failed.
</object>
</p>
</body></html>
</code></pre>
<p>Here's the stack trace:</p>
<pre><code>java.lang.ClassNotFoundException: Test
at sun.plugin2.applet.Applet2ClassLoader.findClass(Applet2ClassLoader.java:252)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Plugin2ClassLoader.java:250)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:180)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:161)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Plugin2ClassLoader.java:687)
at sun.plugin2.applet.Plugin2Manager.createApplet(Plugin2Manager.java:3046)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Plugin2Manager.java:1498)
at java.lang.Thread.run(Thread.java:680)
</code></pre>
<p>I've compiled the class with <code>javac Test.java</code>, and I put the .class file in the same folder as the .html file. Again, this runs fine in both Firefox, Safari and Opera, so why not in Chrome?</p>
<p>I've tried creating a jar and adding <code><param name="archive" value="Test.jar" /></code>, but that didn't help.</p>
<p>Oh, and while I'm asking stuff: Is there an official spec listing the <code><param></code> parameters one can use with applets in <code><object></code> tags? It's not in the HTML5 spec, which makes sense, but Oracle seems to favor the old abandoned <code><applet></code> tag and I need to use strict HTML5.</p>
<h2>Environment</h2>
<p>MacBook Pro running OS X 10.7.1</p>
<pre><code>java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03-383-11A511)
Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02-383, mixed mode)
</code></pre>
<p>Google Chrome 13.0.782.220</p> | 0 | 1,091 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.