title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
ffmpeg: Proper way to encode ac3 to aac?
<p>I have actually encoded an audio file from ac3 to aac using ffmpeg native aac encoder but the issue is that the file is not playing correctly , more specifically i have played that file in different media player but most of them start from 19 seconds and in vlc it is not even starting till I seek to more than 19 seconds duration.</p> <p>command i have used is :- ffmpeg -i source.mkv -map 0:a:0 -c:a aac audio.mp4.</p>
0
How can you scale a Spring Boot application?
<p>I understand that Spring Boot has a built-in Tomcat server (or Jetty) which facilitates rapid development. But what do you do when you need to scale out your application because traffic has increased?</p>
0
python import * or a list from other level
<p>I'm trying to import a few classes from a module in another level. I can type all the classes, but I' trying to do it dynamically</p> <p>if I do:</p> <pre><code>from ..previous_level.module import * raise: SyntaxError: import * only allowed at module level </code></pre> <p>the same from myapp folder:</p> <pre><code>from myapp.previous_level.module import * raise: SyntaxError: import * only allowed at module level </code></pre> <p>So I thought:</p> <pre><code>my_classes = ['Class_Foo', 'Class_Bar'] for i in my_classes: from ..previous_level.module import i raise: ImportError: cannot import name 'i' </code></pre> <p>and also:</p> <pre><code>my_classes = ['Class_Foo', 'Class_Bar'] for i in my_classes: __import__('myapp').previous_level.module.y raise: AttributeError: module 'myapp.previous_level.module' has no attribute 'y' </code></pre> <p>I've tried <code>string format</code> , <code>getattr()</code> , <code>__getattr__</code> but no success.</p> <p>It's impossible to do import this way, or I'm doing something wrong?</p>
0
java.lang.NoSuchMethodError: No static method setOnApplyWindowInsetsListener
<p>I upgraded my android studio to 2.1.3. And now I am getting following error </p> <pre><code>java.lang.NoSuchMethodError: No static method setOnApplyWindowInsetsListener(Landroid/view/View;Landroid/support/v4/view/OnApplyWindowInsetsListener;)V in class Landroid/support/v4/view/ViewCompatLollipop; or its super classes (declaration of 'android.support.v4.view.ViewCompatLollipop' appears in /data/data/com.restroshop.restroowner/files/instant-run/dex/slice-internal_impl-24.2.0_7c318f8d2adb03d07a9def5d35a14e39204ecef2-classes.dex) at android.support.v4.view.ViewCompat$LollipopViewCompatImpl.setOnApplyWindowInsetsListener(ViewCompat.java:1619) at android.support.v4.view.ViewCompat.setOnApplyWindowInsetsListener(ViewCompat.java:2924) at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:425) at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:312) at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:277) at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) at com.restroshop.restroowner.splash.SplashScreen.onCreate(SplashScreen.java:65) at android.app.Activity.performCreate(Activity.java:6033) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902) </code></pre> <p>in line <code>setContentView(R.layout.activity_splash_screen);</code></p> <p>My code snippet is </p> <pre><code>public class SplashScreen extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); // this line giving error } </code></pre> <p>I have no idea what exactly went wrong while upgrading.</p>
0
java.lang.NoClassDefFoundError: org/springframework/core/env/ConfigurableEnvironment
<p>I am trying to write a simple RESTful service using Spring Boot. However, there is an error message I am not able to solve. I have been researching and it looks like it is a conflict between SpringBoot versions, however I am not sure about how can I get rid of it. </p> <p>I have this SpringBootApp:</p> <pre><code>import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * REST Service application */ @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } </code></pre> <p>Associated with this pom.xml: </p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.websystique.springmvc&lt;/groupId&gt; &lt;artifactId&gt;Spring4MVCHelloWorldRestServiceDemo&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;name&gt;Spring4MVCHelloWorldRestServiceDemo Maven Webapp&lt;/name&gt; &lt;properties&gt; &lt;springframework.version&gt;4.3.0.RELEASE&lt;/springframework.version&gt; &lt;jackson.library&gt;2.7.5&lt;/jackson.library&gt; &lt;spring.batch.version&gt;2.1.9.RELEASE&lt;/spring.batch.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;version&gt;1.4.0.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;version&gt;${springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-web&lt;/artifactId&gt; &lt;version&gt;${springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt; &lt;version&gt;${springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.11&lt;/version&gt; &lt;!-- Or whatever JUnit you're using. --&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt; &lt;version&gt;3.1.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt; &lt;version&gt;${jackson.library}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.dataformat&lt;/groupId&gt; &lt;artifactId&gt;jackson-dataformat-xml&lt;/artifactId&gt; &lt;version&gt;${jackson.library}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.batch&lt;/groupId&gt; &lt;artifactId&gt;spring-batch-core&lt;/artifactId&gt; &lt;version&gt;${spring.batch.version}&lt;/version&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-beans&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;pluginManagement&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.2&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.7&lt;/source&gt; &lt;target&gt;1.7&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;version&gt;2.4&lt;/version&gt; &lt;configuration&gt; &lt;warSourceDirectory&gt;src/main/webapp&lt;/warSourceDirectory&gt; &lt;warName&gt;Spring4MVCHelloWorldRestServiceDemo&lt;/warName&gt; &lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/pluginManagement&gt; &lt;finalName&gt;Spring4MVCHelloWorldRestServiceDemo&lt;/finalName&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>Looks fine for me, but I am getting this error:</p> <pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/core/env/ConfigurableEnvironment at com.application.Application.main(Application.java:13) Caused by: java.lang.ClassNotFoundException: org.springframework.core.env.ConfigurableEnvironment at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 1 more </code></pre>
0
Regular Expression to find next word after the match
<p>I have a statement like <code>Data lva_var type Integer value 20</code>. I need to find out the token after <code>type</code>.</p> <p>My latest try was <code>[type](?:\s\S+)</code>, but the match was <code>e integer</code>.</p> <p>Code snippets would be helpful.</p>
0
How to add a legend to hline?
<p>I'd like to add a legend to hline plot. </p> <p>The head of my subset looks like this </p> <pre><code>Site Date Al 1 Bo6 2014-10-07 152.1 2 Bo1 2014-10-07 157.3 3 Bo3 2014-10-07 207.1 4 Bo4 2014-10-07 184.3 5 Bo5 2014-10-07 23.2 13 Bo6 2014-10-14 96.8 </code></pre> <p>My code is as follows:</p> <pre><code>require(ggplot2) require(reshape2) require(magrittr) require(dplyr) require(tidyr) setwd("~/Documents/Results") mydata &lt;- read.csv("Metals sheet Rwosnb5.csv") mydata &lt;- read.csv("Metals sheet Rwosnb5.csv") L &lt;- subset(mydata, Site =="Bo1"| Site == "Bo2"| Site == "Bo3"| Site == "Bo4"| Site == "Bo5" | Site == "Bo6", select = c(Site,Date,Al)) L$Date &lt;- as.Date(L$Date, "%d/%m/%Y") I &lt;- ggplot(data=L, aes(x=Date, y=Al, colour=Site)) + geom_point() + labs(title = "Total Al in the Barlwyd and Bowydd in Pant-yr-afon sites B4-B9 2014-2015.", x = "Month 2014/2015", y = "Total concentration (mg/L)") + scale_y_continuous(limits = c(0, 500)) + scale_x_date(date_breaks = "1 month", date_labels = "%m") I + geom_hline(aes(yintercept= 10), linetype = 2, colour= 'red', show.legend =TRUE) + geom_hline(aes(yintercept= 75.5), linetype = 2, colour= 'blue', show.legend = TRUE) </code></pre> <p>For some reason the legend does not work -- the legend has the six sites with a line through them. I would ideally like a legend with title = limit and Label 1 (10) = NRW limit and label 2 (75.5)= Geochemical atlas limit. </p>
0
homebrew - how to install older versions
<p>I'm trying to install memcached with older versions (ex: 1.4.5) but I'm not sure how to do it. </p> <p><code>brew install memcached</code> installs the latest.</p> <p>I also tried <code>brew install memecached1.4.5</code> but it didn't work.</p>
0
How to show only time picker in date range picker
<p>I am using daterange picker i want show only timepicker but its not working following is the link which is i am using for reference. </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { $('#single_cal4').daterangepicker({ singleDatePicker: true, datePicker: false, timePicker: true, }); })</code></pre> </div> </div> </p> <p><a href="http://www.daterangepicker.com/" rel="noreferrer">http://www.daterangepicker.com/</a></p>
0
MongoDB $aggregate $push multiple fields in Java Spring Data
<p>I have a mongo aggregate group query:</p> <pre><code>db.wizard.aggregate( { $group: { _id: "$title", versions: { $push: {version:"$version", author:"$author", dateAdded:"$dateAdded"}} } }) </code></pre> <p>I need this query in Java Spring-Data-MongoDB, my current solution looks like this:</p> <pre><code> Aggregation agg = Aggregation.newAggregation( Aggregation.group("title"). push("version").as("versions") ); </code></pre> <p>Problem is that i don't know how to add more fields to push method (version, author, dateAdded). Is it possible with Spring-Data-MongoDB?</p>
0
Android two way binding with Integer type causes databinding does not exist
<p>I'm having some issue with implementing two way binding with an Integer data type.</p> <pre><code>public class User { private String firstName; private String lastName; private int age; public User() {} public void setFirstName(String firstName) { this.firstName = firstName; } public String getFirstName() { return this.firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getLastName() { return this.lastName; } public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } } </code></pre> <p><strong>XML:</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;layout xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;data class="UserDataBinding"&gt; &lt;variable name="user" type="com.databinding.model.User" /&gt; &lt;/data&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="@dimen/activity_horizontal_margin"&gt; &lt;EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@={user.firstName}" /&gt; &lt;EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@={user.lastName}" /&gt; &lt;EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@={user.age}" /&gt; &lt;/LinearLayout&gt; &lt;/layout&gt; </code></pre> <p>Unfortunately, it gives me the error </p> <blockquote> <p>"Error:(52, 17) Cannot find the getter for attribute 'android:text' with value type java.lang.Integer on android.support.design.widget.TextInputEditText. "</p> </blockquote> <p>If I change the attribute text to </p> <pre><code> &lt;EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@={Integer.toString(user.age)}" /&gt; </code></pre> <p>then I get the error </p> <blockquote> <p>"Error:cannot generate view binders java.lang.NullPointerException"</p> </blockquote> <p>Appreciate any help on this.</p> <p>UPDATE: It seems there was another error right after the error mentioned above.</p> <blockquote> <p>cannot generate view binders java.lang.NullPointerException</p> </blockquote> <p>Not sure why its giving me NPE even though the app hasn't started yet.</p>
0
Windows alternative to pexpect
<p>I'm trying to write a cross-platform tool that runs specific commands, <em>expects</em> certain output for verification, and sends certain output (like username/password) for authentication.</p> <p>On Unix, I have been successful in programming a Python tool that uses the <code>pexpect</code> library (via <code>pip install pexpect</code>). This code works perfectly and is exactly what I am trying to do. I've provided a small excerpt of my code for proof-of-concept below:</p> <pre><code>self.process = pexpect.spawn('/usr/bin/ctf', env={'HOME':expanduser('~')}, timeout=5) self.process.expect(self.PROMPT) self.process.sendline('connect to %s' % server) sw = self.process.expect(['ERROR', 'Username:', 'Connected to (.*) as (.*)']) if sw == 0: pass elif sw == 1: asked_for_pw = self.process.expect([pexpect.TIMEOUT, 'Password:']) if not asked_for_pw: self.process.sendline(user) self.process.expect('Password:') self.process.sendline(passwd) success = self.process.expect(['Password:', self.PROMPT]) if not success: self.process.close() raise CTFError('Invalid password') elif sw == 2: self.server = self.process.match.groups()[0] self.user = self.process.match.groups()[1].strip() else: info('Could not match any strings, trying to get server and user') self.server = self.process.match.groups()[0] self.user = self.process.match.groups()[1].strip() info('Connected to %s as %s' % (self.server, self.user)) </code></pre> <p>I tried running the same source on Windows (changing <code>/usr/bin/ctf</code> to <code>c:/ctf.exe</code>) and I receive an error message:</p> <pre><code>Traceback (most recent call last): File ".git/hooks/commit-msg", line 49, in &lt;module&gt; with pyctf.CTFClient() as c: File "C:\git-hooktest\.git\hooks\pyctf.py", line 49, in __init__ self.process = pexpect.spawn('c:/ctf.exe', env={'HOME':expanduser('~')}, timeout=5) AttributeError: 'module' object has no attribute 'spawn' </code></pre> <p>According to the <code>pexpect</code> <a href="http://pexpect.readthedocs.io/en/stable/overview.html#windows" rel="noreferrer">documentation</a>:</p> <blockquote> <p><code>pexpect.spawn</code> and <code>pexpect.run()</code> are not available on Windows, as they rely on Unix pseudoterminals (ptys). Cross platform code must not use these.</p> </blockquote> <p>That led me on my search for a Windows equivalent. I have tried the popular <code>winpexpect</code> project <a href="https://bitbucket.org/geertj/winpexpect/wiki/Home" rel="noreferrer">here</a> and even a more recent (forked) version <a href="https://bitbucket.org/weyou/winpexpect/wiki/Home" rel="noreferrer">here</a>, but neither of these projects seem to work. I use the method:</p> <pre><code>self.process = winpexpect.winspawn('c:/ctf.exe', env={'HOME':expanduser('~')}, timeout=5) </code></pre> <p>only to sit and watch the Command Prompt do nothing (it seems as though it's trapped inside the <code>winspawn</code> method). I was wondering what other means I could go about programming a Python script to interact with the command line to achieve the same effect as I have been able to in Unix? If a suitable working Windows-version <code>pexpect</code> script does not exist, what other means could I use to go about this?</p>
0
PHP Decode base64 file contents
<p>I have a script that gets the contents of a file and encodes it using base64. This script works fine:</p> <pre><code>&lt;?php $targetPath="D:/timekeeping/logs/94-20160908.dat"; $data = base64_encode(file_get_contents($targetPath)); $file = fopen($targetPath, 'w'); fwrite($file, $data); fclose($file); echo "file contents has been encoded"; ?&gt; </code></pre> <p>Now, I want to decode the contents back to its original value. I tried:</p> <pre><code>&lt;?php $targetPath="D:/timekeeping/logs/94-20160908.dat"; $data = base64_decode(file_get_contents($targetPath)); $file = fopen($targetPath, 'w'); fwrite($file, $data); fclose($file); echo "file contents has been decoded"; ?&gt; </code></pre> <p>But does not work.</p>
0
Mark as read a specific notification in Laravel 5.3 Notifications
<p>I know that there are many ways to mark as read all notifications of an User in L5.3 like this:</p> <pre><code>$user = App\User::find(1); foreach ($user-&gt;unreadNotifications as $notification) { $notification-&gt;markAsRead(); } </code></pre> <p>Or:</p> <pre><code>$user-&gt;unreadNotifications-&gt;markAsRead(); </code></pre> <p>But suppose I want to mark as read a specific notification with a given ID. </p> <p>In fact, I have made a list of unread user notifications like this:</p> <pre><code>&lt;ul class="menu"&gt; @foreach($AuthUser-&gt;unreadNotifications as $notif) &lt;li&gt; &lt;a href="{{$notif-&gt;data['action']}}" data-notif-id="{{$notif-&gt;id}}"&gt; {{$notif-&gt;data['message']}} &lt;/a&gt; &lt;/li&gt; @endforeach &lt;/ul&gt; </code></pre> <p>As you can see, each <code>a</code> tag has a <code>data-notif-id</code> attribute contain notif ID.</p> <p>Now I want to send this ID to a script via Ajax (on click event) and mark as read that notification only. for that I wrote this:</p> <pre><code>$('a[data-notif-id]').click(function () { var notif_id = $(this).data('notifId'); var targetHref = $(this).data('href'); $.post('/NotifMarkAsRead', {'notif_id': notif_id}, function (data) { data.success ? (window.location.href = targetHref) : false; }, 'json'); return false; }); </code></pre> <p><code>NotifMarkAsRead</code> refers to bellow Controller :</p> <pre><code>class NotificationController extends Controller { public function MarkAsRead (Request $request) { //What Do I do Here........ } } </code></pre> <p>How can I do that while there is not any <code>Notification</code> Model?</p>
0
Avoid keycloak default login page and use project login page
<p>I am working on creating an angular.js web application and looking for how to integrate <code>keycloak</code> into the project. I have read and watched many tutorials and I see that most of them have users logging/registering through the default login page of <code>keycloak</code> which then redirects to the app. </p> <p>I have designed my own login and registration page which I want to use. How do I use them instead of <code>keycloak</code> default. Are there any API that I can call or may be my backend would do that? I also read there are spring adapters available for keycloak, can I use them ? Any link to any example would be good.</p> <p>The second question I have is while registering can I add more user details like address, dob, gender in <code>keycloak</code>? Because my registration page requires those information.</p>
0
ICU version compatibility Symfony 3.1
<p>I have a problem installing symfony 3.1 in php7, nginx and ubuntu 16.04, i have this error:</p> <p>intl ICU version installed on your system is outdated (55.1) and does not match the ICU data bundled with Symfony (57.1) To get the latest internationalization data upgrade the ICU system package and the intl PHP extension.</p> <p>How can i solve this issue? can i change symfony and use IC 55.1 instead of ICU 57.1? </p>
0
SpringBoot JNDI datasource throws java.lang.ClassNotFoundException: org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory
<p>Similar questions have been asked before and I went through all of those but not able to solve problem. Related Questions - <a href="https://stackoverflow.com/questions/14712308/ubuntu-tomcat7-java-lang-classnotfoundexception-org-apache-tomcat-dbcp-dbcp-bas/15880777#15880777">Q1</a>,<a href="https://stackoverflow.com/questions/25573034/spring-boot-how-do-i-set-jdbc-pool-properties-like-maximum-number-of-connection">Q2</a>,<a href="https://stackoverflow.com/questions/4711943/tomcat-dbcp-vs-commons-dbcp">Q3</a>, <a href="https://stackoverflow.com/questions/4711943/tomcat-dbcp-vs-commons-dbcp">Q4</a>, <a href="https://stackoverflow.com/questions/22518748/classnotfoundexception-when-upgraded-to-tomcat-8">Q5</a>, <a href="https://stackoverflow.com/questions/26547934/error-starting-tomcat-context-with-spring-boot-java-lang-classnotfoundexception">Q6</a></p> <p>I have a Spring Batch project with Spring Boot and trying to use DB connection pools. I am using embedded tomcat container with version 8.5.x. </p> <p>Everything works fine if I use application.properties to specify data source and pool settings. </p> <p>But when I try to use JNDI, I get exception - </p> <pre><code>Caused by: java.lang.ClassNotFoundException: org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory </code></pre> <p>I don't see any jar names <code>tomcat-dbcp-**</code> in Maven jars so I am not sure if I need to include any new dependency or need to set default data source factory and how to go about it. </p> <p>Below is my JNDI beans set up, <a href="https://stackoverflow.com/questions/24941829/how-to-create-jndi-context-in-spring-boot-with-embedded-tomcat-container">Question</a>. I have blanked out certain values. </p> <pre><code>@Bean public TomcatEmbeddedServletContainerFactory embeddedServletContainerFactory(){ return new TomcatEmbeddedServletContainerFactory() { @Override protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer( Tomcat tomcat) { tomcat.enableNaming(); return super.getTomcatEmbeddedServletContainer(tomcat); } @Override protected void postProcessContext(Context context) { ContextResource resource = new ContextResource(); resource.setName("jdbc/myDataSource"); resource.setType(DataSource.class.getName()); resource.setProperty("driverClassName", "com.ibm.db2.jcc.DB2Driver"); resource.setProperty("url", "url"); resource.setProperty("username", "user"); resource.setProperty("password", "*****"); context.getNamingResources().addResource(resource); } }; } @Lazy @Bean(destroyMethod="") public DataSource jndiDataSource() throws IllegalArgumentException, NamingException { JndiObjectFactoryBean bean = new JndiObjectFactoryBean(); bean.setJndiName("java:comp/env/jdbc/myDataSource"); bean.setProxyInterface(DataSource.class); bean.setLookupOnStartup(false); bean.afterPropertiesSet(); return (DataSource)bean.getObject(); } </code></pre> <p>My pom.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;groupId&gt;***&lt;/groupId&gt; &lt;artifactId&gt;***&lt;/artifactId&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;1.4.0.RELEASE&lt;/version&gt; &lt;/parent&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-batch&lt;/artifactId&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-logging&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-log4j&lt;/artifactId&gt; &lt;version&gt;1.2.1.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-jdbc&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;db2&lt;/groupId&gt; &lt;artifactId&gt;db2jcc&lt;/artifactId&gt; &lt;version&gt;4.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;db2&lt;/groupId&gt; &lt;artifactId&gt;db2jcc_license_cu&lt;/artifactId&gt; &lt;version&gt;4.0&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.4.0.RELEASE&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;goals&gt; &lt;goal&gt;repackage&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.1&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.7&lt;/source&gt; &lt;target&gt;1.7&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre>
0
How to get children type in react
<p>I'm trying to make my own <code>Tabs</code> component, so that I can use tabs in my app. However I seem to be having issues trying to extract the child components I need by type. </p> <pre><code>import React from 'react' export class Tabs extends React.Component { render() { let children = this.props.children let tablinks = React.Children.map(children, x =&gt; { console.log(x.type.displayName) // Always undefined if (x.type.displayName == 'Tab Link') { return x } }) return ( &lt;div className="tabs"&gt;&lt;/div&gt; ) } } export class TabLink extends React.Component { constructor(props) { super(props) this.displayName = 'Tab Link' } render() { return ( &lt;div className="tab-link"&gt;&lt;/div&gt; ) } } </code></pre> <hr> <pre><code>&lt;Tabs&gt; &lt;TabLink path="tab1"&gt;Test&lt;/TabLink&gt; &lt;TabLink path="tab2"&gt;Test2&lt;/TabLink&gt; &lt;/Tabs&gt; </code></pre> <p>My <code>console.log</code> never returns "Tab Link", it always returns <code>undefined</code>, why?</p>
0
Why am I seeing a 404 (Not Found) error failed to load favicon.ico when not using this?
<p><strong>Synopsis</strong></p> <p>After creating a simple HTML template for testing purpose, with no favicon.ico, I receive an error in the console "Failed to load resource: the server responded with a status of 404 (Not Found)" | "<a href="http://127.0.0.1:47021/favicon.ico" rel="noreferrer">http://127.0.0.1:47021/favicon.ico</a>".</p> <p>I am trying to figure out where this error is coming from and wondered if someone had any ideas to point me in the right direction. </p> <p><strong>My HTML page looks like this:</strong></p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Simple JavaScript Tester 01&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;script src="script.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>When I run this page in Chrome browser and open the console, I see the error message "Failed to load resource: the server responded with a status of 404 (Not Found)" | "<a href="http://127.0.0.1:47021/favicon.ico" rel="noreferrer">http://127.0.0.1:47021/favicon.ico</a>". I am running this on a local IIS server. I see this same error message each time I create a new page. </p> <p>Is it possible this error is coming from another page on my IIS server that I am unaware of? </p>
0
How to highlight selected item in RecyclerView
<p>I have used RecyclerView for showing thumbnails in my Image Editing app.Each item of its comprises of a ImageView(thumbnail) and a textView.In my application I want to <strong>highlight only current selected</strong> thumbnail when clicked.Gone through all the related posts on SO but couldn't find any better solution.</p> <p><strong>My Adapter Class</strong></p> <pre><code> public class FiltersAdapter extends RecyclerView.Adapter&lt;FiltersAdapter.ViewHolder&gt; { private Context mContext; private List&lt;Type&gt; mDataSet; private Uri selectedPhoto; public enum Type { Original, Grayscale, Sepia, Contrast, Invert, Pixel, Sketch, Swirl, Brightness, Vignette } public FiltersAdapter(Context context, List&lt;Type&gt; dataSet, Uri selectedPhoto) { mContext = context; mDataSet = dataSet; this.selectedPhoto = selectedPhoto; } @Override public FiltersAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(mContext).inflate(R.layout.list_item_layout, parent, false); return new ViewHolder(v); } @Override public void onBindViewHolder(FiltersAdapter.ViewHolder holder, int position) { switch (mDataSet.get(position)) { case Original: holder.image.setImageResource(R.drawable.no_filter); break; case Grayscale: Picasso.with(mContext) .load(R.drawable.no_filter) .transform(new GrayscaleTransformation()) .into(holder.image); break; case Sepia: Picasso.with(mContext) .load(R.drawable.no_filter) .transform(new SepiaFilterTransformation(mContext)) .into(holder.image); break; case Contrast: Picasso.with(mContext) .load(R.drawable.no_filter) .transform(new ContrastFilterTransformation(mContext, 2.0f)) .into(holder.image); break; case Invert: Picasso.with(mContext) .load(R.drawable.no_filter) .transform(new InvertFilterTransformation(mContext)) .into(holder.image); break; case Pixel: Picasso.with(mContext) .load(R.drawable.no_filter) .transform(new PixelationFilterTransformation(mContext, 20)) .into(holder.image); break; case Sketch: Picasso.with(mContext) .load(R.drawable.no_filter) .transform(new SketchFilterTransformation(mContext)) .into(holder.image); break; case Swirl: Picasso.with(mContext) .load(R.drawable.no_filter) .transform(new SwirlFilterTransformation(mContext, 0.5f, 1.0f, new PointF(0.5f, 0.5f))) .into(holder.image); break; case Brightness: Picasso.with(mContext) .load(R.drawable.no_filter) .transform(new BrightnessFilterTransformation(mContext, 0.5f)) .into(holder.image); break; case Vignette: Picasso.with(mContext) .load(R.drawable.no_filter) .transform(new VignetteFilterTransformation(mContext, new PointF(0.5f, 0.5f), new float[]{0.0f, 0.0f, 0.0f}, 0f, 0.75f)) .into(holder.image); break; default: holder.image.setImageResource(R.drawable.no_filter); break; } holder.title.setText(mDataSet.get(position).name()); } @Override public void onViewAttachedToWindow(ViewHolder holder) { super.onViewAttachedToWindow(holder); } @Override public int getItemCount() { return mDataSet.size(); } @Override public int getItemViewType(int position) { return position; } static class ViewHolder extends RecyclerView.ViewHolder { public ImageView image; public TextView title; ViewHolder(View itemView) { super(itemView); image = (ImageView) itemView.findViewById(R.id.thumbnailImage); title = (TextView) itemView.findViewById(R.id.title); } } } </code></pre> <p><strong>Fragment Code</strong></p> <pre><code>horizontalFilters = (RecyclerView) mView.findViewById(R.id.rvHorizontal); LinearLayoutManager horizontalLayoutManagaer = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false); horizontalFilters.setLayoutManager(horizontalLayoutManagaer); List&lt;Type&gt; dataSet = new ArrayList&lt;&gt;(); dataSet.add(Type.Original); dataSet.add(Type.Grayscale); dataSet.add(Type.Sepia); dataSet.add(Type.Contrast); dataSet.add(Type.Invert); dataSet.add(Type.Pixel); dataSet.add(Type.Sketch); dataSet.add(Type.Swirl); dataSet.add(Type.Brightness); dataSet.add(Type.Vignette); horizontalFilters.setAdapter(new FiltersAdapter(act, dataSet, selectedPhotoUri)); horizontalFilters.addOnItemTouchListener(new RecyclerClick(act, horizontalFilters, new RecyclerClickListener() { @Override public void onClick(View view, int position) { switch (position){ case 0: photo.setImageDrawable(drawable); break; case 1: Picasso.with(act) .load(selectedPhotoUri) .transform(new GrayscaleTransformation()) .into(photo); break; case 2: Picasso.with(act) .load(selectedPhotoUri) .transform(new SepiaFilterTransformation(act)) .into(photo); break; case 3: Picasso.with(act) .load(selectedPhotoUri) .transform(new ContrastFilterTransformation(act, 2.0f)) .into(photo); break; case 4: Picasso.with(act) .load(selectedPhotoUri) .transform(new InvertFilterTransformation(act)) .into(photo); break; case 5: Picasso.with(act) .load(selectedPhotoUri) .transform(new PixelationFilterTransformation(act, 20)) .into(photo); break; case 6: Picasso.with(act) .load(selectedPhotoUri) .transform(new SketchFilterTransformation(act)) .into(photo); break; case 7: Picasso.with(act) .load(selectedPhotoUri) .transform(new SwirlFilterTransformation(act, 0.5f, 1.0f, new PointF(0.5f, 0.5f))) .into(photo); break; case 8: Picasso.with(act) .load(selectedPhotoUri) .transform(new BrightnessFilterTransformation(act, 0.5f)) .into(photo); break; case 9: Picasso.with(act) .load(selectedPhotoUri) .transform(new VignetteFilterTransformation(act, new PointF(0.5f, 0.5f), new float[]{0.0f, 0.0f, 0.0f}, 0f, 0.75f)) .into(photo); break; default: photo.setImageDrawable(drawable); break; } } @Override public void onLongClick(View view, int position) { } })); } </code></pre>
0
Increasing Heap size on Linux system
<p>I work on linux machine and I'd like to set min heap size and also want to increase the max heap size for Java. The RAM is 4GB and the current Max Heap Size is 1GB. Can you please guide me up to what value can I increase the max heap and also what min heap size I need to set for the above configuration.</p>
0
Installing application and uninstalling does not remove completly - Android Studio
<p>I got a strange issue in few of my recent applications.</p> <p><strong><em>What I did:</em></strong></p> <ul> <li>Installing an application either directly using USB cable with Android Studio . Or downloading and installing signed APK through my local server.</li> <li>Application works fine in all aspects</li> <li>Uninstalling the application by long press and dragging the app icon to Uninstall icon </li> <li>Or uninstalling through Settings -> Apps -> Uninstall by selecting the app</li> </ul> <p><strong><em>Problem:</em></strong></p> <ul> <li>After uninstall , under Settings -> Apps -> Still the app is shown as below</li> </ul> <p><a href="https://i.stack.imgur.com/LSjcp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LSjcp.png" alt="enter image description here"></a></p> <ul> <li>My application still shows in the list at the bottom with <strong>NOT INSTALLED FOR THIS USER</strong> message</li> <li>I am not sure why this is happening. For majority of devices again <strong>downloading/installing new APK version from local server does not work unless I again uninstall by clicking on above list and goes to next screen as shown below</strong>.</li> </ul> <p><a href="https://i.stack.imgur.com/mGRgr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mGRgr.png" alt="enter image description here"></a></p> <ol> <li>What might be causing this? </li> <li>Does any other developer faced same issue?</li> </ol> <blockquote> <p>Android Studio Version : 2.1.3 <br> Min SDK in Manifest : 17<br> Devices Tested : Nexus 4 , OnePlus 3 , Motorolla Gen-3 , Honor </p> </blockquote> <p><strong>Different Trials Made:</strong> Device is having only one user <code>Owner</code> </p> <ol> <li>Now I have uninstalled an application which was downloaded from App store. This was done successfully <strong>without</strong> giving an option again with <strong>NOT INSTALLED FOR THIS USER</strong></li> <li>Again complete removal of my application and reinstalling is done. After this , I tried to uninstall again.The same options are shown for my application <strong>NOT INSTALLED FOR THIS USER</strong> </li> <li>Seems to be this is the issue with custom applications and not those installed from App Store. In-fact some steps which probably I am missing. Can anyone point out!!</li> </ol>
0
How to exclude some url from jersey filter?
<p>I've used jersey to create webservices. I've created request filter using <code>ContainerRequestFilter</code>. I've gone through <a href="https://stackoverflow.com/questions/23641345/jersey-request-filter-only-on-certain-uri">Jersey Request Filter only on certain URI</a> question but I want to exclude filter for some urls only. </p> <pre><code>@Provider public class AuthFilter implements ContainerRequestFilter{ @Override public void filter(ContainerRequestContext requestContext) throws IOException { // business logic } } </code></pre>
0
How to set Jenkinsfile for upload maven artifact to Artifactory
<p>I've my .Jenkinsfile like this:</p> <pre><code>properties([[$class: 'GitLabConnectionProperty', gitLabConnection: 'gitlab@srv']]) node { env.JAVA_HOME = tool 'JDK 7' def mvnHome = tool 'Maven 3.2.2' def nodeJS = tool 'IA_NodeJS' env.PATH = "${mvnHome}/bin:${nodeJS}/bin:${env.JAVA_HOME}/bin:${env.PATH}" stage ('checkout') { checkout scm } stage ('build') { gitlabCommitStatus("build") { // your build steps sh 'mvn clean install -Denv=dev -P !faster' } } stage ('upload') { gitlabCommitStatus("upload") { def server = Artifactory.server "artifactory@ibsrv02" def buildInfo = Artifactory.newBuildInfo() buildInfo.env.capture = true buildInfo.env.collect() def uploadSpec = """{ "files": [ { "pattern": "**/target/*.jar", "target": "libs-snapshot-local" }, { "pattern": "**/target/*.pom", "target": "libs-snapshot-local" }, { "pattern": "**/target/*.war", "target": "libs-snapshot-local" } ] }""" // Upload to Artifactory. server.upload spec: uploadSpec, buildInfo: buildInfo buildInfo.retention maxBuilds: 10, maxDays: 7, deleteBuildArtifacts: true // Publish build info. server.publishBuildInfo buildInfo } } } </code></pre> <p>with this method jenkins uploads artifacts without make the "maven's style" layout (packages subfolder and poms).</p> <p>I want to upload resulting artifact to Artifactory like a normal job uploads it with "Maven3-Artifactory Integration" checked.</p>
0
how to access django form field name in template
<p>I've got a modelform that I would like to iterate through the form fields in the template but at the same time, when I encounter certain fields, to conditionally render extra html. Currently I am pulling the field name from <code>field.html_name</code> but I am not sure if that is the best way (it feels hackish somehow, like I should be using a <code>getattr()</code> filter or something...).</p> <pre><code>{% for field in form %} &lt;div class="form-group"&gt; {{ field }} {% if field.html_name == "location" %} &lt;!-- CUSTOM HTML HERE --&gt; {% endif %} &lt;/div&gt; {% endfor %} </code></pre>
0
Localization in ASP.Net core MVC not working - unable to locate resource file
<p>In trying to localize my application, I've followed the steps here: <a href="https://docs.asp.net/en/latest/fundamentals/localization.html" rel="noreferrer">https://docs.asp.net/en/latest/fundamentals/localization.html</a></p> <p>Here is my code:</p> <p><strong>Startup.cs</strong></p> <pre><code>public List&lt;IRequestCultureProvider&gt; RequestCultureProviders { get; private set; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddLocalization(options =&gt; options.ResourcesPath = "Resources"); services.AddMvc() .AddViewLocalization(options =&gt; options.ResourcesPath = "Resources") .AddDataAnnotationsLocalization(); services.AddOptions(); services.AddTransient&lt;IViewRenderingService, ViewRenderingService&gt;(); services.AddTransient&lt;IEmailSender, EmailSender&gt;(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { var locOptions = app.ApplicationServices.GetService&lt;IOptions&lt;RequestLocalizationOptions&gt;&gt;(); app.UseRequestLocalization(locOptions.Value); app.UseStaticFiles(); app.UseFileServer(new FileServerOptions() { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory())), EnableDirectoryBrowsing = true }); var supportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("fr"), }; app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("fr"), // Formatting numbers, dates, etc. SupportedCultures = supportedCultures, // UI strings that we have localized. SupportedUICultures = supportedCultures, RequestCultureProviders = new List&lt;IRequestCultureProvider&gt; { new QueryStringRequestCultureProvider { QueryStringKey = "culture", UIQueryStringKey = "ui-culture" } } }); } </code></pre> <p><strong>MyController.cs</strong></p> <pre><code>public class MyController : Controller { private readonly IViewRenderingService _viewRenderingService; private IStringLocalizer&lt;MyController&gt; _localizer; private MyOptions _options; //Constructor for dependency injection principle public MyController(IViewRenderingService viewRenderingService, IStringLocalizer&lt;MyController&gt; localizer, IOptions&lt;MyOptions&gt; options) { _viewRenderingService = viewRenderingService; _localizer = localizer; _options = options.Value; } [HttpGet] public string Get() { // _localizer["Name"] return _localizer["Product"]; } } </code></pre> <p>The <code>*.resx</code> file is stored in the <code>Resources</code> folder, with the name <code>Controllers.MyController.fr.resx</code> (which has an entry for "Product").</p> <p>However, it's not able to find the resource file, and "Product" is never returned in French. I am using querystring, so here is the query string:</p> <pre><code>localhost:3333/my?culture=fr </code></pre> <p>Also in the View, <code>@Localizer["Product"]</code> returns "Product".</p> <p>Can anyone please help me find whats missing?</p> <p><strong>EDIT:</strong></p> <p>After some investigation, I found that culture is getting changed, however it is unable to locate the Resource file. I am using VS2015. can anyone help?</p>
0
How to return a proper Promise with TypeScript
<p>So I am learning Angular 2 with typescript.</p> <p>I am reaching a point to write a mocking service which (I believe) should return a Promise if the service get the Object Successfully and Return an Error if anything happens.</p> <p>I have tried following code but looks like it is not a write syntax for typescript.</p> <p>Updated the CODE:</p> <pre><code>saveMyClass(updatedMyClass: MyClass){ //saving MyClass using http service //return the saved MyClass or error var savedMyClass : MyClass = someLogicThatReturnsTheSavedObject(updatedMyClass); if(isSomeCondition) return Promise.reject(new Error('No reason but to reject')); else return new Promise&lt;MyClass&gt;(resolve =&gt; {setTimeout( ()=&gt;resolve(savedMyClass),1500 )} ); } </code></pre> <p>But to my surprise, the typescript complained that "No best common type exists among return expressions".</p> <p>What should be the right code? So that I could use on my component to consume if proper MyClass is returned and reflect error if any exists from service.</p> <p>Thanks</p>
0
How can I add and remove an active class to an element in pure JavaScript
<p>I am trying to make a navigation menu I did all the <em>HTML</em> and <em>CSS</em> when come to <em>javascript</em> I am struck in the middle I am able to add a class to the element, but I am not able to remove the class remaining elements. Please help me with this.<br> here is my code</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Navigation class Toggling&lt;/title&gt; &lt;style type="text/css"&gt; * { margin: 0; padding: 0; box-sizing: border-box; } header { width: 100%; height: auto; max-width: 600px; margin: 0 auto; } nav { width: 100%; height: 40px; background-color: cornflowerblue; } ul { list-style-type: none; } li { display: inline-block; } a { text-decoration: none; padding: 8px 15px; display: block; text-transform: capitalize; background-color: darkgray; color: #fff; } a.active { background-color: cornflowerblue; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;nav&gt; &lt;ul onclick="myFunction(event)"&gt; &lt;li&gt;&lt;a href="#"&gt;home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;about&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;service&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;profile&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;portfolio&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/header&gt; &lt;script type="text/javascript"&gt; function myFunction(e) { e.target.className = "active"; } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and here is my <a href="http://codepen.io/venumadhavdiv/pen/grEXpx" rel="noreferrer"><strong>Codepen</strong></a></p>
0
"unable to locate adb" using Android Studio
<p>I have been trying to test my app on real device. I keep receiving error message that <code>"unable to locate adb"</code>. I have the USB driver for my phone installed. Thank you for the help. The snap shot is shown below. <img src="https://i.stack.imgur.com/6z0SA.png" alt="Snap shot"></p>
0
AttributeError: 'module' object has no attribute 'graphviz_layout' with networkx 1.11
<p>I'm trying to draw some DAGs using networkx 1.11 but I'm facing some errors, here's the test:</p> <pre><code>import networkx as nx print nx.__version__ G = nx.DiGraph() G.add_node(1,level=1) G.add_node(2,level=2) G.add_node(3,level=2) G.add_node(4,level=3) G.add_edge(1,2) G.add_edge(1,3) G.add_edge(2,4) import pylab as plt nx.draw_graphviz(G, node_size=1600, cmap=plt.cm.Blues, node_color=range(len(G)), prog='dot') plt.show() </code></pre> <p>And here's the traceback:</p> <pre><code>Traceback (most recent call last): File "D:\sources\personal\python\framework\stackoverflow\test_dfs.py", line 69, in &lt;module&gt; prog='dot') File "d:\virtual_envs\py2711\lib\site-packages\networkx\drawing\nx_pylab.py", line 984, in draw_graphviz pos = nx.drawing.graphviz_layout(G, prog) AttributeError: 'module' object has no attribute 'graphviz_layout' </code></pre> <p>I'm using python 2.7.11 x64, networkx 1.11 and I've installed <a href="http://www.graphviz.org/Download_windows.php" rel="noreferrer">graphviz-2.38</a> having <code>dot</code> available in PATH. What am I missing?</p> <p>Once it works, how could i draw the graph with nodes which:</p> <ul> <li>Use white background color </li> <li>Have labels inside</li> <li>Have directed arrows</li> <li>Are arranged nicely either automatically or manually</li> </ul> <p>Something similar to the below image</p> <p><a href="https://i.stack.imgur.com/Vhuai.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Vhuai.png" alt="enter image description here"></a></p> <p>As you can see in that image, nodes are aligned really nicely</p>
0
Laravel 5.1 form - 'files' => true
<p>I use Laravel HTML to create form but I have problem, so in creating form I have:</p> <pre><code>{!! Form::open(['url'=&gt;'vocuhers','files' =&gt; 'true','enctype'=&gt;'multipart/form-data']) !!} @include('vouchers.form',['submitButtonText'=&gt;'Click to Add New Vocuher']) {!! Form::close() !!} </code></pre> <p>But when I see my HTML form in browser there is just:</p> <pre><code>&lt;form method="POST" action="http://localhost:8888/vouchers" accept-charset="UTF-8"&gt; &lt;input name="_token" type="hidden" value="dfgdfgdfgdfgdf"&gt; </code></pre> <p>so where is </p> <pre><code>enctype="multipart/form-data" </code></pre> <p>which allow me to upload files from form ?</p> <p>Why I don't get this HTML output:</p> <pre><code>&lt;form method="POST" action="https://bedbids.com/chats" accept-charset="UTF-8" enctype="multipart/form-data"&gt; &lt;input name="_token" type="hidden" value="dsfdfgdfgdfgdfg"&gt; </code></pre> <p>What is the problem here exactly ?</p>
0
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
<p>I'm setting up a new server and keep running into this problem.</p> <p>When I try to log into the MySQL database with the root user, I get the error:</p> <blockquote> <p>ERROR 1698 (28000): Access denied for user 'root'@'localhost'</p> </blockquote> <p>It doesn't matter if I connect through the terminal (SSH), through <a href="https://en.wikipedia.org/wiki/PhpMyAdmin" rel="noreferrer">phpMyAdmin</a> or a MySQL client, e.g., <a href="https://en.wikipedia.org/wiki/Navicat" rel="noreferrer">Navicat</a>. They all fail.</p> <p>I looked in the <em>mysql.user</em> table and get the following:</p> <pre class="lang-none prettyprint-override"><code>+------------------+-------------------+ | user | host | +------------------+-------------------+ | root | % | | root | 127.0.0.1 | | amavisd | localhost | | debian-sys-maint | localhost | | iredadmin | localhost | | iredapd | localhost | | mysql.sys | localhost | | phpmyadmin | localhost | | root | localhost | | roundcube | localhost | | vmail | localhost | | vmailadmin | localhost | | amavisd | test4.folkmann.it | | iredadmin | test4.folkmann.it | | iredapd | test4.folkmann.it | | roundcube | test4.folkmann.it | | vmail | test4.folkmann.it | | vmailadmin | test4.folkmann.it | +------------------+-------------------+ </code></pre> <p>As you can see, user <em>root</em> should have access.</p> <p>The Server is quite simple, as I have tried to troubleshoot this for a while now.</p> <p>It's running <a href="https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_16.04_LTS_.28Xenial_Xerus.29" rel="noreferrer">Ubuntu 16.04.1</a> LTS (Xenial Xerus) with Apache, MySQL and PHP, so that it can host websites, and iRedMail 0.9.5-1, so that it can host mail.</p> <p>Log into the MySQL database works fine before I installed iRedMail. I also tried just installing iRedMail, but then root also doesn't work.</p> <p>How can I fix my MySQL login problem or how can I install iRedMail over an existing MySQL install? And yes, I tried the <a href="https://code.google.com/archive/p/iredmail/wikis/Installation_Tips.wiki" rel="noreferrer">Installation Tips</a> and I can't find those variables in the configuration files.</p>
0
how to set default value to null for datetime variable in Json
<p>i use a json and the class definition is described below</p> <p>how do i set a default value of null for </p> <blockquote> <pre><code>[JsonProperty("Time2ATR")] public DateTime time2atr { get; set; } </code></pre> </blockquote> <p>so i dont get a default value of "0001-01-01T00:00:00" if i dont assign any value to it?</p> <blockquote> <p>full code and datasample below</p> </blockquote> <pre><code> using Newtonsoft.Json; // This namespace holds all indicators and is required. Do not change it. namespace NinjaTrader.STSClasses { /// &lt;summary&gt; /// This file holds all user defined indicator methods. /// &lt;/summary&gt; public class STSmyTrade { [JsonProperty("direction")] public string direction { get; set; } [JsonProperty("entryprice")] public double entry { get; set; } [JsonProperty("exitprice")] public double exit { get; set; } [JsonProperty("potentialtarget")] public double potentialtarget { get; set; } [JsonProperty("entrytime")] public DateTime entrytime { get; set; } [JsonProperty("exittime")] public DateTime exittime { get; set; } [JsonProperty("maxfavourable")] public double mfe { get; set; } [JsonProperty("maxagainst")] public double mae { get; set; } [JsonProperty("maxagainst1ATR")] public double mae1atr { get; set; } [JsonProperty("Time1ATR")] public DateTime time1atr { get; set; } [JsonProperty("maxagainst2ATR")] public double mae2atr { get; set; } [JsonProperty("Time2ATR")] public DateTime time2atr { get; set; } [JsonProperty("gains")] public double gains { get; set; } [JsonProperty("signal")] public string signal { get; set; } [JsonProperty("instrument")] public string instrument { get; set; } [JsonProperty("account")] public string account { get; set; } [JsonProperty("quantity")] public int quantity { get; set; } [JsonProperty("hitedge")] public bool hitedge { get; set; } [JsonProperty("RealizedProfitLoss")] public double RealizedProfitLoss { get; set; } [JsonProperty("CashValue")] public double CashValue { get; set; } [JsonProperty("BuyingPower")] public double BuyingPower { get; set; } } } { "direction": "Long", "entryprice": 1.13211, "exitprice": 1.13197, "potentialtarget": 0.00025, "entrytime": "2016-08-22T13:46:31.7459655-04:00", "exittime": "2016-08-22T15:46:22.3955682-04:00", "maxfavourable": 0.00055, "maxagainst": -0.00035, "maxagainst1ATR": -0.00035, "Time1ATR": "0001-01-01T00:00:00", "maxagainst2ATR": -0.00035, "Time2ATR": "0001-01-01T00:00:00", "gains": -0.00015, "signal": "EnterLongBounce", "instrument": "$EURUSD", "account": "InteractiveBrokersindicatorbased", "quantity": 1, "hitedge": false, "RealizedProfitLoss": 0.0, "CashValue": 0.0, "BuyingPower": 0.0 }'); </code></pre>
0
Run a Macro from C#
<p>I am aware you can use <code>Microsoft.Office.Interop.Excel;</code> to use VBA commands inside of a C# program.</p> <p>I have VBA that is close to 10,000 lines of code and translating that into C# compatible commands is just unrealistic. It creates a workbook and performs data manipulation and formatting to be printed as the user requests.</p> <p>Is there a way of storing the macro in C# and creating a workbook that I can then run the macro on as is?</p>
0
How can I view hidden characters in Notepad++?
<p>I have a string that has been giving some of my code fits of rage and its got "extra" characters in it that I only stumbled upon by using the arrow keys to go through it. I noticed that the cursor stayed in place in certain areas for an extra keystroke of the arrow key. Using View >Show Symbols > Show All Characters still didnt seem to indicate anything there. What kind of character could be there and is there a plugin for it?</p>
0
'User' object has no attribute 'UserProfile'
<p>I tried following the example at <a href="https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#extending-the-existing-user-model" rel="noreferrer">https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#extending-the-existing-user-model</a> on how to extend the user model. But I cannot retrieve the model data which I attached to the User. </p> <p>model</p> <pre><code>from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ip = models.IntegerField(default=0) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) </code></pre> <p>getting my User object </p> <pre><code>user = auth.authenticate(username=username, password=password) g = user.UserProfile.ip print(g) </code></pre> <p>The user gets fetched properly, and I'm able to get all the data that are with the standard user. But user.UserProfile will result in:</p> <pre><code>Internal Server Error: /Crowd/login/ Traceback (most recent call last): File "C:\Anaconda3\Lib\site-packages\django\core\handlers\base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "C:\Anaconda3\Lib\site-packages\django\core\handlers\base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Rasmus\workspace\Crowd\src\Cr\views.py", line 35, in login g = user.UserProfile.ip AttributeError: 'User' object has no attribute 'UserProfile' [05/Sep/2016 04:32:46] "POST /Crowd/login/ HTTP/1.1" 500 69185 </code></pre> <p>I checked my database and I can see that there's a row in UserProfile which has a relation with User. So UserProfile is getting created properly(I assume). </p>
0
Log4j 2 JSON pattern layout + Logging JSON payload
<p>I am using ELK stack along with <strong>log4j 2 via sl4j with <code>json</code> pattern layout</strong> to log messages. All my logs are logged as <code>json</code> messages.Also in one of my logs I am trying to log the <code>json</code> response received from the third party service. But this response <code>json</code> body is not appended to the <code>json</code> structure. But it rather appended as a string including the escape characters.</p> <p><strong>how the ultimate logs being logged out.</strong></p> <pre><code> { "timeMillis": 1471862316416, "thread": "FioranoMQ Pubsub Session Thread", "level": "INFO", "loggerName": "com.mlp.eventing.bridge.fiorano.TopicMessageListener", "message": "{\"Msgtype\":\"SentToRabbitMqTest\",\"MessageData\":\"10\",\"opration\":\"devide\"}", "endOfBatch": false, "loggerFqcn": "org.apache.logging.slf4j.Log4jLogger", "threadId": 28, "threadPriority": 5 } </code></pre> <p>In above message segment is appended as escaped strings rather than the entire <code>json</code> structure. My expected out put should be</p> <pre><code>{ "timeMillis": 1471862316416, "thread": "FioranoMQ Pubsub Session Thread", "level": "INFO", "loggerName": "com.mlp.eventing.bridge.fiorano.TopicMessageListener", "message": { "Msgtype": "SentToRabbitMqTest", "MessageData": "10", "opration": "devide" }, "endOfBatch": false, "loggerFqcn": "org.apache.logging.slf4j.Log4jLogger", "threadId": 28, "threadPriority": 5 } </code></pre> <p>I am expecting to extract the fields in the message segment using the grok filters for <code>json</code> in <code>shipper.conf</code></p> <p>Below are my configurations :- log4j2.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Configuration status="info"&gt; &lt;!-- log4j internals tracing --&gt; &lt;properties&gt; &lt;property name="pattern"&gt;%d{yyyy-MM-dd HH:mm:ss.SSS} | %-5.5p | %-20.20C:%-5.5L | %msg%n&lt;/property&gt; &lt;property name="filePath"&gt;/opt/mlp/logs&lt;/property&gt; &lt;property name="fileName"&gt;logs&lt;/property&gt; &lt;/properties&gt; &lt;Appenders&gt; &lt;RollingFile name="RollingFile" fileName="${filePath}/${fileName}.log" filePattern="${filePath}/${fileName}-%d{yyyy-MM-dd}-%i.log" append="true"&gt; &lt;JSONLayout complete="false" compact="true" eventEol="true" /&gt; &lt;PatternLayout&gt; &lt;pattern&gt;${pattern}&lt;/pattern&gt; &lt;/PatternLayout&gt; &lt;Policies&gt; &lt;SizeBasedTriggeringPolicy size="1000 KB"/&gt; &lt;/Policies&gt;l &lt;/RollingFile&gt; &lt;Console name="STDOUT" target="SYSTEM_OUT"&gt; &lt;PatternLayout&gt; &lt;pattern&gt;${pattern}&lt;/pattern&gt; &lt;/PatternLayout&gt; &lt;/Console&gt; &lt;/Appenders&gt; &lt;Loggers&gt; &lt;Root level="debug"&gt; &lt;AppenderRef ref="RollingFile"/&gt; &lt;AppenderRef ref="STDOUT"/&gt; &lt;/Root&gt; &lt;/Loggers&gt; &lt;/Configuration&gt; </code></pre> <p>sample code snippet </p> <pre><code>import org.slf4j.Logger; import org.slf4j.LoggerFactory; class A { private static final Logger LOG = LoggerFactory.getLogger(Main.class); public void testMethod() { JSONObject responseJson = callService();// json simple object LOG.info(responseJson); } } </code></pre> <p>maven dependencies </p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt; &lt;version&gt;1.7.21&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j-slf4j-impl&lt;/artifactId&gt; &lt;version&gt;2.6.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- end adding sl4j 2 for the message bridge --&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j-api&lt;/artifactId&gt; &lt;version&gt;2.6.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j-core&lt;/artifactId&gt; &lt;version&gt;2.6.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- to enable json support for log4j enable following libraries --&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-core&lt;/artifactId&gt; &lt;version&gt;2.7.5&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt; &lt;version&gt;2.7.5&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-annotations&lt;/artifactId&gt; &lt;version&gt;2.7.5&lt;/version&gt; &lt;/dependency&gt; </code></pre>
0
Get all possible sums from a list of numbers
<p>Let's say I have a list of numbers: 2, 2, 5, 7</p> <p>Now the result of the algorithm should contain all possible sums. </p> <p>In this case: 2+2, 2+5, 5+7, 2+2+5, 2+2+5+7, 2+5+7, 5+7</p> <p>I'd like to achieve this by using Dynamic Programming. I tried using a matrix but so far I have not found a way to get all the possibilities.</p>
0
Electron cookie
<p>For electron cookie I used <a href="https://www.npmjs.com/package/electron-cookies" rel="nofollow">https://www.npmjs.com/package/electron-cookies</a></p> <p>Then added this into my html</p> <pre><code>&lt;script type="text/javascript"&gt; require('electron-cookies') function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function getCookie12(name) { var regexp = new RegExp("(?:^" + name + "|;\s*"+ name + ")=(.*?)(?:;|$)", "g"); var result = regexp.exec(document.cookie); alert(document.cookie); return (result === null) ? null : result[1]; } &lt;/script&gt; </code></pre> <p>and called the methods :</p> <pre><code>&lt;button onclick="createCookie('ppkcookie','testcookie',7)"&gt;Set Cookie&lt;/button&gt; &lt;button onclick="getCookie12('ppkcookie')"&gt;Get Cookie&lt;/button&gt; </code></pre> <p>but the <code>alert(document.cookie)</code> shows me only </p> <p><code>ppkcookie</code> not <code>ppkcookie=testcookie</code></p> <p>Any ideas why?</p> <p>Many thanks</p>
0
How to install Python 3.5 on Raspbian Jessie
<p>I need to install Python 3.5+ on Rasbian (Debian for the Raspberry Pi). Currently only version 3.4 is supported. For the sources I want to compile I have to install:</p> <pre><code>sudo apt-get install -y python3 python-empy python3-dev python3-empy python3-nose python3-pip python3-setuptools python3-vcstool pydocstyle pyflakes python3-coverage python3-mock python3-pep8 </code></pre> <p>But I think that <code>apt-get</code> will install more than these packages, for example <code>libpython3-dev</code>.</p> <p>I already install <code>python3</code> from <a href="https://www.python.org/downloads/" rel="nofollow noreferrer">https://www.python.org/downloads/</a> but I think, that is not complete.</p> <p>Can you give me some suggestion which way is the best to get this?</p> <p>A similar question was posted here <a href="https://stackoverflow.com/questions/35385423/install-python-3-5-with-pip-on-debian-8">Install Python 3.5 with pip on Debian 8</a> but this solution seems not to work on arm64.</p> <hr> <p>Edit:</p> <p>regarding to the comment of Padraic Cunningham: The first step I have done before. The second one results into this:</p> <pre><code>$ sudo python3.5 get-pip.py Traceback (most recent call last): File "get-pip.py", line 19177, in &lt;module&gt; main() File "get-pip.py", line 194, in main bootstrap(tmpdir=tmpdir) File "get-pip.py", line 82, in bootstrap import pip File "/tmp/tmpoe3rjlw3/pip.zip/pip/__init__.py", line 16, in &lt;module&gt; File "/tmp/tmpoe3rjlw3/pip.zip/pip/vcs/subversion.py", line 9, in &lt;module&gt; File "/tmp/tmpoe3rjlw3/pip.zip/pip/index.py", line 30, in &lt;module&gt; File "/tmp/tmpoe3rjlw3/pip.zip/pip/wheel.py", line 39, in &lt;module&gt; File "/tmp/tmpoe3rjlw3/pip.zip/pip/_vendor/distlib/scripts.py", line 14, in &lt;module&gt; File "/tmp/tmpoe3rjlw3/pip.zip/pip/_vendor/distlib/compat.py", line 66, in &lt;module&gt; ImportError: cannot import name 'HTTPSHandler' </code></pre>
0
How to install Scala plugin for IntelliJ
<p>I've installed IntelliJ IDEA and scala on my Windows machine, but those are not integrated and I'm not able to use scala in IntelliJ. How can I configure and use both?</p>
0
PrimeNG - How to dynamically add and remove a p-tabPanel in p-tabView component
<p>I'm on a project where I need to use a p-tabView. A new p-tabPanel is to be created when clicking on a button in the p-tabView.</p> <p>How can I dynamically add new panels to a p-tabView?</p>
0
nunjucks: Template not found
<p>Trying to render a nunjucks template but getting <code>Error: template not found: email.html</code>.</p> <pre><code>server/ views/ email/ email.html workers/ email.worker.js </code></pre> <pre><code>//email.worker.js function createMessage(articles) { console.log(__dirname) // /&lt;path&gt;/server/workers nunjucks.configure('../views/email/'); return nunjucks.render('email.html', articles); } </code></pre> <p>No idea what's wrong here.</p>
0
Android instrumented test no tests found
<p>I am new to Android instrumented unit tests. I have a simple test that looks like this. This is in instrumented tests; before I really write an actual instrumented test, I just want to test a simple one:</p> <pre><code>@RunWith(AndroidJUnit4.class) @SmallTest public class AddressBookKeepingInstrumentedTest { public static final String TEST_STRING = "This is a string"; public static final long TEST_LONG = 12345678L; @Test public void test_simple() { assertEquals(2,1+1); } } </code></pre> <p>When I run this, I get the following error:</p> <pre><code>junit.framework.AssertionFailedError: No tests found in com.example.myfirstapp.AddressBookKeepingInstrumentedTest at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191) at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176) at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554) at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1729) Tests ran to completion. </code></pre> <p>Gradle build passed with success before this. Any ideas why this is happening?</p>
0
Entity Framework + sql injection
<p>I'm building up an <code>IQueryable</code> where I am applying relevant filters, and I come across this line of code here.</p> <pre><code>items = items.OrderBy(string.Format("{0} {1}", sortBy, sortDirection)); </code></pre> <p>Is this snippet vulnerable to SQL injection? Or are these (string) parameters parameterized behind the scenes? I assumed that all Linq queries were escaped and parameterized for me, but the fact that I am able to pass in a string directly like this is throwing me off.</p>
0
Python read named PIPE
<p>I have a named pipe in linux and i want to read it from python. The problem is that the python process 'consumes' one core (100%) continuously. My code is the following:</p> <pre><code>FIFO = '/var/run/mypipe' os.mkfifo(FIFO) with open(FIFO) as fifo: while True: line = fifo.read() </code></pre> <p>I want to ask if the 'sleep' will help the situation or the process going to loss some input data from pipe. I can't control the input so i don't know the frequency of data input. I read about select and poll but i didn't find any example for my problem. Finally, i want to ask if the 100% usage will have any impact on the data input(loss or something?).</p> <p>edit: I don't want to break the loop. I want the process runs continuously and 'hears' for data from the pipe.</p>
0
How to install sagemath kernel in Jupyter
<p>I could use Python Kernel with Jupyter. I am looking for a way to use sagemath inside Jupyter.I couldnt see a way for installing it. How to do that?</p>
0
Access device's register i2c
<p>I recently bought a <a href="http://playground.arduino.cc/uploads/Main/mpu-6050.jpg" rel="nofollow noreferrer">gy-521 board</a> and I'm trying to use it with a Raspberry Pi 3 through the following connections</p> <pre><code>RPi3 | GY-521 --------------------- 3.3V &lt;-------&gt; Vcc GND &lt;-------&gt; GND SCL &lt;-------&gt; SCL SDA &lt;-------&gt; SDA </code></pre> <p>Using <code>i2cdetect -y 1</code> I obtain the following</p> <pre><code> 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: -- -- -- -- -- -- -- -- -- -- -- -- -- 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 60: -- -- -- -- -- -- -- -- 68 -- -- -- -- -- -- -- 70: -- -- -- -- -- -- -- -- </code></pre> <p>so the address of the device is 0x68. Reading the <a href="https://www.olimex.com/Products/Modules/Sensors/MOD-MPU6050/resources/RM-MPU-60xxA_rev_4.pdf" rel="nofollow noreferrer">datasheet</a> I found that for example the acceleration on the X axis is store in registers 3B (higher bits) and 3C (lower bits). My question is <strong>how do I access those registers?</strong></p> <p>My idea is that if I open <code>/dev/i2c-1</code> as a file descriptor, I can use the normal <code>read</code> and <code>write</code> functions. Then instead of getting data all the time, I can use <code>poll</code> in case of new available data.</p> <p>I tried to use the <code>read</code> function as suggested in the <a href="https://www.kernel.org/doc/Documentation/i2c/dev-interface" rel="nofollow noreferrer">documentation</a> but that's not working (I only get zeros) and when I use <code>poll</code> it seems like there's no one on the other side and the timeout (100ms) expires. I think I should say to the chip "give me the value of the 3B register" but I can't figure how to do it.</p> <p><strong>CODE</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;stdint.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/stat.h&gt; #include &lt;fcntl.h&gt; #include &lt;linux/i2c-dev.h&gt; #include &lt;sys/ioctl.h&gt; #include &lt;stdarg.h&gt; #include &lt;poll.h&gt; #include &lt;errno.h&gt; const char *filename = "/dev/i2c-1"; int DEBUG = 0; int ADDRESS = 0x68; struct pollfd pfd; void debug(const char* format, ...) { if (DEBUG) { va_list argptr; va_start(argptr, format); fprintf(stdout, "### "); vfprintf(stdout, format, argptr); va_end(argptr); } } void error_handler(const char *msg) { perror(msg); exit(EXIT_FAILURE); } void set_debug(const char *deb_lev) { unsigned long num; char *p; errno = 0; num = strtoul(deb_lev, &amp;p, 10); if (errno != 0 || *p != '\0') error_handler("set_debug | strtoul"); DEBUG = (num &gt; 0); } int open_file(const char *filename) { int fd; if ((fd = open(filename, O_RDWR)) == -1) error_handler("open_file | open"); debug("\"%s\" opened at %d\n", filename, fd); return fd; } int8_t read_value(int fd) { debug("Reading from %d\n", fd); int8_t num; char *p = (char *)&amp;num; ssize_t size = sizeof(int8_t); ssize_t r = 0; while (size &gt; 0) { if ((r = read(fd, p, size)) == -1) error_handler("read_value | read"); size -= r; p += r; } return num; } void command(uint16_t reg, int fd) { debug("Writing to %d\n", fd); unsigned char reg_buf[2]; ssize_t w = 0; ssize_t size = sizeof(unsigned char)*2; reg_buf[0] = (reg &gt;&gt; 0) &amp; 0xFF; reg_buf[1] = (reg &gt;&gt; 8) &amp; 0xFF; if ((w = write(fd, reg_buf, size)) == -1) error_handler("command | write"); } void read_data_from_imu(struct pollfd *pfd) { int8_t val; int p; for (;;) { command(0x3b, pfd-&gt;fd); switch (p = poll(pfd, 1, 100)) { case -1: error_handler("read_data_from_imu | poll"); case 0: fprintf(stderr, "Timeout expired\n"); break; default: val = read_value(pfd-&gt;fd); printf("Read: %u\n", val); break; } } } int main(int argc, const char **argv) { if (argc &lt; 2) { fprintf(stderr, "Usage: %s debug_flag\n", argv[0]); return EXIT_FAILURE; } set_debug(argv[1]); pfd.fd = open_file(filename); debug("Setting slave address\n"); if (ioctl(pfd.fd, I2C_SLAVE, ADDRESS) == -1) error_handler("main | ioctl"); read_data_from_imu(&amp;pfd); return EXIT_SUCCESS; } </code></pre> <p><strong>EDIT</strong></p> <p>Thanks to <a href="https://stackoverflow.com/a/39411931/5025931">Kennyhyun</a> adding a <code>write</code> solved the problem.</p> <p>So, if you want to read the <strong>accelerometer measurement on the x axis</strong> you have to do something like this</p> <pre><code>... #define ACCEL_XOUT_H 0x3b #define ACCEL_XOUT_L 0x3c ... write_register(ACCEL_XOUT_H, pfd-&gt;fd); x_data = read_value(pfd-&gt;fd); write_register(ACCEL_XOUT_L, pfd-&gt;fd); x_data = (x_data &lt;&lt; 8) + read_value(pfd-&gt;fd); ... </code></pre> <p><strong>EDIT 2</strong></p> <p>Furthermore, you can simplify the code reading directly for 2 bytes after the write. You'll get something like this (error handling omitted)</p> <pre><code>int8_t buff[2]; write_register(ACCEL_XOUT_H, pfd-&gt;fd); read(pfd-&gt;fd, buff, 2); //in this way you'll read both the ACCEL_XOUT_H register and the ACCEL_XOUT_L (the next one). </code></pre>
0
Techniques to improve the accuracy of SVM classifier
<p>I am trying to build a classifier to predict breast cancer using the UCI dataset. I am using support vector machines. Despite my most sincere efforts to improve upon the accuracy of the classifier, I cannot get beyond 97.062%. I've tried the following:</p> <pre><code>1. Finding the most optimal C and gamma using grid search. 2. Finding the most discriminative feature using F-score. </code></pre> <p>Can someone suggest me techniques to improve upon the accuracy? I am aiming at at least 99%. </p> <pre><code>1.Data are already normalized to the ranger of [0,10]. Will normalizing it to [0,1] help? 2. Some other method to find the best C and gamma? </code></pre>
0
module.__init__() takes at most 2 arguments error in Python
<p>I have 3 files, factory_imagenet.py, imdb.py and imagenet.py</p> <p><strong>factory_imagenet.py has:</strong></p> <pre><code>import datasets.imagenet </code></pre> <p>It also has a function call as </p> <pre><code>datasets.imagenet.imagenet(split,devkit_path)) ... </code></pre> <p><strong>imdb.py has:</strong></p> <pre><code>class imdb(object): def __init__(self, name): self._name = name ... </code></pre> <p><strong>imagenet.py has:</strong></p> <pre><code>import datasets import datasets.imagenet import datasets.imdb </code></pre> <p>It also has </p> <pre><code>class imagenet(datasets.imdb): def __init__(self, image_set, devkit_path=None): datasets.imdb.__init__(self, image_set) </code></pre> <p>All three files are in the datasets folder.</p> <p>When I am running another script that interacts with these files, I get this error:</p> <pre><code>Traceback (most recent call last): File "./tools/train_faster_rcnn_alt_opt.py", line 19, in &lt;module&gt; from datasets.factory_imagenet import get_imdb File "/mnt/data2/abhishek/py-faster-rcnn/tools/../lib/datasets/factory_imagenet.py", line 12, in &lt;module&gt; import datasets.imagenet File "/mnt/data2/abhishek/py-faster-rcnn/tools/../lib/datasets/imagenet.py", line 21, in &lt;module&gt; class imagenet(datasets.imdb): TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) </code></pre> <p>What is the problem here and what is the intuitive explanation to how to solve such inheritance problems? </p>
0
How to know if a binary number divides by 3?
<p>I want to know is there any divisible rule in binary system for dividing by 3.</p> <p>For example: in decimal, if the digits sum is divided by 3 then the number is devided by 3. For exmaple: <code>15 -&gt; 1+5 = 6 -&gt; 6</code> is divided by 3 so 15 is divided by 3.</p> <p>The important thing to understand is that im not looking for a CODE that will do so.. bool flag = (i%3==0); is'nt the answer I'm looking for. I look for somthing which is easy for human to do just as the decimal law.</p>
0
Angular Material VS Materializecss
<p>Well, it's about a week i'm trying to running up an application with Angular Material.<br> After so much challenging with Angular Material and its nerve wracking bugs (that might be never solved because of their milestone to releasing V2 for angular V2 as soon as possible), now it's blowing my mind, that why i have to use <code>616KB JS+CSS</code> Angular Material module instead of <code>254KB JS+CSS</code> Materializecss.<br> As i know (tell me if i'm wrong!):</p> <blockquote> <p>It's best to try and avoid changing DOM elements whenever possible</p> </blockquote> <p>But Angular materials base is directives that cause a lot of reflows/repaints, and actually based on demos i saw, Materializecss was much faster and lighter than Angular Material.<br> That's obvious Angular Material is more Angular-friendly and has some specific features like <code>$mdThemingProvider</code> and ..., but i have my doubts about using Angular Material or maybe its performance.<br> Any words to make me believe again in Angular Material?<br> Is it worth to use Angular Material instead of pure Angular + Materializecss ?<br> Because i can't see any major change in result of them?</p>
0
Swapping values in array C++
<p>This is the code:</p> <pre><code>for (i = 0; i &lt; size; i++) { swap(a[i], a[size - i - 1]); } </code></pre> <p>It looks correct.. and it is because I have used it in other languages, but on C++ it doesn't work. Any suggestions? Thanks</p>
0
s_client and gethostbyname failure
<p>I am working with an external company. Lets call them <code>evilcorp.com</code>. I want to use openssl to debug a two way SSL handshake.</p> <ul> <li><code>https://evilcorp.com</code> is setup to not require client authentication.</li> <li><code>https://evilcorp.com/webservices</code> is setup to require client authentication.</li> </ul> <p>How can I specify this path in openssl. So basically this works:</p> <pre><code>openssl s_client -connect evilcorp.com:443 </code></pre> <p>But this does not work and gives me <strong>gethostbyname failure</strong></p> <pre><code>openssl s_client -connect evilcorp.com/webservices:443 </code></pre> <p>How can I get this to work (if possible)</p>
0
xcode 8 push notification capabilities and entitlements file setting
<p>when using <code>xcode 8</code> doing the push notification setting, unlike <code>xcode 7</code>, <code>xcode 8</code> need developer turn on push notifications capabilities switch ( located at <code>TARGETS -&gt; AppName -&gt; Capabilities</code> as following pic ), <a href="https://i.stack.imgur.com/hpcLJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hpcLJ.png" alt="push notifications capabilities"></a></p> <p>then it will generate AppName.entitlements file as following</p> <pre><code>//AppName.entitlements &lt;key&gt;aps-environment&lt;/key&gt; &lt;string&gt;development&lt;/string&gt; </code></pre> <p>but for production version App, if we change the string to </p> <pre><code>//AppName.entitlements &lt;key&gt;aps-environment&lt;/key&gt; &lt;string&gt;production&lt;/string&gt; </code></pre> <p>then the Capabilities show a warning</p> <p><a href="https://i.stack.imgur.com/dFUYM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dFUYM.png" alt="Capabilities warning"></a> </p> <p>and it seems no matter which string value specified in aps-environment, we can still get the push device token at <code>application:didRegisterForRemoteNotificationsWithDeviceToken:</code></p> <p>so what is the correct setting of the push notification entitlements? thank you</p>
0
How to find file without specific file extension in laravel storage?
<p>How to find file by name without specific extension in laravel Storage?</p> <p>like this <code>"filename.*"</code></p> <pre><code>Storage::get("filename.*") </code></pre> <p>I tried this but seems not to work. It searches for specific file with specific extension.</p>
0
Using Socket.io with multiple clients connecting to same server
<p>Server-</p> <pre><code> var dgram = require('dgram'); var client= dgram.createSocket('udp4'); /** @requires socket.io */ var io = require('socket.io')(http); /** Array of clients created to keep track of who is listening to what*/ var clients = []; io.sockets.on('connection', function(socket, username){ /** printing out the client who joined */ console.log('New client connected (id=' + socket.id + ').'); /** pushing new client to client array*/ clients.push(socket); /** listening for acknowledgement message */ client.on('message', function( message, rinfo ){ /** creating temp array to put data in */ var temp = []; /**converting data bit to bytes */ var number= req.body.size * 2 /** acknowledgement message is converted to a string from buffer */ var message = message.toString(); /** cutting hex string to correspong to requested data size*/ var data = message.substring(0, number); /** converting that data to decimal */ var data = parseInt(data, 16); /** adding data to data array */ temp[0] = data /** emitting message to html page */ socket.emit('temp', temp); }); /** listening if client has disconnected */ socket.on('disconnect', function() { clients.splice(clients.indexOf(client), 1); console.log('client disconnected (id=' + socket.id + ').'); clearInterval(loop); }); }); } }); </code></pre> <p>Client-</p> <pre><code>var socket = io.connect('192.168.0.136:3000'); socket.on(temp', function(temp){ var temp= temp.toString(); var message= temp.split(',').join("&lt;br&gt;"); $('#output').html('&lt;output&gt;' + message + '&lt;/output&gt;'); }); </code></pre> <p>When a client connects, a random number called temp is emitted to the client. The above code works when one client connects to the server. Now how can you set a new connection each time? So that if one tab is opened, it gets its own random message back, while when another tab opens, it gets its own random message back. </p>
0
How to compare Enums in Python?
<p>Since Python 3.4, the <code>Enum</code> class exists.</p> <p>I am writing a program, where some constants have a specific order and I wonder which way is the most pythonic to compare them:</p> <pre><code>class Information(Enum): ValueOnly = 0 FirstDerivative = 1 SecondDerivative = 2 </code></pre> <p>Now there is a method, which needs to compare a given <code>information</code> of <code>Information</code> with the different enums:</p> <pre><code>information = Information.FirstDerivative print(value) if information &gt;= Information.FirstDerivative: print(jacobian) if information &gt;= Information.SecondDerivative: print(hessian) </code></pre> <p>The direct comparison does not work with Enums, so there are three approaches and I wonder which one is preferred:</p> <p>Approach 1: Use values:</p> <pre><code>if information.value &gt;= Information.FirstDerivative.value: ... </code></pre> <p>Approach 2: Use IntEnum:</p> <pre><code>class Information(IntEnum): ... </code></pre> <p>Approach 3: Not using Enums at all:</p> <pre><code>class Information: ValueOnly = 0 FirstDerivative = 1 SecondDerivative = 2 </code></pre> <p>Each approach works, Approach 1 is a bit more verbose, while Approach 2 uses the not recommended IntEnum-class, while and Approach 3 seems to be the way one did this before Enum was added. </p> <p>I tend to use Approach 1, but I am not sure. </p> <p>Thanks for any advise!</p>
0
Adding the single string quote for value inside variable using Javascript
<p>I have a variable, before I use that variable,I need to add string quotes to the value/data which is inside the variable using JavaScript need help</p> <pre><code> //i am getting like this // var variable=king; //i want to convert it with single quote// variable=variable; </code></pre> <p>but i need the data inside variable should be in a single quotation. </p>
0
Stopping a JMeter non-gui test that started from Java code
<p>I started a <code>JMeter</code> <code>JMX</code> test from <code>Java</code> code:</p> <pre><code>StandardJMeterEngine jmeter = new StandardJMeterEngine(); .. jmeter.configure(testPlanTree); jmeter.run(); </code></pre> <p>I would like to be able to stop the test (from outside the test, for example command line), similar to the option if it had run from non-gui mode using (from cmd):</p> <pre><code>jmeter -n -t MyTest.jmx </code></pre> <p>Stopping with:</p> <pre><code>shutdown.cmd (/sh) stoptest.cmd (/sh) </code></pre> <p>When starting from non-gui cmd, I can see that it waits for signals:</p> <pre><code>Waiting for possible shutdown message on port 4445 </code></pre> <p>If started from my non-gui <code>Java</code> code, it does not listen on this port. How can I add this functionality to this mode? </p> <p>Any suggestion will be very appreciated? Thanks!</p>
0
git subtree error "fatal: refusing to merge unrelated histories"
<p>I'm trying to figure out how 'git subtree' works. I've followed all directions on <a href="https://help.github.com/articles/about-git-subtree-merges/" rel="noreferrer" title="About subtree merges">this page</a>, but I always get an error trying to merge the subtree project in my own repo ('Step 2'): <code>fatal: refusing to merge unrelated histories</code>. </p> <p>I've read <a href="https://stackoverflow.com/questions/37937984/git-refusing-to-merge-unrelated-histories">this post</a>, and when I use the <code>--allow-unrelated-histories</code> option, it seems to work fine. However, I'm not sure whether I should use this...My impression is that the whole point of subtrees is to have unrelated histories within one repository, so it feels strange to have to add the option. Should I add it nevertheless, or am I doing something wrong?</p> <p>I'm using git v2.9.3 on osx 10.11.6</p>
0
Google API Client "refresh token must be passed in or set as part of setAccessToken"
<p>I am currently facing a very strange problem, indeed I've been following this very same guide (<a href="https://developers.google.com/google-apps/calendar/quickstart/php" rel="noreferrer">https://developers.google.com/google-apps/calendar/quickstart/php</a>) from Google API documentation. I tried it twice, at the first time it work like a charm but after the access token had expire the script provided straight by Google API Doc was unable to refresh it.</p> <p>TL;DR</p> <p>Here is the error message:</p> <pre><code>sam@ssh:~$ php www/path/to/app/public/quickstart.php Fatal error: Uncaught exception 'LogicException' with message 'refresh token must be passed in or set as part of setAccessToken' in /home/pueblo/www/path/to/app/vendor/google/apiclient/src/Google/Client.php:258 Stack trace: #0 /home/pueblo/www/path/to/app/public/quickstart.php(55): Google_Client-&gt;fetchAccessTokenWithRefreshToken(NULL) #1 /home/pueblo/www/path/to/app/public/quickstart.php(76): getClient() #2 {main} thrown in /home/pueblo/www/path/to/app/vendor/google/apiclient/src/Google/Client.php on line 258 </code></pre> <p>Here is the part of the php script from google I've modified:</p> <pre><code>require_once __DIR__ . '/../vendor/autoload.php'; // I don't want the creds to be in my home folder, I prefer them in the app's root define('APPLICATION_NAME', 'LRS API Calendar'); define('CREDENTIALS_PATH', __DIR__ . '/../.credentials/calendar-php-quickstart.json'); define('CLIENT_SECRET_PATH', __DIR__ . '/../client_secret.json'); </code></pre> <p>I also modified the <code>expandHomeDirectory</code> so I could "disable" it without modifying too much code:</p> <pre><code>function expandHomeDirectory($path) { $homeDirectory = getenv('HOME'); if (empty($homeDirectory)) { $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH'); } return $path; // return str_replace('~', realpath($homeDirectory), $path); } </code></pre> <p>So to check if I was wrong or if Google was, I did an experiment: yesterday night I launch the quickstart script from ssh to check if it was working, and indeed it was, so I decided to check this morning if it still working just as it was before I slept and it wasn't so I think there's something wrong with Google's <code>quickstart.php</code>.</p> <p>I hope someone could help me, I already checked all the other posts about the subject but they are all outdated.</p>
0
How to use Action Filters with Dependency Injection in ASP.NET CORE?
<p>I use constructor-based dependency injection everywhere in my <code>ASP.NET CORE</code> application and I also need to resolve dependencies in my action filters:</p> <pre><code>public class MyAttribute : ActionFilterAttribute { public int Limit { get; set; } // some custom parameters passed from Action private ICustomService CustomService { get; } // this must be resolved public MyAttribute() { } public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { // my code ... await next(); } } </code></pre> <p>Then in Controller:</p> <pre><code>[MyAttribute(Limit = 10)] public IActionResult() { ... </code></pre> <p>If I put ICustomService to the constructor, then I'm unable to compile my project. So, how do I supossed to get interface instances in action filter?</p>
0
python serial write timeout
<p>I have used pyserial for a couple of days. However, a problem occurs today. I met serial write timeout. Several days before, when I used a switch, everything is OK. But today I changed for another switch. Then serial write timeout appears. I did not change any code, but the problem is actually quite severe. More seriously, the timeout not always occurs, which means that sometimes I can write in the serial successfully.</p> <pre><code>ser = serial.Serial( #Serial COM configuration port='COM5', baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, rtscts=True, timeout=2, writeTimeout=5 ) strInput = "show ver" ser.flushInput() ser.flushOutput() ser.write(strInput.encode('utf-8')+b'\n') </code></pre> <p>I have ensured that the port is COM5 and the baudrate of the switch is 9600. Thanks a lot for answering my question.</p>
0
Why is a public const method not called when the non-const one is private?
<p>Consider this code:</p> <pre><code>struct A { void foo() const { std::cout &lt;&lt; "const" &lt;&lt; std::endl; } private: void foo() { std::cout &lt;&lt; "non - const" &lt;&lt; std::endl; } }; int main() { A a; a.foo(); } </code></pre> <p>The compiler error is:</p> <blockquote> <p>error: 'void A::foo()' is private`.</p> </blockquote> <p>But when I delete the private one it just works. Why is the public const method not called when the non-const one is private?</p> <p>In other words, why does overload resolution come before access control? This is strange. Do you think it is consistent? My code works and then I add a method, and my working code does not compile at all.</p>
0
Is using async in setTimeout valid?
<p>I had a asynchronous function in Javascript and I added setTimeout to it. The code looks like that:</p> <pre><code> let timer; clearTimeout(timer); timer =setTimeout(() =&gt; { (async() =&gt; { await this._doSomething(); })(); }, 2000); </code></pre> <p>The purpose of setTimeout is to add 2 seconds before function will be run. It is to be sure that user stopped typing. </p> <p>Should I remove async/await from this function now, since setTimeout is asynchronous anyway?</p>
0
How to install xgboost in python on MacOS?
<p>I am a newbie and learning python. Can someone help me- how to install xgboost in python. Im using Mac 10.11. I read online and did the below mentioned step, but not able to decode what to do next: </p> <pre><code>pip install xgboost - </code></pre>
0
Select next 20 rows after top 10
<p>I'm trying to select next 20 rows after top 10 rows.</p> <pre><code>select TOP 20 * from memberform where Row_Number over(10) </code></pre>
0
OWIN OpenIdConnect Middleware IDX10311 nonce cannot be validated
<p>I have an application using the OWIN middleware for OpenIdConnect. The startup.cs file uses the standard implementation of app.UseOpenIdConnectAuthentication. The cookie is set to the browser, but it errors with:</p> <blockquote> <p>IDX10311: RequireNonce is 'true' (default) but validationContext.Nonce is null. A nonce cannot be validated. If you don't need to check the nonce, set OpenIdConnectProtocolValidator.RequireNonce to 'false'.</p> </blockquote> <p>I've found that when running fiddler as I do for most debug projects this behavior happens. The error is returned, but if I go back to the site everything is working and my user is authenticated. Has anyone seen this behavior when running fiddler?</p> <p>With fiddler:</p> <ul> <li>SecurityTokenValidated notification in OpenIdConnect is executed twice.</li> <li>After the second pass through the IDX10311 error is thrown</li> <li>Browser contains the valid cookie, going back to the page I can view the valid User.Identity data.</li> </ul> <p>Running without fiddler:</p> <ul> <li>SecurityTokenValidated executes once in OpenIdConnect</li> <li>No error thrown, proceeds to load up controller action for post authentication redirect Uri</li> <li>Cookie also valid and User.Identity data correct.</li> </ul> <p>Ideas? I can get around it without running fiddler, but when debugging it would be nice to also run fiddler to inspect traffic.</p>
0
deserialize json object does not work
<p>I want to deserialize my json object to my student class</p> <pre><code>var result = JsonConvert.DeserializeObject&lt;Student&gt;(data); </code></pre> <p>My json data</p> <pre><code>{ "student":{ "fname":"997544", "lname":"997544", "subject":"IT", "grade":"F" } } </code></pre> <p>My student class</p> <pre><code>[Serializable] public class Student { [JsonProperty("fname")] public string FirstName{ get; set; } [JsonProperty("lname")] public string LastName{ get; set; } [JsonProperty("subject")] public string Subject { get; set; } [JsonProperty("grade")] public string Grade { get; set; } } </code></pre> <p>The code does not work, the error says:</p> <blockquote> <p>Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.</p> </blockquote>
0
how to reload a page using ajax success function
<p>admin.php </p> <pre><code>$.ajax({ ... success: function() { location.href = "admin.php"; } }); </code></pre> <p>As a result I should get some new content added to the page (<code>admin.php</code>), but sometimes the page is not reloaded and I can see the new content only after pressing F5 key.</p> <p>Any help?</p>
0
How to convert number to time format in javascript
<p>I am trying to convert the number <b>20</b> into minutes with moment js. I need </p> <pre><code>21 to to look like 21:00 </code></pre> <p>This way for my set interval the timer will show 19:58 to 0:01.</p> <p>I had tried</p> <pre><code> var x = 1260000; var d = moment.duration(x, 'milliseconds'); var hours = Math.floor(d.asHours()); var mins = Math.floor(d.asMinutes()) - hours * 60; </code></pre> <p>This still leaves me with 21. I am not sure how to get the minutes form.</p> <p>This seems like it shoud be a short fix. Any help is greatly appreciated. </p>
0
Entity Framework - The migrations configuration type was not be found in the assembly
<p>I have multiple <code>DbContext</code>s in a C# project and I'm trying to enable migrations. When I specify the full command, i.e.:</p> <pre><code>Enable-Migrations -ContextTypeName Models.Account.AccountDetailDbContext </code></pre> <p>A migrations folder is created, with the configuration class, but I then get a message:</p> <blockquote> <p>Checking if the context targets an existing database...</p> </blockquote> <p>And then</p> <blockquote> <p>The migrations configuration type 'Portal.WebUI.Migrations.Configuration' was not be found in the assembly 'Portal.WebUI'.</p> </blockquote> <p>Even though it has just created the file, it can't find it.</p> <p>I have the correct project selected in the Package Manager Console</p> <p>I have tried the command using <code>-verbose</code>, but it gives no additional information</p> <p>If I copy the dbcontexts and classes into a new project then it all works, so it must be something in this existing project that is making the migration fail, but I can't tell what it is.</p>
0
How to cache package manager downloads for docker builds?
<p>If I run <code>composer install</code> from my host, I hit my local composer cache:</p> <pre><code> - Installing deft/iso3166-utility (1.0.0) Loading from cache </code></pre> <p>Yet when building a container having in its Dockerfile:</p> <pre><code>RUN composer install -n -o --no-dev </code></pre> <p>I download all the things, e.g.:</p> <pre><code> - Installing deft/iso3166-utility (1.0.0) Downloading: 100% </code></pre> <p>It's expected, yet I like to avoid it. As even on a rebuilt, it would also download everything again.</p> <p>I would like to have a universal cache for composer that I could also reshare for other docker projects.</p> <p>I looked into this and found the approach to <a href="https://git.framasoft.org/Chill-project/docker-ci-image/commit/002aeaf8ae5845c71eb8191821a98aa7a8565f0e" rel="noreferrer">define a volume in the Dockerfile</a>:</p> <pre><code>ENV COMPOSER_HOME=/var/composer VOLUME /var/composer </code></pre> <p>I added that to my <code>Dockerfile</code>, and expected to only download the files once, and hit the cache afterwards.</p> <p>Yet when I modify my <code>composer</code>, e.g. remove the <code>-o</code> flag, and rerun <code>docker build .</code>, I expected to hit the cache on build, yet I still download the vendors again.</p> <p>How are volumes supposed to work to have a data cache inside a docker container?</p>
0
Difference between sort(), sort(function(a,b){return a-b;}); and sort(function(a,b){...})
<p>I am trying to understand how exactly sort() works and how I am supposed to use it.</p> <p>I did some research (google) and went through the similar questions here on stackoverflow, but there are still a few things not 100% clear to me.</p> <p>So my understanding so far is the following:</p> <p>There are:</p> <p><strong>sort() without parameters</strong>: sorts only simple arrays of <strong>String</strong> values <strong>alphabetically</strong> and in <strong>ascending</strong> order</p> <p>E.g. </p> <pre><code>// sort alphabetically and ascending: var myArr=["Bob", "Bully", "Amy"] myArr.sort() // Array now becomes ["Amy", "Bob", "Bully"] </code></pre> <p><br> <strong>sort() with a function as a parameter</strong>: sorts objects in arrays according to their properties; the items are, however, compared as <strong>numbers</strong></p> <pre><code>myArr.sort(function(a,b) { return a - b; }); </code></pre> <p><br> <strong>sort() with a function as a parameter</strong>: sorts objects in arrays according to their properties; the items can be <strong>numbers</strong> or <strong>Strings</strong></p> <pre><code>myArr.sort(function(a, b) { if (a.sortnumber &lt; b.sortnumber) return -1; else if (a.sortnumber &gt; b.sortnumber) return 1; return 0; }); </code></pre> <p><br> I tried sorting the following array with all these 3 sort() functions.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var myArr = [{ "sortnumber": 9, "name": "Bob" }, { "sortnumber": 5, "name": "Alice" }, { "sortnumber": 4, "name": "John" }, { "sortnumber": 3, "name": "James" }, { "sortnumber": 7, "name": "Peter" }, { "sortnumber": 6, "name": "Doug" }, { "sortnumber": 2, "name": "Stacey" }]; //myArr.sort(); // doesn't do anything since it doesn't know on what property to sort /* myArr.sort(function(a, b) { return (a.sortnumber - b.sortnumber); // sorts array return (a.name - b.name); // doesn't sort array }); */ /* // sorts array even when I use name as property to sort on myArr.sort(function(a, b) { if (a.sortnumber &lt; b.sortnumber) return -1; else if (a.sortnumber &gt; b.sortnumber) return 1; return 0; }); */ console.log(myArr);</code></pre> </div> </div> </p> <p><a href="https://jsfiddle.net/8b3w1Lhf/1/" rel="noreferrer">Here</a> is also a fiddle.</p> <p>So, my questions are:</p> <ol> <li>Is my understanding correct?</li> <li>Is there anything that I am missing?</li> <li>If the third case works at all times, can I always stick to it or are the other two cases more efficient in some way or have any advantages to the third case?</li> </ol> <p>I would really appreciate it if anyone could elaborate on the above. Thank you.</p>
0
Error while waiting for device: The emulator process for AVD .... was killed
<p>I am a freshman for the development of the Andriod, I suffered from a odd question when I runned the app ,just as the follow picture.</p> <p><a href="https://i.stack.imgur.com/MgQAd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MgQAd.png" alt="enter image description here"></a></p> <p>I also google it, but I have not finded a useful answer, who can tell me what I can do ~~~~(>_&lt;)~~~~ thanks</p>
0
There was an error running the selected code generator: 'Object reference not set to an instance of an object.' Error?
<p><a href="https://i.stack.imgur.com/SNj5M.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SNj5M.png" alt="enter image description here"></a></p> <p>I have tried all the solution like repairing the VS 2013 but no use. when you create a controller by right clicking on the Controller folder and you add the controller, then you right click in the Action of the newly created controller and select Add View, it happens right then, when I try to create a view. Its not a new project, its an existing project.</p>
0
Serializing anonymous types
<p>I'd like to convert anonymous type variable to byte[], how can I do that?</p> <p>What I tried:</p> <pre><code>byte[] result; var my = new { Test = "a1", Value = 0 }; BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { bf.Serialize(ms, my); //-- ERROR result = ms.ToArray(); } </code></pre> <p>I've got error:</p> <blockquote> <p>An exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll but was not handled in user code</p> <p>Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' in Assembly 'MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.Additional information: Type '&lt;>f__AnonymousType10`2[[System.String, mscorlib,</p> </blockquote> <p>Can somebody help me? What I'm doing wrong? Or this is not possible to do?</p>
0
Brace (aggregate) initialization for structs with default values
<p>Initializing a struct with default values is trivial:</p> <pre><code>struct X { int a; int b = 2; }; </code></pre> <p>and initializing a struct with a brace initializer is trivial too:</p> <pre><code>X x = {1, 3}; </code></pre> <p>Suprisingly the init code won't compile, until I remove the default value. So, how would I do the init in such a case? I'd like to keep X a POD without c-tor.</p>
0
Angular2 attribute directive Hostbinding to host attribute
<p>I have a &quot;bootstrapModal&quot; attribute directive that adds bootstrap attributes to the host element:</p> <pre><code>data-placement=&quot;top&quot; data-toggle=&quot;modal&quot; data-target=&quot;#DefaultModalWindow&quot; </code></pre> <p>Is it possible to <code>HostBinding</code> to an attribute like this?</p> <pre><code>&lt;htmltag ... bootstrapModal placement=&quot;left&quot;&gt; </code></pre> <p>And in the directive have something like that:</p> <pre><code> @HostBinding('attributes.data-placement') // &lt;== this don't work @Input() placement:string='top'; </code></pre> <p>So the result should be:</p> <pre><code>&lt;htmltag ... data-placement=&quot;left&quot; data-toggle=&quot;modal&quot; data-target=&quot;#DefaultModalWindow&quot;&gt; </code></pre>
0
How do I create a console app in python?
<p>I am attending a coding bootcamp and python is the primary language. For the final project, we were told to study and learn how to create console apps. I have searched online for tutorials and books but none seems to have beginner content. Where can I get the best tutorial on creating Python console apps? I have only done python for a month.</p>
0
How can I stop Excel processes from running in the background after a PowerShell script?
<p>No matter what I try, Excel 2013 continues to run in the background on Windows 10 no matter what commands I throw at the end of my PowerShell script. I've tried adding all suggestions I've found to the end of my script and the only Excel object I open continues to remain open. Here is what I have at the end of my script. Any other suggestions?</p> <pre><code>## Quit Excel and Terminate Excel Application process: $xlsxwb.quit $xlsxobj.Quit [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsxobj) [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsxwb) [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsxSh1) Start-Sleep 1 'Excel processes: {0}' -f @(Get-Process excel -ea 0).Count </code></pre>
0
Duplicated rows when merging dataframes in Python
<p>I am currently merging two dataframes with an outer join. However, after merging, I see all the rows are duplicated even when the columns that I merged upon contain the same values.</p> <p>Specifically, I have the following code.</p> <pre class="lang-py prettyprint-override"><code>merged_df = pd.merge(df1, df2, on=['email_address'], how='inner') </code></pre> <p>Here are the two dataframes and the results.</p> <p><code>df1</code></p> <pre class="lang-none prettyprint-override"><code> email_address name surname 0 [email protected] john smith 1 [email protected] john smith 2 [email protected] elvis presley </code></pre> <p><code>df2</code></p> <pre class="lang-none prettyprint-override"><code> email_address street city 0 [email protected] street1 NY 1 [email protected] street1 NY 2 [email protected] street2 LA </code></pre> <p><code>merged_df</code></p> <pre class="lang-none prettyprint-override"><code> email_address name surname street city 0 [email protected] john smith street1 NY 1 [email protected] john smith street1 NY 2 [email protected] john smith street1 NY 3 [email protected] john smith street1 NY 4 [email protected] elvis presley street2 LA 5 [email protected] elvis presley street2 LA </code></pre> <p>My question is, shouldn't it be like this?</p> <p>This is how I would like my <code>merged_df</code> to be like.</p> <pre class="lang-none prettyprint-override"><code> email_address name surname street city 0 [email protected] john smith street1 NY 1 [email protected] john smith street1 NY 2 [email protected] elvis presley street2 LA </code></pre> <p>Are there any ways I can achieve this?</p>
0
Upload multiple files one by one using DropZone.js
<p>Is there any possibility that the multiple files will be uploaded one by one using dropzone.js. The following is a custom dropzone config script. </p> <pre><code>Dropzone.options.myDropzone = { autoProcessQueue: false, parallelUploads: 10, addRemoveLinks:true, init: function () { var submitButton = document.querySelector("#submit-all"); myDropzone = this; // closure submitButton.addEventListener("click", function () { if(myDropzone.getQueuedFiles().length === 0) { alert("Please drop or select file to upload !!!"); } else{ myDropzone.processQueue(); // Tell Dropzone to process all queued files. } }); }, url: "upload.php" }; </code></pre> <p>Right now, it uploads all files at a time which are all in the process queue. Since, the upload file size will be bigger, all files have to upload one by one. please help to short out the same.</p>
0
Firebase querying data
<pre><code>{ "random_key 1" : { "id": 0, "text": "This is text" }, "random_key 2" : { "id": 1, "text": "This is text" } } </code></pre> <p>If I'm storing my data like this, and I want to get the node where <code>id</code> is equal to <code>0</code>. How can I do that?</p> <p>The above is the child of <code>issue</code>, which is a child of <code>root</code>.</p>
0
How do you destroy an Angular 2 component without a ComponentFactory?
<p>When creating components dynamically through a ComponentFactory the ComponentRef that's returned provides a <a href="https://angular.io/api/core/ComponentRef#destroy" rel="noreferrer">destroy</a> method which works perfectly for what I'd like to accomplish. With that in mind, it looks like all I need to do is a get a ComponentRef for a statically created component and then use its destroy function (which <a href="https://stackoverflow.com/questions/38676997/angular-2-destroy-child-component">this answer</a> states), but when I try this I get an error saying that "destroy is not a function" even though I do get an object back.</p> <p>Here's the syntax I'm using for ViewChild:</p> <pre><code>@ViewChild(MyComponent) myComponentRef: ComponentRef&lt;MyComponent&gt;; </code></pre> <p>And my "destroy" call:</p> <pre><code>private destroy() { this.myComponentRef.destroy(); } </code></pre> <p>Which is triggered here:</p> <pre><code>&lt;button (click)="destroy()"&gt;Destroy&lt;/button&gt; </code></pre> <p>Calling this "destroy" method works for components that I create dynamically, but not statically.</p> <p>Edit: <strike>So it seems like this does partially remove the component, but not from the DOM, which is not the same behavior that occurs when calling "destroy" on a dynamically created component. Additionally, my click event function still fires when I click on a component that I've tried to destroy.</strike></p> <p>Edit 2: I updated my ViewChild syntax to explicitly read for a ComponentRef and I get "undefined" back:</p> <pre><code>@ViewChild(MyComponent, {read: ComponentRef}) myComponentRef: ComponentRef&lt;MyComponent&gt;; </code></pre> <p>If that returns "undefined" then I'm guessing this may not be possible.</p>
0
Can single Kafka producer produce messages to multiple topics and how?
<p>I am just exploring <code>Kafka</code>, currently i am using One <code>producer</code> and One topic to produce messages and it is consumed by one <code>Consumer</code>. very simple.</p> <p>I was reading the Kafka page, the <code>new Producer API is thread-safe</code> and sharing single instance will improve the performance.</p> <p>Does it mean i can use single Producer to publish messages to multiple topics?</p>
0
FUNCTION "SUM does not exist"
<p>I am using mysql 5.5.11, when i execute the script below</p> <pre><code>INSERT INTO payments(created, Amount, user, Remarks, orderid, paymethod) VALUES('2016-09-03', 0.0, 'admin', '', 4, 'Cash'); </code></pre> <p>I get error</p> <blockquote> <p>SQL Error: FUNCTION mydb.SUM does not exist. Check the 'Function Name Parsing and Resolution' section in the Reference Manual</p> </blockquote> <p>This is the table schema</p> <pre><code>CREATE TABLE payments ( ID int AUTO_INCREMENT NOT NULL, OrderID int, Amount decimal(11,2), Created varchar(20), Remarks varchar(160), user varchar(60), PayMethod varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci, /* Keys */ PRIMARY KEY (ID) ) ENGINE = InnoDB; </code></pre> <p>What could be the cause of the error</p> <p>This is the trigger attached to the table</p> <pre><code>BEGIN /* Trigger text */ UPDATE Orders Set Paid =(Select SUM (Amount) From Payments AS p Where p.OrderID = Orders.ID),PayMethod =new.PayMethod WHere Orders.id = new.OrderID; UPDATE Orders Set Bal = Total - Paid WHere Orders.id = new.OrderID; END </code></pre>
0
Python - TypeError: float() argument must be a string or a number, not 'list
<p>Python newbie here. I am trying to operate on lists which contain floating point numbers. <code>avg</code> is a list parameter that is returned from a different method. However, when I tried doing the following, it throws me an error that float() should have a string or a number and not a list. <code>avg1</code> should contain a copy of the lists with float-type numbers instead of lists right? I tried a few edits I read on other posts with similar titles, but couldn't solve this. Just starting out so kindly tell me where I am going wrong. </p> <pre><code>def movingavg(EMA,avg): EMA=[] avg1 = [float(i) for i in avg] EMA[:3] = avg1[:3] for i,j in zip(EMA[2:],avg1[3:]): a =float(i)*0.67 + float(j)*0.33 EMA.append(a) return EMA </code></pre> <p>The error that I get is as follows :</p> <pre><code>avg1 = [float(i) for i in avg] TypeError: float() argument must be a string or a number, not 'list' </code></pre> <p>Using Python 3.4</p>
0
Change Java spark port number
<p>My java spark web application using the embedded jetty web server uses port number 4567. Unfortunately this port number is blocked on my computer and don't wish to unblock it. If looked at the spark documentation but it doesn't contain how to change the port number of the embedded Jetty server to 8080.</p>
0
Editing Woocommerce get_price_html() format
<p>This is a price.php file to show the price of products at category level in Woocommerce. It produces the following output:</p> <blockquote> <p>₹1,504 Save 66% per Bundle</p> </blockquote> <pre><code>&lt;?php if ( $price_html = $product-&gt;get_price_html() ) : ?&gt; &lt;span class="price"&gt;&lt;?php echo $price_html; ?&gt;&lt;/span&gt; &lt;?php endif; ?&gt; </code></pre> <p>I want to edit the format but I am not able to do that I want to use ₹1,504 to manipulate it. How to get this?</p>
0
dcast error: `Error in match(x, table, nomatch = 0L)`
<p>I have a dataframe called <code>df</code> that looks something like this...</p> <pre><code>"ID","ReleaseYear","CriticPlayerPrefer","n","CountCriticScores","CountUserScores" "1",1994,"Both",1,5,283 "2",1994,"Critics",0,0,0 "3",1994,"Players",0,0,0 "4",1995,"Both",3,17,506 "5",1995,"Critics",0,0,0 "6",1995,"Players",0,0,0 "7",1996,"Both",18,163,3536 "8",1996,"Critics",2,18,97 "9",1996,"Players",3,20,79 </code></pre> <p>I want to flip the data frame around so the columns are like this:</p> <p><code>"ReleaseYear","Both","Critics","Players"</code></p> <p>The values for columns <code>Both',</code>Critics<code>and</code>Players<code>would be the</code>n` for each.</p> <p>When I try running this...</p> <pre><code>require(dcast) chartData.CriticPlayerPreferByYear &lt;- dcast( data = df, formula = ReleaseYear ~ CriticPlayerPrefer, fill = 0, value.var = n ) </code></pre> <p>... I get this error:</p> <pre><code>Error in match(x, table, nomatch = 0L) : 'match' requires vector arguments </code></pre> <p>What is the problem here? How do I fix it?</p>
0
background clip text is not working in IE
<p>I have requirement to display the text in a gradient format. Below is the example</p> <p>Html</p> <pre><code>&lt;div class="banner"&gt;Free account&lt;/div&gt; </code></pre> <p>css</p> <pre><code>.banner{ font-family: Univers LT Std Bold; font-size: 18pt; font-weight: bold; /* background: lightblue; */ background: -webkit-linear-gradient(right,#00853f 20%, #8cc63f 80%); background: -ms-linear-gradient(right,#00853f 20%, #8cc63f 80%); color: transparent; -webkit-background-clip: text; -webkit-text-fill-color: transparent; } </code></pre> <p>The problem is in IE the "background-clip: text;" is not working. Please suggest how to resolve this or please suggest is there any alternative way.</p>
0
Version of Android Studio is incompatible with the Gradle Plugin used
<p>When trying to run application on my device (or emulated device) I constantly getting same error:</p> <pre><code>Error running app: This version of Android Studio is incompatible with the Gradle Plugin used. Try disabling Instant Run (or updating either the IDE or the Gradle plugin to the latest version) </code></pre> <p>After successful gradle build.</p> <p>I was trying some Gradle settings - <em>Use default Gradle wrapper</em>, or <em>Use Gradle wrapper task configuration</em> - no changes.</p> <p>gradle-wrapper.properties</p> <pre><code>distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-bin.zip </code></pre> <p>build.gradle</p> <pre><code>classpath 'com.android.tools.build:gradle:2.2.0-alpha6' </code></pre> <p>It's open source project from github. No one else complaining about this.</p> <p>I was working on Ubuntu 15.10, so gradle --version command could be useful informaction,</p> <pre><code>------------------------------------------------------------ Gradle 1.5 ------------------------------------------------------------ Gradle build time: niedziela, 16 listopad 2014 16:24:40 UTC Groovy: 1.8.6 Ant: Apache Ant(TM) version 1.9.4 compiled on January 27 2015 Ivy: non official version JVM: 1.7.0_95 (Oracle Corporation 24.95-b01) </code></pre> <p><strong>EDIT:</strong> Ohh, I tried to disable <em>Instant Run</em> in configuration as well.<br> <strong>EDIT2:</strong> I don't have problems with another project which I was working on simultaneonusly, but every settings are the same, so I really don't know what to do. </p>
0
Show N rows per page in HTML table
<p>Hello I have an html table with a lot of rows and I use a JavaScript code to add a pagination option, works fine but when I load the document shows all the rows and I want to show only 5, 10, or whatever but not all the rows. Here is my JavaScript code and the working Fiddle:</p> <pre><code> $(document).ready(function () { getPagination('#Tabla'); }); function getPagination(table) { $('#maxRows').on('change', function() { $('.pagination').html(''); // reset pagination var trnum = 0; // reset tr counter var maxRows = parseInt($(this).val()); // get Max Rows from select option var totalRows = $(table + ' tbody tr').length; // numbers of rows $(table + ' tr:gt(0)').each(function() { // each TR in table and not the header trnum++; // Start Counter if (trnum &gt; maxRows) { // if tr number gt maxRows $(this).hide(); // fade it out } if (trnum &lt;= maxRows) { $(this).show(); } // else fade in Important in case if it .. }); // was fade out to fade it in if (totalRows &gt; maxRows) { // if tr total rows gt max rows option var pagenum = Math.ceil(totalRows / maxRows); // ceil total(rows/maxrows) to get .. // numbers of pages for (var i = 1; i &lt;= pagenum;) { // for each page append pagination li $('.pagination').append('&lt;li class"wp" data-page="' + i + '"&gt;\ &lt;span&gt;' + i++ + '&lt;span class="sr-only"&gt;(current)&lt;/span&gt;&lt;/span&gt;\ &lt;/li&gt;').show(); } // end for i } // end if row count &gt; max rows $('.pagination li:first-child').addClass('active'); // add active class to the first li $('.pagination li').on('click', function() { // on click each page var pageNum = $(this).attr('data-page'); // get it's number var trIndex = 0; // reset tr counter $('.pagination li').removeClass('active'); // remove active class from all li $(this).addClass('active'); // add active class to the clicked $(table + ' tr:gt(0)').each(function() { // each tr in table not the header trIndex++; // tr index counter // if tr index gt maxRows*pageNum or lt maxRows*pageNum-maxRows fade if out if (trIndex &gt; (maxRows * pageNum) || trIndex &lt;= ((maxRows * pageNum) - maxRows)) { $(this).hide(); } else { $(this).show(); } //else fade in }); // end of for each tr in table }); // end of on click pagination list }); } </code></pre> <p>Fiddle:</p> <p><a href="https://jsfiddle.net/u2e1qvyb/3/" rel="nofollow">Working Code</a></p>
0
TypeError: __init__() got an unexpected keyword argument 'size
<p>How do i fix this unexpected keyword argument 'size'? </p> <hr> <pre><code> Traceback (most recent call last): File "H:\Documents\Astro game\astro games6.py", line 73, in &lt;module&gt; main() File "H:\Documents\Astro game\astro games6.py", line 61, in main new_asteroid = Asteroid(x = x, y = y,size = size) TypeError: __init__() got an unexpected keyword argument 'size' </code></pre> <hr> <p>The full code: </p> <pre><code>import random from superwires import games games.init(screen_width = 640, screen_height = 480, fps = 50) class Asteroid(games.Sprite): """ An asteroid wich floats across the screen""" SMALL = 1 MEDIUM = 2 LARGE = 3 images = {SMALL : games.load_image("asteroid_small.bmp"), MEDIUM : games.load_image("asteroid_med.bmp"), LARGE : games.load_image("asteroid_big.bmp")} speed = 2 def _init_(self, x, y, size): """Initialize asteroid sprite""" super(Asteroid, self)._init_( image = Asteroid.images[size], x = x, y = y, dx = random.choice([1, -1]) *Asteroid.SPEED* random.random()/size, dy = random.choice([1, -1]) *Asteroid.SPEED* random.random()/size) self.size = size def update (self): """ Warp around screen""" if self.top&gt;games.screen.height: self.bottom = 0 if self.bottom &lt; 0: self.top=games.screen.height if self.left &gt; games.screen.width: self.right = 0 if self.left &lt; 0: self.left = games.screen.width class Ship(games.Sprite): """The player's ship""" image = games.load_image("ship.bmp") ROTATION_STEP = 3 def update(self): if games.keyboard.is_pressed(games.K_LEFT): self.angle -= Ship.ROTATION_STEP if games.keyboard.is_pressed(games.K_RIGHT): self.angle += Ship.ROTATION_STEP def main(): nebula_image = games.load_image("nebula.jpg") games.screen.background = nebula_image for i in range(8): x = random.randrange(games.screen.width) y = random.randrange(games.screen.height) size = random.choice([Asteroid.SMALL, Asteroid.MEDIUM, Asteroid.LARGE]) new_asteroid = Asteroid(x = x, y = y,size = size) games.screen.add(new_asteroid) the_ship = Ship(image = Ship.image, x = games.screen.width/2, y = games.screen.height/2) games.screen.add(the_ship) games.screen.mainloop() main() </code></pre> <hr> <p>I have tried removing the size argument but it caused more errors in the code. We also tried changing the size tag to something else to see if that helps and it didn't work either. So I'm stuff for what I need to do to make this code work. I am working on it for a class project in school. English is not my first language so I have had a classmate write this up.</p> <p>Thank you.</p>
0
Mask email in javascript
<p>I am new for javascript, i want to mask email id in js</p> <p>Like <strong>[email protected]</strong> should mask as <strong>m</strong>****<strong>[email protected]</strong>. how do i achieve in js. My below code is not working in ie browser</p> <pre><code>var maskid = &quot;&quot;; var myemailId = &quot;[email protected]&quot;; var prefix= myemailId.substring(0, myemailId.lastIndexOf(&quot;@&quot;)); var postfix= myemailId.substring(myemailId.lastIndexOf(&quot;@&quot;)); for(var i=0; i&lt;prefix.length; i++) { if(i == 0 || i == prefix.length - 1) { maskid = maskid + prefix[i].toString(); } else { maskid = maskid + &quot;*&quot;; } } maskid = maskid + postfix; </code></pre> <p>I want to handle in JS is the requirement.</p> <p>Thanks</p>
0
iOS Contacts How to Fetch contact by phone Number
<p>I just want to get contact given name and family name by phone number. I tried this but this is too much slow and cpu is hitting over %120.</p> <pre><code>let contactStore = CNContactStore() let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey] var contacts = [CNContact]() do { try contactStore.enumerateContactsWithFetchRequest(CNContactFetchRequest.init(keysToFetch: keys), usingBlock: { (contact, cursor) in if (!contact.phoneNumbers.isEmpty) { for phoneNumber in contact.phoneNumbers { if let phoneNumberStruct = phoneNumber.value as? CNPhoneNumber { do { let libPhone = try util.parseWithPhoneCarrierRegion(phoneNumberStruct.stringValue) let phoneToCompare = try util.getNationalSignificantNumber(libPhone) if formattedPhone == phoneToCompare { contacts.append(contact) } }catch { print(error) } } } } }) if contacts.count &gt; 0 { contactName = (contacts.first?.givenName)! + " " + (contacts.first?.familyName)! print(contactName) completionHandler(contactName) } }catch { print(error) } </code></pre> <p>Also When I Use phonenumber Kit for find contacts its increasing cpu and giving late response.</p> <pre><code>var result: [CNContact] = [] let nationalNumber = PhoneNumberKit().parseMultiple([phoneNumber]) let number = nationalNumber.first?.toNational() print(number) for contact in self.addressContacts { if (!contact.phoneNumbers.isEmpty) { let phoneNumberToCompareAgainst = number!.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("") for phoneNumber in contact.phoneNumbers { if let phoneNumberStruct = phoneNumber.value as? CNPhoneNumber { let phoneNumberString = phoneNumberStruct.stringValue let nationalContactNumber = PhoneNumberKit().parseMultiple([phoneNumberString]) let nationalContactNumberString = nationalContactNumber.first?.toNational() if nationalContactNumberString == number { result.append(contact) } } } } } return result </code></pre>
0
id_rsa.pub is not a public key file
<p>I opened my public key in libre office and edited the comment section of the key and then saved. But when I run:</p> <pre><code>ssh-keygen -l -f id_rsa.pub </code></pre> <p>I get:</p> <pre><code>id_rsa.pub is not a public key file. </code></pre> <p>The file is no longer recognized as a public key file. How do I solve this?</p>
0
Method injection using Dagger 2
<p>I haven't managed to find a good explanation/example on method injection using Dagger 2. Could someone please help me understand?</p> <p>Example:</p> <pre><code>@Inject public Dinner makeDinner(Pasta pasta, Sauce sauce) { mPan.add(pasta); mPan.add(sauce); return mPan.cookDinner(); } </code></pre> <p>So if I annotate my method with <code>@Inject</code>, am I correct to assume that the arguments in the method signature will be injected with defined objects from the object graph? How can I use this method in my code then? It will still expect me to supply all the arguments, when I make the method call, which sort of defeats the purpose.</p> <p><strong>UPDATE:</strong></p> <p>So from what I understand the Dinner object will be available if I call <code>DinnerComponent.dinner()</code>, assuming my DinnerComponent is set up like this:</p> <pre><code>@Component(modules = DinnerModule.class) public interface DinnerComponent { Dinner dinner(); } </code></pre> <p>and my DinnerModule is set up like this:</p> <pre><code>@Module public class DinnerModule { public DinnerModule() {} @Provides Pasta providePasta() { return new Pasta(); } @Provides Sauce provideSauce() { return new Sauce(); } } </code></pre> <p>What happens if I want my dinner fried? So let's introduce this method:</p> <pre><code>@Inject public Dinner makeDinner(Pasta pasta, Sauce sauce) { mPan.add(pasta); mPan.add(sauce); return mPan.fryDinner(); } </code></pre> <p>How can I specify within the component which dinner is which?</p>
0