title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
Websocket handshake fails 404 (golang server) | <p>I have a simple go web server which serves on port localhost:8080 an public folder containing both an html file as well as a client script with websocket logic.</p>
<p>in my <a href="https://gist.github.com/Kielan/98706aaf5dc0be9d6fbe" rel="nofollow">main.go file</a></p>
<pre><code>listener, err := net.listen("tcp", "localhost:8080")
if err != nil {
log.Fatal(err)
}
//full code in gist https://gist.github.com/Kielan/98706aaf5dc0be9d6fbe
</code></pre>
<p>then in my client script </p>
<pre><code>try {
var sock = new WebSocket("ws://127.0.0.1:8080");
console.log("Websocket - status: " + sock.readyState);
sock.onopen = function(message) {
console.log("CONNECTION opened..." + this.readyState);
//onmessage, onerr, onclose, ect...
}
</code></pre>
<p>I get the error in chrome</p>
<pre><code>WebSocket connection to 'ws://127.0.0.1:8080/' failed: Error during WebSocket handshake: Unexpected response code: 200
</code></pre>
<p>and Firefox</p>
<pre><code>Firefox can't establish a connection to the server at ws://127.0.0.1:8080/.
</code></pre>
<p>I found <a href="http://procbits.com/connecting-to-a-sockjs-server-from-native-html5-websocket" rel="nofollow">this article</a> referring to node.js indicating to add /websocket to my client websocket string, though it did not solve the problem and resulted in a 404</p>
<p>I thought response code 200 is good, do I need to convert the request to a websocket somehow and maybe it is defaulting to http? If so how can I do this?</p> | 1 |
Error creating bean with name 'dao': Injection of persistence dependencies failed | <p>i dont know ahy i got this error</p>
<p><strong>Main</strong></p>
<pre>
IBanqueMetier metier;
ClassPathXmlApplicationContext context
= new ClassPathXmlApplicationContext(
new String[]{"applicationContext.xml"});
metier = (IBanqueMetier) context.getBean("metier");
metier.addClient(new Client("Client1","Adress1"));
</pre>
<p><strong>BanqueDaoImpl</strong> </p>
<pre>
public class BanqueDaoImpl implements IBanqueDao {
@PersistenceContext
private EntityManager em;
@Override
public Client addClient(Client c) {
// j'enregistre le client c et je le retourne
em.persist(c);
return c;
}
....
</pre>
<p>and this the 1rst error :</p>
<pre>
INFO : org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1be847c: startup date [Fri Feb 05 14:22:40 CET 2016]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [applicationContext.xml]
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1846619: defining beans [dao,metier,dataSource,persistenceUnitManager,entityManagerFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
WARN : org.hibernate.ejb.HibernatePersistence - HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1846619: defining beans [dao,metier,dataSource,persistenceUnitManager,entityManagerFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.annotations.common.reflection.java.JavaReflectionManager.injectClassLoaderDelegate(Lorg/hibernate/annotations/common/reflection/ClassLoaderDelegate;)V
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:342)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:93)
at toto.tata.titi.test.test.main(test.java:14)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.annotations.common.reflection.java.JavaReflectionManager.injectClassLoaderDelegate(Lorg/hibernate/annotations/common/reflection/ClassLoaderDelegate;)V
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:530)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:496)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:657)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:630)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:339)
... 13 more
Caused by: java.lang.NoSuchMethodError: org.hibernate.annotations.common.reflection.java.JavaReflectionManager.injectClassLoaderDelegate(Lorg/hibernate/annotations/common/reflection/ClassLoaderDelegate;)V
at org.hibernate.boot.internal.MetadataBuilderImpl$MetadataBuildingOptionsImpl.generateDefaultReflectionManager(MetadataBuilderImpl.java:737)
at org.hibernate.boot.internal.MetadataBuilderImpl$MetadataBuildingOptionsImpl.(MetadataBuilderImpl.java:709)
at org.hibernate.boot.internal.MetadataBuilderImpl.(MetadataBuilderImpl.java:127)
at org.hibernate.boot.MetadataSources.getMetadataBuilder(MetadataSources.java:135)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.(EntityManagerFactoryBuilderImpl.java:185)
at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:34)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:165)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:160)
at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:135)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:50)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:268)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
... 26 more
</pre>
<p><strong>applicationContext.xml</strong>
<div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean id="dao" class="toto.tata.titi.dao.BanqueDaoImpl" />
<bean id="metier" class="toto.tata.titi.metier.BanqueMetierImpl">
<!-- injection de dependance -->
<!-- on associe objet dao a objet metier -->
<property name="dao" ref="dao"></property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/banque5" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="persistenceUnitManager"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>persistence.xml</value>
</list>
</property>
<property name="defaultDataSource" ref="dataSource"></property>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager"></property>
<property name="persistenceUnitName" value="MY_P_U"></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:annotation-config></context:annotation-config>
</beans></code></pre>
</div>
</div>
</p>
<p><strong>persistence.xml</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<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">
<persistence-unit name="MY_P_U" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence></code></pre>
</div>
</div>
</p> | 1 |
MySQL not able to execute INSERT INTO [table]. Column count doesn't match value count at row 1 | <p>I'm trying to pull information from an HTML form and put this into a database using the following code:</p>
<pre><code>$link = mysqli_connect("localhost", "user", "password", "MyDB");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob' '$addr')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
}else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
</code></pre>
<p>It was working, and I've managed to get 2 test runs in, but now I'm getting the following error at the top of my submission page</p>
<blockquote>
<p>ERROR: Could not able to execute INSERT INTO MyDB (name, email, dob,
address) VALUES ('test name', '[email protected]', '2003-02-01'
'address'). Column count doesn't match value count at row 1</p>
</blockquote>
<p>I have another variant of this which sends a PHP email, which is the file I'm using to base this database connection on. </p>
<p>There is also an autoincrement on ID column which is set as the primary key in the database if that makes a difference? SQL isn't my strong point unfortunately! </p> | 1 |
gradle determine if on 32bit or 64bit windows system | <p>I am building a java application and copying some native dll's before packaging with java packager. </p>
<p>How can I determine in gradle if the build system is 32bit or 64bit so that I can copy the right dll files? At the moment I am manually setting a variable when I remember.</p> | 1 |
Accessing localhost server(xampp) from another one(phonegap) on same pc | <p>I have on my machine XAMPP running through port 80, and now I'm running a PhoneGap app in port 3000. I'd like to request info from the PhoneGap app to my xampp server, but I don't have any answer from it. I don't know if I have permission problems, since no error shows up, but I tried changing httpd.conf and httpf-xampp.conf files with no result. I tried requesting info from 192.168.0.103:80 and 192.168.0.103 being it my local ip. Example: <code><img scr="192.168.0.103/myserver/images/myimage.jpg></code> or even</p>
<pre><code>$.post('192.168.0.103:80/myserver/handler.php', { 'i' : x })
</code></pre>
<p>and neither give any results. Is there some step to access the server that I don't know of? I'd really appreciate any directions.</p>
<p>Edit: I have just tried to run the Phonegap server on another pc. The pc can access the xampp server through the browser, but the phonegap server can't. Is it possible for xampp to be blocking requests from port 3000? If so, what can I do?</p> | 1 |
Compare two integer objects for equality regardless of type | <p>I'm wondering how you could compare two boxed integers (either can be signed or unsigned) to each other for equality.</p>
<p>For instance, take a look at this scenario: </p>
<pre><code>// case #1
object int1 = (int)50505;
object int2 = (int)50505;
bool success12 = int1.Equals(int2); // this is true. (pass)
// case #2
int int3 = (int)50505;
ushort int4 = (ushort)50505;
bool success34 = int3.Equals(int4); // this is also true. (pass)
// case #3
object int5 = (int)50505;
object int6 = (ushort)50505;
bool success56 = int5.Equals(int6); // this is false. (fail)
</code></pre>
<p>I'm stumped on how to reliably compare boxed integer types this way. I won't know what they are until runtime, and I can't just cast them both to <code>long</code>, because one could be a <code>ulong</code>. I also can't just convert them both to <code>ulong</code> because one could be negative.</p>
<p>The best idea I could come up with is to just trial-and-error-cast until I can find a common type or can rule out that they're not equal, which isn't an ideal solution.</p> | 1 |
How to clear pre tag in html | <p>Im using PRE tag of HTML and I need on click to clear the content of it,
I've tried the following without success.</p>
<pre><code>$('#display').clear;
$('#display').val("");
</code></pre>
<p>In the index html I use it like this</p>
<pre><code><pre id="display"></pre>
</code></pre> | 1 |
express-flash message not working with passport custom callback | <p>I'm using express 4, passport and express-flash. When I use the canned passport middleware function and set failureFlash: true, all works fine. But when I use a custom callback in my register function in the same routes file it doesn't work. The messages.info object is null.</p>
<p>This works fine:</p>
<pre><code> router.post('/login', passport.authenticate('local-login', {
successRedirect: '/dashboard',
failureRedirect: '/login',
failureFlash: true
}),
function(req, res){
}
);
</code></pre>
<p>This results in my messages.info object being null:</p>
<pre><code> router.post('/register', function(req, res, next){
passport.authenticate('local-signup', function(err, user, info){
if(err){
req.flash('info', err);
res.render('register');
}else{
res.render('profile');
}
})(req, res, next);
});
</code></pre>
<p>I'm using jade as my preprocessor:</p>
<pre><code> if (messages.info)
.message.info
span= messages.info
</code></pre>
<p>No worky!</p> | 1 |
"SyntaxError: Unexpected token" when compiling VS2015 ios cordova app for local device | <p>When compiling cordova iOS apps using VS2015 (Tools for Apache Cordova Update 6, 60128.14, release 2/3/2016) for a local device, I'm getting the following error:</p>
<pre><code>1> ------ Platform ios already exists
1> ------ Updating plugins
1> SyntaxError: Unexpected token a
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
</code></pre>
<p>What's odd is that the project compiles and deploys successfully to the local iPhone exactly once. On the next compile, this error occurs.</p> | 1 |
Postgresql 9: substring with regex to get string between string and pipe | <p>I need to create a query using the <code>SUBSTRING</code> function in Postgresql 9.x to extract a substring between a string and first pipe occurrence.</p>
<p>My source string is something like this:</p>
<pre><code>THIS IS MY EXAMPLE|OTHER EXAMPLE|HELLO: Kevin|OTHER EXAMPLE|OTHER EXAMPLE
</code></pre>
<p>So I created this query:</p>
<pre><code>SELECT SUBSTRING(myField from 'HELLO: (.*)\|') AS test FROM myTable
</code></pre>
<p>to get the word <code>Kevin</code> between the string <code>'HELLO: '</code> and the first occurrence of character pipe, but it doesn't work as intended because it returns <code>Kevin|OTHER EXAMPLE|OTHER EXAMPLE</code>.</p>
<p>Where am I going wrong?</p> | 1 |
How to crop away convexity defects? | <p>I'm trying to detect and fine-locate some objects in images from contours. The contours that I get often include some noise (maybe form the background, I don't know). The objects should look similar to rectangles or squares like:</p>
<p><a href="https://i.stack.imgur.com/C6NRR.png"><img src="https://i.stack.imgur.com/C6NRR.png" alt="enter image description here"></a> </p>
<p>I get very good results with shape matching (<code>cv::matchShapes</code>) to detect contours with those objects in them, with and without noise, but I have problems with the fine-location in case of noise.</p>
<p>Noise looks like:</p>
<p><a href="https://i.stack.imgur.com/F2Xv3.png"><img src="https://i.stack.imgur.com/F2Xv3.png" alt="enter image description here"></a> or <a href="https://i.stack.imgur.com/1xeKN.png"><img src="https://i.stack.imgur.com/1xeKN.png" alt="enter image description here"></a> for example.</p>
<p>My idea was to find convexity defects and if they become too strong, somehow crop away the part that leads to concavity. Detecting the defects is ok, typically I get two defects per "unwanted structure", but I'm stuck on how to decide what and where I should remove points from the contours.</p>
<p>Here are some contours, their masks (so you can extract the contours easily) and the convex hull including thresholded convexity defects:</p>
<p><a href="https://i.stack.imgur.com/8G14e.png"><img src="https://i.stack.imgur.com/8G14e.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/KLVem.png"><img src="https://i.stack.imgur.com/KLVem.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/ErwpG.png"><img src="https://i.stack.imgur.com/ErwpG.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/YD6Kn.png"><img src="https://i.stack.imgur.com/YD6Kn.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/stLdf.png"><img src="https://i.stack.imgur.com/stLdf.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/3Mx6w.png"><img src="https://i.stack.imgur.com/3Mx6w.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/zSTCu.png"><img src="https://i.stack.imgur.com/zSTCu.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/kTouF.png"><img src="https://i.stack.imgur.com/kTouF.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/58FoY.png"><img src="https://i.stack.imgur.com/58FoY.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/MRsr3.png"><img src="https://i.stack.imgur.com/MRsr3.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/cigBO.png"><img src="https://i.stack.imgur.com/cigBO.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/lFoa7.png"><img src="https://i.stack.imgur.com/lFoa7.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/90DVn.png"><img src="https://i.stack.imgur.com/90DVn.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/InJNh.png"><img src="https://i.stack.imgur.com/InJNh.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/V6QHn.png"><img src="https://i.stack.imgur.com/V6QHn.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/HMOrr.png"><img src="https://i.stack.imgur.com/HMOrr.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/TTARo.png"><img src="https://i.stack.imgur.com/TTARo.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/N6bpe.png"><img src="https://i.stack.imgur.com/N6bpe.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/KjW0X.png"><img src="https://i.stack.imgur.com/KjW0X.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/G4F5A.png"><img src="https://i.stack.imgur.com/G4F5A.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/mIztA.png"><img src="https://i.stack.imgur.com/mIztA.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/d8wz8.png"><img src="https://i.stack.imgur.com/d8wz8.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/vIkRl.png"><img src="https://i.stack.imgur.com/vIkRl.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/Ic8z1.png"><img src="https://i.stack.imgur.com/Ic8z1.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/xO8Zx.png"><img src="https://i.stack.imgur.com/xO8Zx.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/B93t6.png"><img src="https://i.stack.imgur.com/B93t6.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/jbWSS.png"><img src="https://i.stack.imgur.com/jbWSS.png" alt="enter image description here"></a></p>
<p>Could I just walk through the contour and locally decide whether a "left turn" is performed by the contour (if walking clockwise) and if so, remove contour points until the next left turn is taken? Maybe starting at a convexity defect?</p>
<p>I'm looking for algorithms or code, programming language should not be important, algorithm is more important.</p> | 1 |
Mongoose findOneAndUpdate always creating a new document | <p>I am trying this :</p>
<pre><code>var query= {'boardUrl':data.url,'shapes':data.canvas};
Shape.findOneAndUpdate(query,query,{upsert:true},function(err,doc){
if (err){
console.log(err);
}
});
</code></pre>
<p>What I want is to check if in my Shapes collection there is already a document with with the same boardUrl and update it. If not present, create a new document with the the boardUrl and shapes.</p>
<p>My Shape collection is as follows :</p>
<pre><code>var shapeSchema = mongoose.Schema({
boardUrl: String,
shapes: String
});
</code></pre>
<p>A new document is being created at all times. Could you guys see what's wrong with my query?
Thanks</p> | 1 |
Sublime color scheme for XML with Unicode node name | <p>If I use node name in ASCII, I have a nice view:</p>
<p><a href="https://i.stack.imgur.com/8GN72.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8GN72.png" alt="enter image description here"></a></p>
<p>but if I use Unicode node name it is not pretty:</p>
<p><a href="https://i.stack.imgur.com/M7xuS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M7xuS.png" alt="enter image description here"></a></p>
<p>How can I fix this?</p> | 1 |
How to fetch scope value from one controller to another controller in angular JS | <p>How to fetch the scope value from one controller to another controller
<strong>html</strong></p>
<pre><code><button class="btn btn-info" ng-click="setLanguage('en')">English</button>
<button class="btn btn-info" ng-click="setLanguage('de')">Danish</button>
</code></pre>
<p><strong>Javascript</strong></p>
<pre><code> .controller('demoCtrl', function($scope) {
$scope.setLanguage = function(language) {
$scope.language = language;
}
});
</code></pre> | 1 |
Calculate / Estimate the compressed file size without performing compression | <p>I want to calculate / estimate what would be the file size of image (.jpg) after doing compression with Encoder.Quality value.
Here I should not perform any compression before estimating, Is there any formula to do it?</p>
<p>Is there any rough estimate. I want to reduce image file size to < 250kb with out doing iterative compression.</p>
<p>Is there any Encoder.Quality value estimation based on image(jpg) width, height and depth (dpi) , etc...</p>
<p>Thanks in advance.</p> | 1 |
Countif query in access | <p>I am trying to run a query that calculate with a countif function but I am having trouble with it. I have used the count and the iif functions in the builder but I think something weird is going on. I am trying to count the number of times a certain value occurs in a column so I do not want a specific value to equal to if that's possible?</p>
<p>Thanks!</p> | 1 |
Windows: Create folder structure based on XML file | <p>I'm trying to find a way to create a full folder/subfolders/files(shortcuts) arborescence in Windows, based on an XML file input.</p>
<p>My XML looks like this:</p>
<pre><code><folder name="Folder1">
<shortcut url="http://A.com" name="A" />
<shortcut url="http://B.com" name="B" />
<folder name="1.1">
<shortcut url="http://C.com" name="C" />
</folder>
<folder name="Folder1.2">
<shortcut url="http://D.com" name="D" />
</folder>
</folder>
<folder name="Folder2">
...
</folder>
</code></pre>
<p>And the resulting folders would be:</p>
<ul>
<li>Folder1
<ul>
<li>A.url</li>
<li>B.url</li>
<li>Folder1.1
<ul>
<li>C.url</li>
</ul></li>
<li>Folder1.2
<ul>
<li>D.url</li>
</ul></li>
</ul></li>
<li>Folder2
<ul>
<li>...</li>
</ul></li>
</ul>
<p>-> To sum up, recursive folders/subfolders creation, plus creation of shortcuts (.url files)</p>
<p>Any idea on how to do this?
Via cmd, powershell ?</p>
<p>(if .url files creation in not possible, i'll make them manually (more than 300...) )</p>
<p>Many thanks!</p>
<hr/>
<p>EDIT: SOLUTION</p>
<p>Thanks @rojo, good direction.
I've modified my need of creation "Shortcuts" by html files. (content truncated here, just for sample)
I've added a target path, several errors handling (folders and files creation, by creating error txt files, easily searchable to fix manually), as well as added the creation of files at root. (not in subfolders)</p>
<p>Probably not very optimized, but well...</p>
<pre><code><# : Batch Portion
@echo off & setlocal
powershell -noprofile -noexit -noninteractive "iex (gc \"%~f0\" | out-string)"
goto :EOF
: End Batch / begin PowerShell hybrid chimera #>
[xml]$DOM = gc clv.xml
$destPath="D:\Test\Folders"
function CreateShortcut([string]$target, [string]$saveLoc, [string]$fileName) {
$aspxText= @"
<html>
<body>
<a href="$target">Target URL</a>
</form>
</body>
</html>
"@
try{
New-Item ($saveLoc+'/'+$fileName+'.aspx') -type file -value $aspxText -ea Stop
}
catch{
$err=@"
Name:
$fileName
Url:
$target
Error:
$_.Exception.GetType().FUllname
"@
New-Item ($saveLoc+'/###Error.txt') -type file -value $txtDoc
}
write-host "$($saveLoc)\$($fileName)" -f cyan
}
cd $destPath
function launchCreation($root){
$rootshortcuts = @($root.shortcut)
if($rootshortcuts -ne $null){
foreach ($shortcut in $rootshortcuts) {
$fixedShortcutName=$shortcut.name -replace '[<>:"\/\\?\*\|]', '-'
$urlfile = (pwd).Path
CreateShortcut $shortcut.url $urlfile $fixedShortcutName $shortcut.isDoc $shortcut.isTaxo
}
}
Walk($root)
}
function Walk($root) {
$folders = @($root.folder)
if($folders -ne $null){
foreach ($folder in $folders) {
$folderName=$folder.name -replace '[<>:"\/\\?\*\|]', '-'
if (-not (test-path $folderName)) { md $folderName }
cd $folderName
write-host (Join-Path $destPath $folderName) -f magenta
$shortcuts = @($folder.shortcut)
if($shortcuts -ne $null){
foreach ($shortcut in $shortcuts) {
$fixedShortcutName=$shortcut.name -replace '[<>:"\/\\?\*\|]', '-'
$urlfile = (pwd).Path
CreateShortcut $shortcut.url $urlfile $fixedShortcutName $shortcut.isDoc $shortcut.isTaxo
}
}
Walk $folder
cd..
}
}
}
[void](launchCreation $DOM.documentElement)
</code></pre> | 1 |
Start an app daily / on a specific time | <p>I know that an application can be started on boot by receiving the intent <code>RECEIVE_BOOT_COMPLETED</code>.</p>
<p><a href="http://developer.android.com/reference/android/Manifest.permission.html#RECEIVE_BOOT_COMPLETED" rel="nofollow">Documentation link</a></p>
<p>I am developing an app which I want to start daily say at 6 AM.</p>
<p>My question is, is <code>RECEIVE_BOOT_COMPLETED</code> enough for this? I mean suppose user doesn't reboots the phone daily. So how to make sure that my app is started daily in the morning ?</p>
<p>As far as I know an alternative is to keep running a service such as <a href="http://developer.android.com/training/run-background-service/create-service.html" rel="nofollow">this</a> </p>
<p>But if I use that how much resource you think it will consume slowing down overall performance (keeping in mind my app runs always) ?</p>
<p>Thanks in advance. </p> | 1 |
Difference between Git, Github and Github Desktop for Windows/Linux/Mac | <p>I am a very new bie to Git and coming from a TFS background and trying to get on speed with Github. while reading about it,
what I learnt is the following:-
Github is a web based service for Hosting Git repos.
Git is Local Version Control System,</p>
<pre><code>Q1: How could Git track the changes on a local machine without server?
</code></pre>
<p>Git and GitHub are not tightly coupled, meaning Git need not be necessarily using Github</p>
<p>The Git I installed was downloaded from <a href="http://git-scm.com/download" rel="nofollow">here</a>
I also found Github for Windows client <a href="https://desktop.github.com/" rel="nofollow">here</a>
So my Question boils to</p>
<pre><code>Q2:How the two client installers above are different and when to use which one?
</code></pre> | 1 |
Plotting Time Series Values using Bar Chart | <p>I'd like to plot some time series data using a bar chart to show the changes over time, but I'm having trouble doing it with ggplot2. </p>
<p>Sample Data:</p>
<pre><code>df <- structure(list(year = c(1910, 1911, 1912, 1913, 1914, 1915, 1916,
1917, 1918, 1919, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1927,
1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938,
1939, 1940, 1941, 1942, 1943, 1944, 1945, 1946, 1947, 1948, 1949,
1950, 1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918),
dday_30 = c(48.3156566976744, 28.4325095348837, 10.9345420465116,
30.3018175813953, 22.3314346511628, 6.33566069767442, 27.4823442325581,
23.7263461860465, 20.3016930232558, 38.8897564651163, 6.69049065116279,
18.4395965581395, 25.8079846046512, 3.57936218604651, 16.6990909767442,
21.2175313023256, 15.2260691627907, 9.26520976744186, 9.79716334883721,
18.9872194883721, 22.5747300465116, 47.8516541860465, 30.8272055348837,
28.0607320930233, 50.1987654883721, 29.4361414418605, 58.4356670232558,
45.2513310697674, 29.4801361860465, 44.2652285116279, 38.7353984186047,
17.164524372093, 18.8734693488372, 38.7099044186047, 26.9970333953488,
13.3448749767442, 31.4876399534884, 29.700936, 26.0668504651163,
24.7630490232558, 15.4445029767442, 37.5025793548387, 22.0377372580645,
8.63075717741935, 24.8010268548387, 15.4514439516129, 5.60195516129032,
21.3893638709677, 18.4909673387097, 19.3719947580645)), .Names = c("year",
"dday_30"), row.names = c(NA, 50L), class = "data.frame")
</code></pre>
<p>Here's what I've tried:</p>
<pre><code>ggplot(stack, aes(x = year, y = dday_30)) + geom_bar()
</code></pre>
<p>But's telling me there cannot be a <code>y aesthetic</code>:</p>
<blockquote>
<p>Error: stat_count() must not be used with a y aesthetic.</p>
</blockquote>
<p>Is there a way to do this with time series data?</p> | 1 |
Wordpress Custom Url Routing | <p>I have a requirement that all urls have a variable at the end and all resolve to the same controller/view</p>
<p>so for example we have the following URL's:</p>
<pre><code>http://example.com/users/joe
http://example.com/users/sam
http://example.com/users/jack
</code></pre>
<p>All three URLS should resolve to the same controller, where I would apply some logic to render each page differently based on the username.</p>
<p>How can I achieve this type of routing on Wordpress?</p> | 1 |
jQuery validator - Check input field after leaving focus | <p>I want to check if the input field <code>inlineViewProvider_ONLYOFFICE_URL</code> starts with <code>https://</code> - after leaving focus of the field.</p>
<p>Here's my code so far:</p>
<pre><code>$(document).ready(function() {
jQuery.validator.addMethod("httpsStarting", function (fieldInput, element) {
return this.optional(element) || fieldInput.match("^https:\/\/");
}, "Field input should start with 'https://'.");
$('#inlineViewProvider_ONLYOFFICE_URL').validate({
rules : { inlineViewProvider_ONLYOFFICE_URL: { httpsStarting: true } }
});
});
</code></pre>
<p>If I put a <code>console : console.log($('#inlineViewProvider_ONLYOFFICE_URL'))</code> inside the <code>rules</code> value, the field value is printed to the console. But there is no error message if the input field doesn't start with <code>https://</code>.</p> | 1 |
ffmpeg based multi threaded c++ application fails on decoding | <p>I am using remuxing example from ffmpeg sources as reference. I wrote a multi-threaded application based on boost threads to perform a codec copy and remux using ffmpeg API. That works fine . The problem arises when I try to decode the frame </p>
<p>"</p>
<pre><code> ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, &pkt);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Error decoding video %s\n",av_make_error_string(errorBuff,80,ret));
return -1;
}"
</code></pre>
<p>I need the decoded frame to convert it to Opencv Mat object. For a single instance this code works fine. But as soon as I run multiple threads I start getting decoding errors like these</p>
<pre><code> left block unavailable for requested intra mode at 0 0
[h264 @ 0x7f9a48115100] error while decoding MB 0 0, bytestream 1479
[h264 @ 0x7f9a480825e0] number of reference frames (0+2) exceeds max (1; probably corrupt input), discarding one
[h264 @ 0x7f9a480ae680] error while decoding MB 13 5, bytestream -20
[h264 @ 0x7f9a48007700] number of reference frames (0+2) exceeds max (1; probably corrupt input), discarding one
[h264 @ 0x7f9a48110340] top block unavailable for requested intra4x4 mode -1 at 31 0
[h264 @ 0x7f9a48110340] error while decoding MB 31 0, bytestream 1226
[h264 @ 0x7f9a48115100] number of reference frames (0+2) exceeds max (1; probably corrupt input), discarding one
[h264 @ 0x7f9a480825e0] top block unavailable for requested intra4x4 mode -1 at 4 0
[h264 @ 0x7f9a480825e0] error while decoding MB 4 0, bytestream 1292
[h264 @ 0x7f9a480ae680] number of reference frames (0+2) exceeds max (1; probably corrupt input), discarding one
</code></pre>
<p>All variables used by ffmpeg api are declared local to the thread function. I am not sure how ffmpeg frame allocs or context allocs work.</p>
<p>any help in making the decoding process multi-threaded ?</p>
<p><strong>Update:</strong>
I have included ff_lockmgr</p>
<pre><code>static int ff_lockmgr(void **mutex, enum AVLockOp op)
{
pthread_mutex_t** pmutex = (pthread_mutex_t**) mutex;
switch (op) {
case AV_LOCK_CREATE:
*pmutex = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(*pmutex, NULL);
break;
case AV_LOCK_OBTAIN:
pthread_mutex_lock(*pmutex);
break;
case AV_LOCK_RELEASE:
pthread_mutex_unlock(*pmutex);
break;
case AV_LOCK_DESTROY:
pthread_mutex_destroy(*pmutex);
free(*pmutex);
break;
}
return 0;
}
</code></pre>
<p>and initialized it as well "<code>av_lockmgr_register(ff_lockmgr);</code>"
Now the video is being decoded in all threads BUT the images saved from the decoded frame using FFMPEG AVFrame to OpenCv Mat conversion and imwrite results in garbled (mixed) frame. Part of the frame is from one camera and rest is from another or the image doesnt make any sense at all.</p> | 1 |
Datetime format with time zones | <p>I am pulling date from API as a string in this format: <code>yyyy-MM-dd'T'HH:mm:ss'Z'</code></p>
<p>The problem is when I try to save it, let's say today <code>2015-01-23T13:42:00Z</code> the flags <code>Z</code> and <code>T</code> are not shown in MySQL database (the date is saved like this <code>2015-01-23 13:42:00</code>).</p>
<p>I would like to keep the field date type, i.e. I don't want to save the date into <code>varchar</code> field.</p>
<p>I am not familiar with date timezone format, so any suggestions are welcome.</p> | 1 |
Apache Camel and IBM MQ | <p>Looking for some examples for integration between Apache Camel and IBM MQ.</p>
<p>Apache camel acting as middleware router between MQ and our java based socket application. </p> | 1 |
Should the trusted Root CA be a part of the certificate chain? | <p>I'm setting up 2-way SSL communication between services on different hosts. Let's say I have my own CA called A. A is trusted by all of my services through a centralized jks. Now let's say I have certificate B signed by A. When services send the certificate should they be sending the entire chain B - A, or just B? I believe both tend to work with most implementations.</p>
<p>I tried to find canonical information about this online, but I'm coming up with nothing.</p>
<p>Thanks for the help</p> | 1 |
How does window.open(data:application) Export to Excel | <p>Trying to search for a way to send an HTML table to Excel, I came across <strong><em><a href="http://jsfiddle.net/jWAJ7/2054/" rel="nofollow noreferrer">this fiddle</a></em></strong></p>
<pre><code>window.open('data:application/vnd.ms-excel,' + $('#whatever').html());
</code></pre>
<p>I was surprised to find out it was just that simple and I was wondering if anyone could explain how this works. The documentation for window.open doesn't appear to list an explanation under msdn <a href="https://msdn.microsoft.com/en-us/library/windows/apps/hh453415.aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/windows/apps/hh453415.aspx</a> or mozilla developer network <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/open" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/Window/open</a> </p>
<p>It could be that I'm not phrasing my question correctly that's preventing me from finding an answer, but I guess I'm just curious how I can utilize this in the future to export html to excel and other file formats or if I shouldn't touch it(for instance if it's something that was abandoned and should never be used)</p>
<p>I've also looked at several other posts such as <a href="https://stackoverflow.com/questions/13710405/javascript-table-export-to-excel">JavaScript table export to excel</a> and <a href="https://stackoverflow.com/questions/16982872/export-to-excel-using-javascript">export to excel using javascript</a> and though they may answer the questions, I'm asking specifically about what's happening in the above code because it's so simple and concise.</p> | 1 |
Dynamic CSS background image in Wordpress | <p>I just set up WordPress and tried to install a theme. All is good, but for one simple issue. I know how to make an image dynamic a image in the beginning to set up my index.php, like this:</p>
<pre><code><img src="<?php echo get_template_directory_uri(); ?>/img/logo.png" alt="" />
</code></pre>
<p>but how to make an image dynamic which is called by css</p>
<pre><code>.portfolio {
background-attachment: fixed;
background-image: url("../img/o-BUSINESS-TECHNOLOGY-facebook.jpg");
}
</code></pre>
<p>I've tried so many times but fail. Please suggest some ideas.</p> | 1 |
Cannot Change the Version of R in RStudio | <p>My RStudio (V 0.99.491) is inept to change the R Version.
I act in the ordinary way through <code>Global Options --> R-Version</code>. Afterwards it hangs and doesn't work or react any more. The initial version of R which works fine is <code>R 3.1.0</code>. I have never had such a problem before. Maybe someone has faced with a similar problem. </p>
<p>I tried to uninstall RStudio, and install it again, but this hasn't help to fix the issue.</p> | 1 |
AttributeError: module 'pydot' has no attribute 'graph_from_dot_data' in spyder | <p>I am trying to run the following code:</p>
<pre><code>from sklearn.datasets import load_iris
from sklearn import tree
import pydot
clf = tree.DecisionTreeClassifier()
iris = load_iris()
clf = clf.fit(iris.data, iris.target)
from sklearn.externals.six import StringIO
from pydot import *
dotfile = StringIO()
tree.export_graphviz(clf, out_file = dotfile)
pydot.graph_from_dot_data(dot_data.getvalue()).write_png("dtree2.png")
</code></pre>
<p>and i get the following error:
AttributeError: module 'pydot' has no attribute 'graph_from_dot_data'</p>
<p>I have tried hard to find the solution but could not be able to do so. Please someone help me in this regard.</p> | 1 |
Difference between "alert(a)'' and ''alert(a);var a =1;'' in javascript? | <pre><code><script type="text/javascript">
alert(a);
</script>
</code></pre>
<p>Console log shows : "Uncaught ReferenceError: a is not defined";</p>
<pre><code><script type="text/javascript">
alert(a);
var a = 1;
</script>
</code></pre>
<p>at the middle of the browse, Log shows: "undefined"</p>
<p>How does this code run in js and what causes this difference</p> | 1 |
Trying to build shared library in CLion/CMake | <p>I've been trying to download and build the <a href="https://github.com/stepp/stanford-cpp-library/tree/master/StanfordCPPLib" rel="nofollow noreferrer">Stanford Library</a> source files and build a library out of them to use for my own project using the CLion (IDE). I've been following instructions from <a href="https://stackoverflow.com/questions/17511496/create-a-shared-library-with-cmake">this</a> answer and my CMakeLists file looks like this:</p>
<pre><code>cmake_minimum_required(VERSION 3.3)
project(Stanford)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(CMAKE_BUILD_TYPE Release)
file(GLOB MyHeaders "*.h" /stacktrace/"*.h" private/"*.h")
file(GLOB MySources "*.cpp" /stacktrace/"*.cpp" private/"*.cpp")
include_directories(MyHeaders)
add_library(Stanford SHARED ${MySources} ${MyHeaders})
target_include_directories (Stanford PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
</code></pre>
<p>When opening the run menu, I get the following:<a href="https://i.stack.imgur.com/1AuTm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1AuTm.png" alt="Screenshot 1"></a></p>
<p>If I tell it to build anyway I get the following errors.</p>
<p><a href="https://i.stack.imgur.com/zKL0W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zKL0W.png" alt="enter image description here"></a></p>
<p>I've been struggling to find out what why I need an executable to build a library and what those undefined references mean.</p> | 1 |
comma seperated values in string to vector - Java | <p>In java how can i convert a string with comma separating values into a vector. So when a comma is encountered in the string, that value is added to the vector </p> | 1 |
How can I create an argparse mutually exclusive group with multiple positional parameters? | <p>I'm trying to parse command-line arguments such that the three possibilities below are possible:</p>
<pre><code>script
script file1 file2 file3 …
script -p pattern
</code></pre>
<p>Thus, the list of files is optional. If a <code>-p pattern</code> option is specified, then nothing else can be on the command line. Said in a "usage" format, it would probably look like this:</p>
<pre><code>script [-p pattern | file [file …]]
</code></pre>
<p>I thought the way to do this with Python's <code>argparse</code> module would be like this:</p>
<pre><code>parser = argparse.ArgumentParser(prog=base)
group = parser.add_mutually_exclusive_group()
group.add_argument('-p', '--pattern', help="Operate on files that match the glob pattern")
group.add_argument('files', nargs="*", help="files to operate on")
args = parser.parse_args()
</code></pre>
<p>But Python complains that my positional argument needs to be optional:</p>
<pre><code>Traceback (most recent call last):
File "script", line 92, in <module>
group.add_argument('files', nargs="*", help="files to operate on")
…
ValueError: mutually exclusive arguments must be optional
</code></pre>
<p>But the <a href="https://docs.python.org/3/library/argparse.html#nargs">argparse documentation</a> says that the <code>"*"</code> argument to <code>nargs</code> meant that it is optional.</p>
<p>I haven't been able to find any other value for <code>nargs</code> that does the trick either. The closest I've come is using <code>nargs="?"</code>, but that only grabs one file, not an optional list of any number.</p>
<p>Is it possible to compose this kind of argument syntax using <code>argparse</code>?</p> | 1 |
How can I retrieve the data from a bluetooth device? | <p>I have a bluetooth device, in particular a Heart Rate Measurement.</p>
<p>The bluetooth standard for these kind of device is the 180D 2A37. </p>
<p>This is the link: <a href="https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml" rel="nofollow">https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml</a></p>
<p>I would like to get the measurements. How can I do?</p>
<p>At the moment, I am able to connect and pair with my device using the Bluetooth API (<code>BluetoothSocket</code>)</p> | 1 |
DBeaver simple query ORA-00911 invalid character | <p>I am switching from SQLDeveloper to DBeaver in my work with Oracle 10G database, have the Oracle instantclient for the exact version of the database.</p>
<p>I do not make scripts, just a bunch of queries, like select, update. I had a collection of them, each on one or few lines, with semicolon at the end, followed by two dashes and comment.
Multiple line statements for visual separation separated with lines of many dashes.</p>
<p>SQLDeveloper treated such a system well, CTRL+Enter executed only that line (or group from last comment or semicolon to the next semicolon), ignored comment after or before. So I copied the whole collection from the one programs main window to the other (SQL Editor). Usage results are weird.</p>
<p>Example in new SQL Editor tab (table names changed, so ignore if I got some reserved words):</p>
<pre><code>select * from FILE_MOVEMENT where MOVEMENT_STATUS != 'MOVED' and LAST_UPDATE > sysdate -10 order by LAST_UPDATE desc;--My comment, explanation
select * from ACTIVITY where ACTIVITY_TYPE = 'GENERATOR' and STATUS = 'CREATED' and STARTED > sysdate -10 order by STARTED desc;--My other comment
</code></pre>
<p>The first one executes as expected with CTRL+Enter, line start flashes with single triangle and the Execution log shows only my command until the semicolon.
But when cursor placed at second line followed by CTRL+Enter, I get triangles before both lines, all after first lines semicolon until second lines end including both comments gets selected and ORA-00911 pops up. The selected text shows up in Execution log.</p>
<p>If I put an empty line between them, then whole second line gets selected and logged and same error pops up.</p>
<p>What to do to stop such behaviour and make the second line also execute same way as first - without previous and next comment? Is there some language or line end or comment settings in DBeaver I have missed?</p> | 1 |
Python While loops with tuples | <p>I am writing a function which should count the numbers in an inputted phrase. That phrase gets stored as a tuple and the while loop should count the number of vowels. So far I have gotten this.</p>
<pre><code>def whilephrase():
vowels=['A','a','E','e','I','i','O','o','U','u']
print('Please give me a phrase')
inputphrase=input()
inputphrase=tuple(inputphrase)
i=0
while True:
if vowels in inputphrase:
i=i+1
else:
print(i)
</code></pre>
<p>But this just prints out an endless loop of zeros.</p> | 1 |
How to crop an image into a circle button in xml Android studio? | <p>hey guys so I'm trying to make this circle button. And in that circle I want to put an image, like a person's profile picture. So if someone uploads an image, I need to be able to adjust the size and crop it and put it into a circle. Below is an example of what I am trying to accomplish. And behind the circle is a red circle, just for aesthetics. Hope you guys can give me some insight or direction. <a href="https://i.stack.imgur.com/Bh9fv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bh9fv.png" alt="enter image description here"></a></p> | 1 |
Current thread has not called Looper.prepare(). Forcing synchronous mode | <p>I am getting <code>Current thread has not called Looper.prepare(). Forcing synchronous mode</code> warning in logcat.So that I can't get into onsuccess response handler.</p>
<p>I referred this <a href="https://stackoverflow.com/questions/3875184/cant-create-handler-inside-thread-that-has-not-called-looper-prepare">post</a>.But it didn't worked for me.</p>
<p><strong>Stacktrace:</strong></p>
<pre><code>01-19 22:52:30.683: W/AsyncHttpRH(23815): Current thread has not called Looper.prepare(). Forcing synchronous mode.
01-19 22:52:30.685: W/System.err(23815): java.lang.IllegalArgumentException: Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead.
01-19 22:52:30.686: W/System.err(23815): at com.loopj.android.http.AsyncHttpClient.sendRequest(AsyncHttpClient.java:1493)
01-19 22:52:30.686: W/System.err(23815): at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1078)
01-19 22:52:30.686: W/System.err(23815): at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1052)
01-19 22:52:30.686: W/System.err(23815): at agriya.talkr.localdb.RestClient.get(RestClient.java:29)
01-19 22:52:30.686: W/System.err(23815): at agriya.talkr.localdb.ServerCallee.execute(ServerCallee.java:77)
01-19 22:52:30.686: W/System.err(23815): at agriya.talkr.CreateGroup$synchronizeInBg.doInBackground(CreateGroup.java:213)
01-19 22:52:30.686: W/System.err(23815): at agriya.talkr.CreateGroup$synchronizeInBg.doInBackground(CreateGroup.java:1)
01-19 22:52:30.686: W/System.err(23815): at android.os.AsyncTask$2.call(AsyncTask.java:292)
01-19 22:52:30.686: W/System.err(23815): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-19 22:52:30.686: W/System.err(23815): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-19 22:52:30.686: W/System.err(23815): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-19 22:52:30.686: W/System.err(23815): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-19 22:52:30.686: W/System.err(23815): at java.lang.Thread.run(Thread.java:818)
</code></pre>
<p>Below I have posted the code and pointed out the error line:</p>
<p><strong>CreatGroup.java:</strong></p>
<pre><code>public class CreateGroup extends AppCompatActivity {
........
........
@Override
protected String doInBackground(String... params) {
try {
.......
ServerCallee.execute(Constants.SERVER_CALL_newGroup, map); --->213th line
} catch (JSONException e) {
e.printStackTrace();
return "1";
}
</code></pre>
<p><strong>ServerCallee.java:</strong></p>
<pre><code>public static void execute(final Constants _service, HashMap<String, String> params){
........
........
RestClient.get(null, rqm, new JsonHttpResponseHandler(){ --->77th line
........
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
System.out.println("onFailure - String: " + _service.toString());
Log.e("fail 1", "Test");
}
.......(On Success response handler)
</code></pre>
<p><strong>RestClient.java:</strong></p>
<pre><code> public class RestClient {
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get( String url, RequestParams params, final JsonHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler); -->29th line
}
public static void post(final String url, final RequestParams params, final JsonHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
}
</code></pre> | 1 |
scrolling doesn't work even when using <ScrollView> (Android Studio) | <p>I've tried every solution I could find on different sites, but couldn't find anything, hopefully someone here could help me.
There are no errors, just doesn't work to scroll.</p>
<pre><code><LinearLayout 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="385dp"
android:layout_height="540dp"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="gino.navigationface.bar_position"
tools:showIn="@layout/app_bar_bar_position">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/scrollView"
android:padding="10dp"
android:scrollIndicators="top|left|bottom|start|end|right">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="The Queen"
android:id="@+id/textView3"
android:layout_gravity="center_horizontal"
android:textStyle="bold|italic"
android:textSize="30dp"
android:textColor="#c0c0c0" />
<Button
android:layout_width="250dp"
android:layout_height="100dp"
android:text=""
android:background="@drawable/the_queen"
android:id="@+id/queenButton"
android:onClick="theQueen"
android:longClickable="false"
android:nestedScrollingEnabled="true"
android:gravity="center_vertical"
android:foregroundGravity="center_vertical"
android:layout_gravity="center_vertical"
android:layout_marginLeft="50dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Vasa Bar"
android:id="@+id/textView4"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:textStyle="bold|italic"
android:textSize="30dp"
android:textColor="#c0c0c0" />
<Button
android:layout_width="150dp"
android:layout_height="120dp"
android:text=""
android:id="@+id/vasabar"
android:background="@drawable/vasa_bar"
android:onClick="vasaBar"
android:gravity="center_vertical"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:foregroundGravity="center_vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Italienska"
android:id="@+id/textView5"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:textSize="30dp"
android:textStyle="bold|italic"
android:textColor="#c0c0c0" />
<Button
android:layout_width="250dp"
android:layout_height="100dp"
android:id="@+id/button"
android:background="@drawable/italienska"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textView6"
android:layout_gravity="center_horizontal"
android:textSize="30dp"
android:textStyle="bold|italic"
android:textColor="#c0c0c0"
android:layout_marginTop="40dp">
</TextView>
<Button
android:layout_width="200dp"
android:layout_height="200dp"
android:id="@+id/källarn"
android:background="@drawable/kallarn"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</ScrollView>
</LinearLayout>
</code></pre>
<p>If needed I could post screenshots of the app</p> | 1 |
CI integration with Extent Reports using htmlpublisher | <p>I am using HTML publisher plugin in Jenkins, and generating opening Extent Report.
By Report generated with Jenkin don't have UI. However when I open then manually they opens just fine.</p>
<p><a href="http://i.stack.imgur.com/8SweJ.png" rel="nofollow">Click of Report Snapshot</a></p> | 1 |
RecyclerView - animate change of grid layout manager columns | <p>I want to animate the change of my <code>RecyclerView</code>s <code>GridLayoutManager</code>. I defaulty show a list of items in a grid with 3 columns and the user can select to show more or less columns.</p>
<p>I would like the <code>views</code> in the <code>RecyclerView</code> to move/scale to their new positions, but I have no idea how this could be done.</p>
<p><strong>What I want in the end</strong></p>
<ul>
<li>allow to scale the grid via an expand/contract touch gesture => I know how to do that</li>
<li>animate the change of the <code>LayoutManager</code></li>
</ul>
<p><em>Does anyone know how I can animate the change of the <code>LayoutManager</code>?</em></p> | 1 |
Is onChange or onClick deprecated in html GlobalEventHandlers? | <p>I see it used on websites so I"m unsure. Can I use OnChange and onClick inside my html ? I'm a little confused, I thought javascript was deprecated in html ? However, I think these two actions are part of DOM GlobalEventHandlers ? I think jquery uses it alot so I should be fine ? </p>
<pre><code><select id="select" class="button" onChange=getValue()>
</code></pre>
<p>I think what is meant by not using js in html is </p>
<pre><code><p javascript:code> </p>
</code></pre>
<p>Well, I got an error but I think it has to do with the way chrome extension works. I'll have to look into this: </p>
<p>Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.</p> | 1 |
Installing composer.phar | <p>I've been trying to install <code>composer.phar</code> to my <code>HostGator</code> website. However, I come across this error:</p>
<pre><code>[~/public_html/flarum]# php composer.phar install
Loading composer repositories with package information
Installing dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1
- flarum/core v0.1.0-beta.4 requires php >=5.5.9 -> your PHP version (5.4.45) or value of "config.platform.php" in composer.json does not satisfy that requirement.
- flarum/core v0.1.0-beta.3 requires php >=5.5.9 -> your PHP version (5.4.45) or value of "config.platform.php" in composer.json does not satisfy that requirement.
- flarum/flarum-ext-suspend v0.1.0-beta.3 requires flarum/core ^0.1.0-beta.3 -> satisfiable by flarum/core[v0.1.0-beta.3, v0.1.0-beta.4].
- Installation request for flarum/flarum-ext-suspend ^0.1.0 -> satisfiable by flarum/flarum-ext-suspend[v0.1.0-beta.3].
</code></pre>
<p>I have updated my <code>PHP</code> to the newest via the <code>cPanel</code>. </p>
<p>If there is any help at all that I could get on this it would be greatly appreciated!</p> | 1 |
Why laravel model duplicates set of data and how (if possible) to have only one set of data? | <p>It is convenient that laravel model provides a method that it can return results from another associated table.</p>
<p>For example, I have a table called item and another table called feedback, where the feedback table stores feedback of an item in the item table. So, to get the all feedback of item with id 1, I will do:</p>
<pre><code>Item::find(1)->feedback;
</code></pre>
<p>And the following this the printout of the object returned.</p>
<pre><code>Illuminate\Database\Eloquent\Collection Object
( [items:protected] => Array
(
[0] => Feedback Object
(
[table:protected] => feedback
[connection:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[id] => 1
[rma_id] => 3
[item_id] => 8
[quo_id] => 0
[case_id] => i2eM20160120
[line_no] => 000001
[content] => test
[status] => sent
[read] => 0
[sender] => Tester
[created_at] => 2016-01-20 18:03:44
[updated_at] => 2016-01-20 18:03:44
)
[original:protected] => Array
(
[id] => 1
[rma_id] => 3
[item_id] => 8
[quo_id] => 0
[case_id] => i2eM20160120
[line_no] => 000001
[content] => test
[status] => sent
[read] => 0
[sender] => Tester
[created_at] => 2016-01-20 18:03:44
[updated_at] => 2016-01-20 18:03:44
)
[relations:protected] => Array
(
)
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[appends:protected] => Array
(
)
[fillable:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
[dates:protected] => Array
(
)
[touches:protected] => Array
(
)
[observables:protected] => Array
(
)
[with:protected] => Array
(
)
[morphClass:protected] =>
[exists] => 1
)
)
)
</code></pre>
<p>It works fine, and it shows that there is only one feedback on item with id 1. </p>
<p>What concerns me is that the dataset is duplicated in <code>[attributes:protected]</code> and <code>[original:protected]</code>. This is just a testing case and the real case will consist of thousands of feedback and having a duplicated dataset is a huge waste of memory. The dataset is not duplicated if I am using the <code>DB::table('table_name')</code> approach, but that is much less convenient. </p>
<p>Why does laravel need to duplicate the data in model? </p>
<p>And is there a way to make it return only one set of data?</p>
<p>Currently I am using <code>->toArray()</code> to trim down the unnecessary data right after the query, but the memory usage is still there because laravel is still creating that set of data.</p> | 1 |
Using google translate API with cURL | <p>I'm trying to use the Google Translate API to translate text input by the user on my php based website. So far I have:</p>
<pre><code><?php
$google_url = "https://www.googleapis.com/language/translate/v2?key=[API KEY]&q=apple&source=en&target=de";
$handle = curl_init($google_url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
curl_close($handle);
$google_res = $responseDecoded['data']['translations'][0]['translatedText'];
print_r($response);
?>
</code></pre>
<p>This isn't returning anything and I don't know what's wrong. I know that the API is set up correctly as when I enter the url into a browser it returns the following:</p>
<pre><code>{
"data": {
"translations": [
{
"translatedText": "Apfel"
}
]
}
}
</code></pre>
<p>It must be something to do with my code which I took from this <a href="http://www.sitepoint.com/using-google-translate-api-php/" rel="nofollow">This Site</a></p>
<p>Any help would be appreciated as I'm completely stumped. Thanks!</p>
<p>EDIT: thanks to a comment I was able to find out that I'm getting the following cURL error:</p>
<pre><code>Curl error: SSL certificate problem: unable to get local issuer certificate
</code></pre> | 1 |
Send HTTP request using JavaScript? | <p>I'm trying to get a JSON object from <code>http://api.roblox.com/marketplace/productinfo?assetId=361192737</code> (<a href="http://api.roblox.com/marketplace/productinfo?assetId=361192737" rel="nofollow" title="http://api.roblox.com/marketplace/productinfo?assetId=361192737">link</a>) using a GET request, but it doesn't seem to be working.</p>
<pre><code>(function(){
var xmlHttp;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = ProcessRequest;
xmlHttp.open( "GET", 'http://api.roblox.com/marketplace/productinfo?assetId=361192737', true );
xmlHttp.send( null );
function ProcessRequest(){
console.log(xmlHttp.responseText); // "" (empty string)
var respData = JSON.parse(xmlHttp.responseText) || {};
RemoteEvents = JSON.parse(respData.Description) || null;
}
})()
</code></pre>
<p>This is on a Chrome Extension in Development Mode. I'm not very experienced with JavaScript, and even less with HTTP requests. What am I doing wrong?</p> | 1 |
Azure VM connection error - The user account is currently disabled and cannot be used | <p>Using Azure Powershell create a new VM using my own Vhd based on the tutorial:
<a href="https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-create-upload-vhd-windows-server/" rel="nofollow noreferrer">https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-create-upload-vhd-windows-server/</a> </p>
<p>When try to connect to the VM it pops the error:</p>
<blockquote>
<p>The user account is currently disabled and cannot be used.</p>
</blockquote>
<p>Below is the scripts for creating the VM</p>
<pre><code>#create the vm using the image
$image = Get-AzureVMImage $MyImage
$vmname = "Test-Machine"
$vmsize = "Large"
$vm1=New-AzureVMConfig -Name $vmname -InstanceSize $vmsize -ImageName $image.imageName
$vm1 | Add-AzureProvisioningConfig -Windows -AdminUsername $username -Password $password
New-AzureVM –ServiceName $myServiceName -VMs $vm1
</code></pre> | 1 |
Convert a text file to a sql file | <p>I am working on an assignment that open a text file and convert/save as sql file. I got how to open a text file but I am stuck on how to convert to sql file.</p>
<p>Here is code that I got for reading the text file</p>
<pre><code> public static void main(String[] args) {
// The path to open the file.
String fileName = "input.txt";
String line = null;
try {
// The file reads text files
FileReader file = new FileReader(fileName);
// Wrap file in BufferedReader
BufferedReader bufferedReader = new BufferedReader(file);
while ( (line = bufferedReader.readLine()) != null ) {
System.out.println(line);
}
// Close files
bufferedReader.close();
} catch ( FileNotFoundException ex ) {
System.out.println("Unable to open file '" + fileName + "'");
} catch ( IOException ex ) {
ex.printStackTrace();
}
}
</code></pre>
<p>Can you anybody give me some hint how to save a text file as sql file after reading the text file?</p>
<p>Thank you so much!</p> | 1 |
CakePHP 3 - Use saved data inside afterSave() | <p>I have submitted a form in my view which will be processed in the controller. What normally happens is that the controller saves the edits by doing this:</p>
<pre><code>if ($this->Requests->save($request)) {
// the request have been saved.
}
</code></pre>
<p>Now I created another insert query to follow the activity of the editor with the afterSave() statement like so:</p>
<pre><code>public function afterSave()
{
// here I need the data submitted from $this->request->save($request));
// how can I do this to use the data in the query?
// insert query here.
}
</code></pre>
<p>I want to use the afterSave() because I want to use it for all changes made to the requests, but I can't seem to find a way to access the posted data.</p>
<p><a href="http://book.cakephp.org/3.0/en/orm/table-objects.html#aftersave" rel="nofollow">The documentation</a> says that the afterSave() contains the following parameters:</p>
<p><code>afterSave(Event $event, EntityInterface $entity, ArrayObject $options)</code></p>
<p>Do I need these to accomplish what I want? If so, how do I use those properly? because I can't seem to get any debug information to see what it contains of the save action.</p>
<p><strong>The question is as follows:</strong></p>
<p>How can I access the data saved with <code>$this->Requests->save($request)</code> in a beforeSave() or afterSave() statement to use the data in another query?</p> | 1 |
div inside select tag | <p>HTML:</p>
<pre><code><div class="row">
<div class="form-group">
<div class="col-xs-10">
<label for="class_code_reservation">Class Code</label>
<select type="text" class="form-control" id="class_code_reservation" name="class_code_resevation" autocomplete="off">
<div id="classdata"></div>
</select>
</div>
<div class="col-xs-2">
<a href="class_list_form.php" target="_blank"> <span class="glyphicon glyphicon-list-alt"></span> view class list</a>
<br>
<br>
<br>
</div>
</div>
</div>
</code></pre>
<p>PHP:</p>
<pre><code>include "connect_database.php";
$course =$_POST['course'];
$fetchquery = "SELECT * FROM `class` WHERE course = '$course'";
$fetch = mysqli_query($conn, $fetchquery);
while ($rows = mysqli_fetch_assoc($fetch)) {
echo "<option value=".$rows['class_code']." >".$rows['class_code']." </option>";
}
</code></pre>
<p>JavaScript:</p>
<pre><code>function classcode() {
var course = $('#course_reservation').val();
$.ajax({
type: "POST",
url: "reservation_class_code.php",
data: "course=" + course
}).done(function(data) {
alert(data)
$('#classdata').html(data);
});
}
</code></pre>
<p>I want to populate dropdown option depending on what the user will choose using ajax but dreamweaver highlights div with an id of classdata as an error.</p> | 1 |
How to check whether an int input is greater than 2147436647 or smaller than -2147483648? | <p>Doing this :</p>
<pre><code>int nbr;
if (nbr <= -2147483648 || nbr >= 2147483647)
printf("No way !!");
</code></pre>
<p>Does not write No Way !! for value under the lower limit (for example -2147483650) because the inputs numbers become positive !! </p> | 1 |
Redirect Login to Controller Action | <p>Starting with the ASP.NET 5 Web App Template using Individual User Accounts I have managed to get external authentication working with Microsoft accounts. When users click Login they are redirected to <code>ExternalLogin</code> in <code>AccountController</code> like this</p>
<pre><code><form asp-controller="Account" asp-action="ExternalLogin" method="post" asp-route-returnurl="@ViewData["ReturnUrl"]" class="nav navbar-right">
<button type="submit" class="btn btn-null nav navbar-nav navbar-right" name="provider" value="Microsoft" title="Log in"><span class="fa fa-sign-in"/>&nbsp; Log In</button>
</form>
</code></pre>
<p>That gets them logged in using thier Microsoft account and all seems to work nicely. But how do I intercept direct attempts to access privileged actions <code>[Authorize]
</code> so that the user is redirected to <code>ExternalLogin</code>? Can a default action be set in <code>Startup.cs</code>?</p>
<p><strong>EDIT 1</strong> Attempting to follow the advice of @Yves I have created <code>CustomAutorizationFilter</code> in a Filters folder. It doesn't check for any conditions</p>
<pre><code>public class CustomAutorizationFilter : IAuthorizationFilter
{
public void OnAuthorization(Microsoft.AspNet.Mvc.Filters.AuthorizationContext context)
{
//if (...) // Check you conditions here
//{
context.Result = new RedirectToActionResult("ExternalLogin", "Account", null);
//}
}
}
</code></pre>
<p>and have edited <code>ConfigureServices</code> as below</p>
<pre><code> services.AddMvc(config =>
{
config.Filters.Add(typeof(Filters.CustomAutorizationFilter));
});
</code></pre>
<p>When I run the app locally it no longer goes to the Home page. It returns a blank <code>http://localhost:52711/Account/ExternalLogin</code></p>
<p>Obviously there is much I do not understand.</p>
<p><strong>Edit 2:</strong> Here is the signature of <code>ExternalLogin</code></p>
<pre><code> // POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
</code></pre>
<p>This is how <code>ExternalLogin</code> comes out of the box in the ASP.Net 5 Web App Template.</p> | 1 |
JPA2 Criteria and Java 8 Date&Time API | <p>I try to port a Java web application to the new Java 8 Date&Time API (using 'LocalDate' and 'LocalDateTime' types among others)</p>
<p>In Java 7, java.util.Date could be used in JPA2 criteria API to filter result sets on dates. Typically one would do this by adding a predicate e.g.</p>
<pre><code>..
predicatesList.add(builder.between(from.get(AccountLog_.valueDate), fromDate, toDate));
..
</code></pre>
<p>Now JPA2 doesn't support the new Java 8 Date&Time API (LocalDate and LocalDateTime) yet. With own "Attribute Converters", working with entities can already be achieved as described in the blog <a href="http://www.thoughts-on-java.org/persist-localdate-localdatetime-jpa/">http://www.thoughts-on-java.org/persist-localdate-localdatetime-jpa/</a></p>
<p>Now to my question: how can I use LocalDate and LocalDateTime in JPA2 criteria API in order to filter the result sets on <strong>LocalDate</strong> instead of Date? 'between' as used previously doesn't work for LocalDate instances.</p> | 1 |
How can I login to Ubuntu via ssh and automatically sudo su? | <p>From my Mac Terminal I can login via ssh to my various Ubuntu servers without entering a password. That's fine. But the work I do in Ubuntu requires me to have root access, so immediately after login I always execute <code>sudo su</code>which is an extra step and requires manually entering my password at that point.</p>
<p>What's a good way to avoid that extra step so I login with my user name as I do now, but immediately have the <code>sudo su</code> executed for me (or anything with an equivalent result)?</p>
<p>Thanks.</p> | 1 |
send URL request, without leaving page | <p>I have a web-page, with a streaming web-camera. The camera pans and tilts, using a script on the camera's internal web-server. I cannot modify the script, its output, is a web-page that says "OK".</p>
<p>When a user comes to my page, I want them to be able to use arrow keys to pan the camera, but not have the script that sends out the request, leave the page with the camera stream. This source, will pan the camera, but you have to click back, to get to the stream. here is my source:</p>
<pre><code><head>
<?php
$url = "http://Camera-server-IP/decoder_control.cgi?user=admin&pwd=password&command=2";
?>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).keypress(function (e){
if(e.keyCode == 37) // left arrow
{
window.location.href = <?php echo "\"" . $url . "\""; ?>;
}
else if(e.keyCode == 38) // up arrow
{
$(window.location.href = "http://Camera-server-IP/decoder_control.cgi?user=admin&pwd=password&command=6");
}
else if(e.keyCode == 39) // right arrow
{
window.location.href = "http://Camera-server-IP/decoder_control.cgi?user=admin&pwd=password&command=4";
}
else if(e.keyCode == 40) // Down arrow
{
window.location.href = "http://Camera-server-IP/decoder_control.cgi?user=admin&pwd=password&command=0";
}
});
</script>
<title>Navigation</title>
</head>
<body>
<br><h2>use arrows to navigate.</h2>
<iframe src="http://Camera-server-IP/videostream.cgi?user=user&pwd=Password" width="330" height="260"></iframe>
</body>
</html>
</code></pre>
<p>Camera-server-IP is the actual Camera Webserver address.
Why is every navigation arrow done differently? because I’m trying to figure this out. </p>
<p>what can I do to use the arrow keys to send the url requests to the camera, but simultaneously stay on the page where the camera is streaming?</p> | 1 |
Website doesn't load properly on webview | <p>I have a fragment, that includes a simple webview and textview.
I'm trying to load a site, but it doesn't load well.</p>
<p><a href="https://i.stack.imgur.com/4JW64.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4JW64.jpg" alt="ChromeBrowser working properly"></a></p>
<p><a href="https://i.stack.imgur.com/rsosA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rsosA.jpg" alt="webView in fragment don't work well"></a></p>
<p>I googled and didn't find a solution. I think that the sourch of the problem is
the site itself <a href="https://m.headstart.co.il/#/main?id=17863" rel="nofollow noreferrer">https://m.headstart.co.il/#/main?id=17863</a> , but I don't understand web languages well enough to understand if the problem is really there.
What is the problem? and how can I make the site load properly on the webview?
Thanks in advance.</p>
<p>the code block:</p>
<pre><code> View v = inflater.inflate(R.layout.fragment_campaign, container, false);
String address_campaign = "http://www.headstart.co.il/project.aspx?id=17863";
WebView wv = (WebView) v.findViewById(R.id.webView);
// UI setting
// wv.setInitialScale(1);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setLoadWithOverviewMode(true);
wv.getSettings().setUseWideViewPort(false);
wv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
wv.setScrollbarFadingEnabled(false);
// wv.setWebViewClient(new WebViewClient());
wv.loadUrl(address_campaign);
wv.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
return v;
</code></pre>
<p>the xml:</p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ContackRWBForDonate">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Help us build a better community"
android:id="@+id/textView4"
android:foregroundGravity="top|center_vertical"
android:gravity="center"
android:textColor="@color/colorPrimary"
android:background="@color/BackGroundMainActivity"
android:layout_gravity="center_horizontal"
android:textStyle="bold" />
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView"
android:layout_gravity="bottom" />
</code></pre>
<p></p> | 1 |
divs inside div not working properly | <pre><code><div id="footer">
<div>
<h2>Revovation</h2>
<p>Our mission is to provide the best handyman service at an reasonable price without sacrificing quality. You will be satisfy with our work knowing we take the necessary steps to meet your needs and get the job done right
</p>
</div>
<div>
<h2>Information</h2>
<div>
<ul>
<li>Blog</li>
<li>Services</li>
<li>Extras</li>
<li>Contact</li>
</ul>
</div>
<div>
<ul>
<li>Projects</li>
<li>Information</li>
<li>About us</li>
<li>Shop</li>
</ul>
</div>
</div>
<div>
<h2>Renovation Office</h2>
<ul>
<li><img src="images/marker.png" alt="">Address</li>
<li>Phone</li>
<li>Email</li>
<li>Fax</li>
<li>Timings</li>
</ul>
</div>
</div>
</code></pre>
<p>edit: Adding css</p>
<pre><code>#footer
{
background : #282828;
border: 2px solid blue;
font-family : verdana;
position: relative;
color : #8e9a8c;
}
#footer div
{
background : #282828; !important;
width : 28%;
border: 1px solid red;
float : left;
padding: 60px 0px 30px 40px;
}
</code></pre>
<p>blue border is for footer div and red border is for the divs inside it. I am floating inside divs to left. Why wont the outer div cover all three inner child divs? I have no clue whats going wrong in here! </p>
<p><a href="http://i.stack.imgur.com/NYROU.png" rel="nofollow">Output Screenshot</a></p> | 1 |
how to return image in python file? | <p>Do I return it with httpResponse? Is there another way to call my image that's in a static folder?(in python file directly: usual process I follow is to save images in a static file. Then call that image in html file) but I'm trying to return an image in python file. Sorry if this isn't clear. I'll demonstrate with this code. </p>
<pre><code>def extract(url):
g = Goose()
article = g.extract(url=url)
if article.top_image is None:
return "none"
else:
if article.top_image.src is None:
return "none"
else:
resposne = {'image':article.top_image.src}
return article.top_image.src
</code></pre>
<p>Here instead of returning "none" I want to insert an image. </p>
<p>In views.py</p>
<pre><code> def form_valid(self, form):
self.object = form.save(commit=False)
# any manual settings go here
self.object.moderator = self.request.user
self.object.image = extract(self.object.url)
self.object.save()
return HttpResponseRedirect(reverse('post', args=[self.object.slug]))
</code></pre>
<p>Then in html file, I use post.image.</p>
<p>Again, I'm just trying to return some random image that's in my static file to be displayed instead of "none". Not sure how to do this...thanks in advance</p>
<p>Edit: What I'm trying to do is this. in first block of code, I'm returing "none" right/instead of none I want to return an image I saved on my static folder. ex) image = "some code" and that image to be rendered in views.py and use post.image in html file/ right now if I do post.image it shows broken image because I'm returning "none"</p>
<pre><code>class PostCreateView(CreateView):
model = Post
form_class = PostForm
template_name = 'main/add_post.html'
def form_valid(self, form):
self.object = form.save(commit=False)
# any manual settings go here
self.object.moderator = self.request.user
self.object.image = extract(self.object.url)
self.object.save()
return HttpResponseRedirect(reverse('post', args=[self.object.slug]))
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(PostCreateView, self).dispatch(request, *args, **kwargs)
</code></pre> | 1 |
ADB says device unauthorized | <p>I tried installing cyanogenmod on my samsung s2. I managed to sucessfully install <strong>cyanogen recovery</strong> on the device which boots up when I start the device.</p>
<p>After that I tried to install cyanogenmod which gets me an error:</p>
<pre><code>adb push "cm-12.1-20160129-NIGHTLY-i9100.zip" /storage/sdcard0
error: device unauthorized.
This adb server's $ADB_VENDOR_KEYS is not set
Try 'adb kill-server' if that seems wrong.
Otherwise check for a confirmation dialog on your device.
</code></pre>
<p>I already tried to kill and restart <code>adb</code> server and also tried installing different <code>usb</code> drivers using Zadig<code>.</code></p>
<p>I have read that <strong>USB debugging</strong> must be enabled on the device but the problem is that <strong>I cannot boot android anymore</strong> to set that option, I only get a start screen with a <strong>yellow exclamation mark</strong> and right after that cyanogenmod recovery menu shows up. Iam not sure if this option is the source of the problem, though.</p>
<p>Is the device bricked now or is there a way to either install cyanogenmod or at least restore the original android?</p> | 1 |
Hibernate and Postgresql negative primary key id issue | <p>I'm using Hibernate 5.0.7 with Postgresql DBMS. Every thing working just fine, but I face a issue with primary key in postgresql database (Negative value).</p>
<p>Here is my code: </p>
<pre><code>package model;
import javafx.beans.property.*;
import javax.persistence.*;
@Entity
@Table(name = "Product")
@Access(AccessType.PROPERTY)
public class Product {
private LongProperty idProduct;
private StringProperty nameFr;
private DoubleProperty qtyInHand;
private DoubleProperty sellPrice;
public Product() {
idProduct = new SimpleLongProperty();
nameFr = new SimpleStringProperty();
qtyInHand = new SimpleDoubleProperty();
sellPrice = new SimpleDoubleProperty();
}
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "product_seq_gen")
@SequenceGenerator(name = "product_seq_gen", sequenceName = "product_idproduct_seq")
@Column(name = "idproduct", unique = true, nullable = false)
public Long getIdProduct() {
return idProduct.get();
}
public LongProperty idProductProperty() {
return idProduct;
}
public void setIdProduct(Long idProduct) {
this.idProduct.set(idProduct);
}
@Column(name = "nameFr")
public String getNameFr() {
return nameFr.get();
}
public StringProperty nameFrProperty() {
return nameFr;
}
public void setNameFr(String nameFr) {
this.nameFr.set(nameFr);
}
@Column(name = "qtyInHand")
public double getQtyInHand() {
return qtyInHand.get();
}
public DoubleProperty qtyInHandProperty() {
return qtyInHand;
}
public void setQtyInHand(double qtyInHand) {
this.qtyInHand.set(qtyInHand);
}
@Column(name = "sellPrice")
public double getSellPrice() {
return sellPrice.get();
}
public DoubleProperty sellPriceProperty() {
return sellPrice;
}
public void setSellPrice(double sellPrice) {
this.sellPrice.set(sellPrice);
}
}
</code></pre>
<p>Here product table structure </p>
<pre><code>CREATE TABLE product
(
idproduct serial NOT NULL,
namefr character varying(50),
qtyinhand double precision,
sellprice double precision,
CONSTRAINT product_pkey PRIMARY KEY (idproduct)
)
</code></pre>
<p>After making CRUD Operation using hibernate, and retrieve inserted records in database I see that hibernate is inserting negative value starting from -46, -45 ...... and so on.</p>
<p>Here is the connexion to database:</p>
<pre><code>package util;
import model.Product;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class DatabaseUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Product.class);
return configuration. buildSessionFactory(new StandardServiceRegistryBuilder().build());
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("There was an error building the factor");
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
</code></pre>
<p>And here is my test: </p>
<pre><code>import model.Product;
import org.hibernate.Session;
import util.DatabaseUtil;
public class Application {
public static void main(String[] args) {
Product p = new Product();
p.setNameFr("Product 1");
p.setQtyInHand(20);
p.setSellPrice(101);
Session session = DatabaseUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(p);
session.getTransaction().commit();
session.close();
}
}
</code></pre> | 1 |
How to use Task.WhenAll() for multiple Lists of different return types? | <p>I have two sets of Tasks, each with different result type:</p>
<pre><code>IEnumerable<Task<T1>> set1 = GetTasksOfT1();
IEnumerable<Task<T2>> set2 = GetTasksOfT2();
</code></pre>
<p>Now I would like to await both sets in one line, but I had to project set1 with cast:</p>
<pre><code> await Task.WhenAll(set1.Select(p => p as Task).Concat(set2));
</code></pre>
<p>That's because I get this error if I don't use casting:</p>
<pre><code>IEnumerable<Task<T1>>' does not contain a definition for 'Concat'
and the best extension method overload 'Queryable.Concat<Task<T2>>(IQueryable<Task<T2>>, IEnumerable<Task<T2>>)'
requires a receiver of type 'IQueryable<Task<T2>>'
</code></pre>
<p>Which is obvious.</p>
<p>So is there a way to use a single WhenAll() without casting?</p>
<p>Edit:
The return types T1 and T2 <strong>are</strong> important - I consume them after the tasks are awaited:</p>
<pre><code>//After await Task.WhenAll(...):
var t1Results = await set1; // all set1 Tasks are completed by now
var t2Results = await set2; // same
DoSomethingWithResults(t1Results, t2Results);
</code></pre> | 1 |
Determining if a number is negative in Scheme with one function | <p>I have been going through The Little Schemer and I started getting curious about how to deal with negative numbers. It seemed like a nice challenge to figure out how to build a function to determine if a number is negative or positive.</p>
<p>So far I have this solution:</p>
<pre><code>(define negative?
(lambda (a)
(cond
((zero? a) #f)
(else (negativeHelper (sub1 a) (add1 a))))))
(define negativeHelper
(lambda (a b)
(cond
((zero? a) #f)
((zero? b) #t)
(else (negativeHelper (sub1 a) (add1 b))))))
</code></pre>
<p>This looks to be working nicely, but my question is if it is possible to right <code>negative?</code> without the helper function?</p> | 1 |
Using awk to extract a column containing spaces | <p>I'm looking for a way to extract the filename column from the below output. </p>
<pre><code> 2016-02-03 08:22:33 610540 vendor_20160202_67536242.WAV
2016-02-03 08:19:25 530916 vendor_20160202_67536349.WAV
2016-02-03 08:17:10 2767824 vendor_20160201_67369072 - cb.mp3
2016-02-03 08:17:06 368928 vendor_20160201_67369072.mp3
</code></pre>
<p>One of the files has spaces in the name which is causing issues with my current commmand</p>
<pre><code>awk '{print $4}'
</code></pre>
<p>How would I treat a column with spaces as a single column?</p> | 1 |
Android NDK Integration: Error:Unable to load class BuildType$Impl | <p>I am trying to integrate NDK into my project. I am using Gradle wrapper 2.9 and classpath:<code>gradle-experimental:0.6.0-alpha3</code>. </p>
<p>Project level gradle:</p>
<pre><code>buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle-experimental:0.6.0-alpha6'
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p>App level gradle:</p>
<pre><code>apply plugin: 'com.android.model.application'
model {
android {
compileSdkVersion = 23
buildToolsVersion = "23.0.2"
defaultConfig.with {
applicationId = "com.ms.knowursensor.android"
minSdkVersion.apiLevel = 11
targetSdkVersion.apiLevel = 23
}
}
compileOptions.with {
sourceCompatibility=JavaVersion.VERSION_1_7
targetCompatibility=JavaVersion.VERSION_1_7
}
android.ndk {
moduleName = "sensorgraph"
}
android.buildTypes {
release {
minifyEnabled = false
proguardFiles += file('proguard-rules.txt')
}
}
android.productFlavors {
create("arm") {
ndk.abiFilters += "armeabi"
}
create("arm7") {
ndk.abiFilters += "armeabi-v7a"
}
create("arm8") {
ndk.abiFilters += "arm64-v8a"
}
create("x86") {
ndk.abiFilters += "x86"
}
create("x86-64") {
ndk.abiFilters += "x86_64"
}
create("mips") {
ndk.abiFilters += "mips"
}
create("mips-64") {
ndk.abiFilters += "mips64"
}
create("all")
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:support-v4:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.android.support:cardview-v7:23.1.1'
compile 'com.android.support:recyclerview-v7:23.1.1'
}
}
</code></pre>
<p>On building app, i receive this error:</p>
<blockquote>
<p>Error:Unable to load class
'com.android.build.gradle.managed.BuildType$Impl'. Possible causes for
this unexpected error include:<ul><li>Gradle's dependency cache may be
corrupt (this sometimes occurs after a network connection timeout.) Re-download dependencies and sync project (requires
network)</li><li>The state of a Gradle build process (daemon) may
be corrupt. Stopping all Gradle daemons may solve this problem. Stop Gradle build processes (requires
restart)</li><li>Your project may be using a third-party plugin
which is not compatible with the other plugins in the project or the
version of Gradle requested by the project.</li></ul>In the case of
corrupt Gradle processes, you can also try closing the IDE and then
killing all Java processes.</p>
</blockquote>
<p>After modifying description of proguard and product flavor i am receiving this error:</p>
<pre><code>Error:A problem occurred configuring project ':app'.
> The following model rules could not be applied due to unbound inputs and/or subjects:
compileOptions.with { ... } @ app\build.gradle line 15, column 5
subject:
- compileOptions.with Object [*]
dependencies { ... } @ app\build.gradle line 68, column 6
subject:
- dependencies Object [*]
[*] - indicates that a model item could not be found for the path or type.
</code></pre> | 1 |
Cauchy prior in JAGS | <p>I'm building a multi-level Bayesian model using rJAGS and I would like to specify a Cauchy prior for several of my parameters. Is there a way to do this in JAGS, or do I need to switch to STAN? My JAGS model is below. I'd like to replace the <code>dnorm</code> distributions with Cauchy, but JAGS cannot find the standard <code>R</code> Cauchy distributions, e.g. <code>dcauchy</code>, <code>pcauchy</code></p>
<pre><code>model_string <- "model{
for (i in 1:n){
y[i] ~ dbin(mu[i], 1)
p.bound[i] <- max(0, min(1, mu[i])) #381 gelman
logit(mu[i]) <- a[dc[i]] + b1*x1[i] + b2*x2[i]
}
b1 ~ dnorm(0,.001)
b2 ~ dnorm(0,.001)
for (j in 1: n.dc ){
a[j] ~ dnorm(g0, tau.a) #not goj, g1j
}
g0 ~ dnorm(0,.001)
tau.a <- pow(sigma.a , -2)
sigma.a ~ dnorm(0,.001)
}"
</code></pre> | 1 |
R networkD3 package: node coloring in simpleNetwork() | <p>The <code>networkD3</code> package (see <a href="https://christophergandrud.github.io/networkD3/" rel="nofollow noreferrer">here</a> and <a href="https://cran.r-project.org/web/packages/networkD3/networkD3.pdf" rel="nofollow noreferrer">here</a>) allows a user to create simple interactive networks:</p>
<pre><code># Load package
library(networkD3)
# Create fake data
src <- c("A", "A", "A", "A",
"B", "B", "C", "C", "D")
target <- c("B", "C", "D", "J",
"E", "F", "G", "H", "I")
networkData <- data.frame(src, target)
# Plot
simpleNetwork(networkData)
</code></pre>
<p>Is there a way to specify that I want all elements in the <code>src</code> vector to be a certain color, while allowing all the elements in the <code>target</code> vector to be a different color? This would allow me to visually distinguish <code>src</code> nodes from <code>target</code> nodes in the network.</p>
<p>This functionality doesn't seem to be currently supported in <code>simpleNetwork()</code> (but I'm hoping somebody could help me out with a homebrew script):</p>
<p><a href="https://i.stack.imgur.com/jaKAz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jaKAz.png" alt="enter image description here"></a> </p>
<p>A similar but not related question was <a href="https://stackoverflow.com/questions/34480814">asked here</a>.</p> | 1 |
Rails: Updating quantities in shopping cart | <p>Ruby newbie here. I'm going through Agile Web Development With Rails. In chapter 11 it challenges you to add a 'decrease quantity' button to items in the shopping cart. I went ahead and tried to implement an increase link as well.</p>
<p>The problem is it's not doing anything when I click on the links.</p>
<p><strong>line_items_controller.rb</strong></p>
<pre><code>def decrease
@cart = current_cart
@line_item = @cart.decrease(params[:id])
respond_to do |format|
if @line_item.save
format.html { redirect_to store_path, notice: 'Item was successfully updated.' }
format.js { @current_item = @line_item }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: @line_item.errors, status: :unprocessable_entity}
end
end
end
def increase
@cart = current_cart
@line_item = @cart.increase(params[:id])
respond_to do |format|
if @line_item.save
format.html { redirect_to store_path, notice: 'Item was successfully updated.' }
format.js { @current_item = @line_item }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: @line_item.errors, status: :unprocessable_entity }
end
end
end
</code></pre>
<p><strong>cart.rb</strong></p>
<pre><code>def decrease(line_item_id)
current_item = line_items.find(line_item_id)
if current_item.quantity > 1
current_item.quantity -= 1
else
current_item.destroy
end
current_item
end
def increase(line_item_id)
current_item = line_items.find(line_item_id)
current_item.quantity += 1
current_item
end
</code></pre>
<p><strong>routes.rb</strong></p>
<pre><code>resources :line_items do
put 'decrease', on: :member
put 'increase', on: :member
end
</code></pre>
<p><strong>_line_item.html.erb</strong></p>
<pre><code><% if line_item == @current_item %>
<tr id="current_item">
<% else %>
<tr>
<% end %>
<td><%= line_item.quantity %> &times;</td>
<td><%= line_item.product.title %></td>
<td class="item_price"><%= number_to_currency(line_item.total_price) %></td>
<td><%= link_to "-", decrease_line_item_path(line_item), method: :put, remote: true %></td>
<td><%= link_to "+", increase_line_item_path(line_item), method: :put, remote: true %></td>
<td><%= button_to 'Remove Item', line_item, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
</code></pre>
<p><strong>/line_items/increase.js.erb</strong></p>
<pre><code>$('#cart').html("<%= escape_javascript(render(@cart)) %>");
$('#current_item').css({'background-color':'#88ff88'}).animate({'background-color':'#114411'}, 1000);
</code></pre>
<p><strong>/line_items/decrease.js.erb</strong></p>
<pre><code>$('#cart').html("<%= escape_javascript(render(@cart)) %>");
$('#current_item').css({'background-color':'#88ff88'}).animate({'background-color':'#114411'}), 1000);
if ($('#cart tr').length==1) {
// Hide the cart
$('#cart').hide('blind', 1000);
}
</code></pre>
<p>Let me know if I forgot anything crucial. Thanks in advance!</p>
<p><strong>----EDIT----</strong></p>
<p>I changed the code to what Rich posted, and this is what shows up in the console when I click the '+' link.</p>
<pre><code>Started GET "/line_items/25/qty" for ::1 at 2016-01-30 23:49:11 -0600
ActionController::RoutingError (No route matches [GET] "/line_items/25/qty"):
</code></pre>
<p>So I see that it needs a route for qty but I'm not quite sure how to set that up. I'm guessing the JS alert we set up isn't firing because it's snagging up at this point?</p>
<p><strong>----EDIT 2----</strong></p>
<p>Now I'm passing the links as <code>POST</code> and getting this name error, from both the up and down links:</p>
<pre><code>Started POST "/line_items/25/qty" for ::1 at 2016-01-31 09:49:04 -0600
Processing by LineItemsController#qty as JS
Parameters: {"id"=>"25"}
Completed 500 Internal Server Error in 38ms (ActiveRecord: 0.0ms)
NameError (undefined local variable or method `current_cart' for #<LineItemsController:0x007fbfb11ea730>):
app/controllers/line_items_controller.rb:70:in `qty'
</code></pre>
<p>What confuses me here is that <code>current_cart</code> works in the <code>increase</code> and <code>decrease</code> methods but not in <code>qty</code>.</p> | 1 |
name 'session' is not defined for Tweepy | <p>I'm trying to use Tweepy to use Twitter streaming API and I'm following the documentation (<a href="http://docs.tweepy.org/en/v3.5.0/auth_tutorial.html" rel="nofollow">http://docs.tweepy.org/en/v3.5.0/auth_tutorial.html</a>). </p>
<p>However, on the page, Im stuck at <code>http://docs.tweepy.org/en/v3.5.0/auth_tutorial.html</code>. It gives me the error <code>name 'session' is not defined</code>. Since the tutorial doesn't say which library for session it's using, I cannot proceed. Could someone help?</p>
<p>My code:</p>
<pre><code>session.set('request_token', auth.request_token)
</code></pre> | 1 |
Configuration of JTDS for use with HikariCP + Spring + MS SQL Server | <p>I kept googling for configuration of JTDS (1.3.1) for use with HikariCP (2.4.3), Spring (4.1.2), and MS SQL Server (2008), but unable to find a complete and working example.</p>
<p>Here is what I have:</p>
<pre><code><bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg ref="hikariConfig" />
</bean>
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="springHikariCP" />
<property name="connectionTestQuery" value="SELECT 1" />
<property name="dataSourceClassName" value="${jdbc.dataSourceClassName}" />
<property name="maximumPoolSize" value="${jdbc.maximumPoolSize}" />
<property name="minimumIdle" value="${jdbc.minimumIdle}" />
<property name="idleTimeout" value="${jdbc.idleTimeout}" />
....
<property name="dataSourceProperties">
<props>
....
</props>
</property>
</bean>
</code></pre>
<p>Can anyone out there share the JTDS configs used in a production environment?</p>
<p>Regards.</p>
<p><strong>UPDATE</strong></p>
<p>I found this SO post:</p>
<p><a href="https://stackoverflow.com/questions/34739778/hikaricp-hanging-on-getconnection">HikariCP hanging on getConnection</a></p>
<p>It seems that JTDS has a problem working with HikariCP. Actually, I have this problem too. Here is my complete config for JTDS:</p>
<pre><code><bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg ref="hikariConfig" />
</bean>
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="springHikariCP" />
<property name="connectionTestQuery" value="${jdbc.connectionTestQuery}" />
<property name="dataSourceClassName" value="${jdbc.dataSourceClassName}" />
<property name="maximumPoolSize" value="${jdbc.maximumPoolSize}" />
<property name="minimumIdle" value="${jdbc.minimumIdle}" />
<property name="idleTimeout" value="${jdbc.idleTimeout}" />
<property name="connectionTimeout" value="${jdbc.connectionTimeout}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="dataSourceProperties">
<props>
<prop key="user">${jdbc.username}</prop>
<prop key="password">${jdbc.password}</prop>
<prop key="cacheMetaData">${jtds.cacheMetaData}</prop>
</props>
</property>
</bean>
</code></pre>
<p>This is exactly the reason I posted my question, and I hope to see a complete example. However, at HikariCP's page, JTDS is listed as supported. I am confused.</p> | 1 |
Sortable with jQuery and Ajax | <p>I have data that I am accessing via ajax from a Coldfusion component. I am trying to display the data in a sortable jQuery ui format but the sortable feature is not working. Here is the code I am trying to use.</p>
<pre><code>$(document).ready(function() {
// get assets to display
var showid = <cfoutput>'#SESSION.Show#'</cfoutput>;
var html = "";
function assetsPost() {
$.ajax({
cache: false,
type:'POST',
url:'cfc/cfc_COLF.cfc?method=qCOLF&returnformat=json',
dataType: "json",
data: {
show_id: showid
},
success:function(data) {
if(data && data.length) { // DO SOMETHING
html += "<ul id='sortable'>";
jQuery.each(data, function(i, val) {
var linkID = data[i].linkID;
var description = data[i].description;
var discussion = data[i].discussion;
var linkurl = data[i].linkurl;
var index = i;
html += "<li id=' " + index + " ' class='ui-state-default'>";
html += "<h5 style='color:#000; text-align:left;'>";
html += "<a class='process-asset' id=' " + linkID + " ' name='done'><img src='images/icon_done.png'></a>";
html += "<a href='" + linkurl + "' target='_blank'> " + description + "</a>";
html += "<a class='process-asset' id=' " + linkID + " ' name='remove' style='color:#000; float:right;'><img src='images/icon_remove.png'></a>";
html += "</h5>";
html += "<p style='color:#000; margin:5px 15px 5px 15px; text-align:left;'> " + discussion + "</p>";
html += "</li>";
});
html += "</ul>";
$('#linkoutput').html( html );
//alert(html);
} else { // DO SOMETHING
}
}
});
}
assetsPost();
});
$(document).ready(function() {
//sort order
$(function() {
$("#sortable").sortable({
opacity: 0.6,
update: function(event, ui) {
var Order = $("#sortable").sortable('toArray').toString();
$('#order').val(Order);
//alert(Order);
}
});
$( "#sortable" ).disableSelection();
});
// set up sort order for form submission
$("#mForm").submit(function() {
$("#order").val($("#sortable").sortable('toArray'))
});
});
</code></pre>
<p>All the data and the jQuery is loading just fine. In fact, if I added the following code and this list sorts just fine.</p>
<pre><code><ul id="sortable">
<li id="1" class="ui-state-default ">
<h5>1</h5>
</li>
<li id="2" class="ui-state-default ">
<h5>2</h5>
</li>
<li id="3" class="ui-state-default ">
<h5>3</h5>
</li>
</ul>
</code></pre>
<p><strong>HTML</strong> UPDATED</p>
<p>Here is the HTML that I am using that isn't working</p>
<pre><code><form enctype="multipart/form-data"
ACTION="page.cfm?#cgi.QUERY_STRING#"
id="mForm"
method="post">
<fieldset>
<div id="linkoutput"></div>
<label>Order:</label> <input type="text" id="order" />
<div class="mfInfo"></div>
</div>
</fieldset>
</form>
</code></pre>
<p>So there has to be some sort of conflict in the ajax section of code. Any advice is appreciated.</p> | 1 |
Deserialize XML with C# from URL | <p>I'm pulling an XML-Sitemap from a website to parse it.</p>
<p>The easyest way would be to deserialize it into on objet.</p>
<p>I get throw the error "Error in XML-Document" on the last line in my example-code. Does anybody know why. There aren't any more details in the error-message.</p>
<p>My Code so far:</p>
<pre><code>[Serializable, XmlRoot("urlset")]
public class Urlset
{
public B5_Url[] urls;
}
[XmlType("url")]
public class B5_Url
{
[XmlElement("loc")]
public string loc;
[XmlElement("lastmod")]
public string lastmod;
[XmlElement("changefreq")]
public string changefreq;
}
class Program
{
static void Main(string[] args)
{
string url = "http://www.myurl.de/sitemap.xml";
XmlSerializer ser = new XmlSerializer(typeof(Urlset));
WebClient client = new WebClient();
string data = Encoding.Default.GetString(client.DownloadData(url));
Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(data));
Urlset reply = (Urlset)ser.Deserialize(stream);
}
}
</code></pre>
<p>This is the XML:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<url>
<loc>http://www.myurl.de/</loc>
<lastmod>2012-06-25T17:10:30+00:00</lastmod>
<changefreq>always</changefreq>
</url>
</urlset>
</code></pre>
<p>Thanks for your help :)</p> | 1 |
Is it possible to set BLE Tx power on android? | <p>So, I want to know if is it possible to control the BLE power on android when working as central device, can I somehow set the transmission power? I didn't find any examples or documents related.
Any documents related would be helpful. </p>
<p>Thanks. </p> | 1 |
angularjs subtract using $scope | <p>I am very new to not only asking for help but also using Angular so please bear with me.</p>
<p>Below is a copy of my calculator.js code that I am using to create a energy scale for light bulbs - I am currently stuck at the point where I want to show how much savings can be made against the other bulbs for example....</p>
<p>Halogen total - Incandescent total<br>
hal_total - inc_total</p>
<p>Would someone please be so kind as to take a look at my code and maybe point me in the right direction.</p>
<pre><code> /* JavaScript Document */
(function(){
var app = angular.module('myCalculator',[]);
app.controller('calculatorcontroller',['$scope',function($scope){
$scope.lumen_options = [375,600,900,1125,1600];
$scope.current_lumens = 600;
$scope.current_cost = 12;
$scope.current_hours = 3;
$scope.current_years = 1;
$scope.current_bulbs = 1;
$scope.total_days = 365;
$scope.inc_conversion = .0625;
$scope.hal_conversion = .0450;
$scope.cfl_conversion = .0146;
$scope.led_conversion = .0125;
$scope.calculate = function(){
$scope.inc_wattage = ($scope.current_lumens * $scope.inc_conversion).toFixed(1);
$scope.hal_wattage = ($scope.current_lumens * $scope.hal_conversion).toFixed(1);
$scope.cfl_wattage = ($scope.current_lumens * $scope.cfl_conversion).toFixed(1);
$scope.led_wattage = ($scope.current_lumens * $scope.led_conversion).toFixed(1);
if( $scope.current_hours > 24 ){ $scope.current_hours = 24 }
var total_hours = $scope.total_days * $scope.current_hours;
var total_total = $scope.total_days * $scope.current_hours * $scope.current_years * $scope.current_bulbs;
var cost = $scope.current_cost / 100;
$scope.inc_cost = ((($scope.inc_wattage * total_hours) / 1000) * cost).toFixed(2);
$scope.hal_cost = ((($scope.hal_wattage * total_hours) / 1000) * cost).toFixed(2);
$scope.cfl_cost = ((($scope.cfl_wattage * total_hours) / 1000) * cost).toFixed(2);
$scope.led_cost = ((($scope.led_wattage * total_hours) / 1000) * cost).toFixed(2);
$scope.inc_total = ((($scope.inc_wattage * total_total) / 1000) * cost).toFixed(2);
$scope.hal_total = ((($scope.hal_wattage * total_total) / 1000) * cost).toFixed(2);
$scope.cfl_total = ((($scope.cfl_wattage * total_total) / 1000) * cost).toFixed(2);
$scope.led_total = ((($scope.led_wattage * total_total) / 1000) * cost).toFixed(2);
}
$scope.calculate();
}]);
})();
</code></pre> | 1 |
Rails Activerecord/Postgres time format | <p>I am working on a Rails project using a Postgres database. For one of my models, I have a time column, called (cleverly) time. When I created the model, I set the data type for this column as 'time', with the (perhaps incorrect) understanding that this data type was for storing time only, no date.</p>
<pre><code>t.time :time
</code></pre>
<p>However, when I submit data to the model, the time is correct but prefixed by an incorrect date:</p>
<pre><code>time: "2000-01-01 16:57:19"
</code></pre>
<p>I just want the column to store the time (like '16:57:19'). Is 'time' the correct data type to use? Or is there some other way I should handle this problem?</p>
<p>Thank you very much.</p> | 1 |
How to remove section from UITableView in Swift? | <p>I am new to iOS and programming in general and am trying to create my first app. I have searched a while for a solution to this but could not find one. I have a UITableView with cells divided into sections that I would like to enable the user to delete. I had no problem implementing it so that the cells delete, but I want to delete a section when there are zero cells within it, and this is causing me trouble. My numberOfSectionsInTableView and numberOfRowsInSection methods return the correct amount. My commitEditingStyle method looks like this: (dataTable is a dictionary of type [String : [String]] that I am using to store the information for each cell where the key is the section header and the values are cells in that section.)</p>
<pre><code>override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
dataTable[Array(dataTable.keys)[indexPath.section]]!.removeAtIndex(indexPath.row)
if dataTable[Array(dataTable.keys)[indexPath.section]]!.count == 0 {
dataTable.removeValueForKey(Array(dataTable.keys)[indexPath.section])
tableView.deleteSections(NSIndexSet(index: indexPath.section), withRowAnimation: .Fade)
} else {
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
}
</code></pre>
<p>I believe I have narrowed down what the problem is, but I do not know how to fix it. When I call tableView.deleteSections, I get the error</p>
<pre><code>'Invalid update: invalid number of rows in section 1. The number of rows
contained in an existing section after the update (1) must be equal to the
number of rows contained in that section before the update (3), plus or
minus the number of rows inserted or deleted from that section (0 inserted,
0 deleted) and plus or minus the number of rows moved into or out of that
section (0 moved in, 0 moved out).'
</code></pre>
<p>I believe this is because section 2 is moved up to section 1, section 3 to section 2, etc. when section 1 is removed, but the number of cells in each section is not updated. In my testing I found that this error only occurs if every section after the one deleted does not have the same numbers of cells as the one being deleted (so 1 cell, since the section is only deleted when the number of cells is reduced to zero). I think to fix this I could manually update the number of cells in each section, but I do not know how to do this. Again, the problem is not that I am returning an incorrect value for the number of cells and number of sections. Any help would be great, and thanks in advance.</p> | 1 |
Does casting `std::floor()` and `std::ceil()` to integer type always give the correct result? | <p>I am being paranoid that one of these functions may give an incorrect result like this:</p>
<pre><code>std::floor(2000.0 / 1000.0) --> std::floor(1.999999999999) --> 1
or
std::ceil(18 / 3) --> std::ceil(6.000000000001) --> 7
</code></pre>
<p>Can something like this happen? If there is indeed a risk like this, I'm planning to use the functions below in order to work safely. But, is this really necessary?</p>
<pre><code>constexpr long double EPSILON = 1e-10;
intmax_t GuaranteedFloor(const long double & Number)
{
if (Number > 0)
{
return static_cast<intmax_t>(std::floor(Number) + EPSILON);
}
else
{
return static_cast<intmax_t>(std::floor(Number) - EPSILON);
}
}
intmax_t GuaranteedCeil(const long double & Number)
{
if (Number > 0)
{
return static_cast<intmax_t>(std::ceil(Number) + EPSILON);
}
else
{
return static_cast<intmax_t>(std::ceil(Number) - EPSILON);
}
}
</code></pre>
<p>(Note: I'm assuming that the the given 'long double' argument will fit in the 'intmax_t' return type.)</p> | 1 |
Error: 'StatIdentity' is not an exported object from 'namespace:ggplot2' when calling ggmap in R | <p>I'm trying to create a map of board members for my nonprofit using <code>ggmap</code>. I'm located in San Diego so my code is as follows: </p>
<pre><code>mapPoints <- qmap('San Diego, CA', zoom = 10) +
geom_point(data = membershipClean,
aes(x = lon, y = lat, stat = "identity", size = Dues.Amount),
alpha = .5)
</code></pre>
<p>Where <code>lat</code> and <code>lon</code> are the members' geocoded latitude and longitude respectively, and <code>Dues.Amount</code> is the numeric value by which I want the points scaled. When I run this code it throws the error: </p>
<blockquote>
<p>Error: 'StatIdentity' is not an exported object from 'namespace:ggplot2'"</p>
</blockquote>
<p>I can't find anyone else online who is having the same problem. I'm a new user of <code>ggmap</code> but I am following the tutorials I've found online pretty much line by line, so I'm kind of at a loss.</p> | 1 |
DLL Injection - CreateRemoteThread | <p>Hello again at StackOverflow!</p>
<p>I return for help on implementing DLL injection using Python, and the results have been fairly successful. I am using non-reflective injection (<code>'CreateRemoteThread'</code>) to inject 'Python27.dll' into a process. This has been successful. <strong>My problem comes when trying to access functions within the injected DLL.</strong></p>
<p>Namely: <code>'Py_InitializeEx'</code> and
<code>'PyRun_SimpleString'</code> functions (Initializes interpreter, allows a simple string to be passed to interpreter).</p>
<p>This will be a rather involved explanation, apologies in advance.</p>
<p>The first VM I have tested the code on is a x86-XP machine, when <code>'Py_InitializeEx'</code>'' is called, the OS returns an error(OS MessageBox) to the effect of "Data Execution Prevention" , "To help protect your computer, Windows has closed this program". So i simply turned of DEP, however even after reboots, the error persists.</p>
<p>I migrated testing over to x64-Win7 (namely for DEP list in tskmgr.exe :P), and attacked non DEP enabled processes. Windows just shuts down the victim processes. I reckon for the same reason, just for 'security' purposes, MSoft probably removed the DEP warning.</p>
<p>This leads me to think that i must definitley must be doing something wrong, as i have seen examples of similar functionality within Python code. My question is, simply, <strong>can anyone tell me what I'm doing wrong?</strong></p>
<p>Thanks in advance :)</p>
<p><code></p>
<pre>kernel32 = windll.kernel32
PAGE_READWRITE = 0x04 #Set token values
PROCESS_ALL_ACCESS = ( 0x00F0000 | 0x00100000 | 0xFFF )
VIRTUAL_MEM = ( 0x1000 | 0x2000 )
dllpath = r"C:\Documents and Settings\isolina\desktop\python27.dll"
dlllen = len(dllpath)#Set program variable
pid = 8972
processh = kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, int(pid))#Attach to process by gaining a handle
dllpathaddr = kernel32.VirtualAllocEx(processh, 0, dlllen, VIRTUAL_MEM, PAGE_READWRITE)#Allocate room within the processes memory for the code
NULL = c_int(0)
kernel32.WriteProcessMemory(processh, dllpathaddr, dllpath, dlllen, NULL)#Write DLL path to process memory
kernel32h = kernel32.GetModuleHandleA("kernel32.dll")
loadlibh = kernel32.GetProcAddress(kernel32h, "LoadLibraryA")#Get address off LoadLibraryA function
thread_id = c_ulong(0)
if not kernel32.CreateRemoteThread(processh, None, 0, loadlibh, dllpathaddr, 0, byref(thread_id)):#Execute LoadLibraryA on DLL path in target process
print "Check yo' privileges, bro!"
exit()
print "Remote Thread: 0x%08x" %(thread_id.value)
pyhand = kernel32.GetModuleHandleA("python27.dll")
py_initialize_ex = thread_id.value + (kernel32.GetProcAddress(pyhand, 'Py_InitializeEx') - pyhand)
pyrun_simple_string = thread_id.value + (kernel32.GetProcAddress(pyhand, 'PyRun_SimpleString') - pyhand)
print "Py_InitializeEx: 0x{0:08x}".format(py_initialize_ex)
print "PyRun_SimpleString: 0x{0:08x}".format(pyrun_simple_string)
""" Code runs fine with below instruction omitted. """
kernel32.CreateRemoteThread(processh, None, 0, py_initialize_ex, 0, 0, byref(thread_id))#Execute Py_InitializeEx in target process
</code></pre> | 1 |
Android - How to edit RelativeLayout shape | <p>I'm using a pop up window as <code>Activity class</code> with a layout, when the <code>button</code> is pressed, a pop up window will appear. what I want is to edit the <code>shape</code> of my pop up window that is a <code>RelativeLayout</code>. thanks</p>
<p>this is my pop_up.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/layout_shape"
tools:context="com.example.computer.mathkiddofinal.FinalResults.Final_Result_Grade_4">
</RelativeLayout>
</code></pre>
<p>this is my layout_shape
</p>
<pre><code> <solid
android:color="#00B0BE" >
</solid>
<stroke
android:width="2dp"
android:color="#C4CDE0" >
</stroke>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp" >
</padding>
<corners
android:radius="40dp" >
</corners>
</shape>
</code></pre>
<p>A screenshot from my XML, i want to remove that whitespace on the side, i know its from the layout background, can i use transparency? because this will pop up on other layout activity so i need only is the blue shape. btw the layout code is from @Sabari thanks</p>
<p><a href="https://i.stack.imgur.com/GEaz0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GEaz0.png" alt="enter image description here"></a></p> | 1 |
Oracle sub-partition shows data, but oracle query using filter does not show data | <p>In Oracle 11g, I have created fact table with date as partition and site_id as sub-partition.</p>
<p>analyse is running daily on this table. but based on one day interval, analyse step is performed.</p>
<p>In SQL DEVELOPER tool, when I open table definition, under partition tab, I am able to see the partition as 23-JAN-2016. For all site_ids, I am able to see sub-partition.</p>
<pre><code>Select * from NPM.EH_MODEM_HIST_PRFRM_FACT subpartition(SYS_SUBP1256625);
</code></pre>
<p>When I run the above query, I am able to see the data.</p>
<p>But I am running below query using report sql; but table is not fetching data</p>
<pre><code>select * from NPM.EH_MODEM_HIST_PRFRM_FACT
where time_stamp ='23-JAN-16' and site_id =580
</code></pre>
<p>Is there any problem in managing this table?</p> | 1 |
How to test Branch.io in simulator? | <p>I'm scratching my head how I'm supposed to test my branch.io integration on simulator.</p>
<p>For link generation, I'm using the Javascript/web SDK instead of the iOS SDK. When you click a button to 'view content in app' on my landing page, it will generate the link and follow it.</p>
<p>All this works just great, but when I open the jump page in the simulator, it never actually attempts to open the local app on the phone which has the same bundle identifier.</p>
<p>I would guess this might be because the current app store URL box is blank (because it doesn't exist yet)... but I am not sure how I'm supposed to test if it works if I can't get the deeplink to trigger it locally.</p>
<p>Thanks!</p> | 1 |
Why COD not showing in checkout page | <p>I have enable the COD payment option from admin and when I checked this on checkout page it is not showing. There is another payment option which payu it is also enabled and it is working fine. PFB Screenshot for the same</p>
<p><a href="https://i.stack.imgur.com/OsdOW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OsdOW.jpg" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/5cYSK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5cYSK.jpg" alt="enter image description here"></a></p>
<p>Is there I have to change anything in code so that COD option should be available? Please guide me on this, thanks in advance.</p> | 1 |
Using UWP TextBox.TextChanging to ignore wrong data | <p>I'm creating a UWP app which has different TextBoxes to enter numbers. To make sure only numbers can be entered I use the TextChanging event. Sadly I can't find any documentation on how to use TextChanging in detail to ignore wrong inputs.</p>
<p>A working solution for one TextBox is the following:</p>
<pre><code>string oldText;
private void tbInput_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
double temp;
if (double.TryParse(sender.Text, out temp) || sender.Text == "")
oldText = sender.Text;
else
{
int pos = sender.SelectionStart - 1;
sender.Text = oldText;
sender.SelectionStart = pos;
}
}
</code></pre>
<p>Using this solution I would need a <code>string oldText</code> for each TextBox and either also a TextChanging function for each of it or a lot more code inside the function.</p>
<p>Is there a easy way to ignore "wrong" inputs in the TextBox.TextChanging event?</p> | 1 |
MCvFont library is missing at Emgu 3.0 | <p>I integrated my project on Visual Studio 2010 with Emgu 3.0 and I'm working on detection object project , but when I'm using MCvFont like the following line I get error because the library is missing , This library is removed from the last version of Emgu or what ?</p>
<pre><code> MCvFont f2 = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_TRIPLEX, 1.0, 1.0);
</code></pre> | 1 |
Error: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings | <p>Links for screenshots</p>
<ul>
<li><p>Settings.py</p>
<ul>
<li><a href="http://postimg.org/image/83120pd9p/" rel="nofollow">http://postimg.org/image/83120pd9p/</a></li>
<li><a href="http://postimg.org/image/tkdnc9qgd/" rel="nofollow">http://postimg.org/image/tkdnc9qgd/</a></li>
<li><a href="http://postimg.org/image/qsu56cpj5/" rel="nofollow">http://postimg.org/image/qsu56cpj5/</a></li>
<li><a href="http://postimg.org/image/cwz0cnf1v/" rel="nofollow">http://postimg.org/image/cwz0cnf1v/</a></li>
<li><a href="http://postimg.org/image/u193rlac3/" rel="nofollow">http://postimg.org/image/u193rlac3/</a></li>
</ul></li>
<li><p>Manage</p>
<ul>
<li><a href="http://postimg.org/image/qpikg5gbj/" rel="nofollow">http://postimg.org/image/qpikg5gbj/</a></li>
</ul></li>
<li><p>Wsgi</p>
<ul>
<li><a href="http://postimg.org/image/t2pdzffvv/" rel="nofollow">http://postimg.org/image/t2pdzffvv/</a></li>
</ul></li>
</ul> | 1 |
Get stream from webcam with openCV and wxPython | <p>I have read all three or four <em>current</em> threads on this subject that are on the internet, and so far none accurately answer the question.</p>
<p>I am fairly new to wxPython, although I have some experience with FLTK. I am new to OpenCV. </p>
<p>I am attempting to capture an image from a webcam with openCV and paint that image into wxPython. I have had limited success (I can get an image and paint it, but it's faint and not aligned properly). I can confirm that my webcam and openCV are working on their own, because <a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html#display-video" rel="nofollow">sample code like this</a> works as expected.</p>
<p>Here is an example of my latest effort, which I've cobbled together from the internet and my own efforts with opencv2. </p>
<pre><code>import wx
import cv2
class viewWindow(wx.Frame):
imgSizer = (480,360)
def __init__(self, parent, title="View Window"):
super(viewWindow,self).__init__(parent)
self.pnl = wx.Panel(self)
self.vbox = wx.BoxSizer(wx.VERTICAL)
self.image = wx.EmptyImage(self.imgSizer[0],self.imgSizer[1])
self.imageBit = wx.BitmapFromImage(self.image)
self.staticBit = wx.StaticBitmap(self.pnl,wx.ID_ANY,
self.imageBit)
self.vbox.Add(self.staticBit)
self.pnl.SetSizer(self.vbox)
self.timex = wx.Timer(self, wx.ID_OK)
self.timex.Start(1000/12)
self.Bind(wx.EVT_TIMER, self.redraw, self.timex)
self.capture = cv2.VideoCapture(0)
self.SetSize(self.imgSizer)
self.Show()
def redraw(self,e):
ret, frame = self.capture.read()
#print('tick')
self.imageBit = wx.BitmapFromImage(self.image)
self.staticBit = wx.StaticBitmap(self.pnl,
wx.ID_ANY, self.imageBit)
self.Refresh()
def main():
app = wx.PySimpleApp()
frame = viewWindow(None)
frame.Center()
frame.Show()
app.MainLoop()
if __name__ == '__main__':
main()
</code></pre>
<p>OpenCV is not a hard requirement (I'm open to other options as long as the solution is cross-platform. If I'm not mistaken, Gstreamer is not cross platform, and PyGame has been difficult to embed in wxPython, but I'm open to ideas).</p>
<p>wxPython is a hard requirement.</p> | 1 |
How to get the IP address using C# in asp.net | <p>I want to get the public IP address of the visitor in my code.</p>
<p>I have written below code to get it:</p>
<pre><code> var context = System.Web.HttpContext.Current;
string ip = String.Empty;
if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (!String.IsNullOrWhiteSpace(context.Request.UserHostAddress))
{
ip = context.Request.UserHostAddress;
}
if (ip == "::1")
ip = "127.0.0.1";
return ip;
</code></pre>
<p>I am not getting the exact IP address It returns the value like: <code>fe80::9419:dfb3:22ce:4e88%68</code> but when I see my IP in <em>What is my IP?</em> it shows <code>13.67.58.30</code>. How would I get the exact IP address?</p> | 1 |
Maximum table (ListObject) size in Excel | <p>I've developed an Excel solution for one of my clients that revolves around a large table (up to column DI). It's filled with about 25% data and 75% formulas. When we now paste in 43000 rows of data, Excel 2010 starts moaning and croaking. After saving of the workbook and re-opening it, Excel takes a long time and finally tells the workbook is corrupt.</p>
<p>I've already ruled out the possibility that we started with a corrupt workbook to begin with; I've started up a fresh workbook with a fresh like-sized table, added 43000 rows of data (this went fast), and added all formulas one by one (by copying the formula text, not just copy/pasting the cells). After saving and re-opening the workbook, it is again corrupt.</p>
<p>I've tried 10000 rows, and that went fine. around 18000 rows the problem raises it's ugly head again. I also removed all formatting in the table, but that made no difference.</p>
<p>Is this a known issue? Do any of you know if there's a safe rows/cells/complexity limit for tables? Should I post a bug report with Microsoft or is this self-inflicted? :)</p>
<p>ADDED</p>
<p>Thanks to @Jeeped I've investigated how this behaves using the .XLSB format, and under that format the files are fine. Re-saving back as .XLSX and the file is instantly "corrupt" again - i.e. Excel actually crashes on opening it. The XML for the worksheet itself seems valid when checking it with XMLStarlet though (it contains 12.5 million elements); it's possibly a bug in Excel's loading routines?</p> | 1 |
Show div when radio button checked vanilla js | <p>A bit of a struggle here. My eventlistener only detects the "checked" change of my radio button, not the "unchecked" change. Note: Pure javascript (vanillajs) only, no jQuery.</p>
<p>A little JSFiddle to explain my problem: <a href="https://jsfiddle.net/kLuba37w/1/" rel="nofollow">https://jsfiddle.net/kLuba37w/1/</a></p>
<pre><code><label class="checkbox checkbox--block">
<input type="radio" name="radio" class="" data-show-more data-target="showmoretarget2" value="1"> <span></span> This is the first radio
</label>
<label class="checkbox checkbox--block">
<input type="radio" name="radio" class="" value="2"> <span></span> This is the second radio
</label>
<div class="js-show-more" data-hook="showmoretarget2">
<h2 class="h2"> Some more content</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis ipsum repellendus, officia dolores consectetur. Error at officiis sequi iure earum.</p>
</div>
</code></pre>
<p>JS:</p>
<pre><code>(function() {
"use strict";
var elements = document.querySelectorAll('[data-show-more]');
[].forEach.call(elements, function(element) {
element.addEventListener('change', function(e) {
e.preventDefault();
var target = document.querySelectorAll('[data-hook="' + this.getAttribute('data-target') + '"]')[0];
alert("change detected");
}, false);
});
})();
</code></pre> | 1 |
Check if specified element is already the logical child of another element | <p>I a beginner in C# and WPF. I'm programming plugin for a node based software called vvvv. I have implemented sliders, buttons and other simple ui elements. The following code shows how a sliders node look in c# :</p>
<pre><code>using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Xml;
using VVVV.PluginInterfaces.V2;
namespace VVVV.Packs.UI.Nodes.WPF
{
[PluginInfo(Author = "lecloneur", Category = "WPF", Help = "WPF Slider", Name = "Slider", AutoEvaluate = false)]
public class WPFSlider : GenericNode, IPluginEvaluate
{
[Input("SizeX", DefaultValue = 120, Order = 9, MinValue = 0)]
public IDiffSpread<int> SizeX;
[Input("SizeY", DefaultValue = 120, Order = 9, MinValue = 0)]
public IDiffSpread<int> SizeY;
[Input("Orientation", Order = 1, DefaultEnumEntry = "Horizontal")]
public IDiffSpread<Orientation> OrientationIn;
[Output("Value", Order = 2)]
public ISpread<double> ValueOut;
int elements_count = 0;
public void Evaluate(int SpreadMax)
{
UIElementOut.SliceCount = SpreadMax;
ValueOut.SliceCount = SpreadMax;
for (int i = 0; i < SpreadMax; i++)
{
if (UIElementOut == null || !(UIElementOut[0] is Slider) || elements_count < SpreadMax || OrientationIn.IsChanged || SizeX.IsChanged || SizeY.IsChanged)
{
CreateElement(i);
}
OutputData(i);
Transformation(i, (Slider)UIElementOut[i]);
}
elements_count = SpreadMax;
}
private void CreateElement(int i)
{
UIElementOut[i] = new Slider();
var uiElement = (Slider)UIElementOut[i];
uiElement.Minimum = 0;
uiElement.Maximum = 1;
uiElement.Orientation = OrientationIn[i];
uiElement.IsMoveToPointEnabled = true;
uiElement.Width = SizeX[i]; ;
uiElement.Height = SizeY[i];
uiElement.VerticalAlignment = VerticalAlignment.Center;
uiElement.HorizontalAlignment = HorizontalAlignment.Center;
XmlReader XmlRead = XmlReader.Create("Styles/SliderStyle.xaml");
ResourceDictionary myResourceDictionary = (ResourceDictionary)XamlReader.Load(XmlRead);
XmlRead.Close();
Style uiElementStyle = myResourceDictionary["SliderStyle"] as Style;
uiElement.Style = uiElementStyle;
}
private void OutputData(int i)
{
var uiElement = (Slider)UIElementOut[i];
ValueOut[i] = uiElement.Value;
}
}
}
</code></pre>
<p>Now I'm trying to implement a tabcontrol where I could dynamically create tabitem and input UIElement into it. As far as I understand, I can only add one things to a tabitem. So I was thinking about creating a grid everytime I need to and fill it with all the incoming UIElement.</p>
<pre><code> public void Evaluate(int SpreadMax)
{
SpreadMax = 1;
UIElementOut.SliceCount = 1;
for (var i = 0; i < SpreadMax; i++)
{
if (UIElementOut == null || !(UIElementOut[i] is TabControl))
UIElementOut[i] = new TabControl();
var uiElement = (TabControl)UIElementOut[i];
uiElement.Height = 200;
uiElement.Width = 500;
}
Grid grid;
int[] _elementCounts = new int[_elementInputs.SliceCount];
for (var i = 0; i < _elementInputs.SliceCount; i++)
{
if (_elementInputs[i] == null || !(_elementInputs[i] is UIElement))
{
grid = new Grid();
for (var j = 0; j < _elementInputs[i].IOObject.SliceCount; j++)
{
if (_elementInputs[i].IOObject[j] != null)
{
UIElement test = new UIElement();
test = _elementInputs[i].IOObject[j];
grid.Children.Add(test);
}
}
_elementCounts[i] = _elementInputs[i].IOObject.SliceCount;
ValueOut[i] = _elementCounts[i];
if (((TabControl)UIElementOut[0]).Items.Count <= i)
{
((TabControl)UIElementOut[0]).Items.Add(new TabItem { Header = _nameInputs[i].IOObject[0], Content = grid });
}
if (_nameInputs[i].IOObject.IsChanged)
{
((TabItem)((TabControl)UIElementOut[0]).Items[i]).Header = _nameInputs[i].IOObject[0];
}
if (_elementInputs[i].IOObject.IsChanged)
{
((TabItem)((TabControl)UIElementOut[0]).Items[i]).Content = grid;
}
}
}
for (var i = ((TabControl)UIElementOut[0]).Items.Count - 1; ((TabControl)UIElementOut[0]).Items.Count > _elementInputs.SliceCount; i--)
{
((TabControl)UIElementOut[0]).Items.RemoveAt(i);
}
}
</code></pre>
<p>I searched a lot but can't find any idea how to solve the error. Apparently adding elements to a the grid throw "specified element is already the logical child of another element"; </p> | 1 |
Proper JavaScript line breaking? | <p>Is breaking up a long boolean expression like this<br></p>
<pre><code>var x = a === b && c === d && e === f;
</code></pre>
<p>To something more readable like <br></p>
<pre><code>var x = a === b
&& c === d
&& e === f;
</code></pre>
<p>considered bad practice?
With long variable names the former can become extremely long.</p> | 1 |
python ordereddict or OrderedDict? | <p>I'm so confused right now. I'm using PyYAML for editing some YAML files.</p>
<pre><code>data = yaml.load_all(open('testingyaml.yaml'),Loader=yaml.RoundTripLoader)
</code></pre>
<p>My testingyaml.yaml file contains the following content:</p>
<pre><code>spring:
profiles: dev
datasource:
url: jdbc:postgresql://127.0.0.1:5432/nfvgrid
dns:
enable: false
cassandra:
host: 192.168.7.151
</code></pre>
<p>When I print data it prints the following:</p>
<p><code>ordereddict([('spring', ordereddict([('profiles', 'dev'), ('datasource', ordereddict([('url', 'jdbc:postgresql://127.0.0.1:5432/nfvgrid')]))])), ('dns', ordereddict([('enable', False)])), ('cassandra', ordereddict([('host', '192.168.7.151')]))])</code></p>
<p>I further want to perform some operations on this ordered dictionary but python throws an error <code>NameError: name 'ordereddict' is not defined</code></p>
<p>It's usually <code>OrderedDict</code> but somehow PyYAML returns ordereddict.
How should I solve this issue?</p> | 1 |
Use https on localhost xampp on mac | <p>I have been trying to use my xampp in localhost with https.</p>
<p>1/ The first step (certificate creation) seems okay. I generated a crt & a key using openssl. Using *.frenchpie.com as common name.</p>
<p>2/ I then copied those two respectively in /etc/ssl.crt/ & /etc/ssl.key/ folders.</p>
<p>3/ I did the following in httpd-vhosts.conf using what I found on stackoverflow</p>
<pre><code><VirtualHost *:443>
DocumentRoot C:/xampp/htdocs/frenchpie
ServerName local.frenchpie.com
SSLEngine on
SSLCertificateFile "conf/ssl.crt/frenchpie.crt"
SSLCertificateKeyFile "conf/ssl.key/frenchpie.key"
</VirtualHost>
</code></pre>
<p>4/ Of course I restarted xampp</p>
<p>Please note that I did not change anything else.
The website main folder is "frenchpie" in htdocs. Also 127.0.0.1 is mapped to local.frenchpie.com</p>
<p>Using <a href="http://local.frenchpie.com/frenchpie" rel="nofollow noreferrer">http://local.frenchpie.com/frenchpie</a> works as usual (homepage).
Using <a href="https://local.frenchpie.com/frenchpie" rel="nofollow noreferrer">https://local.frenchpie.com/frenchpie</a> gives me a certificate error (see picture).</p>
<p>Any help appreciated.</p>
<p><a href="https://i.stack.imgur.com/fXYT4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fXYT4.png" alt="enter image description here"></a></p> | 1 |
Printf splits a string at spaces using Bash | <p>I'm having some troubles with the <code>printf</code> function in bash.
I wrote a little script on which I pass a name and two letters (such as "sh", "py", "ht") and it creates a file in the current working directory named "name.extension".
For instance, if I execute <code>seed test py</code> a file named <code>test.py</code> is created in the current working dir with the shebang <code>#!/usr/bin/python3</code>.</p>
<p>So far, so good, nothing fancy: I'm learning shell scripting and I thought this could be a simple exercise to test the knowledge gained so far.
The problem is when I want to create an HTML file. This is the function that I use:</p>
<pre><code>creaHtml(){
head='<!--DOCTYPE html-->\n<html>\n\t<head>\n\t\t<meta charset=\"UTF-8\">\n\t</head>\n\t<body>\n\t</body>\n</html>'
percorso=$CARTELLA_CORRENTE/$NOME_FILE.html
printf $head>>$percorso
chmod 755 $percorso
}
</code></pre>
<p>If I run, for instance, <code>seed test ht</code> the correct function (<code>creaHtml</code>) is called, <code>test.html</code> is created but if I try to look into it I only see:</p>
<pre><code><!--DOCTYPE
</code></pre>
<p>And nothing else.
This is the trace for that function:</p>
<pre><code>[sviluppo:~/bin]$ seed test ht
+ creaHtml
+ head='<!--DOCTYPE html-->\n<html>\n\t<head>\n\t\t<meta charset=\"UTF-8\">\n\t</head>\n\t<body>\n\t</body>\n</html>'
+ percorso=/home/sviluppo/bin/test.html
+ printf '<!--DOCTYPE' 'html-->\n<html>\n\t<head>\n\t\t<meta' 'charset=\"UTF-8\">\n\t</head>\n\t<body>\n\t</body>\n</html>'
+ chmod 755 /home/sviluppo/bin/test.html
+ set +x
</code></pre>
<p>However, if I try to run <code>printf '<!--DOCTYPE html-->\n<html>\n\t<head>\n\t\t<meta charset=\"UTF-8\">\n\t</head>\n\t<body>\n\t</body>\n</html>'</code> from the terminal, I see the correct output: the "skeleton" of an HTML file neatly displayed with indentation and everything. What am I missing here?</p> | 1 |
How to render images in WebGL from ArrayBuffer | <p>I am having a image that I am reading in server side and pushing to web browser via AJAX call. I have a requirement where I have to render them line by line using WebGL.</p>
<p>For Example : Image is 640X480 where 640 is width and 480 is height. Now the total number of pixels will be 640*480 = 307200 pixels. So, I want to render the whole image in 640(total width) intervals in a loop using WebGL.</p>
<p>Now I have texture2D(as per my knowledge) in webgl to do so, but not getting any idea of where to start . I also having the ArrayBuffer with me , only thing is using Texture2D I want to render it slowly ,line by line.</p>
<p>I am ready to go for any js libraries ,if they are satisfying the requirements.
So, to write a image line by line we can do something like this.</p>
<p><strong>Vertex Shader</strong></p>
<ul>
<li><pre><code>attribute vec2 a_position;?
attribute vec2 a_texCoord;?
void main() {
???
}
</code></pre></li>
<li><p><strong>Fragment Shader</strong></p>
<pre><code> #ifdef GL_ES
precision mediump float;
#endif
uniform float time;
uniform vec2 mouse;
uniform vec2 resolution;
void main( void ) {
vec2 position = 1.0 - gl_FragCoord.xy / resolution;
vec3 color = vec3(1.0);
if (time > position.y * 10.0) {
color = texture2D(uImage0, uv);
}
gl_FragColor = vec4(color, 1.0);
}
</code></pre></li>
<li><p><strong>Javascript For rendering pixel by pixel</strong></p>
<pre><code> function createTextureFromArray(gl, dataArray, type, width, height) {
var data = new Uint8Array(dataArray);
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, type, width, height, 0, type, gl.UNSIGNED_BYTE, data);
return texture;
}
var arrayBuffer = new ArrayBuffer(640*480);
for (var i=0; i < 640; i++) {
for (var j=0; j < 480; j++) {
arrayBuffer[i] = Math.floor(Math.random() * 255) + 0; //filling buffer with random data between 0 and 255 which will be further filled to the texture
//NOTE : above data is just dummy data , I will get this data from server pixel by pixel.
}
}
var gl = canvas.getContext('webgl');
// setup GLSL program
var program = createProgramFromScripts(gl, ["2d-vertex-shader", "2d-fragment-shader"]);
gl.useProgram(program);
//what should I add after this ?
</code></pre>
<p>Can anybody complete the code , I have no idea of how to write code to accomplish this.</p></li>
</ul> | 1 |
ANDROID: Caused by: java.lang.reflect.InvocationTargetException | <p>I'm trying insert data from edittext into DB but i get these errors and can't solve it. I created DBHelper which code is below, just like class for adding data in DB. Also constructors and getters and setters. I really need some help.</p>
<pre><code>02-01 22:22:07.180 23428-23428/? E/SQLiteLog: (1) AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY
02-01 22:22:07.200 23428-23428/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x42020540)
02-01 22:22:07.380 23428-23428/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:275)
at android.view.View.performClick(View.java:4102)
at android.view.View$PerformClick.run(View.java:17085)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270)
at android.view.View.performClick(View.java:4102)
at android.view.View$PerformClick.run(View.java:17085)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY (code 1): , while compiling: CREATE TABLE Logs(_idINTEGER PRIMARY KEY AUTOINCREMENT,titleTEXT,plate_numberTEXT,sort_idTEXT,gradeTEXT,diameterTEXT,lengthTEXT,survey_idINTEGER AUTOINCREMENT);
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:909)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:520)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1719)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1650)
at com.example.matija.ams.LogsDBHandler.onCreate(LogsDBHandler.java:51)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.example.matija.ams.LogsDBHandler.addLogs(LogsDBHandler.java:62)
at com.example.matija.ams.AddLogs.saveButtonClicked(AddLogs.java:55)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270)
at android.view.View.performClick(View.java:4102)
at android.view.View$PerformClick.run(View.java:17085)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
02-01 22:22:09.240 23428-23428/? D/Process: killProcess, pid=23428
02-01 22:22:09.270 23428-23428/? D/Process: dalvik.system.VMStack.getThreadStackTrace(Native Method)
02-01 22:22:09.270 23428-23428/? D/Process: java.lang.Thread.getStackTrace(Thread.java:599)
02-01 22:22:09.270 23428-23428/? D/Process: android.os.Process.killProcess(Process.java:956)
02-01 22:22:09.270 23428-23428/? D/Process: com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:108)
02-01 22:22:09.270 23428-23428/? D/Process: java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
02-01 22:22:09.270 23428-23428/? D/Process: java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
02-01 22:22:09.270 23428-23428/? D/Process: dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>And this is my DbHandler with add method</p>
<pre><code>public class LogsDBHandler extends SQLiteOpenHelper {
//DB version
private static final int DATABASE_VERSION = 11;
// DB name
private static final String DATABASE_NAME = "Log";
//table name
public static final String TABLE_LOGS = "Logs";
public static final String TABLE_SURVEY = "SURVEY";
//TableLogs column names
public static final String KEY_ID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_PLATE_NUMBER = "plate_number";
public static final String KEY_SORTID = "sort_id";
public static final String KEY_GRADE = "grade";
public static final String KEY_DIAMETER = "diameter";
public static final String KEY_LENGTH = "length";
public static final String KEY_SURVEYID = "survey_id";
//TableSurvey column names
public static final String KEY_CREATEDAT = "created_at";
public static final String KEY_SURVEY_TITLE = "survey_title";
public static final String KEY_STATE = "state";
public LogsDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGS_TABLE = "CREATE TABLE " + TABLE_LOGS + "(" +
KEY_ID + "INTEGER PRIMARY KEY AUTOINCREMENT," +
KEY_TITLE + "TEXT," + KEY_PLATE_NUMBER + "TEXT," +
KEY_SORTID + "TEXT," + KEY_GRADE + "TEXT," +
KEY_DIAMETER + "TEXT," + KEY_LENGTH + "TEXT," +
KEY_SURVEYID + "INTEGER AUTOINCREMENT" +");";
db.execSQL(CREATE_LOGS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGS);
onCreate(db);
}
//add new row
public void addLogs(Logs log) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, log.get_title());
values.put(KEY_PLATE_NUMBER, log.get_plate_number());
values.put(KEY_SORTID, log.get_sort_id());
values.put(KEY_GRADE, log.get_grade());
values.put(KEY_DIAMETER, log.get_diameter());
values.put(KEY_LENGTH, log.get_length());
db.insert(TABLE_LOGS, null, values);
db.close();
}
}
</code></pre>
<p>So next code is for adding data from edittext to database. If anything is wrong please tell me. </p>
<pre><code>public class AddLogs extends AppCompatActivity {
private EditText title;
private EditText plate_number;
private Spinner sort_id;
private Spinner grade;
private EditText diameter;
private EditText length;
LogsDBHandler dbHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_logs);
final Button changeActivityButton1 = (Button) findViewById(R.id.btn_back);
changeActivityButton1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View aView) {
Intent toAnotherActivity = new Intent(aView.getContext(), MainActivity.class);
startActivityForResult(toAnotherActivity, 0);
}
});
title = (EditText) findViewById(R.id.inputTitle);
plate_number = (EditText) findViewById(R.id.supplierNumberInput);
sort_id = (Spinner) findViewById(R.id.spinnerSortInput);
grade = (Spinner) findViewById(R.id.spinnerClassInput);
diameter = (EditText) findViewById(R.id.diameterInput);
length = (EditText) findViewById(R.id.lengthInput);
dbHandler = new LogsDBHandler(this, null, null, 1);
}
public void saveButtonClicked(View view) {
Logs log = new Logs(title.getText().toString(), plate_number.getText().toString(),
sort_id.getSelectedItem().toString(), grade.getSelectedItem().toString(),
diameter.getText().toString(), length.getText().toString());
dbHandler.addLogs(log);
Toast.makeText(getBaseContext(), "Spremljeno", Toast.LENGTH_SHORT ).show();
}
}
</code></pre>
<p>So this is all code (i didn't put the code with constructors, getters and setters). So i anybody knows what is the problem please say and write. Thanks.</p> | 1 |
Angular2 beta getting exception "No provider for Router! (RouterLink -> Router)" | <p>I have been banging my head against this for two days now. I am trying to implement some simple routing in Angular2 beta0.0.2. Please note that I am using <strong>typescript</strong>.</p>
<p>So what I understand is that I need to bootstrap my root app component with <strong>ROUTER_PROVIDERS</strong> so that these services are available to my who app <strong>AND</strong> set the directives for the components that want to implement routing to <strong>ROUTER_DIRECTIVES</strong>. </p>
<p>Here is what I have:</p>
<pre><code>//ANGULAR ******************************
import {provide, Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {
APP_BASE_HREF,
ROUTER_DIRECTIVES,
ROUTER_PROVIDERS,
HashLocationStrategy,
LocationStrategy,
RouteConfig,
} from 'angular2/router';
//COMPONENTS ******************************
import {ShiftCalendarComponent} from './components/calendar/shift-calendar.component';
import {ShiftAdminComponent} from './components/admin/shift-admin.component';
import {ShiftListComponent} from './components/shifts/shift-list.component';
//CLASS ******************************
@Component({
selector: 'shift-app',
directives: [ROUTER_DIRECTIVES],
template: `<div>
<nav>
<h3> Navigation: </h3>
<ul>
<li><a [routerLink]="['Calendar']" > Home </a></li>
<li><a [routerLink]="['Admin']" > About </a></li>
<li><a [routerLink]="['Shifts']" > Contact us </a></li>
</ul>
</nav>
<router-outlet></router-outlet>
</div>`
})
@RouteConfig([
{ path: '/', name: 'root', redirectTo: ['/Calendar'] },
{ path: '/calendar', name: 'Calendar', component: ShiftCalendarComponent },
{ path: '/admin', name: 'Admin', component: ShiftAdminComponent },
{ path: '/shifts', name: 'Shifts', component: ShiftListComponent }
])
export class ShiftApp { }
//BOOTSTRAP ******************************
bootstrap(ShiftApp, [
ROUTER_PROVIDERS,
provide(LocationStrategy, { useClass: HashLocationStrategy }),
provide(APP_BASE_HREF, { useValue: '/' })
]);
</code></pre>
<p>The angular app loads and the template is displayed, but no link works and I get the following error in my console:</p>
<blockquote>
<p>EXCEPTION: No provider for Router! (RouterLink -> Router) angular2.dev.js</p>
</blockquote>
<p>In my index.html (which i call view.html) I have linked to all the relevant libraries and have included <strong>router.dev.js</strong> and the sources tab of my console shows me that all the needed scripts are successfully loaded.</p>
<p>I have read about every stack overflow question with router link errors for Angular2 and the entire router docs but cannot find why mine is not working. As far as I can tell my code matches <a href="https://angular.io/docs/ts/latest/guide/router.html" rel="nofollow">the Angular2 Documentation</a></p>
<p><a href="https://angular.io/docs/ts/latest/api/router/ROUTER_DIRECTIVES-let.html" rel="nofollow">This documentation</a> shows that the ROUTER_DIRECTIVES includes the directives like RouterOutlet and RouterLink</p>
<h2>Question?</h2>
<p>If I am successfully setting the directives for the component to <strong>ROUTER_DIRECTIVES</strong>, why am I getting the "No provider for Router! RouterLink" error?</p> | 1 |
Min, Max, Range | <p>I have a problem approaching this problem. It says that I have let the program find the min, max, and range when the User enter a min range and a max range.</p>
<p>Here it the code I have:</p>
<pre><code>#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#define pi 3.1416
#define POINTS 20
using namespace std;
int main()
{
int Xmin, Xmax;
double step;
cout << "Enter a value for xMin and xMax:\n";
cin >> Xmin >> Xmax;
step = (double)(Xmax - Xmin) / (double)POINTS;
cout << "X-VALUES " << "" << "| " << "" << "Y-VALUES" << endl;
cout << "_________" << "" << "|_" << "" << "_________" << endl;
for (int i = 0; i < POINTS; ++i)
{
double x = Xmin + (step * i);
double y = 0.0572 * cos(4.667 * x) + 0.0218 * pi * cos(12.22 * x);
cout << x << "\t " << setprecision(2) << y << endl;
}
cout << "____________________" << endl;
return 0;
}
</code></pre>
<p>I here is the output of my program:</p>
<pre><code>X-Value | Y-Value
__________|__________
-2 -0.0043
-1.8 -0.0982
-1.6 0.0378
-1.4 0.0438
-1.2 0.0099
-1 0.0618
-0.8 -0.1118
-0.6 -0.0198
-0.4 -0.0047
-0.2 -0.0184
0 0.1257
0.2 -0.0184
0.4 -0.0047
0.6 -0.0198
0.8 -0.1118
1 0.0618
1.2 0.0099
1.4 0.0438
1.6 0.0738
1.8 -0.0982
2 -0.0043
─────────────────────
</code></pre>
<p>Basically, this program all ready has a equation that calculates the numbers and list them based on the users inputs for Xmin and Xmax. I'm suppose to let the program find the min, max, and calculate it's range from the Y-Values from the table above.</p>
<p>Here is my code for finding min and max.</p>
<pre><code>#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <limits>
#define pi 3.1416
#define POINTS 20
using namespace std;
int main()
{
int Xmin, Xmax;
double step;
int max = numeric_limits<int> :: min();
int min = numeric_limits<int> :: max();
int num = 0;
cout << "Enter a value for xMin and xMax:\n";
cin >> Xmin >> Xmax;
step = (double)(Xmax - Xmin) / (double)POINTS;
cout << "X-VALUES " << "" << "| " << "" << "Y-VALUES" << endl;
cout << "_________" << "" << "|_" << "" << "_________" << endl;
for (int i = 0; i < POINTS; ++i)
{
double x = Xmin + (step * i);
double y = 0.0572 * cos(4.667 * x) + 0.0218 * pi * cos(12.22 * x);
//printf(" %f\t%f\n ", x, y);
cout << x << "\t " << setprecision(2) << y << endl;
}
cout << "____________________" << endl;
while (cout << "Enter a value for xMin and xMax:\n" &&
cin >> Xmin >> Xmax)
{
if (num > max) max = num;
if (num < min) min = num;
}
cout << "max is: " << max << '\n'
<< "min is: " << min << '\n';
return 0;
}
</code></pre>
<p>It runs, but it doesn't print out the min or max. It just repeats the program at "enter Xmin and Xmax". But when I enter a any leter it prints out the min and max. Help me. I'm confused.</p> | 1 |
Random Access for Vector | <p>I have a vector in C++ that has sorted data, I want to access the data in random order for shuffling the data. The problem with rand is that two indexes can be accessed at the same time and also when the last item remains there will be a lot of un-needed lookups. Any suggestions.</p> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.