title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
How to make a dotnet webservice set minOccurs="1" on a string value
|
<p>I have an XSD:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://a.com/a.xsd"
targetNamespace="http://a.com/a.xsd"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xs:element name="A">
<xs:complexType>
<xs:sequence>
<xs:element name="Item" minOccurs="1" maxOccurs="1">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
<xs:whiteSpace value="collapse"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
</code></pre>
<p>Which I have converted into a C# class using XSD.exe v2.0.50727.3615 which generates code as follows</p>
<pre><code>namespace A {
using System.Xml.Serialization;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://a.com/a.xsd")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://a.com/a.xsd", IsNullable=false)]
public partial class A {
private string itemField;
/// <remarks/>
public string Item {
get {
return this.itemField;
}
set {
this.itemField = value;
}
}
}
}
</code></pre>
<p>I am returning an A.A object in my webservice, which produces this snippet in the service description</p>
<pre><code><s:schema elementFormDefault="qualified" targetNamespace="http://a.com/a.xsd">
<s:element name="Test2Result">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="Item" type="s:string" />
</s:sequence>
</s:complexType>
</s:element>
</s:schema>
</code></pre>
<p>The change from minOccrus="1" in the XSD to minOccurs="0" on the auto-generated WSDL is causing grief to the machine on the other end of the system.</p>
<p>I could of course provide a hand edited WSDL for them to use, but I would like the auto-generated one to suit their needs.</p>
<p>Any suggestions on how to convince dotnet to output minOccurs="1" for a string type in its autogenerated WSDLs without also adding nillable="true"?</p>
| 0 | 1,373 |
Row-major vs Column-major confusion
|
<p>I've been reading a lot about this, the more I read the more confused I get.</p>
<p>My understanding: In row-major rows are stored contiguously in memory, in column-major columns are stored contiguously in memory. So if we have a sequence of numbers <code>[1, ..., 9]</code> and we want to store them in a row-major matrix, we get:</p>
<pre><code>|1, 2, 3|
|4, 5, 6|
|7, 8, 9|
</code></pre>
<p>while the column-major (correct me if I'm wrong) is:</p>
<pre><code>|1, 4, 7|
|2, 5, 8|
|3, 6, 9|
</code></pre>
<p>which is effectively the transpose of the previous matrix.</p>
<p>My confusion: Well, I don't see any difference. If we iterate on both the matrices (by rows in the first one, and by columns in the second one) we'll cover the same values in the same order: <code>1, 2, 3, ..., 9</code></p>
<p>Even matrix multiplication is the same, we take the first contiguous elements and multiply them with the second matrix columns. So say we have the matrix <code>M</code>:</p>
<pre><code>|1, 0, 4|
|5, 2, 7|
|6, 0, 0|
</code></pre>
<p>If we multiply the previous row-major matrix <code>R</code> with <code>M</code>, that is <code>R x M</code> we'll get:</p>
<pre><code>|1*1 + 2*0 + 3*4, 1*5 + 2*2 + 3*7, etc|
|etc.. |
|etc.. |
</code></pre>
<p>If we multiply the column-major matrix <code>C</code> with <code>M</code>, that is <code>C x M</code> by taking the columns of <code>C</code> instead of its rows, we get exactly the same result from <code>R x M</code></p>
<p>I'm really confused, if everything is the same, why do these two terms even exist? I mean even in the first matrix <code>R</code>, I could look at the rows and consider them columns...</p>
<p>Am I missing something? What does row-major vs col-major actually imply on my matrix math? I've always learned in my Linear Algebra classes that we multiply rows from the first matrix with columns from the second one, does that change if the first matrix was in column-major? do we now have to multiply its columns with columns from the second matrix like I did in my example or was that just flat out wrong?</p>
<p>Any clarifications are really appreciated!</p>
<p><strong>EDIT:</strong> One of the other main sources of confusion I'm having is GLM... So I hover over its matrix type and hit F12 to see how it's implemented, there I see a vector array, so if we have a 3x3 matrix we have an array of 3 vectors. Looking at the type of those vectors I saw 'col_type' so I assumed that each one of those vectors represent a column, and thus we have a column-major system right?</p>
<p>Well, I don't know to be honest. I wrote this print function to compare my translation matrix with glm's, I see the translation vector in glm at the last row, and mine is at the last column... </p>
<p><a href="https://i.stack.imgur.com/qMxjQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qMxjQ.png" alt="enter image description here"></a></p>
<p>This adds nothing but more confusion. You can clearly see that each vector in <code>glmTranslate</code> matrix represents a row in the matrix. So... that means that the matrix is row-major right? What about my matrix? (I'm using a float array[16]) the translation values are in the last column, does that mean my matrix is column-major and I didn't now it? <em>tries to stop head from spinning</em></p>
| 0 | 1,037 |
How do I write multiple objects to the serializable file and read them when the program is used again?
|
<p>I want to maintain database of users of a Bank for my project. I am able to save the number of users in one serializable file. But when I try to save the user to database it adds only the latest one to database.</p>
<p>Below is the sneak peak of code which writes the objects:</p>
<pre><code>if(e.getSource()==submit) {
if(uFName != null && uLName != null && uInitialDeposit !=0) {
if(uAccountType=="Savings") {
Random randomGenerator = new Random();
//Gets the number of users from file if file exists
File f = new File(fileNameAdmin);
if(f.exists() && !f.isDirectory()) {
admin=db.readFromAdminDatabase();
}
u[admin.numberOfUsers]= new User();
u[admin.numberOfUsers].fName=uFName;
u[admin.numberOfUsers].lName=uLName;
u[admin.numberOfUsers].initalDeposit=uInitialDeposit;
u[admin.numberOfUsers].interestRate=uInterestRate;
u[admin.numberOfUsers].accountType="Saving";
u[admin.numberOfUsers].accountNumber=690000+admin.numberOfSavingsAccount;
//Generates a 4 digit random number which will be used as ATM pin
u[admin.numberOfUsers].atmPin=randomGenerator.nextInt(9999-1000)+1000;
//A savings account will be created
sa[admin.numberOfSavingsAccount]=new SavingsAccount(u[admin.numberOfUsers].accountNumber,u[admin.numberOfUsers].fName,u[admin.numberOfUsers].lName,
u[admin.numberOfUsers].initalDeposit,
u[admin.numberOfUsers].interestRate);
u[admin.numberOfUsers].sa=sa[admin.numberOfSavingsAccount];
System.out.println(u[admin.numberOfUsers].sa.balance);
JOptionPane.showMessageDialog(submit,"Congratulations! You are now a member of Symbiosis Bank."
+ "\nYour account number is "+u[admin.numberOfUsers].accountNumber
+" and your ATM Pin is "+u[admin.numberOfUsers].atmPin,"Account Created",JOptionPane.INFORMATION_MESSAGE);
try {
//for(int j = 0; j<admin.numberOfUsers; j++)
db.addUserToDatabase(u[admin.numberOfUsers]);
admin.numberOfSavingsAccount++;
admin.numberOfUsers++;
db.updateAdminDatabase(admin);
dispose();
setVisible(false);
//Welcome welcome = new Welcome();
//welcome.setVisible(true);
InitialInput back = new InitialInput();
back.setVisible(true);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
</code></pre>
<p>The database class which has functions to write to database:</p>
<pre><code>import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Database implements Serializable {
String fileName = System.getProperty("user.home")+"/db.ser";
String fileNameAdmin = System.getProperty("user.home")+"/admindb.ser";
public void addUserToDatabase(User u){
FileOutputStream fos;
try {
fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(u);
oos.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("finally")
public User readFromUserDatabase() {
FileInputStream fis;
User temp = null;
try {
fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
temp = (User)ois.readObject();
//System.out.println(temp.fName);
ois.close();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
return temp;
}
}
public void updateAdminDatabase(Administrator admin) {
FileOutputStream fos;
try {
fos = new FileOutputStream(fileNameAdmin);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(admin);
oos.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("finally")
public Administrator readFromAdminDatabase() {
FileInputStream fis;
Administrator temp = null;
try {
fis = new FileInputStream(fileNameAdmin);
ObjectInputStream ois = new ObjectInputStream(fis);
temp = (Administrator)ois.readObject();
//System.out.println(temp.fName);
ois.close();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
return temp;
}
}
}
</code></pre>
<p>The code which is trying to read the database:</p>
<pre><code>public void actionPerformed(ActionEvent e) {
if(e.getSource()==deposit) {
//Ask the amount to deposit
int userAmountToDeposit;
try {
for(int i = 0; i<=admin.numberOfUsers; i++) {
u[i] = db.readFromUserDatabase();
System.out.println(u[i].accountNumber);
}
for(int j =0; j<=admin.numberOfUsers; j++) {
if(u[j].accountNumber==userAccountNumber) {
if(u[j].atmPin==userPin) {
u[j].accountBalance=u[j].sa.balance;
u[j].sa.deposit(10);
u[j].accountBalance=u[j].sa.balance;
System.out.println(u[j].accountBalance);
}
}
}
}
</code></pre>
| 0 | 3,105 |
Twitter Bootstrap carousel not working
|
<p>Do I need to download more library to run Twitter Bootstrap carousel? I just downloaded Twitter Bootstrap from <a href="http://twitter.github.io/bootstrap/index.html" rel="nofollow">http://twitter.github.io/bootstrap/index.html</a>. I think there is a problem with my javascript libraries. I can see images, left and right buttons but when i click to right for example, nothing happens.</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<script>
!function ($) {
$(function(){
// carousel demo
$('#myCarousel').carousel()
})
}(window.jQuery)
</script>
<!-- Le styles -->
<link href="css/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {
padding-top: 60px;
padding-bottom: 40px;
}
</style>
<link href="css/bootstrap-responsive.css" rel="stylesheet">
</code></pre>
<p></p>
<p></p>
<pre><code> <div id="myCarousel" class="carousel slide">
<div class="carousel-inner">
<div class="item active">
<img src="assets/img/01.jpg" alt="">
<div class="container">
<div class="carousel-caption">
<h1>Example headline.</h1>
<p class="lead">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p>
<a class="btn btn-large btn-primary" href="#">Sign up today</a>
</div>
</div>
</div>
<div class="item">
<img src="assets/img/02.jpg" alt="">
<div class="container">
<div class="carousel-caption">
<h1>Another example headline.</h1>
<p class="lead">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p>
<a class="btn btn-large btn-primary" href="#">Learn more</a>
</div>
</div>
</div>
<div class="item">
<img src="assets/img/03.jpg" alt="">
<div class="container">
<div class="carousel-caption">
<h1>One more for good measure.</h1>
<p class="lead">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p>
<a class="btn btn-large btn-primary" href="#">Browse gallery</a>
</div>
</div>
</div>
</div>
<a class="left carousel-control" href="#myCarousel" data-slide="prev">&lsaquo;</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">&rsaquo;</a>
</div><!-- /.carousel -->
<script src="js/jquery.js"></script>
<script src="js/bootstrap-transition.js"></script>
<script src="js/bootstrap-alert.js"></script>
<script src="js/bootstrap-modal.js"></script>
<script src="js/bootstrap-dropdown.js"></script>
<script src="js/bootstrap-scrollspy.js"></script>
<script src="js/bootstrap-tab.js"></script>
<script src="js/bootstrap-tooltip.js"></script>
<script src="js/bootstrap-popover.js"></script>
<script src="js/bootstrap-button.js"></script>
<script src="js/bootstrap-collapse.js"></script>
<script src="js/bootstrap-carousel.js"></script>
<script src="js/bootstrap-typeahead.js"></script>
<script src="js/holder/holder.js"></script>
</code></pre>
<p>
</p>
| 0 | 1,870 |
ionic: module has no exported member
|
<p>I am a newbie of ionic framework, just started now. I am working on windows. I created my app with this command:</p>
<pre><code>ionic start ionic-welcome tabs
ionic serve
</code></pre>
<p>I create a new page with below command</p>
<pre><code>ionic g page welcome
</code></pre>
<p>I get this response in my console:</p>
<blockquote>
<p>[OK] Generated a page named welcome!</p>
</blockquote>
<p>updated app.module.ts for welcome page:</p>
<pre><code>import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { Welcome } from '../pages/welcome/welcome';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
@NgModule({
declarations: [
MyApp,
Welcome,
AboutPage,
ContactPage,
HomePage,
TabsPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
Welcome,
AboutPage,
ContactPage,
HomePage,
TabsPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
</code></pre>
<p>But when i browse to localhost:8100 i am getting this error for "welcome page". </p>
<blockquote>
<p>Module
'"C:/xampp/htdocs/ionic/ionic-welcome/src/pages/welcome/welcome"' has
no exported member 'Welcome'.</p>
</blockquote>
<p>package.json:</p>
<pre><code>{
"name": "ionic-welcome",
"version": "0.0.1",
"author": "Ionic Framework",
"homepage": "http://ionicframework.com/",
"private": true,
"scripts": {
"clean": "ionic-app-scripts clean",
"build": "ionic-app-scripts build",
"lint": "ionic-app-scripts lint",
"ionic:build": "ionic-app-scripts build",
"ionic:serve": "ionic-app-scripts serve"
},
"dependencies": {
"@angular/common": "4.1.3",
"@angular/compiler": "4.1.3",
"@angular/compiler-cli": "4.1.3",
"@angular/core": "4.1.3",
"@angular/forms": "4.1.3",
"@angular/http": "4.1.3",
"@angular/platform-browser": "4.1.3",
"@angular/platform-browser-dynamic": "4.1.3",
"@ionic-native/core": "3.12.1",
"@ionic-native/splash-screen": "3.12.1",
"@ionic-native/status-bar": "3.12.1",
"@ionic/storage": "2.0.1",
"ionic-angular": "3.6.0",
"ionicons": "3.0.0",
"rxjs": "5.4.0",
"sw-toolbox": "3.6.0",
"zone.js": "0.8.12"
},
"devDependencies": {
"@ionic/app-scripts": "2.1.3",
"typescript": "2.3.4"
},
"description": "An Ionic project"
}
</code></pre>
<p>Some says to remove '^' character from package.json but don't have one. I am out of options don't know what to do next, please help.
<a href="https://i.stack.imgur.com/DfYAV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DfYAV.png" alt="enter image description here"></a></p>
| 0 | 1,273 |
Uploading mp4 files using PHP
|
<p>I am able to upload png/jpegs/images using PHP upload script but am not able to upload mp4 files on my local server. Script is not displaying any error.</p>
<pre><code><?php
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
//include authentication here/ Gmail is good solution for now
//check if it's not allowing any other extenstion other than MP4
$allowedExts = array("gif", "jpeg", "jpg", "png","mp4");
$temp = explode(".", $_FILES["file"]["name"]);
print_r($_FILES["file"]["type"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
|| ($_FILES["file"]["type"] == "video/mp4"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("uploads/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $_FILES["file"]["name"]);
echo "Stored in: " . "uploads/" . $_FILES["file"]["name"];
}
}
} else {
echo "Invalid file";
}
?>
enter code here
changed my code to this
<?php
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
//include authentication here/ Gmail is good solution for now
//check if it's not allowing any other extenstion other than MP4
$allowedExts = array("gif", "jpeg", "jpg", "png","mp4");
$temp = explode(".", $_FILES["file"]["name"]);
print_r($_FILES["file"]["type"]);
$extension = end($temp);
if (($_FILES["file"]["size"] < 200000)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("uploads/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $_FILES["file"]["name"]);
echo "Stored in: " . "uploads/" . $_FILES["file"]["name"];
}
}
} else {
echo "Invalid file";
}
?>
</code></pre>
<p>still same error</p>
<blockquote>
<p>video/mp4Invalid file</p>
</blockquote>
| 0 | 1,373 |
"error: expected identifier or ‘(’ before numeric constant" –?
|
<p>The error in the title occurs on the '<code>#define</code>' line for every single function-like macro in this header file (starting at line 45). Am I doing something wrong?</p>
<pre><code>#ifndef ASSEMBLER_H
#define ASSEMBLER_H
/* Ports */
#define Input 0
#define Output 15
/* Registers */
#define Z 0
#define A 1
#define B 2
#define C 3
#define D 4
#define E 5
#define F 6
#define G 7
/* OP Codes */
/*-----Control--------*/
#define HLT_OP 0
#define JMP_OP 1
#define CJMP_OP 2
#define OJMP_OP 3
/*-----Load/Store-----*/
#define LOAD_OP 4
#define STORE_OP 5
#define LOADI_OP 6
#define NOP_OP 7
/*-----Math-----------*/
#define ADD_OP 8
#define SUB_OP 9
/*-----Device I/O-----*/
#define IN_OP 10
#define OUT_OP 11
/*-----Comparison-----*/
#define EQU_OP 12
#define LT_OP 13
#define LTE_OP 14
#define NOT_OP 15
/* Macros */
/*-----Control--------*/
#define HLT()
( HLT_OP << 28 )
#define JMP(address)
( (JMP_OP << 28) | (address) )
#define CJMP(address)
( (CJMP_OP << 28) | (address) )
#define OJMP(address)
( (OJMP_OP << 28) | (address) )
/*-----Load/Store-----*/
#define LOAD(dest, value)
( (LOAD_OP << 28) | ((dest) << 24) | (value) )
#define STORE(dest, value)
( (STORE_OP << 28) | ((dest) << 24) | (value) )
#define LOADI(dest, value)
( (LOADI_OP << 28) | ((dest) << 24) | (value) )
#define NOP()
( NOP_OP << 28 )
/*-----Math-----------*/
#define ADD(dest, op1, op2)
( (ADD_OP << 28) | ((dest) << 24) | ((op1) << 20) | ((op2) << 16) )
#define SUB(dest, op1, op2)
( (SUB_OP << 28) | ((dest) << 24) | ((op1) << 20) | ((op2) << 16) )
/*-----Device I/O-----*/
#define IN(reg)
( (IN_OP << 28) | ((reg) << 24) | (Input) )
#define OUT(reg)
( (OUT_OP << 28) | ((reg) << 24) | (Output) )
/*-----Comparison-----*/
#define EQU(reg1, reg2)
( (EQU_OP << 28) | ((reg1) << 24) | ((reg2) << 20) )
# define LT(reg1, reg2)
( (LT_OP << 28) | ((reg1) << 24) | ((reg2) << 20) )
#define LTE(reg1, reg2)
( (LTE_OP << 28) | ((reg1) << 24) | ((reg2) << 20) )
#define NOT()
( NOT_OP << 28 )
#endif
</code></pre>
| 0 | 1,180 |
How to create a vertical carousel using plain JavaScript and CSS
|
<p>I am trying to create a vertical carousel using vanilla JavaScript and CSS. I know that jQuery has a carousel library but I want to have a go at building this from scratch using no external libraries. I started off by just trying to move the top image and then I planned to move on to making the next image move. I got stuck on the first image. This is where I need your help, StackOverflowers.</p>
<p>My HTML:</p>
<pre><code><div class="slider vertical" >
<img class="first opened" src="http://malsup.github.io/images/beach1.jpg">
<img class="opened" src="http://malsup.github.io/images/beach2.jpg">
<img src="http://malsup.github.io/images/beach3.jpg">
<img src="http://malsup.github.io/images/beach4.jpg">
<img src="http://malsup.github.io/images/beach5.jpg">
<img src="http://malsup.github.io/images/beach9.jpg">
</div>
<div class="center">
<button id="prev">∧ Prev</button>
<button id="next">∨ Next</button>
</div>
</code></pre>
<p>JavaScript:</p>
<pre><code>var next = document.getElementById('next');
var target = document.querySelector('.first');
next.addEventListener('click', nextImg, false);
function nextImg(){
if (target.classList.contains('opened')) {
target.classList.remove('opened');
target.classList.add('closed');
} else {
target.classList.remove('closed');
target.classList.add('opened');
}
}
</code></pre>
<p>CSS:</p>
<pre><code>div.vertical {
width: 100px;
}
.slider {
position: relative;
overflow: hidden;
height: 250px;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
-ms-box-sizing:border-box;
box-sizing:border-box;
-webkit-transition:-webkit-transform 1.3s ease;
-moz-transition: -moz-transform 1.3s ease;
-ms-transition: -ms-transform 1.3s ease;
transition: transform 1.3s ease;
}
.slider img {
width: 100px;
height: auto;
padding: 2px;
}
.first.closed{
/* partially offscreen */
-webkit-transform: translate(0, -80%);
-moz-transform: translate(0, -80%);
-ms-transform: translate(0, -80%);
transform: translate(0, -80%);
}
.first.opened{
/* visible */
-webkit-transform: translate(0, 0%);
-moz-transform: translate(0, 0%);
-ms-transform: translate(0, 0%);
transform: translate(0, 0%);
}
</code></pre>
<p>My mode of thinking was:</p>
<ol>
<li>use classes to move and show content</li>
<li>use JavaScript to add and remove classes </li>
</ol>
<p>I think I may not have broken the problem down properly.</p>
<p>This is how I would like it to look: <a href="http://jsfiddle.net/natnaydenova/7uXPx/" rel="noreferrer">http://jsfiddle.net/natnaydenova/7uXPx/</a></p>
<p>And this is my abysmal attempt: <a href="http://jsfiddle.net/6cb58pkr/" rel="noreferrer">http://jsfiddle.net/6cb58pkr/</a></p>
| 0 | 1,260 |
Hibernate: how to call a stored function returning a varchar?
|
<p>I am trying to call a legacy stored function in an Oracle9i DB from Java using Hibernate. The function is declared like this:</p>
<pre><code>create or replace FUNCTION Transferlocation_Fix (mnemonic_code IN VARCHAR2)
RETURN VARCHAR2
</code></pre>
<p>After several failed tries and extensive googling, I found <a href="https://forum.hibernate.org/viewtopic.php?f=1&t=976887&view=previous" rel="nofollow noreferrer">this thread</a> on the Hibernate forums which suggested a mapping like this:</p>
<pre><code><sql-query name="TransferLocationFix" callable="true">
<return-scalar column="retVal" type="string"/>
select Transferlocation_Fix(:mnemonic) as retVal from dual
</sql-query>
</code></pre>
<p>My code to execute it is</p>
<pre><code> Query query = session.getNamedQuery("TransferLocationFix");
query.setParameter("mnemonic", "FC3");
String result = (String) query.uniqueResult();
</code></pre>
<p>and the resulting log is</p>
<pre><code>DEBUG (org.hibernate.jdbc.AbstractBatcher:366) - - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
DEBUG (org.hibernate.SQL:401) - - select Transferlocation_Fix(?) as retVal from dual
TRACE (org.hibernate.jdbc.AbstractBatcher:484) - - preparing statement
TRACE (org.hibernate.type.StringType:133) - - binding 'FC3' to parameter: 2
TRACE (org.hibernate.type.StringType:133) - - binding 'FC3' to parameter: 2
java.lang.NullPointerException
at oracle.jdbc.ttc7.TTCAdapter.newTTCType(TTCAdapter.java:300)
at oracle.jdbc.ttc7.TTCAdapter.createNonPlsqlTTCColumnArray(TTCAdapter.java:270)
at oracle.jdbc.ttc7.TTCAdapter.createNonPlsqlTTCDataSet(TTCAdapter.java:231)
at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1924)
at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:850)
at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2599)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2963)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:658)
at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:736)
at com.mchange.v2.c3p0.impl.NewProxyCallableStatement.execute(NewProxyCallableStatement.java:3044)
at org.hibernate.dialect.Oracle8iDialect.getResultSet(Oracle8iDialect.java:379)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:193)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1784)
at org.hibernate.loader.Loader.doQuery(Loader.java:674)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.doList(Loader.java:2220)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
at org.hibernate.loader.Loader.list(Loader.java:2099)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:289)
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1695)
at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:142)
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:152)
at org.hibernate.impl.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:811)
at com.my.project.SomeClass.method(SomeClass.java:202)
...
</code></pre>
<p>Any clues what am I doing wrong? Or any better ways to call this stored function?</p>
<hr>
<p><strong>Update:</strong> upon trying @axtavt's suggestion, I get the following error:</p>
<pre><code>ORA-14551: cannot perform a DML operation inside a query
</code></pre>
<p>The function indeed does extensive inserts/updates, so I guess the only way to run it would be using the stored procedure syntax. I just have no clue how to map the return value:</p>
<pre><code><sql-query name="TransferLocationFix" callable="true">
<return-scalar column="???" type="string"/>
{ ? = call Transferlocation_Fix(:mnemonic) }
</sql-query>
</code></pre>
<p>What should be the <code>column</code>? I will try an empty value...</p>
<hr>
<p><strong>Update2:</strong> that failed as well, with an SQL Grammar Exception... So I tried the JDBC way as suggested by Pascal, and it seems to work! I added the code in an answer below.</p>
| 0 | 1,521 |
Sync SQLite Database to google drive without confirmation
|
<p>I have to implement synchronization in my android app. So, I need to use user's google drive to store and retrieve info. I have created functionality to store *.db file to drive. But problem is user has to confirm file upload operation every time. I want to upload file on every app close without confirmation. Is it possible ? Is there other way to synchronize sqlite db without having own server ?</p>
<pre><code>public static void backUpDb(final Activity context){
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(new ConnectionCallbacks() {
@Override
public void onConnectionSuspended(int arg0) {
}
@Override
public void onConnected(Bundle arg0) {
Log.i(TAG, "API client connected.");
saveFileToDrive( context);
}
})
.addOnConnectionFailedListener(
new OnConnectionFailedListener() {
@Override
public void onConnectionFailed(
ConnectionResult result) {
Log.i(TAG,
"GoogleApiClient connection failed: "
+ result.toString());
if (!result.hasResolution()) {
// show the localized error
// dialog.
GooglePlayServicesUtil
.getErrorDialog(
result.getErrorCode(),
context, 0).show();
return;
}
try {
result.startResolutionForResult(
context,
REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG,
"Exception while starting resolution activity",
e);
}
}
}).build();
mGoogleApiClient.connect();
//mGoogleApiClient.disconnect();
}
public static void saveFileToDrive(final Activity context) {
Drive.DriveApi.newContents(mGoogleApiClient).setResultCallback(
new ResultCallback<ContentsResult>() {
@Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
return;
}
OutputStream outputStream = result.getContents()
.getOutputStream();
try {
// outputStream.write(bitmapStream.toByteArray());
//ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
File dbFile = context.getDatabasePath(databaseName);
//dbFile.
int size = (int) dbFile.length();
byte[] bytes = new byte[size];
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(dbFile));
buf.read(bytes, 0, bytes.length);
buf.close();
byte[] b = "aa".getBytes();
outputStream.write(bytes);
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("db");
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType(mimeType).setTitle("aldkan.db")
.build();
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialContents(result.getContents())
.build(mGoogleApiClient);
try {
context.startIntentSenderForResult(intentSender, 2,
null, 0, 0, 0);
} catch (SendIntentException e) {
e.printStackTrace();
}
}
});
}
</code></pre>
| 0 | 2,460 |
The Name "___" does not exist in the current context
|
<p>I seem to be having an issue with my project in Visual Studio 2012 where I received 21 errors saying the names(ddlstud,hidId,txtName,txtCoverImage,txtReldate,gvVidGame) do not exist in the current context. I have my default.aspx file set to read from my default.aspx.cs file.</p>
<p>Here is my default.aspx file</p>
<pre><code><%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="True" CodeBehind="Default.aspx.cs" Inherits="VideoGameWiki._Default" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<asp:GridView ID="gvVidGame" runat="server"></asp:GridView><br />
<asp:Label ID="lblName" runat="server" Text="Name: "></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
<asp:Label ID="lblStud" runat="server" Text="Studio: "></asp:Label>
<asp:DropDownList ID="ddlStud" runat="server"></asp:DropDownList><br />
<asp:Label ID="lblReldate" runat="server" Text="Release date: "></asp:Label>
<asp:TextBox ID="txtReldate" runat="server"></asp:TextBox><br />
<asp:Label ID="lblCoverImage" runat="server" Text="Cover Image: "></asp:Label>
<asp:TextBox ID="txtCoverImage" runat="server"></asp:TextBox><br />
<asp:Label ID="lblDescr" runat="server" Text="Description: "></asp:Label>
<asp:TextBox ID="txtDescr" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add" />
<br />
<asp:Button ID="btnNext" runat="server" Text="Next" OnClick="btnNext_Click" />
<input runat="server" id="hidId" type="hidden" />
<asp:Button ID="btnPrev" runat="server" OnClick="btnPrev_Click" Text="Prev" />
<asp:Button ID="Btn_delete" runat="server" Text="Delete" />
</asp:Content>
</code></pre>
<p>and here is my default.aspx.cs file</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace VideoGameWiki
{
public partial class _Default : System.Web.UI.Page
{
private VideoGamesWikiContainer entities = new VideoGamesWikiContainer();
private int currentId = 0;
}
}
</code></pre>
<p><sup><a href="http://pastebin.com/raw.php?i=NrpfX3Rb" rel="nofollow">complete sources here</a></sup></p>
<p>(EDIT) Here is my designer.cs file as the methods that were suggested did not work unfortunately.</p>
<pre><code> namespace VideoGameWiki {
public partial class _Default : System.Web.UI.Page
{
/// <summary>
/// gvVidGame control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView gvVidGame;
</code></pre>
<p><sup><a href="http://pastebin.com/raw.php?i=WsN3RnVX" rel="nofollow">complete sources here</a></sup></p>
<p>Any help would be appreciated!</p>
| 0 | 1,345 |
Cannot open http://localhost:8080/ when Tomcat is running in Eclipse
|
<p>I got the same problem with the questions here : <a href="https://stackoverflow.com/questions/2280064/tomcat-started-in-eclipse-but-unable-to-connect-to-link-to-http-localhost8085">Tomcat started in eclipse but unable to connect to link to http://localhost:8085/</a>, that means I can't open <a href="http://localhost:8080/" rel="nofollow noreferrer">http://localhost:8080/</a> at the browser :</p>
<pre><code>HTTP Status 404 - /
type Status report
message /
description The requested resource (/) is not available.
Apache Tomcat/7.0.27
//Console info when tomcat started//
Apr 10, 2012 4:26:32 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to org.eclipse.jst.jee.server:SimpleServletProject' did not find a matching property.
Apr 10, 2012 4:26:32 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Apr 10, 2012 4:26:33 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Apr 10, 2012 4:26:33 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 880 ms
Apr 10, 2012 4:26:33 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Apr 10, 2012 4:26:33 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.27
Apr 10, 2012 4:26:33 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Apr 10, 2012 4:26:33 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Apr 10, 2012 4:26:33 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 495 ms
</code></pre>
<p>I'm using Tomcat 7.0.27, Eclipse Europa and Java 1.6.0_32. I saw BalusC's answer, but the problem is that I couldn't select Tomcat installation (the picture below).</p>
<p>What could be wrong here?</p>
<p><img src="https://i.stack.imgur.com/hoRaE.png" alt="enter image description here"></p>
<p>EDIT1 : When I tried to create demo webpage, it couldn't be opened too (with the same error).</p>
<p>EDIT2: Followed this thread <a href="https://stackoverflow.com/questions/4919846/why-tomcat-server-location-property-is-greyed-in-eclipse">Why tomcat server location property is greyed in Eclipse</a> I can open <a href="http://localhost:8080/" rel="nofollow noreferrer">http://localhost:8080/</a> in the browser, but still cant access the demo web page..</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SimpleServletProject</display-name>
<welcome-file-list>
<welcome-file> index.html</welcome-file>
</welcome-file-list>
</web-app>
</code></pre>
<p>PS : It seems that there's no more space to me to post index.hmtl (it's just a normal html )..</p>
| 0 | 1,176 |
Login request validation token issue
|
<p>I have been going through the error logs of a development project and found the following error (name changed to protect the <strike>guilty</strike> innocent)-</p>
<blockquote>
<p>The provided anti-forgery token was meant for user "", but the current
user is "admin".</p>
</blockquote>
<p>This was not an especially difficult issue to reproduce-</p>
<ol>
<li>Open the application at the login page</li>
<li>Open a second window or tab in the <strong>same browser</strong> on the <strong>same computer</strong> to the login page before logging in</li>
<li>Login in the first window (or indeed second, the order doesn't matter)</li>
<li>Attempt to login in the remaining login window</li>
</ol>
<p>The stack trace is-</p>
<blockquote>
<p>System.Web.Mvc.HttpAntiForgeryException (0x80004005): The provided
anti-forgery token was meant for user "", but the current user is
"admin". at
System.Web.Helpers.AntiXsrf.TokenValidator.ValidateTokens(HttpContextBase
httpContext, IIdentity identity, AntiForgeryToken sessionToken,
AntiForgeryToken fieldToken) at
System.Web.Helpers.AntiXsrf.AntiForgeryWorker.Validate(HttpContextBase
httpContext) at System.Web.Helpers.AntiForgery.Validate() at
System.Web.Mvc.ValidateAntiForgeryTokenAttribute.OnAuthorization(AuthorizationContext
filterContext) at
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext
controllerContext, IList`1 filters, ActionDescriptor actionDescriptor)
at
System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.b__1e(AsyncCallback
asyncCallback, Object asyncState)</p>
</blockquote>
<p>The login method signature is-</p>
<pre><code>[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
...
}
</code></pre>
<p>This is exactly the same as the signature for the method in a internet "ASP.NET MVC 4 Web Application" templated project, which indicates that Microsoft either felt the ValidateAntiForgeryToken was necessary/best practice, or simply added the attribute here because it was used everywhere else.</p>
<p>Obviously there is nothing I can do to handle the problem <em>within</em> this method as it isn't reached, the ValidateAntiForgeryToken is a pre-request filter and it is blocking the request before it reaches the controller.</p>
<p>I could check if the user is authenticated via Ajax before submitting the form and attempt to redirect to them if so, or simply remove the attribute.</p>
<p>The question is this - I understand that the token is design to prevent requests from another site (CSRF) when the user <em>is already authenticated against your site</em> so on that basis <strong>is it an issue to remove it from a form which by definition will be used by unauthenticated users</strong>? </p>
<p>Presumably the attribute in this instance is designed to mitigate malicious actors providing fake login forms for your application (although by the time the exception is thrown presumably the user has already entered his or her details which will have been recorded - but it might alert them something is wrong). Otherwise submitting incorrect credentials to the form from an external site will result in exactly the same result as on the site itself surely? I am not relying on client validation/sanitation to clean up potentially unsafe input.</p>
<p>Have other devs come across this issue (or do we have unusually creative users) and if so how have you resolved/mitigated it?</p>
<p><strong>Update:</strong> This issue still exists in MVC5, entirely intentionally, now with the error message "The provided anti-forgery token was meant for a different claims-based user than the current user." when using default template and Identity providers. There is a relevant question and interesting answer from Microsoft Developer Evangelist and Troy's fellow PluralSight author Adam Tuliper at <a href="https://stackoverflow.com/questions/9433083/anti-forgery-token-on-login-page">Anti forgery token on login page</a> which recommends simply removing the token.</p>
| 0 | 1,093 |
Matching query does not exist?
|
<p>This is the view:</p>
<pre><code>def showProject(request, project_slug):
project = Project.objects.get(slug=project_slug)
tickets = Ticket.objects.filter(project=project)
payload = { 'project':project, 'tickets':tickets }
return render(request, 'project/project.html', payload)
</code></pre>
<p>This is the error:</p>
<pre><code>Traceback:
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\\project\views.py" in showProject
13. project = Project.objects.get(slug=project_slug)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\manager.py" in get
132. return self.get_query_set().get(*args, **kwargs)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\query.py" in get
349. % self.model._meta.object_name)
Exception Type: DoesNotExist at /project/ticket/
Exception Value: Project matching query does not exist.
</code></pre>
<p>A more detailed explanation of what is expected: I have a sidebar that lists all open "tickets." When I click on one of those tickets, it should open it. Instead when I try to open it, I'm getting this error. What is happening?
Here is the model class:</p>
<pre><code>class Project(models.Model):
"""simple project for tracking purposes"""
name = models.CharField(max_length = 64)
slug = models.SlugField(max_length = 100, unique=True,blank=True, null=True)
description = models.CharField(max_length = 255)
owner = models.ForeignKey(User, related_name="+")
created_on = models.DateTimeField(auto_now_add = 1)
active = models.BooleanField(default=True)
parent = models.ForeignKey("self", related_name="children", null=True, blank=True)
repository = models.ForeignKey("Repository", related_name="projects", null=True, blank=True)
book = models.ForeignKey(Book, related_name="+", null=True, blank=True)
acl = models.ManyToManyField(AclEntry)
def save (self):
if not self.slug:
self.slug = '-'.join(self.name.lower().split())
if not self.book:
book = Book(name=self.name, owner=self.owner)
book.save()
self.book = book
super(Project, self).save()
</code></pre>
<p>Here is the template code:</p>
<pre><code>{% block title %}Tickets: {{project.name}}{% endblock %}
{% block main %}
<div id="project-nav">
<span><a href="/project/{{project.slug}}/">Tickets</a></span>
<span><a href="/book/{{book.slug}}{{book.name}}">Docs</a></span>
<span><a href="/project/{{project.slug}}/browse">Browser</a></span>
</div>
<div id="action-nav">
{% block actions %}
<span><a href="/project/{{project.slug}}/tickets/create">Create Ticket</a></span>
<span><a href="/project/{{ project.slug }}/tickets/recent">Recent Activity</a> </span>
<span><a href="/project/{{ project.slug }}/tickets/my/">My Tickets</a></span>
{% endblock %}
</div>
{% for ticket in tickets %}
<div class="ticket">
<div class="ticket-header">
<div class="ticket-title">
<a href="/project/ticket/{{ticket.pk}}">{{ticket.subject}}</a>
</div>
<div id="ticket-number">
#{{ticket.pk}}
</div>
<div id="ticket-state">
{{ticket.get_state_display}}
</div>
<div id="ticket-info">
Reported by {{ticket.created_by}} | created: {{ticket.created_on }} | modified: {{ticket.modified_on}}
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
</code></pre>
<p>It seems that everything I try to do is going back to this, and I don't understand why. What am I missing? Thanks so much!</p>
| 0 | 1,659 |
MySQL MAX from SUM
|
<p>This is freaking me out!
Got the following data:</p>
<pre><code>+----+-----+-------+------------+
| ID | REG | VALUE | DATE |
+----+-----+-------+------------+
| 1 | 1A | 100 | 2009-01-01 |
| 1 | 1A | 100 | 2009-02-01 |
| 1 | 1A | 100 | 2009-03-01 |
| 2 | 1B | 100 | 2009-01-01 |
| 2 | 1B | 100 | 2009-02-01 |
| 2 | 1B | 100 | 2009-03-01 |
| 2 | 1C | 100 | 2009-01-01 |
| 2 | 1C | 100 | 2009-02-01 |
| 2 | 1C | 200 | 2009-03-01 |
+----+-----+-------+------------+
</code></pre>
<p><strong>PS {edit 0001}</strong> :: there's an extra field, which also must be used for filter data, call it {TYPE}, an could get 'SINGLE' or 'MULTIPLE' as value.</p>
<p>I want to get the MAX between SUM(of each different {REG}) for every {ID}. Obviously, this is a simple representation, table got up to 64985928 registers and {DATE} is the filtering data.</p>
<p>That will be, 1st step get the SUM for each {REG}:</p>
<pre><code>+----+------+
| ID | SUM |
+----+------+
| 1 | 300 |
| 2 | 300 |
| 2 | 400 |
+----+------+
</code></pre>
<p>That's: </p>
<pre><code>SELECT
SUM(value)
FROM
table
WHERE
(date BETWEEN '2009-01-01' AND '2009-03-01')
GROUP BY
reg;
</code></pre>
<p>And then, get the MAX from each SUM, which is where I'm stucked:</p>
<pre><code>+----+------+
| ID | MAX |
+----+------+
| 1 | 300 |
| 2 | 400 |
+----+------+
</code></pre>
<p>I've tried:</p>
<pre><code>SELECT
a.id,
MAX(b.sum)
FROM
table a,
(SELECT
SUM(b.value)
FROM
table b
WHERE
(b.date BETWEEN '2009-01-01' AND '2009-03-01') AND (a.id = b.id)
GROUP BY
b.reg);
</code></pre>
<p>Any idea?
PS: Sorry for mistakes.</p>
<p><strong>PS {edit 0002}</strong> Gonna copy original queries and data, so may it helps better.</p>
<p>$QUERY: </p>
<pre><code>SELECT
clienteid AS "CLIENTE",
SUM(saldo) AS "SUMA"
FROM
etl.creditos
WHERE
(titularidad_tipo LIKE 'TITULAR')
AND
(mes_datos BETWEEN '2008-11-01' AND '2009-10-01')
GROUP BY
nuc
ORDER BY
clienteid;
</code></pre>
<p>Got:</p>
<pre><code>+---------+-------------+
| CLIENTE | SUMA |
+---------+-------------+
| 64 | 1380690.74 |
| 187 | 1828468.71 |
| 187 | 2828102.80 |
| 325 | 26037422.21 |
| 389 | 875519.05 |
| 495 | 20084.93 |
| 495 | 109850.46 |
+---------+-------------+
</code></pre>
<p>Then, what I'm looking for is:</p>
<pre><code>+---------+-------------+
| CLIENTE | MAX |
+---------+-------------+
| 64 | 1380690.74 |
| 187 | 1828468.71 |
| 325 | 26037422.21 |
| 389 | 875519.05 |
| 495 | 109850.46 |
+---------+-------------+
</code></pre>
<p>But running: </p>
<pre><code>SELECT
clienteid AS "CLIENTE",
MAX(suma)
FROM
(SELECT clienteid, SUM(saldo) AS "suma" FROM etl.creditos
WHERE (mes_datos BETWEEN '2009-08-01' AND '2009-10-01') AND (titularidad_tipo LIKE 'TITULAR')
GROUP BY clienteid, nuc) AS sums
GROUP BY
clienteid
ORDER BY
clienteid;
</code></pre>
<p>Results as:</p>
<pre><code>+---------+-------------+
| CLIENTE | SUMA |
+---------+-------------+
| 64 | 336879.21 |
| 187 | 1232824.51 |
| 325 | 3816173.62 |
| 389 | 218423.83 |
| 495 | 34105.99 |
+---------+-------------+
</code></pre>
| 0 | 1,506 |
Gradle jacoco code coverage - Then publish/show in Jenkins
|
<p>I'm trying to setup code coverage for a Java application project.</p>
<p>Project name : NewApp</p>
<p>Project structure: </p>
<ul>
<li>src/java/** (source code)</li>
<li>src/java-test (unit tests - Jnuit)</li>
<li>test/it-test (integration test)</li>
<li>test/at-tests (acceptance tests)</li>
<li>tomcat/* (contain tomcat start/stop scripts)</li>
<li>xx/.. etc folders which are required for a usual application.</li>
</ul>
<p>Gradle version : 1.6</p>
<p>Environment : Linux</p>
<p>I have a running gradle build script that fetches application (NewApp) dependencies (i.e. service jars used by the app for build process) from a build artifact repository (artifactory/maven for ex), and builds the app.</p>
<p>Now at this point, I wanted to get code coverage using JaCoCo plugin for my NewApp application project.</p>
<p>I followed the documentation per Gradle/Jacoco but it doesn't seems to create any reports/... folder for jacoco etc where I can find what Jacoco coverage report did.</p>
<p>My questions:
1. For getting code coverage using Unit tests (Junit), I assume all I have to do is the following and it will NOT require me to start/stop the tomcat before running unit test (test task i.e. "gradle test") to get code coverage for/via using unit tests. Please advise/correct. The code (just for Gradle jacoco unit test part) - I'm using is:</p>
<pre><code>apply plugin: 'jacoco'
test {
include 'src/java-test/**'
}
jacocoTestReport {
group = "reporting"
description = "Generate Jacoco coverage reports after running tests."
reports {
xml.enabled true
html.enabled true
csv.enabled false
}
//classDirectories = fileTree(dir: 'build/classes/main', include: 'com/thc/**')
//sourceDirectories = fileTree(dir: 'scr/java', include: 'com/thc/**')
additionalSourceDirs = files(sourceSets.main.allJava.srcDirs)
}
</code></pre>
<p>and for Integration tests:</p>
<pre><code>task integrationTest(type: Test) {
include 'test/java/**'
}
</code></pre>
<p>As jacocoTestReport is depends upon test task(s), thus they will be called first and then finally jacocoTestReport will report what it found for the code coverage.</p>
<ol>
<li>For getting code coverage for integration tests, I assume I must start tomcat first (i.e. before running / calling test target for integration tests), then call "gradle integrationTest" or "gradle test" task and then stop tomcat -- to get the code coverage report. From other blog posts I also found that one should setup JAVA_OPTS variable to assign jacoco agent before tomcat starts.</li>
</ol>
<p>for ex: setting JAVA_OPTS variable like:</p>
<pre><code>export JACOCO="-Xms256m -Xmx512m -XX:MaxPermSize=1024m -javaagent:/production/jenkinsAKS/jobs/NewApp/workspace/jacoco-0.6.3.201306030806/lib/jacocoagent.jar=destfile=/production/jenkinsAKS/jobs/NewApp/workspace/jacoco/jacoco.exec,append=true,includes=*"
export JAVA_OPTS="$JAVA_OPTS $JACOCO"
</code></pre>
<ol>
<li><p>Being new to Gradle/groovy - I'm not sure what code should I write within build.gradle (build script) to get the above Integration/Unit tests working if it involves start/stop of tomcat. If someone can provide a sample script to do that, I'll try.</p></li>
<li><p>I'm not getting any code coverage right now, when I publish Jacoco code coverage in Jenkins (using Jenkins post build action for publishing Jacoco reports). Jenkins build dashboard shows 0% for code coverage (i.e. bars showing all red color, no green for actual code coverage).</p></li>
</ol>
<p>Need your advice to get some traction on this.</p>
| 0 | 1,170 |
Why does Eclipse Kepler SR1 error with : JAX-RS 2.0 requires Java 1.7 or newer
|
<p>I have a maven project that give the following two errors</p>
<p>JAX-RS (REST Web Services) 2.0 can not be installed : One or more constraints have not been satisfied.<br>
JAX-RS (REST Web Services) 2.0 requires Java 1.7 or newer.</p>
<p>I have JDK 1.6 installed (I cant change this)</p>
<p>The project facets does NOT have JAX-RS ticked.</p>
<p>The project facets has java 1.6 set.</p>
<p>The project facets has Dynamic Web Project 2.4 set.</p>
<p>I have following plugins</p>
<p>Sonar 3.2.0
MercurialEclipse 2.10
EclEmma 2.2.1</p>
<p>The pom.xml is just this...</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fake.company</groupId>
<artifactId>customerservice-war</artifactId>
<version>2.0.0-SNAPSHOT</version>
</project>
</code></pre>
<p>the web.xml is</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Customer Service</display-name>
</web-app>
</code></pre>
<p>Cleaning or "Update Maven Project" makes no difference.</p>
<p>Note: This is in eclipse-jee-kepler-SR1-win32-x86_64.
Note: Version eclipse-jee-kepler-win32-x86_64 does not give the error.</p>
<p>Note: New workspace does not change the error.</p>
<p>Note: I'm using JDK.1.6.0_43</p>
<p>The only error I can see related to this in the ".log" file is..</p>
<p>!ENTRY org.eclipse.osgi 2 1 2013-10-16 15:07:58.816
!MESSAGE NLS unused message: JaxrsProjectConfigurator_The_project_does_not_contain_required_facets in: org.eclipse.m2e.wtp.jaxrs.internal.messages</p>
<p>Adding the facet, wont let me apply it since it says I need Java 1.7</p>
<p>JSR339 (<a href="http://download.oracle.com/otn-pub/jcp/jaxrs-2_0-fr-spec/jsr339-jaxrs-2.0-final-spec.pdf?AuthParam=1381932823_3d235d93090d7ad1709113fead897636" rel="nofollow noreferrer">JSR339</a>) states "The API will make extensive use of annotations and will
require J2SE 6.0 or later"</p>
<p>Any ideas?</p>
| 0 | 1,084 |
Getting python3 to work in jenkins
|
<p>I'm having trouble getting python3 to work in jenkins. Jenkins is currently running in a docker container and i'm using <code>pipeline</code> scripts to facilitate CI/CD</p>
<p>This is my <code>Jenkinsfile</code> for a python repo</p>
<pre><code>pipeline {
agent any
tools {
nodejs 'nodejs'
python3 'python3'
}
environment{
}
stages {
stage('build'){
steps{
echo 'Preparing'
sh 'python3 --version'
sh 'pip3 install -U pytest'
script{
// pull git tag and add to a variable to set the build info - {tag#build_no}
GIT_TAG = sh(script: "git describe --abbrev=0 --tags", returnStdout: true).trim()
sh 'echo ${GIT_TAG}'
currentBuild.displayName = "${GIT_TAG}#${BUILD_NUMBER}"
}
}
}
stage('Checkout'){
steps {
echo 'Checking out code from repo'
checkout scm
}
}
stage('install'){
steps{
echo 'installing libraries'
sh 'pip3 install -r requirements.txt'
}
}
stage('test'){
steps {
echo 'running tests'
sh 'pytest'
}
post{
success{
bitbucketStatusNotify(buildState: 'SUCCESSFUL')
office365ConnectorSend message: "The build was successfull", status: "Success", webhookUrl: "${env.HOOK}"
}
failure{
bitbucketStatusNotify(buildState: 'FAILED')
office365ConnectorSend message: "The build has failed", status: "Failure", webhookUrl: "${env.HOOK}"
}
}
}
}
}
</code></pre>
<p>python3 isnt recognized by jenkins as it hasnt been installed yet. How do i get a python3 installation in my jenkins folder? I tried making the changes here - but for some reason - this doesnt seem to work (using the <code>shiningpanda</code> plugin)</p>
<p><a href="https://i.stack.imgur.com/utVmI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/utVmI.png" alt="enter image description here"></a></p>
<p>python2.7 actually does exist in <code>/usr/bin/python</code> but this seem to be unrecognized by Jenkins</p>
| 0 | 1,208 |
NodeJS - Error installing with NPM
|
<pre><code>Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.
C:\Windows\system32>npm install caress-server
npm http GET https://registry.npmjs.org/caress-server
npm http 304 https://registry.npmjs.org/caress-server
npm http GET https://registry.npmjs.org/jspack/0.0.1
npm http GET https://registry.npmjs.org/buffertools
npm http 304 https://registry.npmjs.org/jspack/0.0.1
npm http 304 https://registry.npmjs.org/buffertools
> buffertools@2.0.1 install C:\Windows\system32\node_modules\caress-server\node_
modules\buffertools
> node-gyp rebuild
C:\Windows\system32\node_modules\caress-server\node_modules\buffertools>node "G:
\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-
gyp.js" rebuild
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT
HON env variable.
gyp ERR! stack at failNoPython (G:\nodejs\node_modules\npm\node_modules\node
-gyp\lib\configure.js:101:14)
gyp ERR! stack at G:\nodejs\node_modules\npm\node_modules\node-gyp\lib\confi
gure.js:64:11
gyp ERR! stack at Object.oncomplete (fs.js:107:15)
gyp ERR! System Windows_NT 6.2.9200
gyp ERR! command "node" "G:\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\
bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Windows\system32\node_modules\caress-server\node_modules\buffert
ools
gyp ERR! node -v v0.10.25
gyp ERR! node-gyp -v v0.12.2
gyp ERR! not ok
npm ERR! buffertools@2.0.1 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the buffertools@2.0.1 install script.
npm ERR! This is most likely a problem with the buffertools package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get their info via:
npm ERR! npm owner ls buffertools
npm ERR! There is likely additional logging output above.
npm ERR! System Windows_NT 6.2.9200
npm ERR! command "G:\\nodejs\\\\node.exe" "G:\\nodejs\\node_modules\\npm\\bin\\n
pm-cli.js" "install" "caress-server"
npm ERR! cwd C:\Windows\system32
npm ERR! node -v v0.10.25
npm ERR! npm -v 1.3.24
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! C:\Windows\system32\npm-debug.log
npm ERR! not ok code 0
C:\Windows\system32>
</code></pre>
<p>I am installing a certain NodeJS script - <a href="http://caressjs.com/" rel="noreferrer">Caress</a>. But i am not unable to. I am using Windows 8.1, can anyone tell me what is the problem i am facing, and why is this installation not working. There seems to be a problem with the buffertools dependency, thats far as i can think. Dont know how maybe fix this?</p>
<p>If i download the build from github and place it in node-modules, nothing seems to work. when i try to start, using npm start, or during implementation either.</p>
<pre><code>G:\nodejs\node_modules\caress-server>npm install
G:\nodejs\node_modules\caress-server>npm start
> caress-server@0.1.1 start G:\nodejs\node_modules\caress-server
> node examples/server.js
info - socket.io started
module.js:340
throw err;
^
Error: Cannot find module './build/Release/buffertools.node'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (G:\nodejs\node_modules\caress-server\node_modules\buf
fertools\buffertools.js:16:19)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
npm ERR! caress-server@0.1.1 start: `node examples/server.js`
npm ERR! Exit status 8
npm ERR!
npm ERR! Failed at the caress-server@0.1.1 start script.
npm ERR! This is most likely a problem with the caress-server package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node examples/server.js
npm ERR! You can get their info via:
npm ERR! npm owner ls caress-server
npm ERR! There is likely additional logging output above.
npm ERR! System Windows_NT 6.2.9200
npm ERR! command "G:\\nodejs\\\\node.exe" "G:\\nodejs\\node_modules\\npm\\bin\\n
pm-cli.js" "start"
npm ERR! cwd G:\nodejs\node_modules\caress-server
npm ERR! node -v v0.10.25
npm ERR! npm -v 1.3.24
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! G:\nodejs\node_modules\caress-server\npm-debug.log
npm ERR! not ok code 0
G:\nodejs\node_modules\caress-server>
</code></pre>
| 0 | 1,836 |
IntegrityError: ERROR: null value in column "user_id" violates not-null constraint
|
<p>Using: postgres (PostgreSQL) 9.4.5</p>
<p>I just migrated a <code>sqlite3</code> db onto a <code>postgresql</code> db. For some reason since this migration, when I try to create a user, an error regarding the <code>user_id</code> (which is a primary key) is being raised. This was not an issue before with <code>sqlite3</code>. I have spent time looking through the docs and stack questions, but remain confused.</p>
<p>Inside <code>api.create_user()</code>:</p>
<pre><code>api.create_user(username ='lola ', firstname ='cats ', lastname ='lcatk', email='cags@falc.com')
</code></pre>
<p><em>sqlalchemy db</em> Model: </p>
<pre><code>class User(Base):
__tablename__ = 'users'
#user_id = Column(Integer, primary_key=True)
#changed to:
id = Column(Integer, primary_key=True)
username = Column(String(50))
firstname = Column(String(50))
lastname = Column(String(50))
email = Column(String(300))
password = Column(String(12))
institution = Column(String(50))
def __init__(self, username, firstname, lastname, email):
self.username = username
self.firstname = firstname
self.lastname = lastname
self.email = email
def __repr__(self):
return "<User(username ='%s', firstname ='%s', lastname ='%s', email='%s')>" % (self.username, self.firstname, self.lastname, self.email)
</code></pre>
<p><em>pyramid</em> views.py: </p>
<pre><code>@view_config(#code supplying the template and etc.)
def save_assessment_result(request):
with transaction.manager:
username = request.params['username']
firstname = request.params['firstname']
lastname = request.params['lastname']
email = request.params['email']
user = api.create_user(username, firstname, lastname, email)
#mode code to commit and etc.
transaction.commit()
return HTTPCreated()
</code></pre>
<p><em>postgres</em> Server.log:</p>
<pre><code>ERROR: null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (null, lola , cats , lcatk, cags@falc.com, null, null, 2015-10-19 23:02:21.560395).
STATEMENT: INSERT INTO users (username, firstname, lastname, email, password, institution, created_on) VALUES ('lola ', 'cats ', 'lcatk', 'cags@falc.com', NULL, NULL, '2015-10-19T23:02:21.560395'::timestamp) RETURNING users.user_id
</code></pre>
<p><em>Traceback</em>: </p>
<pre><code>015-10-19 19:02:21,563 ERROR [pyramid_debugtoolbar][Dummy-3] Exception at http://0.0.0.0:6432/save_assessment_result
File "/Users/ack/code/venv/NotssWEB/notssweb/views/default.py", line 61, in save_assessment_result
assessment = api.retrieve_assessment(assessment_id)
File "/usr/local/lib/python2.7/site-packages/notssdb/api/object.py", line 112, in retrieve_assessment
filter(Assessment.assessment_id == something_unique).one()
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2473, in one
ret = list(self)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2515, in __iter__
self.session._autoflush()
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 1292, in _autoflush
util.raise_from_cause(e)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 199, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 1282, in _autoflush
self.flush()
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 2004, in flush
self._flush(objects)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 2122, in _flush
transaction.rollback(_capture_exception=True)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 60, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 2086, in _flush
flush_context.execute()
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/unitofwork.py", line 373, in execute
rec.execute(self)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/unitofwork.py", line 532, in execute
uow
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/persistence.py", line 174, in save_obj
mapper, table, insert)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/persistence.py", line 781, in _emit_insert_statements
execute(statement, params)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 914, in execute
return meth(self, multiparams, params)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 323, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1010, in _execute_clauseelement
compiled_sql, distilled_params
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1146, in _execute_context
context)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1341, in _handle_dbapi_exception
exc_info
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 199, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1139, in _execute_context
context)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 450, in do_execute
cursor.execute(statement, parameters)
IntegrityError: (raised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurely) (psycopg2.IntegrityError) null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (null, lola , cats , lcatk, cags@falc.com, null, null, 2015-10-19 23:02:21.560395).
[SQL: 'INSERT INTO users (username, firstname, lastname, email, password, institution, created_on) VALUES (%(username)s, %(firstname)s, %(lastname)s, %(email)s, %(password)s, %(institution)s, %(created_on)s) RETURNING users.user_id'] [parameters: {'username': u'lola ', 'firstname': u'cats ', 'lastname': u'lcatk', 'institution': None, 'created_on': datetime.datetime(2015, 10, 19, 23, 2, 21, 560395), 'password': None, 'email': u'cags@falc.com'}]
2015-10-19 19:02:21,564 DEBUG [notssweb][Dummy-3] route matched for url http://0.0.0.0:6432/_debug_toolbar/exception?token=a30c0989db02aeff9cd2&tb=4459323984; route_name: 'debugtoolbar', path_info: u'/_debug_toolbar/exception', pattern: '/_debug_toolbar/*subpath', matchdict: {'subpath': (u'exception',)}, predicates: '
</code></pre>
| 0 | 2,565 |
Translate validation message in laravel 5
|
<p>I have a problem translating the laravel messages. I have created a folder called <code>es</code> inside <code>lang</code> folder and I have translated the messages from English to Spanish. Also I have set <code>'locale' => 'es'</code> on <code>config/app.php</code>. But English messages continues appearing.</p>
<p>I have used the default views for login provided by laravel, to generate it (and routes) I used the command (as says in <a href="https://laravel.com/docs/5.2/authentication" rel="noreferrer">https://laravel.com/docs/5.2/authentication</a>)</p>
<p><code>php artisan make:auth</code></p>
<p>I have changed the default routes by the following:</p>
<pre><code>Route::get('/login', 'UserController@getLogin');
Route::post('/login', 'UserController@postLogin');
</code></pre>
<p>And in UserController I have:</p>
<pre><code>public function getLogin(){
return view('auth.login');
}
public function postLogin(Request $request){
$input = $request->all();
if (Auth::attempt(['email' => $input["email"], 'password' => $input["password"]], true))
{
return redirect()->intended('/tables');
}
}
</code></pre>
<p>Here are two screenshots of the messages that appears in English</p>
<p><a href="http://i64.tinypic.com/if4k83.png" rel="noreferrer">http://i64.tinypic.com/if4k83.png</a></p>
<p><a href="http://i64.tinypic.com/51zhnp.png" rel="noreferrer">http://i64.tinypic.com/51zhnp.png</a></p>
<p>How can I transate these messages?</p>
<p>Thanks</p>
<p>Edit:</p>
<p><code>resources/lang/en/validation.php</code></p>
<pre><code><?php
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
'accepted' => 'The :attribute must be accepted.',
'active_url' => 'The :attribute is not a valid URL.',
'after' => 'The :attribute must be a date after :date.',
'alpha' => 'The :attribute may only contain letters.',
'alpha_dash' => 'The :attribute may only contain letters, numbers, and dashes.',
'alpha_num' => 'The :attribute may only contain letters and numbers.',
'array' => 'The :attribute must be an array.',
'before' => 'The :attribute must be a date before :date.',
'between' => [
'numeric' => 'The :attribute must be between :min and :max.',
'file' => 'The :attribute must be between :min and :max kilobytes.',
'string' => 'The :attribute must be between :min and :max characters.',
'array' => 'The :attribute must have between :min and :max items.',
],
'boolean' => 'The :attribute field must be true or false.',
'confirmed' => 'The :attribute confirmation does not match.',
'date' => 'The :attribute is not a valid date.',
'date_format' => 'The :attribute does not match the format :format.',
'different' => 'The :attribute and :other must be different.',
'digits' => 'The :attribute must be :digits digits.',
'digits_between' => 'The :attribute must be between :min and :max digits.',
'distinct' => 'The :attribute field has a duplicate value.',
'email' => 'The :attribute must be a valid email address.',
'exists' => 'The selected :attribute is invalid.',
'filled' => 'The :attribute field is required.',
'image' => 'The :attribute must be an image.',
'in' => 'The selected :attribute is invalid.',
'in_array' => 'The :attribute field does not exist in :other.',
'integer' => 'The :attribute must be an integer.',
'ip' => 'The :attribute must be a valid IP address.',
'json' => 'The :attribute must be a valid JSON string.',
'max' => [
'numeric' => 'The :attribute may not be greater than :max.',
'file' => 'The :attribute may not be greater than :max kilobytes.',
'string' => 'The :attribute may not be greater than :max characters.',
'array' => 'The :attribute may not have more than :max items.',
],
'mimes' => 'The :attribute must be a file of type: :values.',
'min' => [
'numeric' => 'The :attribute must be at least :min.',
'file' => 'The :attribute must be at least :min kilobytes.',
'string' => 'The :attribute must be at least :min characters.',
'array' => 'The :attribute must have at least :min items.',
],
'not_in' => 'The selected :attribute is invalid.',
'numeric' => 'The :attribute must be a number.',
'present' => 'The :attribute field must be present.',
'regex' => 'The :attribute format is invalid.',
'required' => 'The :attribute field is required.',
'required_if' => 'The :attribute field is required when :other is :value.',
'required_unless' => 'The :attribute field is required unless :other is in :values.',
'required_with' => 'The :attribute field is required when :values is present.',
'required_with_all' => 'The :attribute field is required when :values is present.',
'required_without' => 'The :attribute field is required when :values is not present.',
'required_without_all' => 'The :attribute field is required when none of :values are present.',
'same' => 'The :attribute and :other must match.',
'size' => [
'numeric' => 'The :attribute must be :size.',
'file' => 'The :attribute must be :size kilobytes.',
'string' => 'The :attribute must be :size characters.',
'array' => 'The :attribute must contain :size items.',
],
'string' => 'The :attribute must be a string.',
'timezone' => 'The :attribute must be a valid zone.',
'unique' => 'The :attribute has already been taken.',
'url' => 'The :attribute format is invalid.',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => [],
];
</code></pre>
<p><code>resources/lang/es/validation.php</code></p>
<pre><code><?php
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
'accepted' => ':attribute debe ser aceptado.',
'active_url' => 'El campo :attribute no es una URL válida.',
'after' => 'El campo :attribute debe ser una fecha posterior a :date.',
'alpha' => 'El campo :attribute debe contener solo letras.',
'alpha_dash' => 'El campo :attribute debe contener solo letras números y guiones.',
'alpha_num' => 'El campo :attribute debe contenterdebe contenter letras y números.',
'array' => 'El campo :attribute debe ser un array.',
'before' => 'El campo :attribute debe ser una fecha anterior a :date.',
'between' => [
'numeric' => 'El campo :attribute debe estar entre :min y :max.',
'file' => 'El campo :attribute ebe estar entre :min y :max kilobytes.',
'string' => 'El campo :attribute ebe estar entre :min y :max carácteres.',
'array' => 'El campo :attribute debe tener entre :min y :max elementos.',
],
'boolean' => 'El campo :attribute debe ser verdadero o falso.',
'confirmed' => 'El campo :attribute confirmación no coincide.',
'date' => 'El campo :attribute no es una fecha válida.',
'date_format' => 'El campo :attribute does not match the format :format.',
'different' => 'El campo :attribute y :other deben ser diferentes.',
'digits' => 'El campo :attribute debe ser de :digits dígitos.',
'digits_between' => 'El campo :attribute debe estar entre :min y :max dígitos.',
'distinct' => 'El campo :attribute tiene un valor duplicado.',
'email' => 'El campo :attribute debe ser una dirección de correo válida.',
'exists' => 'El campo :attribute no es válido.',
'filled' => 'El campo :attribute es obligatorio.',
'image' => 'El campo :attribute debe ser una imagen.',
'in' => 'El campo :attribute no es válido',
'in_array' => 'El campo :attribute no existe en :other.',
'integer' => 'El campo :attribute debe ser un entero.',
'ip' => 'El campo :attribute debe ser una dirección IP válida.',
'json' => 'El campo :attribute debe ser una cadena JSON válida.',
'max' => [
'numeric' => 'El campo :attribute no debe ser mayor que :max.',
'file' => 'El campo :attribute no debe ser mayor que :max kilobytes.',
'string' => 'El campo :attribute no debe ser mayor que :max carácteres.',
'array' => 'El campo :attribute no debe contener más de :max elementos.',
],
'mimes' => 'El campo :attribute debe ser un archivo del tipo: :values.',
'min' => [
'numeric' => 'El campo :attribute debe ser de al menos :min.',
'file' => 'El campo :attribute debe ser de al menos :min kilobytes.',
'string' => 'El campo :attribute debe ser de al menos :min carácteres.',
'array' => 'El campo :attribute debe tener al menos :min elementos.',
],
'not_in' => 'El campo selected :attribute no es válido.',
'numeric' => 'El campo :attribute debe ser un número.',
'present' => 'El campo :attribute debe estar presente.',
'regex' => 'El formatp del campo :attribute no es válido.',
'required' => 'El campo :attribute es obligatorio.',
'required_if' => 'El campo :attribute es obligatorio cuando :other es :value.',
'required_unless' => 'El campo :attribute es obligatorio a menos que :other esté en :values.',
'required_with' => 'El campo :attribute es obligatorio cuando :values está presente.',
'required_with_all' => 'El campo :attribute es obligatorio cuando :values está presente.',
'required_without' => 'El campo :attribute es obligatorio cuando :values no está presente.',
'required_without_all' => 'El campo :attribute es obligatorio cuando ninguno de :values está presente.',
'same' => 'Los campos :attribute y :other deben coincidir.',
'size' => [
'numeric' => 'El campo :attribute debe ser de :size.',
'file' => 'El campo :attribute debe ser de :size kilobytes.',
'string' => 'El campo :attribute debe ser de :size carácteres.',
'array' => 'El campo :attribute debe contenter :size elementos.',
],
'string' => 'El campo :attribute debe ser una cadena de texto.',
'timezone' => 'El campo :attribute debe ser una zona válida.',
'unique' => 'El campo :attribute debe ser único.',
'url' => 'El campo :attribute tiene un formato no válido.',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => [],
];
</code></pre>
<p>The begining of my <code>config/app.php</code></p>
<pre><code>return [
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services your application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG', true),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'es',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'es',
</code></pre>
| 0 | 6,701 |
Header, footer and large tables with iTextSharp
|
<p>I've added an header and a footer on my document by PdfPageEventHelper.</p>
<p>The document has several "large" tables populated at runtime.</p>
<p>I've tried to add those tables simply by "documen.Add(table)", but my header and my footer results overwritten.</p>
<p>I've already tried both methods to add the tables (WriteSelectedRows and document.Add(myPdfPtable).</p>
<p>Here is the code of the PageEventHelper:</p>
<pre><code>private class MyPageEventHandler : PdfPageEventHelper
{
public iTextSharp.text.Image ImageHeader { get; set; }
public iTextSharp.text.Image ImageFooter { get; set; }
public override void OnEndPage(PdfWriter writer, Document document)
{
var fontintestazione = FontFactory.GetFont("Verdana", 10, Font.BOLD, BaseColor.LIGHT_GRAY);
var fontRight = FontFactory.GetFont("Verdana", 8, Font.BOLD, BaseColor.WHITE);
var fontFooter = FontFactory.GetFont("Verdana", 6, Font.NORMAL, BaseColor.BLUE);
float cellHeight = document.TopMargin;
Rectangle page = document.PageSize;
PdfPTable head = new PdfPTable(3);
head.TotalWidth = page.Width;
PdfPCell c = new PdfPCell(ImageHeader, true);
c.HorizontalAlignment = Element.ALIGN_LEFT;
c.FixedHeight = cellHeight;
c.Border = PdfPCell.NO_BORDER;
head.AddCell(c);
c = new PdfPCell(new Phrase("somePhrase", fontintestazione));
c.Border = PdfPCell.NO_BORDER;
head.AddCell(c);
c = new PdfPCell(new Phrase("someTextBlah", fontRight));
c.Border = PdfPCell.NO_BORDER;
c.HorizontalAlignment = 1;
c.BackgroundColor = new BaseColor(70, 130, 180);
head.AddCell(c);
head.WriteSelectedRows(0, -1, 10, page.Height - cellHeight + head.TotalHeight -30, writer.DirectContent);
PdfPTable footer = new PdfPTable(2);
footer.TotalWidth = 316f;
float[] cfWidths = new float[] { 2f, 1f };
footer.SetWidths(cfWidths);
PdfPCell cf = new PdfPCell(ImageFooter, true);
cf.HorizontalAlignment = Element.ALIGN_RIGHT;
cf.FixedHeight = cellHeight;
cf.Border = PdfPCell.NO_BORDER;
footer.AddCell(cf);
cf = new PdfPCell(new Phrase("someEndingText", fontFooter));
cf.HorizontalAlignment = Element.ALIGN_LEFT;
cf.Border = PdfPCell.NO_BORDER;
footer.AddCell(cf);
footer.WriteSelectedRows(0, -1, 10, 50, writer.DirectContent);
}
</code></pre>
<p>On my page, i simply do:</p>
<pre><code>var document = new Document(PageSize.A4);
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, output);
iTextSharp.text.Image imageHeader = iTextSharp.text.Image.GetInstance(Server.MapPath("/images/header.ong"));
iTextSharp.text.Image imageFooter = iTextSharp.text.Image.GetInstance(Server.MapPath("/images/footer.png"));
MyPageEventHandler eve = new MyPageEventHandler
{
ImageHeader = imageHeader ,
ImageFooter = imageFooter
};
writer.PageEvent = eve;
document.Open();
//adding a table
PdfPTable cvTable = new PdfPtable(3);
cvTable.TotalWidth = document.PageSize.Width;
PdfPCell hCell = new PdfPCell(new Phrase("Jobs By User", aCustomFont));
cvTable.AddCell(hCell);
for(int i = 0; i < myTable.Records.Count; i++)
{
PdfPCell idCell = new PdfPCell(new Phrase(myTable.Records[i]._id, aFont));
cvTable.Add(idCell);
//same stuff for other fields of table
}
//first attempt.... failed:
document.Add(cvTable) //<- header and footer are overwritten by table
//second attempt..... failed too...
cvTable.WriteSelectedRows(0, -1, 10, myPoisition, writer.DirectContent);
//kind of fail...:
//the table is large and need more pages. It is trunked on the first page and overwrite
//the footer.
</code></pre>
| 0 | 1,822 |
Hello world with boost python and python 3.2
|
<p>So I'm trying to interface python 3.2 and c++ using boost python, and have come across many many issues. I've finally gotten it to compile using the 2.7 libraries and it works, but I can't seem to make it work with python 3.2. </p>
<p>Here's the c++ code</p>
<pre><code>#include <iostream>
using namespace std;
void say_hello(const char* name) {
cout << "Hello " << name << "!\n";
}
int main(){return 0;}
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(hello)
{
def("say_hello", say_hello);
}
</code></pre>
<p>If I compile it using the 2.7 libraries it works just fine, but when I use the 3.2 libraries I get tons of undefined references from libboost_python.so</p>
<p>Otherwise I wrote a little bit of python to make it work:</p>
<pre><code>from distutils.core import setup
from distutils.extension import Extension
setup(name="PackageName",
ext_modules=[
Extension("hello", ["testBoost.cpp"],
libraries = ["boost_python"])
])
</code></pre>
<p>and this will create an so using python 3.2 or 2.7 build, but when I open the python 3 interpreter and attempt to import the so it give me the error undefined symbol PyClass_Type from libboost_python.so again. Any ideas? Is boost python compatible with python 3.x?</p>
<p>If the information is useful, here is my attempted compile using 3.2:</p>
<pre><code> $ g++ testBoost.cpp -I/usr/include/python3.2 -I/usr/local/include/boost/python -lboost_python -lpython3.2mu
/tmp/ccdmU1Yu.o: In function `PyInit_hello':
testBoost.cpp:(.text+0xc2): undefined reference to `boost::python::detail::init_module(PyModuleDef&, void (*)())'
/usr/local/lib/libboost_python.so: undefined reference to `PyString_Size'
/usr/local/lib/libboost_python.so: undefined reference to `PyFile_FromString'
/usr/local/lib/libboost_python.so: undefined reference to `PyString_Type'
/usr/local/lib/libboost_python.so: undefined reference to `PyInt_Type'
/usr/local/lib/libboost_python.so: undefined reference to `PyString_FromString'
/usr/local/lib/libboost_python.so: undefined reference to `PyString_FromStringAndSize'
/usr/local/lib/libboost_python.so: undefined reference to `Py_InitModule4_64'
/usr/local/lib/libboost_python.so: undefined reference to `PyString_FromFormat'
/usr/local/lib/libboost_python.so: undefined reference to `PyNumber_Divide'
/usr/local/lib/libboost_python.so: undefined reference to `PyNumber_InPlaceDivide'
/usr/local/lib/libboost_python.so: undefined reference to `PyInt_AsLong'
/usr/local/lib/libboost_python.so: undefined reference to `PyString_InternFromString'
/usr/local/lib/libboost_python.so: undefined reference to `PyClass_Type'
/usr/local/lib/libboost_python.so: undefined reference to `PyString_AsString'
/usr/local/lib/libboost_python.so: undefined reference to `PyInt_FromLong'
/usr/local/lib/libboost_python.so: undefined reference to `PyFile_AsFile'
collect2: ld returned 1 exit status
</code></pre>
<p>And the error from the python 3 interpreter is</p>
<pre><code>File "<stdin>", line 1, in <module>
ImportError: /usr/local/lib/libboost_python.so.1.47.0: undefined symbol: PyClass_Type
</code></pre>
<p>Thanks for any help!</p>
| 0 | 1,179 |
javax.persistence.TransactionRequiredException: Executing an update/delete query
|
<p>I am using JPA2.0+hibernate3.2+Spring3.0.5+MySql5.5 to implement DAO function,but it doesn't work and just throw javax.persistence.TransactionRequiredException when i tried to persist entity to DB. Please see my coding and configuration.</p>
<p>1.Entity </p>
<pre><code>@Entity
@Table(name="booking_no")
public class BookingNo {
public BookingNo(){
};
@Id
@GeneratedValue
private Integer id;
@Column(unique=true,length=30)
private String prefix;
</code></pre>
<p>2.DAO</p>
<pre><code>@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT)
public Object generateBookingNo(String customer) throws Exception{
logger.debug("generateBookingNo() start,generate booking no by customer:"+customer);
if(customer == null || customer.trim().length() == 0){
logger.error("generateBookingNo(),customer is empty,return null");
return null;
}
EntityManager em = emf.createEntityManager();
try{
Query query = em.createQuery("select b from BookingNo b where b.prefix='"+customer+"'");
Object object =null;
try{
object = query.getSingleResult();
}catch(NoResultException e){
logger.info("generateBookingNo(),not find id for customer["+customer+"],will save a initial record");
BookingNo bkNo = new BookingNo();
bkNo.setPrefix(customer);
logger.debug("generateBookingNo(),the bookingNo is:"+bkNo);
em.persist(bkNo);
//em.flush();
Object object2 =null;
try{
object2 = em.createQuery("select b.id from BookingNo b where b.prefix='"+customer+"'").getSingleResult();
}catch(Exception e2){
logger.error("get error when query customer ["+customer+"]",e);
return null;
}
return customer+"-"+object2;
}
if(object == null || !(object instanceof BookingNo)){
logger.error("generateBookingNo(),return nothing but not catch NoResultException,return null");
return null;
}
BookingNo bkNo =(BookingNo) object;
Integer newId = bkNo.getId()+1;
//Query query2 = em.createQuery("update BookingNo b set b.id="+newId+" where b.prefix='"+customer+"'");
Query query2 = em.createNativeQuery("update booking_no b set b.id="+newId+" where b.prefix='"+customer+"'");
int res = query2.executeUpdate();
logger.debug("generateBookingNo(),the to be update bookingNo is:"+bkNo+",the update result is:"+res);
//em.flush();
return customer+"-"+newId;
}catch(Exception e){
logger.error("get error in generateBookingNo()",e);
return null;
}finally{
em.close();
emf.close();
}
</code></pre>
<p>3.Spring cfg file</p>
<pre><code> <tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="bookingEMF"/>
</bean>
<bean id="dataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost/booking"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
<property name="initialPoolSize" value="1"></property>
<property name="minPoolSize" value="1"></property>
<property name="maxPoolSize" value="20"></property>
<property name="maxIdleTime" value="60"></property>
<property name="acquireIncrement" value="5"></property>
<property name="idleConnectionTestPeriod" value="60"></property>
<property name="acquireRetryAttempts" value="20"></property>
<property name="breakAfterAcquireFailure" value="true"></property>
</bean>
<!-- Entity Manager Factory -->
<bean id="bookingEMF" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="booking"/>
<property name="dataSource" ref="dataSource1" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.transaction.flush_before_completion" value="true"/>
<entry key="hibernate.transaction.auto_close_session" value="true"/>
<entry key="hibernate.connection.release_mode" value="auto"/>
<entry key="hibernate.hbm2ddl.auto" value="update"/>
<entry key="format_sql" value="true"/>
<!-- <entry key="hibernate.transaction.manager_lookup_class" value="com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup"/> -->
</map>
</property>
</bean>
<!-- JPA Vendor,Implementation is hibernate -->
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="true"/>
<property name="generateDdl" value="false"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
<!-- DAO -->
<bean id="BookingDAO" class="com.chailie.booking.dao.impl.booking.BookingDAO" >
<property name="emf" ref="bookingEMF"/>
</bean>
</code></pre>
<p>when run junit test case as following</p>
<pre><code>@Test
public void testGenerateBookingNo(){
try {
BookingDAO dao = (BookingDAO) DAOFactory.getDAO("BookingDAO", DAOFactory.TYPE_APPLICATION);
dao.generateBookingNo("chailie");
//dao.generateBookingNo("chailie2");
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("get error",e);
}
}
</code></pre>
<p>It will occur javax.persistence.TransactionRequiredException and i don't know what happeded,does anybody could help to solve this?i really appreciate it
By the way,please see my log</p>
<pre><code>23:15:46.817 [main] DEBUG org.hibernate.hql.ast.ErrorCounter - throwQueryException() : no errors
23:15:46.837 [main] DEBUG o.h.hql.ast.QueryTranslatorImpl - HQL: select b from com.chailie.booking.model.booking.BookingNo b where b.prefix='chailie'
23:15:46.837 [main] DEBUG o.h.hql.ast.QueryTranslatorImpl - SQL: select bookingno0_.id as id0_, bookingno0_.prefix as prefix0_ from booking_no bookingno0_ where bookingno0_.prefix='chailie'
23:15:46.837 [main] DEBUG org.hibernate.hql.ast.ErrorCounter - throwQueryException() : no errors
23:15:46.856 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
23:15:46.856 [main] DEBUG org.hibernate.jdbc.ConnectionManager - opening JDBC connection
23:15:46.891 [main] DEBUG org.hibernate.SQL - select bookingno0_.id as id0_, bookingno0_.prefix as prefix0_ from booking_no bookingno0_ where bookingno0_.prefix='chailie' limit ?
Hibernate: select bookingno0_.id as id0_, bookingno0_.prefix as prefix0_ from booking_no bookingno0_ where bookingno0_.prefix='chailie' limit ?
23:15:46.922 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open ResultSet (open ResultSets: 0, globally: 0)
23:15:46.926 [main] DEBUG org.hibernate.loader.Loader - result row: EntityKey[com.chailie.booking.model.booking.BookingNo#8]
23:15:46.935 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close ResultSet (open ResultSets: 1, globally: 1)
23:15:46.936 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
23:15:46.936 [main] DEBUG org.hibernate.jdbc.ConnectionManager - aggressively releasing JDBC connection
23:15:46.936 [main] DEBUG org.hibernate.jdbc.ConnectionManager - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
23:15:46.939 [main] DEBUG org.hibernate.engine.TwoPhaseLoad - resolving associations for [com.chailie.booking.model.booking.BookingNo#8]
23:15:46.941 [main] DEBUG org.hibernate.engine.TwoPhaseLoad - done materializing entity [com.chailie.booking.model.booking.BookingNo#8]
23:15:46.942 [main] DEBUG o.h.e.StatefulPersistenceContext - initializing non-lazy collections
23:15:46.942 [main] DEBUG org.hibernate.jdbc.ConnectionManager - aggressively releasing JDBC connection
23:15:46.944 [main] DEBUG o.h.ejb.AbstractEntityManagerImpl - mark transaction for rollback
23:15:46.954 [main] ERROR c.c.b.d.booking.impl.BookingDAOTest - get error in generateBookingNo()
javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.hibernate.ejb.QueryImpl.executeUpdate(QueryImpl.java:48) [hibernate-entitymanager-3.4.0.GA.jar:3.4.0.GA]
at com.chailie.booking.dao.impl.booking.BookingDAO.generateBookingNo(BookingDAO.java:104) [classes/:na]
at com.chailie.booking.dao.impl.booking.BookingDAO$$FastClassByCGLIB$$2898182b.invoke(<generated>) [cglib-2.2.jar:na]
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191) [cglib-2.2.jar:na]
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688) [spring-aop-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) [spring-aop-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) [spring-tx-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) [spring-aop-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621) [spring-aop-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at com.chailie.booking.dao.impl.booking.BookingDAO$$EnhancerByCGLIB$$58d6a935.generateBookingNo(<generated>) [cglib-2.2.jar:na]
at com.chailie.booking.dao.booking.impl.BookingDAOTest.testGenerateBookingNo(BookingDAOTest.java:42) [test-classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [na:1.7.0_15]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [na:1.7.0_15]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [na:1.7.0_15]
at java.lang.reflect.Method.invoke(Unknown Source) [na:1.7.0_15]
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) [junit-4.7.jar:na]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) [junit-4.7.jar:na]
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) [junit-4.7.jar:na]
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) [junit-4.7.jar:na]
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76) [junit-4.7.jar:na]
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) [junit-4.7.jar:na]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) [junit-4.7.jar:na]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) [junit-4.7.jar:na]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) [junit-4.7.jar:na]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) [junit-4.7.jar:na]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) [junit-4.7.jar:na]
at org.junit.runners.ParentRunner.run(ParentRunner.java:236) [junit-4.7.jar:na]
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53) [surefire-junit4-2.10.jar:2.10]
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123) [surefire-junit4-2.10.jar:2.10]
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104) [surefire-junit4-2.10.jar:2.10]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [na:1.7.0_15]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [na:1.7.0_15]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [na:1.7.0_15]
at java.lang.reflect.Method.invoke(Unknown Source) [na:1.7.0_15]
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164) [surefire-api-2.10.jar:2.10]
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110) [surefire-booter-2.10.jar:2.10]
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175) [surefire-booter-2.10.jar:2.10]
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107) [surefire-booter-2.10.jar:2.10]
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68) [surefire-booter-2.10.jar:2.10]
23:15:46.958 [main] INFO o.hibernate.impl.SessionFactoryImpl - closing
23:15:46.960 [main] DEBUG o.h.transaction.JDBCTransaction - commit
23:15:46.962 [main] DEBUG o.h.transaction.JDBCTransaction - re-enabling autocommit
23:15:46.962 [main] DEBUG o.h.transaction.JDBCTransaction - committed JDBC Connection
23:15:46.962 [main] DEBUG org.hibernate.jdbc.ConnectionManager - aggressively releasing JDBC connection
23:15:46.963 [main] DEBUG org.hibernate.jdbc.ConnectionManager - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
</code></pre>
| 0 | 6,469 |
Using JavaFX with Intellij IDEA
|
<p>I've followed a tutorial precisely and I can't seem to get it to work. The tutorial is under <code>JavaFX and Intellij</code> <code>Non-modular from IDE</code> sections: <a href="https://openjfx.io/openjfx-docs/#install-java" rel="noreferrer">https://openjfx.io/openjfx-docs/#install-java</a></p>
<p>Here is the error message I receive when trying to run the default Intellij Idea JavaFX project:</p>
<pre><code>"C:\Program Files\Java\jdk-11.0.1\bin\java.exe" --module-path %PATH_TO_FX% --add-modules=javafx.controls,javafx.fxml --add-modules javafx.base,javafx.graphics --add-reads javafx.base=ALL-UNNAMED --add-reads javafx.graphics=ALL-UNNAMED "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2018.3\lib\idea_rt.jar=53491:C:\Program Files\JetBrains\IntelliJ IDEA 2018.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Users\jonat\IdeaProjects\Tawe-Lib FX\out\production\Tawe-Lib FX;C:\Program Files\Java\javafx-sdk-11.0.1\lib\src.zip;C:\Program Files\Java\javafx-sdk-11.0.1\lib\javafx-swt.jar;C:\Program Files\Java\javafx-sdk-11.0.1\lib\javafx.web.jar;C:\Program Files\Java\javafx-sdk-11.0.1\lib\javafx.base.jar;C:\Program Files\Java\javafx-sdk-11.0.1\lib\javafx.fxml.jar;C:\Program Files\Java\javafx-sdk-11.0.1\lib\javafx.media.jar;C:\Program Files\Java\javafx-sdk-11.0.1\lib\javafx.swing.jar;C:\Program Files\Java\javafx-sdk-11.0.1\lib\javafx.controls.jar;C:\Program Files\Java\javafx-sdk-11.0.1\lib\javafx.graphics.jar" sample.Main
Error occurred during initialization of boot layer
java.lang.module.FindException: Module javafx.base not found
Process finished with exit code 1
</code></pre>
<p>This makes little sense to me as I can see <code>javafx.base</code> under <code>lib</code> on the sidebar:
<a href="https://i.stack.imgur.com/7ifU3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7ifU3.png" alt="enter image description here"></a></p>
<p>The path leading to <code>jdk-11.0.1</code> and <code>javafx-sdk-11.0.1</code>:</p>
<blockquote>
<p>C:\Program Files\Java</p>
</blockquote>
<p>Java is installed:</p>
<pre><code>C:\Users\jonat>java --version
openjdk 11.0.1 2018-10-16
OpenJDK Runtime Environment 18.9 (build 11.0.1+13)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.1+13, mixed mode)
</code></pre>
<p><code>JAVA_HOME</code> variable (mentioned in guide) is set:</p>
<pre><code>C:\Users\jonat>echo %JAVA_HOME%
C:\Program Files\Java\jdk-11.0.1
</code></pre>
<p><code>PATH_TO_FX</code> variable is set:</p>
<pre><code>C:\Users\jonat>echo %PATH_TO_FX%
C:\Program Files\Java\javafx-sdk-11.0.1\lib
</code></pre>
<p>I have really no idea where to go from here. I have followed the tutorial precisely, and it does not work. Any help would be greatly appreciated and if you require more info please just drop a comment about it.</p>
| 0 | 1,146 |
Connecting to a SQL server using ADODB from a C# dll
|
<p>I am writing a custom <code>Connection</code> class in C# for Excel to be able to connect to a SQL Server.
When I use <code>SQLConnection</code> from <code>System.Data.SqlClient</code> library I am able to establish a connection. The working code I've got:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
namespace Test
{
[InterfaceType(ComInterfaceType.InterfaceIsDual),
Guid("6E8B9F68-FB6C-422F-9619-3BA6D5C24E84")]
public interface IConnection
{
bool Status { get; }
bool Open();
}
[ClassInterface(ClassInterfaceType.None)]
[Guid("B280EAA4-CE11-43AD-BACD-723783BB3CF2")]
[ProgId("Test.Connection")]
public class Connection : IConnection
{
private bool status;
private SqlConnection conn;
private string connString = "Data Source=[server]; Initial Catalog=[initial]; User ID=[username]; Password=[password]";
public Connection()
{
}
public bool Status
{
get
{
return status;
}
}
public bool Open()
{
try
{
conn = new SqlConnection(connString);
conn.Open();
status = true;
return true;
}
catch(Exception e)
{
e.ToString();
return false;
}
}
}
}
</code></pre>
<p>And after adding the reference to Excel I am able to test the connection using a simple VBA code like this:</p>
<pre><code>Sub TestConnection()
Dim conn As Test.Connection
Set conn = New Test.Connection
Debug.Print conn.Status
conn.Open
Debug.Print conn.Status
End Sub
</code></pre>
<p>It outputs:</p>
<blockquote>
<p>False <br>
True <br></p>
</blockquote>
<p>So everything is fine. Now I would like to create custom <code>Recordset</code> class in my C# library so I decided to use an <code>ADODB</code> library and its <code>RecordSet</code>instead of <code>SqlDataReader</code> as I am planning to work with some big chunks of data. So, I have modified my code to this:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
namespace Test
{
[InterfaceType(ComInterfaceType.InterfaceIsDual),
Guid("6E8B9F68-FB6C-422F-9619-3BA6D5C24E84")]
public interface IConnection
{
bool Status { get; }
bool Open();
}
[ClassInterface(ClassInterfaceType.None)]
[Guid("B280EAA4-CE11-43AD-BACD-723783BB3CF2")]
[ProgId("Test.Connection")]
public class Connection : IConnection
{
private bool status;
private ADODB.Connection conn = new ADODB.Connection();
private string connString = "Data Source=[server]; Initial Catalog=[initial]; User ID=[username]; Password=[password]";
public Connection()
{
}
public bool Status
{
get
{
return status;
}
}
public bool Open()
{
try
{
conn.ConnectionString = connString;
conn.Open();
// conn.Open(connString, ["username"], ["password"], 0)
// what else can I try? is this where it actually fails?
status = true;
return true;
}
catch (Exception e)
{
e.ToString();
return false;
}
}
}
}
</code></pre>
<p>I also have added references to <code>Microsoft ActiveX Data Objects 6.1 Library</code>.</p>
<p>Now, when I am executing the VBA code it outputs:</p>
<blockquote>
<p>0 <br>
0 <br></p>
</blockquote>
<p>But I was expecting <code>0</code> and <code>1</code>. It seems to me like I am not properly connecting to the server <em>( credentials are the same i have just removed actual data from this code )</em>.
<br></p>
<p>I have tried to use different variations of the connection string, however it always returns <code>0</code> and <code>0</code>. I have tried creating a new project with new GUIDs and also tried renaming the projects, classes, etc. nothing has worked. I am suspecting its the establishment of the connection but I am unsure how to debug a dll.</p>
<p>I have used <a href="http://support.microsoft.com/kb/308611" rel="nofollow">link1</a>, <a href="http://msdn.microsoft.com/en-us/library/ms807027.aspx" rel="nofollow">link2</a>, <a href="http://msdn.microsoft.com/en-us/library/ms130978.aspx" rel="nofollow">link3</a>, <a href="http://homeofcox-cs.blogspot.co.uk/2009/07/use-adodbrecordset-in-c.html" rel="nofollow">link4</a> for reference<br></p>
<p><strong>Update:</strong><br>
I have wrote the exception to the file as TheKingDave suggested. This is the exception error message</p>
<blockquote>
<p>System.Runtime.InteropServices.COMException (0x80004005):
[Microsoft][ODBC Driver Manager] Data source name not found and no
default driver specified at ADODB._Connection.Open(String
ConnectionString, String UserID, String Password, Int32 Options) at
TestADODB.Connection.Open() in c:\Users\administrator\Documents\Visual
Studio 2012\Projects\Test\Test\Connection.cs:line 49</p>
</blockquote>
| 0 | 2,287 |
How to find the "last page" in a view pager. Or the total 'number' of views. Android Development
|
<p>Thank you for your help in advanced. And sorry if this is a very silly question, but I cannot find it elsewhere.
What I want, is basically, to determine the total amount of pages I have in my ViewPager when it is all set up, like in my code. I have tried (on a later version) adding the "size variable" to f as it's argument (see, FirstFragment). It's not a known number, as the user input's the number of forms (view's) I will create, and passes it to FirstFragment as an intent. So I have tried : </p>
<pre><code>Fragment f = new UserFragment();
Bundle bundl = new Bundle();
bundl.putInt("pagenumbers", size);
f.setArguments(bundl);
lf.add(f);
</code></pre>
<p>Inside FirstFragment. But when UserFragment extracts its arguments under "pagenumbers" it is returning 0.
I then tried to gain access to the getCount() method that lives inside FragmentAdapter, however, I'm not sure how to go about this, given that I'm inside UserFragment when I need it.</p>
<p>What I'm trying to do maybe to help clarify, is I'm extracting "current page info" which I now have working thanks to an earlier post of mine and those whom helped. Now I want to see if "currentpage == size (//which is number of pages. Total views in the viewpager)". So in the onClick method you can see in UserFragment, if it's the last page, and the user hits the button to go to the next page. I want it to jump to another activity, where it manipulates all the SparseArray data that was collected from all the forms. (Which I need help on how to put this SparseArray data into an intent, I will probably make a new question with this ... as it's not very related). So if you could either assist me in getting my current attempts to work (how to do it properly) or just suggest an entirely new method I'm happy. As long as I can get it working!</p>
<p>Thank you very much for all your assistance, in advanced. Please help! </p>
<p><strong>My UserFragment.java</strong>:</p>
<pre><code> package com.example.thinice;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class UserFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layout_avgcalcform,
container, false);
final EditText markc = (EditText)rootView.findViewById(R.id.editTextASSMARK);
final EditText marktotc = (EditText)rootView.findViewById(R.id.editTextASSTOT);
final EditText assvalc = (EditText)rootView.findViewById(R.id.editTextASSWORTH);
int currentviewnum = ((FirstFragment) getActivity()).getPager().getCurrentItem();
String pagenum = Integer.toString(currentviewnum);
TextView tv = (TextView) rootView.findViewById(R.id.avg_testtv);
tv.setText(pagenum);
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener( new View.OnClickListener(){
public void onClick(View v){
int currentviewnum = ((FirstFragment) getActivity()).getPager().getCurrentItem();
((FirstFragment) getActivity()).saveData(new Question(markc.getText().toString(),marktotc.getText().toString(),assvalc.getText().toString()));
((FirstFragment) getActivity()).getPager().setCurrentItem(currentviewnum+1);
}
});
return rootView;
}
}
</code></pre>
<p>If you need to see any more of my code, please let me know. But this is really annoying me.
So if anybody out there could help me, it would be fantastic!
Thank you very much in advanced.</p>
<p><strong>FragmentAdapter.java</strong> : </p>
<pre><code> package com.example.thinice;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;
public class FragmentAdapter extends FragmentPagerAdapter{
private List<Fragment> fragments;
public FragmentAdapter(FragmentManager fragmentManager, ArrayList<Fragment> fragments) {
super(fragmentManager);
this.fragments = fragments;
}
@Override
public Fragment getItem(int position) {
//Bundle args = new Bundle();
//args.putInt("page_position", position+1);
//((Fragment) fragments).setArguments(args);
return this.fragments.get(position);
}
@Override
public void destroyItem (ViewGroup container, int position, Object object)
{
super.destroyItem(container, position, object);
}
@Override
public int getCount() {
return this.fragments.size();
}
}
</code></pre>
<p><strong>FirstFragment.java (this is my activity)</strong> : </p>
<pre><code> package com.example.thinice;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.SparseArray;
import android.widget.Button;
public class FirstFragment extends FragmentActivity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_viewpager);
// Check whether the activity is using the layout version with
// the fragment_container FrameLayout. If so, we must add the first fragment
int size = getIntent().getExtras().getInt("numass1");
ViewPager vp = (ViewPager) findViewById(R.id.viewPager);
if (savedInstanceState != null) {
return;
}
ArrayList<Fragment> lf = new ArrayList<Fragment>();
for(int count=0; count<size; count ++){
Fragment f = new UserFragment();
lf.add(f);
}
FragmentAdapter hello = new FragmentAdapter(getSupportFragmentManager() , lf);
vp.setAdapter(hello);
// vp.setOffscreenPageLimit(size);
}
SparseArray<Question> questions = new SparseArray<Question>();
public void saveData(Question quest){
ViewPager vp = (ViewPager) findViewById(R.id.viewPager);
questions.put(vp.getCurrentItem(), quest);
}
public ViewPager getPager() {
ViewPager vp = (ViewPager) findViewById(R.id.viewPager);
return vp;
}
}
</code></pre>
<p><strong>EDIT:LOGCAT FILE FOR SUGGESTED SOLUTION</strong> :</p>
<pre><code>07-06 20:51:50.241: D/AndroidRuntime(8151): Shutting down VM
07-06 20:51:50.241: W/dalvikvm(8151): threadid=1: thread exiting with uncaught exception (group=0x415a4ba8)
07-06 20:51:50.251: E/AndroidRuntime(8151): FATAL EXCEPTION: main
07-06 20:51:50.251: E/AndroidRuntime(8151): Process: com.example.thinice, PID: 8151
07-06 20:51:50.251: E/AndroidRuntime(8151): java.lang.NullPointerException
07-06 20:51:50.251: E/AndroidRuntime(8151): at com.example.thinice.UserFragment.onCreateView(UserFragment.java:34)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.View.measure(View.java:16497)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.View.measure(View.java:16497)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
07-06 20:51:50.251: E/AndroidRuntime(8151): at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.View.measure(View.java:16497)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
07-06 20:51:50.251: E/AndroidRuntime(8151): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.View.measure(View.java:16497)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1912)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1109)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1291)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.Choreographer.doCallbacks(Choreographer.java:574)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.Choreographer.doFrame(Choreographer.java:544)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.os.Handler.handleCallback(Handler.java:733)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.os.Handler.dispatchMessage(Handler.java:95)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.os.Looper.loop(Looper.java:136)
07-06 20:51:50.251: E/AndroidRuntime(8151): at android.app.ActivityThread.main(ActivityThread.java:5001)
07-06 20:51:50.251: E/AndroidRuntime(8151): at java.lang.reflect.Method.invokeNative(Native Method)
07-06 20:51:50.251: E/AndroidRuntime(8151): at java.lang.reflect.Method.invoke(Method.java:515)
07-06 20:51:50.251: E/AndroidRuntime(8151): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
07-06 20:51:50.251: E/AndroidRuntime(8151): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
07-06 20:51:50.251: E/AndroidRuntime(8151): at dalvik.system.NativeStart.main(Native Method)
</code></pre>
| 0 | 4,623 |
vue.js: how to update state with object?
|
<p>I am a newcomer to vue.js, but I have some experience with React from before.</p>
<p>I have read the vue guidelines and I am trying to understand vue through the concepts from React.</p>
<p>I assume that the vue <code>data</code> is similar to the React <code>state</code>, since when it updates the app it will render the page again.</p>
<p>So I would like to do something like ... (the code is in React) </p>
<pre><code>this.setState(Object.assign({}, this.state, { key1: 'value1', key2 : 'value2'}))
</code></pre>
<p>But as far as I know, in vue:</p>
<pre><code>this.key1 = 'value1';
this.key2 = 'value2';
</code></pre>
<p>Is that correct? I guess vue will render twice since it is 2 statements.
How could I set multi values at once?</p>
<p>I have already tried ...</p>
<pre><code>// not working
this.$set(Object.assign({}, thisRef.data, { key1: 'value1', key2: 'value2' }))
// not working
this.data = { key1 : 'value1', key2: 'value2' };
</code></pre>
<p>In the second one, data has changed - I have printed value with <code>console.log(this)</code>- , but it does not render again.</p>
<p>FYI, the full code from the vue template is here. Code review and correction will be very welcomed.</p>
<pre><code><script>
export default {
layout: 'reactQuickly'
, data: function(){
return {
time: null
, init: null
}
}
, methods: {
startTimer: function(time){
clearInterval(this.init);
let thisRef = this;
let interval = setInterval(
function(){
console.log('2: Inside of interval', time)
let timeLeft = thisRef.time - 1;
if(timeLeft <= 0) clearInterval(interval);
thisRef.time = timeLeft;
// thisRef.$set(Object.assign({}, thisRef.data, { time: timeLeft }))
console.log('thisRef', thisRef, this);}
, 1000);
console.log('1: After interval');
// this.data = { time : time, init: interval };
this.time = time;
this.init = interval;
console.log('this.data', this.data);
// this.$set(Object.assign({}, this.data, { time : time, init: interval}));
}
}
}
</script>
</code></pre>
<p>============ Edition ===========</p>
<p>react <code>this.state</code> and vue <code>this.data</code> is not same, right?
To me, main confusion starts from that point.</p>
<p>In vue</p>
<pre><code>export default {
data : function() {
return {
foo : 'bar'
}
}
}
</code></pre>
<p>and </p>
<p>In react</p>
<pre><code>constructor() {
super()
this.state = {
foo : 'bar'
}
}
</code></pre>
<p>are completely different concept, right?</p>
| 0 | 1,300 |
Django - how to save my hashed password
|
<p>I'm trying to save my hashed password in my database, but It keeps saving my plaintext password</p>
<p><strong>Models:</strong></p>
<pre><code>class StudentRegistration(models.Model):
email = models.EmailField(max_length=50)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
password = models.CharField(max_length=100, default="", null=False)
prom_code = models.CharField(max_length=8, default="", null=False)
gender = (
("M","Male"),
("F","Female"),
)
gender = models.CharField(max_length=1, choices=gender, default="M", null=False)
prom_name = models.CharField(max_length=20, default="N/A")
prom_year = models.IntegerField(max_length=4, default=1900)
school = models.CharField(max_length=50, default="N/A")
def save(self):
try:
Myobj = Space.objects.get(prom_code = self.prom_code)
self.prom_name = Myobj.prom_name
self.prom_year = Myobj.prom_year
self.school = Myobj.school_name
super(StudentRegistration, self).save()
except Space.DoesNotExist:
print("Error")
</code></pre>
<p><strong>Views:</strong></p>
<pre><code>def register_user(request):
args = {}
if request.method == 'POST':
form = MyRegistrationForm(request.POST) # create form object
if form.is_valid():
clearPassNoHash = form.cleaned_data['password']
form.password = make_password(clearPassNoHash, None, 'md5')
form.save()
form = MyRegistrationForm()
print ('se salvo')
else:
print ('Error en el form')
else:
form = MyRegistrationForm()
args['form'] = form #MyRegistrationForm()
return render(request, 'register/register.html', args)
</code></pre>
<p>I've printed the hashed result so I know it is hashing but not saving that. </p>
<p>Am I using the make_password wrong? or is there any better way to protect my passwords?</p>
<p>--------------------------<strong>UPDATE:(The Solution)</strong>----------------------------</p>
<p>Remember In settings.py:</p>
<pre><code>#The Hasher you are using
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
</code></pre>
<p>Models.py:</p>
<pre><code>#Import and add the AbstractBaseUser in your model
class StudentRegistration(AbstractBaseUser, models.Model):
</code></pre>
<p>Views.py: </p>
<pre><code>if form.is_valid():
user = form.save(commit=False)
clearPassNoHash = form.cleaned_data['password']
varhash = make_password(clearPassNoHash, None, 'md5')
user.set_password(varhash)
user.save()
</code></pre>
| 0 | 1,077 |
Two simple IBM MQ client tests write to MQ queue - why does one work, but, NOT the other?
|
<p>I'm running two(2) client tests.</p>
<p>Presumably they should both work. But, one does not, and I do not know why.</p>
<p><strong><em>(1) This one works...</em></strong></p>
<pre><code>package aaa.bbb.ccc;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.constants.CMQC;
import com.ibm.mq.constants.MQConstants;
public class MQCheck {
public static void main(String args[]) {
try {
int openOptions = CMQC.MQOO_INQUIRE | CMQC.MQOO_INPUT_AS_Q_DEF | MQConstants.MQOO_OUTPUT;
MQEnvironment.hostname = "localhost";
MQEnvironment.port = 1414;
MQEnvironment.channel = "DEV.APP.SVRCONN";
MQEnvironment.properties.put(CMQC.USER_ID_PROPERTY, "admin");
MQEnvironment.properties.put(CMQC.PASSWORD_PROPERTY, "passw0rd");
MQEnvironment.properties.put(CMQC.TRANSPORT_PROPERTY, CMQC.TRANSPORT_MQSERIES);
MQQueueManager qMgr;
qMgr = new MQQueueManager("QM1");
MQQueue destQueue = qMgr.accessQueue("mylocalqueue", openOptions);
MQMessage hello_world = new MQMessage();
hello_world.writeUTF("Blah...blah...bleah...test message no.1...!");
MQPutMessageOptions pmo = new MQPutMessageOptions();
destQueue.put(hello_world, pmo);
destQueue.close();
qMgr.disconnect();
System.out.println("------------------------success...");
} catch (Exception e) {
System.out.println("Exception: " + e);
e.printStackTrace();
}
}
}
</code></pre>
<p><strong><em>(2) This one does NOT work...</em></strong> </p>
<pre><code>package aaa.bbb.ccc;
import com.ibm.mq.jms.MQQueueConnection;
import com.ibm.mq.jms.MQQueueConnectionFactory;
import com.ibm.mq.jms.MQSession;
import com.ibm.msg.client.wmq.WMQConstants;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
public class MQCheck3 {
public static void main(String args[]) {
Connection qconn = null;
QueueSession qsess = null;
MQSession mqsess;
Queue queue = null;
try {
MQQueueConnectionFactory connectionFactory = new MQQueueConnectionFactory();
connectionFactory.setHostName("localhost");
connectionFactory.setChannel("DEV.APP.SVRCONN");//communications link
connectionFactory.setPort(1414);
connectionFactory.setQueueManager("QM1");
connectionFactory.setTransportType(WMQConstants.WMQ_CM_CLIENT);
connectionFactory.setBooleanProperty(WMQConstants.CAPABILITY_USERNAME_PASSWORD, true);
connectionFactory.setStringProperty(WMQConstants.USERID, "admin");
connectionFactory.setStringProperty(WMQConstants.PASSWORD, "passw0rd");
qconn = (MQQueueConnection) connectionFactory.createConnection();
qconn = connectionFactory.createQueueConnection();
qconn.start();
mqsess = (MQSession) qconn.createSession(false, Session.AUTO_ACKNOWLEDGE); //.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
queue = mqsess.createQueue("mylocalqueue");
TextMessage textMessage = mqsess.createTextMessage("Bleah...bleah...blech...test message no.2...!");
MessageProducer mc = mqsess.createProducer(queue);
mc.send(textMessage, 0, 0, 0);
System.out.println("------------------------success...");
} catch (JMSException e) {
System.out.println("Exception: " + e);
e.printStackTrace();
} finally {
try {
qsess.close();
qconn.close();
} catch (JMSException e) {
System.err.print(e);
}
}
}
}
</code></pre>
<p>NOTE:
Running the code in (2) gets the following exception...</p>
<pre><code>Exception: com.ibm.msg.client.jms.DetailedJMSSecurityException: JMSWMQ2013: The security authentication was not valid that was supplied for QueueManager 'QM1' with connection mode 'Client' and host name 'localhost(1414)'.
Please check if the supplied username and password are correct on the QueueManager to which you are connecting.
com.ibm.msg.client.jms.DetailedJMSSecurityException: JMSWMQ2013: The security authentication was not valid that was supplied for QueueManager 'QM1' with connection mode 'Client' and host name 'localhost(1414)'.
Please check if the supplied username and password are correct on the QueueManager to which you are connecting.
at com.ibm.msg.client.wmq.common.internal.Reason.reasonToException(Reason.java:514)
at com.ibm.msg.client.wmq.common.internal.Reason.createException(Reason.java:214)
at com.ibm.msg.client.wmq.internal.WMQConnection.<init>(WMQConnection.java:408)
at com.ibm.msg.client.wmq.factories.WMQConnectionFactory.createV7ProviderConnection(WMQConnectionFactory.java:6398)
at com.ibm.msg.client.wmq.factories.WMQConnectionFactory.createProviderConnection(WMQConnectionFactory.java:5740)
at com.ibm.msg.client.jms.admin.JmsConnectionFactoryImpl._createConnection(JmsConnectionFactoryImpl.java:293)
at com.ibm.msg.client.jms.admin.JmsConnectionFactoryImpl.createConnection(JmsConnectionFactoryImpl.java:234)
at com.ibm.mq.jms.MQConnectionFactory.createCommonConnection(MQConnectionFactory.java:6016)
at com.ibm.mq.jms.MQQueueConnectionFactory.createQueueConnection(MQQueueConnectionFactory.java:111)
at aaa.bbb.ccc.MQCheck3.main(MQCheck3.java:35)
Caused by: com.ibm.mq.MQException: JMSCMQ0001: WebSphere MQ call failed with compcode '2' ('MQCC_FAILED') reason '2035' ('MQRC_NOT_AUTHORIZED').
at com.ibm.msg.client.wmq.common.internal.Reason.createException(Reason.java:202)
... 8 more
Exception in thread "main" java.lang.NullPointerException
at aaa.bbb.ccc.MQCheck3.main(MQCheck3.java:48)
</code></pre>
<p><strong>*QUESTION: can anyone explain to me why the 2nd example does not work?: *</strong> </p>
<p>-Is there something that is incorrect and/or missing from the code that would enable it to work?</p>
<p><strong><em>FYI - running MQ server from Docker image:</em></strong></p>
<p>C:>docker exec mq dspmqver</p>
<pre><code>C:\>docker exec mq dspmqver
Name: IBM MQ
Version: 9.0.3.0
Level: p903-L170517.DE
BuildType: IKAP - (Production)
Platform: IBM MQ for Linux (x86-64 platform)
Mode: 64-bit
O/S: Linux 4.9.31-moby
InstName: Installation1
InstDesc:
Primary: Yes
InstPath: /opt/mqm
DataPath: /var/mqm
MaxCmdLevel: 903
LicenseType: Developer
C:\>
</code></pre>
<p><strong><em>pom.xml</em></strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>aaa.bbb.ccc</groupId>
<artifactId>mqcheck</artifactId>
<version>1</version>
<packaging>jar</packaging>
<name>mqcheck</name>
<description>mqcheck</description>
<properties>
<mq.version>8.0.0.2</mq.version>
</properties>
<dependencies>
<dependency>
<groupId>ibm.mq</groupId>
<artifactId>fscontext</artifactId>
<version>${mq.version}</version>
</dependency>
<dependency>
<groupId>ibm.mq</groupId>
<artifactId>jms</artifactId>
<version>${mq.version}</version>
</dependency>
<dependency>
<groupId>ibm.mq</groupId>
<artifactId>com.ibm.mq</artifactId>
<version>${mq.version}</version>
</dependency>
<dependency>
<groupId>ibm.mq</groupId>
<artifactId>com.ibm.mqjms</artifactId>
<version>${mq.version}</version>
</dependency>
<dependency>
<groupId>ibm.mq</groupId>
<artifactId>com.ibm.mq.jmqi</artifactId>
<version>${mq.version}</version>
</dependency>
<dependency>
<groupId>ibm.mq</groupId>
<artifactId>com.ibm.mq.headers</artifactId>
<version>${mq.version}</version>
</dependency>
<dependency>
<groupId>ibm.mq</groupId>
<artifactId>com.ibm.mq.commonservices</artifactId>
<version>${mq.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<p><strong><em>as per the suggestion in the post below (thx, joshmc), here is the AMQERR01.log</em></strong>
it appears to provide a clue... -now, the quest to determine how to I unblock the 'admin' user :-)</p>
<pre><code>----- cmqxrmsa.c : 1347 -------------------------------------------------------
08/11/17 17:32:09 - Process(1847.6) User(root) Program(amqrmppa)
Host(bd069b8075db) Installation(Installation1)
VRMF(9.0.3.0) QMgr(QM1)
Time(2017-08-11T17:32:09.967Z)
AMQ9776: Channel was blocked by userid
EXPLANATION:
The inbound channel 'DEV.APP.SVRCONN' was blocked from address '172.17.0.1'
because the active values of the channel were mapped to a userid which should
be blocked. The active values of the channel were 'MCAUSER(admin)
CLNTUSER(admin)'.
ACTION:
Contact the systems administrator, who should examine the channel
authentication records to ensure that the correct settings have been
configured. The ALTER QMGR CHLAUTH switch is used to control whether channel
authentication records are used. The command DISPLAY CHLAUTH can be used to
query the channel authentication records.
----- cmqxrmsa.c : 1347 -------------------------------------------------------
</code></pre>
<p><strong><em>running following command (as suggested)...</em></strong></p>
<pre><code>C:\>docker exec --tty --interactive mq runmqsc
5724-H72 (C) Copyright IBM Corp. 1994, 2017.
Starting MQSC for queue manager QM1.
</code></pre>
<p><strong><em>DIS CHL(DEV.APP.SVRCONN) MCAUSER</em></strong></p>
<pre><code>DIS CHL(DEV.APP.SVRCONN) MCAUSER
1 : DIS CHL(DEV.APP.SVRCONN) MCAUSER
AMQ8414: Display Channel details.
CHANNEL(DEV.APP.SVRCONN) CHLTYPE(SVRCONN)
MCAUSER(app)
:
</code></pre>
<p><strong><em>DISPLAY CHLAUTH(DEV.APP.SVRCONN) MATCH(RUNCHECK) ALL ADDRESS(172.17.0.1)</em></strong></p>
<pre><code>DISPLAY CHLAUTH(DEV.APP.SVRCONN) MATCH(RUNCHECK) ALL ADDRESS(172.17.0.1) CLNTUSER('admin')
5 : DISPLAY CHLAUTH(DEV.APP.SVRCONN) MATCH(RUNCHECK) ALL ADDRESS(172.17.0.1) CLNTUSER('admin')
AMQ8878: Display channel authentication record details.
CHLAUTH(DEV.APP.SVRCONN) TYPE(ADDRESSMAP)
DESCR( ) CUSTOM( )
ADDRESS(*) USERSRC(CHANNEL)
CHCKCLNT(ASQMGR) ALTDATE(2017-08-11)
ALTTIME(19.23.31)
</code></pre>
<p><strong><em>DIS QMGR CONNAUTH</em></strong></p>
<pre><code>DIS QMGR CONNAUTH
1 : DIS QMGR CONNAUTH
AMQ8408: Display Queue Manager details.
QMNAME(QM1) CONNAUTH(DEV.AUTHINFO)
</code></pre>
<p><strong><em>DIS AUTHINFO(DEV.AUTHINFO)</em></strong></p>
<pre><code>DIS AUTHINFO(DEV.AUTHINFO)
2 : DIS AUTHINFO(DEV.AUTHINFO)
AMQ8566: Display authentication information details.
AUTHINFO(DEV.AUTHINFO) AUTHTYPE(IDPWOS)
ADOPTCTX(YES) DESCR( )
CHCKCLNT(REQDADM) CHCKLOCL(OPTIONAL)
FAILDLAY(1) AUTHENMD(OS)
ALTDATE(2017-08-14) ALTTIME(13.57.29)
</code></pre>
<p><strong><em>DISPLAY CHLAUTH(DEV.APP.SVRCONN) all</em></strong></p>
<pre><code>DISPLAY CHLAUTH(DEV.APP.SVRCONN) all
1 : DISPLAY CHLAUTH(DEV.APP.SVRCONN) all
AMQ8878: Display channel authentication record details.
CHLAUTH(DEV.APP.SVRCONN) TYPE(ADDRESSMAP)
DESCR( ) CUSTOM( )
ADDRESS(*) USERSRC(CHANNEL)
CHCKCLNT(ASQMGR) ALTDATE(2017-08-16)
ALTTIME(13.43.26)
</code></pre>
<p><strong><em>DISPLAY CHLAUTH(</em>) all*</strong></p>
<pre><code>DISPLAY CHLAUTH(*) all
2 : DISPLAY CHLAUTH(*) all
AMQ8878: Display channel authentication record details.
CHLAUTH(DEV.ADMIN.SVRCONN) TYPE(USERMAP)
DESCR(Allows admin user to connect via ADMIN channel)
CUSTOM( ) ADDRESS( )
CLNTUSER(admin) USERSRC(CHANNEL)
CHCKCLNT(ASQMGR) ALTDATE(2017-08-16)
ALTTIME(13.43.26)
AMQ8878: Display channel authentication record details.
CHLAUTH(DEV.ADMIN.SVRCONN) TYPE(BLOCKUSER)
DESCR(Allows admins on ADMIN channel) CUSTOM( )
USERLIST(nobody) WARN(NO)
ALTDATE(2017-08-16) ALTTIME(13.43.26)
AMQ8878: Display channel authentication record details.
CHLAUTH(DEV.APP.SVRCONN) TYPE(ADDRESSMAP)
DESCR( ) CUSTOM( )
ADDRESS(*) USERSRC(CHANNEL)
CHCKCLNT(ASQMGR) ALTDATE(2017-08-16)
ALTTIME(13.43.26)
AMQ8878: Display channel authentication record details.
CHLAUTH(MY.ADMIN.SVRCONN) TYPE(ADDRESSMAP)
DESCR( ) CUSTOM( )
ADDRESS(127.0.0.1) USERSRC(CHANNEL)
CHCKCLNT(ASQMGR) ALTDATE(2017-08-11)
ALTTIME(20.17.14)
AMQ8878: Display channel authentication record details.
CHLAUTH(MY.ADMIN.SVRCONN) TYPE(BLOCKUSER)
DESCR( ) CUSTOM( )
USERLIST(*NOBODY) WARN(NO)
ALTDATE(2017-08-11) ALTTIME(20.17.51)
AMQ8878: Display channel authentication record details.
CHLAUTH(SYSTEM.ADMIN.SVRCONN) TYPE(ADDRESSMAP)
DESCR(Default rule to allow MQ Explorer access)
CUSTOM( ) ADDRESS(*)
USERSRC(CHANNEL) CHCKCLNT(ASQMGR)
ALTDATE(2017-08-03) ALTTIME(17.22.22)
AMQ8878: Display channel authentication record details.
CHLAUTH(SYSTEM.*) TYPE(ADDRESSMAP)
DESCR(Default rule to disable all SYSTEM channels)
CUSTOM( ) ADDRESS(*)
USERSRC(NOACCESS) WARN(NO)
ALTDATE(2017-08-03) ALTTIME(17.22.22)
AMQ8878: Display channel authentication record details.
CHLAUTH(*) TYPE(ADDRESSMAP)
DESCR(Back-stop rule - Blocks everyone)
CUSTOM( ) ADDRESS(*)
USERSRC(NOACCESS) WARN(NO)
ALTDATE(2017-08-16) ALTTIME(13.43.26)
AMQ8878: Display channel authentication record details.
CHLAUTH(*) TYPE(BLOCKUSER)
DESCR(Default rule to disallow privileged users)
CUSTOM( ) USERLIST(*MQADMIN)
WARN(NO) ALTDATE(2017-08-03)
ALTTIME(17.22.22)
</code></pre>
| 0 | 7,675 |
Using primefaces p:tabView, the refresh of the tabs using p:ajax doesn't work fine. The first time refresh but the next times doesn't refresh
|
<p>I have a page with a tabView, with 3 tabs, each tab has a tree. The tree of the third tab (DEVICES CATEGORY/TYPE), depends on what I select in the tree of the second tab (CERTIFICATIONS SYSTEM/PROGRAM). I generate the tree of the third tab dynamically when tab changes, using the event "tabChange"</p>
<pre><code><p:ajax event="tabChange" listener="#{profileMB.onTabChange}" />
</code></pre>
<p>When I select an element of the tree of the second tab and I change to the third tab, <strong>for the first time, it works OK</strong>, but when I <strong>return to the second tab</strong> and I <strong>mark differents nodes</strong> of the tree and I change to the third tab, <strong>the third tabs doesn't refresh</strong>.</p>
<p>The methods of the event it works OK, and generate the tree well.</p>
<pre><code>public void onTabChange(TabChangeEvent event) {
log.debug(Constants.BEGIN);
if(selectedNodesCS!=null && selectedNodesCS.length>0){
rootDeviceCategory =
getDeviceCategoryService().createRootStructure(rootDeviceCategory, null,listCertSystem,listCertProgram);
}
}
</code></pre>
<p>I tried using the update in the ajax event "tabChange":</p>
<pre><code><p:ajax event="tabChange" listener="#{profileMB.onTabChange}" update=":formManagerProfile:tabsProfile:tabDC" />
</code></pre>
<p>but the console says: </p>
<p><strong><em>Can not update component "org.primefaces.component.tabview.Tab" with id "formManagerProfile:tabsProfile:tabDC" without a attached renderer</em></strong></p>
<p>This is the code of my XHTML:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:form id="formManagerProfile" style="margin: auto auto">
<h:panelGroup id="displayManager">
<p:panelGrid id="panelUp" style="text-align: left;"
styleClass="panelGridWithoutBorder">
<p:row>
<p:column>
<h:outputText value="#{msg['profile.name']}: " for="profileName" />
</p:column>
<p:column>
<h:inputText id="profileName" value="#{profileMB.profileName}"
maxlength="64" styleClass="width-100x100" />
</p:column>
</p:row>
<p:row>
<p:column>
<h:outputText value="#{msg['profile.profileGroup']}: "
for="profileGroup" />
</p:column>
<p:column>
<p:selectOneMenu id="profileGroup"
value="#{profileMB.profileGroupSelected}"
converter="#{selectOneMenuConverterSelf}">
<f:selectItem itemLabel="" itemValue="#{null}" />
<f:selectItems id="pgSelectedItem"
value="#{profileMB.listProfileGroups}" var="pgItem"
itemValue="#{pgItem}" itemLabel="#{pgItem.name}" />
</p:selectOneMenu>
</p:column>
<p:column>
<p:commandButton id="editProfileGroup"
icon="#{msg['icon.update']}"
value="#{msg['button.text.updateProfileGroup']}"
title="#{msg['button.text.updateProfileGroup']}"
actionListener="#{profileMB.managementProfileGroup}"
update=":managerProfileGroupForm :growl"
oncomplete="PF('profileGroupManagerDialogWidget').initPosition();PF('profileGroupManagerDialogWidget').show()" />
</p:column>
</p:row>
</p:panelGrid>
<p:panel styleClass="text_align_left">
<p:commandButton id="saveButtonUp" icon="#{msg['icon.save']}"
value="#{msg['button.text.save']}"
title="#{msg['button.text.save']}"
action="#{profileMB.saveProfile}" update=":growl" />
<p:commandButton id="backButtonUp" icon="#{msg['icon.back']}"
value="#{msg['button.text.back']}"
title="#{msg['button.text.back']}" action="#{profileMB.backAction}"
ajax="false" />
</p:panel>
</h:panelGroup>
<h:panelGroup>
<p:tabView id="tabsProfile" dynamic="true">
<p:ajax event="tabChange" listener="#{profileMB.onTabChange}" />
<p:tab id="tabMenu" title="MENUS">
<p:tree value="#{profileMB.rootAction}" var="elementAction"
selectionMode="checkbox" selection="#{profileMB.selectedNodes}">
<p:treeNode>
<h:outputText value="#{elementAction}" />
</p:treeNode>
</p:tree>
</p:tab>
<p:tab id="tabCS" title="CERTIFICATIONS SYSTEM/PROGRAM">
<p:tree id="TreeCS" value="#{profileMB.rootCertSystem}"
var="elementCS" selectionMode="checkbox"
selection="#{profileMB.selectedNodesCS}">
<!-- <p:ajax event="select" listener="#{profileMB.onClickTreeCS}" /> -->
<!-- <p:ajax event="unselect" listener="#{profileMB.onClickUnSelectTreeCS}" /> -->
<p:ajax async="true" delay="none" immediate="true"
process="TreeCS" event="select" />
<p:ajax async="true" delay="none" immediate="true"
process="TreeCS" event="unselect" />
<p:treeNode>
<h:outputText value="#{elementCS}" />
</p:treeNode>
</p:tree>
</p:tab>
<p:tab id="tabDC" title="DEVICES CATEGORY/TYPE">
<p:tree id="TreeDC" value="#{profileMB.rootDeviceCategory}"
var="elementDC" selectionMode="checkbox"
selection="#{profileMB.selectedNodesDevCat}">
<p:ajax event="select" listener="#{profileMB.onClickTreeDC}" />
<p:ajax event="unselect"
listener="#{profileMB.onClickUnSelectTreeDC}" />
<p:treeNode>
<h:outputText value="#{elementDC}" />
</p:treeNode>
</p:tree>
</p:tab>
</p:tabView>
</h:panelGroup>
</h:form>
</ui:composition>
</code></pre>
<p>I'm using primefaces v5.1, JSF v2.2.8, spring v3.2.5, hibernate v4.2.7 and java v1.7 </p>
| 0 | 4,161 |
Sprite Rotation in Android using Canvas.DrawBitmap. I am close, what am I doing wrong?
|
<p>I have this sprite rotating algorithm (its poorly named and just used for testing). It is so close, sprites drawn with it do rotate. Everyframe I can add +5 degrees to it and see my nice little sprite rotate around. The problem is, the other stuff drawn to the canvas now flickers. If I don't do the rotation the regular drawn sprites work great. I think I am close but I just don't know what piece I am missing. Below is my two "Draw_Sprite" methods, one just draws the previously resource loaded bitmap to the canvas passed in. The other one, does some rotation the best I know how to rotate the sprite by so x many degrees..and then draw it. If I have a nice game loop that draws several objects, one type is the rotated kind. Then the non-rotated sprites flicker and yet the rotated sprite never does. Though if I draw the non-rotated sprites first, all is well, but then the Z-Ordering could be messed up (sprites on top of UI elements etc)... The method definitions:</p>
<pre><code> /*************************************************
* rotated sprite, ignore the whatever, its for ease of use and testing to have this argument list
* @param c canvas to draw on.
* @param whatever ignore
* @param rot degrees to rotate
* @return
*/
public int Draw_Sprite(Canvas c, int whatever, int rot) {
//rotating sprite
Rect src = new Rect(0, 0, width, height);
Rect dst = new Rect(x, y, x + width, y + height);
Matrix orig = c.getMatrix();
mMatrix = orig;
orig.setTranslate(0, 0);
orig.postRotate(rot, x+width/2, y+height/2);
c.setMatrix(orig);
c.drawBitmap(images[curr_frame], src, dst, null);
c.setMatrix(mMatrix); //set it back so all things afterwards are displayed correctly.
isScaled=false;
return 1;
}
/********************************************************
* draw a regular sprite to canvas c
* @param c
* @return
*/
public int Draw_Sprite(Canvas c) {
Rect src = new Rect(0, 0, width, height);
Rect dst = new Rect(x, y, x + width, y + height);
c.drawBitmap(images[curr_frame], src, dst, null);
isScaled=false;
return 1;
}
</code></pre>
<p>And now the usage:</p>
<pre><code>void onDraw(Canvas c)
{
canvas.drawRect( bgRect, bgPaint); //draw the background
//draw all game objects
// draw the normal items
for (GameEntity graphic : _graphics) {
graphic.toScreenCoords((int)player_x, (int)player_y);
if(graphic.getType().equals("planet")) //draw planets
graphic.Draw_Sprite(canvas); //before the rotation call draws fine
else
{
//rotate all space ships every frame so i see them spinning
//test rotation
mRot +=5;
if(mRot>=360)
mRot=0;
graphic.Draw_Sprite(canvas, 0, mRot); //yes function name will be better in future. this rotates spins draws fine
}
}
thePlayer.Draw_Sprite(canvas); //FLICKERS
drawUI(canvas);//all things here flickr
}
</code></pre>
<p>So it does do it, things after a call to a rotational draw are drawn correctly. But the problem is it flickrs. Now One could say I should just do all my non rotational stuff and save that last, but the zordering would be off.... suggestions as to how to tackle this issue of zordering or the flickering?</p>
| 0 | 1,198 |
How to re-render Formik values after updated it - React Native?
|
<p>I have a screen for update previously data "name, email, age, etc". at the first time I call a function that gets data from server name as <code>getProfileData()</code></p>
<p>after user write the new data I send a POST request for that "update Profile"</p>
<p>and it's a success, but after that, I want to re-render this form with new data, So i call the <code>getProfileData()</code> function to get new data but it's not working to re-render Input Values!
it's just still with previous data</p>
<p>I also try with <code>componentDidUpdate()</code> but sadly not re-render :)</p>
<p>So how can i solve it?</p>
<p>Code </p>
<pre><code>getProfileData = async () => {
let USER_TOKEN =
'....';
let AuthStr = `Bearer ${USER_TOKEN}`;
let response = await API.get('/profile', {
headers: {Authorization: AuthStr},
});
let {
data: {data},
} = response;
let password = '';
let password_confirmation = '';
let {name, email, avatar, age, gender, country_id} = data;
let initialValues = [];
initialValues.push({
name,
password,
password_confirmation,
email,
avatar,
age,
gender,
country_id,
});
this.setState({initialValues: initialValues, loading: false}, () =>
reactotron.log(this.state.initialValues[0]),
);
};
updateProfile = async value => {
let USER_TOKEN =
'....';
let AuthStr = `Bearer ${USER_TOKEN}`;
const headers = {
'Content-Type': 'application/json',
Authorization: AuthStr,
};
let response = await API.post('/update_profile', value, {
headers: headers,
});
let {
data: {data},
} = response;
alert(data);
this.getProfileData(); // called
};
componentDidMount() {
this.getCountryList();
this.getProfileData();
}
componentDidUpdate(prevProps, prevState) {
if (prevState.initialValues !== this.state.initialValues) {
console.log('componentDidUpdate', this.state.initialValues);
this.setState({initialValues: this.state.initialValues});
}
}
</code></pre>
<p>UI</p>
<pre><code><Formik
validationSchema={formSchema}
initialValues={this.state.initialValues[0]}
onSubmit={(values, actions) => {
this.updateProfile(values);
reactotron.log(values), actions.resetForm();
}}>
{({
handleChange,
handleBlur,
touched,
errors,
handleSubmit,
values,
setFieldValue,
}) => (
<View>
<Item style={styles.item} floatingLabel>
<Label style={styles.formLabel}>name</Label>
<Input
style={styles.value}
rounded
onChangeText={handleChange('name')}
onBlur={handleBlur('name')}
value={values.name}
/>
</Item>
<Text style={styles.errorText}>
{touched.name && errors.name}
</Text>
</View>
)}
</Formik>
</code></pre>
| 0 | 1,730 |
My SetupDiEnumDeviceInterfaces is not working
|
<p>I am interested to find out if I am doing this right:</p>
<pre><code>//DeviceManager.h
#include <windows.h>
//#include <hidsdi.h>
#include <setupapi.h>
#include <iostream>
#include <cfgmgr32.h>
#include <tchar.h>
#include <devpkey.h>
extern "C"{
#include <hidsdi.h>
}
//#pragma comment (lib, "setupapi.lib")
class DeviceManager
{
public:
DeviceManager();
~DeviceManager();
void ListAllDevices();
void GetDevice(std::string vid, std::string pid);
HANDLE PSMove;
byte reportBuffer;
private:
HDEVINFO deviceInfoSet; //A list of all the devices
SP_DEVINFO_DATA deviceInfoData; //A device from deviceInfoSet
SP_DEVICE_INTERFACE_DATA deviceInterfaceData;
SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailedData;
};
//DeviceManager.cpp
#include"DeviceManager.h"
DeviceManager::DeviceManager()
{
deviceInfoSet = SetupDiGetClassDevs(NULL, TEXT("USB"), NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES); //Gets all Devices
}
DeviceManager::~DeviceManager()
{
}
void DeviceManager::ListAllDevices()
{
DWORD deviceIndex = 0;
deviceInfoData.cbSize = sizeof(deviceInfoData);
while(SetupDiEnumDeviceInfo(deviceInfoSet, deviceIndex, &deviceInfoData))
{
deviceInfoData.cbSize = sizeof(deviceInfoData);
ULONG tcharSize;
CM_Get_Device_ID_Size(&tcharSize, deviceInfoData.DevInst, 0);
TCHAR* deviceIDBuffer = new TCHAR[tcharSize]; //the device ID will be stored in this array, so the tcharSize needs to be big enough to hold all the info.
//Or we can use MAX_DEVICE_ID_LEN, which is 200
CM_Get_Device_ID(deviceInfoData.DevInst, deviceIDBuffer, MAX_PATH, 0); //gets the devices ID - a long string that looks like a file path.
/*
//SetupDiGetDevicePropertyKeys(deviceInfoSet, &deviceInfoData, &devicePropertyKey, NULL, 0, 0);
if( deviceIDBuffer[8]=='8' && deviceIDBuffer[9]=='8' && deviceIDBuffer[10]=='8' && deviceIDBuffer[11]=='8' && //VID
deviceIDBuffer[17]=='0' && deviceIDBuffer[18]=='3' && deviceIDBuffer[19]=='0' && deviceIDBuffer[20]=='8') //PID
{
std::cout << deviceIDBuffer << "\t<-- Playstation Move" << std::endl;
}
else
{
std::cout << deviceIDBuffer << std::endl;
}*/
std::cout << deviceIDBuffer << std::endl;
deviceIndex++;
}
}
void DeviceManager::GetDevice(std::string vid, std::string pid)
{
DWORD deviceIndex = 0;
deviceInfoData.cbSize = sizeof(deviceInfoData);
while(SetupDiEnumDeviceInfo(deviceInfoSet, deviceIndex, &deviceInfoData))
{
deviceInfoData.cbSize = sizeof(deviceInfoData);
ULONG IDSize;
CM_Get_Device_ID_Size(&IDSize, deviceInfoData.DevInst, 0);
TCHAR* deviceID = new TCHAR[IDSize];
CM_Get_Device_ID(deviceInfoData.DevInst, deviceID, MAX_PATH, 0);
if( deviceID[8]==vid.at(0) && deviceID[9]==vid.at(1) && deviceID[10]==vid.at(2) && deviceID[11]==vid.at(3) && //VID
deviceID[17]==pid.at(0) && deviceID[18]==pid.at(1) && deviceID[19]==pid.at(2) && deviceID[20]==pid.at(3)) //PID
{
//DWORD requiredBufferSize;
//SetupDiGetDeviceInterfaceDetail(deviceInfoSet, &deviceInterfaceData, NULL, 0, &requiredBufferSize,
HDEVINFO deviceInterfaceSet = SetupDiGetClassDevs(&deviceInfoData.ClassGuid, NULL, NULL, DIGCF_ALLCLASSES);
DWORD deviceInterfaceIndex = 0;
deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
while(SetupDiEnumDeviceInterfaces(deviceInterfaceSet, NULL, &deviceInterfaceData.InterfaceClassGuid, deviceInterfaceIndex, &deviceInterfaceData))
{
deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
std::cout << deviceInterfaceIndex << std::endl;
deviceInterfaceIndex++;
}
//std::cout << deviceInterfaceData.cbSize << std::endl;
break;
}
deviceIndex++;
}
}
</code></pre>
<p>My SetupDiEnumDeviceInterfaces (in the GetDevice() function) is not doing anything. It is not even entering the while loop. What is it that I'm doing wrong?</p>
<h2>Edit</h2>
<p>I've just called the GetLastError() function and it has returned a 259 - ERROR_NO_MORE_ITEMS. Is it even possible for a device to contain no interfaces?</p>
| 0 | 2,022 |
Angular2: rendering / reloading a component's template
|
<p>Ideally I would need to reload / rerender my component's template but if there is a better way to do this I will gladly implement it.</p>
<p><strong>Desired behavior:</strong></p>
<p>So, I have a component for a menu element. When <em>(in another component)</em> I click an IBO <em>(some sort of 'client', per say)</em> is clicked I need to <em>add</em> (I'm using <code>*ngIf</code>) a new option in the menu that would be <em>IBO Details</em> and a child list.</p>
<p><strong><code>IBOsNavigationElement</code> component (menu component):</strong></p>
<pre class="lang-js prettyprint-override"><code>@Component({
selector: '[ibos-navigation-element]',
template: `
<a href="#"><i class="fa fa-lg fa-fw fa-group"></i> <span
class="menu-item-parent">{{'IBOs' | i18n}}</span>
</a>
<ul>
<li routerLinkActive="active">
<a routerLink="/ibos/IBOsMain">{{'IBOs Main' | i18n}} {{id}}</a>
</li>
<li *ngIf="navigationList?.length > 0">
<a href="#">{{'IBO Details' | i18n}}</a>
<ul>
<li routerLinkActive="active" *ngFor="let navigatedIBO of navigationList">
<a href="#/ibos/IboDetails/{{navigatedIBO['id']}}">{{navigatedIBO['name']}}</a>
</li>
</ul>
</li>
</ul>
`
})
export class IBOsNavigationElement implements OnInit {
private navigationList = <any>[];
constructor(private navigationService: NavigationElementsService) {
this.navigationService.updateIBOsNavigation$.subscribe((navigationData) => {
this.navigationList.push(navigationData);
log.d('I received this Navigation Data:', JSON.stringify(this.navigationList));
}
);
}
ngOnInit() {
}
}
</code></pre>
<p>Initially, <code>navigationList</code> will be empty <code>[]</code>, because the user didn't click any IBO <em>(client)</em>, but as soon as an IBO is clicked the list will be populated and, therefore, I need the new option to appear in the menu.</p>
<p>With this code, when I click an IBO, the <code><li></code> element and it's children are created but: <strong>I only see the <code><li></code> element.</strong></p>
<p><strong>Issue:</strong></p>
<p>The menu option is generated but not proccessed by the layout styles. It needs to be initialized with all the elements in order to know how to display the menu options.</p>
<p><strong>I need to reload the template of that component in order to display correctly the menu.</strong></p>
<p><strong>NOTE:</strong></p>
<p>If I use the template without the <code>*ngIf</code>, works well but I would have from the first moment an <em>IBO Details</em> option that has no sense, because no IBO has been clicked when initialized.</p>
<pre class="lang-js prettyprint-override"><code>template: `
<a href="#"><i class="fa fa-lg fa-fw fa-group"></i> <span
class="menu-item-parent">{{'IBOs' | i18n}}</span>
</a>
<ul>
<li routerLinkActive="active">
<a routerLink="/ibos/IBOsMain">{{'IBOs Main' | i18n}} {{id}}</a>
</li>
<li>
<a href="#">{{'IBO Details' | i18n}}</a>
<ul>
<li routerLinkActive="active" *ngFor="let navigatedIBO of navigationList">
<a href="#/ibos/IboDetails/{{navigatedIBO['id']}}">{{navigatedIBO['name']}}</a>
</li>
</ul>
</li>
</ul>
`
</code></pre>
<p><strong>Desired Output:</strong></p>
<p>Before clicking anything (on init):</p>
<p><a href="https://i.stack.imgur.com/gAv2n.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/gAv2n.jpg" alt="enter image description here"></a></p>
<p>After I clicked an IBO <em>(client)</em>:</p>
<p><a href="https://i.stack.imgur.com/7xaBU.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/7xaBU.jpg" alt="enter image description here"></a></p>
<p><strong>Update 1:</strong></p>
<p>To clarify what I meant with: </p>
<blockquote>
<p>The menu option is generated but not proccessed by the layout styles</p>
</blockquote>
<p>If, my menu component is initialized without the <code>*ngIf</code>:</p>
<pre class="lang-js prettyprint-override"><code><li>
<a href="#">{{'IBO Details' | i18n}}</a>
<ul>
<li routerLinkActive="active" *ngFor="let navigatedIBO of navigationList">
<a href="#/ibos/IboDetails/{{navigatedIBO['id']}}">{{navigatedIBO['name']}}</a>
</li>
</ul>
</li>
</code></pre>
<p>Then the layout styles can generate the menu output <em>(see images)</em> according to this structure:</p>
<pre class="lang-js prettyprint-override"><code><li>
<a>
<ul>
<li *ngFor>
<a>
</li>
</ul>
</li>
</code></pre>
<p>And therefore add the <code>+</code> symbol and the submenu behavior, etc.</p>
<p>But, if it's initialized without all the elements (when <code>*ngIf</code> is <code>false</code> the <code><li></code> and it's children are not rendered so the layout does not take them into account to draw/create the menu) and these elements are added <strong>after</strong> the rendering, then they will exist in source code, but we won't be able to see them in the menu because:</p>
<ul>
<li>No <code>+</code> created</li>
<li>No submenu behavior</li>
</ul>
| 0 | 2,616 |
Django count on many-to-many
|
<p>I have the models:</p>
<pre><code>class Article(models.Model):
title = models.TextField(blank=True)
keywords = models.ManyToManyField(Keyword, null=True, blank=True)
class Keyword(models.Model):
keyword = models.CharField(max_length=355, blank=True)
</code></pre>
<p>I want to get a count of how many articles have each keyword. In essence I want to have a list of keywords where I can get each ones count to give it a relative weighting.</p>
<p>I have tried: </p>
<pre><code>keyword_list=Article.objects.all().annotate(key_count=Count('keywords__keyword'))
</code></pre>
<p>but </p>
<pre><code>keyword_list[0].key_count
</code></pre>
<p>just seems to give me the number of <em>different</em> keywords each article has? Is it somehow a reverse lookup?</p>
<p>Any help would be much appreciated.</p>
<p><strong>UPDATE</strong></p>
<p>So I got it working:</p>
<pre><code>def keyword_list(request):
MAX_WEIGHT = 5
keywords = Keyword.objects.order_by('keyword')
for keyword in keywords:
keyword.count = Article.objects.filter(keywords=keyword).count()
min_count = max_count = keywords[0].count
for keyword in keywords:
if keyword.count < min_count:
min_count = keyword.count
if max_count > keyword.count:
max_count = keyword.count
range = float(max_count - min_count)
if range == 0.0:
range = 1.0
for keyword in keywords:
keyword.weight = (
MAX_WEIGHT * (keyword.count - min_count) / range
)
return { 'keywords': keywords }
</code></pre>
<p>but the view results in a hideous number of queries. I have tried implementing the suggestions given here (thanks) but this is the only methid which seems to work at the moment. However, I must be doing something wrong as I now have 400+ queries!</p>
<p><strong>UPDATE</strong></p>
<p>Wooh! Finally got it working:</p>
<pre><code>def keyword_list(request):
MAX_WEIGHT = 5
keywords_with_article_counts = Keyword.objects.all().annotate(count=Count('keyword_set'))
# get keywords and count limit to top 20 by count
keywords = keywords_with_article_counts.values('keyword', 'count').order_by('-count')[:20]
min_count = max_count = keywords[0]['count']
for keyword in keywords:
if keyword['count'] < min_count:
min_count = keyword['count']
if max_count < keyword['count']:
max_count = keyword['count']
range = float(max_count - min_count)
if range == 0.0:
range = 1.0
for keyword in keywords:
keyword['weight'] = int(
MAX_WEIGHT * (keyword['count'] - min_count) / range
)
return { 'keywords': keywords}
</code></pre>
| 0 | 1,059 |
.... undeclared (first use in this function)?
|
<p>I have a simple code in lex language and i generate lex.yy.c with Flex.
when i want to compile lex.yy.c to .exe file i get some error like "undeclared (first use in this function) " ! when i search in web i understand i need a Const.h file, so i want to generate that file.
how i can do this ?</p>
<p>Some Errors:</p>
<p>35 C:\Users\Majid\Desktop\win\lex.l <code>STRING' undeclared (first use in this function)
38 C:\Users\Majid\Desktop\win\lex.l</code>LC' undeclared (first use in this function)
39 C:\Users\Majid\Desktop\win\lex.l `LP' undeclared (first use in this function)
....</p>
<p>Beginnig of The Code is :</p>
<pre><code>%{int stk[20],stk1[20];
int lbl=0,wlbl=0;
int lineno=0;
int pcount=1;
int lcount=0,wlcount=0;
int token=100;
int dtype=0;
int count=0;
int fexe=0;
char c,str[20],str1[10],idename[10];
char a[100];
void eatcom();
void eatWS();
int set(int);
void check(char);
void checkop();
int chfunction(char *);%}
Digit [0-9]
Letter [a-zA-Z]
ID {letter}({letter}|{digit})*
NUM {digit}+
Delim [ \t]
A [A-Za-z]]
%%
"/*" eatcom();
"//"(.)*
\"(\\.|[^\"])*\" return (STRING);
\"(\\.|[^\"])*\n printf("Adding missing \" to sting constant");
"{" {a[count++]='{';fexe=0;eatWS();return LC;}
"(" {a[count++]='(';eatWS();return LP;}
"[" {a[count++]='[';eatWS();return LB;}
"}" {check('{');eatWS();
if(cflag)
{
//stk[lbl++]=lcount++;
fprintf(fc,"lbl%d:\n",stk[--lbl]);
//stk[lbl++]=lcount++;
printf("%d\n",stk[lbl]);
cflag=0;
}
return RC;
}
"]" {check('[');eatWS();return RB;}
")" {check('(');eatWS();return RP;}
"++" | "--" return INCOP;
[~!] return UNOP;
"*" {eatWS();return STAR;}
[/%] {eatWS();return DIVOP;}
"+" {eatWS();return PLUS;}
"-" {eatWS();return MINUS;}
</code></pre>
| 0 | 1,129 |
Why is my scoped_session raising an AttributeError: 'Session' object has no attribute 'remove'
|
<p>I'm trying to set up a system that elegantly defers database operations to a seperate thread in order to avoid blocking during Twisted callbacks.</p>
<p>So far, here is my approach:</p>
<pre><code>from contextlib import contextmanager
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from twisted.internet.threads import deferToThread
_engine = create_engine(initialization_string)
Session = scoped_session(sessionmaker(bind=_engine))
@contextmanager
def transaction_context():
session = Session()
try:
yield session
session.commit()
except:
# No need to do session.rollback(). session.remove will do it.
raise
finally:
session.remove()
def threaded(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
return deferToThread(fn, *args, **kwargs)
return wrapper
</code></pre>
<p>This should allow me to wrap a function with the <code>threaded</code> decorator and then use the <code>transaction_context</code> context manager in said function's body. Below is an example:</p>
<pre><code>from __future__ import print_function
from my_lib.orm import User, transaction_context, threaded
from twisted.internet import reactor
@threaded
def get_n_users(n):
with transaction_context() as session:
return session.query(User).limit(n).all()
if __name__ == '__main__':
get_n_users(n).addBoth(len)
reactor.run()
</code></pre>
<p>However, when I run the above script, I get a failure containing the following traceback:</p>
<pre><code>Unhandled error in Deferred:
Unhandled Error
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 781, in __bootstrap
self.__bootstrap_inner()
File "/usr/lib/python2.7/threading.py", line 808, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 761, in run
self.__target(*self.__args, **self.__kwargs)
--- <exception caught here> ---
File "/usr/local/lib/python2.7/dist-packages/twisted/python/threadpool.py", line 191, in _worker
result = context.call(ctx, function, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/twisted/python/context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/usr/local/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext
return func(*args,**kw)
File "testaccess.py", line 9, in get_n_users
return session.query(User).limit(n).all()
File "/usr/lib/python2.7/contextlib.py", line 24, in __exit__
self.gen.next()
File "/home/louis/Documents/Python/knacki/knacki/db.py", line 36, in transaction_context
session.remove()
exceptions.AttributeError: 'Session' object has no attribute 'remove'
</code></pre>
<p>I was not expecting this at all. What am I missing? Did I not instantiate my <code>scoped_session</code> properly?</p>
<p><strong>Edit:</strong> <a href="https://stackoverflow.com/questions/21076105/is-this-an-acceptable-way-to-make-threaded-sqlalchemy-queries-from-twisted">Here</a> is a related question about integrating this setup with Twisted. It might help clarify what I'm trying to achieve.</p>
| 0 | 1,121 |
Bootstrap SASS variable override challenge
|
<p><strong>EDIT:</strong> This question was marked as a duplicate of <a href="https://stackoverflow.com/questions/17089717/how-to-overwrite-scss-variables-when-compiling-to-css">this one</a>, but see the addendum near the end of this answer to see what that question doesn't ask, and what the answer doesn't answer.</p>
<p>I'm working on a web app that uses Bootstrap 3. I have a basic 3-layer override architecture, where 1) Bootstrap's _variables.scss contains the core variables, 2) _app-variables.scss contains the base app variables that override Bootstrap's _variables.scss, and 3) _client-variables.scss contains client-specific customizations that override _app-variables.scss. Either #2 or #3 (or both) can be blank files. So here's the override order:</p>
<pre><code>_variables.scss // Bootstrap's core
_app-variables.scss // App base
_client-variables.scss // Client-specific
</code></pre>
<p>Simple enough in theory, but a problem arises because of what I'll call "variable dependencies" -- where variables are defined as other variables. For example:</p>
<pre><code>$brand: blue;
$text: $brand;
</code></pre>
<p>Now, let's say the above variables are defined in _variables.scss. Then let's say in _app-variables.scss, I override only the $brand variable to make it red: <code>$brand: red</code>. Since SASS interprets the code line by line sequentially, it will first set $brand to blue, then it will set $text to blue (because $brand is blue at that point), and finally it will set $brand to red. So the end result is that changing $brand afterwards does not affect any variables that were based on the old value of $brand:</p>
<pre><code>_variables.scss
---------------------
$brand: blue;
$text: $brand; // $text = blue
.
.
.
_app-variables.scss
---------------------
$brand: red; // this does not affect $text, b/c $text was already set to blue above.
</code></pre>
<p>But obviously that's not what I want - I want my change of $brand to affect everything that depends on it. In order to properly override variables, I'm currently just making a full copy of _variables.scss into _app-variables.scss, and then making modifications within _app-variables from that point. And similarly I'm making a full copy of _app-variables.scss into _client-variables.scss and then making modifications within _client-variables.scss at that point. Obviously this is less than ideal (understatement) from a maintenance point of view - everytime I make a modification to _variables.scss (in the case of a Bootstrap upgrade) or _app-variables.scss, I have to manual trickle the changes down the file override stack. And plus I'm having to redeclare a ton of variables that I may not even be overriding.</p>
<p>I found out that LESS has what they call "lazy loading" (<a href="http://lesscss.org/features/#variables-feature-lazy-loading" rel="noreferrer">http://lesscss.org/features/#variables-feature-lazy-loading</a>), where the last definition of a variable is used everywhere, even before the last definition. I believe this would solve my problem. But does anyone know a proper variable-override solution using SASS?</p>
<p><strong>ADDENDUM:</strong><br>
Here's one technique I've already thought through: include the files in reverse order, using <code>!default</code> for all variables (this technique was also suggested in the answer to <a href="https://stackoverflow.com/questions/17089717/how-to-overwrite-scss-variables-when-compiling-to-css">this question</a>). So here's how this would play out:</p>
<pre><code>_app-variables.scss
---------------------
$brand: red !default; // $brand is set to red here, overriding _variables.scss's blue.
.
.
.
_variables.scss
---------------------
$brand: blue !default; // brand already set in _app-variables.scss, so not overridden here.
$text: $brand !default; // $text = red (desired behavior)
</code></pre>
<p>So that solution is <strong><em>almost</em></strong> perfect. <strong><em>However</em></strong>, now in my override files, I don't have access to variables defined in Bootstrap's _variables.scss, which I would need if I wanted to define my variable overrides (or my own additional custom variables) using other Bootstrap variables. For example, I might want to do: <code>$custom-var: $grid-gutter-width / 2;</code></p>
| 0 | 1,230 |
ERROR: Non-resolvable parent POM: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom
|
<p>I am getting the below exception in my pom.xml when trying to run my application. I saw some posts regarding the error and followed them but no use. I understand the artifact(parent) is referred locally and is not present, but I don't know how to resolve this, could somebody please help me?</p>
<p>The error is</p>
<pre><code>Project build error: Non-resolvable parent POM for com.example:demo:0.0.1-SNAPSHOT: Failure
to transfer org.springframework.boot:spring-boot-starter-parent:pom:1.5.18.BUILD-SNAPSHOT
from https://repo.spring.io/snapshot was cached in the local repository, resolution will not be
reattempted until the update interval of spring-snapshots has elapsed or updates are forced.
Original error: Could not transfer artifact org.springframework.boot:spring-boot-starter-
parent:pom:1.5.18.BUILD-SNAPSHOT from/to spring-snapshots (https://repo.spring.io/
snapshot): repo.spring.io and 'parent.relativePath' points at no local POM
</code></pre>
<p>below is the pom.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.18.BUILD-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
</code></pre>
| 0 | 2,987 |
How to Run a Jmeter script within Java code?
|
<p>I'm unable to run the JMeter Java file with the below setup. Can anyone please help me and tell me what is wrong. I am using Eclipse with Maven integration.</p>
<p>Referring the post: <a href="https://stackoverflow.com/q/19147235/3755692">How to create and run Apache JMeter Test Scripts from a Java program?</a></p>
<p><strong>Java code:</strong></p>
<pre><code>package com.blazemeter.demo;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.protocol.http.sampler.HTTPSampler;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jmeter.threads.SetupThreadGroup;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
public class JMeterFromScratch {
public static void main(String[] args){
// Engine
StandardJMeterEngine jm = new StandardJMeterEngine();
// jmeter.properties
JMeterUtils.loadJMeterProperties("C:/Users/sthomas/jmeter.properties");
HashTree hashTree = new HashTree();
// HTTP Sampler
HTTPSampler httpSampler = new HTTPSampler();
httpSampler.setDomain("www.google.com");
httpSampler.setPort(80);
httpSampler.setPath("/");
httpSampler.setMethod("GET");
// Loop Controller
LoopController loopCtrl = new LoopController();
((LoopController)loopCtrl).setLoops(1);
((LoopController)loopCtrl).addTestElement(httpSampler);
((LoopController)loopCtrl).setFirst(true);
((LoopController)loopCtrl).initialize();
// Thread Group
SetupThreadGroup threadGroup = new SetupThreadGroup();
threadGroup.setNumThreads(1);
threadGroup.setRampUp(1);
threadGroup.setSamplerController((LoopController)loopCtrl);
// Test plan
TestPlan testPlan = new TestPlan("MY TEST PLAN");
hashTree.add("testPlan", testPlan);
hashTree.add("loopCtrl", loopCtrl);
hashTree.add("threadGroup", threadGroup);
hashTree.add("httpSampler", httpSampler);
jm.configure(hashTree);
jm.run();
}
}
</code></pre>
<hr>
<p><strong>Jmeter.properties file</strong></p>
<pre><code>log_level.jmeter=DEBUG
log_level.jmeter.junit=DEBUG
log_level.jmeter.control=DEBUG
log_level.jmeter.testbeans=DEBUG
log_level.jmeter.engine=DEBUG
log_level.jmeter.threads=DEBUG
log_level.jmeter.gui=WARN
log_level.jmeter.testelement=DEBUG
log_level.jmeter.util=DEBUG
log_level.jmeter.util.classfinder=DEBUG
log_level.jmeter.test=DEBUG
log_level.jmeter.protocol.http=DEBUG
# For CookieManager, AuthManager etc:
log_level.jmeter.protocol.http.control=DEBUG
log_level.jmeter.protocol.ftp=WARN
log_level.jmeter.protocol.jdbc=DEBUG
log_level.jmeter.protocol.java=WARN
log_level.jmeter.testelements.property=DEBUG
log_level.jorphan=DEBUG
jmeterengine.startlistenerslater=false
log_file=jmeter-debug.log
</code></pre>
<hr>
<p><strong>Debug Log:</strong></p>
<pre><code>2014-11-03 16:29:36.905 [jmeter.e] (): Listeners will be started after enabling running version
INFO 2014-11-03 16:29:36.967 [jmeter.e] (): To revert to the earlier behaviour, define jmeterengine.startlistenerslater=false
INFO 2014-11-03 16:29:36.983 [jmeter.p] (): No response parsers defined: text/html only will be scanned for embedded resources
INFO 2014-11-03 16:29:36.991 [jmeter.p] (): Maximum connection retries = 10
INFO 2014-11-03 16:29:37.001 [jmeter.e] (): Running the test!
INFO 2014-11-03 16:29:37.009 [jmeter.s] (): List of sample_variables: []
INFO 2014-11-03 16:29:37.009 [jmeter.s] (): List of sample_variables: []
DEBUG 2014-11-03 16:29:37.016 [jorphan.] (): searchPathsOrJars : [null/lib/ext]
DEBUG 2014-11-03 16:29:37.016 [jorphan.] (): superclass : [interface org.apache.jmeter.functions.Function]
DEBUG 2014-11-03 16:29:37.016 [jorphan.] (): innerClasses : true annotations: false
DEBUG 2014-11-03 16:29:37.016 [jorphan.] (): contains: null notContains: null
DEBUG 2014-11-03 16:29:37.017 [jorphan.] (): Classpath = C:\Users\sthomas\workspace\JmeterProj\target\classes;C:\Users\sthomas\.m2\repository\org\apache\jmeter\ApacheJMeter_core\2.11\ApacheJMeter_core-2.11.jar;C:\Users\sthomas\.m2\repository\avalon-framework\avalon-framework\4.1.4\avalon-framework-4.1.4.jar;C:\Users\sthomas\.m2\repository\org\apache\jmeter\ApacheJMeter_http\2.11\ApacheJMeter_http-2.11.jar;C:\Users\sthomas\.m2\repository\commons-logging\commons-logging\1.2\commons-logging-1.2.jar;C:\Users\sthomas\.m2\repository\logkit\logkit\2.0\logkit-2.0.jar;C:\Users\sthomas\.m2\repository\oro\oro\2.0.8\oro-2.0.8.jar;C:\Users\sthomas\.m2\repository\commons-io\commons-io\2.4\commons-io-2.4.jar;C:\Users\sthomas\.m2\repository\org\apache\commons\commons-lang3\3.3.2\commons-lang3-3.3.2.jar;C:\Users\sthomas\.m2\repository\com\thoughtworks\xstream\xstream\1.4.7\xstream-1.4.7.jar;C:\Users\sthomas\.m2\repository\org\apache\jmeter\jorphan\2.11\jorphan-2.11.jar;C:\Users\sthomas\.m2\repository\bsf\bsf\2.4.0\bsf-2.4.0.jar;C:\Users\sthomas\.m2\repository\org\beanshell\bsh\2.0b5\bsh-2.0b5.jar;C:\Users\sthomas\.m2\repository\org\bouncycastle\bcmail-jdk15on\1.49\bcmail-jdk15on-1.49.jar;C:\Users\sthomas\.m2\repository\org\bouncycastle\bcprov-jdk15on\1.49\bcprov-jdk15on-1.49.jar;C:\Users\sthomas\.m2\repository\org\bouncycastle\bcpkix-jdk15on\1.49\bcpkix-jdk15on-1.49.jar;C:\Users\sthomas\.m2\repository\commons-codec\commons-codec\1.8\commons-codec-1.8.jar;C:\Users\sthomas\.m2\repository\commons-collections\commons-collections\3.2.1\commons-collections-3.2.1.jar;C:\Users\sthomas\.m2\repository\commons-httpclient\commons-httpclient\3.1\commons-httpclient-3.1.jar;C:\Users\sthomas\.m2\repository\commons-jexl\commons-jexl\1.1\commons-jexl-1.1.jar;C:\Users\sthomas\.m2\repository\org\apache\commons\commons-jexl\2.1.1\commons-jexl-2.1.1.jar;C:\Users\sthomas\.m2\repository\commons-net\commons-net\3.3\commons-net-3.3.jar;C:\Users\sthomas\.m2\repository\excalibur-datasource\excalibur-datasource\1.1.1\excalibur-datasource-1.1.1.jar;C:\Users\sthomas\.m2\repository\excalibur-instrument\excalibur-instrument\1.0\excalibur-instrument-1.0.jar;C:\Users\sthomas\.m2\repository\excalibur-logger\excalibur-logger\1.1\excalibur-logger-1.1.jar;C:\Users\sthomas\.m2\repository\excalibur-pool\excalibur-pool\1.2\excalibur-pool-1.2.jar;C:\Users\sthomas\.m2\repository\org\htmlparser\htmllexer\2.1\htmllexer-2.1.jar;C:\Users\sthomas\.m2\repository\org\htmlparser\htmlparser\2.1\htmlparser-2.1.jar;C:\Users\sthomas\.m2\repository\org\apache\httpcomponents\httpclient\4.2.6\httpclient-4.2.6.jar;C:\Users\sthomas\.m2\repository\org\apache\httpcomponents\httpmime\4.2.6\httpmime-4.2.6.jar;C:\Users\sthomas\.m2\repository\org\apache\httpcomponents\httpcore\4.2.5\httpcore-4.2.5.jar;C:\Users\sthomas\.m2\repository\jcharts\jcharts\0.7.5\jcharts-0.7.5.jar;C:\Users\sthomas\.m2\repository\org\jdom\jdom\1.1.3\jdom-1.1.3.jar;C:\Users\sthomas\.m2\repository\org\mozilla\rhino\1.7R4\rhino-1.7R4.jar;C:\Users\sthomas\.m2\repository\junit\junit\4.11\junit-4.11.jar;C:\Users\sthomas\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Users\sthomas\.m2\repository\soap\soap\2.3.1\soap-2.3.1.jar;C:\Users\sthomas\.m2\repository\net\sf\jtidy\jtidy\r938\jtidy-r938.jar;C:\Users\sthomas\.m2\repository\org\apache\tika\tika-core\1.4\tika-core-1.4.jar;C:\Users\sthomas\.m2\repository\org\apache\tika\tika-parsers\1.4\tika-parsers-1.4.jar;C:\Users\sthomas\.m2\repository\org\gagravarr\vorbis-java-tika\0.1\vorbis-java-tika-0.1.jar;C:\Users\sthomas\.m2\repository\org\gagravarr\vorbis-java-core\0.1\vorbis-java-core-0.1-tests.jar;C:\Users\sthomas\.m2\repository\edu\ucar\netcdf\4.2-min\netcdf-4.2-min.jar;C:\Users\sthomas\.m2\repository\org\apache\james\apache-mime4j-core\0.7.2\apache-mime4j-core-0.7.2.jar;C:\Users\sthomas\.m2\repository\org\apache\james\apache-mime4j-dom\0.7.2\apache-mime4j-dom-0.7.2.jar;C:\Users\sthomas\.m2\repository\org\apache\commons\commons-compress\1.5\commons-compress-1.5.jar;C:\Users\sthomas\.m2\repository\org\tukaani\xz\1.2\xz-1.2.jar;C:\Users\sthomas\.m2\repository\org\apache\pdfbox\pdfbox\1.8.1\pdfbox-1.8.1.jar;C:\Users\sthomas\.m2\repository\org\apache\pdfbox\fontbox\1.8.1\fontbox-1.8.1.jar;C:\Users\sthomas\.m2\repository\org\apache\pdfbox\jempbox\1.8.1\jempbox-1.8.1.jar;C:\Users\sthomas\.m2\repository\org\bouncycastle\bcmail-jdk15\1.45\bcmail-jdk15-1.45.jar;C:\Users\sthomas\.m2\repository\org\bouncycastle\bcprov-jdk15\1.45\bcprov-jdk15-1.45.jar;C:\Users\sthomas\.m2\repository\org\apache\poi\poi\3.9\poi-3.9.jar;C:\Users\sthomas\.m2\repository\org\apache\poi\poi-scratchpad\3.9\poi-scratchpad-3.9.jar;C:\Users\sthomas\.m2\repository\org\apache\poi\poi-ooxml\3.9\poi-ooxml-3.9.jar;C:\Users\sthomas\.m2\repository\org\apache\poi\poi-ooxml-schemas\3.9\poi-ooxml-schemas-3.9.jar;C:\Users\sthomas\.m2\repository\org\apache\xmlbeans\xmlbeans\2.3.0\xmlbeans-2.3.0.jar;C:\Users\sthomas\.m2\repository\dom4j\dom4j\1.6.1\dom4j-1.6.1.jar;C:\Users\sthomas\.m2\repository\org\apache\geronimo\specs\geronimo-stax-api_1.0_spec\1.0.1\geronimo-stax-api_1.0_spec-1.0.1.jar;C:\Users\sthomas\.m2\repository\org\ccil\cowan\tagsoup\tagsoup\1.2.1\tagsoup-1.2.1.jar;C:\Users\sthomas\.m2\repository\org\ow2\asm\asm-debug-all\4.1\asm-debug-all-4.1.jar;C:\Users\sthomas\.m2\repository\com\googlecode\mp4parser\isoparser\1.0-RC-1\isoparser-1.0-RC-1.jar;C:\Users\sthomas\.m2\repository\org\aspectj\aspectjrt\1.6.11\aspectjrt-1.6.11.jar;C:\Users\sthomas\.m2\repository\com\drewnoakes\metadata-extractor\2.6.2\metadata-extractor-2.6.2.jar;C:\Users\sthomas\.m2\repository\com\adobe\xmp\xmpcore\5.1.2\xmpcore-5.1.2.jar;C:\Users\sthomas\.m2\repository\de\l3s\boilerpipe\boilerpipe\1.1.0\boilerpipe-1.1.0.jar;C:\Users\sthomas\.m2\repository\rome\rome\0.9\rome-0.9.jar;C:\Users\sthomas\.m2\repository\jdom\jdom\1.0\jdom-1.0.jar;C:\Users\sthomas\.m2\repository\org\gagravarr\vorbis-java-core\0.1\vorbis-java-core-0.1.jar;C:\Users\sthomas\.m2\repository\com\googlecode\juniversalchardet\juniversalchardet\1.0.3\juniversalchardet-1.0.3.jar;C:\Users\sthomas\.m2\repository\xmlpull\xmlpull\1.1.3.1\xmlpull-1.1.3.1.jar;C:\Users\sthomas\.m2\repository\xpp3\xpp3_min\1.1.4c\xpp3_min-1.1.4c.jar;C:\Users\sthomas\.m2\repository\xalan\xalan\2.7.1\xalan-2.7.1.jar;C:\Users\sthomas\.m2\repository\xalan\serializer\2.7.1\serializer-2.7.1.jar;C:\Users\sthomas\.m2\repository\xerces\xercesImpl\2.9.1\xercesImpl-2.9.1.jar;C:\Users\sthomas\.m2\repository\xml-apis\xml-apis\1.3.04\xml-apis-1.3.04.jar;C:\Users\sthomas\.m2\repository\org\apache\xmlgraphics\xmlgraphics-commons\1.5\xmlgraphics-commons-1.5.jar;C:\Users\sthomas\.m2\repository\javax\mail\mail\1.5.0-b01\mail-1.5.0-b01.jar;C:\Users\sthomas\.m2\repository\javax\activation\activation\1.1\activation-1.1.jar;C:\Users\sthomas\.m2\repository\org\apache\geronimo\specs\geronimo-jms_1.1_spec\1.1.1\geronimo-jms_1.1_spec-1.1.1.jar;C:\Users\sthomas\.m2\repository\org\jsoup\jsoup\1.7.3\jsoup-1.7.3.jar;C:\Users\sthomas\.m2\repository\org\jodd\jodd-core\3.4.10\jodd-core-3.4.10.jar;C:\Users\sthomas\.m2\repository\org\jodd\jodd-lagarto\3.4.10\jodd-lagarto-3.4.10.jar;C:\Users\sthomas\.m2\repository\org\mongodb\mongo-java-driver\2.11.3\mongo-java-driver-2.11.3.jar;C:\Users\sthomas\.m2\repository\com\fifesoft\rsyntaxtextarea\2.5.1\rsyntaxtextarea-2.5.1.jar;C:\Users\sthomas\.m2\repository\org\slf4j\slf4j-api\1.7.5\slf4j-api-1.7.5.jar;C:\Users\sthomas\.m2\repository\org\slf4j\slf4j-nop\1.7.5\slf4j-nop-1.7.5.jar
DEBUG 2014-11-03 16:29:37.017 [jorphan.] (): strPathsOrJars[0] : null/lib/ext
DEBUG 2014-11-03 16:29:37.018 [jorphan.] (): Did not find: C:/Users/sthomas/workspace/JmeterProj/target/classes
DEBUG 2014-11-03 16:29:37.018 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/jmeter/ApacheJMeter_core/2.11/ApacheJMeter_core-2.11.jar
DEBUG 2014-11-03 16:29:37.018 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/avalon-framework/avalon-framework/4.1.4/avalon-framework-4.1.4.jar
DEBUG 2014-11-03 16:29:37.018 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/jmeter/ApacheJMeter_http/2.11/ApacheJMeter_http-2.11.jar
DEBUG 2014-11-03 16:29:37.018 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/commons-logging/commons-logging/1.2/commons-logging-1.2.jar
DEBUG 2014-11-03 16:29:37.018 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/logkit/logkit/2.0/logkit-2.0.jar
DEBUG 2014-11-03 16:29:37.018 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/oro/oro/2.0.8/oro-2.0.8.jar
DEBUG 2014-11-03 16:29:37.018 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/commons-io/commons-io/2.4/commons-io-2.4.jar
DEBUG 2014-11-03 16:29:37.018 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/commons/commons-lang3/3.3.2/commons-lang3-3.3.2.jar
DEBUG 2014-11-03 16:29:37.018 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/com/thoughtworks/xstream/xstream/1.4.7/xstream-1.4.7.jar
DEBUG 2014-11-03 16:29:37.018 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/jmeter/jorphan/2.11/jorphan-2.11.jar
DEBUG 2014-11-03 16:29:37.018 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/bsf/bsf/2.4.0/bsf-2.4.0.jar
DEBUG 2014-11-03 16:29:37.018 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/beanshell/bsh/2.0b5/bsh-2.0b5.jar
DEBUG 2014-11-03 16:29:37.018 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/bouncycastle/bcmail-jdk15on/1.49/bcmail-jdk15on-1.49.jar
DEBUG 2014-11-03 16:29:37.019 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/bouncycastle/bcprov-jdk15on/1.49/bcprov-jdk15on-1.49.jar
DEBUG 2014-11-03 16:29:37.019 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/bouncycastle/bcpkix-jdk15on/1.49/bcpkix-jdk15on-1.49.jar
DEBUG 2014-11-03 16:29:37.019 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/commons-codec/commons-codec/1.8/commons-codec-1.8.jar
DEBUG 2014-11-03 16:29:37.019 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/commons-collections/commons-collections/3.2.1/commons-collections-3.2.1.jar
DEBUG 2014-11-03 16:29:37.019 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/commons-httpclient/commons-httpclient/3.1/commons-httpclient-3.1.jar
DEBUG 2014-11-03 16:29:37.019 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/commons-jexl/commons-jexl/1.1/commons-jexl-1.1.jar
DEBUG 2014-11-03 16:29:37.019 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/commons/commons-jexl/2.1.1/commons-jexl-2.1.1.jar
DEBUG 2014-11-03 16:29:37.019 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/commons-net/commons-net/3.3/commons-net-3.3.jar
DEBUG 2014-11-03 16:29:37.019 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/excalibur-datasource/excalibur-datasource/1.1.1/excalibur-datasource-1.1.1.jar
DEBUG 2014-11-03 16:29:37.019 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/excalibur-instrument/excalibur-instrument/1.0/excalibur-instrument-1.0.jar
DEBUG 2014-11-03 16:29:37.019 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/excalibur-logger/excalibur-logger/1.1/excalibur-logger-1.1.jar
DEBUG 2014-11-03 16:29:37.019 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/excalibur-pool/excalibur-pool/1.2/excalibur-pool-1.2.jar
DEBUG 2014-11-03 16:29:37.019 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/htmlparser/htmllexer/2.1/htmllexer-2.1.jar
DEBUG 2014-11-03 16:29:37.019 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/htmlparser/htmlparser/2.1/htmlparser-2.1.jar
DEBUG 2014-11-03 16:29:37.019 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/httpcomponents/httpclient/4.2.6/httpclient-4.2.6.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/httpcomponents/httpmime/4.2.6/httpmime-4.2.6.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/httpcomponents/httpcore/4.2.5/httpcore-4.2.5.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/jcharts/jcharts/0.7.5/jcharts-0.7.5.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/jdom/jdom/1.1.3/jdom-1.1.3.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/mozilla/rhino/1.7R4/rhino-1.7R4.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/junit/junit/4.11/junit-4.11.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/soap/soap/2.3.1/soap-2.3.1.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/net/sf/jtidy/jtidy/r938/jtidy-r938.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/tika/tika-core/1.4/tika-core-1.4.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/tika/tika-parsers/1.4/tika-parsers-1.4.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/gagravarr/vorbis-java-tika/0.1/vorbis-java-tika-0.1.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/gagravarr/vorbis-java-core/0.1/vorbis-java-core-0.1-tests.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/edu/ucar/netcdf/4.2-min/netcdf-4.2-min.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/james/apache-mime4j-core/0.7.2/apache-mime4j-core-0.7.2.jar
DEBUG 2014-11-03 16:29:37.020 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/james/apache-mime4j-dom/0.7.2/apache-mime4j-dom-0.7.2.jar
DEBUG 2014-11-03 16:29:37.021 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/commons/commons-compress/1.5/commons-compress-1.5.jar
DEBUG 2014-11-03 16:29:37.021 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/tukaani/xz/1.2/xz-1.2.jar
DEBUG 2014-11-03 16:29:37.021 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/pdfbox/pdfbox/1.8.1/pdfbox-1.8.1.jar
DEBUG 2014-11-03 16:29:37.021 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/pdfbox/fontbox/1.8.1/fontbox-1.8.1.jar
DEBUG 2014-11-03 16:29:37.021 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/pdfbox/jempbox/1.8.1/jempbox-1.8.1.jar
DEBUG 2014-11-03 16:29:37.021 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/bouncycastle/bcmail-jdk15/1.45/bcmail-jdk15-1.45.jar
DEBUG 2014-11-03 16:29:37.021 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/bouncycastle/bcprov-jdk15/1.45/bcprov-jdk15-1.45.jar
DEBUG 2014-11-03 16:29:37.021 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/poi/poi/3.9/poi-3.9.jar
DEBUG 2014-11-03 16:29:37.021 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/poi/poi-scratchpad/3.9/poi-scratchpad-3.9.jar
DEBUG 2014-11-03 16:29:37.021 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/poi/poi-ooxml/3.9/poi-ooxml-3.9.jar
DEBUG 2014-11-03 16:29:37.021 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/poi/poi-ooxml-schemas/3.9/poi-ooxml-schemas-3.9.jar
DEBUG 2014-11-03 16:29:37.021 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/xmlbeans/xmlbeans/2.3.0/xmlbeans-2.3.0.jar
DEBUG 2014-11-03 16:29:37.021 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar
DEBUG 2014-11-03 16:29:37.021 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/geronimo/specs/geronimo-stax-api_1.0_spec/1.0.1/geronimo-stax-api_1.0_spec-1.0.1.jar
DEBUG 2014-11-03 16:29:37.022 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/ccil/cowan/tagsoup/tagsoup/1.2.1/tagsoup-1.2.1.jar
DEBUG 2014-11-03 16:29:37.022 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/ow2/asm/asm-debug-all/4.1/asm-debug-all-4.1.jar
DEBUG 2014-11-03 16:29:37.022 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/com/googlecode/mp4parser/isoparser/1.0-RC-1/isoparser-1.0-RC-1.jar
DEBUG 2014-11-03 16:29:37.022 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/aspectj/aspectjrt/1.6.11/aspectjrt-1.6.11.jar
DEBUG 2014-11-03 16:29:37.022 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/com/drewnoakes/metadata-extractor/2.6.2/metadata-extractor-2.6.2.jar
DEBUG 2014-11-03 16:29:37.022 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/com/adobe/xmp/xmpcore/5.1.2/xmpcore-5.1.2.jar
DEBUG 2014-11-03 16:29:37.022 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/de/l3s/boilerpipe/boilerpipe/1.1.0/boilerpipe-1.1.0.jar
DEBUG 2014-11-03 16:29:37.022 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/rome/rome/0.9/rome-0.9.jar
DEBUG 2014-11-03 16:29:37.022 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/jdom/jdom/1.0/jdom-1.0.jar
DEBUG 2014-11-03 16:29:37.022 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/gagravarr/vorbis-java-core/0.1/vorbis-java-core-0.1.jar
DEBUG 2014-11-03 16:29:37.022 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/com/googlecode/juniversalchardet/juniversalchardet/1.0.3/juniversalchardet-1.0.3.jar
DEBUG 2014-11-03 16:29:37.022 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/xmlpull/xmlpull/1.1.3.1/xmlpull-1.1.3.1.jar
DEBUG 2014-11-03 16:29:37.022 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/xpp3/xpp3_min/1.1.4c/xpp3_min-1.1.4c.jar
DEBUG 2014-11-03 16:29:37.022 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/xalan/xalan/2.7.1/xalan-2.7.1.jar
DEBUG 2014-11-03 16:29:37.022 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/xalan/serializer/2.7.1/serializer-2.7.1.jar
DEBUG 2014-11-03 16:29:37.023 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/xerces/xercesImpl/2.9.1/xercesImpl-2.9.1.jar
DEBUG 2014-11-03 16:29:37.023 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/xml-apis/xml-apis/1.3.04/xml-apis-1.3.04.jar
DEBUG 2014-11-03 16:29:37.023 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/xmlgraphics/xmlgraphics-commons/1.5/xmlgraphics-commons-1.5.jar
DEBUG 2014-11-03 16:29:37.023 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/javax/mail/mail/1.5.0-b01/mail-1.5.0-b01.jar
DEBUG 2014-11-03 16:29:37.023 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/javax/activation/activation/1.1/activation-1.1.jar
DEBUG 2014-11-03 16:29:37.023 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/apache/geronimo/specs/geronimo-jms_1.1_spec/1.1.1/geronimo-jms_1.1_spec-1.1.1.jar
DEBUG 2014-11-03 16:29:37.023 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/jsoup/jsoup/1.7.3/jsoup-1.7.3.jar
DEBUG 2014-11-03 16:29:37.023 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/jodd/jodd-core/3.4.10/jodd-core-3.4.10.jar
DEBUG 2014-11-03 16:29:37.023 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/jodd/jodd-lagarto/3.4.10/jodd-lagarto-3.4.10.jar
DEBUG 2014-11-03 16:29:37.023 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/mongodb/mongo-java-driver/2.11.3/mongo-java-driver-2.11.3.jar
DEBUG 2014-11-03 16:29:37.023 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/com/fifesoft/rsyntaxtextarea/2.5.1/rsyntaxtextarea-2.5.1.jar
DEBUG 2014-11-03 16:29:37.023 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/slf4j/slf4j-api/1.7.5/slf4j-api-1.7.5.jar
DEBUG 2014-11-03 16:29:37.023 [jorphan.] (): Did not find: C:/Users/sthomas/.m2/repository/org/slf4j/slf4j-nop/1.7.5/slf4j-nop-1.7.5.jar
DEBUG 2014-11-03 16:29:37.024 [jorphan.] (): listClasses.size()=0
WARN 2014-11-03 16:29:37.024 [jmeter.e] (): Did not find any functions
DEBUG 2014-11-03 16:29:37.026 [jmeter.e] (): About to replace in property of type: class org.apache.jmeter.testelement.property.IntegerProperty: 1
DEBUG 2014-11-03 16:29:37.026 [jmeter.e] (): Won't replace 1
DEBUG 2014-11-03 16:29:37.026 [jmeter.e] (): About to replace in property of type: class org.apache.jmeter.testelement.property.IntegerProperty: 1
DEBUG 2014-11-03 16:29:37.026 [jmeter.e] (): Won't replace 1
DEBUG 2014-11-03 16:29:37.026 [jmeter.e] (): About to replace in property of type: class org.apache.jmeter.testelement.property.TestElementProperty: org.apache.jmeter.control.LoopController@bdf5e5
DEBUG 2014-11-03 16:29:37.026 [jmeter.e] (): About to replace in property of type: class org.apache.jmeter.testelement.property.BooleanProperty: false
DEBUG 2014-11-03 16:29:37.026 [jmeter.e] (): Won't replace false
DEBUG 2014-11-03 16:29:37.026 [jmeter.e] (): About to replace in property of type: class org.apache.jmeter.testelement.property.IntegerProperty: 1
DEBUG 2014-11-03 16:29:37.026 [jmeter.e] (): Won't replace 1
DEBUG 2014-11-03 16:29:37.026 [jmeter.e] (): Replacement result: org.apache.jmeter.control.LoopController@bdf5e5
DEBUG 2014-11-03 16:29:37.027 [jmeter.e] (): About to replace in property of type: class org.apache.jmeter.testelement.property.TestElementProperty:
DEBUG 2014-11-03 16:29:37.027 [jmeter.e] (): About to replace in property of type: class org.apache.jmeter.testelement.property.CollectionProperty: []
DEBUG 2014-11-03 16:29:37.027 [jmeter.e] (): Replacement result: []
DEBUG 2014-11-03 16:29:37.027 [jmeter.e] (): Replacement result:
DEBUG 2014-11-03 16:29:37.027 [jmeter.e] (): About to replace in property of type: class org.apache.jmeter.testelement.property.StringProperty: www.google.com
DEBUG 2014-11-03 16:29:37.027 [jmeter.e] (): Replacement result: www.google.com
DEBUG 2014-11-03 16:29:37.027 [jmeter.e] (): About to replace in property of type: class org.apache.jmeter.testelement.property.IntegerProperty: 80
DEBUG 2014-11-03 16:29:37.027 [jmeter.e] (): Won't replace 80
DEBUG 2014-11-03 16:29:37.028 [jmeter.e] (): About to replace in property of type: class org.apache.jmeter.testelement.property.StringProperty: /
DEBUG 2014-11-03 16:29:37.028 [jmeter.e] (): Replacement result: /
DEBUG 2014-11-03 16:29:37.028 [jmeter.e] (): About to replace in property of type: class org.apache.jmeter.testelement.property.StringProperty: GET
DEBUG 2014-11-03 16:29:37.028 [jmeter.e] (): Replacement result: GET
DEBUG 2014-11-03 16:29:37.028 [jmeter.e] (): About to replace in property of type: class org.apache.jmeter.testelement.property.StringProperty: MY TEST PLAN
DEBUG 2014-11-03 16:29:37.028 [jmeter.e] (): Replacement result: MY TEST PLAN
DEBUG 2014-11-03 16:29:37.030 [jmeter.e] (): About to replace in property of type: class org.apache.jmeter.testelement.property.BooleanProperty: false
DEBUG 2014-11-03 16:29:37.030 [jmeter.e] (): Won't replace false
DEBUG 2014-11-03 16:29:37.030 [jmeter.e] (): About to replace in property of type: class org.apache.jmeter.testelement.property.IntegerProperty: 1
DEBUG 2014-11-03 16:29:37.030 [jmeter.e] (): Won't replace 1
INFO 2014-11-03 16:29:37.033 [jmeter.e] (): Starting setUp thread groups
INFO 2014-11-03 16:29:37.033 [jmeter.e] (): Starting setUp ThreadGroup: 1 :
INFO 2014-11-03 16:29:37.033 [jmeter.e] (): Starting 1 threads for group .
INFO 2014-11-03 16:29:37.033 [jmeter.e] (): Thread will continue on error
INFO 2014-11-03 16:29:37.035 [jmeter.t] (): Starting thread group number 1 threads 1 ramp-up 1 perThread 1000.0 delayedStart=false
INFO 2014-11-03 16:29:37.040 [jmeter.t] (): jmeterthread.startearlier=true (see jmeter.properties)
INFO 2014-11-03 16:29:37.040 [jmeter.t] (): Running PostProcessors in forward order
INFO 2014-11-03 16:29:37.042 [jmeter.t] (): Started thread group number 1
INFO 2014-11-03 16:29:37.042 [jmeter.e] (): Waiting for all setup thread groups to exit
DEBUG 2014-11-03 16:29:37.043 [jmeter.t] (): Subtracting node, stack size = 1
INFO 2014-11-03 16:29:37.045 [jmeter.t] (): Thread started: 1-1
DEBUG 2014-11-03 16:29:37.055 [jmeter.c] (): Calling next on: org.apache.jmeter.control.LoopController
INFO 2014-11-03 16:29:37.055 [jmeter.t] (): Thread finished: 1-1
DEBUG 2014-11-03 16:29:37.055 [jmeter.t] (): Ending thread 1-1
INFO 2014-11-03 16:29:37.056 [jmeter.e] (): All Setup Threads have ended
INFO 2014-11-03 16:29:37.063 [jmeter.e] (): No enabled thread groups found
INFO 2014-11-03 16:29:37.063 [jmeter.e] (): Notifying test listeners of end of test
INFO 2014-11-03 16:29:37.064 [jmeter.s] (): Default base='C:\Users\sthomas\workspace\JmeterProj'
</code></pre>
| 0 | 13,170 |
Apache Rewrite - Redirect Wildcard Subdomain and Handling Internal URL shortener
|
<p>I have problem in redirecting wild-card sub-domain and handing internal URL shortener.</p>
<p>Let's say I have an internal URL shortener in my app</p>
<pre><code>example.com/b/ABCDE
</code></pre>
<p>that will translate</p>
<pre><code>example.com/book/12345678-the-book-name
</code></pre>
<p>the script referred by <code>/b/</code> (I use PHP framework that could handle URL rule) will translate short ID <code>ABCDE</code> to the book real ID <code>12345678</code> (and the title "The Book Name") then redirect it the book's permanent URL <code>example.com/book/12345678-the-book-name</code></p>
<p>so then every time I spread a link about a book in websites like bulletin boards, micro-blogging sites, or physical media like posters or business cards, I use the short link (the <code>example.com/b/ABCDE</code>) instead of the permanent link (<code>example.com/book/12345678-the-book-name</code>).</p>
<p>next, I need to redirect all wild-card sub-domain to the main domain (<code>www.example.com</code>) while maintaining the request URI, e.g.</p>
<pre><code>http://random.example.com/book/11111111-some-book -> http://www.example.com/book/11111111-some-book
http://123456.example.com/book/22222222-another-book -> http://www.example.com/book/22222222-another-book
http://abcdefg.example.com/book/33333333-another-book-again -> http://www.example.com/book/33333333-another-book-again
</code></pre>
<p>by adding the rule below after all the rules I used</p>
<pre><code><VirtualHost *:80>
ServerName example.com
ServerAlias *.example.com
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.example.com [NC]
RewriteRule ^/(.*)$ http://www.example.com/$1 [R=301]
</VirtualHost>
</code></pre>
<p>Consequently the url with example.com domain and without prefix like below</p>
<pre><code>http://example.com/book/11111111-some-book
</code></pre>
<p>will translate to</p>
<pre><code>http://www.example.com/book/11111111-some-book
</code></pre>
<p>And, another consequence is that if the internal URL shortener use plain domain without the prefix, it will take two redirection to resolve. For example, </p>
<pre><code>http://example.com/b/ABCDE
</code></pre>
<p>will first be redirected to </p>
<pre><code>http://www.example.com/b/ABCDE
</code></pre>
<p>which then be redirected to </p>
<pre><code>http://www.example.com/book/12345678-the-book-name
</code></pre>
<p>Actually, I don't mind with the two-times redirection. But my SEO consultant said that the two-times redirection is bad for my site's SEO. (which I still don't know why)</p>
<p>So I tried change the last rule to below</p>
<pre><code><VirtualHost *:80>
ServerName example.com
ServerAlias *.example.com
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteCond %{REQUEST_URI} ^/b/(.*)$
RewriteRule . index.php [L]
RewriteCond %{HTTP_HOST} !^www.example.com [NC]
RewriteRule ^/(.*)$ http://www.example.com/$1 [R=301]
</VirtualHost>
</code></pre>
<p>I'm not very good at configuring Apache, but when I simulate above rule in <a href="http://htaccess.madewithlove.be/" rel="nofollow">http://htaccess.madewithlove.be/</a>, it works. But when I applied it to my server, it gave me <strong>400 Bad Request</strong> for the <code>example.com/p/ABCDE</code>.</p>
<p>So, my questions are</p>
<ol>
<li>Is my SEO consultant right about his argument? Is there any explanation that can back him up or is there a counter-argument?</li>
<li>Why the server gave <strong>400 Bad Request</strong>?</li>
<li>How to fix the redirection? I want to maintain the short URL (<code>example.com/b/ABCDE</code> without <code>www</code> prefix) but still in one redirection.</li>
</ol>
| 0 | 1,277 |
Android Eclipse failing to debug
|
<p>Debugging of my app is now suddenly broken. It has been fine up to now and I even reloaded a known good version of my entire code and it still fails to debug or even run. When I hit debug or run the app starts up and right when it is about to display the app, it crashes (before even entering the main view). I have a break point on the first line of code and it never even reaches it. It just goes to Source not found - The source attachment does not contains the source for the file DexFile.class.....
I am 100% certain all the code I have loaded is working, as it is a saved backup which was saved when last working.</p>
<p>Also, what is odd is that if I unplug the cable at this point, the app loads normally and works fine. So this is definitely a debugging issue. It is getting stuck somewhere at boot. I have restarted my computer and phone several times to no avail.</p>
<pre><code>LogCat:
`04-04 11:17:33.462: DEBUG/AndroidRuntime(4148): CheckJNI is OFF
04-04 11:17:33.462: DEBUG/dalvikvm(4148): creating instr width table
04-04 11:17:33.502: DEBUG/AndroidRuntime(4148): --- registering native functions ---
04-04 11:17:33.712: DEBUG/AndroidRuntime(4148): Shutting down VM
04-04 11:17:33.712: DEBUG/dalvikvm(4148): Debugger has detached; object registry had 1 entries
04-04 11:17:33.712: INFO/AndroidRuntime(4148): NOTE: attach of thread 'Binder Thread #3' failed
04-04 11:17:33.902: DEBUG/AndroidRuntime(4157): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
04-04 11:17:33.902: DEBUG/AndroidRuntime(4157): CheckJNI is OFF
04-04 11:17:33.902: DEBUG/dalvikvm(4157): creating instr width table
04-04 11:17:33.942: DEBUG/AndroidRuntime(4157): --- registering native functions ---
04-04 11:17:34.152: INFO/Process(107): Sending signal. PID: 4137 SIG: 9
04-04 11:17:34.152: INFO/ActivityManager(107): Force stopping package org.scanner uid=10110
04-04 11:17:34.162: ERROR/ActivityManager(107): fail to set top app changed!
04-04 11:17:34.182: INFO/UsageStats(107): Unexpected resume of com.htc.launcher while already resumed in org.scanner
04-04 11:17:34.192: INFO/ActivityManager(107): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=org.obdscanner/.activity.ObdReaderMainActivity }
04-04 11:17:34.202: DEBUG/AndroidRuntime(4157): Shutting down VM
04-04 11:17:34.202: DEBUG/dalvikvm(4157): Debugger has detached; object registry had 1 entries
04-04 11:17:34.212: INFO/AndroidRuntime(4157): NOTE: attach of thread 'Binder Thread #3' failed
04-04 11:17:34.222: WARN/InputManagerService(107): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@464105d8
04-04 11:17:34.242: INFO/ActivityManager(107): Start proc org.scanner for activity org.obdscanner/.activity.ReaderMainActivity: pid=4165 uid=10110 gids={3003, 3002}
04-04 11:17:34.332: WARN/ActivityThread(4165): Application org.scanner is waiting for the debugger on port 8100...
04-04 11:17:34.332: INFO/System.out(4165): Sending WAIT chunk
04-04 11:17:34.352: INFO/dalvikvm(4165): Debugger is active
04-04 11:17:34.472: DEBUG/Norton Community Watch/smrsd(3910): smrsd broadcast intent success!
04-04 11:17:34.512: ERROR/(3910): /data/data/com.symantec.monitor/app_log_item/1301930254.txt//data/data/com.symantec.monitor/app_log_item
04-04 11:17:34.542: INFO/System.out(4165): Debugger has connected
04-04 11:17:34.542: INFO/System.out(4165): waiting for debugger to settle...
04-04 11:17:34.632: INFO/global(3898): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
04-04 11:17:34.742: INFO/System.out(4165): waiting for debugger to settle...
04-04 11:17:34.862: DEBUG/dalvikvm(3898): GC_FOR_MALLOC freed 4492 objects / 274560 bytes in 41ms
04-04 11:17:34.942: INFO/System.out(4165): waiting for debugger to settle...
04-04 11:17:35.142: INFO/System.out(4165): waiting for debugger to settle...
04-04 11:17:35.342: INFO/System.out(4165): waiting for debugger to settle...
04-04 11:17:35.552: INFO/System.out(4165): waiting for debugger to settle...
04-04 11:17:35.752: INFO/System.out(4165): waiting for debugger to settle...
04-04 11:17:35.952: INFO/System.out(4165): waiting for debugger to settle...
04-04 11:17:36.157: INFO/System.out(4165): debugger has settled (1451)
04-04 11:17:37.296: DEBUG/dalvikvm(4165): threadid=1: still suspended after undo (sc=1 dc=1 s=Y)
</code></pre>
<p>`</p>
| 0 | 1,567 |
Error 422 Ajax Post using Laravel
|
<p>I'm trying to make a simple Ajax post using Laravel 5. I read that there is a issue with the Csrf Token matching and that i could put my uri into the VerifyCsrfToken expection to step around this. This part functions, however now I get a 422 error when i make the post. </p>
<p><a href="https://i.stack.imgur.com/8gIpr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8gIpr.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/HQ9U0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HQ9U0.png" alt="enter image description here"></a></p>
<p>Did I mess something up in my code? How can I get this working? Here is what I have:</p>
<p><strong>HTML:</strong></p>
<pre><code><div class = "q-form">
{!!Form::open(array('url' => 'questions')) !!}
<div class = "form-group">
{!! Form::hidden('user_id', $myid, ['class' => 'form-control']) !!}
{!!Form::label('title', 'Title:')!!}
{!!Form::text('title', null, ['class'=> 'form-control'])!!}
{!!Form::label('question', 'Question:')!!}
{!!Form::textarea('question', null, ['class'=> 'form-control area', 'placeholder' => 'What would you like to ask?'])!!}
{!!Form::submit('Ask!', ['class'=> 'btn btn-danger form-control ask'])!!}
</div>
{!! Form::close() !!}
</div>
</code></pre>
<p><strong>JS:</strong></p>
<pre><code>$('.ask').click(function(e) {
e.preventDefault();
var postData = $(this).serializeArray();
var base_url = 'http://rem-edu-es.eu1.frbit.net/';
$.ajax({
type: "POST",
url: base_url + "questions",
data: postData,
success: function (data) {
console.log(data);
}
});
});
</code></pre>
<p><strong>Controller:</strong></p>
<pre><code> public function book()
{
if(Request::ajax()){
return Response::json(Input::all());
}
}
</code></pre>
<p><strong>VerifyCsrfToken:</strong></p>
<pre><code> class VerifyCsrfToken extends BaseVerifier
{
protected $except = [
'book/*',
'book',
'questions'
];
}
</code></pre>
| 0 | 1,160 |
Sending image over sockets (ONLY) in Python, image can not be open
|
<p>I want to upload the image from client to server using ONLY sockets in Python. I designed a very simple protocol flow of how I would like to do this:</p>
<pre><code>CLIENT SERVER
SIZE 512 (send image size)
---------------------------------->
GOT SIZE
<----------------------------------
send image itself
---------------------------------->
GOT IMAGE
<----------------------------------
BYE BYE
---------------------------------->
server closes socket
</code></pre>
<p>Here's my client code:</p>
<pre><code>#!/usr/bin/env python
import random
import socket, select
from time import gmtime, strftime
from random import randint
image = "tux.png"
HOST = '127.0.0.1'
PORT = 6666
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (HOST, PORT)
sock.connect(server_address)
try:
# open image
myfile = open(image, 'rb')
bytes = myfile.read()
size = len(bytes)
# send image size to server
sock.sendall("SIZE %s" % size)
answer = sock.recv(4096)
print 'answer = %s' % answer
# send image to server
if answer == 'GOT SIZE':
sock.sendall(bytes)
# check what server send
answer = sock.recv(4096)
print 'answer = %s' % answer
if answer == 'GOT IMAGE' :
sock.sendall("BYE BYE ")
print 'Image successfully send to server'
myfile.close()
finally:
sock.close()
</code></pre>
<p>And my server, which receives images from clients:</p>
<pre><code>#!/usr/bin/env python
import random
import socket, select
from time import gmtime, strftime
from random import randint
imgcounter = 1
basename = "image%s.png"
HOST = '127.0.0.1'
PORT = 6666
connected_clients_sockets = []
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
connected_clients_sockets.append(server_socket)
while True:
read_sockets, write_sockets, error_sockets = select.select(connected_clients_sockets, [], [])
for sock in read_sockets:
if sock == server_socket:
sockfd, client_address = server_socket.accept()
connected_clients_sockets.append(sockfd)
else:
try:
data = sock.recv(4096)
txt = str(data)
if txt.startswith('SIZE'):
tmp = txt.split()
size = int(tmp[1])
print 'got size'
sock.send("GOT SIZE")
elif txt.startswith('BYE'):
sock.shutdown()
elif data:
myfile = open(basename % imgcounter, 'wb')
data = sock.recv(40960000)
if not data:
myfile.close()
break
myfile.write(data)
myfile.close()
sock.send("GOT IMAGE")
sock.shutdown()
except:
sock.close()
connected_clients_sockets.remove(sock)
continue
imgcounter += 1
server_socket.close()
</code></pre>
<p>For the example image:</p>
<p><a href="https://i.stack.imgur.com/CNyA4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CNyA4.png" alt="enter image description here"></a></p>
<p>The client prints out messages, that suggest, that it send the image to server successfully:</p>
<pre><code>answer = GOT SIZE
answer = GOT IMAGE
Image successfully send to server
</code></pre>
<p>The image is created at server's side, but I can not open it. And yes, I tried different images. With no success. I can't open them at server's side, even though they are available there. </p>
<p>Thanks to @BorrajaX, I managed to make it work! Thanks! :)</p>
<pre><code>#!/usr/bin/env python
import random
import socket, select
from time import gmtime, strftime
from random import randint
imgcounter = 1
basename = "image%s.png"
HOST = '127.0.0.1'
PORT = 6666
connected_clients_sockets = []
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
connected_clients_sockets.append(server_socket)
while True:
read_sockets, write_sockets, error_sockets = select.select(connected_clients_sockets, [], [])
for sock in read_sockets:
if sock == server_socket:
sockfd, client_address = server_socket.accept()
connected_clients_sockets.append(sockfd)
else:
try:
data = sock.recv(4096)
txt = str(data)
if data:
if data.startswith('SIZE'):
tmp = txt.split()
size = int(tmp[1])
print 'got size'
sock.sendall("GOT SIZE")
elif data.startswith('BYE'):
sock.shutdown()
else :
myfile = open(basename % imgcounter, 'wb')
myfile.write(data)
data = sock.recv(40960000)
if not data:
myfile.close()
break
myfile.write(data)
myfile.close()
sock.sendall("GOT IMAGE")
sock.shutdown()
except:
sock.close()
connected_clients_sockets.remove(sock)
continue
imgcounter += 1
server_socket.close()
</code></pre>
| 0 | 2,943 |
get value in array in json object android
|
<p>i have a json like this, <p></p>
<pre><code>{
"id": 293,
"type": "post",
"slug": "a-box-rd",
"url": "http:\/\/www.godigi.tv\/blog\/2013\/07\/01\/a-box-rd\/",
"status": "publish",
"title": "A Box R&#038;D",
"title_plain": "A Box R&#038;D",
"content": "",
"excerpt": "",
"date": "2013-07-01 09:09:25",
"modified": "2013-07-01 09:18:09",
"categories": [
{
"id": 15,
"slug": "info",
"title": "Info",
"description": "",
"parent": 0,
"post_count": 7
}
],
"tags": [
],
"author": {
"id": 2,
"slug": "eka2013",
"name": "ekawijaya",
"first_name": "",
"last_name": "",
"nickname": "ekawijaya",
"url": "",
"description": ""
},
"comments": [
],
"attachments": [
{
"id": 298,
"url": "http:\/\/www.godigi.tv\/wp-content\/uploads\/2013\/07\/rnd.jpg",
"slug": "rnd",
"title": "rnd",
"description": "",
"caption": "",
"parent": 293,
"mime_type": "image\/jpeg",
"images": {
"full": {
"url": "http:\/\/www.godigi.tv\/wp-content\/uploads\/2013\/07\/rnd.jpg",
"width": 528,
"height": 493
},
"thumbnail": {
"url": "http:\/\/www.godigi.tv\/wp-content\/uploads\/2013\/07\/rnd-150x150.jpg",
"width": 150,
"height": 150
},
"medium": {
"url": "http:\/\/www.godigi.tv\/wp-content\/uploads\/2013\/07\/rnd-300x280.jpg",
"width": 300,
"height": 280
},
"large": {
"url": "http:\/\/www.godigi.tv\/wp-content\/uploads\/2013\/07\/rnd.jpg",
"width": 528,
"height": 493
},
"post-thumbnail": {
"url": "http:\/\/www.godigi.tv\/wp-content\/uploads\/2013\/07\/rnd-150x150.jpg",
"width": 150,
"height": 150
},
"custom-small": {
"url": "http:\/\/www.godigi.tv\/wp-content\/uploads\/2013\/07\/rnd-160x90.jpg",
"width": 160,
"height": 90
},
"custom-medium": {
"url": "http:\/\/www.godigi.tv\/wp-content\/uploads\/2013\/07\/rnd-320x180.jpg",
"width": 320,
"height": 180
},
"custom-large": {
"url": "http:\/\/www.godigi.tv\/wp-content\/uploads\/2013\/07\/rnd-528x360.jpg",
"width": 528,
"height": 360
},
"custom-full": {
"url": "http:\/\/www.godigi.tv\/wp-content\/uploads\/2013\/07\/rnd.jpg",
"width": 528,
"height": 493
}
}
}
],
"comment_count": 0,
"comment_status": "open",
"custom_fields": {
"dp_video_poster": [
"http:\/\/www.godigi.tv\/wp-content\/uploads\/2013\/07\/rnd.jpg"
],
"views": [
"7"
],
"likes": [
"0"
],
"dp_video_file": [
"http:\/\/www.godigi.tv\/wp-content\/uploads\/2013\/07\/03-A-BOX-RD-ada-pak-bulit.mp4"
]
}
},
</code></pre>
<p>and i use the code like this => <p></p>
<pre><code>jsonarray = jsonobject.getJSONArray("posts");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
JSONObject jsoncustom;
jsoncustom = jsonobject.getJSONObject("custom_fields");
JSONArray araycus = jsoncustom.getJSONArray("dp_video_poster");
String urlvid = araycus.getString(i);
// Retrive JSON Objects
map.put("title", jsonobject.getString("title"));
map.put("date", jsonobject.getString("date"));
map.put("dp_video_poster", urlvid);
// Set the JSON Objects into the array
arraylist.add(map);
}
</code></pre>
<p>what i expect for output is : <p>
title =<p>
date = <p>
poster (this is in folder dp_video_poster) = <p>
video (this is in folder dp_video_file) = <p></p>
<p>can any body help me with this?<p>
thanks in advance<p></p>
| 0 | 2,133 |
Revised Simplex Method - Matlab Script
|
<p>I've been asked to write down a Matlab program in order to solve LPs using the <strong>Revised Simplex Method</strong>. </p>
<p>The code I wrote runs without problems with input data although I've realised it doesn't solve the problem properly, as it does not update the inverse of the basis B (the real core idea of the abovementioned method).</p>
<p>The problem is only related to a part of the code, the one in the bottom of the script aiming at:</p>
<p><strong>Computing the new inverse basis B^-1 by performing elementary row operations on [B^-1 u] (pivot row index is l_out). The vector u is transformed into a unit vector with u(l_out) = 1 and u(i) = 0 for other i.</strong></p>
<p>Here's the code I wrote:</p>
<pre><code> %% Implementation of the revised Simplex. Solves a linear
% programming problem of the form
%
% min c'*x
% s.t. Ax = b
% x >= 0
%
% The function input parameters are the following:
% A: The constraint matrix
% b: The rhs vector
% c: The vector of cost coefficients
% C: The indices of the basic variables corresponding to an
% initial basic feasible solution
%
% The function returns:
% x_opt: Decision variable values at the optimal solution
% f_opt: Objective function value at the optimal solution
%
% Usage: [x_opt, f_opt] = S12345X(A,b,c,C)
% NOTE: Replace 12345X with your own student number
% and rename the file accordingly
function [x_opt, f_opt] = SXXXXX(A,b,c,C)
%% Initialization phase
% Initialize the vector of decision variables
x = zeros(length(c),1);
% Create the initial Basis matrix, compute its inverse and
% compute the inital basic feasible solution
B=A(:,C);
invB = inv(B);
x(C) = invB*b;
%% Iteration phase
n_max = 10; % At most n_max iterations
for n = 1:n_max % Main loop
% Compute the vector of reduced costs c_r
c_B = c(C); % Basic variable costs
p = (c_B'*invB)'; % Dual variables
c_r = c' - p'*A; % Vector of reduced costs
% Check if the solution is optimal. If optimal, use
% 'return' to break from the function, e.g.
J = find(c_r < 0); % Find indices with negative reduced costs
if (isempty(J))
f_opt = c'*x;
x_opt = x;
return;
end
% Choose the entering variable
j_in = J(1);
% Compute the vector u (i.e., the reverse of the basic directions)
u = invB*A(:,j_in);
I = find(u > 0);
if (isempty(I))
f_opt = -inf; % Optimal objective function cost = -inf
x_opt = []; % Produce empty vector []
return % Break from the function
end
% Compute the optimal step length theta
theta = min(x(C(I))./u(I));
L = find(x(C)./u == theta); % Find all indices with ratio theta
% Select the exiting variable
l_out = L(1);
% Move to the adjacent solution
x(C) = x(C) - theta*u;
% Value of the entering variable is theta
x(j_in) = theta;
% Update the set of basic indices C
C(l_out) = j_in;
% Compute the new inverse basis B^-1 by performing elementary row
% operations on [B^-1 u] (pivot row index is l_out). The vector u is trans-
% formed into a unit vector with u(l_out) = 1 and u(i) = 0 for
% other i.
M=horzcat(invB,u);
[f g]=size(M);
R(l_out,:)=M(l_out,:)/M(l_out,j_in); % Copy row l_out, normalizing M(l_out,j_in) to 1
u(l_out)=1;
for k = 1:f % For all matrix rows
if (k ~= l_out) % Other then l_out
u(k)=0;
R(k,:)=M(k,:)-M(k,j_in)*R(l_out,:); % Set them equal to the original matrix Minus a multiple of normalized row l_out, making R(k,j_in)=0
end
end
invM=horzcat(u,invB);
% Check if too many iterations are performed (increase n_max to
% allow more iterations)
if(n == n_max)
fprintf('Max number of iterations performed!\n\n');
return
end
end % End for (the main iteration loop)
end % End function
%% Example 3.5 from the book (A small test problem)
% Data in standard form:
% A = [1 2 2 1 0 0;
% 2 1 2 0 1 0;
% 2 2 1 0 0 1];
% b = [20 20 20]';
% c = [-10 -12 -12 0 0 0]';
% C = [4 5 6]; % Indices of the basic variables of
% % the initial basic feasible solution
%
% The optimal solution
% x_opt = [4 4 4 0 0 0]' % Optimal decision variable values
% f_opt = -136 % Optimal objective function cost
</code></pre>
| 0 | 2,074 |
Sort List of HashMaps based on hashMap values [not keys]
|
<p>Here is what I have- </p>
<p>How I can include multiple keys and their values in comparison? Right now I am only using employeeId but I wanted to include departmentId and other in my comparison for sorting...</p>
<pre><code>import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class Tester {
boolean flag = false ;
public static void main(String args[]) {
Tester tester = new Tester() ;
tester.printValues() ;
}
public void printValues ()
{
List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>() ;
HashMap<String,Object> map = new HashMap<String,Object>();
map = new HashMap<String,Object>();
map.put("employeeId", new Integer(1234)) ;
map.put("departmentId", new Integer(110)) ;
map.put("someFlag", "B") ;
map.put("eventTypeId", new Integer(11)) ;
map.put("startDate", new Date() ) ;
map.put("endDate", new Date() ) ;
list.add(map);
map = new HashMap<String,Object>();
map.put("employeeId", new Integer(456)) ;
map.put("departmentId", new Integer(100)) ;
map.put("someFlag", "B") ;
map.put("eventTypeId", new Integer(11)) ;
map.put("startDate", new Date() ) ;
map.put("endDate", new Date() ) ;
list.add(map);
map = new HashMap<String,Object>();
map.put("employeeId", new Integer(1234)) ;
map.put("departmentId", new Integer(10)) ;
map.put("someFlag", "B") ;
map.put("eventTypeId", new Integer(17)) ;
map.put("startDate", new Date() ) ;
map.put("endDate", new Date() ) ;
list.add(map);
map = new HashMap<String,Object>();
map.put("employeeId", new Integer(1234)) ;
map.put("departmentId", new Integer(99)) ;
map.put("someFlag", "B") ;
map.put("eventTypeId", new Integer(11)) ;
map.put("startDate", new Date() ) ;
map.put("endDate", new Date() ) ;
list.add(map);
map = new HashMap<String,Object>();
map.put("employeeId", new Integer(1234)) ;
map.put("departmentId", new Integer(100)) ;
map.put("someFlag", "B") ;
map.put("eventTypeId", new Integer(11)) ;
map.put("startDate", new Date() ) ;
map.put("endDate", new Date() ) ;
list.add(map);
map = new HashMap<String,Object>();
map.put("employeeId", new Integer(567)) ;
map.put("departmentId", new Integer(200)) ;
map.put("someFlag", "P") ;
map.put("eventTypeId", new Integer(12)) ;
map.put("startDate", new Date() ) ;
map.put("endDate", new Date() ) ;
list.add(map);
Collections.sort ( list , new HashMapComparator2 () ) ;
for( int i = 0 ; i < list.size() ; i ++ ) {
System.out.println(list.get(i));
}
System.out.println("======================================");
flag = true ; // desc
Collections.sort ( list , new HashMapComparator2 () ) ;
for( int i = 0 ; i < list.size() ; i ++ ) {
System.out.println(list.get(i));
}
}
public class HashMapComparator2 implements Comparator
{
public int compare ( Object object1 , Object object2 )
{
if ( flag == false )
{
Integer obj1Value = ( Integer ) ( ( HashMap ) object1 ).get ( "employeeId" ) ;
Integer obj2Value = ( Integer ) ( ( HashMap ) object2 ).get ( "employeeId" ) ;
return obj1Value.compareTo ( obj2Value ) ;
}
else
{
Integer obj1Value = ( Integer ) ( ( HashMap ) object1 ).get ( "employeeId" ) ;
Integer obj2Value = ( Integer ) ( ( HashMap ) object2 ).get ( "employeeId" ) ;
return obj2Value.compareTo ( obj1Value ) ;
}
}
}
}
</code></pre>
| 0 | 1,872 |
How to return an ArrayList <Integer>?
|
<p>I am working on a question from an assignment. It is called the 3n+1 problem. The task is to get an integer from user (not 1 or negative number) and based on the number input (n), if it is even - divide by 2, and if it is negative - multiple n * 3 + 1.</p>
<p>The method I MUST use is as follows:</p>
<pre><code>public static ArrayList<Integer> getHailstoneSequence(int n) {
</code></pre>
<p>^ this part is mandatory for my assignment, so it is necessary for me to work with an ArrayList of Integers. </p>
<p>I am struggling to make my program work. I can't figure out if I should store the input in the main method OR in my definition class. I also am not sure how to have the loop execute for even numbers in the main method without the redundancy of already having it stated in the definition class ( where my getHailstoneSequence() method is located).</p>
<p>Here is the code I have: <strong>(DEFINITION CLASS)</strong></p>
<pre><code>package question7;
import java.util.ArrayList;
public class HailstoneSequence {
// Method for computing the Hailstone Sequence:
public static ArrayList<Integer> getHailstoneSequence(int n) {
ArrayList<Integer> hailstoneSequence = new ArrayList<Integer>();
if (n % 2 == 0) {
n = n / 2;
hailstoneSequence.add(n);
}
else {
n = (n * 3) + 1;
hailstoneSequence.add(n);
}
return hailstoneSequence;
}
}
</code></pre>
<p>I am unsure how to include the method I created above into the main method for printing. I want the output to look like this (example):</p>
<p>5 is odd, so we make 3N+1: 16
16 is even, so we take half: 8
8 is even, so we take half: 4
4 is even, so we take half: 2
2 is even, so we take half: 1</p>
<p>And have the program stop whe n = 1</p>
<p>Here is what I have in my <strong>main method</strong> to date:</p>
<pre><code>package question7;
import java.util.ArrayList;
import java.util.Scanner;
public class HailstoneSequenceTest {
public static void main(String[] args) {
Scanner hailstone = new Scanner(System.in);
System.out.println("To begin, please enter a positive integer that is not 1:");
int n = hailstone.nextInt();
ArrayList<Integer> list = HailstoneSequence.getHailstoneSequence(n);
for (int sequence : list) {
try {
if (n > 1) {
System.out.println("Great choice! Let's begin!");
System.out.println();
while (n % 2 == 0) {
System.out.println(n +
" is even, so we take half: " +
HailstoneSequence.getHailstoneSequence(n));
list.add(n);
if (n == 1) break;
while (n % 2 != 0) {
System.out.println(n +
" is odd, so I make 3n+1: " +
HailstoneSequence.getHailstoneSequence(n));
list.add(n);
if (n == 1) break;
}
// while (n == 1) {
// System.out.println(sequence);
// break;
}
}
}
catch (Exception error) {
while (n <= 1) {
System.out
.println("You did not enter a valid positive, greater than 1 integer. Please try again: ");
System.out.println();
n = hailstone.nextInt();
}
// End of HailstoneSequenceTest class
hailstone.close();
}
}
}
}
// }
</code></pre>
<p>Does anyone have any idea where I am going wrong? I know my code is probably wrong if multiple ways, I am just not sure where to start.</p>
<p>Do I need a for loop to hold the characteristics and increment ect.. ?</p>
<p>When I try to do this the way I know, it says I must return a ArrayList not an Int .</p>
<p>Please advise. </p>
| 0 | 1,961 |
Using Tables in RTF
|
<p>I need to create a table in an RTF file. However I am not familiar with RΤF. Here is an example of a text file that these RTF files are supposed to replace:</p>
<pre><code> GENERAL JOURNAL
Page 1
Date Description Post Ref Debit Credit
------------------------------------------------------------------------------
2011
Dec 1 Utilities Expense 512 250.00
Cash 111 250.00
Paid electric bill for November,
Check No. 1234
2 Cash 111 35.00
Accounts Receivable / Customer Name 115/√ 30.00
Interest Income 412 5.00
Receipt of payment on account
from Customer, Check No. 5678
. . .
</code></pre>
<p>The table is supposed to have borders, but I don't know how to do this either. Some cells have to have special borders on the bottom as in this file:</p>
<pre><code> Company Name
Schedule of Accounts Receivable
December 31, 2011
Name Balance
------------------------------------------------------------------------------
Adams, John 354.24
Jefferson, Thomas 58.35
Washington, George 754.58
--------
1167.17
========
</code></pre>
<p>I am aware of the <code>\cell</code>, <code>\row</code> etc., but I cannot figure out how to use them properly as the documentation that I have found is not very good. Please help.</p>
| 0 | 1,289 |
iPad Safari IOS 5 window.close() closing wrong window
|
<p>We have an iPad application that's working on our older iPads.</p>
<p>We open external links using
var x = window.open(url)</p>
<p>at the end of the day, when the user closes this part of the app, we go through all the windows it opened and do x.close() for each one and everything is okie dokie.</p>
<p>Testing on the new iPad with IOS 5 and the lovely tabs,
opening the new windows (although now they open as tabs) is fine, but doing x.close() doesn't seem to necessarily close x, it may close window y or z. Doing x.focus() or y.focus() works just fine, the correct tab comes into focus, but close seems to just pick whatever tab it wants.</p>
<p>Is this a bug or am I doing something wrong? Example program:</p>
<pre><code><html>
<head></head>
<body>
<script>
//The openWindow array will hold the handles of all open child windows
var openWindow = new Array();
var win1;
var win2;
//Track open adds the new child window handle to the array.
function trackOpen(winName) {
openWindow[openWindow.length]=winName;
}
//loop over all known child windows and try to close them. No error is
//thrown if a child window(s) was already closed.
function closeWindows() {
var openCount = openWindow.length;
for(r=openCount-1;r>=0;r--) {
openWindow[r].close();
}
}
//Open a new child window and add it to the tracker.
function open1() {
win1 = window.open("http://www.yahoo.com");
trackOpen(win1);
}
//Open a different child window and add it to the tracker.
function open2() {
win2 = window.open("http://www.google.com");
trackOpen(win2);
}
//Open whatever the user enters and add it to the tracker
function open3() {
var newURL = document.getElementById("url").value;
var win3= window.open(newURL);
trackOpen(win3);
}
</script>
<input type="button" value="Open 1" onclick="open1()">
<input type="button" value="Open 2" onclick="open2()">
<input type="button" value="Focus 1" onclick="win1.focus()">
<input type="button" value="Focus 2" onclick="win2.focus()">
<input type="button" value="Close 1" onclick="win1.close()">
<input type="button" value="Close 2" onclick="win2.close()">
URL: <input type="text" id="url"> <input type="button" value="Open URL" onclick="open3()">
<input type="button" value="Close All" onclick="closeWindows()">
</body>
</html>
</code></pre>
| 0 | 1,113 |
Convert base64 encoding to pdf
|
<p>I tried multiple solution but every time I am getting error that pdf can not be open. This is the edited code with actual data stream that need to be converted in .pdf.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;
using System.Threading;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
try
{
string base64BinaryStr = "Q29tcGFueSBTZXJ2aWNpbmcNCjEuCVRvb2xiYXIgQ29tcGFueSBTZXJ2aWNpbmcgU2VsZWN0IEFuIEFjY291bnQNCjIuCVRvb2xiYXJfQ29tcGFueSBTZXJ2aWNpbmcgRG91YmxlIENsaWNrIG9uIGFuIEFjY291bnQNCjMuCVRvb2xiYXIgQ29tcGFueSBTZXJ2aWNpbmdfRW50ZXIgYWNjb3VudCBudW1iZXIgaW4gdGhlIE51bWJlciBmaWVsZCBvZiB0aGUgQWNvdW50IFNlYXJjaCBTZWN0aW9uDQo0LglUb29sYmFyIENvbXBhbnkgU2VydmljaW5nX1JldHVybg0KNS4JVG9vbGJhciBDb21wYW55IFNlcnZpY2luZ19DbG9zZQ0KNi4JVG9vbGJhciBDb21wYW55IFNlcnZpY2luZ19NZW1vc19DbGVhciBCdXR0b24NCjcuCVRvb2xiYXJfQ29tcGFueSBTZXJ2aWNpbmdfTWVtb3NfQWRkIEJ1dHRvbg0KOC4JVG9vbGJhcl9Db21wYW55IFNlcnZpY2luZ19NZW1vc19BbHQtQSBUbyBBZGQgQSBNZW1vDQo5LglUb29sYmFyX0NvbXBhbnkgU2VydmljaW5nX01lbW9zX0NoYW5nZQ0KMTAuCVRvb2xiYXJfQ29tcGFueSBTZXJ2aWNpbmdfTWVtb3NfRGVsZXRlIEJ1dHRvbg0KMTEuCVRvb2xiYXJfQ29tcGFueSBTZXJ2aWNpbmdfTWVtb3NfUmVmcmVzaA0KMTIuCVRvb2xiYXJfQ29tcGFueSBTZXJ2aWNpbmdfTWVtb3NfQ2xvc2UgQnV0dG9uDQoxMy4JVG9vbGJhcl9Db21wYW55IFNlcnZpY2luZ19TcGVuZGluZyBDb250cm9sX0VsaXRlDQoxNC4JVG9vbGJhcl9Db21wYW55IFNlcnZpY2luZ19TcGVuZGluZyBDb250cm9sX0Rlc2NyaXB0aW9uIGJ1dHRvbg0KMTUuCVRvb2xiYXJfQ29tcGFueSBTZXJ2aWNpbmdfU3BlbmRpbmcgQ29udHJvbF9EZXNjcmlwdGlvbiBidXR0b25fU2VsZWN0IFNwZW5kaW5nIENvbnRyb2wNCjE2LglUb29sYmFyX0NvbXBhbnkgU2VydmljaW5nX1NwZW5kaW5nIENvbnRyb2xfRGVzY3JpcHRpb24gYnV0dG9uX1NwZW5kaW5nIENvbnRyb2wgTGluayB0byBWTA0KMTcuCVRvb2xiYXJfQ29tcGFueSBTZXJ2aWNpbmdfU3BlbmRpbmcgQ29udHJvbF9EZXNjcmlwdGlvbl9DbG9zZSBidXR0b24NCjE4LglUb29sYmFyX0NvbXBhbnkgU2VydmljaW5nX1NwZW5kaW5nIENvbnRyb2xfU2VsZWN0IEFsbF9WaWV3IFRyYW5zYWN0aW9ucw0KMTkuCVRvb2xiYXJfQ29tcGFueSBTZXJ2aWNpbmdfU3BlbmRpbmcgQ29udHJvbF9TcGVuZGluZyBDb250cm9sIExpbmsgdG8gVkwNCjIwLglUb29sYmFyX0NvbXBhbnkgU2VydmljaW5nX1NwZW5kaW5nIENvbnRyb2xfQ2FuY2VsIGJ1dHRvbg0K";
byte[] sPDFDecoded = Convert.FromBase64String(base64BinaryStr);
BinaryWriter writer = new BinaryWriter(File.Open(@"c:\Users\u316383\Documents\pdf9.pdf", FileMode.CreateNew));
writer.Write(sPDFDecoded);
string s = Encoding.UTF8.GetString(sPDFDecoded);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
}
}
}
</code></pre>
<p>}</p>
| 0 | 1,621 |
iphone app - how to get the current location only once and store that to be used in another function?
|
<p>I've been working on this for the past 2 weeks - i have an app that shows a legible route on a map that goes from a start point to a destination point. the destination point is the users address (as defined/entered by the user in the settings menu we have set up) and if i hard code the start point, the map, route and application all work fine. once i try to implement anything that involves using the cllocation or cllocationmanager, it crashes and gives me a thread error (there are 3). </p>
<p>Here is the current view controller header & implementation file for this:</p>
<pre><code>#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import "MapView.h"
#import "Place.h"
#import <CoreLocation/CoreLocation.h>
@interface HomeMapViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>{
IBOutlet UILabel *HomeAddressLabel;
}
@property (weak, nonatomic) IBOutlet MKMapView *MapView;
@property (strong, nonatomic) IBOutlet CLLocationManager *location;
@end
</code></pre>
<p>implementation file:</p>
<pre><code>#import "HomeMapViewController.h"
@interface HomeMapViewController ()
@end
@implementation HomeMapViewController
@synthesize MapView;
@synthesize location;
double lat = 37.331706;
double lon = -122.030598;
- (id)initWithNibNameNSString *)nibNameOrNil bundleNSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
//Retrieve saved address before view loads
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *HomeAddress = [defaults objectForKey:@"HomeAddress"];
NSString *HomeCity = [defaults objectForKey:@"HomeCity"];
NSString *HomeProvince = [defaults objectForKey:@"HomeProvince"];
NSString *HomeZip = [defaults objectForKey:@"HomeZip"];
NSString *HomeCountry = [defaults objectForKey:@"HomeCountry"];
NSString *HomeAddressFull = [NSString stringWithFormat:@"%@, %@, %@, %@, %@", HomeAddress, HomeCity, HomeProvince, HomeZip, HomeCountry];
//Set address label to saved address values
HomeAddressLabel.text = HomeAddressFull;
//Map Route Code
MapView* mapView = [[MapView alloc] initWithFrame:
CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
//Shows user location
[self.MapView setShowsUserLocation:YES];
//set which mapview to show
[self.MapView addSubview:mapView];
self.location = [[CLLocationManager alloc]init];
location.delegate = self;
location.desiredAccuracy=kCLLocationAccuracyBest;
location.distanceFilter = kCLLocationAccuracyBestForNavigation;//constant update of device location
[location startUpdatingLocation];
Place* start = [[Place alloc] init];
start.name = @"Start Location";
start.description = @"You started here.";
//^should be changed to current location once that is implemented
//start.latitude = 37.331706;
//start.longitude = -122.030598;
start.latitude = lat;
start.longitude = lon;
//start.latitude = location.location.coordinate.latitude;
//start.longitude = location.location.coordinate.longitude;
//Geocoder Code
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:HomeAddressFull completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(@"Error: %@", [error localizedDescription]);
return;
}
for (id object in placemarks) {
CLPlacemark *placemark = object;
Place* destination = [[Place alloc] init];
destination.name = @"Destination";
destination.description = [NSString stringWithFormat:@"%@, %@, %@", HomeAddress, HomeCity, HomeProvince];
destination.latitude = placemark.location.coordinate.latitude;
destination.longitude = placemark.location.coordinate.longitude;
[mapView showRouteFrom:start toestination];
}
}];
[super viewDidLoad];
}
- (void)locationManagerCLLocationManager *)manager didUpdateToLocationCLLocation *)newLocation fromLocationCLLocation *)oldLocation{
[manager stopUpdatingLocation];
}
//************NEW METHOD
-(void)locationManagerCLLocationManager *)manager didFailWithErrorNSError *)error{
NSString *msg = @"Error obtraining location:";
UIAlertView *alert;
alert = [[UIAlertView alloc]
initWithTitle:@"Error"
message:msg delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alert show];
}
- (void)viewDidUnload
{
[self setMapView:nil];
HomeAddressLabel = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientationUIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
</code></pre>
<p>I'd basically like to ask if anyone can help shed some light on how I might go about getting the users current location coordinates and storing them as the start.latitude and start.longitude values so the route shows a pathway from the users current location to their destination. the route is not supposed to update itself as the user moves, I would just like to have an annotation/placemark on the users current location and destination (as i do have) and then the blue point (aka the user) will be able to see themselves move along the route they are to take. I've tried all the suggestions on here - and some havent worked at all, some worked only once and then after that it failed to work again (even after resetting the simulator content!). some links are relevant but very outdated so the methods there don't work.</p>
<p>And here i was thinking getting the users current location coordinates would be the easier task of this function!</p>
| 0 | 2,057 |
ASP.NET Multiple controls with the same ID 'x' were found. FindControl
|
<p>Getting the following error</p>
<p>Multiple controls with the same ID 'ltlItemCode' were found. FindControl requires that controls have unique IDs.</p>
<p>This Error does not happen on page loads but when I change the value of a drop down which has AutoPostBack="true".</p>
<p>Code is </p>
<pre><code> //Number of Services
numberofServices = Int32.Parse(DCCFunctions.GetNumServicesPerRoom(roomId.ToString()));
additionalServices = new UserControls_AdditionalService[numberofServices - 1];
String htmlTable = String.Empty;
Int32 cell = 1;
Int32 rows = numberofServices;
Int32 cols = 4;
TableHeaderRow h = new TableHeaderRow();
TableHeaderCell hc1 = new TableHeaderCell();
hc1.Text = "Item Description";
h.Cells.Add(hc1);
TableHeaderCell hc2 = new TableHeaderCell();
hc2.Text = "Item Price";
h.Cells.Add(hc2);
TableHeaderCell hc3 = new TableHeaderCell();
hc3.Text = "Item Quantity";
h.Cells.Add(hc3);
TableHeaderCell hc4 = new TableHeaderCell();
hc4.Text = "Item Sub Total";
h.Cells.Add(hc4);
Table1.Rows.Add(h);
// Open database connection
DBConnection conn = new DBConnection();
// Retrieve details
SqlCommand sqlGetDetails = conn.SetStoredProcedure("spGetAdditionalServicesDetails");
DBConnection.AddNewParameter(sqlGetDetails, "@roomId", ParameterDirection.Input, SqlDbType.Int, roomId);
try
{
conn.Open();
SqlDataReader reader_list = sqlGetDetails.ExecuteReader();
if (reader_list.HasRows)
{
while (reader_list.Read())
{
//returnVal = reader_list["Num"].ToString();
htmlTable += "&lt;tr>" + Environment.NewLine;
TableRow r = new TableRow();
additionalServices[cell - 1] = (ASP.usercontrols_additionalservice_ascx)LoadControl("~/UserControls/AdditionalService.ascx");
Literal ItemCode = (Literal)additionalServices[cell - 1].FindControl("ltlItemCode") as Literal;
ItemCode.Text = reader_list["itemDescription"].ToString();
Literal ItemPrice = (Literal)additionalServices[cell - 1].FindControl("ltlItemPrice") as Literal;
ItemPrice.Text = "&euro;" + reader_list["unitPrice"].ToString();
Literal ItemTotal = (Literal)additionalServices[cell - 1].FindControl("ltlTotalPrice") as Literal;
ItemTotal.Text = "&euro;" + "0";
TableCell ItemCodeCell = new TableCell();
ItemCodeCell.Controls.Add((Literal)additionalServices[cell - 1].FindControl("ltlItemCode") as Literal);
TableCell ItemCodePriceCell = new TableCell();
ItemCodePriceCell.Controls.Add((Literal)additionalServices[cell - 1].FindControl("ltlItemPrice") as Literal);
TableCell ItemCodeTotalCell = new TableCell();
ItemCodeTotalCell.Controls.Add((Literal)additionalServices[cell - 1].FindControl("ltlTotalPrice") as Literal);
TableCell c = new TableCell();
DropDownList qtyList = (DropDownList)additionalServices[cell - 1].FindControl("qtyList") as DropDownList;
qtyList.Items.Add(new System.Web.UI.WebControls.ListItem("Select Quantity...", "0"));
qtyList.DataBind();
for (Int32 count = 1; count < 101; count++)
{
qtyList.Items.Add(new System.Web.UI.WebControls.ListItem(count.ToString(),count.ToString()));
}
//c.ColumnSpan = 5;
c.Controls.Add((DropDownList)additionalServices[cell - 1].FindControl("qtyList") as DropDownList);
r.Cells.Add(ItemCodeCell);
r.Cells.Add(ItemCodePriceCell);
r.Cells.Add(c);
r.Cells.Add(ItemCodeTotalCell);
//r.Controls.Add(additionalServices[cell - 1]);
//cell += 1;
// Add the row
Table1.Rows.Add(r);
}
}
reader_list.Close();
}
catch (Exception ex)
{
M1Utils.ErrorHandler(ex);
}
finally
{
conn.Close();
}`
</code></pre>
| 0 | 1,900 |
How to make dynamic content display across a grid using Django with Bootstrap?
|
<p>I'm working on a Django project with a homepage similar to StackOverflow's: it displays snippets of incoming user-generated content in a single main column. However, I'd like those content snippets to display across rows of 3 filling up the homepage (think [Pinterest pinboard page][2] or a grid layout blog).</p>
<p>I'm using Bootstrap's grid system, but realized I don't know the right combination of Python/Django template magic + Bootstrap to get that incoming content to populate across a grid. Can someone spell this out for me?</p>
<p>I want...</p>
<pre><code> {% for question in questions.paginator.page %}
{% question_list_item question %}
{% endfor %}
</code></pre>
<p>...to have the repeating effect of</p>
<pre><code><div class="container">
<div class="row clearfix">
<div class="col-md-4">
item 1
</div>
<div class="col-md-4">
item 2
</div>
<div class="col-md-4">
item 3
</div>
</div>
<div class="row clearfix">
<div class="col-md-4">
item 1
</div>
<div class="col-md-4">
item 2
</div>
<div class="col-md-4">
item 3
</div>
</div>
</div>
</code></pre>
<p><strong>Update:</strong> I was able to get this working (with a little column-count variation for responsiveness) using the following, but I'm a beginner so please let me know if there's a better solution.</p>
<pre><code> <div class="row">
{% for question in questions.paginator.page %}
<div class="col-lg-3 col-sm-6 col-xs-12">
{% question_list_item question %}
</div>
{% if forloop.counter|divisibleby:4 %}
</div>
<div class="row">
{% endif %}
{% endfor %}
</div>
</code></pre>
<p>Thank you!</p>
| 0 | 1,158 |
Open an UI Dialog on click of a button in JQuery
|
<p>My previous qstn in this forum was about assigning text dynamically to buttons in jquery dynamically and I got solution for that here. Now my question is, upon clicking that button, I have to open another UI dialog with 2 buttons. I have written the following code. I am able to open UI Dialog but buttons are not appearing. Pls help me to alter my code.</p>
<pre><code><html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</head>
<body>
<div id="selector" title="Pop Up" class = "selector"> <p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span> Do u want to save the score?</p> </div>
<script>
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var today = new Date();
var month = monthNames[today.getMonth()];
var nextMonth = monthNames[today.getMonth() + 1];
$(".selector").dialog({buttons: [
{
text: month,
click: function() {
$("#opener").dialog({modal: true, height: 590, width: 1005 });
$(this).dialog("close");
}
},
{
text: nextMonth,
click: function() {
$(this).dialog('close');
}
}
]});
</script>
<script>
$(".opener").dialog({buttons: [
{
text: "ok",
click: function() {
$(this).dialog("open");
}
},
{
text: "cancel",
click: function() {
$(this).dialog('open');
}
}
]});
</script>
<div id="opener" title="Pop Up" class = "opener" width ="100px">
<p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>
Score will be updated</p> </div>
</body>
</code></pre>
<p></p>
| 0 | 1,377 |
Android java.lang.NullPointerException: println needs a message
|
<p>I have a problem with my app when I try to login.</p>
<p>In fact, if I register (if the checkbox <code>remerberMe</code> <code>isChecked()</code> on register action, at the next connection the main activity is displayed otherwise the login activity appears) first, it works fine.</p>
<p>However, the <code>Login</code> Activity doesn't work when it's called on the next connection after register action.</p>
<h2>Login Activity</h2>
<pre><code>public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
setTitle(R.string.loginTitle);
// Importing all assets like buttons, text fields
inputUsername = (EditText) findViewById(R.id.username_value);
inputPassword = (EditText) findViewById(R.id.password_value);
btnLogin = (Button) findViewById(R.id.loginButton);
btnExit = (Button) findViewById(R.id.exitButton);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegister);
rememberMe = (CheckBox) findViewById(R.id.rememberNameRegister);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LoginAction();
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
btnExit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
public void LoginAction() {
Log.i("Login", "Login Action");
progressDialog = ProgressDialog.show(LoginActivity.this, null,
getResources().getString(R.string.loginProgressMessage), true);
// try {
runOnUiThread(new Runnable() {
String username = inputUsername.getText().toString();
String password = inputPassword.getText().toString();
@Override
public void run() {
Log.i("Login Run", "username " + username);
switch (username.length()) {
case 0:
blankUserName();
break;
}
switch (password.length()) {
case 0:
blankPassWord();
// thread.stop();
break;
}
try {
if (username.length() > 0 && password.length() > 0) {
Log.i("Login Run", "password " + password);
// Password pass = new Password(username, password);
DatabaseHelper db = new DatabaseHelper(
getApplicationContext());
int count = db.getRowCount();
Log.i("Login", "getRowCompte " + count);
if (count == 1) {
Log.i("Login","getLogin1 ");
// if (db.getLogin(username, password) == 1) {
if (db.Login(username, password)== true) {
Log.i("Login", "rememberMe.isChecked()");
if (rememberMe.isChecked() == true) {
statut = "on";
} else if (rememberMe.isChecked() == false) {
statut = "off";
}
Log.i("Login", "ok ischecked");
Log.i("Login","getRowCompteStat "+ db.getRowCountStat());
if (db.getRowCountStat() == 1) {
db.UpdateStatut(statut);
Log.i("Login", "getRowCompte " + count);
}
Toast.makeText(getApplicationContext(),
"Student Moyenne \n Bienvenu!",
Toast.LENGTH_LONG).show();
Log.i("Login Run", "Connecté");
Intent moy = new Intent(
getApplicationContext(),
MoyenneMain.class);
// Close all views before launching
// Dashboard
moy.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(moy);
finish();
db.close();
} else if (db.Login(username, password)==false){
// if (db.getLogin(username, password) == 0) {
// Log.i("Login Run", "faux password");
Toast.makeText(LoginActivity.this,"Invalid Username/Password",Toast.LENGTH_LONG).show();
Intent login = new Intent(getApplicationContext(),LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
finish();
db.close();
}
} else if (count == 0) {
Log.i("Login Run", "Enregistrez vous");
Toast.makeText(LoginActivity.this,
"Enregistrez vous!", Toast.LENGTH_SHORT)
.show();
Intent register = new Intent(
getApplicationContext(),
RegisterActivity.class);
register.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(register);
finish();
db.close();
}
}
} catch (Exception e) {
Log.i("Login Error1", e.getMessage());
Toast.makeText(LoginActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
// } catch (Exception e) {
// Thread.currentThread().destroy();
// Log.i("Login Error2", e.getMessage());
// Toast.makeText(LoginActivity.this, e.getMessage(),
// Toast.LENGTH_LONG).show();
// }
}
private void blankUserName() {
Toast.makeText(LoginActivity.this, "Entrez un nom Utilisateur SVP!",
Toast.LENGTH_SHORT).show();
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
finish();
}
private void blankPassWord() {
Toast.makeText(LoginActivity.this, "Entrez un mot de passe SVP!",
Toast.LENGTH_SHORT).show();
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
finish();
}
</code></pre>
<h2>A part of DatabaseHelper</h2>
<pre><code>public int getRowCountStat() {
String countQuery = "SELECT * FROM " + TABLE_STATUT;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
public boolean Login(String username, String password) throws SQLException
{
Cursor mCursor = db.rawQuery("SELECT * FROM " + TABLE_LOGIN + " WHERE username=? AND password=?"
, new String[]{username,password});
if (mCursor != null) {
if(mCursor.getCount() > 0)
{
return true;
}
}
return false;
}
public int UpdateStatut(String statut) {
final static int idStat = 1;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(STATUT, statut);
return db.update(TABLE_STATUT, cv, ID_STAT + "=?",
new String[] { String.valueOf(idStat) });
}
</code></pre>
<h2>Logcat</h2>
<pre><code>10-24 01:48:08.819: E/AndroidRuntime(29242): FATAL EXCEPTION: main
10-24 01:48:08.819: E/AndroidRuntime(29242): java.lang.NullPointerException: println needs a message
10-24 01:48:08.819: E/AndroidRuntime(29242): at android.util.Log.println_native(Native Method)
10-24 01:48:08.819: E/AndroidRuntime(29242): at android.util.Log.i(Log.java:143)
10-24 01:48:08.819: E/AndroidRuntime(29242): at com.android.moyenne.activity.LoginActivity$4.run(LoginActivity.java:163)
10-24 01:48:08.819: E/AndroidRuntime(29242): at android.app.Activity.runOnUiThread(Activity.java:3707)
10-24 01:48:08.819: E/AndroidRuntime(29242): at com.android.moyenne.activity.LoginActivity.LoginAction(LoginActivity.java:78)
10-24 01:48:08.819: E/AndroidRuntime(29242): at com.android.moyenne.activity.LoginActivity$1.onClick(LoginActivity.java:46)
10-24 01:48:08.819: E/AndroidRuntime(29242): at android.view.View.performClick(View.java:2408)
10-24 01:48:08.819: E/AndroidRuntime(29242): at android.view.View$PerformClick.run(View.java:8816)
10-24 01:48:08.819: E/AndroidRuntime(29242): at android.os.Handler.handleCallback(Handler.java:587)
10-24 01:48:08.819: E/AndroidRuntime(29242): at android.os.Handler.dispatchMessage(Handler.java:92)
10-24 01:48:08.819: E/AndroidRuntime(29242): at android.os.Looper.loop(Looper.java:123)
10-24 01:48:08.819: E/AndroidRuntime(29242): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-24 01:48:08.819: E/AndroidRuntime(29242): at java.lang.reflect.Method.invokeNative(Native Method)
10-24 01:48:08.819: E/AndroidRuntime(29242): at java.lang.reflect.Method.invoke(Method.java:521)
10-24 01:48:08.819: E/AndroidRuntime(29242): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
10-24 01:48:08.819: E/AndroidRuntime(29242): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
10-24 01:48:08.819: E/AndroidRuntime(29242): at dalvik.system.NativeStart.main(Native Method)
10-24 01:48:12.260: I/Process(29242): Sending signal. PID: 29242 SIG: 9
</code></pre>
| 0 | 5,857 |
Spread operator and EsLint
|
<p>I want to copy object and change one of its field. Something like this:</p>
<pre><code>const initialState = {
showTagPanel: false,
};
export default function reducerFoo(state = initialState, action) {
switch(action.type) {
case types.SHOW_TAG_PANEL:
console.log(state);
return {
...state,
showTagPanel: true
};
default:
return state;
}
}
</code></pre>
<p>This code works fine, but <code>eslint</code> show me error</p>
<pre><code>Unexpected token (14:8)
12 |
13 | return {
> 14 | ...state,
| ^
15 | showTagPanel: true
16 | };
17 |
</code></pre>
<p>Here is my .eslintrc:</p>
<pre><code>{
"extends": [
"eslint:recommended",
"plugin:import/errors",
"plugin:import/warnings"
],
"plugins": [
"react"
],
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"env": {
"es6": true,
"browser": true,
"node": true,
"jquery": true,
"mocha": true
},
"rules": {
"quotes": 0,
"no-console": 1,
"no-debugger": 1,
"no-var": 1,
"semi": [1, "always"],
"no-trailing-spaces": 0,
"eol-last": 0,
"no-unused-vars": 0,
"no-underscore-dangle": 0,
"no-alert": 0,
"no-lone-blocks": 0,
"jsx-quotes": 1,
"react/display-name": [ 1, {"ignoreTranspilerName": false }],
"react/forbid-prop-types": [1, {"forbid": ["any"]}],
"react/jsx-boolean-value": 1,
"react/jsx-closing-bracket-location": 0,
"react/jsx-curly-spacing": 1,
"react/jsx-indent-props": 0,
"react/jsx-key": 1,
"react/jsx-max-props-per-line": 0,
"react/jsx-no-bind": 1,
"react/jsx-no-duplicate-props": 1,
"react/jsx-no-literals": 0,
"react/jsx-no-undef": 1,
"react/jsx-pascal-case": 1,
"react/jsx-sort-prop-types": 0,
"react/jsx-sort-props": 0,
"react/jsx-uses-react": 1,
"react/jsx-uses-vars": 1,
"react/no-danger": 1,
"react/no-did-mount-set-state": 1,
"react/no-did-update-set-state": 1,
"react/no-direct-mutation-state": 1,
"react/no-multi-comp": 1,
"react/no-set-state": 0,
"react/no-unknown-property": 1,
"react/prefer-es6-class": 1,
"react/prop-types": 1,
"react/react-in-jsx-scope": 1,
"react/require-extension": 1,
"react/self-closing-comp": 1,
"react/sort-comp": 1,
"react/wrap-multilines": 1
}
}
</code></pre>
<p>How can I fix it ?</p>
| 0 | 1,215 |
eclipse android programming Error in an XML file: aborting build
|
<p>i am creating an android application, a simple calculator, but i am getting an "[2012-03-12 20:22:21 - Calculator] Error in an XML file: aborting build." which i couldn't solve. could you identify the problem?</p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="@+id/txtResult"
android:layout_width="fill_parent"
android:layout_height="54dp"
android:inputType="number"
android:singleLine="true"
android:text="@string/result"
android:editable="false"
android:gravity="right">
</EditText>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.25"
android:text="@string/number1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.25"
android:text="@string/number2" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/number3"
android:layout_weight="1.25" />
<Button
android:id="@+id/buttonPlus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.25"
android:text="@string/calcAddition" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/number4"
android:layout_weight="1.25" />
<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/number5"
android:layout_weight="1.25"/>
<Button
android:id="@+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/number6"
android:layout_weight="1.25"/>
<Button
android:id="@+id/buttonMinus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.25"
android:text="@string/calcMinus" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/number7"
android:layout_weight="1.25" />
<Button
android:id="@+id/button8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/number8"
android:layout_weight="1.25"/>
<Button
android:id="@+id/button9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/number9"
android:layout_weight="1.25"/>
<Button
android:id="@+id/buttonMultiplication"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.25"
android:text="@string/calcMultiplication" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout6"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/button0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.02"
android:text="@string/number0" />
<Button
android:id="@+id/buttonCLR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.67"
android:text="@string/calcCLR" />
<Button
android:id="@+id/btnCalcEqual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/calcEqual" />
<Button
android:id="@+id/buttonDivision"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.1"
android:text="@string/calcDiv" />
</LinearLayout>
</LinearLayout>
</code></pre>
<p>strings.xml:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
</code></pre>
<p></p>
<pre><code><string name="app_name">Calculator</string>
<string name="number1">1</string>
<string name="number2">2</string>
<string name="number3">3</string>
<string name="number4">4</string>
<string name="number5">5</string>
<string name="number6">6</string>
<string name="number7">7</string>
<string name="number8">8</string>
<string name="number9">9</string>
<string name="number0">0</string>
<string name="calcCLR">CLR</string>
<string name="calcDiv">/</string>
<string name="calcMultiplication">*</string>
<string name="calcAddition">+</string>
<string name="calcMinus">-</string>
<string name="result">0</string>
<string name="calcEqual">Calculate</string>
</resources>
</code></pre>
| 0 | 2,765 |
PrimeFaces TypeError: PF(...) is undefined
|
<p>I followed the DataTable Filter <a href="http://www.primefaces.org/showcase/ui/data/datatable/filter.xhtml" rel="noreferrer">showcase</a> from PrimeFaces on my own DataTable. Every time the "onkeyup" event occurs I get a</p>
<blockquote>
<p>TypeError: PF(...) is undefined error in Firebug and a "Uncaught
TypeError: Cannot read property 'filter' of undefined</p>
</blockquote>
<p>in Chrome Console. The filtering does not work.</p>
<p>Here is my XHTML page:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<h:title>List of User</h:title>
</h:head>
<h:body>
<h:form id="UserForm" name="UserRecords">
<p:dataTable id="users" widgetVar="usersTable" var="user" value="#{userBean.users}" scrollable="false" frozenColumns="0" sortMode="multiple" stickyHeader="true" filteredValue="#{userBean.filteredUsers}">
<f:facet name="header">User<p:inputText id="globalFilter" onkeyup="PF('usersTable').filter()" style="float:right" placeholder="Filter"/>
<p:commandButton id="toggler" type="button" style="float:right" value="Columns" icon="ui-icon-calculator"/>
<p:columnToggler datasource="users" trigger="toggler"/>
<p:commandButton id="optionsButton" value="Options" type="button" style="float:right"/>
<p:menu overlay="true" trigger="optionsButton" my="left top" at="left bottom">
<p:submenu label="Export">
<p:menuitem value="XLS">
<p:dataExporter type="xls" target="users" fileName="users"/>
</p:menuitem>
<p:menuitem value="PDF">
<p:dataExporter type="pdf" target="users" fileName="users"/>
</p:menuitem>
<p:menuitem value="CSV">
<p:dataExporter type="csv" target="users" fileName="users"/>
</p:menuitem>
<p:menuitem value="XML">
<p:dataExporter type="xml" target="users" fileName="users"/>
</p:menuitem>
</p:submenu>
</p:menu>
</f:facet>
<p:column disabledSection="false" colspan="1" exportable="true" filterBy="#{user.firstName}" filterMatchMode="startsWith" filterStyle="display:none; visibility:hidden;" filterable="true" headerText="FirstName" priority="0" rendered="true" resizable="true" rowspan="1" selectRow="true" sortable="true" toggleable="true" visible="true">
<h:outputText value="#{user.firstName}"/>
</p:column>
<p:column disabledSection="false" colspan="1" exportable="true" filterBy="#{user.lastName}" filterMatchMode="startsWith" filterStyle="display:none; visibility:hidden;" filterable="true" headerText="LastName" priority="0" rendered="true" resizable="true" rowspan="1" selectRow="true" sortable="true" toggleable="true" visible="true">
<h:outputText value="#{user.lastName}"/>
</p:column>
<p:column disabledSection="false" colspan="1" exportable="true" filterBy="#{user.username}" filterMatchMode="startsWith" filterStyle="display:none; visibility:hidden;" filterable="true" headerText="Username" priority="0" rendered="true" resizable="true" rowspan="1" selectRow="true" sortable="true" toggleable="true" visible="true">
<h:outputText value="#{user.username}"/>
</p:column>
<p:column disabledSection="false" colspan="1" exportable="true" filterBy="#{user.password}" filterMatchMode="startsWith" filterStyle="display:none; visibility:hidden;" filterable="true" headerText="Password" priority="0" rendered="true" resizable="true" rowspan="1" selectRow="true" sortable="true" toggleable="true" visible="true">
<h:outputText value="#{user.password}"/>
</p:column>
<p:column disabledSection="false" colspan="1" exportable="true" filterBy="#{user.id}" filterMatchMode="startsWith" filterStyle="display:none; visibility:hidden;" filterable="true" headerText="Id" priority="0" rendered="true" resizable="true" rowspan="1" selectRow="true" sortable="true" toggleable="true" visible="true">
<h:outputText value="#{user.id}"/>
</p:column>
<p:column disabledSection="false" colspan="1" exportable="true" filterBy="#{user.createdOn}" filterMatchMode="startsWith" filterStyle="display:none; visibility:hidden;" filterable="true" headerText="CreatedOn" priority="0" rendered="true" resizable="true" rowspan="1" selectRow="true" sortable="true" toggleable="true" visible="true">
<h:outputText value="#{user.createdOn}"/>
</p:column>
<p:column disabledSection="false" colspan="1" exportable="true" filterBy="#{user.lastModified}" filterMatchMode="startsWith" filterStyle="display:none; visibility:hidden;" filterable="true" headerText="LastModified" priority="0" rendered="true" resizable="true" rowspan="1" selectRow="true" sortable="true" toggleable="true" visible="true">
<h:outputText value="#{user.lastModified}"/>
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>
</code></pre>
<p>I'm using PrimeFaces 5.2 with Mojarra 2.2.8 and JSF 2.2.10.</p>
| 0 | 2,797 |
How to create a custom top navigation bar in React Native
|
<p>Hi i am building an app in React Native and I want to have a customized tabbar. I have tried it with React navigation but I can't figure out how to style the way I want...</p>
<p>This is what I want it to look like eventually:</p>
<p><a href="https://i.stack.imgur.com/YsV0G.png" rel="noreferrer">The information page</a></p>
<p><a href="https://i.stack.imgur.com/cKW9g.png" rel="noreferrer">The photos page</a></p>
<p>With react navigation i'm able to swipe the screen and go to the other page. So that is really nice usability which I'd like to keep (if that's possible ofcourse)</p>
<p>I have tried with passing a custom component in the navigator, but I couldn't get that to work. So when clean and native it looks like this right now:</p>
<pre><code>const ProfileTabScreen = ({ navigation }) => {
return (
<ProfileTabNavigator.Navigator>
<ProfileTabNavigator.Screen name="Info" component={ProfileInfoScreen} />
<ProfileTabNavigator.Screen name="Photos" component={ProfilePhotosScreen} />
</ProfileTabNavigator.Navigator>
);
};
</code></pre>
<p>The ProfileInfo- and ProfilePhotoScreen components are right now just empty views through which i can navigate with the top navigation.</p>
<h2>EDIT</h2>
<p>Thanks @Hikaru Watanabe, I have looked into createMaterialTopTabNavigator and managed to get it looking like the picture below. It works really well, the only thing I'm worries about is the white space on the sides I created because they are made with percentages (width: 45%, left: 2.5%). So on bigger screens it might look a bit different. This is not optimal, but I couldn't figure out how else to make it. This was the only thing that seemed to work and look the same on the iPhone and Android I test on.</p>
<p><a href="https://i.stack.imgur.com/zogQO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zogQO.png" alt="enter image description here" /></a></p>
<p>The code to get it done:</p>
<pre><code>const ProfileTabScreen = () => {
return (
<ProfileTabNavigator.Navigator tabBarOptions={{
activeTintColor: Colors.COLOR_WHITE,
labelStyle: {
textTransform: "uppercase",
},
inactiveTintColor: Colors.COLOR_SUPER_DARK_GREY,
indicatorStyle: {
height: null,
top: '10%',
bottom: '10%',
width: '45%',
left: '2.5%',
borderRadius: 100,
backgroundColor: Colors.PRIMARY_TWO,
},
style: {
alignSelf: "center",
width: '50%',
borderRadius: 100,
borderColor: "blue",
backgroundColor: "white",
elevation: 5, // shadow on Android
shadowOpacity: .10, // shadow on iOS,
shadowRadius: 4, // shadow blur on iOS
},
tabStyle: {
borderRadius: 100,
},
}}
swipeEnabled={true}>
<ProfileTabNavigator.Screen name="Info" component={ProfileInfoScreen} />
<ProfileTabNavigator.Screen name="Photos" component={ProfilePhotosScreen} />
</ProfileTabNavigator.Navigator>
);
};
</code></pre>
| 0 | 1,384 |
How to expose property of QObject pointer to QML
|
<p>I am giving very brief (and partial) description of my class to show my problem. Basically I have setup two properties.</p>
<pre><code>class Fruit : public QObject
{
Q_OBJECT
....
public:
Q_PROPERTY( int price READ getPrice NOTIFY priceChanged)
Q_PROPERTY(Fruit * fruit READ fruit WRITE setFruit NOTIFY fruitChanged)
}
</code></pre>
<p>In my QML if I access the <code>price</code> property it works well and good. But if I access the <code>fruit</code> property which obviously returns <code>Fruit</code> and then try to use its <code>price</code> property, that doesn't work. Is this not supposed to work this way?</p>
<pre><code>Text {
id: myText
anchors.centerIn: parent
text: basket.price // shows correctly
//text: basket.fruit.price // doesn't show
}
</code></pre>
<p>The 2nd one returns <code>Fruit</code> which also is a property and it has <code>price</code> property but it doesn't seem to access that property? Should this work?</p>
<p><strong>Updated</strong> </p>
<p>I am including my source code. I created a new demo with <code>HardwareComponent</code>, it just makes more sense this way. I tried to make it work based on answer I received but no luck.</p>
<p><code>HardwareComponent</code> class is the base class for <code>Computer</code> and <code>CPU</code>.</p>
<h3>main.cpp</h3>
<pre><code>#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
class HardwareComponent : public QObject
{
Q_OBJECT
public:
HardwareComponent() : m_price(0) {}
virtual int price() = 0;
virtual Q_INVOKABLE void add(HardwareComponent * item) { m_CPU = item; }
HardwareComponent * getCPU() const { return m_CPU; }
Q_SLOT virtual void setPrice(int arg)
{
if (m_price == arg) return;
m_price = arg;
emit priceChanged(arg);
}
Q_SIGNAL void priceChanged(int arg);
protected:
Q_PROPERTY(HardwareComponent * cpu READ getCPU);
Q_PROPERTY(int price READ price WRITE setPrice NOTIFY priceChanged)
HardwareComponent * m_CPU;
int m_price;
};
class Computer : public HardwareComponent
{
Q_OBJECT
public:
Computer() { m_price = 500; }
int price() { return m_price; }
void setprice(int arg) { m_price = arg; }
};
class CPU : public HardwareComponent
{
Q_OBJECT
public:
CPU() { m_price = 100; }
int price() { return m_price; }
void setprice(int arg) { m_price = arg; }
};
int main(int argc, char *argv[])
{
HardwareComponent * computer = new Computer;
CPU * cpu = new CPU;
computer->add( cpu );
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
engine.rootContext()->setContextProperty("computer", computer);
return app.exec();
}
#include "main.moc"
</code></pre>
<h3>main.qml</h3>
<pre><code>import QtQuick 2.3
import QtQuick.Window 2.2
Window {
visible: true
width: 360
height: 360
Text {
anchors.centerIn: parent
text: computer.price // works
//text: computer.cpu.price // doesn't work, doesn't show any value
}
}
</code></pre>
<p>This is the complete source code for all my project files.</p>
<p>When I run it I get this output:</p>
<blockquote>
<p>Starting C:\Users\User\Documents\My Qt
Projects\build-hardware-Desktop_Qt_5_4_0_MSVC2010_OpenGL_32bit-Debug\debug\hardware.exe...
QML debugging is enabled. Only use this in a safe environment.
qrc:/MainForm.ui.qml:20: ReferenceError: computer is not defined</p>
</blockquote>
<p>Even though it gives a warning at line 20 (computer.price) line, it still works and shows the price of computer (=500). If change it <code>computer.cpu.price</code>, the same warning is reported but the price no longer shows - it doesn't seem to work.</p>
<p>The problem is since price is a virtual property, it works! but if I use this property on another hardware component inside the computer component, it doesn't work! The code/answer posted by Mido gives me hope there could be a solution to this, it looks quite close! I hope I can make this work.</p>
| 0 | 1,404 |
How to submit a form using JS, Node, Mongo, and Express?
|
<p>I am a beginner programmer. I am wondering how to submit a form, composed of JQuery date picker and radio buttons, using a button. I want to submit the form to a Mongo Database called <code>test</code>. In my <code>home.html</code> file I call the different stylesheets and javascript files I need. Then I set up an input field in the <code>home.html</code> and a button beneath the form to submit:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Home</title>
<!-- Local CSS and JS -->
<script src="/javascripts/home.js"></script>
<!-- Materialize: Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/css/materialize.min.css">
<!-- Materialize: Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/js/materialize.min.js"></script>
</head>
<body>
<!-- Input field I want to submit -->
<form method="post" action="/submit">
<input id="test1" type="radio"><label for="test1">Test</label>
<input id="test2" type="radio"><label for="test2">Test 2</label>
<input id="test3" type="radio"><label for="test3">Test 3</label>
</form>
<!-- Button I want to use to submit -->
<button type="submit" class="btn waves-effect waves-light" name="action">Sumbit</button>
</div>
</body>
</html>
</code></pre>
<p>Right now, I am loading this file by typing in localhost:3000/home.html. I want to use my <code>index.js</code> file to write the post method for submitting the data to my DB called <code>test</code>. After doing some research, I found that I'll need something to start my <code>index.js</code> like:</p>
<pre><code>var express = require('express');
var router = express.Router();
//TALKING TO THE DB?
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert')
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/test';
var bodyParser = require('body-parser');
/*something would follow like?:
router.get('/submit', function(req, res) {
var db = req.test;
});*/
</code></pre>
<p>For reference, I'm using the express skeleton so my <code>app.js</code> looks like:</p>
<pre><code>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Database
var mongo = require('mongodb');
var monk = require('monk');
//DB TEST
var db = monk('localhost:27017/test');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
</code></pre>
<p>However, I am confused as to how to set up routes that grabs the data from my input fields (using the submit button). Then I want to use a post method to write that information to my <code>test</code> database. Any help would be greatly appreciated! Thank you!</p>
| 0 | 1,541 |
Create a count up timer in java (seconds and milliseconds only)
|
<p>I'm doing a <strong>count up timer in java</strong>. I found the following example: <a href="https://stackoverflow.com/questions/5745745/creating-a-count-up-timer-to-break-in-java">Creating a Count Up timer to Break in java</a>, and that's working fine. But I want to show the time in the <strong>format "mm:ss:SSS"</strong>, because I want to measure really small time responses. So, when it reaches the 1000 msec, it is 1 second.</p>
<p>I made some changes, but I can't present the time in the pretended format. The numbers start to appear were the seconds should be, and not in the milliseconds.</p>
<p>If you have a better example that the one that I'm following, it's fine.</p>
<p><strong>Edit:</strong> It is better, but it is not working fine yet. It is counting too slow (1 minute here correspond to 2 real minutes). My code is here:</p>
<pre><code>public class Counter extends JFrame {
private static final String stop = "Stop";
private static final String start = "Start";
private final ClockListener clock = new ClockListener();
private final Timer timer = new Timer(1, clock);
private final JTextField tf = new JTextField(9);
public Counter()
{
timer.setInitialDelay(0);
JPanel panel = new JPanel();
tf.setHorizontalAlignment(JTextField.RIGHT);
tf.setEditable(false);
panel.add(tf);
final JToggleButton b = new JToggleButton(start);
b.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e)
{
if (b.isSelected())
{
timer.start();
b.setText(stop);
}
else
{
timer.stop();
b.setText(start);
}
}
});
panel.add(b);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(panel);
this.setTitle("Timer");
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
private class ClockListener implements ActionListener
{
private int minutes;
private int seconds;
private int milliseconds;
@Override
public void actionPerformed(ActionEvent e)
{
SimpleDateFormat date = new SimpleDateFormat("mm.ss.SSS");
if (milliseconds == 1000)
{
milliseconds = 000;
seconds++;
}
if (seconds == 60) {
seconds = 00;
minutes++;
}
tf.setText(String.valueOf(minutes + ":" + seconds + ":" + milliseconds));
milliseconds++;
}
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run() {
Counter clock = new Counter();
clock.start();
}
});
}
}
</code></pre>
| 0 | 1,143 |
Android RecyclerView addition & removal of items
|
<p>I have a RecyclerView with an TextView text box and a cross button ImageView. I have a button outside of the recyclerview that makes the cross button ImageView visible / gone.</p>
<p>I'm looking to remove an item from the recylerview, when that items cross button ImageView is pressed.</p>
<p>My adapter:</p>
<pre><code>public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements View.OnClickListener, View.OnLongClickListener {
private ArrayList<String> mDataset;
private static Context sContext;
public MyAdapter(Context context, ArrayList<String> myDataset) {
mDataset = myDataset;
sContext = context;
}
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_text_view, parent, false);
ViewHolder holder = new ViewHolder(v);
holder.mNameTextView.setOnClickListener(MyAdapter.this);
holder.mNameTextView.setOnLongClickListener(MyAdapter.this);
holder.mNameTextView.setTag(holder);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mNameTextView.setText(mDataset.get(position));
}
@Override
public int getItemCount() {
return mDataset.size();
}
@Override
public void onClick(View view) {
ViewHolder holder = (ViewHolder) view.getTag();
if (view.getId() == holder.mNameTextView.getId()) {
Toast.makeText(sContext, holder.mNameTextView.getText(), Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onLongClick(View view) {
ViewHolder holder = (ViewHolder) view.getTag();
if (view.getId() == holder.mNameTextView.getId()) {
mDataset.remove(holder.getPosition());
notifyDataSetChanged();
Toast.makeText(sContext, "Item " + holder.mNameTextView.getText() + " has been removed from list",
Toast.LENGTH_SHORT).show();
}
return false;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mNumberRowTextView;
public TextView mNameTextView;
public ViewHolder(View v) {
super(v);
mNameTextView = (TextView) v.findViewById(R.id.nameTextView);
}
}
}
</code></pre>
<p>My layout is:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:id="@+id/layout">
<TextView
android:id="@+id/nameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="5dp"
android:background="@drawable/greyline"/>
<ImageView
android:id="@+id/crossButton"
android:layout_width="16dp"
android:layout_height="16dp"
android:visibility="gone"
android:layout_marginLeft="50dp"
android:src="@drawable/cross" />
</LinearLayout>
</code></pre>
<p>How can I get something like an onClick working for my crossButton ImageView? Is there a better way? Maybe changing the whole item onclick into a remove the item? The recyclerview shows a list of locations that need to be edited. Any technical advice or comments / suggestions on best implementation would be hugely appreciated.</p>
| 0 | 1,454 |
Parser configuration exception parsing XML from class path resource
|
<p>I am trying to run a junit test case for testing whether the applicationcontext is initialized and it throws the following error. Is it something related to the xml or the java version. How do I fix this?</p>
<pre><code> org.springframework.beans.factory.BeanDefinitionStoreException: Parser configuration exception parsing XML from class path resource [tasospring-online-context.xml]; nested exception is javax.xml.parsers.ParserConfigurationException: Unable to validate using XSD: Your JAXP provider [org.apache.crimson.jaxp.DocumentBuilderFactoryImpl@82701e] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? Upgrade to Apache Xerces (or Java 1.5) for full XSD support.
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:404)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:243)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.roger.tas.manager.util.OnlineSpringBootStrapper.initialize(OnlineSpringBootStrapper.java:23)
at com.roger.tas.manager.util.OnlineSpringBootStrapperTest.testGetEventHandler(OnlineSpringBootStrapperTest.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: javax.xml.parsers.ParserConfigurationException: Unable to validate using XSD: Your JAXP provider [org.apache.crimson.jaxp.DocumentBuilderFactoryImpl@82701e] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? Upgrade to Apache Xerces (or Java 1.5) for full XSD support.
at org.springframework.beans.factory.xml.DefaultDocumentLoader.createDocumentBuilderFactory(DefaultDocumentLoader.java:102)
at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:70)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:388)
... 38 more
Caused by: java.lang.IllegalArgumentException: No attributes are implemented
at org.apache.crimson.jaxp.DocumentBuilderFactoryImpl.setAttribute(DocumentBuilderFactoryImpl.java:93)
at org.springframework.beans.factory.xml.DefaultDocumentLoader.createDocumentBuilderFactory(DefaultDocumentLoader.java:99)
... 40 more
</code></pre>
<p>This is the tasospring-online-context.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean id="onlineDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="TasDS"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg index="0" ref="onlineDataSource"/>
</bean>
<bean name="taskEventHandler" class="com.roger.tas.util.TaskEventHandlerFactory">
<constructor-arg name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg index="0" ref="onlineDataSource"/>
</bean>
</beans>
</code></pre>
| 0 | 2,329 |
How to implement single search form in yii2
|
<p>Yii2 has a <code>searchModel</code> to search each field in the <code>GridView</code>. Is it possible to just create a single search field outside the <code>GridView</code> where the user can input keywords and by the time Search button is hit, the results will display in the <code>GridView</code> based on the keywords entered.</p>
<p>CONTROLLER</p>
<pre><code>public function actionIndex()
{
$session = Yii::$app->session;
//$searchModel = new PayslipTemplateSearch();
$PayslipEmailConfig = PayslipEmailConfig::find()->where(['company_id'=> new \MongoId($session['company_id'])])->one();
$payslipTemplateA = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'A'])->one();
$payslipTemplateB = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'B'])->one();
$pTemplateModel = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->all();
$user = User::find()->where(['_id' => new \MongoId($session['user_id'])])->one();
$module_access = explode(',', $user->module_access);
//$dataProvider = User::find()->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])])->all();
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'PayslipEmailConfig' => $PayslipEmailConfig,
'dataProvider' => $dataProvider,
'payslipTemplateA' => $payslipTemplateA,
'payslipTemplateB' => $payslipTemplateB,
'searchModel' => $searchModel,
]);
}
public function actionSearchresults($keyword)
{
$session = Yii::$app->session;
if ( $keyword == '') {
return $this->redirect(\Yii::$app->request->getReferrer());
} else {
$user = User::find()->where( [ '_id' => new \MongoId($id) ] )->one();
$searchModel = new PayslipTemplateSearch();
$payslipTemplateA = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'A'])->one();
$payslipTemplateB = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'B'])->one();
return $this->render('searchresults', [
'searchModel' => $searchModel,
'user' => $user,
'payslipTemplateA' => $payslipTemplateA,
'payslipTemplateB' => $payslipTemplateB,
]);
}
}
</code></pre>
<p>I asked a question connected to this problem here: <a href="https://stackoverflow.com/questions/32882097/main-search-form-in-yii2">Main Search Form in Yii2</a></p>
<p>It didn't due to some complications in Kartik's <code>Select2</code> search dropdown widget. Now I switched temporarily to a simple Yii2 search field.</p>
<p>VIEW</p>
<pre><code>echo $form->field($model, '_id')->textInput(array('placeholder' => 'search'))->label(false);
</code></pre>
<p>MODEL</p>
<pre><code><?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\User;
/**
* UserSearch represents the model behind the search form about `app\models\User`.
*/
class UserSearch extends User
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[[/*'_id',*/ 'creator_id'], 'integer'],
[['fname', 'lname', 'email', 'username', 'user_type'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$session = Yii::$app->session;
$query = User::find();
$query->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'_id' => $this->_id,
'creator_id' => $this->creator_id,
]);
$query->andFilterWhere(['like', 'fname', $this->fname])
->andFilterWhere(['like', 'lname', $this->lname])
->andFilterWhere(['like', 'email', $this->email])
->andFilterWhere(['like', 'username', $this->username])
->andFilterWhere(['like', 'user_type', $this->user_type]);
return $dataProvider;
}
}
</code></pre>
<p>Do you have any idea on how to I implement a single search? It's kind of a smarter search since it can search everything in the database table based on keywords inputted.</p>
<p>EDIT</p>
<p>When I search a keyword, say for example 'hello', it then gives me this url and error after hitting enter key:</p>
<p>URL: </p>
<blockquote>
<p><a href="http://localhost/iaoy-dev/web/index.php?r=payslip-template%2Fsearchresults&PayslipTemplateSearch%5B_id%5D=hello" rel="nofollow noreferrer">http://localhost/iaoy-dev/web/index.php?r=payslip-template%2Fsearchresults&PayslipTemplateSearch%5B_id%5D=hello</a></p>
</blockquote>
<p>Error message:</p>
<blockquote>
<p>Bad Request (#400) Missing required parameters: id</p>
</blockquote>
<p>Help.</p>
| 0 | 2,553 |
Designing CardView while it's Parent is ConstraintLayout?
|
<p>I messed up while editing RelativeLayout inside Cardview that contains Relativelayout ! ConstraintLayout will change wrap_content of relative layout to 0 and adds tools:layout_editor_absoluteX="10dp" all textview inside Relative layout will collapse top right of the cardview !!! (element in the nested CardView gets aligned to the element outside of the CardView)</p>
<p>
</p>
<pre><code><android.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_gravity="center"
android:layout_width="357dp"
android:layout_height="114dp"
android:layout_margin="5dp"
app:cardCornerRadius="2dp"
app:contentPadding="10dp"
app:cardElevation="10dp"
tools:layout_editor_absoluteY="36dp"
app:cardBackgroundColor="@android:color/white"
tools:layout_editor_absoluteX="11dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="10dp"
tools:layout_editor_absoluteY="10dp">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView2"
tools:text="Location"
android:textAppearance="@style/TextAppearance.AppCompat.Body2"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
<ImageView
android:src="@drawable/ic_hotel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView3"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView3"
tools:text="Bangalore"
android:textAppearance="@style/TextAppearance.AppCompat.Medium"
tools:layout_editor_absoluteX="10dp"
tools:layout_editor_absoluteY="10dp"
android:layout_alignBottom="@+id/imageView3"
android:layout_toRightOf="@+id/textView2"
android:layout_toEndOf="@+id/textView2" />
</android.support.v7.widget.CardView>
</code></pre>
<p></p>
<p>any guide regarding designing RelativeLayout with ConstraintLayout would be great full, RelativeLayout can't be used anywhere while using ConstraintLayout? what is the guidline to use children of a CardView while using RelativeLayout while CardViews is a children of ConstraintLayout?</p>
| 0 | 1,186 |
Can not extract resource from com.android.aaptcompiler
|
<p>Can not extract resource from com.android.aaptcompiler.ParsedResource@636e1e76.</p>
<pre><code>Execution failed for task ':app:mergeDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.res.ResourceCompilerRunnable
> Resource compilation failed (Failed to compile values resource file E:\My Client\Henkako\HenkakoPlus\app\build\intermediates\incremental\debug\mergeDebugResources\merged.dir\values\values.xml. Cause: java.lang.IllegalStateException: Can not extract resource from com.android.aaptcompiler.ParsedResource@636e1e76.). Check logs for more details.
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:mergeDebugResources'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.lambda$executeIfValid$1(ExecuteActionsTaskExecuter.java:145)
at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:282)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:143)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:131)
at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:77)
at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:51)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:199)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:73)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:74)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:402)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:389)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:382)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:368)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:61)
Caused by: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing com.android.build.gradle.internal.res.ResourceCompilerRunnable
at org.gradle.workers.internal.DefaultWorkerExecutor$WorkItemExecution.waitForCompletion(DefaultWorkerExecutor.java:342)
at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForItemsAndGatherFailures(DefaultAsyncWorkTracker.java:142)
at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForItemsAndGatherFailures(DefaultAsyncWorkTracker.java:94)
at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForAll(DefaultAsyncWorkTracker.java:80)
at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForCompletion(DefaultAsyncWorkTracker.java:68)
at org.gradle.api.internal.tasks.execution.TaskExecution$2.run(TaskExecution.java:247)
at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:29)
at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:26)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.run(DefaultBuildOperationRunner.java:47)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:68)
at org.gradle.api.internal.tasks.execution.TaskExecution.executeAction(TaskExecution.java:224)
at org.gradle.api.internal.tasks.execution.TaskExecution.executeActions(TaskExecution.java:207)
at org.gradle.api.internal.tasks.execution.TaskExecution.executeWithPreviousOutputFiles(TaskExecution.java:190)
at org.gradle.api.internal.tasks.execution.TaskExecution.execute(TaskExecution.java:168)
at org.gradle.internal.execution.steps.ExecuteStep.executeInternal(ExecuteStep.java:89)
at org.gradle.internal.execution.steps.ExecuteStep.access$000(ExecuteStep.java:40)
at org.gradle.internal.execution.steps.ExecuteStep$1.call(ExecuteStep.java:53)
at org.gradle.internal.execution.steps.ExecuteStep$1.call(ExecuteStep.java:50)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:199)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:73)
at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:50)
at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:40)
at org.gradle.internal.execution.steps.RemovePreviousOutputsStep.execute(RemovePreviousOutputsStep.java:68)
at org.gradle.internal.execution.steps.RemovePreviousOutputsStep.execute(RemovePreviousOutputsStep.java:38)
at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:48)
at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:36)
at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:41)
at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:74)
at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:55)
at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:51)
at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:29)
at org.gradle.internal.execution.steps.CaptureStateAfterExecutionStep.execute(CaptureStateAfterExecutionStep.java:61)
at org.gradle.internal.execution.steps.CaptureStateAfterExecutionStep.execute(CaptureStateAfterExecutionStep.java:42)
at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:60)
at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:27)
at org.gradle.internal.execution.steps.BuildCacheStep.executeWithoutCache(BuildCacheStep.java:188)
at org.gradle.internal.execution.steps.BuildCacheStep.lambda$execute$1(BuildCacheStep.java:75)
at org.gradle.internal.Either$Right.fold(Either.java:175)
at org.gradle.internal.execution.caching.CachingState.fold(CachingState.java:59)
at org.gradle.internal.execution.steps.BuildCacheStep.execute(BuildCacheStep.java:73)
at org.gradle.internal.execution.steps.BuildCacheStep.execute(BuildCacheStep.java:48)
at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:38)
at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:27)
at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:36)
at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:22)
at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:109)
at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$2(SkipUpToDateStep.java:56)
at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:56)
at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:38)
at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:73)
at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:44)
at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:37)
at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:27)
at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:89)
at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:50)
at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:114)
at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:57)
at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:76)
at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:50)
at org.gradle.internal.execution.steps.SkipEmptyWorkStep.lambda$execute$2(SkipEmptyWorkStep.java:93)
at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:93)
at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:34)
at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsStartedStep.execute(MarkSnapshottingInputsStartedStep.java:38)
at org.gradle.internal.execution.steps.LoadPreviousExecutionStateStep.execute(LoadPreviousExecutionStateStep.java:43)
at org.gradle.internal.execution.steps.LoadPreviousExecutionStateStep.execute(LoadPreviousExecutionStateStep.java:31)
at org.gradle.internal.execution.steps.AssignWorkspaceStep.lambda$execute$0(AssignWorkspaceStep.java:40)
at org.gradle.api.internal.tasks.execution.TaskExecution$3.withWorkspace(TaskExecution.java:284)
at org.gradle.internal.execution.steps.AssignWorkspaceStep.execute(AssignWorkspaceStep.java:40)
at org.gradle.internal.execution.steps.AssignWorkspaceStep.execute(AssignWorkspaceStep.java:30)
at org.gradle.internal.execution.steps.IdentityCacheStep.execute(IdentityCacheStep.java:37)
at org.gradle.internal.execution.steps.IdentityCacheStep.execute(IdentityCacheStep.java:27)
at org.gradle.internal.execution.steps.IdentifyStep.execute(IdentifyStep.java:44)
at org.gradle.internal.execution.steps.IdentifyStep.execute(IdentifyStep.java:33)
at org.gradle.internal.execution.impl.DefaultExecutionEngine$1.execute(DefaultExecutionEngine.java:76)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:142)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:131)
at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:77)
at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:51)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:199)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:73)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:74)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:402)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:389)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:382)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:368)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182)
at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:61)
Caused by: com.android.aaptcompiler.ResourceCompilationException: Resource compilation failed (Failed to compile values resource file E:\My Client\Henkako\HenkakoPlus\app\build\intermediates\incremental\debug\mergeDebugResources\merged.dir\values\values.xml. Cause: java.lang.IllegalStateException: Can not extract resource from com.android.aaptcompiler.ParsedResource@636e1e76.). Check logs for more details.
at com.android.aaptcompiler.ResourceCompiler.compileResource(ResourceCompiler.kt:129)
at com.android.build.gradle.internal.res.ResourceCompilerRunnable$Companion.compileSingleResource(ResourceCompilerRunnable.kt:34)
at com.android.build.gradle.internal.res.ResourceCompilerRunnable.run(ResourceCompilerRunnable.kt:15)
at com.android.build.gradle.internal.profile.ProfileAwareWorkAction.execute(ProfileAwareWorkAction.kt:74)
at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:63)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.create(NoIsolationWorkerFactory.java:66)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.create(NoIsolationWorkerFactory.java:62)
at org.gradle.internal.classloader.ClassLoaderUtils.executeInClassloader(ClassLoaderUtils.java:97)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1.lambda$execute$0(NoIsolationWorkerFactory.java:62)
at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:44)
at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:41)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:199)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:73)
at org.gradle.workers.internal.AbstractWorker.executeWrappedInBuildOperation(AbstractWorker.java:41)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1.execute(NoIsolationWorkerFactory.java:59)
at org.gradle.workers.internal.DefaultWorkerExecutor.lambda$submitWork$2(DefaultWorkerExecutor.java:206)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runExecution(DefaultConditionalExecutionQueue.java:214)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runBatch(DefaultConditionalExecutionQueue.java:164)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.run(DefaultConditionalExecutionQueue.java:131)
... 3 more
Caused by: com.android.aaptcompiler.ResourceCompilationException: Failed to compile values resource file E:\My Client\Henkako\HenkakoPlus\app\build\intermediates\incremental\debug\mergeDebugResources\merged.dir\values\values.xml
at com.android.aaptcompiler.ResourceCompiler.compileTable(ResourceCompiler.kt:192)
at com.android.aaptcompiler.ResourceCompiler.access$compileTable(ResourceCompiler.kt:1)
at com.android.aaptcompiler.ResourceCompiler$getCompileMethod$1.invoke(ResourceCompiler.kt:138)
at com.android.aaptcompiler.ResourceCompiler$getCompileMethod$1.invoke(ResourceCompiler.kt:138)
at com.android.aaptcompiler.ResourceCompiler.compileResource(ResourceCompiler.kt:123)
... 27 more
Caused by: java.lang.IllegalStateException: Can not extract resource from com.android.aaptcompiler.ParsedResource@636e1e76.
at com.android.aaptcompiler.TableExtractor.extractResourceValues(TableExtractor.kt:270)
at com.android.aaptcompiler.TableExtractor.extract(TableExtractor.kt:181)
at com.android.aaptcompiler.ResourceCompiler.compileTable(ResourceCompiler.kt:188)
... 31 more
</code></pre>
| 0 | 7,097 |
how to add image from photo library or camera to my Ipad application?
|
<p>I want to add images from photo library or by using camera to my ipad application. I had used same coding as iphone . But the application is crashing. I think this is not the right way to add picture from library to ipad application. If anyone knows please help me.</p>
<pre><code>-(void)ctnPhotoSelection
{
isMyCtView = YES;
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@""
delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil
otherButtonTitles:@"Take Photo With Camera", @"Select Photo From Library", @"Cancel", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleAutomatic;
actionSheet.destructiveButtonIndex = 1;
[actionSheet showInView:self.view];
[actionSheet release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
[self TakePhotoWithCamera];
}
else if (buttonIndex == 1)
{
[self SelectPhotoFromLibrary];
}
else if (buttonIndex == 2)
{
NSLog(@"cancel");
}
}
-(void) TakePhotoWithCamera
{
[self startCameraPickerFromViewController:self usingDelegate:self];
}
-(void) SelectPhotoFromLibrary
{
[self startLibraryPickerFromViewController:self usingDelegate:self];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
}
- (BOOL)startCameraPickerFromViewController:(UIViewController*)controller usingDelegate:(id<UIImagePickerControllerDelegate>)delegateObject
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.allowsEditing = YES;
picker.delegate = self;
[controller presentModalViewController:picker animated:YES];
[picker release];
}
return YES;
}
- (BOOL)startLibraryPickerFromViewController:(UIViewController*)controller usingDelegate:(id<UIImagePickerControllerDelegate>)delegateObject
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
{
UIImagePickerController *picker1 = [[UIImagePickerController alloc]init];
picker1.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker1.allowsEditing = YES;
picker1.delegate = self;
[controller presentModalViewController:picker1 animated:YES];
[picker1 release];
}
return YES;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage * img = [info objectForKey:@"UIImagePickerControllerEditedImage"];
[self useImage:img];
[[picker parentViewController] dismissModalViewControllerAnimated:NO];
UINavigationController* navController = self.navigationController;
UIViewController* controller = [navController.viewControllers objectAtIndex:0];
[controller dismissModalViewControllerAnimated:NO];
}
-(void)useImage:(UIImage *)theImage
{
NSData *addImageData = UIImagePNGRepresentation(theImage);
IpadAppDelegate *appDelegate=(IpadAppDelegate*)[ [UIApplication sharedApplication] delegate];
if(isMyCtView == YES)
{
isMyCtView = NO;
appDelegate.imageCtData = addImageData;
appDelegate.isctFromDevice = YES;
appDelegate.isctnCntrl = YES;
[self.view sendSubviewToBack:myCtnView];
}
[self reloadView];
}
</code></pre>
<p><strong>Crash Log</strong></p>
<pre><code>Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'On iPad, UIImagePickerController must be presented via UIPopoverController'
*** Call stack at first throw:
(
0 CoreFoundation 0x3587a987 __exceptionPreprocess + 114
1 libobjc.A.dylib 0x34a8249d objc_exception_throw + 24
2 UIKit 0x34378317 UIImagePickerEnsureViewIsInsidePopover + 258
3 PhotoLibrary 0x3499893b -[PLLibraryView didMoveToWindow] + 86
4 UIKit 0x341bf76b -[UIView(Internal) _didMoveFromWindow:toWindow:] + 698
5 UIKit 0x341bf583 -[UIView(Internal) _didMoveFromWindow:toWindow:] + 210
6 UIKit 0x341bf433 -[UIView(Hierarchy) _postMovedFromSuperview:] + 106
7 UIKit 0x341aa82f -[UIView(Internal) _addSubview:positioned:relativeTo:] + 678
8 UIKit 0x341aa57f -[UIView(Hierarchy) addSubview:] + 22
9 UIKit 0x341fc8a9 -[UINavigationTransitionView transition:fromView:toView:] + 416
10 UIKit 0x341fc6fd -[UINavigationTransitionView transition:toView:] + 20
11 UIKit 0x341ef8cf -[UINavigationController _startTransition:fromViewController:toViewController:] + 1274
12 UIKit 0x341ef35f -[UINavigationController _startDeferredTransitionIfNeeded] + 182
13 UIKit 0x341ef2a3 -[UINavigationController viewWillLayoutSubviews] + 14
14 UIKit 0x341ef23f -[UILayoutContainerView layoutSubviews] + 138
15 UIKit 0x341b80cf -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 26
16 CoreFoundation 0x35818bbf -[NSObject(NSObject) performSelector:withObject:] + 22
17 QuartzCore 0x31075685 -[CALayer layoutSublayers] + 120
18 QuartzCore 0x3107543d CALayerLayoutIfNeeded + 184
19 QuartzCore 0x3106f56d _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 212
20 QuartzCore 0x3106f383 _ZN2CA11Transaction6commitEv + 190
21 QuartzCore 0x31092f9d _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 52
22 CoreFoundation 0x3580ac59 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 16
23 CoreFoundation 0x3580aacd __CFRunLoopDoObservers + 412
24 CoreFoundation 0x358020cb __CFRunLoopRun + 854
25 CoreFoundation 0x35801c87 CFRunLoopRunSpecific + 230
26 CoreFoundation 0x35801b8f CFRunLoopRunInMode + 58
27 GraphicsServices 0x320c84ab GSEventRunModal + 114
28 GraphicsServices 0x320c8557 GSEventRun + 62
29 UIKit 0x341dc329 -[UIApplication _run] + 412
30 UIKit 0x341d9e93 UIApplicationMain + 670
31 IpadComicBuilder 0x00002537 main + 70
32 IpadComicBuilder 0x000024b8 start + 52
)
terminate called after throwing an instance of 'NSException'
Program received signal: “SIGABRT”.
warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib (file not found).
(gdb)
</code></pre>
| 0 | 3,283 |
react-native componentWillUnmount not working while navigating
|
<p>I am doing this simple steps but unmount was not calling I don't know why. Please I need a solution for this I need unmount to be get called while navigating to another screen...</p>
<pre><code>class Homemain extends Component {
constructor(props) {
super(props);
}
componentWillMount(){
alert('willMount')
}
componentDidMount(){
alert('didMount')
}
componentWillUnmount(){
alert('unMount')
}
Details = () => {
this.props.navigation.navigate('routedetailsheader')
}
render() {
return(
<View style={styles.container}>
<TouchableOpacity onPress={() => this.Details()} style={{ flex: .45, justifyContent: 'center', alignItems: 'center', marginTop: '10%', marginRight: '10%' }}>
<Image
source={require('./../Asset/Images/child-notification.png')}
style={{ flex: 1, height: height / 100 * 20, width: width / 100 * 20, resizeMode: 'contain' }} />
<Text
style={{ flex: 0.5, justifyContent: 'center', fontSize: width / 100 * 4, fontStyle: 'italic', fontWeight: '400', color: '#000', paddingTop: 10 }}>Details</Text>
</TouchableOpacity>
</View>
);
}
}
export default (Homemain);
</code></pre>
<p>This is my RouteConfiguration in this way I am navigating to the next screen. Can someone please help me for this error so that i can proceed to the next steps</p>
<pre><code>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { addNavigationHelpers, NavigationActions } from 'react-navigation';
import { connect } from 'react-redux';
import { BackHandler } from 'react-native';
import { Stack } from './navigationConfiguration';
const getCurrentScreen = (navigationState) => {
if (!navigationState) {
return null
}
const route = navigationState.routes[navigationState.index]
if (route.routes) {
return getCurrentScreen(route)
}
return route.routeName
}
class StackNavigation extends Component {
static propTypes = {
dispatch: PropTypes.func.isRequired,
navigation: PropTypes.shape().isRequired,
};
constructor(props) {
super(props);
BackHandler.addEventListener('hardwareBackPress', this.backAction);
}
//backAction = () => this.navigator.props.navigation.goBack();
backAction = () => {
const { dispatch, navigation } = this.props;
const currentScreen = getCurrentScreen(navigation)
if (currentScreen === 'Homemain') {
return false
}
else
if (currentScreen === 'Login') {
return false
}
dispatch(NavigationActions.back());
return true;
};
render() {
const { dispatch, navigation } = this.props;
return (
<Stack
ref={(ref) => { this.navigator = ref; }}
navigation={
addNavigationHelpers({
dispatch,
state: navigation,
})
}
/>
);
}
}
export default connect(state => ({ navigation: state.stack }))(StackNavigation);
</code></pre>
| 0 | 1,289 |
How can I perform flood fill with HTML Canvas?
|
<p>Has anyone implemented a flood fill algorithm in javascript for use with HTML Canvas?</p>
<p>My requirements are simple: flood with a single color starting from a single point, where the boundary color is any color greater than a certain delta of the color at the specified point. </p>
<pre><code>var r1, r2; // red values
var g1, g2; // green values
var b1, b2; // blue values
var actualColorDelta = Math.sqrt((r1 - r2)*(r1 - r2) + (g1 - g2)*(g1 - g2) + (b1 - b2)*(b1 - b2))
function floodFill(canvas, x, y, fillColor, borderColorDelta) {
...
}
</code></pre>
<p>Update:</p>
<p>I wrote my own implementation of flood fill, which follows. It is slow, but accurate. About 37% of the time is taken up in two low-level array functions that are part of the prototype framework. They are called by push and pop, I presume. Most of the rest of the time is spent in the main loop. </p>
<pre><code>var ImageProcessing;
ImageProcessing = {
/* Convert HTML color (e.g. "#rrggbb" or "#rrggbbaa") to object with properties r, g, b, a.
* If no alpha value is given, 255 (0xff) will be assumed.
*/
toRGB: function (color) {
var r, g, b, a, html;
html = color;
// Parse out the RGBA values from the HTML Code
if (html.substring(0, 1) === "#")
{
html = html.substring(1);
}
if (html.length === 3 || html.length === 4)
{
r = html.substring(0, 1);
r = r + r;
g = html.substring(1, 2);
g = g + g;
b = html.substring(2, 3);
b = b + b;
if (html.length === 4) {
a = html.substring(3, 4);
a = a + a;
}
else {
a = "ff";
}
}
else if (html.length === 6 || html.length === 8)
{
r = html.substring(0, 2);
g = html.substring(2, 4);
b = html.substring(4, 6);
a = html.length === 6 ? "ff" : html.substring(6, 8);
}
// Convert from Hex (Hexidecimal) to Decimal
r = parseInt(r, 16);
g = parseInt(g, 16);
b = parseInt(b, 16);
a = parseInt(a, 16);
return {r: r, g: g, b: b, a: a};
},
/* Get the color at the given x,y location from the pixels array, assuming the array has a width and height as given.
* This interprets the 1-D array as a 2-D array.
*
* If useColor is defined, its values will be set. This saves on object creation.
*/
getColor: function (pixels, x, y, width, height, useColor) {
var redIndex = y * width * 4 + x * 4;
if (useColor === undefined) {
useColor = { r: pixels[redIndex], g: pixels[redIndex + 1], b: pixels[redIndex + 2], a: pixels[redIndex + 3] };
}
else {
useColor.r = pixels[redIndex];
useColor.g = pixels[redIndex + 1]
useColor.b = pixels[redIndex + 2];
useColor.a = pixels[redIndex + 3];
}
return useColor;
},
setColor: function (pixels, x, y, width, height, color) {
var redIndex = y * width * 4 + x * 4;
pixels[redIndex] = color.r;
pixels[redIndex + 1] = color.g,
pixels[redIndex + 2] = color.b;
pixels[redIndex + 3] = color.a;
},
/*
* fill: Flood a canvas with the given fill color.
*
* Returns a rectangle { x, y, width, height } that defines the maximum extent of the pixels that were changed.
*
* canvas .................... Canvas to modify.
* fillColor ................. RGBA Color to fill with.
* This may be a string ("#rrggbbaa") or an object of the form { r: red, g: green, b: blue, a: alpha }.
* x, y ...................... Coordinates of seed point to start flooding.
* bounds .................... Restrict flooding to this rectangular region of canvas.
* This object has these attributes: { x, y, width, height }.
* If undefined or null, use the whole of the canvas.
* stopFunction .............. Function that decides if a pixel is a boundary that should cause
* flooding to stop. If omitted, any pixel that differs from seedColor
* will cause flooding to stop. seedColor is the color under the seed point (x,y).
* Parameters: stopFunction(fillColor, seedColor, pixelColor).
* Returns true if flooding shoud stop.
* The colors are objects of the form { r: red, g: green, b: blue, a: alpha }
*/
fill: function (canvas, fillColor, x, y, bounds, stopFunction) {
// Supply default values if necessary.
var ctx, minChangedX, minChangedY, maxChangedX, maxChangedY, wasTested, shouldTest, imageData, pixels, currentX, currentY, currentColor, currentIndex, seedColor, tryX, tryY, tryIndex, boundsWidth, boundsHeight, pixelStart, fillRed, fillGreen, fillBlue, fillAlpha;
if (Object.isString(fillColor)) {
fillColor = ImageProcessing.toRGB(fillColor);
}
x = Math.round(x);
y = Math.round(y);
if (bounds === null || bounds === undefined) {
bounds = { x: 0, y: 0, width: canvas.width, height: canvas.height };
}
else {
bounds = { x: Math.round(bounds.x), y: Math.round(bounds.y), width: Math.round(bounds.y), height: Math.round(bounds.height) };
}
if (stopFunction === null || stopFunction === undefined) {
stopFunction = new function (fillColor, seedColor, pixelColor) {
return pixelColor.r != seedColor.r || pixelColor.g != seedColor.g || pixelColor.b != seedColor.b || pixelColor.a != seedColor.a;
}
}
minChangedX = maxChangedX = x - bounds.x;
minChangedY = maxChangedY = y - bounds.y;
boundsWidth = bounds.width;
boundsHeight = bounds.height;
// Initialize wasTested to false. As we check each pixel to decide if it should be painted with the new color,
// we will mark it with a true value at wasTested[row = y][column = x];
wasTested = new Array(boundsHeight * boundsWidth);
/*
$R(0, bounds.height - 1).each(function (row) {
var subArray = new Array(bounds.width);
wasTested[row] = subArray;
});
*/
// Start with a single point that we know we should test: (x, y).
// Convert (x,y) to image data coordinates by subtracting the bounds' origin.
currentX = x - bounds.x;
currentY = y - bounds.y;
currentIndex = currentY * boundsWidth + currentX;
shouldTest = [ currentIndex ];
ctx = canvas.getContext("2d");
//imageData = ctx.getImageData(bounds.x, bounds.y, bounds.width, bounds.height);
imageData = ImageProcessing.getImageData(ctx, bounds.x, bounds.y, bounds.width, bounds.height);
pixels = imageData.data;
seedColor = ImageProcessing.getColor(pixels, currentX, currentY, boundsWidth, boundsHeight);
currentColor = { r: 0, g: 0, b: 0, a: 1 };
fillRed = fillColor.r;
fillGreen = fillColor.g;
fillBlue = fillColor.b;
fillAlpha = fillColor.a;
while (shouldTest.length > 0) {
currentIndex = shouldTest.pop();
currentX = currentIndex % boundsWidth;
currentY = (currentIndex - currentX) / boundsWidth;
if (! wasTested[currentIndex]) {
wasTested[currentIndex] = true;
//currentColor = ImageProcessing.getColor(pixels, currentX, currentY, boundsWidth, boundsHeight, currentColor);
// Inline getColor for performance.
pixelStart = currentIndex * 4;
currentColor.r = pixels[pixelStart];
currentColor.g = pixels[pixelStart + 1]
currentColor.b = pixels[pixelStart + 2];
currentColor.a = pixels[pixelStart + 3];
if (! stopFunction(fillColor, seedColor, currentColor)) {
// Color the pixel with the fill color.
//ImageProcessing.setColor(pixels, currentX, currentY, boundsWidth, boundsHeight, fillColor);
// Inline setColor for performance
pixels[pixelStart] = fillRed;
pixels[pixelStart + 1] = fillGreen;
pixels[pixelStart + 2] = fillBlue;
pixels[pixelStart + 3] = fillAlpha;
if (minChangedX < currentX) { minChangedX = currentX; }
else if (maxChangedX > currentX) { maxChangedX = currentX; }
if (minChangedY < currentY) { minChangedY = currentY; }
else if (maxChangedY > currentY) { maxChangedY = currentY; }
// Add the adjacent four pixels to the list to be tested, unless they have already been tested.
tryX = currentX - 1;
tryY = currentY;
tryIndex = tryY * boundsWidth + tryX;
if (tryX >= 0 && ! wasTested[tryIndex]) {
shouldTest.push(tryIndex);
}
tryX = currentX;
tryY = currentY + 1;
tryIndex = tryY * boundsWidth + tryX;
if (tryY < boundsHeight && ! wasTested[tryIndex]) {
shouldTest.push(tryIndex);
}
tryX = currentX + 1;
tryY = currentY;
tryIndex = tryY * boundsWidth + tryX;
if (tryX < boundsWidth && ! wasTested[tryIndex]) {
shouldTest.push(tryIndex);
}
tryX = currentX;
tryY = currentY - 1;
tryIndex = tryY * boundsWidth + tryX;
if (tryY >= 0 && ! wasTested[tryIndex]) {
shouldTest.push(tryIndex);
}
}
}
}
//ctx.putImageData(imageData, bounds.x, bounds.y);
ImageProcessing.putImageData(ctx, imageData, bounds.x, bounds.y);
return { x: minChangedX + bounds.x, y: minChangedY + bounds.y, width: maxChangedX - minChangedX + 1, height: maxChangedY - minChangedY + 1 };
},
getImageData: function (ctx, x, y, w, h) {
return ctx.getImageData(x, y, w, h);
},
putImageData: function (ctx, data, x, y) {
ctx.putImageData(data, x, y);
}
};
</code></pre>
<p>BTW, when I call this, I use a custom stopFunction:</p>
<pre><code> stopFill : function (fillColor, seedColor, pixelColor) {
// Ignore alpha difference for now.
return Math.abs(pixelColor.r - seedColor.r) > this.colorTolerance || Math.abs(pixelColor.g - seedColor.g) > this.colorTolerance || Math.abs(pixelColor.b - seedColor.b) > this.colorTolerance;
},
</code></pre>
<p>If anyone can see a way to improve performance of this code, I would appreciate it. The basic idea is:
1) Seed color is the initial color at the point to start flooding.
2) Try four adjacent points: up, right, down and left one pixel.
3) If point is out of range or has been visited already, skip it.
4) Otherwise push point onto to the stack of interesting points.
5) Pop the next interesting point off the stack.
6) If the color at that point is a stop color (as defined in the stopFunction) then stop processing that point and skip to step 5.
7) Otherwise, skip to step 2.
8) When there are no more interesting points to visit, stop looping.</p>
<p>Remembering that a point has been visited requires an array with the same number of elements as there are pixels.</p>
| 0 | 4,288 |
How should I handle "java.net.SocketException: Connection reset" in multithread AWS S3 file upload?
|
<p>I have a ThreadPoolExecutorService to which I'm submitting runnable jobs that are uploading large (1-2 GB) files to Amazon's S3 file system, using the AWS Java SDK. Occasionally one of my worker threads will report a java.net.SocketException with "Connection reset" as the cause and then die.</p>
<p>AWS doesn't use checked exceptions so I actually can't catch SocketException directly---it must be wrapped somehow. My question is how I should deal with this problem so I can retry any problematic uploads and increase the reliability of my program.</p>
<p>Would the Multipart Upload API be more reliable?</p>
<p>Is there some exception I can reliably catch to enable retries?</p>
<p>Here's the stack trace. The com.example.* code is mine. Basically what the DataProcessorAWS call does is call <code>putObject(String bucketName, String key, File file)</code> on an instance of <code>AmazonS3Client</code> that's shared across threads.</p>
<pre><code>14/12/11 18:43:17 INFO http.AmazonHttpClient: Unable to execute HTTP request: Connection reset
java.net.SocketException: Connection reset
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:118)
at java.net.SocketOutputStream.write(SocketOutputStream.java:159)
at sun.security.ssl.OutputRecord.writeBuffer(OutputRecord.java:377)
at sun.security.ssl.OutputRecord.write(OutputRecord.java:363)
at sun.security.ssl.SSLSocketImpl.writeRecordInternal(SSLSocketImpl.java:830)
at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:801)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:122)
at org.apache.http.impl.io.AbstractSessionOutputBuffer.write(AbstractSessionOutputBuffer.java:169)
at org.apache.http.impl.io.ContentLengthOutputStream.write(ContentLengthOutputStream.java:119)
at org.apache.http.entity.InputStreamEntity.writeTo(InputStreamEntity.java:102)
at com.amazonaws.http.RepeatableInputStreamRequestEntity.writeTo(RepeatableInputStreamRequestEntity.java:153)
at org.apache.http.entity.HttpEntityWrapper.writeTo(HttpEntityWrapper.java:98)
at org.apache.http.impl.client.EntityEnclosingRequestWrapper$EntityWrapper.writeTo(EntityEnclosingRequestWrapper.java:108)
at org.apache.http.impl.entity.EntitySerializer.serialize(EntitySerializer.java:122)
at org.apache.http.impl.AbstractHttpClientConnection.sendRequestEntity(AbstractHttpClientConnection.java:271)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.sendRequestEntity(ManagedClientConnectionImpl.java:197)
at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:257)
at com.amazonaws.http.protocol.SdkHttpRequestExecutor.doSendRequest(SdkHttpRequestExecutor.java:47)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:715)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:520)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:685)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:460)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:295)
at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3697)
at com.amazonaws.services.s3.AmazonS3Client.putObject(AmazonS3Client.java:1434)
at com.amazonaws.services.s3.AmazonS3Client.putObject(AmazonS3Client.java:1294)
at com.example.DataProcessorAWS$HitWriter.close(DataProcessorAWS.java:156)
at com.example.DataProcessorAWS$Processor.run(DataProcessorAWS.java:264)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
| 0 | 1,377 |
Best approach to real time http streaming to HTML5 video client
|
<p>I'm really stuck trying to understand the best way to stream real time output of ffmpeg to a HTML5 client using node.js, as there are a number of variables at play and I don't have a lot of experience in this space, having spent many hours trying different combinations.</p>
<p>My use case is:</p>
<p>1) IP video camera RTSP H.264 stream is picked up by FFMPEG and remuxed into a mp4 container using the following FFMPEG settings in node, output to STDOUT. This is only run on the initial client connection, so that partial content requests don't try to spawn FFMPEG again.</p>
<pre><code>liveFFMPEG = child_process.spawn("ffmpeg", [
"-i", "rtsp://admin:12345@192.168.1.234:554" , "-vcodec", "copy", "-f",
"mp4", "-reset_timestamps", "1", "-movflags", "frag_keyframe+empty_moov",
"-" // output to stdout
], {detached: false});
</code></pre>
<p>2) I use the node http server to capture the STDOUT and stream that back to the client upon a client request. When the client first connects I spawn the above FFMPEG command line then pipe the STDOUT stream to the HTTP response.</p>
<pre><code>liveFFMPEG.stdout.pipe(resp);
</code></pre>
<p>I have also used the stream event to write the FFMPEG data to the HTTP response but makes no difference</p>
<pre><code>xliveFFMPEG.stdout.on("data",function(data) {
resp.write(data);
}
</code></pre>
<p>I use the following HTTP header (which is also used and working when streaming pre-recorded files)</p>
<pre><code>var total = 999999999 // fake a large file
var partialstart = 0
var partialend = total - 1
if (range !== undefined) {
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
}
var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : total; // fake a large file if no range reques
var chunksize = (end-start)+1;
resp.writeHead(206, {
'Transfer-Encoding': 'chunked'
, 'Content-Type': 'video/mp4'
, 'Content-Length': chunksize // large size to fake a file
, 'Accept-Ranges': 'bytes ' + start + "-" + end + "/" + total
});
</code></pre>
<p>3) The client has to use HTML5 video tags.</p>
<p>I have no problems with streaming playback (using fs.createReadStream with 206 HTTP partial content) to the HTML5 client a video file previously recorded with the above FFMPEG command line (but saved to a file instead of STDOUT), so I know the FFMPEG stream is correct, and I can even correctly see the video live streaming in VLC when connecting to the HTTP node server.</p>
<p>However trying to stream live from FFMPEG via node HTTP seems to be a lot harder as the client will display one frame then stop. I suspect the problem is that I am not setting up the HTTP connection to be compatible with the HTML5 video client. I have tried a variety of things like using HTTP 206 (partial content) and 200 responses, putting the data into a buffer then streaming with no luck, so I need to go back to first principles to ensure I'm setting this up the right way.</p>
<p>Here is my understanding of how this should work, please correct me if I'm wrong:</p>
<p>1) FFMPEG should be setup to fragment the output and use an empty moov (FFMPEG frag_keyframe and empty_moov mov flags). This means the client does not use the moov atom which is typically at the end of the file which isn't relevant when streaming (no end of file), but means no seeking possible which is fine for my use case.</p>
<p>2) Even though I use MP4 fragments and empty MOOV, I still have to use HTTP partial content, as the HTML5 player will wait until the entire stream is downloaded before playing, which with a live stream never ends so is unworkable.</p>
<p>3) I don't understand why piping the STDOUT stream to the HTTP response doesn't work when streaming live yet if I save to a file I can stream this file easily to HTML5 clients using similar code. Maybe it's a timing issue as it takes a second for the FFMPEG spawn to start, connect to the IP camera and send chunks to node, and the node data events are irregular as well. However the bytestream should be exactly the same as saving to a file, and HTTP should be able to cater for delays.</p>
<p>4) When checking the network log from the HTTP client when streaming a MP4 file created by FFMPEG from the camera, I see there are 3 client requests: A general GET request for the video, which the HTTP server returns about 40Kb, then a partial content request with a byte range for the last 10K of the file, then a final request for the bits in the middle not loaded. Maybe the HTML5 client once it receives the first response is asking for the last part of the file to load the MP4 MOOV atom? If this is the case it won't work for streaming as there is no MOOV file and no end of the file.</p>
<p>5) When checking the network log when trying to stream live, I get an aborted initial request with only about 200 bytes received, then a re-request again aborted with 200 bytes and a third request which is only 2K long. I don't understand why the HTML5 client would abort the request as the bytestream is exactly the same as I can successfully use when streaming from a recorded file. It also seems node isn't sending the rest of the FFMPEG stream to the client, yet I can see the FFMPEG data in the .on event routine so it is getting to the FFMPEG node HTTP server.</p>
<p>6) Although I think piping the STDOUT stream to the HTTP response buffer should work, do I have to build an intermediate buffer and stream that will allow the HTTP partial content client requests to properly work like it does when it (successfully) reads a file? I think this is the main reason for my problems however I'm not exactly sure in Node how to best set that up. And I don't know how to handle a client request for the data at the end of the file as there is no end of file.</p>
<p>7) Am I on the wrong track with trying to handle 206 partial content requests, and should this work with normal 200 HTTP responses? HTTP 200 responses works fine for VLC so I suspect the HTML5 video client will only work with partial content requests?</p>
<p>As I'm still learning this stuff its difficult to work through the various layers of this problem (FFMPEG, node, streaming, HTTP, HTML5 video) so any pointers will be greatly appreciated. I have spent hours researching on this site and the net, and I have not come across anyone who has been able to do real time streaming in node but I can't be the first, and I think this should be able to work (somehow!).</p>
| 0 | 1,888 |
Error: deleted_client The OAuth client was deleted
|
<p>How can you delete an old clientID?</p>
<p>I have created and generated a new clientID in the google developer console</p>
<p><a href="https://i.stack.imgur.com/LQpqh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LQpqh.png" alt="google developer console"></a></p>
<p>the new clientID does not match the one in the browser. This probably explains the error while attempting to signin</p>
<p><a href="https://i.stack.imgur.com/NqBox.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NqBox.png" alt="error while attempting to signin"></a></p>
<p>I know everything is right in the app set up</p>
<ul>
<li><p>this is my <strong>package.json</strong></p>
<p>"name": "auth-firebase-2",
"version": "0.0.1",
"author": "Ionic Framework",
"homepage": "<a href="http://ionicframework.com/" rel="nofollow noreferrer">http://ionicframework.com/</a>",
"private": true,
"scripts": {
"clean": "ionic-app-scripts clean",
"build": "ionic-app-scripts build",
"lint": "ionic-app-scripts lint",
"ionic:build": "ionic-app-scripts build",
"ionic:serve": "ionic-app-scripts serve"
},
"dependencies": {
"@angular/animations": "5.2.9",
"@angular/common": "5.2.9",
"@angular/compiler": "5.2.9",
"@angular/compiler-cli": "5.2.9",
"@angular/core": "5.2.9",
"@angular/forms": "5.2.9",
"@angular/http": "5.2.9",
"@angular/platform-browser": "5.2.9",
"@angular/platform-browser-dynamic": "5.2.9",
"@ionic-native/core": "4.6.0",
"@ionic-native/splash-screen": "4.6.0",
"@ionic-native/status-bar": "4.6.0",
"@ionic/storage": "2.1.3",
"angularfire2": "^5.0.0-rc.6.0",
"cordova-android": "7.0.0",
"cordova-browser": "5.0.3",
"cordova-ios": "4.5.4",
"cordova-plugin-device": "^2.0.2",
"cordova-plugin-googleplus": "^5.3.0",
"cordova-plugin-ionic-keyboard": "^2.0.5",
"cordova-plugin-ionic-webview": "^1.2.0",
"cordova-plugin-splashscreen": "^5.0.2",
"cordova-plugin-whitelist": "^1.3.3",
"firebase": "^4.13.0",
"ionic-angular": "3.9.2",
"ionicons": "3.0.0",
"rxjs": "5.5.8",
"sw-toolbox": "3.6.0",
"zone.js": "0.8.26"
},
"devDependencies": {
"@ionic/app-scripts": "3.1.9",
"typescript": "~2.6.2"
},
"description": "An Ionic project",
"cordova": {
"plugins": {
"cordova-plugin-whitelist": {},
"cordova-plugin-device": {},
"cordova-plugin-splashscreen": {},
"cordova-plugin-ionic-webview": {},
"cordova-plugin-ionic-keyboard": {},
"cordova-plugin-googleplus": {
"WEB_APPLICATION_CLIENT_ID": "1043269342338-6fta7jjp2u2rf4fhiupme8b0g1bf3br4.apps.googleusercontent.com",
"REVERSED_CLIENT_ID": "com.googleusercontent.apps.558165536676-14360cssjil4t4c6tcvnr9ugu8lanehc"
}
},
"platforms": [
"browser",
"android"
]
}
}</p></li>
<li><p>Google Sign in is enabled </p></li>
</ul>
<p><a href="https://i.stack.imgur.com/y0yNX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y0yNX.png" alt="enter image description here"></a></p>
<ul>
<li>I have created the credentials in the google developper console and GooglePlus API is enabled as well</li>
</ul>
<p>The only issue is that the browser seems to retain the old clientID (now deleted)</p>
<p>I have tried as follows :
- clear caching in chrome : settings > advanced > clear browsing data
- npm cache clean</p>
<p>nothing worked. So How do you actually remove all references to an old clientID ?</p>
<p>Thanks</p>
| 0 | 1,548 |
DTrace missing Java frames with ustack(). Running on Joyent SmartOS infrastructure container
|
<p>I cannot get any Java stack with dtrace in a Joyent SmartOS instance. </p>
<p>I tried the <code>java:15.1.1</code> image and a plain SmartOS 'base64' image, where I installed openjdk 8.</p>
<p>I most basic example:
cat Loop.java </p>
<pre><code>[root@7e8c2a25-c852-4967-b60c-7b4fbd9a1de5 /demo]# cat Loop.java
class Loop {
public static void main(String[] args) throws InterruptedException {
while (true) {
System.out.println("Sleepy");
Thread.sleep(2000);
}
}
}
[root@7e8c2a25-c852-4967-b60c-7b4fbd9a1de5 /demo]# javac Loop.java
[root@7e8c2a25-c852-4967-b60c-7b4fbd9a1de5 /demo]# java Loop
</code></pre>
<p>I added the <code>libdtrace_forceload.so</code> as <a href="https://stackoverflow.com/questions/36166805/how-do-i-use-the-hotspot-dtrace-probes-on-smartos/36167514#36167514">recommended</a>.</p>
<pre><code>export LD_AUDIT_64=/usr/lib/dtrace/64/libdtrace_forceload.so
</code></pre>
<p>It is a 64 bit JVM:</p>
<pre><code>[root@7e8c2a25-c852-4967-b60c-7b4fbd9a1de5 /demo]# java -version
openjdk version "1.7.0-internal"
OpenJDK Runtime Environment (build 1.7.0-internal-pkgsrc_2015_05_29_19_05-b00)
OpenJDK 64-Bit Server VM (build 24.76-b04, mixed mode)
</code></pre>
<p>When I run dtrace, and use jstack, I get the C-stacks. However, the JAVA frames are the raw addresses, quite useless:</p>
<pre><code>[root@7e8c2a25-c852-4967-b60c-7b4fbd9a1de5 ~]# pgrep -fn "java Loop"
32597
[root@7e8c2a25-c852-4967-b60c-7b4fbd9a1de5 ~]# dtrace -n 'syscall:::entry/pid == 32597/ { @num[ustack(20)] = count(); }'
dtrace: description 'syscall:::entry' matched 237 probes
^C
libc.so.1`__write+0xa
libjvm.so`_ZN2os5writeEiPKvj+0x128
libjvm.so`JVM_Write+0x34
libjava.so`writeBytes+0x1b5
libjava.so`Java_java_io_FileOutputStream_writeBytes+0x1f
0xffffbf7ffa612d98
0xffffbf7ffa606058
0xffffbf7ffa606058
0xffffbf7ffa606058
0xffffbf7ffa606058
0xffffbf7ffa606058
0xffffbf7ffa606058
0xffffbf7ffa606058
0xffffbf7ffa606058
0xffffbf7ffa606058
0xffffbf7ffa606058
0xffffbf7ffa606058
0xffffbf7ffa606058
0xffffbf7ffa6004e7
libjvm.so`_ZN9JavaCalls11call_helperEP9JavaValueP12methodHandleP17JavaCallArgumentsP6Thread+0x31d
*snip*
</code></pre>
<p>I do see hotspot probes are available:</p>
<pre><code>[root@7e8c2a25-c852-4967-b60c-7b4fbd9a1de5 ~]# dtrace -l | grep hotspot | more
6103 hotspot32597 libjvm.so _ZN17VM_GenCollectFull4doitEv gc-begin
6104 hotspot32597 libjvm.so _ZN15VM_GC_Operation13notify_gc_endEv gc-end
6105 hotspot32597 libjvm.so _ZN26VM_GenCollectForAllocation4doitEv gc-end
6106 hotspot32597 libjvm.so _ZN35VM_GenCollectForPermanentAllocation4doitEv gc-end
6107 hotspot32597 libjvm.so _ZN17VM_GenCollectFull4doitEv gc-end
6132 hotspot32597 libjvm.so _ZN13instanceKlass15initialize_implE19instanceKlassHandleP6Thread class-initialization-end
6133 hotspot32597 libjvm.so _ZN13instanceKlass15initialize_implE19instanceKlassHandleP6Thread class-initialization-erroneous
6441 hotspot_jni32597 libjvm.so jni_DeleteLocalRef DeleteLocalRef-entry
6442 hotspot_jni32597 libjvm.so jni_DeleteLocalRef DeleteLocalRef-return
6443 hotspot_jni32597 libjvm.so jni_DeleteWeakGlobalRef DeleteWeakGlobalRef-entry
6444 hotspot_jni32597 libjvm.so jni_DeleteWeakGlobalRef DeleteWeakGlobalRef-return
6445 hotspot_jni32597 libjvm.so jni_DestroyJavaVM DestroyJavaVM-entry
6446 hotspot_jni32597 libjvm.so jni_DestroyJavaVM DestroyJavaVM-return
</code></pre>
<p>Question: Is there a way to list ustack helpers and if they are loaded? Any way to get the Java stack?</p>
| 0 | 2,027 |
Make draggable element sortable within droppable using jQuery UI
|
<p><strong>RESOLVED</strong></p>
<p>So I studied <code>sortable()</code> with the <code>connectWith</code> attribute a bit more and found the solution was simpler than I expected, but I was thinking about it sort of backwards because of <code>draggable()</code> and <code>droppable()</code>.</p>
<p>Here's the fiddle: <a href="http://jsfiddle.net/DKBU9/12/" rel="nofollow noreferrer">http://jsfiddle.net/DKBU9/12/</a></p>
<hr>
<p><em>Original question follows:</em></p>
<p>This is an extension of a previous SO question that I felt should be kept separate.</p>
<p>The original question is here: <a href="https://stackoverflow.com/questions/20964467/jquery-ui-clone-droppable-sortable-list-after-drop-event/20964766?noredirect=1#20964766">jQuery UI - Clone droppable/sortable list after drop event</a>. It regards reinitializing the droppable handler on cloned elements.</p>
<p>On top of that though, I'm trying to allow the elements that have been dragged from the initial list to be sorted within the droppable lists.</p>
<p>Here is a fiddle essentially illustrating the current behaviour as a result of the original question: <a href="http://jsfiddle.net/DKBU9/7/" rel="nofollow noreferrer">http://jsfiddle.net/DKBU9/7/</a></p>
<p>And the required code because SO likes to complain and bloat these posts:</p>
<p>HTML</p>
<pre><code><ul id="draggables">
<li>foo1</li>
<li>foo2</li>
<li>foo3</li>
</ul>
<ul class="droppable new">
</ul>
</code></pre>
<p>JS</p>
<pre><code>$(function() {
$('#draggables > li').draggable({
appendTo: 'document',
revert: 'invalid'
});
$('.droppable > li').draggable({
appendTo: 'document',
revert: 'invalid'
});
$('#draggables').droppable({
accept: '.droppable > li',
drop: function(event, ui) {
ui.draggable.detach().css({top: 0,left: 0}).appendTo($(this));
cleanUp();
}
});
initDrop($('.droppable'));
});
function initDrop($element) {
$element.droppable({
accept: function(event, ui) {
return true;
},
drop: function(event, ui) {
if($(this).hasClass('new')) {
var clone = $(this).clone();
$(this).after(clone);
$(this).removeClass('new');
initDrop( clone );
}
ui.draggable.detach().css({top: 0,left: 0}).appendTo($(this));
cleanUp();
}
}).sortable({
items: 'li',
revert: false,
update: function() {
cleanUp();
}
});
}
function cleanUp() {
$('.droppable').not('.new').each(function() {
if($(this).find('li').length == 0) {
$(this).remove();
}
});
}
</code></pre>
<p>Reference question: <a href="https://stackoverflow.com/questions/18399543/jquery-ui-combine-sortable-and-draggable">Jquery UI combine sortable and draggable</a></p>
<p>I've been trying to use this SO question to resolve my issue as the result is exactly what I'm trying to achieve, specifically the last fiddle provided in the comments of the accepted answer, but I can't seem to figure out how to adapt it to my code considering the minor differences. For example, the fiddle in that question clones the draggable rather than dragging the actual element and unlike mine doesn't allow elements to be dragged back into the initial list.</p>
<p>So any help to try to get that result for my code would be greatly appreciated.</p>
<p>Also, in that example, the <code>accept</code> attribute is set as a function to return true. What is the reason for this? Doesn't that just mean it will accept anything, or any draggable element?</p>
<p>EDIT: I read a couple answers that just used sortable() with the connectWith attribute, but for some reason I didn't think it did what I needed to, partly because I didn't want the initial list to be sortable as well. However, using sortable() alone seems to get the functionality I'm after but I just haven't yet adapted all the event handlers.</p>
| 0 | 1,620 |
Can't bind to 'ngIf' since it isn't a known property of 'md-card-title'
|
<p>I am learning <code>Angular2 RC5</code> with Angular2 material libraries and getting it to run in a <code>AspNetCore 1.0</code> app using <code>VisualStudio 2015.</code> I took a perfectly running <code>Angular2 RC5</code> single page application and tried to introduce lazy loading where only the login page will load first. When I have successfully logged in, I want to load the remaining pages. </p>
<p>When I clicked on the login button in SPA mode, I would redirect successfully to the DashboardComponent page which was preloaded with the login page - that was before I introduced lazy loading.
After following <a href="https://angular.io/docs/ts/latest/guide/ngmodule.html#!#lazy-load" rel="nofollow">this tutorial</a> I now get these errors</p>
<p><strong><em>Error Snippet</em></strong></p>
<blockquote>
<pre><code>EXCEPTION: Error: Uncaught (in promise): Template parse errors: Can't bind to 'ngIf' since it isn't a known property of 'md-card-title'.
1. If 'md-card-title' is an Angular component and it has 'ngIf' input, then verify that it is part of this module.
2. If 'md-card-title' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message. ("
<md-card-title [ERROR ->]*ngIf="!showMessage && !isApproved">
Please use the information below...
</md-card-title> "): ReportListComponent@63:23 Property binding ngIf not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "directives" section. ("
</code></pre>
</blockquote>
<p>Why is the ngIf directive suddenly not working? It was working before I moved the Dashboard to load lazily post the login success.</p>
<p>I have gone all the way till using the Shared modules approach in the link I posted above. Is not using the Shared modules a cause for this issue? I presumed module sharing to be a way to clean up the code and not repeat stuff once everything works and nothing more than that. </p>
<p>My Dashboard is similar to the HeroesList page in the link I am following above, where in it loads some more pages the minute the DashboardModule is loaded. I have put breakpoints in the Dashboard page on the MVC side and have confirmed that the Dashboard and pages after does load lazily only on a successful login.</p>
<p>The error seems like its not able to get the reference of core angular references and/or angular2 material libraries. I have put all of those imports listed here in all the modules that would have them other than the routing modules</p>
<pre><code>import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { MdRadioModule } from '@angular2-material/radio';
import { MdToolbarModule } from '@angular2-material/toolbar';
import { MdButtonModule } from '@angular2-material/button';
import { MdIconModule } from '@angular2-material/icon';
import { MdProgressBarModule } from '@angular2-material/progress-bar';
import { MdListModule } from '@angular2-material/list';
import { MdInputModule } from '@angular2-material/input';
import { MdCardModule } from '@angular2-material/card';
</code></pre>
<p>Still I get the errors as in the snippet above. What could I be missing?
Any help or tips appreciated.</p>
<p><strong>EDIT</strong></p>
<p><strong><em>Dashboard.Module.ts</em></strong></p>
<pre><code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { MdRadioModule } from '@angular2-material/radio';
import { MdToolbarModule } from '@angular2-material/toolbar';
import { MdButtonModule } from '@angular2-material/button';
import { MdIconModule } from '@angular2-material/icon';
import { MdProgressBarModule } from '@angular2-material/progress-bar';
import { MdListModule } from '@angular2-material/list';
import { MdInputModule } from '@angular2-material/input';
import { MdCardModule } from '@angular2-material/card';
import { AppService } from './app.service';
import { DashboardRoutingModule } from './Dashboard-routing.Module';
@NgModule({
imports: [
CommonModule, HttpModule, FormsModule, RouterModule,
MdRadioModule, MdToolbarModule, MdProgressBarModule,
MdButtonModule, MdIconModule, MdListModule,
MdCardModule, MdInputModule, MdToolbarModule,
DashboardRoutingModule],
/*declarations: [ DashboardComponent ],*/
exports: [ CommonModule ],
providers: [ AppService ]
})
export class DashboardModule { }
</code></pre>
<p><strong><em>DashBoardComponent.ts</em></strong></p>
<pre><code>import { Component } from '@angular/core';
import { AppService } from './app.service';
@Component({
template: `
<router-outlet></router-outlet>
`
})
export class DashboardComponent {
userName = '';
constructor(service: AppService) {
//this.userName = service.userName;
}
}
</code></pre>
<p><strong><em>dashboard-routing.Module.ts</em></strong></p>
<pre><code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { HttpModule } from '@angular/http';
import { MdRadioModule } from '@angular2-material/radio';
import { MdToolbarModule } from '@angular2-material/toolbar';
import { MdButtonModule } from '@angular2-material/button';
import { MdIconModule } from '@angular2-material/icon';
import { MdProgressBarModule } from '@angular2-material/progress-bar';
import { MdListModule } from '@angular2-material/list';
import { MdInputModule } from '@angular2-material/input';
import { MdCardModule } from '@angular2-material/card';
import { DashboardComponent } from './DashBoardComponent';
import { ReportListComponent } from './ReportListComponent';
import { ReportDetailComponent } from './ReportDetailComponent';
const routes: Routes = [
{
children: [
{ path: 'Home/ReportList', component: ReportListComponent },
{ path: 'Home/ReportDetail/:reportId', component: ReportDetailComponent }
]
}
];
@NgModule({
imports: [RouterModule.forChild([routes])
],
declarations: [ DashboardComponent, ReportListComponent, ReportDetailComponent ],
exports: [RouterModule, ReportListComponent, ReportDetailComponent, CommonModule]
})
export class DashboardRoutingModule {}
</code></pre>
| 0 | 2,168 |
Rewrite spring-security redirect URLs
|
<p>I'm trying to get Tuckey UrlRewriteFilter to tidy up URLs for my webapp. One problem I've got is that when spring-security notices that an anonymous user is trying to access a protected resource it redirects to a URL which includes the servlet path.</p>
<p>What I'd like is, by example:</p>
<pre><code>> GET http://localhost:8080/my-context/protected-resource
< Location: http://localhost:8080/my-context/login
</code></pre>
<p>What I currently get is:</p>
<pre><code>> GET http://localhost:8080/my-context/protected-resource
< Location: http://localhost:8080/my-context/-/login
</code></pre>
<p>Relevant documents I've found so far:</p>
<p>DefaultRedirectStrategy, which does the actual redirect in question: <a href="http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/DefaultRedirectStrategy.html" rel="nofollow noreferrer">http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/DefaultRedirectStrategy.html</a>. It has a contextRelative property which is tempting but I don't think is going to cut it, if I can even find a way of configuring it.</p>
<p>A blog post that helped get me this far: <a href="http://nonrepeatable.blogspot.com/2009/11/using-spring-security-with-tuckey.html" rel="nofollow noreferrer">http://nonrepeatable.blogspot.com/2009/11/using-spring-security-with-tuckey.html</a></p>
<p>What I'd like to know is:</p>
<ol>
<li>Can/should I convince Tuckey to rewrite the Location header. <outbound-rule> doesn't seem to help any here.</li>
<li>Can/should I somehow tweak the SS config to emit the rewritten URL. I don't think this is quite as tidy, as it'd break if rewrite was disabled.</li>
</ol>
<p><code>web.xml</code> looks like</p>
<pre><code><filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
<init-param>
<param-name>LogLevel</param-name>
<param-value>log4j</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
<servlet>
<servlet-name>my-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>psms</servlet-name>
<url-pattern>/-/*</url-pattern>
</servlet-mapping>
</code></pre>
<p><code>urlrewrite.xml</code> looks like:</p>
<pre><code><urlrewrite>
<rule>
<from>^/(.*)$</from>
<to>/-/$1</to>
</rule>
</urlrewrite>
</code></pre>
<p><code>applicationContent-security.xml</code> looks like:</p>
<pre><code><http auto-config="true">
<!-- allow GET requests to /login without authentication -->
<intercept-url pattern="/-/login" method="GET" filters="none"/>
<intercept-url pattern="/-/admin/**" access="ROLE_ADMIN"/>
<intercept-url pattern="/-/**" access="ROLE_USER"/>
<form-login login-page="/-/login"
login-processing-url="/-/login.do"
authentication-failure-url="/-/login?login_error"
default-target-url="/-/index"
always-use-default-target="true"/>
<logout logout-url="/-/logout"
logout-success-url="/-/login"/>
<access-denied-handler error-page="/-/access-denied"/>
</http>
</code></pre>
| 0 | 1,824 |
Conditional Output Shiny UI
|
<p>I have survey data. I want to use Shiny to share results of my univariate and bivariate analyses with collaborators. In the survey there are numeric and factor variables. Depending on whether the person viewing the Shiny applications is interested in univariate/bivariate summaries, and depending on the variable type(s) they want to summarize I want different output to appear. </p>
<p>Specifically,</p>
<p>i) If univariate and numeric then display:</p>
<ul>
<li>Item response rate: <code>length() - sum(is.na())</code> </li>
<li><code>hist()</code> </li>
<li><code>summary()</code></li>
</ul>
<p>ii) If univariate and factor then display:</p>
<ul>
<li>Item response rate</li>
<li><code>barplot()</code></li>
<li><code>table()</code></li>
<li><code>prop.table()</code></li>
</ul>
<p>iii) If bivariate and numeric*numeric then display:</p>
<ul>
<li>Item response rate</li>
<li>Scatter graph: <code>plot(x,y)</code></li>
<li><code>summary(x)</code></li>
<li><code>summary(y)</code></li>
<li><code>cor(x,y,method="spearman")</code></li>
</ul>
<p>iv) If bivariate and factor*factor then display:</p>
<ul>
<li>Item response rate</li>
<li>Bar Chart...something like "rCharts nvd3 multiBarChart"</li>
<li><code>table(x,y)</code></li>
<li><code>prop.table(x,y)</code></li>
<li><code>chisq.test(x,y)</code></li>
</ul>
<p>v) If bivariate and (factor*numeric OR numeric*factor ) then display:</p>
<ul>
<li>Item response rate</li>
<li>boxplot</li>
<li>summary of numeric variable by factor variable: <code>by(numeric, factor, summary)</code></li>
<li>Kruskal Wallis Test <code>kruskal.test(numeric ~ factor)</code></li>
</ul>
<p>Currently, I have code to generate the desired output for all 5 steps as separate applications. I want to bring them together into 1 Shiny app. I am struggling conceptually with how to set up the <code>mainPanel()</code> display to be reactive to the different output that it will receive as a function of the choices the user is making on the <code>sidebarPanel()</code> UI. </p>
<p>Specifically,</p>
<ul>
<li>How to change <code>mainPanel()</code> UI headers to reflect different outputs</li>
<li>How to conceptually expand my code below to include multiple pieces of output (i.e. Below code works for a single piece <code>verbatimTextOutput()</code> but I don't know how to proceed for the multiple pieces/types of output I want to display as discussed in (i-iv) above. e.g. Text, tables, plots. </li>
</ul>
<p>Below is my code for the ui.R file:</p>
<pre><code>library(shiny)
shinyUI(pageWithSidebar(
headerPanel("Shiny Example"),
sidebarPanel(
wellPanel(
selectInput(inputId = "variable1",label = "Select First Variable:",
choices = c("Binary Variable 1" = "binary1",
"Binary Variable 2" = "binary2",
"Continuous Variable 1" = "cont1",
"Continuous Variable 2" = "cont2"),
selected = "Binary Variable 1"
)
),
wellPanel(
checkboxInput("bivariate", "Proceed to Bivariate Analysis", FALSE),
conditionalPanel(
condition="input.bivariate==true",
selectInput(inputId = "variable2",
label = "Select Second Variable:",
choices = c("Binary Variable 1" = "binary1",
"Binary Variable 2" = "binary2",
"Continuous Variable 1" = "cont1",
"Continuous Variable 2" = "cont2"),
selected = "Binary Variable 2"
)
)
)
),
mainPanel(
h5("Output"),
verbatimTextOutput("out")
)
))
</code></pre>
<p>Below is my simulated data and my server.R file:</p>
<pre><code>binary1 <- rbinom(100,1,0.5)
binary2 <- rbinom(100,1,0.5)
cont1 <- rnorm(100)
cont2 <- rnorm(100)
dat <- as.data.frame(cbind(binary1, binary2, cont1, cont2))
dat$binary1 <- as.factor(dat$binary1)
dat$binary2 <- as.factor(dat$binary2)
dat$cont1 <- as.numeric(dat$cont1)
dat$cont2 <- as.numeric(dat$cont2)
library(shiny)
library(rCharts)
shinyServer(function(input, output) {
inputVar1 <- reactive({
parse(text=sub(" ","",paste("dat$", input$variable1)))
})
inputVar2 <- reactive({
parse(text=sub(" ","",paste("dat$", input$variable2)))
})
output$out <- renderPrint({
if ( (input$bivariate==FALSE) & (is.factor(eval(inputVar1()))==TRUE) ) {
table(eval(inputVar1()))
} else {
if ( (input$bivariate==FALSE) & (is.numeric(eval(inputVar1()))==TRUE) ) {
summary(eval(inputVar1()))
} else {
if ( (input$bivariate==TRUE) & (is.factor(eval(inputVar1()))==TRUE) & (is.factor(eval(inputVar2()))==TRUE) ) {
table(eval(inputVar1()), eval(inputVar2()))
} else {
if ( (input$bivariate==TRUE) & (is.numeric(eval(inputVar1()))==TRUE) & (is.numeric(eval(inputVar2()))==TRUE) ) {
cor(eval(inputVar1()), eval(inputVar2()))
} else {
if ( (input$bivariate==TRUE) & (is.factor(eval(inputVar1()))==TRUE) & (is.numeric(eval(inputVar2()))==TRUE) ) {
by(eval(inputVar2()), eval(inputVar1()), summary)
} else {
if ( (input$bivariate==TRUE) & (is.numeric(eval(inputVar1()))==TRUE) & (is.factor(eval(inputVar2()))==TRUE) ) {
by(eval(inputVar1()), eval(inputVar2()), summary)
}
}
}
}
}
}
})
})
</code></pre>
<p>Any help you could provide would be greatly appreciated. Even simply showing how to adjust the code to render two pieces of desired output given choices of variables. And how to adjust headers to reflect named pieces of output. </p>
<p>Thanks in advance...Chris</p>
| 0 | 1,907 |
Android DrawerLayout - No drawer view found with gravity
|
<p>When I click on my drawer toggle I get the following exception:</p>
<blockquote>
<p>java.lang.IllegalArgumentException: No drawer view found with gravity
LEFT</p>
</blockquote>
<p>This is my <code>activity_drawer.xml</code>:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"/>
<FrameLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<fragment
android:id="@+id/navigation"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.xyz.ui.navigation.NavigationFragment"
tools:layout="@layout/fragment_navigation" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
</code></pre>
<p>My <code>fragment_navigation.xml</code>:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start">
</ListView>
</code></pre>
<p>And my list item:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/navigation_item_text"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</code></pre>
| 0 | 1,057 |
How to assign which MenuItems open onClick when multiple Menus are present on the material-ui Appbar using React?
|
<p>I created an AppBar with a menu based on the examples given on <a href="https://material-ui-next.com/demos/app-bar/" rel="noreferrer">the material UI site</a> and it works fine with one menu. But when I try adding a second dropdown menu, on clicking either icon, I get the same set of MenuItems showing up as seen in the image.</p>
<p><a href="https://i.stack.imgur.com/TKdtn.png" rel="noreferrer">Here is the list of menu items that are showing up when either icon is clicked</a></p>
<pre><code>import React, { Component } from 'react';
// Material UI Imports
import { withStyles } from 'material-ui/styles';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import Typography from 'material-ui/Typography';
import Button from 'material-ui/Button';
import IconButton from 'material-ui/IconButton';
import Tooltip from 'material-ui/Tooltip';
import Menu, { MenuItem } from 'material-ui/Menu';
import PeopleIcon from 'material-ui-icons/People';
import ViewListIcon from 'material-ui-icons/ViewList';
import CompareArrowsIcon from 'material-ui-icons/CompareArrows';
const styles = {
root: {
width: '100%',
},
flex: {
flex: 1,
},
menuItem: {
paddingLeft: '10px'
}
}
class Header extends Component {
constructor(props) {
super(props);
this.state = { anchorEl: null };
}
handleMenu = event => {
console.log(event.currentTarget);
this.setState({ anchorEl: event.currentTarget });
}
handleClose = () => {
this.setState({ anchorEl: null });
}
render() {
const { classes } = this.props;
const { anchorEl } = this.state;
const open = Boolean(anchorEl);
return(
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<Typography type="title" color="inherit" className={classes.flex}>
New Faces
</Typography>
{/* Menu Item One */}
<div>
<Tooltip title="Lists" className={classes.menuItem}>
<IconButton
color="inherit"
aria-owns={open ? 'menu-list' : null}
aria-haspopup="true"
onClick={this.handleMenu}
>
<ViewListIcon />
</IconButton>
</Tooltip>
<Menu
id="menu-list"
anchorEl={anchorEl}
anchorOrigin={{
vertical: 'top',
horizontal:'right',
}}
transformOrigin={{
vertical: 'top',
horizontal:'right',
}}
open={open}
onClose={this.handleClose}
>
<MenuItem onClick={this.handleClose}>Create List</MenuItem>
<MenuItem onClick={this.handleClose}>List 1</MenuItem>
<MenuItem onClick={this.handleClose}>List 2</MenuItem>
</Menu>
</div>
{/* Menu Item Two */}
<div>
<Tooltip title="User Management" className={classes.menuItem}>
<IconButton
color="inherit"
aria-owns={open ? 'menu-appbar' : null}
aria-haspopup="true"
onClick={this.handleMenu}
>
<PeopleIcon />
</IconButton>
</Tooltip>
<Menu
id="menu-appbar"
anchorEl={anchorEl}
anchorOrigin={{
vertical: 'top',
horizontal:'right',
}}
transformOrigin={{
vertical: 'top',
horizontal:'right',
}}
open={open}
onClose={this.handleClose}
>
<MenuItem onClick={this.handleClose}>Profile</MenuItem>
<MenuItem onClick={this.handleClose}>User Management</MenuItem>
<MenuItem onClick={this.handleClose}>Logout</MenuItem>
</Menu>
</div>
</Toolbar>
</AppBar>
</div>
);
}
}
export default withStyles(styles)(Header);
</code></pre>
<p>How do you assign which MenuItems show up according to the icon that is clicked? I assumed it was supposed to show the MenuItems that are directly under the selected anchorEl. Any help would be much appreciated! </p>
| 0 | 2,360 |
Java 8 is not maintaining the order while grouping
|
<p>I m using Java 8 for grouping by data. But results obtained are not in order formed.</p>
<pre><code>Map<GroupingKey, List<Object>> groupedResult = null;
if (!CollectionUtils.isEmpty(groupByColumns)) {
Map<String, Object> mapArr[] = new LinkedHashMap[mapList.size()];
if (!CollectionUtils.isEmpty(mapList)) {
int count = 0;
for (LinkedHashMap<String, Object> map : mapList) {
mapArr[count++] = map;
}
}
Stream<Map<String, Object>> people = Stream.of(mapArr);
groupedResult = people
.collect(Collectors.groupingBy(p -> new GroupingKey(p, groupByColumns), Collectors.mapping((Map<String, Object> p) -> p, toList())));
public static class GroupingKey
public GroupingKey(Map<String, Object> map, List<String> cols) {
keys = new ArrayList<>();
for (String col : cols) {
keys.add(map.get(col));
}
}
// Add appropriate isEqual() ... you IDE should generate this
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final GroupingKey other = (GroupingKey) obj;
if (!Objects.equals(this.keys, other.keys)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 37 * hash + Objects.hashCode(this.keys);
return hash;
}
@Override
public String toString() {
return keys + "";
}
public ArrayList<Object> getKeys() {
return keys;
}
public void setKeys(ArrayList<Object> keys) {
this.keys = keys;
}
}
</code></pre>
<p>Here i am using my class groupingKey by which i m dynamically passing from ux. How can get this groupByColumns in sorted form?</p>
| 0 | 1,092 |
Jest: Cannot spy the property because it is not a function; undefined given instead
|
<p>I'm trying to write a Jest test for a simple React component to confirm that a function has been called when I simulate a click. </p>
<p><strong>However, when I use spyOn method, I keep getting TypeError: Cannot read property 'validateOnSave' of undefined.</strong> My code looks like this:</p>
<p><strong>OptionsView.js</strong></p>
<pre><code>class OptionsView extends React.Component {
constructor(props) {
super(props);
this.state = {
reasonCode: null,
remarkCode: null,
otherCode: null,
codeSelectionIsInvalid: [false, false, false],
};
this.validateOnSave = this.validateOnSave.bind(this);
this.saveOptions = this.saveOptions.bind(this);
validateOnSave() {
const copy = this.state.codeSelectionIsInvalid;
copy[0] = !this.state.reasonCode;
copy[1] = !this.state.remarkCode;
copy[2] = !this.state.otherCode;
this.setState({ codeSelectionIsInvalid: copy });
if (!copy[0] && !copy[1] && !copy[2]) {
this.saveOptions();
}
}
saveOptions() {
const { saveCallback } = this.props;
if (saveCallback !== undefined) {
saveCallback({ reasonCode: this.state.reasonCode, remarkCode: this.state.remarkCode, otherCode: this.state.otherCode,
});
}
}
render() {
const cx = classNames.bind(styles);
const reasonCodes = this.props.reasonCodeset.map(reasonCode => (
<Select.Option
value={reasonCode.objectIdentifier}
key={reasonCode.objectIdentifier}
display={`${reasonCode.name}`}
/>
));
const remarkCodes = this.props.remarkCodeset.map(remarkCode => (
<Select.Option
value={remarkCode.objectIdentifier}
key={remarkCode.objectIdentifier}
display={`${remarkCode.name}`}
/>
));
const otherCodes = this.props.otherCodeset.map(otherCode => (
<Select.Option
value={otherCode.objectIdentifier}
key={otherCode.objectIdentifier}
display={`${otherCode.name}`}
/>
));
return (
<ContentContainer fill>
<Spacer marginTop="none" marginBottom="large+1" marginLeft="none" marginRight="none" paddingTop="large+2" paddingBottom="none" paddingLeft="large+2" paddingRight="large+2">
<Fieldset legend="Code sets">
<Grid>
<Grid.Row>
<Grid.Column tiny={3}>
<SelectField selectId="reasons" required placeholder="Select" label="Reasons:" error="Required field is missing" value={this.state.reasonCode} onChange={this.updateReasonCode} isInvalid={this.state.codeSelectionIsInvalid[0]}>
{reasonCodes}
</SelectField>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column tiny={3}>
<SelectField selectId="remarks" required placeholder="Select" label="Remarks:" error="Required field is missing" value={this.state.remarkCode} onChange={this.updateRemarkCode} isInvalid={this.state.codeSelectionIsInvalid[1]}>
{remarkCodes}
</SelectField>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column tiny={3}>
<SelectField selectId="other-codes" required placeholder="Select" label="Other Codes:" error="Required field is missing" value={this.state.otherCode} onChange={this.updateOtherCode} isInvalid={this.state.codeSelectionIsInvalid[2]}>
{otherCodes}
</SelectField>
</Grid.Column>
</Grid.Row>
</Grid>
</Fieldset>
</Spacer>
<ActionFooter
className={cx(['action-header-footer-color'])}
end={(
<React.Fragment>
<Spacer isInlineBlock marginRight="medium">
<Button text="Save" onClick={this.validateOnSave} />
</Spacer>
</React.Fragment>
)}
/>
</ContentContainer>
);
}
}
OptionsView.propTypes = propTypes;
export default injectIntl(OptionsView);
</code></pre>
<p><strong>OptionsView.test</strong></p>
<pre><code>describe('RemittanceOptions View', () => {
let defaultProps = {...defined...}
beforeAll(() => {
Object.defineProperty(window, "matchMedia", {
value: jest.fn(() => {
return {
matches: true,
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
}
})
});
});
it('should validate remit codes on save', () => {
const wrapper = mountWithIntl(<OptionsView
{...defaultProps}
/>);
const instance = wrapper.instance();
const spy = jest.spyOn(instance, "validateOnSave");
wrapper.setState({
reasonCode: 84,
remarkCode: 10,
otherCode: null
});
console.log(wrapper.find('Button[text="Save"]').debug());
const button = wrapper.find('Button[text="Save"]').at(0);
expect(button.length).toBe(1);
button.simulate('click');
expect(spy).toHaveBeenCalled();
expect(wrapper.state('codeSelectionIsInvalid')).toEqual([false,false,true]);
});
});
</code></pre>
<p><strong>Ultimate goal is to test two cases when save is clicked:</strong></p>
<ol>
<li><p>When state.codeSelectionIsInvalid: [false,false,true]</p></li>
<li><p>When state.codeSelectionIsInvalid: [false,false,false]</p></li>
</ol>
<p>Where am I going wrong here. Any help is appreciated!</p>
| 0 | 2,554 |
AADSTS90019: No tenant-identifying information found in either the request or implied by any provided credentials
|
<p>Hi i want to implement the Office365 SSO login.
I've created an account and following now this documentation: <a href="https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx" rel="noreferrer">https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx</a></p>
<p>I'm at the point where i got the code and now want to implement "Use the Authorization Code to Request an Access Token"</p>
<p>But i get an error: <strong>AADSTS90019: No tenant-identifying information found in either the request or implied by any provided credentials.</strong></p>
<p>Here is an detailed log of my call:</p>
<pre><code>http-bio-8080-exec-10 29/06/2015 14:45:37,496 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 >> "POST /common/oauth2/token HTTP/1.1[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,496 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 >> "Content-Length: 810[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,497 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 >> "Content-Type: application/x-www-form-urlencoded[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,497 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 >> "Host: login.microsoftonline.com[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,498 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 >> "Connection: Keep-Alive[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,499 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 >> "User-Agent: Apache-HttpClient/4.3.5 (java 1.5)[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,499 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 >> "Accept-Encoding: gzip,deflate[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,500 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 >> "[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,501 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 >> "client_id=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2FXXXXXXXXX%2FREST%2FUser%2Foffice&client_secret=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&code=XXXXXXXXXXXXXXXXXXX&grant_type=authorization_code"
http-bio-8080-exec-10 29/06/2015 14:45:37,570 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "H"
http-bio-8080-exec-10 29/06/2015 14:45:37,571 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "TTP/1.1 400 Bad Request[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,572 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "Cache-Control: no-cache, no-store[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,572 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "Pragma: no-cache[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,573 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "Content-Type: application/json; charset=utf-8[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,573 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "Expires: -1[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,574 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "Server: Microsoft-IIS/8.5[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,575 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "x-ms-request-id: c7702631-895c-4c6c-bad1-691ced9259f5[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,575 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "x-ms-gateway-service-instanceid: ESTSFE_IN_3[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,576 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "X-Content-Type-Options: nosniff[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,576 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "Strict-Transport-Security: max-age=31536000; includeSubDomains[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,577 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,578 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "Set-Cookie: flight-uxoptin=true; path=/; secure; HttpOnly[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,578 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "Set-Cookie: x-ms-gateway-slice=productiona; path=/; secure; HttpOnly[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,579 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "Set-Cookie: stsservicecookie=ests; path=/; secure; HttpOnly[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,580 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "X-Powered-By: ASP.NET[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,580 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "Date: Mon, 29 Jun 2015 12:45:48 GMT[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,581 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "Content-Length: 501[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,581 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "[\r][\n]"
http-bio-8080-exec-10 29/06/2015 14:45:37,582 | DEBUG | org.apache.http.wire | wire | http-outgoing-3 << "{"error":"invalid_request","error_description":"AADSTS90019: No tenant-identifying information found in either the request or implied by any provided credentials.\r\nTrace ID: c7702631-895c-4c6c-bad1-691ced9259f5\r\nCorrelation ID: bd641f9d-9982-4808-b7ba-95d3dc0ba8d9\r\nTimestamp: 2015-06-29 12:45:49Z","error_codes":[90019],"timestamp":"2015-06-29 12:45:49Z","trace_id":"c7702631-895c-4c6c-bad1-691ced9259f5","correlation_id":"bd641f9d-9982-4808-b7ba-95d3dc0ba8d9","submit_url":null,"context":null}"
</code></pre>
<p>This is how i configured the APP</p>
<p><img src="https://i.stack.imgur.com/eDvPN.png" alt="enter image description here"></p>
| 0 | 2,542 |
How to fetch local html file with vue.js?
|
<p>I am following <a href="https://jsfiddle.net/coligo/mfxb9aeh/" rel="noreferrer">this example</a></p>
<p>I am trying to load a html file with vue.js and add into my template.</p>
<p>my attempt:</p>
<p>HTTML:</p>
<pre><code><html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="/Static/content/css/foundation.css">
<link rel="stylesheet" type="text/css" href="/Static/content/css/spaceGame.css">
</head>
<body>
<div id="app">
<div class="grid-container">
<div class="grid-x grid-padding-x">
<div class="large-12 cell">
<h1>Welcome to Foundation</h1>
</div>
</div>
</div>
<div class="grid-x grid-padding-x">
<div class="large-4 columns"></div>
<div class="large-8 columns">
<component :is="currentView"></component>
</div>
</div>
</div>
<!-- Footer -->
<script src="https://unpkg.com/vue"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="/Static/scripts/foundation.js"></script>
<script type="text/javascript" src="/Static/scripts/what-input.js"></script>
<script type="text/javascript" src="/Static/scripts/space.js"></script>
</body>
</html>
</code></pre>
<p>script:</p>
<pre><code>$(function() {
$(document).foundation()
var myData = '../../Views/login.html';
Vue.component('manage-posts', {
template: myData,
})
Vue.component('create-post', {
template: '#create-template'
})
new Vue({
el: '#app',
data: {
currentView: 'manage-posts'
}
})
});
</code></pre>
<p>Errors:</p>
<p>above I get the following: </p>
<blockquote>
<ul>
<li>Component template requires a root element, rather than just text.</li>
</ul>
</blockquote>
<p>changing <code>var myData = '../../Views/login.html';</code></p>
<p>to</p>
<pre><code> var myData = '<div>../../Views/login.html</div>';
</code></pre>
<p>gets rid of that error but...how do I load the actual html file?</p>
<p>I am new to single page applications and to vue.js, been at this for some time now and can't figure it out.</p>
<p>EDIT: </p>
<p>The html file that I am trying to load:</p>
<pre><code><div>
<template id="manage-template">
<form>
<div class="sign-in-form">
<h4 class="text-center">Sign In</h4>
<label for="sign-in-form-username">Username</label>
<input type="text" class="sign-in-form-username" id="sign-in-form-username">
<label for="sign-in-form-password">Password</label>
<input type="text" class="sign-in-form-password" id="sign-in-form-password">
<button type="submit" class="sign-in-form-button">Sign In</button>
</div>
</form>
</template>
</div>
</code></pre>
<p>EDIT 2:</p>
<p>If this has any impact on answers i just want to point out:
using VS-code, site is running in IIS, no node.js is used here. </p>
| 0 | 1,665 |
WCF: A registration already exists for URI
|
<p>I have the below in my WCF Web.Config. When I try to access the WCF service I am getting the "A registration already exists for URI" error. The WCF Service is hosted in an SSL enviroment.</p>
<p>Can anyone help please?</p>
<pre><code> <system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="WSBinding" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:01:00" sendTimeout="00:01:00" allowCookies="false"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="52428800" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding name="SOAPBinding" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:01:00" sendTimeout="00:01:00" allowCookies="false"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="52428800" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="wsHTTPBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
<behavior name="jsonBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="WsBehavior">
<serviceMetadata httpsGetEnabled="true" httpsGetUrl="https://*******.com/*****/*****.svc" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="***.***" behaviorConfiguration="WsBehavior">
<endpoint behaviorConfiguration="wsHTTPBehavior" binding="basicHttpBinding" contract="***.***" bindingConfiguration="WSBinding" />
<endpoint address="xml" behaviorConfiguration="jsonBehavior" binding="webHttpBinding" contract="***.***" bindingConfiguration="SOAPBinding" name="SOAP" />
</service>
</services>
</code></pre>
<p></p>
| 0 | 1,196 |
Dynamic loading of external modules in webpack fails
|
<p>I am trying to set up the following architecture: a core React application that gets built with some basic functionality, and the ability to load additional React components at runtime. These additional React components can be loaded on-demand, and they are not available at build time for the core application (so they cannot be included in the bundles for the core application, and must be built separately). After researching for some time, I came across <a href="https://webpack.js.org/configuration/externals/" rel="noreferrer">Webpack Externals</a>, which seemed like a good fit. I am now building my modules separately using the following webpack.config.js:</p>
<pre><code>const path = require('path');
const fs = require('fs');
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
module.exports = {
entry: './src/MyModule.jsx',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'MyModule.js',
library: 'MyModule',
libraryTarget: 'umd'
},
externals: {
"react": "react",
"semantic-ui-react": "semantic-ui-react"
},
module: {
rules: [
{
test: /\.(js|jsx|mjs)$/,
include: resolveApp('src'),
loader: require.resolve('babel-loader'),
options: {
compact: true,
},
}
]
},
resolve: {
extensions: ['.wasm', '.mjs', '.js', '.json', '.jsx']
}
};
</code></pre>
<p>Took a look at the generated MyModule.js file, and it looks correct to me.</p>
<p>Now, in my core app, I am importing the module as follows:</p>
<pre><code>let myComponent = React.lazy(() => import(componentName + '.js'));
</code></pre>
<p>where <code>componentName</code> is the variable that matches the name of my module, in this case, "MyModule" The name is not known at build time, and the file is not present in the src folder at build time. To avoid errors from webpack when building this code with an unknown import, I have added the following to my webpack.config.js for the core project:</p>
<pre><code>module.exports = {
externals: function (context, request, callback/*(err, result)*/) {
if (request === './MyModule.js') {
callback(null, "umd " + request);
} else {
callback();
}
}
}
</code></pre>
<p>I have confirmed that the function in externals gets called during the build, and the if condition is matched for this module. The build succeeds, and I am able to run my core application. </p>
<p>Then, to test dynamic loading, I drop <code>MyModule.js</code> into the static/js folder where the bundles for my core app live, then I navigate to the page in my core app that requests MyModule via <code>let myComponent = React.lazy(() => import(componentName + '.js'));</code></p>
<p>I see a runtime error in the console on the import line, </p>
<pre><code>TypeError: undefined is not a function
at Array.map (<anonymous>)
at webpackAsyncContext
</code></pre>
<p>My guess is it's failing to find the module. I don't understand where it is looking for the module, or how to get more information to debug.</p>
| 0 | 1,129 |
How many ways are there to configure the Spring framework? What are the differences between them technically? (Not pros or cons..)
|
<p>I am studying <a href="https://rads.stackoverflow.com/amzn/click/com/1118892925" rel="noreferrer" rel="nofollow noreferrer">this</a> book (which I would highly recommend), and I am confused about how the authors explain the way Spring framework can be configured.</p>
<p>You can see some code examples that are used in the book <a href="http://www.wrox.com/WileyCDA/WroxTitle/Beginning-Spring.productCd-1118892925,descCd-DOWNLOAD.html" rel="noreferrer">here</a>. (They are available to anyone..) The code I am referring the will be the code from chapter 2, if you would like to take a look.</p>
<p>The book states that there are <strong>3 ways to configure the Spring Container</strong>.</p>
<hr />
<p><strong>XML - based configuration</strong></p>
<p>This will require an xml file that resembles something like this:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" ...>
<bean id="accountService" class="com.wiley.beginningspring.ch2.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
<bean id="accountDao" class="com.wiley.beginningspring.ch2.AccountDaoInMemoryImpl">
</bean>
</beans>
</code></pre>
<p>And then in order to bootstrap Spring, the code that will be used will be:</p>
<pre><code>ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("/com/wiley/beginningspring/ch2/ch2-beans.xml");
</code></pre>
<p>I do not have any confusions at this moment.</p>
<hr />
<p><strong>Java Based Configuration</strong></p>
<p>In this Configuration method, there will be a class for the configuration as follows:</p>
<pre><code>@Configuration
public class Ch2BeanConfiguration {
@Bean
public AccountService accountService() {
AccountServiceImpl bean = new AccountServiceImpl();
bean.setAccountDao(accountDao());
return bean;
}
@Bean
public AccountDao accountDao() {
AccountDaoInMemoryImpl bean = new AccountDaoInMemoryImpl();
return bean;
}
}
</code></pre>
<p>and the code that is responsible for bootstrapping Spring looks like:</p>
<pre><code>ApplicationContext applicationContext
= new AnnotationConfigApplicationContext(Ch2BeanConfiguration.class);
</code></pre>
<p>So up to here, all is clear for me. (Kind of..) I would also like to note that, here we actually have an Annotation which is called @Configuration...</p>
<hr />
<p><strong>Annotation Based Configuration</strong></p>
<p>The last configuration method available, explained in the book is the <strong>Annotation Based Configuration</strong>.</p>
<p>There is an xml file just like we had in the XML-Based Configuration, however a much smaller one:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" ...>
<context:component-scan base-package="com.wiley.beginningspring.ch2"/>
</beans>
</code></pre>
<p>All the beans have Annotations such as:</p>
<pre><code>@Component, @Service
</code></pre>
<p>etc..</p>
<p>And all the dependencies have the annotations:</p>
<pre><code>@Autowired
</code></pre>
<p>so that beans can be injected.</p>
<p>The way Spring framework bootstrapped in this configuration method is as follows:</p>
<pre><code>ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("/ch2-beans.xml");
</code></pre>
<hr />
<p><strong>Here are my questions:</strong></p>
<p>Why is the (so-called) <strong>Annotation Based Configuration</strong> actually using <strong>ClassPathXmlApplicationContext</strong> but not <strong>AnnotationConfigApplicationContext</strong> above? The latter seems much more appropriate to be used in a Configuration that has the words "Annotation Based" in it, isn 't it?</p>
<p>The <strong>Java Based Configuration</strong> explained in the book seems like what should be called <strong>Annotation Based Configuration</strong>.?</p>
<p>And the way Annotation Based Configuration explained in the book actually seems to me something like: XML-Based Configuration with Autowired beans. It does not even have the @Configuration annotation, which the "Java Based Configuration" has..</p>
<p>How many ways are there to configure Spring framework?</p>
| 0 | 1,528 |
Toggle Show And Hide Only Some Table Rows
|
<p>I am trying to show/hide (via a toggle mechanism) only certain rows in my table. I have gotten somewhat close, code is below. What I was reading about in other questions regarding this is the use of style id's and I have tried that but it fails for me. So that is why I used 'hide=yes' and pass that into the toggle function.</p>
<p>This is going to be a table with a couple of hundred entries that when I click toggle can be reduce down to less than 30 on any given day. </p>
<p>Is there a better way to do this?</p>
<pre><code><html>
<head>
<script>
function toggle(thisname) {
tr=document.getElementsByTagName('tr')
for (i=0;i<tr.length;i++){
if (tr[i].getAttribute(thisname)){
if ( tr[i].style.display=='none' ){
tr[i].style.display = '';
}
else {
tr[i].style.display = 'none';
}
}
}
}
</script>
</head>
<body>
<span onClick="toggle('hide');">TOGGLE</span><br /><br />
<table>
<tr ><td >display this row 1</td></tr>
<tr hide=yes ><td>hide this row 1</td></tr>
<tr><td>display this row 2</td></tr>
<tr hide=yes ><td>hide this row 2</td></tr>
<tr hide=yes ><td>hide this row 3</td></tr>
<tr><td>display this row 3</td></tr>
<tr><td>display this row 4</td></tr>
<tr><td>display this row 5</td></tr>
<tr><td>display this row 6</td></tr>
<tr hide=yes ><td>hide this row 4</td></tr>
<tr hide=yes ><td>hide this row 5</td></tr>
<tr><td>display this row 7</td></tr>
<tr hide=yes ><td>hide this row 6</td></tr>
<tr hide=yes ><td>hide this row 7</td></tr>
</table>
</body>
</html>
</code></pre>
| 0 | 1,117 |
Relational attribute in Yii2 form
|
<p>I am trying to get to figure out the proper way of handling a form receiving relational data in Yii2. I haven't been able to find any good examples of this. I have 2 models Sets and SetsIntensity, every Set may have one SetsIntensity associated with it. I'm am trying to make a form where you can input both at the same time. I'm not sure how to handle getting the input for a particular field 'intensity' in SetsIntensity.</p>
<p>Where</p>
<pre><code>$model = new \app\models\Sets();
</code></pre>
<p>If I put it in the field like this client validation won't work and the attribute name is ambiguous and saving becomes difficult</p>
<pre><code><?= $form->field($model, 'lift_id_fk') ?>
<?= $form->field($model, 'reps') ?>
<?= $form->field($model, 'sets') ?>
<?= $form->field($model, 'type') ?>
<?= $form->field($model, 'setsintensity') ?>
</code></pre>
<p>I would like to do something like this but I get an error if I do</p>
<pre><code><?= $form->field($model, 'setsintensity.intensity') ?>
Exception (Unknown Property) 'yii\base\UnknownPropertyException' with message 'Getting unknown property: app\models\Sets::setsintensity.intensity'
</code></pre>
<p>I could do make another object in the controller <code>$setsintensity = new Setsintensity();</code> but I feel this is a cumbersome solution and probably not good practice especially for handling multiple relations</p>
<pre><code><?= $form->field($setsintensity, 'intensity') ?>
</code></pre>
<p>relevant code from SetsModel</p>
<pre><code>class Sets extends \yii\db\ActiveRecord
{
public function scenarios() {
$scenarios = parent::scenarios();
$scenarios['program'] = ['lift_id_fk', 'reps', 'sets', 'type', 'intensity'];
return $scenarios;
}
public function rules()
{
return [
[['lift_id_fk'], 'required'],
[['lift_id_fk', 'reps', 'sets','setsintensity'], 'integer'],
[['type'], 'string', 'max' => 1],
['intensity', 'safe', 'on'=>'program']
];
}
public function getSetsintensity()
{
return $this->hasOne(Setsintensity::className(), ['sets_id_fk' => 'sets_id_pk']);
}
</code></pre>
<p>SetsIntensity Model</p>
<pre><code>class Setsintensity extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'setsintensity';
}
public function rules()
{
return [
[['sets_id_fk', 'intensity', 'ref_set'], 'required'],
[['sets_id_fk', 'intensity', 'ref_set'], 'integer']
];
}
public function getSetsIdFk()
{
return $this->hasOne(Sets::className(), ['sets_id_pk' => 'sets_id_fk']);
}
}
</code></pre>
<p>I was also thinking maybe I could put in a <code>hasOne()</code> relation for the specific attribute 'intensity' in 'Sets'</p>
| 0 | 1,082 |
Rails: FATAL - Peer authentication failed for user (PG::Error)
|
<p>I am running my development on Ubuntu 11.10, and RubyMine</p>
<p>Here is my development settings for the database.yml: which RubyMine created for me</p>
<pre><code>development:
adapter: postgresql
encoding: unicode
database: mydb_development
pool: 5
username: myuser
password:
</code></pre>
<p>when I try to run the app, I get this error below, it seems that I didn't create a 'project' user yet, but, how can I create a user and grant it a database in postgres ? if this is the problem, then, what is the recommended tool to use in Ubuntu for this task ? if this is not the problem, then, please advice.</p>
<pre><code>Exiting
/home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/postgresql_adapter.rb:1194:in `initialize': FATAL: Peer authentication failed for user "project" (PG::Error)
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/postgresql_adapter.rb:1194:in `new'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/postgresql_adapter.rb:1194:in `connect'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/postgresql_adapter.rb:329:in `initialize'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `new'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `postgresql_connection'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:303:in `new_connection'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:313:in `checkout_new_connection'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:237:in `block (2 levels) in checkout'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:232:in `loop'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:232:in `block in checkout'
from /home/sam/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:229:in `checkout'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:95:in `connection'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:398:in `retrieve_connection'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_specification.rb:168:in `retrieve_connection'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_specification.rb:142:in `connection'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/model_schema.rb:308:in `clear_cache!'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activerecord-3.2.3/lib/active_record/railtie.rb:91:in `block (2 levels) in <class:Railtie>'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:418:in `_run__757346023__prepare__404863399__callbacks'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:405:in `__run_callback'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:385:in `_run_prepare_callbacks'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:81:in `run_callbacks'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/actionpack-3.2.3/lib/action_dispatch/middleware/reloader.rb:74:in `prepare!'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/actionpack-3.2.3/lib/action_dispatch/middleware/reloader.rb:48:in `prepare!'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/railties-3.2.3/lib/rails/application/finisher.rb:47:in `block in <module:Finisher>'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/railties-3.2.3/lib/rails/initializable.rb:30:in `instance_exec'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/railties-3.2.3/lib/rails/initializable.rb:30:in `run'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/railties-3.2.3/lib/rails/initializable.rb:55:in `block in run_initializers'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/railties-3.2.3/lib/rails/initializable.rb:54:in `each'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/railties-3.2.3/lib/rails/initializable.rb:54:in `run_initializers'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/railties-3.2.3/lib/rails/application.rb:136:in `initialize!'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/railties-3.2.3/lib/rails/railtie/configurable.rb:30:in `method_missing'
from /home/sam/RubymineProjects/project/config/environment.rb:5:in `<top (required)>'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:251:in `require'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:251:in `block in require'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:236:in `load_dependency'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/activesupport-3.2.3/lib/active_support/dependencies.rb:251:in `require'
from /home/sam/RubymineProjects/project/config.ru:4:in `block in <main>'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/rack-1.4.1/lib/rack/builder.rb:51:in `instance_eval'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/rack-1.4.1/lib/rack/builder.rb:51:in `initialize'
from /home/sam/RubymineProjects/project/config.ru:1:in `new'
from /home/sam/RubymineProjects/project/config.ru:1:in `<main>'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/rack-1.4.1/lib/rack/builder.rb:40:in `eval'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/rack-1.4.1/lib/rack/builder.rb:40:in `parse_file'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/rack-1.4.1/lib/rack/server.rb:200:in `app'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/railties-3.2.3/lib/rails/commands/server.rb:46:in `app'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/rack-1.4.1/lib/rack/server.rb:301:in `wrapped_app'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/rack-1.4.1/lib/rack/server.rb:252:in `start'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/railties-3.2.3/lib/rails/commands/server.rb:70:in `start'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/railties-3.2.3/lib/rails/commands.rb:55:in `block in <top (required)>'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/railties-3.2.3/lib/rails/commands.rb:50:in `tap'
from /home/sam/.rvm/gems/ruby-1.9.3-p0@project/gems/railties-3.2.3/lib/rails/commands.rb:50:in `<top (required)>'
from /home/sam/RubymineProjects/project/script/rails:6:in `require'
from /home/sam/RubymineProjects/project/script/rails:6:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
Process finished with exit code 1
</code></pre>
| 0 | 3,592 |
This constraint cannot be enabled as not all values have corresponding parent values
|
<p>I have three nested tables in a dataset. I display the data based on the language ID, ie: EN is 1 FR is 2 and NL is 3. French and english exist in the database but Dutch does not exist yet and when the user selects NL I get the following error:</p>
<blockquote>
<p>This constraint cannot be enabled as not all values have corresponding
parent values.</p>
</blockquote>
<p>Below is the code that I use to get the data. The error happens when I try to create relations in the dataset.</p>
<pre><code> (ds.Relations.Add(new DataRelation("Cat_SubCat", dk1, dk2));
</code></pre>
<p>Now my question is, how can I check if the value exists in the dataset or database with the given code below?</p>
<pre><code> public static DataTable GetData(Int32 languageID)
{
DataSet ds = new DataSet();
string commandText = @"SELECT * FROM AlacarteCat where languageID = @ID;
SELECT * FROM AlacarteSubCat where languageID = @ID;
SELECT * from AlacarteItems where languageID = @ID";
using (SqlConnection myConnection = new SqlConnection(Common.GetConnectionString("SQLConnectionString")))
{
SqlCommand command = new SqlCommand(commandText, myConnection);
command.Parameters.Add("@ID", SqlDbType.Int);
command.Parameters["@ID"].Value = languageID;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = command;
da.TableMappings.Add("AlacarteCat", "AlacarteCat"); // table 0
da.TableMappings.Add("AlacarteSubCat", "AlacarteSubCat"); // table 1
da.TableMappings.Add("AlacarteItems", "AlacarteItems"); // table 2
da.Fill(ds, "AlacarteCat");
DataColumn dk1 = ds.Tables[0].Columns["ID"];
DataColumn dk2 = ds.Tables[1].Columns["AlacarteCatID"];
DataColumn dk3 = ds.Tables[1].Columns["ID"];
DataColumn dk4 = ds.Tables[2].Columns["AlacarteSubCatID"];
DataColumn dk5 = ds.Tables[0].Columns["id"];
DataColumn dk6 = ds.Tables[2].Columns["AlacarteCatID"];
ds.Relations.Add(new DataRelation("Cat_SubCat", dk1, dk2));
ds.Relations.Add(new DataRelation("SubCat_Items", dk3, dk4));
ds.Relations.Add(new DataRelation("Cat_Items", dk5, dk6));
if ((ds != null))
{
return ds.Tables["AlacarteCat"];
}
return null;
}
}
</code></pre>
| 0 | 1,087 |
Writing Byte Array To Binary File Javascript
|
<p>I am trying to write a script that generates random numbers these number then are converted to groups of 4Bytes each then these 4-bytes-groups are put into an Uint8Array finally I try to save the array to binary file. Here is my code:</p>
<pre><code><html>
<head>
<title>Raandom Number Generator</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="filesaver.min.js"></script>
<script type="text/javascript">
$(function() {
if (!Date.now) {
Date.now = function() {
return new Date().getTime();
};
}
alert("started");
var currentMousePos = {
x : -1,
y : -1
};
var randomData = [];
var bytes = new Int8Array(4);
$(document).mousemove(function(event) {
if(randomData.length>=1231){
$(document).unbind('mousemove');
console.log("Finished generating numbers ... trying to save file");
randomData = new Uint8Array(randomData);
var blob = new Blob(randomData, {type: "application/octet-stream"});
saveAs(blob, "rand.bin");
return;
}
currentMousePos.x = event.pageX;
currentMousePos.y = event.pageY;
var longRandomNumber = Date.now() * (event.pageX + 1)
* (event.pageY + 1);
for ( var i = 3; i >= 0; i--) {
bytes[i] = longRandomNumber & (255);
longRandomNumber = longRandomNumber >> 8
}
for ( var i = 0; i < 4; i++) {
randomData.push(bytes[i]);
}
console.log(randomData.length);
});
})
</script>
</body>
</html>
</code></pre>
<p>The problem is that the generated file contains numbers <code>plain numbers</code> for example an element in the Uint8Array may be 65, in my understanding to binary this value should be saved as capital letter <strong>A</strong> but it is stored as <strong>65</strong> instead</p>
<p><strong><em>Note</em></strong></p>
<p>filesaver.min.js is a library that I use to save files from JS (<a href="https://github.com/eligrey/FileSaver.js/" rel="nofollow">Link on GitHub</a>)</p>
| 0 | 1,101 |
Apache POI Java Excel Performance for Large Spreadsheets
|
<p>I have a spreadsheet I'm trying to read with POI (I have both xls and xlsx formats), but in this case, the problem is with the xls file. My spreadsheet has about 10,000 rows and 75 columns, and reading it in can take several minutes (though Excel opens in a few seconds). I'm using the event based reading, rather than reading the whole file into memory. The meat of my code is below. It's a bit messy right now, but it's really just a long switch statement that was mostly copied from the POI examples.</p>
<p>Is it typical for POI performance using the event model to be so slow? Is there anything I an do to speed this up? I think several minutes will be unacceptable for my application.</p>
<pre><code> POIFSFileSystem poifs = new POIFSFileSystem(fis);
InputStream din = poifs.createDocumentInputStream("Workbook");
try
{
HSSFRequest req = new HSSFRequest();
listener = new FormatTrackingHSSFListener(new HSSFListener() {
@Override
public void processRecord(Record rec)
{
thisString = null;
int sid = rec.getSid();
switch (sid)
{
case SSTRecord.sid:
strTable = (SSTRecord) rec;
break;
case LabelSSTRecord.sid:
LabelSSTRecord labelSstRec = (LabelSSTRecord) rec;
thisString = strTable.getString(labelSstRec
.getSSTIndex()).getString();
row = labelSstRec.getRow();
col = labelSstRec.getColumn();
break;
case RKRecord.sid:
RKRecord rrk = (RKRecord) rec;
thisString = "";
row = rrk.getRow();
col = rrk.getColumn();
break;
case LabelRecord.sid:
LabelRecord lrec = (LabelRecord) rec;
thisString = lrec.getValue();
row = lrec.getRow();
col = lrec.getColumn();
break;
case BlankRecord.sid:
BlankRecord blrec = (BlankRecord) rec;
thisString = "";
row = blrec.getRow();
col = blrec.getColumn();
break;
case BoolErrRecord.sid:
BoolErrRecord berec = (BoolErrRecord) rec;
row = berec.getRow();
col = berec.getColumn();
byte errVal = berec.getErrorValue();
thisString = errVal == 0 ? Boolean.toString(berec
.getBooleanValue()) : ErrorConstants
.getText(errVal);
break;
case FormulaRecord.sid:
FormulaRecord frec = (FormulaRecord) rec;
switch (frec.getCachedResultType())
{
case Cell.CELL_TYPE_NUMERIC:
double num = frec.getValue();
if (Double.isNaN(num))
{
// Formula result is a string
// This is stored in the next record
outputNextStringRecord = true;
}
else
{
thisString = formatNumericValue(frec, num);
}
break;
case Cell.CELL_TYPE_BOOLEAN:
thisString = Boolean.toString(frec
.getCachedBooleanValue());
break;
case Cell.CELL_TYPE_ERROR:
thisString = HSSFErrorConstants
.getText(frec.getCachedErrorValue());
break;
case Cell.CELL_TYPE_STRING:
outputNextStringRecord = true;
break;
}
row = frec.getRow();
col = frec.getColumn();
break;
case StringRecord.sid:
if (outputNextStringRecord)
{
// String for formula
StringRecord srec = (StringRecord) rec;
thisString = srec.getString();
outputNextStringRecord = false;
}
break;
case NumberRecord.sid:
NumberRecord numRec = (NumberRecord) rec;
row = numRec.getRow();
col = numRec.getColumn();
thisString = formatNumericValue(numRec, numRec
.getValue());
break;
case NoteRecord.sid:
NoteRecord noteRec = (NoteRecord) rec;
row = noteRec.getRow();
col = noteRec.getColumn();
thisString = "";
break;
case EOFRecord.sid:
inSheet = false;
}
if (thisString != null)
{
// do something with the cell value
}
}
});
req.addListenerForAllRecords(listener);
HSSFEventFactory factory = new HSSFEventFactory();
factory.processEvents(req, din);
</code></pre>
| 0 | 3,719 |
Visual Studio Error: "Object reference not set to an instance of an object" when clicking on a project and opening Properties
|
<p>I have a weird behavior of Visual Studio 2013 (and 2010), that i cant seem to fix.</p>
<p>I know this is not directly related to programming (similar questions achieve the same error message via code, so i assume it is code within VisualStudio that has a problem).</p>
<p>My projects are C++.</p>
<p>Whenever i click on a project and open its properties, i get the following error box:</p>
<p><img src="https://i.stack.imgur.com/HUZyw.png" alt="Error Message"></p>
<p>with the text:</p>
<blockquote>
<p>Object reference not set to an instance of an object.</p>
</blockquote>
<p>I can trigger that error message by selecting "Configuration Properties -> General". The view then does not show the information for "General".</p>
<p>My setting is the following: Windows 7 Enterprise SP1 64bit, Visual Studio 2010 (i need the compiler) and Visual Studio 2013 Professional (Update 4).</p>
<p>I have to work with these extensions:</p>
<ul>
<li>IBM Clearcase Integration</li>
<li>IBM RTC VS Integration</li>
<li>Visual Assist X</li>
<li>Xoreax Incredibuild</li>
</ul>
<p>What i did try without success:</p>
<ul>
<li>Remove all VS related files/folders in
<ul>
<li><code>%APPDATA%\..\Local\Microsoft</code></li>
<li><code>%APPDATA%\..\Roaming\Microsoft</code></li>
<li><code>%PROGRAMFILES%</code></li>
<li><code>%PROGRAMFILES(X86)%</code></li>
<li><code>%USERPROFILE%\Documents</code></li>
</ul></li>
<li>Repair/Reinstall VS2010 and VS2013 (i always installed VS2010 first)</li>
<li>Reinstall .NET Framework 4.5.2</li>
<li>Create a new project from within VS2013, i get the usual error plus:<img src="https://i.stack.imgur.com/z8nP0.png" alt="new_proj_error"></li>
<li>Use TotalUninstaller as described <a href="https://stackoverflow.com/a/28050106/875020">here</a> to remove all extensions</li>
<li>Hooking into the devenv process with WinDBG did not work (in non-invasive i couldnt get it to run)</li>
<li>Start devenv.exe with <a href="https://msdn.microsoft.com/en-us/library/ms241278.aspx" rel="nofollow noreferrer">safemode</a> and <a href="https://msdn.microsoft.com/en-us/library/ms241272.aspx" rel="nofollow noreferrer">log</a></li>
<li>Uninstall NuGet as proposed <a href="https://stackoverflow.com/a/17312698/875020">here</a></li>
<li>Create new solution and delete old .suo and .sdf files</li>
<li>Look at output <img src="https://i.stack.imgur.com/O8PO8.png" alt="output"> of <a href="https://technet.microsoft.com/en-us/library/bb896645.aspx" rel="nofollow noreferrer">ProcMon</a> while triggering the error. I checked the registry for that key: nonexistent</li>
<li>Look at <a href="https://gist.github.com/anonymous/2e32538548fcbf10c204" rel="nofollow noreferrer">logfile</a> at <code>%APPDATA%\..\Roaming\Microsoft\VisualStudio\12.0\ActivityLog.xml</code> generated via /log: the keys are found within other keys of the value "(Default)". No clue on how to interpret that</li>
<li>Reset all user settings via the (also secret) options named <a href="https://stackoverflow.com/a/19460071/875020">here</a></li>
<li>Run .NET <a href="https://support.microsoft.com/en-us/kb/2698555" rel="nofollow noreferrer">Fixing Tools</a> and <a href="https://support.microsoft.com/en-us/kb/929833" rel="nofollow noreferrer">SFC</a></li>
<li>Clean (remove from) registry
<ul>
<li><code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\</code></li>
<li><code>HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\</code></li>
</ul></li>
</ul>
<p>So my questions are</p>
<ul>
<li>How could i further debug the problem</li>
<li>How can i really delete/reset all user settings and files and cleanup the registry</li>
<li>Could this be related to solutions or projects</li>
<li>Any third party components known to be problematic? .Net Frameworks?</li>
</ul>
| 0 | 1,331 |
How to pass props to Screen component with a tab navigator?
|
<p>This is my first post on StackOverflow, so apologies if I'm not following the correct format.</p>
<p>I'm building my first app using <code>tab navigator from React Navigation v 5.x</code> and have run into a big problem when passing props from one screen to another</p>
<p>What I want to achieve is to:</p>
<ol>
<li>Make changes to a list of data in one of my screens.</li>
<li>Have those changes affect what happens on another screen.</li>
</ol>
<p>I have tried <a href="https://reactnavigation.org/docs/hello-react-navigation/#passing-additional-props" rel="noreferrer">this</a> (I failed to set the props to pass down), <a href="https://stackoverflow.com/questions/57186298/react-native-pass-props-from-one-screen-to-another-screen-using-tab-navigator">this</a> (Deprecated version of react-navigation) and <a href="https://stackoverflow.com/a/56764509/12974771">this</a> (Also old version of react-navigation).</p>
<p>and Redux but there are no examples available with the current version of react navigation.</p>
<p>I'm at the end of my rope with this and really need some step by step on how to achieve this.
Here's a rough sketch of what I want to do:</p>
<p><a href="https://i.stack.imgur.com/rbSCL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rbSCL.png" alt="enter image description here" /></a></p>
<p>The way I thought about it is sending the parent state down as props via callback, but I can't find a way to send props through the screen components in the up-to-date version of react navigation...</p>
<p>This is my navigation setup:</p>
<pre class="lang-js prettyprint-override"><code>const Tab = createBottomTabNavigator()
export default class MyApp extends Component{
constructor(props) {
super(props);
}
render(){
return (
<NavigationContainer>
<Tab.Navigator
screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
let iconName;
if (route.name === 'My tests') {
iconName = focused ? 'ios-list-box' : 'ios-list';
} else if (route.name === 'Testroom') {
iconName = focused ? 'ios-body' : 'ios-body';
}
return <Ionicons name={iconName} size={size} color={color} />;
},
})}
tabBarOptions={{
activeTintColor: 'tomato',
inactiveTintColor: 'gray',
}}>
<Tab.Screen name="My tests" component={MyTests}/> //This is where I want to send props
<Tab.Screen name="Testroom" component={TestRoom} /> //This is where I want to send props
</Tab.Navigator>
</NavigationContainer>
)
}
}
</code></pre>
<p>I've read <a href="https://reactnavigation.org/docs/redux-integration" rel="noreferrer">this</a> but it makes no sense to me. How does this fit into a tree of components? What goes where? Please help!</p>
| 0 | 1,443 |
Application error with MyFaces 1.2: java.lang.IllegalStateException: No Factories configured for this Application
|
<p>For my app I'm using <strong>Tomcat 6.0.x</strong> and <strong>Mojarra 1.2_04</strong> JSF implementation.
It works fine, just I would like to switch now to <strong>MyFaces 1.2_10</strong> impl of JSF.</p>
<p>During the deployment of my app a get the following error:</p>
<pre><code>ERROR [org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/myApp]] StandardWrapper.Throwable
java.lang.IllegalStateException: No Factories configured for this Application. This happens if the faces-initialization does not work at all - make sure that you properly include all configuration settings necessary for a basic faces application and that all the necessary libs are included. Also check the logging output of your web application and your container for any exceptions!
If you did that and find nothing, the mistake might be due to the fact that you use some special web-containers which do not support registering context-listeners via TLD files and a context listener is not setup in your web.xml.
A typical config looks like this;
<listener>
<listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
</listener>
at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:106)
at javax.faces.webapp.FacesServlet.init(FacesServlet.java:137)
at org.apache.myfaces.webapp.MyFacesServlet.init(MyFacesServlet.java:113)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1172)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:992)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4058)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4371)
...
</code></pre>
<p>Here is part of my web.xml configuration:</p>
<pre><code> <servlet>
<servlet-name>Faces Servlet</servlet-name>
<!-- <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> -->
<servlet-class>org.apache.myfaces.webapp.MyFacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
...
<listener>
<listener- class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
</listener>
</code></pre>
<p>Has anyone experienced similar error, and what should I do i order to fix it? Thanx!</p>
<p><strong>EDIT:</strong></p>
<p>I was able to fix the problem. Since I am using delegator for <strong>FacesServlet</strong>, it turned out that this delegator was causing the problem.
All I needed to do is to make this class implement <strong>DelegatedFacesServlet</strong>, and I've removed <em>org.apache.myfaces.webapp.StartupServletContextListener</em>. Here is my web.xml now:</p>
<pre><code> <servlet>
<servlet-name>Faces Servlet</servlet-name>
<!-- <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> -->
<servlet-class>org.apache.myfaces.webapp.MyFacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>Faces Servlet Delegator</servlet-name>
<servlet-class>com.myapp.web.FacesServletDelegator</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet Delegator</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</code></pre>
<p>and here is <strong>FacesServletDelegator</strong></p>
<pre><code>public class PLMFacesServlet extends HttpServlet implements DelegatedFacesServlet {
private MyFacesServlet delegate;
public final void init(ServletConfig servletConfig) throws ServletException {
delegate = new MyFacesServlet();
delegate.init(servletConfig);
}
public final void destroy() {
delegate.destroy();
}
public final ServletConfig getServletConfig() {
return delegate.getServletConfig();
}
public final String getServletInfo() {
return delegate.getServletInfo();
}
public final void service(HttpServletRequest request, HttpServletResponse response) throws ServletException {
try {
delegate.service(request, response);
} catch(Exception e) {}
}
// some other code...
}
</code></pre>
<p><strong>EDIT 2</strong>:</p>
<p>Following <strong>BalusC</strong> advice, I've edited my <em>web.xml</em> a bit, here is the final version:</p>
<pre><code><servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>Faces Servlet Delegator</servlet-name>
<servlet-class>com.myapp.web.FacesServletDelegator</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet Delegator</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</code></pre>
| 0 | 2,139 |
Error in Angular ng serve static ɵfac: i0.ɵɵFactoryDef<ShepherdService>
|
<p>I had to install a project in another pc, I use Angular v 9.1.0 but after I run npm install I have this error:</p>
<blockquote>
<p>ERROR in node_modules/angular-shepherd/lib/shepherd.service.d.ts:64:18 - error TS2314: Generic type 'ɵɵFactoryDef' requires 2 type argument(s).</p>
<p>64 static ɵfac: i0.ɵɵFactoryDef;</p>
</blockquote>
<p>I have the same version of the package in both pc <code>angular-shepherd": "^0.5.0</code></p>
<p>I already tried to remove and reinstall node_modules and also the package angular-shepherd but I still have the error.
In the old pc, all works well.
If it helps this is the package:</p>
<pre><code>"dependencies": {
"@angular/animations": "^9.1.0",
"@angular/cdk": "^9.1.0",
"@angular/common": "^9.1.0",
"@angular/compiler": "^9.1.0",
"@angular/core": "^9.1.0",
"@angular/forms": "^9.1.0",
"@angular/material": "^9.1.0",
"@angular/material-moment-adapter": "^9.1.0",
"@angular/platform-browser": "^9.1.0",
"@angular/platform-browser-dynamic": "^9.1.0",
"@angular/platform-server": "^9.1.0",
"@angular/router": "^9.1.0",
"@angular/service-worker": "^9.1.0",
"@auth0/angular-jwt": "^3.0.1",
"@fullcalendar/angular": "^4.4.5-beta",
"@ngx-translate/core": "12.1.2",
"@ngx-translate/http-loader": "4.0.0",
"angular-shepherd": "^0.5.0",
"animate.css": "3.7.2",
"bootstrap": "4.4.1",
"chart.js": "^2.9.3",
"core-js": "^3.6.4",
"font-awesome": "^4.7.0",
"google-libphonenumber": "^3.2.7",
"i18n-iso-countries": "^5.1.0",
"intl-tel-input": "^16.0.11",
"jquery": "^3.4.1",
"jsbarcode": "^3.11.0",
"latinize": "^0.4.0",
"material-community-components": "^6.0.0",
"moment": "^2.24.0",
"moment-timezone": "0.5.28",
"net": "^1.0.2",
"ng2-ckeditor": "^1.2.7",
"ng2-password-strength-bar": "^1.2.3",
"ng2-tel-input": "2.3.0",
"ngx-barcode6": "^1.0.10",
"ngx-cookie-service": "^3.0.3",
"ngx-daterangepicker-material": "^2.2.0",
"ngx-device-detector": "latest",
"ngx-highlightjs": "^4.0.2",
"ngx-image-zoom": "^0.6.0",
"ngx-infinite-scroll": "^8.0.1",
"ngx-loading": "^8.0.0",
"node-sass": "^4.13.1",
"placeholder-loading": "^0.2.5",
"popper.js": "^1.16.1",
"primeicons": "^2.0.0",
"primeng": "^9.0.0",
"print-js": "^1.0.63",
"rxjs": "^6.5.4",
"stompjs": "^2.3.3",
"stream": "0.0.2",
"timers": "^0.1.1",
"tslib": "^1.10.0",
"url-search-params-polyfill": "^8.0.0",
"zone.js": "~0.10.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "^0.901.0",
"@angular/cli": "^9.1.0",
"@angular/compiler-cli": "^9.1.0",
"@types/bootstrap": "4.3.2",
"@types/chartist": "0.9.48",
"@types/jasmine": "3.5.10",
"@types/jquery": "3.3.34",
"@types/node": "^13.9.5",
"@types/xml2js": "^0.4.5",
"codelyzer": "^5.2.1",
"concurrently": "^5.1.0",
"cypress": "^4.1.0",
"cypress-plugin-tab": "^1.0.5",
"jasmine-core": "~3.5.0",
"jasmine-spec-reporter": "~5.0.1",
"karma": "~4.4.1",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "^2.1.1",
"karma-jasmine": "~3.1.1",
"karma-jasmine-html-reporter": "^1.5.2",
"lite-server": "^2.5.4",
"protractor": "^5.4.3",
"ts-node": "~8.8.1",
"tslint": "6.1.0",
"typescript": "3.8.3"
}
</code></pre>
| 0 | 1,789 |
Attempt to invoke virtual method 'int java.lang.String.hashCode()'
|
<p>I'm trying to load images from URL into girdview using Volley Library. For this I'm following <a href="http://www.101apps.co.za/index.php/articles/using-volley-to-download-cache-and-display-bitmaps.html" rel="noreferrer">this</a> tutorial. When I run my project, it collects all URLs from server database and then store in arraylist. But doesn't displays images. And I am getting <code>java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference</code> error. It doesn't even point to any line number of code where I'm getting this error. See below Logcat Output :</p>
<pre><code>java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at com.android.volley.Request.<init>(Request.java:136)
at com.android.volley.toolbox.ImageRequest.<init>(ImageRequest.java:71)
at com.android.volley.toolbox.ImageLoader.get(ImageLoader.java:219)
at com.android.volley.toolbox.ImageLoader.get(ImageLoader.java:171)
at com.android.volley.toolbox.NetworkImageView.loadImageIfNecessary(NetworkImageView.java:141)
at com.android.volley.toolbox.NetworkImageView.onLayout(NetworkImageView.java:190)
at android.view.View.layout(View.java:15596)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15596)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.GridView.setupChild(GridView.java:1542)
at android.widget.GridView.makeAndAddView(GridView.java:1436)
at android.widget.GridView.makeRow(GridView.java:361)
at android.widget.GridView.fillDown(GridView.java:302)
at android.widget.GridView.fillFromTop(GridView.java:437)
at android.widget.GridView.layoutChildren(GridView.java:1276)
at android.widget.AbsListView.onLayout(AbsListView.java:2148)
at android.view.View.layout(View.java:15596)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
at android.view.View.layout(View.java:15596)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.widget.ScrollView.onLayout(ScrollView.java:1502)
at android.view.View.layout(View.java:15596)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15596)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:494)
at android.view.View.layout(View.java:15596)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15596)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2072)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1829)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
</code></pre>
<p>Can anybody help me what is the exact problem and how do I solve this ?</p>
| 0 | 1,857 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.