title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
Type mismatch: inferred type is LoginActivity but LifecycleOwner was expected
|
<p>I am playing with the preview version of <code>AndroidStudio - 3.4 Canary 9</code>.</p>
<p>I selected the default login activity option from <code>Configure your project</code> window and provided, selected below options:</p>
<p><a href="https://i.stack.imgur.com/mYobT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mYobT.png" alt="Configure your project"></a></p>
<p>No error reported on Gradle sync, however on build compilation it produces following error:</p>
<pre><code>Type mismatch: inferred type is LoginActivity but LifecycleOwner was expected
</code></pre>
<p>Here is the code snippet on which it is showing the error:</p>
<pre><code>// Type mismatch at this@LoginActivity, required LifeCycleOwner, found - LoginActivity
loginViewModel.loginFormState.observe(this@LoginActivity, Observer {
val loginState = it ?: return@Observer
// disable login button unless both username / password is valid
login.isEnabled = loginState.isDataValid
if (loginState.usernameError != null) {
username.error = getString(loginState.usernameError)
}
if (loginState.passwordError != null) {
password.error = getString(loginState.passwordError)
}
})
</code></pre>
<p><code>LoginActivity</code> is derived from <code>AppCompatActivity()</code></p>
<p>Respective imported library is <code>androidx.appcompat.app.AppCompatActivity</code></p>
<p>Here is content from app level build.gradle:</p>
<pre><code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.socialsample"
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.core:core-ktx:1.1.0-alpha03'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.annotation:annotation:1.0.1'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
</code></pre>
<p>Here is content from Project level build.gradle:</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.3.11'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.0-alpha09'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p>Am I missing anything over here? Please suggest.</p>
| 1 | 1,394 |
Mapping coordinates from 3D perspective projection to 2D orthographic projection in OpenGL in C++
|
<p>I have written a simple openGL program in C++. This program draws a sphere in 3D perspective projection and tries to draw a line joining the center of the sphere to the current cursor position in 2D orthographic projection. Now for drawing the line I can't figure out the coordinate of center of the sphere.</p>
<p>This is my code : </p>
<pre><code>#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
void passive(int,int);
void reshape(int,int);
void init(void);
void display(void);
void camera(void);
int cursorX,cursorY,width,height;
int main (int argc,char **argv) {
glutInit (&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA);
glutInitWindowSize(1364,689);
glutInitWindowPosition(0,0);
glutCreateWindow("Sample");
init();
glutDisplayFunc(display);
glutIdleFunc(display);
glutPassiveMotionFunc(passive);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
void display() {
glClearColor (0.0,0.0,0.0,1.0);
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Render 3D content
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60,(GLfloat)width/(GLfloat)height,1.0,100.0); // create 3D perspective projection matrix
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
camera();
glTranslatef(-6,-2,0);
glColor3f(1,0,0);
glutSolidSphere(5,50,50);
glPopMatrix();
// Render 2D content
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, width,height, 0); // create 2D orthographic projection matrix
glMatrixMode(GL_MODELVIEW);
glColor3f(1,1,1);
glBegin(GL_LINES);
glVertex2f( centreX,centreY ); // coordinate of center of the sphere in orthographic projection
glVertex2f( cursorX,cursorY );
glEnd();
glutSwapBuffers();
}
void camera(void) {
glRotatef(0.0,1.0,0.0,0.0);
glRotatef(0.0,0.0,1.0,0.0);
glTranslated(0,0,-20);
}
void init(void) {
glEnable (GL_DEPTH_TEST);
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_COLOR_MATERIAL);
}
void reshape(int w, int h) {
width=w; height=h;
}
void passive(int x1,int y1) {
cursorX=x1; cursorY=y1;
}
</code></pre>
<p>I can,t figure out the values for centreX and centreY. Anyway I can get the correct values to draw the line?</p>
| 1 | 1,058 |
error: expected declaration before } token (when trying to compile)
|
<p>I'm having a problem. I have the template and implementation for a stack in files <strong>stack.h</strong> and <strong>stack.hpp</strong>. Then I have an <strong>in2out.cpp</strong> file that converts infix expressions to outfix expressions and evaluates them. At the beginning of in2out.cpp I "#include stack.h". And inside <strong>stack.h (which is my interface)</strong> I "#include stack.hpp" <strong>(stack.hpp is my implementation)</strong>. I know this is weird but it's the way I'm required to do it.</p>
<p>Anyways, my problem is, when I'm trying to compile these 3 files together. I get only 1 error which is in stack.h (my interface, listed below). The error is: </p>
<pre><code>In file included from in2post.cpp:7:
stack.h:49: error: expected declaration before â}â token
</code></pre>
<p>Line 49 is near the bottom. here is my stack.h file.</p>
<pre><code>#ifndef STACK_H
#define STACK_H
#include <iostream>
#include <vector>
namespace cop4530 {
template<typename T>
class Stack {
private:
std::vector<T> v;
public:
Stack();
~Stack();
Stack (const Stack<T>&);
//Stack (Stack<T>&& );
Stack<T>& operator= (const Stack <T>&);
//Stack<T> & operator=(Stack<T> &&);
bool empty() const;
void clear();
void push(const T& x);
//void push(T && x);
void pop();
T& top();
const T& top() const;
int size() const;
void print(std::ostream& os, char ofc = ' ') const;
};
template<typename T>
std::ostream& operator<< (std::ostream& os, const Stack<T>& a);
template<typename T>
bool operator== (const Stack<T>& a, const Stack <T>& b);
template<typename T>
bool operator!= (const Stack<T>& a, const Stack <T>& b);
template<typename T>
bool operator< (const Stack<T>& a, const Stack <T>& b);
#include "stack.hpp"
} //this is line 49
#endif
</code></pre>
<p>Here's my makefile:</p>
<pre><code>CC = g++
FLAGS = -Wall -pedantic
DDD = -g
in2post.x: in2post.cpp stack.h stack.hpp
$(CC) $(FLAGS) $(DDD) -o in2post.x in2post.cpp
</code></pre>
<p>EDIT: Here's the beginning of Stack.hpp: (tell me if I should change or add something)
EDIT2: I just decided to include the whole Stack.hpp. Some functions are blanked out cause I didn't need them or couldn't figure them out</p>
<pre><code>#include <iostream>
#include <vector>
template<typename T>
Stack<T>::Stack(){}
template<typename T>
Stack<T>::~Stack(){
v.clear();
}
template<typename T>
Stack<T>::Stack(const Stack<T> & S){
v = S.v;
}
/*
template<typename T>
Stack<T>::Stack(Stack<T> &&){
}
*/
template<typename T>
Stack<T> & Stack<T>::operator=(const Stack<T> & S){
v = S.v;
return *this;
}
/*
template<typename T>
Stack<T>::Stack<T> & Stack<T>::operator=(Stack<T> &&){
}
*/
template<typename T>
bool Stack<T>::empty() const {
return v.empty();
}
template<typename T>
void Stack<T>::clear(){
while (!v.empty())
v.clear();
}
template<typename T>
void Stack<T>::push(const T& x){
v.push_back(x);
}
/*
template<typename T>
void Stack<T>::push(T && x){
}
*/
template<typename T>
void Stack<T>::pop(){
v.pop_back();
}
template<typename T>
T& Stack<T>::top(){
return v[v.size()-1];
}
template<typename T>
const T & Stack<T>::top() const{
return v[0];
}
template<typename T>
int Stack<T>::size() const {
return v.size();
}
template<typename T>
void Stack<T>::print(std::ostream & os, char ofc) const {
for(int i = 0; i < v.size(); i++)
os << v[i] << ofc;
}
/*------------------NON-MEMBER GLOBAL FUNCTIONS-----------------*/
template<typename T>
std::ostream & operator<<(std::ostream & os, const Stack<T> & a) {
a.print(os);
return os;
}
template <typename T>
bool operator==(const Stack<T> & a, const Stack<T> & b) {
if(a.size() != b.size())
return false;
else {
Stack<T> c = a;
Stack<T> d = b;
bool retVal = true;
while(!c.empty()) {
if(c.top() == d.top()) {
c.pop();
d.pop();
}
else {
retVal = false;
break;
}
}
return retVal;
}
}
template <typename T>
bool operator!=(const Stack<T> & a, const Stack<T> & b) {
return !(a == b);
}
template <typename T>
bool operator<(const Stack<T> & a, const Stack<T> & b) {
Stack<T> c = a;
Stack<T> d = b;
bool retVal = true;
while(!c.empty()) {
if(!(c.top() < d.top())) {
retVal = false;
break;
}
else {
c.pop();
d.pop();
}
}
return retVal;
}
</code></pre>
| 1 | 2,364 |
How to pass multiple arguments to a smarty function?
|
<p>I've a following code snippet from smarty template:</p>
<pre><code><div class="pagination">
{pagination_link_01 values=$pagination_links}
</div>
</code></pre>
<p>The following is the function body:</p>
<pre><code><?php
function smarty_function_pagination_link_01($params, &$smarty)
{
if ( !is_array($params['values']) )
{
return "is not array";
}
if ( 0 == count($params['values']) )
{
return "Empty Array";
}
if ( empty($params['values']['current_page']) )
{
return "Invalid Request";
}
$values = $params['values'];
//Seperator Used Betwinn Pagination Links
$seprator = empty( $params['seperator'] ) ? "&nbsp;&nbsp;" : $params['seperator'];
//Class Name For Links
$extra = empty( $params['extra'] ) ? "" : $params['extra'];
$current_page = (int)$values['current_page'];
if ( !empty($values['first']) )
{
//$ret[] = "<a $extra href='{$values['first']}' >&lt;First</a>";
}
if ( !empty($values['previous'] ) )
{
$ret[] = "<a $extra href='{$values['previous']}' class='prev active'><span></span></a>";
}
$ret[] = "<ul>";
foreach( $values as $k => $v )
{
if( is_numeric( $k ) )
{
if ( $k == $current_page)
{
$ret[] = "<li><a $extra class='active'>$k</a></li>";
}
else
{
$ret[] = "<li><a $extra href='$v'>$k </a></li>";
}
}
}
if ( !empty($values['next'] ) )
{
$ret[] = "</ul><a $extra href='{$values['next']}' class='next active'><span></span></a>";
}
if ( !empty($values['last'] ) )
{
//$ret[] = "<a $extra href='{$values['last']}' >Last&gt;</a>";
}
//$str_ret = $first . $previous . $str_ret . $next . $last;
if ( $ret )
{
return implode( $seprator, $ret );
}
}
?>
</code></pre>
<p>If I print <code>$params</code> I'm getting the values I passed by means of an array <code>$pagination_links</code>. Similarly I want to add one more argument named <code>$total_pages</code> to the above function call and use it in the function body. I tried many ways but it couldn't happen. Can anyone please guide me in this regard please. Thanks in advance.</p>
| 1 | 1,227 |
Performance of FirstOrDefault()
|
<p>Looking at a section of the webapp I work on today with a performance profiler. I thought that a Union was causing some delays, but found other surprising results instead.</p>
<p>One of the causes of slowdown appeared to be FirstOrDefault.</p>
<p>It was a very simple LINQ query that looked like this:</p>
<pre><code>foreach(Report r in reports)
IDTOStudy study = studies.FirstOrDefault(s => s.StudyID == r.StudyID);
</code></pre>
<p>I created a small method to duplicate the behaviour I figured FirstOrDefault was doing.</p>
<pre><code>private IDTOStudy GetMatchingStudy(Report report, IList<IDTOStudy> studies)
{
foreach (var study in studies)
if (study.StudyID == report.StudyID)
return study;
return null;
}
</code></pre>
<p>This method replaced the FirstOrDefault to look like this:</p>
<pre><code>foreach(Report r in reports)
IDTOStudy study = GetMatchingStudy(r, studies);
</code></pre>
<p>Looking at the new code running with the performance profiler showed <code>FirstOrDefault</code> to take twice as long to complete as my new method. This was a shock to see.</p>
<p>I must be doing something incorrect with the <code>FirstOrDefault()</code> query. What is it? </p>
<p>Does <code>FirstOrDefault()</code> complete the entire query and then take the first element? </p>
<p>How can I speed this up and use <code>FirstOrDefault()</code>?</p>
<p>Edit 1:</p>
<p>One additional point I noticed is that the profiler says I'm maxing out my CPU on both of these implementations. That's also something I don't care for and didn't expect. The additional method I added didn't reduce that spike, just cut its duration in half.</p>
<p>Edit 3:</p>
<p>Putting the studies into a dictionary has improved the run time tremendously. It's definitely going to be how the committed code looks. Doesn't answer the question on FirstOrDefault though.</p>
<p>Edit 2:</p>
<p>Here's the sample code requested in a simple console app. My run still shows that in most cases FirstOrDefault takes longer.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reactive.Linq;
using System.Reactive.Concurrency;
using System.Diagnostics;
namespace TestCode
{
public class Program
{
public List<IntHolder> list;
public static void Main(string[] args)
{
var prog = new Program();
prog.list = new List<IntHolder>();
prog.Add50000Items();
prog.list.Add(new IntHolder() { Num = 12345 });
prog.Add50000Items();
var stopwatch = new Stopwatch();
stopwatch.Start();
prog.list.FirstOrDefault(n => n.Num == 12345);
stopwatch.Stop();
Console.WriteLine("First run took: " + stopwatch.ElapsedTicks);
var lookingFor = new IntHolder() { Num = 12345 };
stopwatch.Reset();
stopwatch.Start();
prog.GetMatching(lookingFor);
stopwatch.Stop();
Console.WriteLine("Second run took: " + stopwatch.ElapsedTicks);
Console.ReadLine();
}
public void Add50000Items()
{
var rand = new Random();
for (int i = 0; i < 50000; i++)
list.Add(new IntHolder() { Num = rand.Next(100000) });
}
public IntHolder GetMatching(IntHolder num)
{
foreach (var number in list)
if (number.Num == num.Num)
return number;
return null;
}
}
public class IntHolder
{
public int Num { get; set; }
}
}
</code></pre>
| 1 | 1,418 |
ASP.Net MVC switching Cultures after compile for initial load
|
<p>I have a hybrid ASP.Net web forms/MVC app. On one of the MVC "pages"/views, I have it render a bunch of dates using the ToShortDateString() and ToLongDateString(). These work correctly most of the time, but the first time I load the view after compiling the app, they are formatted incorrectly.</p>
<p>I traced this down and checked the current thread's culture. For 99% of the time it's en-US, but on the first load of the MVC view after compiling it is set to en-GB. If I reload the page immediately after that, it's back to en-US.</p>
<p>I have tried setting the culture and uiculture in the web.config file to en-US to force it to be correct, but no luck.</p>
<p>Anyone have any ideas on this one? Bug in MVC?</p>
<p>Edit (additional code and attempts):
Even if I go completely overboard and include this in the base class of the view</p>
<pre><code>public class DNViewPage<T> : ViewPage<T> where T : class
{
protected override void OnInit(EventArgs e) {
base.OnInit(e);
CultureInfo cultureInfo = new CultureInfo("en-US");
this.Culture = "en-US";
this.UICulture = "en-US";
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = cultureInfo;
}
protected void Page_Load(object sender, EventArgs e) {
CultureInfo cultureInfo = new CultureInfo("en-US");
this.Culture = "en-US";
this.UICulture = "en-US";
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = cultureInfo;
}
protected override void InitializeCulture() {
CultureInfo cultureInfo = new CultureInfo("en-US");
this.Culture = "en-US";
this.UICulture = "en-US";
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = cultureInfo;
base.InitializeCulture();
}
}
</code></pre>
<p>and include this in the web.config</p>
<pre><code><globalization requestEncoding="utf-8" responseEncoding="utf-8" uiCulture="en-US" culture="en-US"/>
</code></pre>
<p>and this in the header of the .aspx file</p>
<pre><code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Culture="en-US" UICulture="en-US"
</code></pre>
<p>Again, this is only on the initial load after compiling the code, when that page first loads. Other web forms pages are unaffected, even if they descend from System.Web.Mvc.ViewPage. All subsequent loads treat the culture correctly. Just changing the .aspx file doesn't cause this, the c# code has to be compiled to cause this.</p>
<p>More data:
I have it tracked down to the Render method. Before the Render method, the culture is en-US and afterwards it is en-GB (again only on initial pageload after compilation).</p>
| 1 | 1,054 |
You have an error in your SQL syntax - hibernate and mysql
|
<p>I'm learning Hibernate, and during simple demo application, I encounter problem, I can't overcame. There are only two tables, two entity classes and main app. Project is in maven.</p>
<p>Github: github.com/fangirsan/maruszka.git</p>
<p>Batch.class:</p>
<pre><code>package com.maruszka.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name="batch")
public class Batch {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="batch_number")
private int batchNumber;
@Column(name="batch_style")
private String batchStyle;
@Column(name="batch_name")
private String batchName;
@Column(name="batch_creation_date", columnDefinition="DATE")
@Temporal(TemporalType.TIMESTAMP)
private Date batchCreationDate;
@ManyToMany(fetch=FetchType.LAZY,
cascade= {CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.DETACH, CascadeType.REFRESH})
@JoinTable(
name="batch_malt",
joinColumns=@JoinColumn(name="batch_id"),
inverseJoinColumns=@JoinColumn(name="malt_id")
)
private List<Malt> malts;
public Batch() {
}
public Batch(int batchNumber, String batchStyle, String batchName, Date batchCreationDate) {
this.batchNumber = batchNumber;
this.batchStyle = batchStyle;
this.batchName = batchName;
this.batchCreationDate = batchCreationDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBatchNumber() {
return batchNumber;
}
public void setBatchNumber(int batchNumber) {
this.batchNumber = batchNumber;
}
public String getBatchStyle() {
return batchStyle;
}
public void setBatchStyle(String batchStyle) {
this.batchStyle = batchStyle;
}
public String getBatchName() {
return batchName;
}
public void setBatchName(String batchName) {
this.batchName = batchName;
}
public Date getBatchCreationDate() {
return batchCreationDate;
}
public void setBatchCreationDate(Date batchCreationDate) {
this.batchCreationDate = batchCreationDate;
}
public List<Malt> getMalts() {
return malts;
}
public void setMalts(List<Malt> malts) {
this.malts = malts;
}
@Override
public String toString() {
return "Batch [id=" + id + ", batchNumber=" + batchNumber + ", batchStyle=" + batchStyle + ", batchName="
+ batchName + ", batchCreationDate=" + batchCreationDate + ", malts=" + malts + "]";
}
// add a convenience method
public void addMalt(Malt theMalt) {
if (malts == null) {
malts = new ArrayList<>();
}
malts.add(theMalt);
}
}
</code></pre>
<p>Malt.class</p>
<pre><code>package com.maruszka.entity;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name="malt")
public class Malt {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="malt_name")
private String maltName;
@Column(name="malt_manufacturer")
private String maltManufacturer;
@Column(name="filling")
private int filling;
@Column(name="ebc")
private int ebc;
@Column(name="usage")
private String usage;
@ManyToMany(fetch=FetchType.LAZY,
cascade= {CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.DETACH, CascadeType.REFRESH})
@JoinTable(
name="batch_malt",
joinColumns=@JoinColumn(name="malt_id"),
inverseJoinColumns=@JoinColumn(name="batch_id")
)
private List<Batch> batches;
public Malt() {
}
public Malt(String maltName, String maltManufacturer, int filling, int ebc, String usage) {
this.maltName = maltName;
this.maltManufacturer = maltManufacturer;
this.filling = filling;
this.ebc = ebc;
this.usage = usage;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMaltName() {
return maltName;
}
public void setMaltName(String maltName) {
this.maltName = maltName;
}
public String getMaltManufacturer() {
return maltManufacturer;
}
public void setMaltManufacturer(String maltManufacturer) {
this.maltManufacturer = maltManufacturer;
}
public int getFilling() {
return filling;
}
public void setFilling(int filling) {
this.filling = filling;
}
public int getEbc() {
return ebc;
}
public void setEbc(int ebc) {
this.ebc = ebc;
}
public String getUsage() {
return usage;
}
public void setUsage(String usage) {
this.usage = usage;
}
public List<Batch> getBatches() {
return batches;
}
public void setBatches(List<Batch> batches) {
this.batches = batches;
}
@Override
public String toString() {
return "Malt [id=" + id + ", maltName=" + maltName + ", maltManufacturer=" + maltManufacturer + ", filling="
+ filling + ", ebc=" + ebc + ", usage=" + usage + ", batches=" + batches + "]";
}
}
</code></pre>
<p>CreateBatchAndMalt.class (main):</p>
<pre><code>package com.maruszka.test;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.maruszka.entity.Malt;
import com.maruszka.entity.Batch;
public class CreateBatchAndMalt {
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Batch.class)
.addAnnotatedClass(Malt.class)
.buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// start a transaction
session.beginTransaction();
// create a malt
Malt tempMalt = new Malt("Carafa (R) typ I", "Weyerman", 10, 900, "Stout, Porter, Schwarzbier");
// save the malt
System.out.println("\nSaving the malt ...");
session.save(tempMalt);
System.out.println("Saved the malt: " + tempMalt);
// create the batch
Date now = new Date();
Batch tempBatch = new Batch(2, "Mild", "Szatan", now);
// add malt to the batch
tempBatch.addMalt(tempMalt);
// save the batch
System.out.println("\nSaving batch ...");
session.save(tempBatch);
System.out.println("Saved batch: " + tempBatch.getMalts());
// commit transaction
session.getTransaction().commit();
System.out.println("Done!");
}
finally {
// close session
session.close();
factory.close();
}
}
}
</code></pre>
<p>pom.xml:</p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.maruszka</groupId>
<artifactId>maruszka</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>maruszka Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<springframework.version>5.0.2.RELEASE</springframework.version>
<springsecurity.version>5.0.1.RELEASE</springsecurity.version>
<hibernate.version>5.3.1.Final</hibernate.version>
<!-- 5.2.12.Final -->
<mysql.connector.version>5.1.38</mysql.connector.version>
<c3po.version>0.9.5.2</c3po.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- Add support for JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring MVC support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Add support for Spring Tags -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.4.Final</version>
</dependency>
<!-- Add MySQL and C3P0 support -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
<!-- dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency-->
</dependencies>
<build>
<!-- TO DO: Add support for Maven WAR Plugin -->
<finalName>maruszka</finalName>
<pluginManagement>
<plugins>
<plugin>
<!-- Add Maven coordinates for: maven-war-plugin -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
</code></pre>
<p>hibernate.cfg.xml (in maruszka\src\main\resources\hibernate.cfg.xml):</p>
<pre><code><!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/maruszka?serverTimezone=UTC</property>
<!-- &useSSL=false -->
<property name="connection.username">***</property>
<property name="connection.password">***</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">false</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
</code></pre>
<p>DB script:</p>
<pre><code>CREATE DATABASE IF NOT EXISTS `maruszka`;
USE `maruszka`;
SET FOREIGN_KEY_CHECKS=0;
-- batch
DROP TABLE IF EXISTS `batch`;
CREATE TABLE `batch` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`batch_number` int(3) NOT NULL,
`batch_style` varchar(45) DEFAULT NULL,
`batch_name` varchar(45) DEFAULT NULL,
`batch_creation_date` DATE,
PRIMARY KEY (`id`),
UNIQUE KEY(`batch_number`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
LOCK TABLE `batch` WRITE;
INSERT INTO `batch` VALUES
(1, 1, 'Stout', 'Happy Stout', '2018-06-06');
UNLOCK TABLES;
-- malt
DROP TABLE IF EXISTS `malt`;
CREATE TABLE `malt` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`malt_name` varchar(45) DEFAULT NULL,
`malt_manufacturer` varchar(45) DEFAULT NULL,
`filling` int(3) DEFAULT NULL,
`ebc` int(3) DEFAULT NULL,
`usage` varchar(254) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY(`malt_name`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
LOCK TABLES `malt` WRITE;
INSERT INTO `malt` VALUES
(1, 'Pale Ale', 'Malteurop', 100, 6, 'All');
UNLOCK TABLES;
-- join table for batch - malt
DROP TABLE IF EXISTS `batch-malt`;
CREATE TABLE `batch-malt` (
`batch_id` int(11) NOT NULL,
`malt_id` int(11) NOT NULL,
PRIMARY KEY (`batch_id`, `malt_id`),
-- fk_[referencing table name]_[referenced table name]_[referencing field name]
CONSTRAINT `FK_BATCH_MALT_ID` FOREIGN KEY (`malt_id`)
REFERENCES `malt` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_MALT_BATCH_ID` FOREIGN KEY (`batch_id`)
REFERENCES `batch` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
SET FOREIGN_KEY_CHECKS=1;
</code></pre>
<p>When using mysql connector in version 8.0.11:</p>
<pre><code>cze 06, 2018 9:33:53 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.3.1.Final}
cze 06, 2018 9:33:53 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
cze 06, 2018 9:33:53 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.3.Final}
cze 06, 2018 9:33:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
cze 06, 2018 9:33:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/maruszka?serverTimezone=UTC]
cze 06, 2018 9:33:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
cze 06, 2018 9:33:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
cze 06, 2018 9:33:53 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Wed Jun 06 21:33:53 CEST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
cze 06, 2018 9:33:53 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
cze 06, 2018 9:33:54 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 6.0.4.Final
Saving the malt ...
cze 06, 2018 9:33:54 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1064, SQLState: 42000
cze 06, 2018 9:33:54 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage) values (900, 10, 'Weyerman', 'Carafa (R) typ I', 'Stout, Porter, Schwarzb' at line 1
cze 06, 2018 9:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/maruszka?serverTimezone=UTC]
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3037)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3628)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:359)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:292)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:200)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:131)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:709)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:696)
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.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:349)
at com.sun.proxy.$Proxy36.save(Unknown Source)
at com.maruszka.test.CreateBatchAndMalt.main(CreateBatchAndMalt.java:42)
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage) values (900, 10, 'Weyerman', 'Carafa (R) typ I', 'Stout, Porter, Schwarzb' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:960)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1116)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1066)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1396)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1051)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
... 28 more
</code></pre>
<p>I've double check syntax, but can't figure out wha is causing this:</p>
<pre><code>ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage) values (900, 10, 'Weyerman', 'Carafa (R) typ I', 'Stout, Porter, Schwarzb' at line 1
</code></pre>
<p>Best regards</p>
| 1 | 9,601 |
Error Installing php-devel on centos 6.5 and php 5.4
|
<p>Server is running Centos 6.5 with PHP 5.4.40.</p>
<p>Entering:</p>
<pre><code>yum install php-devel
</code></pre>
<p>Results in the following:</p>
<pre><code>Loaded plugins: fastestmirror, refresh-packagekit, replace, security
Loading mirror speeds from cached hostfile
* base: mirror.tngwebhost.com
* epel: fedora.westmancom.com
* extras: mirror.tocici.com
* updates: mirror.oss.ou.edu
* webtatic: uk.repo.webtatic.com
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package php-devel.x86_64 0:5.3.3-46.el6_6 will be installed
--> Processing Dependency: php(x86-64) = 5.3.3-46.el6_6 for package: php-devel-5.3.3-46.el6_6.x86_64
--> Running transaction check
---> Package php.x86_64 0:5.3.3-46.el6_6 will be installed
--> Processing Dependency: php-common(x86-64) = 5.3.3-46.el6_6 for package: php-5.3.3-46.el6_6.x86_64
--> Processing Dependency: php-cli(x86-64) = 5.3.3-46.el6_6 for package: php-5.3.3-46.el6_6.x86_64
--> Running transaction check
---> Package php-cli.x86_64 0:5.3.3-46.el6_6 will be installed
---> Package php-common.x86_64 0:5.3.3-46.el6_6 will be installed
--> Processing Conflict: php54w-common-5.4.40-1.w6.x86_64 conflicts php-common < 5.4.0
--> Restarting Dependency Resolution with new changes.
--> Running transaction check
---> Package php54w-common.x86_64 0:5.4.40-1.w6 will be updated
--> Processing Dependency: php54w-common(x86-64) = 5.4.40-1.w6 for package: php54w-mbstring-5.4.40-1.w6.x86_64
--> Processing Dependency: php54w-common(x86-64) = 5.4.40-1.w6 for package: php54w-gd-5.4.40-1.w6.x86_64
--> Processing Dependency: php54w-common(x86-64) = 5.4.40-1.w6 for package: php54w-pdo-5.4.40-1.w6.x86_64
--> Processing Dependency: php54w-common(x86-64) = 5.4.40-1.w6 for package: php54w-5.4.40-1.w6.x86_64
--> Processing Dependency: php54w-common(x86-64) = 5.4.40-1.w6 for package: php54w-cli-5.4.40-1.w6.x86_64
--> Processing Dependency: php54w-common(x86-64) = 5.4.40-1.w6 for package: php54w-xml-5.4.40-1.w6.x86_64
--> Processing Dependency: php54w-common(x86-64) = 5.4.40-1.w6 for package: php54w-dba-5.4.40-1.w6.x86_64
--> Processing Dependency: php54w-common(x86-64) = 5.4.40-1.w6 for package: php54w-bcmath-5.4.40-1.w6.x86_64
---> Package php54w-common.x86_64 0:5.4.45-1.w6 will be an update
--> Running transaction check
---> Package php54w.x86_64 0:5.4.40-1.w6 will be updated
---> Package php54w.x86_64 0:5.4.45-1.w6 will be an update
---> Package php54w-bcmath.x86_64 0:5.4.40-1.w6 will be updated
---> Package php54w-bcmath.x86_64 0:5.4.45-1.w6 will be an update
---> Package php54w-cli.x86_64 0:5.4.40-1.w6 will be updated
---> Package php54w-cli.x86_64 0:5.4.45-1.w6 will be an update
---> Package php54w-dba.x86_64 0:5.4.40-1.w6 will be updated
---> Package php54w-dba.x86_64 0:5.4.45-1.w6 will be an update
---> Package php54w-gd.x86_64 0:5.4.40-1.w6 will be updated
---> Package php54w-gd.x86_64 0:5.4.45-1.w6 will be an update
---> Package php54w-mbstring.x86_64 0:5.4.40-1.w6 will be updated
---> Package php54w-mbstring.x86_64 0:5.4.45-1.w6 will be an update
---> Package php54w-pdo.x86_64 0:5.4.40-1.w6 will be updated
---> Package php54w-pdo.x86_64 0:5.4.45-1.w6 will be an update
---> Package php54w-xml.x86_64 0:5.4.40-1.w6 will be updated
---> Package php54w-xml.x86_64 0:5.4.45-1.w6 will be an update
--> Processing Conflict: php54w-common-5.4.45-1.w6.x86_64 conflicts php-common < 5.4.0
--> Finished Dependency Resolution
Error: php54w-common conflicts with php-common-5.3.3-46.el6_6.x86_64
You could try using --skip-broken to work around the problem
You could try running: rpm -Va --nofiles --nodigest
</code></pre>
<p>Another user on SO had the issue when running 5.3, tried variations of their recommendations with no luck. The last two lines of the error make to recommendations but don't want try random commands that may negatively impact the server. Any ideas or more information I can provide?</p>
<p>To note, ultimately trying to install SSH2 but requires php-devel.</p>
| 1 | 1,784 |
Python plot base64 string as image
|
<p>I am attempting to convert a jpg, which is encoded as a base64 string that I receive over the server into an RGB image that I can use with numpy, but also plot with matplot lib. I am unable to find docs on how to take a raw base64 string and plot that using python.</p>
<p>I also have the option to receive as a png.</p>
<p>Here is where I am currently, which does not work. Feel free to snag the image bytes.</p>
<pre><code>image = '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAA2AGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxNYvapBF7VoLaH0qVbM+ldCgYOZmCH2p3k+1aosm9KeLFv7tVyE85keT7Unk+1bP2Fv7tJ9hb+7RyBzmN5PtSGL2ro7LQri/l2RrgDlnboK318FWqwqWujK7HopC4/A8/lScRqR52YvamGKuzl0/S7G7ltpbaWZkbaSW4BHp0qbUbPT9JZfLtUklcE7GBIA+p/H8qXKNSOEMRPam+Q7EAIST0AFd1pqRXrySC2jhKYxtUd/wrM1K/ljvJooAjRI5VW65APXIqXErmJEnAAJt1x/vH/CrCXSf8+6f99n/Ckg1W6jRUMgkjUYVJVDqPoDxWha6nZGUNe6Vbzj+IoWjJ9OhwPy/xquaXYhwj2/r8Cul0n/PvH/32f8KtWrC5mWJLeAM3QvPtH5kYq0kPhq5iiUTX1pMzfOzqsiKPwwfT/CraeEorwudM1uxnXO2NJGMcjnHQKffgc0/atf0xezh/V/8AhvxMySRY5GRreAlSQcTZH5gc1YtJNPYFrsJHg8KrFs/pUn/CIaul8LOZYopmjMiqZA2QP93OPxwK6rRfBcVvKJry0jmVR92acjnC84UdM7uCe/tk8GJzejh9G7vy/wCHBUoP/h/+CZM7XMFqklnpszW2zfvMbKoXrnOOfXNVtKm36pFLcqqKc5dpOnB9q2tZ0OwW2mjt4hDcyAmGMSNkYySMZIPbv9AO/AXtw1rcvFBOZY1+65UDP4Anv71WDzGGJT5F95bgv6/4c39RFvca1OFWIo05/eCTPG7r0qHxI8BuLfYIpQIsE+Z0O5uKwIdYvbWQyQXDxORgsjYOPTim3Wt3t5t+03EsxX7u9ycV2e0fYlU1tY3tDhE3noERC20D5s+tctLGdx/dL/31/wDWpr3rn/8AXUo1ydI1TyrbCjGTAhP545pObK5Cuj1OsnvWeklTLJQmOxoLJUqykHIOPpWestSCWncRpiefPEsu4rlMHitZbzUTp2A6mTH38n+WK4ya5kEhUOwA6YOKeuqXax7BMdvuAa8qvgZVHdNFqTOosbq7+1RJJI4ZzjkkgjvxW1aaP4U1Wadb7WHtr92fIP3A2TgkkY9+tefR6teRA7LhhkYz3/D0qGO5bzSzsSW6k1vh8NKnJylb5Cep6ZP8LVmtUm0vXba53HgsNq49iCc81z+ofDzxDZNJttlnjQZ3xODnjsOv6Vz6Xk0Lq8UroynKlWxg1q2/jTXrWMomoyMucnzMOfzNddn3/r5Cu/6/4BkXek6lZoHubG4iQnALxkDNZr5U4IIPvXfRfEu8IIu7OKUdtpxj880lx4m8Oak8n2mxVWdfmkeIZPbqOaWvYd/I87SQ1OshoopgSLIakEhoopgRzDd83eq+40UUAG40m7miigC0H+UU1pDRRQBEzmoWkNFFJgf/2Q=='
import base64
import io
from matplotlib import pyplot as plt
from array import array
import numpy as np
i = base64.b64decode(image)
i = np.fromstring(image, np.ubyte)
plt.imshow(i, interpolation='nearest')
plt.show()
</code></pre>
<p>Any assistance is greatly appreciated.</p>
<p>Here is code that generates the encoded string that is sent out by the server:</p>
<pre><code>byte[] bytes = image.EncodeToJPG();
return Convert.ToBase64String(bytes);
</code></pre>
| 1 | 2,000 |
Segmentation fault in OpenGL under Linux
|
<p>I am following some tutorials and came up with the following code:</p>
<pre><code>// rendering.cpp
#include "rendering.h"
#include <GL/gl.h>
#include <GL/freeglut.h>
void DrawGLScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
}
int InitGL(int argc, char** argv)
{
/*glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);*/
glutInit(&argc, argv);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutDisplayFunc(DrawGLScene);
glutCreateWindow("Swimming Simulation");
glutMainLoop(); // Enter GLUT's main loop
return true;
}
</code></pre>
<p>My main function is very simple and only calls that function:</p>
<pre><code>#include "rendering.h"
int main(int argc, char** argv)
{
InitGL(argc, argv);
return 0;
}
</code></pre>
<p>I am compiling with this command:</p>
<pre><code>g++ -Wall -g swim.cpp rendering.cpp -lglut -lGLU -o swim
</code></pre>
<p>Running <code>swim</code> creates a window as expected. However, if I uncomment the lines in <code>InitGL</code>, then I get a segmentation fault when running the program:</p>
<pre><code>(gdb) r
Starting program: <dir>
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib64/libthread_db.so.1".
Program received signal SIGSEGV, Segmentation fault.
0x000000335ca52ca7 in glShadeModel () from /usr/lib64/libGL.so.1
Missing separate debuginfos, use: debuginfo-install freeglut-2.6.0-6.fc15.x86_64 glibc-2.14.90-24.fc16.6.x86_64 libX11-1.4.3-1.fc16.x86_64 libXau-1.0.6-2.fc15.x86_64 libXdamage-1.1.3-2.fc15.x86_64 libXext-1.3.0-1.fc16.x86_64 libXfixes-5.0-1.fc16.x86_64 libXi-1.4.5-1.fc16.x86_64 libXxf86vm-1.1.1-2.fc15.x86_64 libdrm-2.4.33-1.fc16.x86_64 libgcc-4.6.3-2.fc16.x86_64 libstdc++-4.6.3-2.fc16.x86_64 libxcb-1.7-3.fc16.x86_64 mesa-libGL-7.11.2-3.fc16.x86_64 mesa-libGLU-7.11.2-3.fc16.x86_64
(gdb) backtrace
#0 0x000000335ca52ca7 in glShadeModel () from /usr/lib64/libGL.so.1
#1 0x0000000000401d67 in InitGL (argc=1, argv=0x7fffffffe198)
at rendering.cpp:25
#2 0x0000000000401c8c in main (argc=1, argv=0x7fffffffe198) at swim.cpp:37
</code></pre>
<p>What should I be doing here to get my program to run without crashing?</p>
| 1 | 1,078 |
Adding Table.Row fadeout transition
|
<p>I've built a simple add-your-todos system in React using Semantic-UI-React. It currently looks like this:</p>
<p><a href="https://i.stack.imgur.com/h1u43.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h1u43.gif" alt="before-transition-attempt"></a></p>
<h2>Problem description, and my attempt</h2>
<p>When the user clicks on the red bin icon, <strong>I'd like to delete the Table.Row using a Fadeout Transition</strong>. It currently deletes the row, but an animation here would make the user experience more enjoyable. <a href="https://react.semantic-ui.com/modules/transition#transition-example-transition-explorer" rel="nofollow noreferrer">I've visited the docs and tried to implement the solution</a>, using a Transition.Group component.</p>
<h2>...but it didn't work well</h2>
<p>After trying to solve this problem on my own, I got some unexpected behaviours. First of all, rows don't fadeout. Furthermore, all Table.Cell kind of "blend" into one single cell, which is annoying. See the (gruesome) result:</p>
<p><a href="https://i.stack.imgur.com/B8LZ7.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B8LZ7.gif" alt="after-transition-attempt"></a></p>
<h2>The Todo component (before)</h2>
<p>Each Todo row is being dynamically added on the Table using a Todo component, which, before implementing Transition.Group, looked like this:</p>
<pre><code>const React = require('react');
const moment = require('moment');
import { Table, Checkbox, Icon, Popup, Grid, Button } from 'semantic-ui-react';
class Todo extends React.Component {
constructor(props) {
super(props);
}
render() {
const { id, text, completed, createdAt, completedAt } = this.props;
const renderDate = (date) => {
const timestamp = date;
if (timestamp)
return `${moment.unix(timestamp).format('MMM Do YYYY @ h:mm a')}`;
return '';
}
const renderPopup = () => {
if (completedAt) {
return (
<Popup trigger={<Icon name="calendar check" size="large"/>} header={'Completed at'} content={renderDate(completedAt)}/>
);
} else {
return (
''
);
}
}
return (
<Table.Row>
<Table.Cell>
<Grid columns="equal">
<Grid.Column width={3}>
<Checkbox toggle
defaultChecked={completed}
onClick={() => this.props.onToggle(id)} />
</Grid.Column>
<Grid.Column textAlign="left">
{renderPopup()}
</Grid.Column>
</Grid>
</Table.Cell>
<Table.Cell>{text}</Table.Cell>
<Table.Cell>{renderDate(createdAt)}</Table.Cell>
<Table.Cell textAlign="right">
<Button basic color="red" icon="trash"
onClick={() => {
this.props.onRemoveTodo(id);
this.handleFadeoutItem();
}}/>
</Table.Cell>
</Table.Row>
);
}
}
module.exports = Todo;
</code></pre>
<h2>The component (after)</h2>
<p>This is how it looks now (which is obviously wrong!):</p>
<pre><code>const React = require('react');
const moment = require('moment');
import { Table, Checkbox, Icon, Popup, Grid, Button, Transition } from 'semantic-ui-react';
class Todo extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: true
};
this.handleFadeoutItem = this.handleFadeoutItem.bind(this);
}
handleFadeoutItem () {
this.setState({
visible: false
});
}
render() {
const { visible } = this.state;
const { id, text, completed, createdAt, completedAt } = this.props;
const renderDate = (date) => {
const timestamp = date;
if (timestamp)
return `${moment.unix(timestamp).format('MMM Do YYYY @ h:mm a')}`;
return '';
}
const renderPopup = () => {
if (completedAt) {
return (
<Popup trigger={<Icon name="calendar check" size="large"/>} header={'Completed at'} content={renderDate(completedAt)}/>
);
} else {
return (
''
);
}
}
return (
<Transition.Group as={Table.Row} visible={visible} animation="fade" duration={500}>
<Table.Row>
<Table.Cell>
<Grid columns="equal">
<Grid.Column width={3}>
<Checkbox toggle
defaultChecked={completed}
onClick={() => this.props.onToggle(id)} />
</Grid.Column>
<Grid.Column textAlign="left">
{renderPopup()}
</Grid.Column>
</Grid>
</Table.Cell>
<Table.Cell>{text}</Table.Cell>
<Table.Cell>{renderDate(createdAt)}</Table.Cell>
<Table.Cell textAlign="right">
<Button basic color="red" icon="trash"
onClick={() => {
this.props.onRemoveTodo(id);
this.handleFadeoutItem();
}}/>
</Table.Cell>
</Table.Row>
</Transition.Group>
);
}
}
module.exports = Todo;
</code></pre>
<p>Any help offered will be greatly appreciated!</p>
<hr>
<p><strong>EDIT</strong></p>
<p>@Adrien's answer partially solved my problem. Now every cell is in its place, but the animation transition doesn't seem to play. Furthermore, the calendar icon next to my "completed" checkboxes (check the initial, unmodified version of the app) seem to disappear. Any idea why these two things happen? See:</p>
<p><a href="https://i.stack.imgur.com/ajaOa.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ajaOa.gif" alt="still-not-quite-right"></a></p>
| 1 | 3,555 |
Remember Me with Spring Security 3.1.3 - deprecated default constructors
|
<p>I'm doing a login with Spring Security 3.1 but I get a warning to deprecated and I could not get erased, it seems that this configuration is for version 3.0</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/pages/admin/**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/**" access="permitAll"/>
<form-login login-page="/pages/login.jsf"/>
<remember-me key="jsfspring-sec" services-ref="rememberMeServices"/>
<logout
invalidate-session="true"
delete-cookies="JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE"
logout-success-url="/pages/login.jsf"/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider ref="rememberMeAuthenticationProvider">
</authentication-provider>
<authentication-provider>
<user-service id="userDetailsService">
<user authorities="ROLE_ADMIN" name="admin" password="admin" />
</user-service>
</authentication-provider>
</authentication-manager>
<beans:bean id="rememberMeServices"
class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
<beans:property name="key" value="jsfspring-sec" />
<beans:property name="userDetailsService" ref="userDetailsService" />
<beans:property name="alwaysRemember" value="true" />
<beans:property name="tokenValiditySeconds" value="60" />
</beans:bean>
<beans:bean id="rememberMeAuthenticationProvider"
class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
<beans:property name="key" value="jsfspring-sec"/>
</beans:bean>
<beans:bean id="rememberMeFilter"
class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
<beans:property name="rememberMeServices" ref="rememberMeServices"/>
<beans:property name="authenticationManager" ref="authenticationManager" />
</beans:bean>
</beans:beans>
</code></pre>
<p>I could not find how to do it with Spring 3.1. Can someone help me? The last three beans are deprecated, I would appreciate help. Here is the url of the repository in GitHub: <a href="https://github.com/wmanriques/spring_template" rel="nofollow">https://github.com/wmanriques/spring_template</a></p>
| 1 | 1,295 |
How to right align a <img> in Bootstrap 4 card-body?
|
<p>I am trying to right-align a in a Bootstrap 4 <code>card-body</code>, I tried to leverage the <code>float-right</code> class but it does not seem to work. Is there anything special in regard to images alignment in <code>card-body</code>?</p>
<pre><code><div class="card border-primary m-3" *ngIf='product'>
<div class="card-header bg-primary text-light text-center">
{{ pageTitle + ': ' + product?.productName }}
</div>
<div class="card-body">
<div class="row">
<div class="col-2-md">
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Id:</td>
<td>{{ product.productId }}</td>
</tr>
<tr>
<td>Name:</td>
<td>{{ product.productName }}</td>
</tr>
<tr>
<td>Code:</td>
<td>{{ product.productCode }}</td>
</tr>
<tr>
<td>Release Date:</td>
<td>{{ product.releaseDate }}</td>
</tr>
<tr>
<td>Price:</td>
<td>{{ product.price }}</td>
</tr>
<tr>
<td>Description:</td>
<td>{{ product.description }}</td>
</tr>
<tr>
<td>Rating:</td>
<td>
<app-star
[rating]='product.starRating'></app-star>
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-10-md">
<img class="card-img-top float-right" [src]='product.imageUrl'>
</div>
</div>
</div>
<div class="card-footer">
<button class="btn btn-secondary" (click)='onBackClicked()'> <i class="fa fa-chevron-left"></i> Back to List</button>
</div>
</div>
</code></pre>
<p>Any idea?</p>
| 1 | 1,550 |
Create Shiny Presentation from Shiny App?
|
<p>I found this - <a href="http://shiny.rstudio.com/gallery/download-knitr-reports.html" rel="nofollow">http://shiny.rstudio.com/gallery/download-knitr-reports.html</a> - awesome example that can create static PDFs, HTMLs, and Word Docs.</p>
<p>What I want to be able to do is upload a data set that can then generate a templatized Shiny Presentation. I've tried multiple routes with little success. The furthest I've gotten is including this code in my markdown file:</p>
<pre><code>---
title: "shinyPresentation"
author: "maloneypatr"
date: "Wednesday, September 03, 2014"
output:
ioslides_presentation:
self_contained: false
lib_dir: libs
runtime: shiny
---
</code></pre>
<p>Upon trying to download the sample .HTML file, I get this error <code>path for html_dependency not provided</code>. Am I chasing a functionality that doesn't currently exist? If not, does anyone have some advice?</p>
<p>Thanks in advance!</p>
<h2>--UPDATE AFTER YIHUI'S COMMENT--</h2>
<pre><code>>library(rmarkdown);library(shiny);sessionInfo()
R version 3.1.1 (2014-07-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] grid stats graphics grDevices utils datasets methods base
other attached packages:
[1] rmarkdown_0.2.47 knitr_1.6 shiny_0.10.1 ggmap_2.3 googleVis_0.5.5
[6] stringr_0.6.2 gdata_2.13.3 fileR_1.0 plyr_1.8.1 XLConnect_0.2-9
[11] XLConnectJars_0.2-9 dplyr_0.2 bigrquery_0.1 devtools_1.5 statebins_1.0
[16] RColorBrewer_1.0-5 gridExtra_0.9.1 scales_0.2.4 ggplot2_1.0.0 httr_0.4
loaded via a namespace (and not attached):
[1] assertthat_0.1.0.99 bitops_1.0-6 Cairo_1.5-5 caTools_1.17 colorspace_1.2-4
[6] digest_0.6.4 evaluate_0.5.5 formatR_0.10 gtable_0.1.2 gtools_3.4.1
[11] htmltools_0.2.4 httpuv_1.3.0 jsonlite_0.9.8 labeling_0.2 magrittr_1.0.1
[16] mapproj_1.2-2 maps_2.3-7 markdown_0.7 MASS_7.3-33 memoise_0.2.1
[21] mime_0.1.1 munsell_0.4.2 parallel_3.1.1 png_0.1-7 proto_0.3-10
[26] psych_1.4.8.11 Rcpp_0.11.2 RCurl_1.95-4.1 reshape2_1.4 RgoogleMaps_1.2.0.6
[31] rJava_0.9-6 rjson_0.2.14 RJSONIO_1.2-0.2 tools_3.1.1 whisker_0.3-2
[36] xtable_1.7-3 yaml_2.1.13
</code></pre>
<h2>This is my updated report.Rmd file:</h2>
<hr>
<pre><code>title: "shinyPresentation"
author: "maloneypatr"
date: "Wednesday, September 03, 2014"
output:
ioslides_presentation:
self_contained: false
lib_dir: libs
runtime: shiny
---
## Shiny Presentation
This R Markdown presentation is made interactive using Shiny. The viewers of the presentation can change the assumptions underlying what's presented and see the results immediately.
To learn more, see [Interative Documents](http://rmarkdown.rstudio.com/authoring_shiny.html).
## Slide with Interactive Plot
```{r, echo=FALSE}
inputPanel(
selectInput("n_breaks", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 20),
sliderInput("bw_adjust", label = "Bandwidth adjustment:",
min = 0.2, max = 2, value = 1, step = 0.2)
)
renderPlot({
hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks),
xlab = "Duration (minutes)", main = "Geyser eruption duration")
dens <- density(faithful$eruptions, adjust = input$bw_adjust)
lines(dens, col = "blue")
})
```
</code></pre>
| 1 | 1,813 |
Configuring Oozie- java NoClassDefFoundError
|
<p>I have been trying to run Oozie server on my machine, but am unable to do so. Following is the output of various commands and configuration I have done so far. Please explain what I am missing.</p>
<pre><code>INDhruvk:oozie-3.3.2-cdh4.5.0 Dhruv$ bin/oozie-start.sh
WARN: Use of this script is deprecated; use 'oozied.sh start' instead
Setting OOZIE_HOME: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0
Setting OOZIE_CONFIG: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/conf
Sourcing: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/conf/oozie-env.sh
/usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/conf/oozie-env.sh: line 1: pw#!/bin/bash: No such file or directory
setting CATALINA_OPTS="$CATALINA_OPTS -Xmx1024m"
Setting OOZIE_CONFIG_FILE: oozie-site.xml
Setting OOZIE_DATA: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/data
Setting OOZIE_LOG: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/logs
Setting OOZIE_LOG4J_FILE: oozie-log4j.properties
Setting OOZIE_LOG4J_RELOAD: 10
Setting OOZIE_HTTP_HOSTNAME: INDhruvk.local
Setting OOZIE_HTTP_PORT: 11000
Setting OOZIE_ADMIN_PORT: 11001
Setting OOZIE_HTTPS_PORT: 11443
Setting OOZIE_BASE_URL: http://INDhruvk.local:11000/oozie
Setting CATALINA_BASE: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/oozie-server
Setting OOZIE_HTTPS_KEYSTORE_FILE: /Users/Dhruv/.keystore
Setting OOZIE_HTTPS_KEYSTORE_PASS: password
Setting CATALINA_OUT: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/logs/catalina.out
Setting CATALINA_PID: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/oozie-server/temp/oozie.pid
Using CATALINA_OPTS: -Xmx1024m -Dderby.stream.error.file=/usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/logs/derby.log
Adding to CATALINA_OPTS: -Doozie.home.dir=/usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0 -Doozie.config.dir=/usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/conf -Doozie.log.dir=/usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/logs -Doozie.data.dir=/usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/data -Doozie.config.file=oozie-site.xml -Doozie.log4j.file=oozie-log4j.properties -Doozie.log4j.reload=10 -Doozie.http.hostname=INDhruvk.local -Doozie.admin.port=11001 -Doozie.http.port=11000 -Doozie.https.port=11443 -Doozie.base.url=http://INDhruvk.local:11000/oozie -Doozie.https.keystore.file=/Users/Dhruv/.keystore -Doozie.https.keystore.pass=password -Djava.library.path=
Using CATALINA_BASE: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/oozie-server
Using CATALINA_HOME: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/oozie-server
Using CATALINA_TMPDIR: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/oozie-server/temp
Using JRE_HOME: /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home
Using CLASSPATH: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/oozie-server/bin/bootstrap.jar
Using CATALINA_PID: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/oozie-server/temp/oozie.pid
Existing PID file found during start.
Removing/clearing stale PID file.
</code></pre>
<p>And another invocation of <code>oozie-run.sh</code>: </p>
<pre><code>INDhruvk:oozie-3.3.2-cdh4.5.0 Dhruv$ bin/oozie-run.sh
WARN: Use of this script is deprecated; use 'oozied.sh run' instead
Setting OOZIE_HOME: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0
Setting OOZIE_CONFIG: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/conf
Sourcing: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/conf/oozie-env.sh
/usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/conf/oozie-env.sh: line 1: pw#!/bin/bash: No such file or directory
setting CATALINA_OPTS="$CATALINA_OPTS -Xmx1024m"
Setting OOZIE_CONFIG_FILE: oozie-site.xml
Setting OOZIE_DATA: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/data
Setting OOZIE_LOG: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/logs
Setting OOZIE_LOG4J_FILE: oozie-log4j.properties
Setting OOZIE_LOG4J_RELOAD: 10
Setting OOZIE_HTTP_HOSTNAME: INDhruvk.local
Setting OOZIE_HTTP_PORT: 11000
Setting OOZIE_ADMIN_PORT: 11001
Setting OOZIE_HTTPS_PORT: 11443
Setting OOZIE_BASE_URL: http://INDhruvk.local:11000/oozie
Setting CATALINA_BASE: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/oozie-server
Setting OOZIE_HTTPS_KEYSTORE_FILE: /Users/Dhruv/.keystore
Setting OOZIE_HTTPS_KEYSTORE_PASS: password
Setting CATALINA_OUT: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/logs/catalina.out
Setting CATALINA_PID: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/oozie-server/temp/oozie.pid
Using CATALINA_OPTS: -Xmx1024m -Dderby.stream.error.file=/usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/logs/derby.log
Adding to CATALINA_OPTS: -Doozie.home.dir=/usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0 -Doozie.config.dir=/usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/conf -Doozie.log.dir=/usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/logs -Doozie.data.dir=/usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/data -Doozie.config.file=oozie-site.xml -Doozie.log4j.file=oozie-log4j.properties -Doozie.log4j.reload=10 -Doozie.http.hostname=INDhruvk.local -Doozie.admin.port=11001 -Doozie.http.port=11000 -Doozie.https.port=11443 -Doozie.base.url=http://INDhruvk.local:11000/oozie -Doozie.https.keystore.file=/Users/Dhruv/.keystore -Doozie.https.keystore.pass=password -Djava.library.path=
Using CATALINA_BASE: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/oozie-server
Using CATALINA_HOME: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/oozie-server
Using CATALINA_TMPDIR: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/oozie-server/temp
Using JRE_HOME: /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home
Using CLASSPATH: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/oozie-server/bin/bootstrap.jar
Using CATALINA_PID: /usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/oozie-server/temp/oozie.pid
Jan 06, 2014 11:24:43 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path:
Jan 06, 2014 11:24:43 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-11000
Jan 06, 2014 11:24:43 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 439 ms
Jan 06, 2014 11:24:43 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Jan 06, 2014 11:24:43 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.36
Jan 06, 2014 11:24:43 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor oozie.xml
ERROR: Oozie could not be started
REASON: java.lang.NoClassDefFoundError: org/apache/hadoop/util/ReflectionUtils
Stacktrace:
-----------------------------------------------------------------
java.lang.NoClassDefFoundError: org/apache/hadoop/util/ReflectionUtils
at org.apache.oozie.service.Services.setServiceInternal(Services.java:359)
at org.apache.oozie.service.Services.<init>(Services.java:108)
at org.apache.oozie.servlet.ServicesLoader.contextInitialized(ServicesLoader.java:38)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:675)
at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:601)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:502)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1317)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:324)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1065)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.util.ReflectionUtils
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
... 27 more
</code></pre>
<p>My lib folder has following jars:</p>
<pre><code>commons-cli-1.2.jar
hadoop-auth-2.0.0-cdh4.5.0.jar
json-simple-1.1.jar
slf4j-api-1.6.1.jar
xercesImpl-2.10.0.jar
commons-codec-1.4.jar
hadoop-core-2.0.0-mr1-cdh4.5.0.jar
oozie-client-3.3.2-cdh4.5.0.jar
slf4j-simple-1.6.1.jar
xml-apis-1.4.01.jar
</code></pre>
<p>I also added the same 2 jars to <code>libext</code> folder:</p>
<pre><code>hadoop-auth-2.0.0-cdh4.5.0.jar
hadoop-core-2.0.0-mr1-cdh4.5.0.jar
</code></pre>
<p>These are the contents of the <code>src/hadooplibs/</code></p>
<pre><code>hadoop-cdh4mr1/
hadoop-distcp-cdh4mr1/
hadoop-test-cdh4mr1/
pom.xml
hadoop-cdh4mr2/
hadoop-distcp-cdh4mr2/
hadoop-test-cdh4mr2/
</code></pre>
<p>These are the contents of the <code>/usr/local/hadoop/oozie/oozie-3.3.2-cdh4.5.0/libext</code></p>
<pre><code>JavaEWAH-0.3.2.jar
ST4-4.0.4.jar
activation-1.1.jar
antlr-2.7.7.jar
antlr-3.4.jar
antlr-runtime-3.4.jar
apache-log4j-extras-1.1.jar
asm-3.2.jar
avro-1.7.4.jar
avro-ipc-1.7.4-tests.jar
avro-ipc-1.7.4.jar
avro-mapred-1.7.4-hadoop2.jar
cloudera-jets3t-2.0.0-cdh4.5.0.jar
collections-generic-4.01.jar
commons-beanutils-1.7.0.jar
commons-beanutils-core-1.8.0.jar
commons-cli-1.2.jar
commons-codec-1.4.jar
commons-collections-3.2.1.jar
commons-compress-1.4.1.jar
commons-configuration-1.6.jar
commons-dbcp-1.4.jar
commons-digester-1.8.jar
commons-el-1.0.jar
commons-io-2.1.jar
commons-lang-2.4.jar
commons-logging-1.1.jar
commons-math-2.1.jar
commons-net-3.1.jar
commons-pool-1.5.4.jar
datanucleus-api-jdo-3.2.1.jar
datanucleus-connectionpool-2.0.3.jar
datanucleus-core-3.2.2.jar
datanucleus-enhancer-2.0.3.jar
datanucleus-rdbms-3.2.1.jar
derby-10.6.1.0.jar
geronimo-jms_1.1_spec-1.1.1.jar
geronimo-jpa_2.0_spec-1.1.jar
geronimo-jta_1.1_spec-1.1.1.jar
guava-11.0.2.jar
hadoop-annotations-2.0.0-cdh4.5.0.jar
hadoop-auth-2.0.0-cdh4.5.0.jar
hadoop-client-2.0.0-cdh4.5.0.jar
hadoop-client-2.0.0-mr1-cdh4.5.0.jar
hadoop-common-2.0.0-cdh4.5.0.jar
hadoop-core-2.0.0-mr1-cdh4.5.0.jar
hadoop-hdfs-2.0.0-cdh4.5.0.jar
hadoop-mapreduce-client-app-2.0.0-cdh4.5.0.jar
hadoop-mapreduce-client-common-2.0.0-cdh4.5.0.jar
hadoop-mapreduce-client-core-2.0.0-cdh4.5.0.jar
hadoop-mapreduce-client-jobclient-2.0.0-cdh4.5.0.jar
hadoop-mapreduce-client-shuffle-2.0.0-cdh4.5.0.jar
hadoop-yarn-api-2.0.0-cdh4.5.0.jar
hadoop-yarn-client-2.0.0-cdh4.5.0.jar
hadoop-yarn-common-2.0.0-cdh4.5.0.jar
hadoop-yarn-server-common-2.0.0-cdh4.5.0.jar
haivvreo-1.0.7-cdh-4.jar
hamcrest-core-1.1.jar
hive-builtins-0.10.0-cdh4.5.0.jar
hive-cli-0.10.0-cdh4.5.0.jar
hive-common-0.10.0-cdh4.5.0.jar
hive-contrib-0.10.0-cdh4.5.0.jar
hive-exec-0.10.0-cdh4.5.0.jar
hive-jdbc-0.10.0-cdh4.5.0.jar
hive-metastore-0.10.0-cdh4.5.0.jar
hive-serde-0.10.0-cdh4.5.0.jar
hive-service-0.10.0-cdh4.5.0.jar
hive-shims-0.10.0-cdh4.5.0.jar
hsqldb-1.8.0.7.jar
httpclient-4.2.5.jar
httpcore-4.2.5.jar
jackson-core-asl-1.8.8.jar
jackson-jaxrs-1.8.8.jar
jackson-mapper-asl-1.8.8.jar
jackson-xc-1.8.8.jar
jaxb-api-2.2.2.jar
jaxb-impl-2.2.3-1.jar
jdo2-api-2.3-ec.jar
jdom-1.1.jar
jersey-core-1.8.jar
jersey-json-1.8.jar
jersey-server-1.8.jar
jettison-1.1.jar
jetty-util-6.1.26.cloudera.2.jar
jline-0.9.94.jar
jsch-0.1.42.jar
json-20090211.jar
json-simple-1.1.jar
jsr305-1.3.9.jar
jta-1.1.jar
jung-algorithms-2.0.1.jar
jung-api-2.0.1.jar
jung-graph-impl-2.0.1.jar
jung-visualization-2.0.1.jar
junit-4.10.jar
libfb303-0.9.0.jar
libthrift-0.9.0.jar
log4j-1.2.16.jar
mockito-all-1.8.5.jar
netty-3.2.4.Final.jar
netty-3.4.0.Final.jar
oozie-client-3.3.2-cdh4.5.0.jar
oozie-core-3.3.2-cdh4.5.0.jar
oozie-hadoop-2.0.0-cdh4.5.0.oozie-3.3.2-cdh4.5.0.jar
oozie-hadoop-2.0.0-mr1-cdh4.5.0.oozie-3.3.2-cdh4.5.0.jar
oozie-hadoop-distcp-2.0.0-cdh4.5.0.oozie-3.3.2-cdh4.5.0.jar
oozie-hadoop-distcp-2.0.0-mr1-cdh4.5.0.oozie-3.3.2-cdh4.5.0.jar
oozie-hadoop-test-2.0.0-cdh4.5.0.oozie-3.3.2-cdh4.5.0.jar
oozie-hadoop-test-2.0.0-mr1-cdh4.5.0.oozie-3.3.2-cdh4.5.0.jar
oozie-tools-3.3.2-cdh4.5.0.jar
openjpa-jdbc-2.2.2.jar
openjpa-kernel-2.2.2.jar
openjpa-lib-2.2.2.jar
openjpa-persistence-2.2.2.jar
openjpa-persistence-jdbc-2.2.2.jar
paranamer-2.3.jar
postgresql-9.0-801.jdbc4.jar
protobuf-java-2.4.0a.jar
serp-1.14.1.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar
slf4j-simple-1.6.1.jar
snappy-java-1.0.4.1.jar
sqlline-1_0_2.jar
stax-api-1.0.1.jar
stringtemplate-3.2.1.jar
xercesImpl-2.10.0.jar
xml-apis-1.4.01.jar
xmlenc-0.52.jar
xz-1.0.jar
zookeeper-3.4.5-cdh4.5.0.jar
</code></pre>
<p>Thanks a lot.</p>
| 1 | 6,963 |
LDAP authentication using passport-ldapauth on Node.js
|
<p>I've been struggling with passport-ldapauth for a couple of days, and I have no more ideas left what am I doing wrong.</p>
<p>Briefly, I have a project that uses two passport strategies: local and LDAP. Local strategy works perfectly for me, but LDAP is the problematic one.</p>
<p>I have a read-only user for AD (let's call it "ldap-read-only-admin"), and I am able to connect with this user via external LDAP client and view the relevant OU. I have also triple-checked the SearchBase, and it seems to be correct.</p>
<p>However, when passing the same configuration to passport-ldapauth, it seems that it cannot bind user credentials (I guess). Any ideas on how to debug this will be much appreciated.</p>
<p>This is the app.js:</p>
<pre><code> var express = require("express");
var app = express();
var path = require("path");
var session = require("express-session");
var mongoose = require("mongoose");
var passport = require("passport");
var flash = require("connect-flash");
var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var morgan = require("morgan");
var configDB = require('./config/database.js');
require('./config/passport.js')(passport); // pass passport for configuration
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
//connect to the Database
var promise = mongoose.connect(configDB.url, {
useMongoClient: true,
});
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
//app.use(bodyParser()); // get information from html forms
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json({
extended: true
}));
// configuring passport
app.use(session({ secret: 'secret', resave: true, saveUninitialized: true })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
require('./modules/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
//make Web server listen on a specific port
app.listen(3000);
logger.info("Listening on port 3000");
</code></pre>
<p>This is routes.js (the relevant part):</p>
<pre><code>module.exports = function(app, passport) {
app.post('/', function(req, res, next) {
passport.authenticate('ldap-login', {session: true}, function(err, user, info) {
console.log("user: " + user);
console.log("info: " + JSON.stringify(info));
if (err) {
return next(err); // will generate a 500 error
}
// Generate a JSON response reflecting authentication status
if (! user) {
return res.send({ success : false, message : 'authentication failed' });
}
return res.send({ success : true, message : 'authentication succeeded' });
})(req, res, next);
});
}
</code></pre>
<p>And this is passport.js:</p>
<pre><code> var LocalStrategy = require('passport-local').Strategy;
var LdapStrategy = require('passport-ldapauth').Strategy;
// load the user model
var User = require('../modules/user.js');
// expose this function to our app using module.exports
module.exports = function(passport) {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// =========================================================================
// LOCAL LOGIN =============================================================
// =========================================================================
passport.use('local-login', new LocalStrategy({
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) { // callback with email and password from our form
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ username : username }, function(err, user) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if no user is found, return the message
if (!user)
return done(null, false, req.flash('loginMessage', 'The username "' + username + '" is not found.')); // req.flash is the way to set flashdata using connect-flash
// if the user is found but the password is wrong
if (!user.validPassword(password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
return done(null, user);
});
}));
// =========================================================================
// LDAP Login ==============================================================
// =========================================================================
var opts = {
server: {
url: 'ldap://<ldap server address>:389',
bindDn: 'cn=ldap-read-only-admin',
bindCredentials: 'password',
searchBase: 'OU=XX1, OU=XX2, DC=domain, DC=local',
searchFilter: '(uid={{username}})',
// passReqToCallback : true
}
};
passport.use('ldap-login', new LdapStrategy(opts, function(req, user, done) {
console.log("Passport LDAP authentication.");
done(null, user);
}
));
};
</code></pre>
| 1 | 2,381 |
Node Js Steam Trade Offers Bot Items
|
<p>This bot accept all trades but it need to accept only trade offers which contains [type: 'Consumer Grade SMG',] item in itemsToReceive. I was trying to do something like: If itemsToReceive contains Consumer Grade SMG then accpet offer else cancel offer but i failed. Im newby and i dont have any idea how to do that.
Sorry for my bad english.</p>
<p>My output console:</p>
<pre><code>New offer #644673626 from [U:1:205839253]
[ { appid: 730,
contextid: { low: 2, high: 0, unsigned: true },
assetid: '3142560367',
classid: '310777708',
instanceid: '302028390',
amount: 1,
missing: true,
id: '3142560367',
icon_url: '-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHL
bXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpopuP1FBRw7ODYYzxb08-3moS0m_7zO6-fxzNQ65J03L2Vo
9-sigzj_kU6Mmr6LIKVdwNvZVHTqVTqxri8jZS4tYOJlyVoTeLjug',
icon_url_large: '-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4o
FJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpopuP1FBRw7ODYYzxb08-3moS0m_7zO6_ummpD78A
_27HA9tvw3gDg_UBlMWH0IYDDIwU3aVzQ_1Tvxefs1pPou8uawXBnsz5iuyjoOPjz8g',
icon_drag_url: '',
name: 'P90 | Sand Spray',
market_hash_name: 'P90 | Sand Spray (Minimal Wear)',
market_name: 'P90 | Sand Spray (Minimal Wear)',
name_color: 'D2D2D2',
background_color: '',
type: 'Consumer Grade SMG',
tradable: true,
marketable: true,
commodity: false,
market_tradable_restriction: 7,
fraudwarnings: '',
descriptions:
{ '0': [Object],
'1': [Object],
'2': [Object],
'3': [Object],
'4': [Object],
'5': [Object] },
owner_descriptions: '',
actions: { '0': [Object] },
market_actions: { '0': [Object] },
tags:
{ '0': [Object],
'1': [Object],
'2': [Object],
'3': [Object],
'4': [Object],
'5': [Object] } } ]
Offer accepted
Offer #644673626 changed: Active -Accepted
Received: P90 | Sand Spray
</code></pre>
<p>And bot code:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/**
* STOREHOUSE - node-steam
*
* Uses node-steam-user for notifications and accepts all incoming trade offers
*/
var SteamUser = require('steam-user');
var TradeOfferManager = require('../lib/index.js'); // use require('steam-tradeoffer-manager') in production
var fs = require('fs');
var client = new SteamUser();
var manager = new TradeOfferManager({
"steam": client, // Polling every 30 seconds is fine since we get notifications from Steam
"domain": "example.com", // Our domain is example.com
"language": "en" // We want English item descriptions
});
// Steam logon options
var logOnOptions = {
"accountName": "xxxxx",
"password": "xxxxx"
};
if(fs.existsSync('polldata.json')) {
manager.pollData = JSON.parse(fs.readFileSync('polldata.json'));
}
client.logOn(logOnOptions);
client.on('loggedOn', function() {
console.log("Logged into Steam");
});
client.on('webSession', function(sessionID, cookies) {
manager.setCookies(cookies, function(err) {
if(err) {
console.log(err);
process.exit(1); // Fatal error since we couldn't get our API key
return;
}
console.log("Got API key: " + manager.apiKey);
});
});
manager.on('newOffer', function(offer) {
console.log("New offer #" + offer.id + " from " + offer.partner.getSteam3RenderedID());
console.log(offer.itemsToReceive);
offer.accept(function(err) {
if(err) {
console.log("Unable to accept offer: " + err.message);
} else {
console.log("Offer accepted");
}
});
});
manager.on('receivedOfferChanged', function(offer, oldState) {
console.log("Offer #" + offer.id + " changed: " + TradeOfferManager.getStateName(oldState) + " -> " + TradeOfferManager.getStateName(offer.state));
if(offer.state == TradeOfferManager.ETradeOfferState.Accepted) {
offer.getReceivedItems(function(err, items) {
if(err) {
console.log("Couldn't get received items: " + err);
} else {
var names = items.map(function(item) {
return item.name;
});
console.log("Received: " + names.join(', '));
}
});
}
});
manager.on('pollData', function(pollData) {
fs.writeFile('polldata.json', JSON.stringify(pollData));
});</code></pre>
</div>
</div>
</p>
| 1 | 1,949 |
Make the PHP MySql Search Engine and Pagination work
|
<p>I don't know how to make the search through another table. how should i do that?
the table name is comments and i want to search for all the post stored in the column name kom</p>
<p>Another thing is that i cant get the pagination start working...
I started the pagination within an else statment because i only need it when i get more than 1 result.
I can get the page links showing and limit the search posting showing but when i click on one off the links i cant get to the next page
Heres the code</p>
<pre><code><?php
$search = $_POST["search"];
$field = $_POST["field"];
if($_POST["submit"] && $search)
{
echo "<div id='result'>";
echo "<h2>Resultat</h2>";
$search = strtoupper($search);
$search = strip_tags($search);
$search = trim($search);
$query = "SELECT * FROM blogTable WHERE title LIKE '%$search%'
UNION
SELECT * FROM blogTable WHERE post LIKE '%$search%'";
$result = mysql_query($query, $conn) or die(mysql_error());
$matches = mysql_num_rows($result);
if($matches == 0)
//code if serch didnt result any results
else if($matches == 1)
//code if the matches only 1
else
{
$per_page = 4;
$pages = ceil($matches / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page']: 1;
$start = ($page - 1) * $per_page;
$query2 = "SELECT * FROM blogTable WHERE title LIKE '%$search%'
UNION
SELECT * FROM blogTable WHERE post LIKE '%$search%' LIMIT $start, $per_page";
$result2 = mysql_query($query2, $conn) or die(mysql_error());
echo "<font size='-1'>Sökningen $search gav $matches resultat</font><br/>";
while ($r2 = mysql_fetch_array($result2))
{
$id = $r["id"];
$title = $r["title"];
$post = $r["post"];
$time = $r["time"];
echo "<br/><strong><a href='comment.php?id=$id'>$title</a></strong><br/>";
echo "<font size='-1'>".substr($post, 0, 60)."</font><br/>";
echo "<font size='-1'>".substr($post, 60, 70)."</font><br/>";
echo "<font size='-3'>$time</font><br/>";
}
//theese are showin but cannot click of any of them
if($pages >= 1 && $page <= $pages)
{
for($nr = 1; $nr <= $pages; $nr++)
{
if($nr == $page)
echo "<a href='?page=".$nr."' style='font-size:20px;'>$nr</a>";
else
echo "<a href='?page=".$nr."' style='font-size:15px;'>$nr</a> ";
}
}
}
}
?>
</code></pre>
| 1 | 1,480 |
Spring LDAP Context.REFERRAL to follow
|
<p>How do I set the LDAP Context.REFERRAL to follow in a Spring Security configuration? This is related to a problem I already reported and for which I found an unsatisfactory solution before discovering the real solution I am seeking for involve setting this environment attribute in the LDAP context to follow the referral for the ActiveDirectoryLdapAuthenticationProvider.</p>
<p>Here is the reference to my original question: <a href="https://stackoverflow.com/questions/29658844/spring-security-4-0-0-activedirectoryldapauthenticationprovider-badcredentia">Spring Security 4.0.0 + ActiveDirectoryLdapAuthenticationProvider + BadCredentialsException PartialResultException</a></p>
<p><strong>Addendum:</strong> It seems no one is having such an environment here. Despite the silence on this problem, I post here my configuration hoping someone will be able to help me with this. I just don't know what I should do to solve this problem.</p>
<p>Here are the error messages in my log:</p>
<pre><code>2015-06-15 10:32:19,810 DEBUG (o.s.s.w.FilterChainProxy$VirtualFilterChain.doFilter) [http-8443-1] /identite.proc at position 7 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2015-06-15 10:32:19,810 DEBUG (o.s.s.w.u.m.AntPathRequestMatcher.matches) [http-8443-1] Checking match of request : '/identite.proc'; against '/identite.proc'
2015-06-15 10:32:19,810 DEBUG (o.s.s.w.a.AbstractAuthenticationProcessingFilter.doFilter) [http-8443-1] Request is to process authentication
2015-06-15 10:32:19,811 DEBUG (o.s.s.a.ProviderManager.authenticate) [http-8443-1] Authentication attempt using org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider
2015-06-15 10:32:19,811 DEBUG (o.s.s.l.a.AbstractLdapAuthenticationProvider.authenticate) [http-8443-1] Processing authentication request for user: myusername
2015-06-15 10:32:19,841 DEBUG (o.s.s.l.SpringSecurityLdapTemplate.searchForSingleEntryInternal) [http-8443-1] Searching for entry under DN '', base = 'dc=dept,dc=company,dc=com', filter = '(&(userPrincipalName={0})(objectClass=user)(objectCategory=inetOrgPerson))'
2015-06-15 10:32:19,842 DEBUG (o.s.s.w.a.AbstractAuthenticationProcessingFilter.unsuccessfulAuthentication) [http-8443-1] Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials
2015-06-15 10:32:19,842 DEBUG (o.s.s.w.a.AbstractAuthenticationProcessingFilter.unsuccessfulAuthentication) [http-8443-1] Updated SecurityContextHolder to contain null Authentication
2015-06-15 10:32:19,842 DEBUG (o.s.s.w.a.AbstractAuthenticationProcessingFilter.unsuccessfulAuthentication) [http-8443-1] Delegating to authentication failure handler org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler@a5d7f2
</code></pre>
<p>And here is the configuration:</p>
<pre><code><b:bean id="monFournisseurAD" class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
<b:constructor-arg value="dept.company.com" />
<b:constructor-arg value="ldap://dept.company.com:3268/" />
<b:constructor-arg value="dc=dept,dc=company,dc=com" />
<b:property name="searchFilter" value="(&amp;(userPrincipalName={0})(objectClass=user)(objectCategory=inetOrgPerson))" />
<b:property name="userDetailsContextMapper">
<b:bean class="org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper" />
</b:property>
<b:property name="authoritiesMapper" ref="grantedAuthoritiesMapper" />
<b:property name="convertSubErrorCodesToExceptions" value="true" />
</b:bean>
<b:bean id="contextSource" class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<b:constructor-arg value="ldap://dept.company.com:3268/dc=dept,dc=company,dc=com" />
<b:property name="baseEnvironmentProperties">
<b:map>
<b:entry key="java.naming.referral" value="follow" />
</b:map>
</b:property>
</b:bean>
<b:bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
<b:constructor-arg ref="contextSource" />
</b:bean>
<b:bean id="securityContextPersistenceFilter" class="org.springframework.security.web.context.SecurityContextPersistenceFilter" />
<b:bean id="myDeconnexionHandler" class="com.company.dept.web.my.DeconnexionHandler" />
</code></pre>
<p>The two beans with ids contextSource and ldapTemplate seems not to change anything. I was trying to get the referral follow behavior. It seems not the right way to configure it. Also, here the port in the ldap URL is set to 3268 because it is the general catalog and someone in another description elsewhere suggested to use it. But, the results are exactly the same with port 389.</p>
<p>If I change the first constructor argument in the bean monFournisseurAD to set it to a single userPrincipalName domain, it will work for all users into that domain. While I can actually authenticate anyone from the command line using ldapsearch command using dept.company.com instead of the userPrincipalName domain associated directly to the user. In fact, if I enter a wrong password, I will get the specific wrong password message. This seems to prove the user is actually authenticated by AD/LDAP, however Spring fails later to fetch the attributes for that user.</p>
<p>How can I solve this problem?</p>
| 1 | 1,794 |
I cannot send a mail in mule
|
<p>I get that error message when I try to execute my muleproject </p>
<blockquote>
<p>"The endpoint is malformed an cannot be parsed" and this is the endpoint </p>
</blockquote>
<p>Here's the code:</p>
<pre><code><smtp:outbound-endpoint host="smtp.gmail.com" user="mymail@gmail.com" password="mypass"
to="destiny@gmail.com" from="my@gmail.com" responseTimeout="10000"
doc:name="SMTP" port="587" subject="the subject"/>
</code></pre>
<p>where is the mistake??</p>
<p>I have removed the "@gmail.com" from user and the project now is deployed but it rises this exception</p>
<pre><code>Root Exception stack trace:
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. cf12sm8298386wjb.10 - gsmtp
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1829)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1368)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:886)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
</code></pre>
<p>Here is the full stacktrace</p>
<pre><code> INFO 2015-03-26 22:26:00,479 [[domotica2].connector.smtp.mule.default.dispatcher.01] org.mule.transport.service.DefaultTransportServiceDescriptor: Loading default outbound transformer: org.mule.transport.email.transformers.ObjectToMimeMessage
INFO 2015-03-26 22:26:00,499 [[domotica2].connector.smtp.mule.default.dispatcher.01] org.mule.lifecycle.AbstractLifecycleManager: Initialising: 'connector.smtp.mule.default.dispatcher.2081412619'. Object is: SmtpMessageDispatcher
INFO 2015-03-26 22:26:00,912 [[domotica2].connector.smtp.mule.default.dispatcher.01] org.mule.lifecycle.AbstractLifecycleManager: Starting: 'connector.smtp.mule.default.dispatcher.2081412619'. Object is: SmtpMessageDispatcher
ERROR 2015-03-26 22:26:01,100 [[domotica2].connector.smtp.mule.default.dispatcher.01] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message : Failed to route event via endpoint: DefaultOutboundEndpoint{endpointUri=smtp://mymail:<password>@smtp.gmail.com, connector=SmtpConnector
{
name=connector.smtp.mule.default
lifecycle=start
this=77c233af
numberOfConcurrentTransactedReceivers=4
createMultipleTransactedReceivers=true
connected=true
supportedProtocols=[smtp]
serviceOverrides=<none>
}
, name='endpoint.smtp.mymail.gmail.com.587', mep=ONE_WAY, properties={fromAddress=mymail@gmail.com, toAddresses=destiny@gmail.com, subject=SD}, transactionConfig=Transaction{factory=null, action=INDIFFERENT, timeout=0}, deleteUnacceptedMessages=false, initialState=started, responseTimeout=10000, endpointEncoding=UTF-8, disableTransportTransformer=false}. Message payload is of type: MimeMessage
Code : MULE_ERROR-42999
--------------------------------------------------------------------------------
Exception stack is:
1. 530 5.7.0 Must issue a STARTTLS command first. md2sm586901wic.19 - gsmtp
(com.sun.mail.smtp.SMTPSendFailedException)
com.sun.mail.smtp.SMTPTransport:1829 (null)
2. Failed to route event via endpoint: DefaultOutboundEndpoint{endpointUri=smtp://mymail:<password>@smtp.gmail.com, connector=SmtpConnector
{
name=connector.smtp.mule.default
lifecycle=start
this=77c233af
numberOfConcurrentTransactedReceivers=4
createMultipleTransactedReceivers=true
connected=true
supportedProtocols=[smtp]
serviceOverrides=<none>
}
, name='endpoint.smtp.mymail.gmail.com.587', mep=ONE_WAY, properties={fromAddress=mymail@gmail.com, toAddresses=destiny@gmail.com, subject=SD}, transactionConfig=Transaction{factory=null, action=INDIFFERENT, timeout=0}, deleteUnacceptedMessages=false, initialState=started, responseTimeout=10000, endpointEncoding=UTF-8, disableTransportTransformer=false}. Message payload is of type: MimeMessage (org.mule.api.transport.DispatchException)
org.mule.transport.AbstractMessageDispatcher:117 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/transport/DispatchException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. md2sm586901wic.19 - gsmtp
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1829)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1368)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:886)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************
</code></pre>
| 1 | 1,608 |
Need jquery code to disable Drop downs and people pickers when a option in dropdown is selected in sharepoint
|
<p>I am working with moss 2007. I created a drop down column in which has 3 options. If option1 and option 2 are selected the Dropdowns and People pickers should be disabled and if option 3 selected the Dropdowns and People picker columns should be enabled. I provided the page source code, could someone help me out with this with some coding since i am newbie to jquery.</p>
<pre><code><TR>
<TD nowrap="true" valign="top" width="190px" class="ms-formlabel"><H3 class="ms-standardheader">
<nobr>Type of Notification</nobr>
</H3></TD>
<TD valign="top" class="ms-formbody" width="400px">
<!-- FieldName="Type of Notification"
FieldInternalName="Type_x0020_of_x0020_Notification"
FieldType="SPFieldChoice"
-->
<span dir="none"><select name="ctl00$m$g_785c653c_cfa1_4aa5_8060_a84901274cc3$ctl00$ctl04$ctl07$ctl00$ctl00$ctl04$ctl00$DropDownChoice" id="ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl07_ctl00_ctl00_ctl04_ctl00_DropDownChoice" title="Type of Notification" class="ms-RadioText">
<option selected="selected" value="Select One">Select One</option>
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
<option value="Option3">Option3</option>
</select><br></span></TD></TR>
<TR>
<TD nowrap="true" valign="top" width="190px" class="ms-formlabel"><H3 class="ms-standardheader">
<nobr>Functional Team</nobr>
</H3></TD>
<TD valign="top" class="ms-formbody" width="400px">
<!-- FieldName="Functional Team"
FieldInternalName="Mytest"
FieldType="SPFieldCascadingDropDownListFieldWithFilter"
-->
<span dir="none">
<select name="ctl00$m$g_785c653c_cfa1_4aa5_8060_a84901274cc3$ctl00$ctl04$ctl16$ctl00$ctl00$ctl04$ctl00$ctl00$Functional Team" onchange="javascript:setTimeout('WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$m$g_785c653c_cfa1_4aa5_8060_a84901274cc3$ctl00$ctl04$ctl16$ctl00$ctl00$ctl04$ctl00$ctl00$Functional Team&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, true))', 0)" id="ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl16_ctl00_ctl00_ctl04_ctl00_ctl00_Functional Team" title="Functional Team Parent" class="ms-input">
<option selected="selected" value="">Please select an Item</option>
<option value="Test">Test</option>
<option value="Other">Other</option>
</select></span></TD></TR>
<TR>
<TD nowrap="true" valign="top" width="190px" class="ms-formlabel"><H3 class="ms-standardheader">
<nobr>Therapeutic Area</nobr>
</H3></TD>
<TD valign="top" class="ms-formbody" width="400px">
<!-- FieldName="Therapeutic Area"
FieldInternalName="Therapeutic_x0020_Area"
FieldType="SPFieldChoice"
-->
<span dir="none"><select name="ctl00$m$g_785c653c_cfa1_4aa5_8060_a84901274cc3$ctl00$ctl04$ctl17$ctl00$ctl00$ctl04$ctl00$DropDownChoice" id="ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl17_ctl00_ctl00_ctl04_ctl00_DropDownChoice" title="Therapeutic Area" class="ms-RadioText">
<option selected="selected" value="Select One">Select One</option>
<option value="Anti-Infective">Anti-Infective</option>
<option value="Other">Other</option>
</select><br></span></TD> </TR>
<TR>
<TD nowrap="true" valign="top" width="190px" class="ms-formlabel"><H3 class="ms-standardheader">
<nobr>Admin Name</nobr>
</H3></TD>
<TD valign="top" class="ms-formbody" width="400px">
<!-- FieldName="Admin Name"
FieldInternalName="Admin_x0020_Name"
FieldType="SPFieldUser"
-->
<span dir="none">
<input name="ctl00$m$g_785c653c_cfa1_4aa5_8060_a84901274cc3$ctl00$ctl04$ctl20$ctl00$ctl00$ctl04$ctl00$ctl00$HiddenUserFieldValue" type="hidden" id="ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_HiddenUserFieldValue" />
<span id="ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField" class="ms-usereditor" NoMatchesText="&lt;No Matching Names>" MoreItemsText="More Names..." RemoveText="Remove" value="" allowEmpty="1" ShowEntityDisplayTextInTextBox="0" EEAfterCallbackClientScript=""><input name="ctl00$m$g_785c653c_cfa1_4aa5_8060_a84901274cc3$ctl00$ctl04$ctl20$ctl00$ctl00$ctl04$ctl00$ctl00$UserField$hiddenSpanData" type="hidden" id="ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_hiddenSpanData" /><input name="ctl00$m$g_785c653c_cfa1_4aa5_8060_a84901274cc3$ctl00$ctl04$ctl20$ctl00$ctl00$ctl04$ctl00$ctl00$UserField$OriginalEntities" type="hidden" id="ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_OriginalEntities" value="&lt;Entities />" /><input name="ctl00$m$g_785c653c_cfa1_4aa5_8060_a84901274cc3$ctl00$ctl04$ctl20$ctl00$ctl00$ctl04$ctl00$ctl00$UserField$HiddenEntityKey" type="hidden" id="ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_HiddenEntityKey" /><input name="ctl00$m$g_785c653c_cfa1_4aa5_8060_a84901274cc3$ctl00$ctl04$ctl20$ctl00$ctl00$ctl04$ctl00$ctl00$UserField$HiddenEntityDisplayText" type="hidden" id="ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_HiddenEntityDisplayText" /><table id="ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_OuterTable" class="ms-usereditor" cellspacing="0" cellpadding="0" border="0" style="border-collapse:collapse;">
<tr valign="bottom">
<td valign="top" style="width:90%;"><table cellpadding="0" cellspacing="0" border="0" style="width:100%;table-layout:fixed;">
<tr>
<td><div id="ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_upLevelDiv" TabIndex="0" onFocusIn="this._fFocus=1;saveOldEntities('ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_upLevelDiv')" onClick="onClickRw(true, true);" onChange="updateControlValue('ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField')" onFocusOut="this._fFocus=0;" onPaste="dopaste();" AutoPostBack="0" class="ms-inputuserfield" onDragStart="canEvt(event);" onKeyup="return onKeyUpRw('ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField');" onCopy="docopy();" onBlur="updateControlValue('ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField')" Title="People Picker" onKeyDown="return onKeyDownRw(this, 'ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField', 3, true, event);" contentEditable="true" style="width: 100%; word-wrap: break-work;overflow-x: hidden; background-color: window; color: windowtext;" name="upLevelDiv"></div><textarea name="ctl00$m$g_785c653c_cfa1_4aa5_8060_a84901274cc3$ctl00$ctl04$ctl20$ctl00$ctl00$ctl04$ctl00$ctl00$UserField$downlevelTextBox" rows="1" cols="20" id="ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_downlevelTextBox" class="ms-input" onKeyDown="return onKeyDownRw(this, 'ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField', 3, true, event);" onKeyUp="onKeyUpRw('ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField');" Title="People Picker" AutoPostBack="0" style="width:100%;display: none;position: absolute; "></textarea></td>
</tr>
</table></td><td align="right" valign="top" nowrap="true" style="padding-left:5px;"><a id="ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_checkNames" title="Check Names" onclick="var arg=getUplevel('ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField');var ctx='ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField';EntityEditorSetWaitCursor(ctx);WebForm_DoCallback('ctl00$m$g_785c653c_cfa1_4aa5_8060_a84901274cc3$ctl00$ctl04$ctl20$ctl00$ctl00$ctl04$ctl00$ctl00$UserField',arg,EntityEditorHandleCheckNameResult,ctx,EntityEditorHandleCheckNameError,true);return false;" href="javascript:"><img title="Check Names" src="/_layouts/images/checknames.gif" alt="Check Names" style="border-width:0px;" /></a>&nbsp;<a id="ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_browse" accesskey="B" title="Browse" onclick="__Dialog__ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField(); return false;" href="javascript:"><img title="Browse" src="/_layouts/images/addressbook.gif" alt="Browse" style="border-width:0px;" /></a></td>
</tr><tr>
<td colspan="3"><span id="ctl00_m_g_785c653c_cfa1_4aa5_8060_a84901274cc3_ctl00_ctl04_ctl20_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_errorLabel" class="ms-error"></span></td>
</tr>
</table></span>
</span>
</TD>
</TR>
</code></pre>
| 1 | 4,946 |
Unable to generate call to cell phone using asterisk
|
<p>I'm currently working on a project 'email to voice call'. Using python i'v extracted the email & converted it into speech and saved in a WAV file. Now using asterisk (I'v installed Asterisk 10.2.1 on my ubuntu 10.10 os) i want to generate call to the cell phone (say 919833000000 india's no.) of the user through my system. </p>
<p>I have written a python code to connect to asterisk manager interface. Also i have configured the sip.conf and extensions.conf files as well as manager.conf. I have registered with voip provider <strong>voiceall.com</strong> and have a username password of it. </p>
<p>Now when i'm executing the python code, the code is getting executed without any error but nothing is happening. No call is getting generated. Can anyone help me out with this.
The python code is as below:</p>
<pre><code>import sys, os, socket, random
# Asterisk Manager connection details
HOST = '127.0.0.1'
PORT = 5038
# Asterisk Manager username and password
USER = 'MYUSERNAME'
SECRET = 'MYPASSWORD'
# Set the name of the SIP trunk to use for outbound calls
TRUNK = 'voiceall'
OUTBOUND = '919833000000'
# Send the call details to the Asteirsk Manager Interface
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
sleep(3)
s.send('Action: login\r\n')
s.send('Username: ' + USER + '\r\n')
s.send('Secret: ' + SECRET + '\r\n\r\n')
sleep(3)
s.send('Action: status\r\n')
data = s.recv(1024)
print data + '\n'
s.send('Events: off\r\n\r\n')
sleep(3)
s.send('Action: originate\r\n')
s.send('Channel: Sip/' + TRUNK + '/' + OUTBOUND + '\r\n')
s.send('WaitTime: 30\r\n')
s.send('CallerId: VOICEALL_USERNAME\r\n')
s.send('Application: playback\r\n')
s.send('Data: /home/Documents/newdemo1' + '\r\n') #newdemo1 is the wave file
s.send('Context: testing\r\n')
s.send('Async: true\r\n')
s.send('Priority: 1\r\n\r\n')
sleep(10)
s.send('Action: Logoff\r\n\r\n')
s.close()
</code></pre>
<p>My sip.conf file is as below:</p>
<pre><code>[general]
register => VOICEALL_USERNAME:VOICEALL_PASSWORD@sip.voiceall.net:5038
[voiceall]
canreinvite=no
context=mycontext
host=sip.voiceall.net
secret=VOICEALL_PASSWORD ;your password
type=peer
username=VOICEALL_USERNAME ;your account
disallow=all
allow=ulaw
fromuser=VOICEALL_USERNAME ;your account
trustrpid=yes
sendrpid=yes
insecure=invite
nat=yes
</code></pre>
<p>The extensions.conf file is as below:</p>
<pre><code>[mycontext]
include => voiceall-outbound
[voiceall-outbound]
exten => _1NXXNXXXXXX,1,Dial(SIP/${EXTEN}@voiceall)
exten => _1NXXNXXXXXX,n,Playback(/home/Documents/demonew1)
exten => _1NXXNXXXXXX,n,Hangup()
exten => _NXXNXXXXXX,1,Dial(SIP/1${EXTEN}@voiceall)
exten => _NXXNXXXXXX,n,Playback(/home/Documents/demonew1)
exten => _NXXNXXXXXX,n,Hangup()
exten => _011.,1,Dial(SIP/${EXTEN}@voiceall)
exten => _011.,n,Playback(/home/Documents/demonew1)
exten => _011.,n,Hangup()
</code></pre>
<p>Please help me out, as i am new to asterisk.
Any help will be appreciated. Thanks in advance.</p>
| 1 | 1,185 |
WorkManager stops scheduling periodic Worker after the app closes
|
<p>maybe this is yet another question about WorkManager, but I really can't find a solution...</p>
<p>I'm trying, as the title suggests, to run a periodic work every 15 minutes. Actually in the worker I'm polling some data every minute. After every poll, every almost 1 second I check if the worker is being stopped and if so return, otherwise keep waiting until 1 minute is reached and poll data again.</p>
<p>According to the documentation this should work and indeed it is, until I kill the app from the recent app screen.</p>
<p>Here is the code:</p>
<pre><code>package com.qsea.app.cordova;
import android.content.Context;
import android.os.SystemClock;
import android.util.Log;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
public class ServerListenerWorker extends Worker {
public static final String TAG = "ServerListenerWorker";
public ServerListenerWorker(
Context appContext,
WorkerParameters workerParams
) {
super(appContext, workerParams);
}
@Override
public Result doWork() {
Log.d(TAG, "Doing work");
final long startTime = SystemClock.elapsedRealtime();
final int maxDelta = 840000; // 14 minutes
while (true) {
// I did this to stop this worker until 15 minutes
// and then let the next worker run
if (SystemClock.elapsedRealtime() - startTime >= maxDelta) {
break;
}
// Here I'm polling data, if the polling results in a failure
// I return Result.retry()
// It avoid waiting if it remains only 1 minute until the max time
if (SystemClock.elapsedRealtime() - startTime >= (maxDelta - 60000)) {
break;
}
for (int i = 0; i < 60; i++) {
SystemClock.sleep(950);
// Here it checks if it is stopped
if (isStopped()) {
Log.d(TAG, "Detected stop"); // this is actually never reached
break;
}
}
}
return Result.success();
}
}
</code></pre>
<p>And I do as following to start the work</p>
<pre><code>Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(ServerListenerWorker.class, 15, TimeUnit.MINUTES)
.addTag(serverListenerWorkerUID)
.setConstraints(constraints)
.build();
WorkManager.getInstance(cordova.getActivity()).enqueueUniquePeriodicWork(serverListenerWorkerUID, ExistingPeriodicWorkPolicy.KEEP, periodicWorkRequest);
</code></pre>
<p>I check the correct working of the worker by viewing the log of my server (If I receive the request it is working fine) and it seems to work ok until I close the app. Then it stops running the actual worker and never run a worker again until I reopen the app, where the work seems to be enqueued and resumes right after the app opening.</p>
<p>Am I doing something wrong in the initialization?
I have also <code><service android:name=".ServerListenerWorker" android:permission="android.permission.BIND_JOB_SERVICE" /></code> in my AndroidManifest.xml</p>
<p>Is this expected behavior?</p>
<p>I read that chinese ROM have additional restriction to background services and I have a HUAWEI, which seems to be the worst in this. So could it be the device? And if so, how do Facebook, WhatsApp, Instagram and others manage this to work even in these devices?</p>
| 1 | 1,266 |
Linq group by parent property order by child
|
<p>Basicly what i am trying to do is getting the parent grouped by Parent.type where their Child.type has status 'y' ordered by child.Date</p>
<p>As an example i created these classes:</p>
<pre><code>public class Collection
{
public IEnumerable<Parent> Parents { get; set; }
public int Id { get; set; }
}
public class Parent
{
public int Id { get; set; }
public Type type { get; set; }
public IEnumerable<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
public Status Status { get; set; }
public DateTime Date { get; set; }
}
public enum Type
{
a,
b
}
public enum Status
{
x,
y
}
</code></pre>
<p>What i want is a list of Parents of each type where the Child's Date is highest in value.</p>
<p>To get this example going i added some test data:</p>
<pre><code>Collection collection= new Collection
{
Id = 1,
Parents = new List<Parent>
{
new Parent
{
Id= 1,
type = Type.a,
Children = new List<Child>
{
new Child
{
Id = 1,
Status = Status.y,
Date = DateTime.Now.AddDays(-1)
},
new Child
{
Id = 2,
Status = Status.x,
Date = DateTime.Now.AddDays(-1)
}
}
},
new Parent
{
Id= 2,
type = Type.b,
Children = new List<Child>
{
new Child
{
Id = 3,
Status = Status.y,
Date = DateTime.Now.AddDays(-2)
},
new Child
{
Id = 4,
Status = Status.x,
Date = DateTime.Now.AddDays(-2)
}
}
},
new Parent
{
Id= 3,
type = Type.a,
Children = new List<Child>
{
new Child
{
Id = 5,
Status = Status.y,
Date = DateTime.Now.AddDays(-3)
}
}
},
new Parent
{
Id= 4,
type = Type.b,
Children = new List<Child>
{
new Child
{
Id = 6,
Status = Status.y,
Date = DateTime.Now.AddDays(-3)
},
new Child
{
Id = 7,
Status = Status.y,
Date = DateTime.Now.AddDays(-4)
},
new Child
{
Id = 8,
Status = Status.x,
Date = DateTime.Now.AddDays(-4)
}
}
},
}
};
</code></pre>
<p>The result of the select should be a List containing 2 Parents. One for each type ( a and b ). Both of these still containing all of their Child objects.</p>
<p>Is there any simple solution for this ?</p>
<p>I tried something like:</p>
<pre><code>List<Parent> test = collection.Parents
.GroupBy(m => m.type)
.Select(
m => m.OrderByDescending(
mm => mm.Children.Select(
r => r).OrderByDescending(
r => r.Date)).FirstOrDefault()).ToList();
</code></pre>
<p>But that didn't end well.</p>
<p>=====UPDATE=====</p>
<p>Thanks to the example of Enigmativity this issue is solved. I made a slight modification to the linq query as the original content i am using is provided by Entity Framework (6). This meant for me that the selected Parent object was not containing any Children, so i had to select into a new object type (As we can't instantiate a new object of the type provided by the Entity Framework model) . Also my Parents were in another IEnumerable so I had to use a SelectMany on the Parents as well.</p>
<p>This resulted in something like this: (This won't work with the test classes though)</p>
<pre><code>var result =
collection
.SelectMany(c => c.Parents)
.GroupBy(p => p.type)
.SelectMany(gps =>
gps
.SelectMany(
gp => gp.Children.Where(c => c.Status == Status.y),
(gp, c) => new { gp, c })
.OrderByDescending(gpc => gpc.c.Date)
.Take(1)
.Select(gpc => new ParentData {Id = gpc.gp.Id, Children= gpc.gp.Children}))
.ToList();
</code></pre>
| 1 | 3,334 |
Check if value in Firebase Realtime Database is equal to String
|
<p>When a user logs in on my application, I want to check if the userType is a "Customer" or a "Venue Owner". This decides which activity is run next. Currently, the application crashes when attempting to log in.</p>
<p>Here is my Firebase Realtime database structure:</p>
<p><img src="https://i.imgur.com/V5evylH.jpg" alt="two muppets" title="tooltip"></p>
<p>Here is the related code:</p>
<pre><code>public void loginUser(View v)
{
if(e1.getText().toString().equals("") && e2.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(),"Blank fields not allowed", Toast.LENGTH_SHORT).show();
}
else
{
auth.signInWithEmailAndPassword(e1.getText().toString(),e2.getText().toString())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
Toast.makeText(getApplicationContext(),"User logged in successfully",Toast.LENGTH_SHORT).show();
finish();
//Intent i = new Intent(getApplicationContext(),ProfileActivity.class);
//startActivity(i);
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
//String userType = dataSnapshot.getValue(String.class);
String userType = (String) dataSnapshot.child("userType").getValue();
if (userType.equals("Customer")) {
Intent i = new Intent(getApplicationContext(), UserMainPageActivity.class);
startActivity(i);
} else {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
startActivity(i);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
else
{
Toast.makeText(getApplicationContext(),"User could not be logged in",Toast.LENGTH_SHORT).show();
}
}
});
}
}
</code></pre>
<p>As requested, here is the crash log:</p>
<pre><code>01-31 13:35:14.348 5322 5322 E AndroidRuntime: FATAL EXCEPTION: main
01-31 13:35:14.348 5322 5322 E AndroidRuntime: Process:
com.example.myapplication, PID: 5322
01-31 13:35:14.348 5322 5322 E AndroidRuntime:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean
java.lang.String.equals(java.lang.Object)' on a null object reference
01-31 13:35:14.348 5322 5322 E AndroidRuntime: at
com.example.myapplication.LoginActivity$1$1.onDataChange(
LoginActivity.java:66 01-31 13:35:14.348 5322 5322 E AndroidRuntime:
at com.google.firebase.database.zzp.onDataChange(Unknown Source)
01-31 13:35:14.348 5322 5322 E AndroidRuntime: at
com.google.android.gms.internal.firebase_database.zzfc.zza(Unknown Source)
01-31 13:35:14.348 5322 5322 E AndroidRuntime: at
com.google.android.gms.internal.firebase_database.zzgx.zzdr(Unknown Source)
01-31 13:35:14.348 5322 5322 E AndroidRuntime: at
com.google.android.gms.internal.firebase_database.zzhd.run(Unknown Source)
01-31 13:35:14.348 5322 5322 E AndroidRuntime: at
android.os.Handler.handleCallback(Handler.java:746)
01-31 13:35:14.348 5322 5322 E AndroidRuntime: at
android.os.Handler.dispatchMessage(Handler.java:95)
01-31 13:35:14.348 5322 5322 E AndroidRuntime: at
android.os.Looper.loop(Looper.java:148)
01-31 13:35:14.348 5322 5322 E AndroidRuntime: at
android.app.ActivityThread.main(ActivityThread.java:5443)
01-31 13:35:14.348 5322 5322 E AndroidRuntime: at
java.lang.reflect.Method.invoke(Native Method)
01-31 13:35:14.348 5322 5322 E AndroidRuntime: at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:728)
01-31 13:35:14.348 5322 5322 E AndroidRuntime: at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
</code></pre>
<p>Here is the entire class:</p>
<pre><code> package com.example.myapplication;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class LoginActivity extends AppCompatActivity {
EditText e1,e2;
FirebaseAuth auth;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
e1 = (EditText)findViewById(R.id.editText);
e2 = (EditText)findViewById(R.id.editText2);
auth = FirebaseAuth.getInstance();
}
public void loginUser(View v)
{
if(e1.getText().toString().equals("") && e2.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(),"Blank fields not allowed", Toast.LENGTH_SHORT).show();
}
else
{
auth.signInWithEmailAndPassword(e1.getText().toString(),e2.getText().toString())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
Toast.makeText(getApplicationContext(),"User logged in successfully",Toast.LENGTH_SHORT).show();
finish();
//Intent i = new Intent(getApplicationContext(),ProfileActivity.class);
//startActivity(i);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child(uid);
uidRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child("userType").equals("Customer")) {
startActivity(new Intent(getApplicationContext(), UserMainPageActivity.class));
} else if (dataSnapshot.child("userType").equals("Venue Owner")) {
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
});
}
else
{
Toast.makeText(getApplicationContext(),"User could not be logged in",Toast.LENGTH_SHORT).show();
}
}
});
}
}
</code></pre>
<p>}</p>
| 1 | 4,140 |
Test servlet API with Mockito
|
<p>I have <code>AddBookController</code>:</p>
<pre><code>public class BookAddController extends HttpServlet {
@EJB(name = "BuyerServiceEJB")
private BuyerServiceInterface buyerService;
@EJB(name = "AuthorServiceEJB")
private AuthorServiceInterface authorService;
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Book newBook = new Book();
newBook.setName(request.getParameter("name"));
newBook.setAuthor(authorService.findAuthorById(Long.parseLong(request.getParameter("author_id"))));
newBook.setBought(Boolean.parseBoolean(request.getParameter("sold")));
newBook.setGenre(request.getParameter("genre"));
newBook.setPrice(Integer.parseInt(request.getParameter("price")));
buyerService.addNewBook(newBook);
doGet(request, response);
}
</code></pre>
<p>And I have testing class:</p>
<pre><code>public class BookAddControllerTest {
final static Logger logger = Logger.getLogger(UserServiceBean.class);
private Book testBook = new Book();
private Author testAuthor = new Author();
@Before
public void precondition(){
logger.info("Add Book Controller Test");
testBook.setName("Возера Радасці");
testAuthor.setAuthor_id(1L);
testBook.setAuthor(testAuthor);
testBook.setBought(false);
testBook.setGenre("postmodernism");
testBook.setPrice(15);
}
@Test
public void testDoPost() {
logger.info("Test post request processing");
BookAddController bookAddController = Mockito.mock(BookAddController.class);
HttpServletRequest testRequest = Mockito.mock(HttpServletRequest.class);
HttpServletResponse testResponse = Mockito.mock(HttpServletResponse.class);
BuyerServiceInterface buyerServiceInterface = Mockito.mock(BuyerServiceInterface.class);
AuthorServiceInterface authorServiceInterface = Mockito.mock(AuthorServiceInterface.class);
when(testRequest.getParameter("name")).thenReturn("Возера Радасці");
when(testRequest.getParameter("author_id")).thenReturn("1");
when(testRequest.getParameter("sold")).thenReturn("false");
when(testRequest.getParameter("genre")).thenReturn("postmodernism");
when(testRequest.getParameter("price")).thenReturn("15");
bookAddController.doPost(testRequest, testResponse);
verify(buyerServiceInterface, times(1)).addNewBook(testBook);
verify(authorServiceInterface, times(1)).findAuthorById(Long.parseLong("1"));
verify(bookAddController, times(1)).doGet(testRequest, testResponse);
}
</code></pre>
<p>I receive exception:</p>
<pre><code>java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/servlet/ServletException
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at org.junit.internal.builders.SuiteMethodBuilder.hasSuiteMethod(SuiteMethodBuilder.java:18)
at org.junit.internal.builders.SuiteMethodBuilder.runnerForClass(SuiteMethodBuilder.java:10)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:98)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
</code></pre>
<p><strong>Questions:</strong></p>
<ol>
<li>Do I use correct approach of testing <code>doPost</code> method?</li>
<li>How to fix this exception? </li>
</ol>
| 1 | 1,862 |
how receive arraylist in fragment
|
<p>I need to know how to get array list using Bundle in fragment , in the <a href="https://stackoverflow.com/questions/9245408/best-practice-for-instantiating-a-new-android-fragment">examples</a> I have seen they are using ints or strings. how to get fragments ? In my activity it was working good getting the arraylist </p>
<p>my updated code</p>
<pre><code>public class SingleViewActivity extends FragmentActivity {
ImageView imageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
ArrayList<Listitem> personArrayList = new ArrayList<Listitem>();
// add some ListItem's...
DemoObjectFragment f = DemoObjectFragment.newInstance(personArrayList);
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
imageView = (ImageView) findViewById(R.id.funnyimage);
Bundle bundle = getIntent().getExtras();
Log.d("s","singleview");
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
/*
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter( getSupportFragmentManager());
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
imageView = (ImageView) findViewById(R.id.funnyimage);
Bundle bundle = getIntent().getExtras();
Log.d("s","singleview");
mViewPager.setAdapter(mDemoCollectionPagerAdapter);*/
/* if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
MyFragment myrag = new MyFragment();
myrag.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(android.R.id.content, myrag).commit();
}
*/
}
</code></pre>
<hr>
<pre><code> // Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public static final String ARG_OBJECT = "Person_List";
public DemoCollectionPagerAdapter(FragmentManager fm, ArrayList<Listitem> personArrayList)
{
super(fm);
Log.d("s","adapterview");
}
@Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_PERSON_LIST, i + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
return 100;
}
@Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
</code></pre>
<hr>
<pre><code>// Instances of this class are fragments representing a single
// object in our collection.
public class DemoObjectFragment extends Fragment {
public static final String ARG_PERSON_LIST = "Person_List";
private ArrayList<Listitem> items;
public DemoObjectFragment newInstance(ArrayList<Listitem> items) {
DemoObjectFragment f = new DemoObjectFragment();
Bundle args = new Bundle();
args.putParcelableArrayList(ARG_PERSON_LIST, items);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args.containsKey(ARG_PERSON_LIST)) {
// UNTESTED: probably will need to cast this
this.items = args.getParcelableArrayList(ARG_PERSON_LIST);
} else { // avoid the NullPointerException later by initializing the list
this.items = new ArrayList<Listitem>();
}
// use this.items as you wish, but it will be empty if you didn't set the Bundle argument correctly
}
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
// Bundle args = getArguments();
// ((TextView) rootView.findViewById(R.id.text1)).setText(Integer.toString(args.getInt(ARG_OBJECT)));
Bundle args= new Bundle();
ArrayList<Listitem> personArrayList = args.getParcelableArrayList("Person_List");
System.out.print(personArrayList);
System.out.print("here1");
if (personArrayList != null && !personArrayList.isEmpty()) {
for (Listitem person : personArrayList) {
Picasso.
with(getActivity()).
load(person.url)
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(imageView);
Log.i("PersonsActivity",String.valueOf(person.url));
}
}
return rootView;
}
}
}
</code></pre>
<hr>
<p>I have 2 errors now :
<a href="https://i.stack.imgur.com/oq030.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oq030.png" alt="enter image description here"></a></p>
<p>for newInstance as I mentioned before I cannot refer to not static .</p>
<p>and I am getting error now for picasso </p>
<p><a href="https://i.stack.imgur.com/qs014.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qs014.png" alt="enter image description here"></a></p>
<p>edit 3 <a href="https://i.stack.imgur.com/szAhT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/szAhT.png" alt="enter image description here"></a></p>
| 1 | 2,821 |
Getting session and SFTP channel in Java using JSch library
|
<p>I am using JSch library for SFTP. I need to do several operations on SFTP server like move remote files in other directory, pull files, etc. For all these operations I need <code>Session</code> and from it I get <code>Channel</code> an then cast it to <code>ChannelSftp</code>. This is redundant step. So I thought of abstracting it into a <code>private</code> method.</p>
<pre><code>private ChannelSftp getChannelSftp() throws JSchException
{
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session;
session = jsch.getSession(VENDOR1_USERID, VENDOR1_SERVER, VENDOR1_PORT);
session.setPassword(VENDOR1_PASSWORD);
session.setConfig(config);
session.connect();
ChannelSftp channelSftp = null;
Channel channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
return channelSftp;
}
</code></pre>
<p>But after the SFTP operation I need to disconnect from channel and session <strong>both</strong>.
With above method, though I can disconnect from <code>Channel</code> in the calling method but I can't disconnect from <code>Session</code> as I don't have its instance which might be a leak so I now separated that into <code>getSession()</code> method and now <code>ChannelSftp</code> creation is duplicated in all methods. </p>
<p>What is better way to <strong><em>design/refactor</em></strong> it?</p>
<pre><code>private Session getSession() throws JSchException
{
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session;
session = jsch.getSession(VENDOR1_USERID, VENDOR1_SERVER, VENDOR1_PORT);
session.setPassword(VENDOR1_PASSWORD);
session.setConfig(config);
session.connect();
return session;
}
</code></pre>
<p><strong>Calling Method example:</strong> - <em>Duplicated code indicated</em></p>
<pre><code>public void sftp(File file) throws SftpException, FileNotFoundException, JSchException
{
Session session = getSession();
/* Duplicate code START*/
if ( session == null ) throw new SftpException(0 , "Service: Session is NULL");
ChannelSftp channelSftp = null;
Channel channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
/* Duplicate code END*/
channelSftp.cd(VENDOR1_PATH);
channelSftp.put(new FileInputStream(file), file.getName());
channelSftp.disconnect();
session.disconnect();
}
</code></pre>
| 1 | 1,028 |
React Apollo Testing is not working. Query data is always coming undefined
|
<p>I am getting loading state only and data as undefined in testing. I don't know why I am following everything in the given example. Please help.</p>
<p>Testing file. When i am waiting thsi line toexecute <code>await wait(() => getByTestId('edit-category'));</code>. It is giving response data of query as undefined.
Error: <code>TypeError: Cannot read property 'getCategory' of undefined</code>
Line 34 on <code>editConatinerCategory.tsx</code> => <code>category={data!.getCategory!}</code></p>
<pre><code>import React from 'react';
import gql from 'graphql-tag';
import { cleanup, wait } from 'react-testing-library';
import { customRender } from '../../../test-utils/customRender';
import { EditCategoryContainer } from './Container';
afterEach(() => {
cleanup();
console.error;
});
console.error = jest.fn();
const getCategoryMock = {
request: {
query: gql`
query getCategory($id: Int!) {
getCategory(id: $id) {
id
name
active
position
}
}
`,
variables: {
id: 1
}
},
result: {
data: {
getCategory: {
id: 1,
name: 'category',
active: true,
position: 1
}
}
}
};
describe('create edit category module', () => {
test('Rendering correct', async () => {
const { container, debug, getByTestId } = customRender(<EditCategoryContainer />, [
getCategoryMock
]);
await wait(() => getByTestId('edit-category'));
await wait(() => expect(container).toMatchSnapshot());
//Getting this TypeError: Cannot read property 'getCategory' of undefined. Because i am data as undefined from my query response
});
});
</code></pre>
<p>CustomRender.tsx</p>
<pre><code>import React from 'react';
import { render } from 'react-testing-library';
import { MockedProvider, MockedResponse } from 'react-apollo/test-utils';
import { Router, Switch } from 'react-router-dom';
import { createMemoryHistory } from 'history';
export const customRender = (
node: JSX.Element | null,
mocks?: MockedResponse[],
{
route = '/',
history = createMemoryHistory({ initialEntries: [route] })
} = {}
) => {
return {
history,
...render(
<MockedProvider mocks={mocks} addTypename={false}>
<Router history={history}>
<Switch>{node}</Switch>
</Router>
</MockedProvider>
)
};
};
</code></pre>
<p>EditCategoryContainer.tsx</p>
<pre><code>import React from 'react';
import { withRouter } from 'react-router';
import { Spin } from 'antd';
import {
AddCategoryComponent,
GetCategoryComponent
} from '../../../generated/graphql';
import { EditCategory } from './Edit';
import { LoadingComponent } from '../../../components/LoadingComponent';
export const EditCategoryContainer = withRouter(({ history, match }) => {
const id: number = parseInt(match.params.id, 10);
return (
<GetCategoryComponent
variables={{
id
}}
>
{({ data, loading: getCategoryLoading }) => {
console.log(getCategoryLoading, 'getCategoryLoading');
if (getCategoryLoading) {
return <LoadingComponent />;
}
if (data && !data.getCategory) {
return <div>Category not found!</div>;
}
console.log(data);
return (
<AddCategoryComponent>
{(addCategory, { loading, error }) => {
return (
<EditCategory
data-testid="edit-category"
category={data!.getCategory!}
loading={loading || getCategoryLoading}
onSubmit={values => {
addCategory({ variables: values }).then(() => {
history.push('/dashboard/categories');
});
}}
/>
);
}}
</AddCategoryComponent>
);
}}
</GetCategoryComponent>
);
});
</code></pre>
<p>Edit:
I tried @mikaelrs solution which is passed match. But it is not working. I also tried to pass id:1 as fixed. But it is still giving error. </p>
<pre><code> <GetCategoryComponent
variables={{
id:1
}}
>
...rest of code.
</GetCategoryComponent>
</code></pre>
<p>This is not working. My query without veriable is working fine. Mutation is also working fine. I am having only problem with this. When i have to pass like varible like this.</p>
| 1 | 1,891 |
Oracle procedure to kill jobs that do not complete in given time
|
<p>I have created an oracle procedure to reschedule job that do not complete in a given amount of time:</p>
<pre><code>create or replace procedure kill_stuck_jobs
as
begin
for x in (
select j.sid,
s.spid,
s.serial#,
j.log_user,
j.job,
j.broken,
j.failures,
j.last_date,
j.this_date,
j.next_date,
j.next_date - j.last_date interval,
j.what
from
(select
djr.SID,
dj.LOG_USER,
dj.JOB,
dj.BROKEN,
dj.FAILURES,
dj.LAST_DATE,
dj.LAST_SEC,
dj.THIS_DATE, dj.THIS_SEC,
dj.NEXT_DATE, dj.NEXT_SEC, dj.INTERVAL, dj.WHAT
from dba_jobs dj, dba_jobs_running djr
where dj.job = djr.job ) j,
(select p.spid, s.sid, s.serial#
from v$process p, v$session s
where p.addr = s.paddr ) s
where j.sid = s.sid and
j.next_date+15/1440 < sysdate
) loop
EXEC DBMS_JOB.BROKEN(x.job,TRUE);
execute immediate 'alter system disconnect session '''|| x.sid|| ',' || x.serial# || ''' immediate';
EXEC DBMS_JOB.BROKEN(x.job,FALSE);
dbms_output.put_line( 'Alter session done' );
end loop;
end;
</code></pre>
<p>But this procedure compiles with error:</p>
<pre><code>PLS-00103: Encountered the symbol "DBMS_JOB" when expecting one of the following:
:= . ( @ % ;
The symbol ":=" was substituted for "DBMS_JOB" to continue.
</code></pre>
<p><img src="https://i.stack.imgur.com/vLxRm.png" alt="enter image description here"></p>
<ul>
<li><p>Here came the discussion on dbms_job and dbms_scheduler_job. Actually the problem here is I created materialized view using linked db but sometime the query is stuck for whole day in session with <code>SQL*Net more data from dblink</code> . I used the above procedure to kill jobs that are created while creating materialized view and I am killing the session using :</p>
<pre><code>create or replace procedure kill_stuck_refresh as
begin
for x in (
select username, osuser, sid, serial#, seconds_in_wait,
event, state, wait_class
from v$session
where username is not null
and seconds_in_wait > 600
and event = 'SQL*Net more data from dblink'
) loop
execute immediate 'alter system disconnect session '''|| x.sid
|| ',' || x.serial# || ''' immediate';
dbms_output.put_line( 'Alter session done' );
end loop;
end; -- end of kill_stuck_refresh;
</code></pre></li>
</ul>
| 1 | 1,574 |
Unable to Open Connection to Zebra Printer
|
<p>I am currently in the process of creating an android application that requires the ability to print tickets/receipts from a mobile printer. The organization I am currently with has decided to purchase android tablets that are currently running 7.0 as well as Zebra Mobile Printers (ZQ510). We determined that using the BluetoothConnectionInsecure would be the best method of connecting and printing with these printers, since the application will be used on a multitude of tablets each connecting to their own printers.</p>
<p>Although we were able to successfully connect and print on the previous version of the application which was designed to work with android devices running 5.0 and above, it seems that the current version of our application is unable to establish a connection with the printer. </p>
<p>I've looked through stack for a similar error, but was unable to find any. If there is one similar to mine that exists, I would appreciate a link.</p>
<p><a href="https://stackoverflow.com/questions/36262106/zebra-printer-connection-failed-read-failed-socket-might-closed-or-timeout-re">Zebra printer connection failed “read failed, socket might closed or timeout, read ret: -1”</a></p>
<p>Here is the stack trace of the error:
<code>
01-18 14:24:08.332 9048-9165/marist.edu.mets_issue_ticket W/System.err: com.zebra.sdk.comm.ConnectionException: Could not connect to device: read failed, socket might closed or timeout, read ret: -1
01-18 14:24:08.333 9048-9165/marist.edu.mets_issue_ticket W/System.err: at com.zebra.sdk.comm.ConnectionA.open(Unknown Source)
01-18 14:24:08.333 9048-9165/marist.edu.mets_issue_ticket W/System.err: at com.zebra.sdk.comm.BluetoothConnection.open(Unknown Source)
01-18 14:24:08.333 9048-9165/marist.edu.mets_issue_ticket W/System.err: at marist.edu.mets_issue_ticket_helpers.BluetoothUnsecurePrint$1.run(BluetoothUnsecurePrint.java:308)
01-18 14:24:08.333 9048-9165/marist.edu.mets_issue_ticket W/System.err: at java.lang.Thread.run(Thread.java:761)
01-18 14:24:08.333 9048-9165/marist.edu.mets_issue_ticket W/System.err: Caused by: com.zebra.sdk.comm.ConnectionException: read failed, socket might closed or timeout, read ret: -1
01-18 14:24:08.333 9048-9165/marist.edu.mets_issue_ticket W/System.err: at com.zebra.sdk.comm.internal.BluetoothInsecureZebraConnectorImpl.tryPublicApiWay(Unknown Source)
01-18 14:24:08.333 9048-9165/marist.edu.mets_issue_ticket W/System.err: at com.zebra.sdk.comm.internal.BluetoothInsecureZebraConnectorImpl.open(Unknown Source)
</code></p>
<p>The method I am currently using to establish connection with the printer is as follows:</p>
<p>Creating an intent to search for discoverable devices, then passing that intent to my Bluetooth class:</p>
<pre><code>Intent discoverableIntent =
new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
BluetoothUnsecurePrint bluetoothUnsecurePrint = new BluetoothUnsecurePrint(resultMap,violationResults,getActivity(), theTicketNumber, discoverableIntent);
bluetoothUnsecurePrint.print();
</code></pre>
<p>Gather the list of devices found and grab MAC address of devices already paired to the tablet:</p>
<pre><code> public void print(){
//ask user to allow device to be discoverable by paired printer, display dialog box
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
userActivity.startActivity(discoverableIntent);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter().getAddress();
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
String deviceHardwareAddress = device.getAddress(); // MAC address
sendZplOverBluetooth(deviceHardwareAddress);
Log.d(TAG,device.getAddress()+ device.getName()+device.getBondState());
Intent ticketFinishedIntent = new Intent(userActivity, OffendingVehicleSearch.class);
userActivity.startActivity(ticketFinishedIntent);
}
}
}
</code></pre>
<p>Using the bluetooth mac address to establish a connection to the printer and then print the written data.</p>
<pre><code>private void sendZplOverBluetooth(final String theBtMacAddress) {
new Thread(new Runnable() {
public void run() {
try {
// Instantiate insecure connection for given Bluetooth&reg; MAC Address.
Connection thePrinterConn = new BluetoothConnectionInsecure(theBtMacAddress);
// Initialize
Looper.prepare();
Log.d(TAG,thePrinterConn.getSimpleConnectionName());
// Open the connection - physical connection is established here.
thePrinterConn.open();
Log.d(TAG, String.valueOf(thePrinterConn.bytesAvailable()));
// Send the data to printer as a byte array.
thePrinterConn.write(generateZPL().getBytes());
// Make sure the data got to the printer before closing the connection
Thread.sleep(500);
// Close the insecure connection to release resources.
thePrinterConn.close();
Looper.myLooper().quit();
} catch (Exception e) {
// Handle communications error here.
e.printStackTrace();
}
}
}).start();
}
</code></pre>
<p>I did come across some other semi-related forum posts concerning possible new permissions needed for the manifest file, however it looks like those permissions do not make a difference in the connection error.</p>
<p>
</p>
<pre><code><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera2.full" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code></pre>
<p>Please let me know if any other information is needed.</p>
| 1 | 2,428 |
Unable to parse document faces-config.xml in JSF application
|
<p>I'm developing a JSF web app. I use JSF 2.2 with Apache Tomcat 8.0.27.0.
When I press clean & build it works ok, but when I try to run my app I get this exception:</p>
<pre><code> com.sun.faces.config.ConfigurationException: java.util.concurrent.ExecutionException: com.sun.faces.config.ConfigurationException: Unable to parse document 'file:/C:/Users/axeli/Desktop/SeminarioPagina/build/web/WEB-INF/faces-config.xml': null
28-Feb-2016 18:00:19.275 INFO [http-nio-8084-exec-10] org.apache.catalina.util.LifecycleBase.stop The stop() method was called on component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]] after stop() had already been called. The second call will be ignored.
28-Feb-2016 18:00:19.777 INFO [http-nio-8084-exec-10] org.apache.catalina.startup.HostConfig.undeploy Repliegue (undeploy) de la aplicación web que tiene como trayectoria de contexto
28-Feb-2016 18:00:19.878 INFO [http-nio-8084-exec-10] org.apache.catalina.startup.HostConfig.deployDescriptor Desplieque del descriptor de configuración C:\Users\axeli\AppData\Roaming\NetBeans\8.1\apache-tomcat-8.0.27.0_base\conf\Catalina\localhost\ROOT.xml
28-Feb-2016 18:00:19.878 WARNING [http-nio-8084-exec-10] org.apache.catalina.startup.SetContextPropertiesRule.begin [SetContextPropertiesRule]{Context} Setting property 'antiJARLocking' to 'true' did not find a matching property.
28-Feb-2016 18:00:20.826 INFO [http-nio-8084-exec-10] org.apache.jasper.servlet.TldScanner.scanJars Al menos un JAR, que se ha explorado buscando TLDs, aún no contenía TLDs. Activar historial de depuración para este historiador para una completa lista de los JARs que fueron explorados y de los que nos se halló TLDs. Saltarse JARs no necesarios durante la exploración puede dar lugar a una mejora de tiempo significativa en el arranque y compilación de JSP .
28-Feb-2016 18:00:20.948 INFO [http-nio-8084-exec-10] com.sun.faces.config.ConfigureListener.contextInitialized Inicializando Mojarra 2.2.7 ( 20140610-1547 https://svn.java.net/svn/mojarra~svn/tags/2.2.7@13362) para el contexto ''
28-Feb-2016 18:00:21.079 SEVERE [http-nio-8084-exec-10] com.sun.faces.config.ConfigureListener.contextInitialized Critical error during deployment:
com.sun.faces.config.ConfigurationException: java.util.concurrent.ExecutionException: com.sun.faces.config.ConfigurationException: Unable to parse document 'file:/C:/Users/axeli/Desktop/SeminarioPagina/build/web/WEB-INF/faces-config.xml': null
at com.sun.faces.config.ConfigManager.getConfigDocuments(ConfigManager.java:761)
at com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:349)
at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:221)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4736)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5181)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:460)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1586)
at sun.reflect.GeneratedMethodAccessor47.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1460)
at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:906)
at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:344)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:614)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.util.concurrent.ExecutionException: com.sun.faces.config.ConfigurationException: Unable to parse document 'file:/C:/Users/axeli/Desktop/SeminarioPagina/build/web/WEB-INF/faces-config.xml': null
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at com.sun.faces.config.ConfigManager.getConfigDocuments(ConfigManager.java:759)
... 49 more
Caused by: com.sun.faces.config.ConfigurationException: Unable to parse document 'file:/C:/Users/axeli/Desktop/SeminarioPagina/build/web/WEB-INF/faces-config.xml': null
at com.sun.faces.config.ConfigManager$ParseTask.call(ConfigManager.java:1012)
at com.sun.faces.config.ConfigManager$ParseTask.call(ConfigManager.java:954)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at com.sun.faces.config.ConfigManager.getConfigDocuments(ConfigManager.java:747)
... 49 more
Caused by: java.lang.NullPointerException
at com.sun.faces.config.ConfigManager$ParseTask.getDocument(ConfigManager.java:1172)
at com.sun.faces.config.ConfigManager$ParseTask.call(ConfigManager.java:1003)
... 52 more
28-Feb-2016 18:00:21.195 SEVERE [http-nio-8084-exec-10] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
28-Feb-2016 18:00:21.195 SEVERE [http-nio-8084-exec-10] org.apache.catalina.core.StandardContext.startInternal Falló en arranque del Contexto [] debido a errores previos
28-Feb-2016 18:00:21.227 SEVERE [http-nio-8084-exec-10] javax.faces.FactoryFinder$FactoryManager.copyInjectionProviderFromFacesContext Unable to obtain InjectionProvider from init time FacesContext. Does this container implement the Mojarra Injection SPI?
28-Feb-2016 18:00:21.227 SEVERE [http-nio-8084-exec-10] javax.faces.FactoryFinder$FactoryManager.getFactory La aplicación no se ha inicializado correctamente durante el inicio, no se encuentra la fábrica: javax.faces.application.ApplicationFactory. Attempting to find backup.
28-Feb-2016 18:00:21.227 SEVERE [http-nio-8084-exec-10] com.sun.faces.config.ConfigureListener.contextDestroyed Unexpected exception when attempting to tear down the Mojarra runtime
java.lang.IllegalStateException: Could not find backup for factory javax.faces.application.ApplicationFactory.
at javax.faces.FactoryFinder$FactoryManager.getFactory(FactoryFinder.java:1135)
at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:379)
at com.sun.faces.config.InitFacesContext.getApplication(InitFacesContext.java:142)
at com.sun.faces.config.ConfigureListener.contextDestroyed(ConfigureListener.java:319)
at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4783)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5404)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:460)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1586)
at sun.reflect.GeneratedMethodAccessor47.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1460)
at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:906)
at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:344)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:614)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
28-Feb-2016 18:00:21.358 SEVERE [http-nio-8084-exec-10] javax.faces.FactoryFinder.releaseFactories Unable to call @PreDestroy annotated methods because no InjectionProvider can be found. Does this container implement the Mojarra Injection SPI?
28-Feb-2016 18:00:21.390 INFO [http-nio-8084-exec-10] org.apache.catalina.startup.HostConfig.deployDescriptor Deployment of configuration descriptor C:\Users\axeli\AppData\Roaming\NetBeans\8.1\apache-tomcat-8.0.27.0_base\conf\Catalina\localhost\ROOT.xml has finished in 1.512 ms
</code></pre>
<p>And these are the libraries I am using right now:</p>
<p><a href="https://i.stack.imgur.com/uNcyk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uNcyk.png" alt="enter image description here"></a></p>
| 1 | 5,564 |
PHP Make a simple calculator - Code doesnt work
|
<p>I am trying to make a simple calculator like this :</p>
<p>input1 select input2 = input3</p>
<ul>
<li>input1,input2 is first and second value</li>
<li>select have 4 operator : + - * /</li>
<li>input3 show the result</li>
</ul>
<p>This is my code and it doesnt work as expected,can someone help me out ?</p>
<pre><code><?php
ini_set('display_errors', 0);
session_start();
/* Check if form is submit
* if any input field is empty --> "NaN" result
* else check value of select field --> do the math --> result
* Then call JS function to change value of result field
*/
if(isset($_GET['act']) && $_GET['act']== 'do') {
$val1 = $_GET['val1'];
$val2 = $_GET['val2'];
$oper = $_GET['oper'];
if($val1 == NULL || $val2 == NULL)
$result= "NaN";
else {
switch($oper) {
case 1 : $result= $val1 + $val2; break;
case 2 : $result= $va1l - $val2; break;
case 3 : $result= $val1 * $val2; break;
case 4 : $result= $val1 / $val2; break;
}
}
echo "<script> showResult('".$result."') </script>";
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style>
input,select { height:30px;width:50px}
</style>
</head>
<body>
<form method="GET" action="bai4_1.php?act=do">
<table>
<tr><td>Op1</td>
<td>Oper</td>
<td>Op2</td>
<td>Result</td></tr>
<tr><td><input id="val1" type="text" name="val1" value="<?php echo
$_GET['val1'];?>"/></td>
<td><select id="oper" name="oper">
<option value=1>+</option>
<option value=2>-</option>
<option value=3>*</option>
<option value=4>/</option>
</select></td>
<td><input id="val2" type="text" name="val2" value="<?php
echo$_GET['val2'];?>"/> =</td>
<td><input id="result" type="text"></td></tr>
</table>
</form>
</body>
</html>
<script>
$("input,select").change(function(){
setTimeout(function(){
$("form").submit();
},1000);
});
function showResult(result) {
$("#result").val(result);
}
</script>
</code></pre>
| 1 | 1,230 |
Spring Hibernate Lazy loading - no session
|
<p>i have a lazy loading problem at a service call or at least i thought i just have a lazy loading problem... it seems to be, that i have a session problem => the session is not available during the hole service call.</p>
<p>This is my service-source:</p>
<pre><code>@Service
public class MyServiceImpl implements MyService{
@Autowired
private MyRepository myRepository;
@Override
@Transactional
public MyDTO find(String pk){
MyObject o = myRepository.findByPK(pk);
o.lazyCall();//Exception, but only at server call, tests runs without any problems
}
}
</code></pre>
<p>My Test-Class is annotated with:</p>
<pre><code>@Test
@ContextConfiguration (locations = { "classpath:spring-test-config.xml" })
@TransactionConfiguration (transactionManager="transactionManager", defaultRollback=true)
@Transactional
public class MyServiceTest
extends AbstractTransactionalTestNGSpringContextTests{
</code></pre>
<p>
and the test runs fine.</p>
<p>But if i deploy my stuff into a jetty server, i receive this exception:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.test.product.domain.ProductBase.productComponent, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:575) ~[hibernate-core-4.3.9.Final.jar:4.3.9.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:214) ~[hibernate-core-4.3.9.Final.jar:4.3.9.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:554) ~[hibernate-core-4.3.9.Final.jar:4.3.9.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:142) ~[hibernate-core-4.3.9.Final.jar:4.3.9.Final]
at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:294) ~[hibernate-core-4.3.9.Final.jar:4.3.9.Final]
at java.util.Collections$UnmodifiableCollection$1.<init>(Collections.java:1039) ~[na:1.8.0_25]
at java.util.Collections$UnmodifiableCollection.iterator(Collections.java:1038) ~[na:1.8.0_25]
at com.test.service.MyServiceImpl.find(MyServiceImpl.java:104) ~[My.service-0.0.1-SNAPSHOT.jar:na]
at com.test.webservice.MyServiceController.create(MyServiceController.java:44) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_25]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_25]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_25]
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_25]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) ~[spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) ~[spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776) ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705) ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) [javax.servlet-api-3.1.0.jar:3.1.0]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) [spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) [javax.servlet-api-3.1.0.jar:3.1.0]
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:816) [jetty-servlet-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1684) [jetty-servlet-9.3.0.RC1.jar:9.3.0.RC1]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:168) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:48) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:162) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176) [spring-security-web-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1667) [jetty-servlet-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581) [jetty-servlet-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) [jetty-server-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548) [jetty-security-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226) [jetty-server-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1121) [jetty-server-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511) [jetty-servlet-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185) [jetty-server-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1055) [jetty-server-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) [jetty-server-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213) [jetty-server-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:109) [jetty-server-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:118) [jetty-server-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.server.Server.handle(Server.java:515) [jetty-server-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:291) [jetty-server-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:242) [jetty-server-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:238) [jetty-io-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95) [jetty-io-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:57) [jetty-io-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:191) [jetty-util-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:126) [jetty-util-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654) [jetty-util-9.3.0.RC1.jar:9.3.0.RC1]
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572) [jetty-util-9.3.0.RC1.jar:9.3.0.RC1]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_25]
2015-07-15 00:00:28,383 | DEBUG | qtp1971855969-26 | o.s.s.w.c.Sec</code></pre>
</div>
</div>
</p>
<p>And finally my server datasource / tx configuration looks like this:</p>
<pre><code><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" >
<list>
<value>com.test</value>
</list>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
</bean>
</property>
</bean>
<!-- Transaction Manager configuration -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</code></pre>
<p>So what's the difference? Why is the behavior between the test and the server different? Why i don't have a database session in my servicemethod, but when i load something from the database i have a session? I read something about OpenSessionInViewFilter but this seems to be a solution for a front end app => but i want to implement a rest-server, which is called by a frontend.</p>
<p>Any ideas? Please help. </p>
<p>KR</p>
<p>--- update ---
Complete config files:</p>
<p>root-context.xml:
</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:amq="http://activemq.apache.org/schema/core"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/jms
http://www.springframework.org/schema/jms/spring-jms.xsd
http://activemq.apache.org/schema/core
http://activemq.apache.org/schema/core/activemq-core.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"
default-autowire="byName">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- only components from this package can be wired by spring -->
<context:component-scan base-package="com.test.product.*" />
<context:component-scan base-package="com.test.person.*" />
<!-- Directory to scan for repository classes -->
<jpa:repositories base-package="com.test.*.domain.repository" />
<!-- jdbc.properties => used to put db-connection data to an own property-file -->
<bean id="domainPropertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="locations">
<list>
<value>/WEB-INF/jdbc.properties</value>
</list>
</property>
</bean>
<!-- Datasource configuration - which database we use, look for jdbc.properties to set this data -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" >
<list>
<value>com.test.product.domain</value>
<value>com.test.person.domain</value>
</list>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
</bean>
</property>
</bean>
<!-- Transaction Manager configuration -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Couch DB Configuration -->
<!-- production and configuration or if you want to do a test to a real couch db (for example at continues integration) -->
<util:properties id="couchdbProperties" location="/WEB-INF/couchdb.properties"/>
<bean id="documentArchiveDatabase" class="org.ektorp.impl.StdCouchDbConnector">
<constructor-arg value="documentArchive" />
<constructor-arg>
<bean id="couchDbInstance" class="org.ektorp.impl.StdCouchDbInstance">
<constructor-arg>
<bean class="org.ektorp.spring.HttpClientFactoryBean" />
</constructor-arg>
</bean>
</constructor-arg>
</bean>
<!-- START JMS Config -->
<jms:annotation-driven/>
<!-- Possible productive configuration -->
<amq:broker id="broker" useJmx="false" persistent="false" >
<amq:transportConnectors>
<amq:transportConnector uri="tcp://localhost:61616"/>
</amq:transportConnectors>
</amq:broker>
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://localhost:61616"/>
</bean>
<bean id="cachingConnectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory" ref="connectionFactory"/>
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="cachingConnectionFactory"/>
</bean>
<bean id = "destinationResolver" class = "org.springframework.jms.support.destination.DynamicDestinationResolver"></bean>
<bean id="jmsListenerContainerFactory" class="org.springframework.jms.config.DefaultJmsListenerContainerFactory">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destinationResolver" ref="destinationResolver"/>
<property name="concurrency" value="1-10"/>
</bean>
<!-- END JMS Config -->
</beans>
</code></pre>
<p>Spring-Security.xml:
</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<http entry-point-ref="restAuthenticationEntryPoint">
<intercept-url pattern="/rest/**" access="hasRole('ROLE_USER')" />
<form-login authentication-success-handler-ref="mySuccessHandler"
authentication-failure-handler-ref="myFailureHandler" />
<logout />
<csrf disabled="true"/>
</http>
<beans:bean id="restAuthenticationEntryPoint" class="com.test.webservice.security.RestAuthenticationEntryPoint" />
<beans:bean id="mySuccessHandler"
class="com.test.webservice.security.RestAuthenticationSuccessHandler" />
<beans:bean id="myFailureHandler"
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler" />
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service>
<user name="temporary" password="temporary" authorities="ROLE_ADMIN" />
<user name="user" password="user" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
</code></pre>
<p>Servlet-context.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Configure to plugin JSON as request and response in method handler -->
<annotation-driven>
<message-converters>
<beans:bean class="org.springframework.http.converter.StringHttpMessageConverter">
</beans:bean>
<beans:bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<beans:property name="objectMapper">
<beans:bean class="com.test.webservice.MyObjectMapper" />
</beans:property>
</beans:bean>
</message-converters>
</annotation-driven>
<!-- only components from this package can be wired by spring -->
<context:component-scan base-package="com.test.product.*" />
<context:component-scan base-package="com.test.person.*" />
</beans:beans>
</code></pre>
<p>Web.xml</p>
<pre><code><?xml version="1.0" encoding="ISO-8859-1"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml, /WEB-INF/spring/spring-security.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Security Stuff -->
<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>
</filter-mapping>
</web-app>
</code></pre>
<p>jdbc.properties</p>
<pre><code>db.driver=org.h2.Driver
db.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
db.username=sa
db.password=
db.memurl=jdbc:h2:mem:test
</code></pre>
| 1 | 11,152 |
How to fix '_react["default"].memo is not a function. (In '_react["default"].memo(connectFunction)' error in React native?
|
<p>I am trying to connect Redux mapStateToProps() and mapActionCreators() to Login Screen through Container and I am using React navigation.</p>
<p>After build my app the following error message appears:</p>
<blockquote>
<p>_react["default"].memo is not a function. (In '_react["defaults"].memo(connectFunction)', '_react["defaults"].memo' is undefined.</p>
</blockquote>
<p>I searched for a while but what I have gotten is that React.memo() helps us control when our components rerender but I don't use any code related to React.memo().</p>
<p>Login Screen: (screens/LoginScreen/index.js)</p>
<pre><code>import React from 'react';
import {Dimensions, View} from 'react-native';
//Get width of mobile screen
var width = Dimensions.get("window").width;
var height = Dimensions.get("window").height;
export default class LoginScreen extends React.Component {
constructor(props){
super(props);
this.state = {
}
}
render() {
return (
<View style={styles.container}>
<Text>Log In page</Text>
</View>
);
}
}
LoginScreen.defaultProps = {
}
const styles = {
container: {
flex: 1
}
}
</code></pre>
<p>Login screen container: (containers/LoginContainer/index.js)</p>
<pre><code>import {connect} from "react-redux";
import LoginScreen from "../../screens/LoginScreen";
const mapStateToProps = (state) =>({
});
const mapActionCreators = {
};
export default connect(mapStateToProps, mapActionCreators)(LoginScreen);
</code></pre>
<p>Top level navigation: (navigations/TopLevelSwitchNav.js)</p>
<pre><code>import {createSwitchNavigation, createAppContainer} from 'react-navigation';
import LoginScreen from '../containers/LoginContainer';
import MainTabNav from './MainTabNav';
const TopLevelSwitchNav = createSwitchNavigation({
Login: {
screen: LoginScreen,
navigationOptions: {
header: null
}
},
MainTab: {
screen: MainTabNav,
navigationOptions: {
header: null
}
}
},
{
initialRouteName: Login,
navigationOptions: { header: null }
});
export default createAppContainer(TopLevelSwitchNav);
</code></pre>
<p>Dependencies:</p>
<pre><code>"dependencies": {
"expo": "^32.0.0",
"react": "16.5.0",
"react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz",
"react-navigation": "^3.8.1",
"react-redux": "^7.0.2",
"redux": "^4.0.1",
"redux-logger": "^3.0.6",
"redux-persist": "^5.10.0",
"redux-persist-transform-filter": "^0.0.18",
"redux-thunk": "^2.3.0"
},
</code></pre>
| 1 | 1,101 |
auto closing bootstrap alerts after form submission
|
<p>I have an ajax form that submits data into a database, and it uses bootstrap alerts for when it has been successful, I would like the alerts to close after a period of time has passed, but this needs to happen everytime.</p>
<p>For example if I load the form and make some changes and press submit it will show the success alert and then close, if I then submit the form again for example I forgot to change something perhaps, it will show the alert again, but this time it doesn't close.</p>
<p>How can I get the alert to show and close everytime?</p>
<p>I've provided an example with a hardcoded alert in the page, this is however written into the page using javascript, I couldn't figure out a way to provide a full example with working ajax code that showed the success alert with no back end PHP.</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!--[if IE]>
<meta http-equiv="X-UA-Compatible" content="IE=10">
<![endif]-->
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Bootstrap Alerts</title>
<link href="bootstrap.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
</head>
<body class="bg-dark text-white">
<div id="wrap">
<div class="container-fluid mt-4">
<p>Example Form</p>
<div class="col-sm-6">
<form action="process_add_task.php" method="post" class="row form-horizontal align-items-start" role="form">
<input name="task_id" type="hidden" value="1" class="form-control input-sm" />
<div class="col-sm-12">
<div id="name-group" class="form-group">
<label for="name" class="control-label">Name</label>
<input name="name" type="text" class="form-control input-sm" />
</div>
</div>
<div class="col-sm-12 mx-auto text-center">
<button type="submit" class="btn btn-md btn-primary">Submit <span class="fa fa-arrow-right"></span></button>
</div>
</form>
<div class="col-sm-12 mx-auto"><div class="alert alert-success" role="alert">Success</div></div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="static/js/bootstrap/bootstrap.js"></script>
<script src="static/js/bootstrap/bootstrap.notify.js"></script>
<script type="text/javascript">
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function() {
$(this).remove();
});
}, 1000);
</script>
</body>
</html>
</code></pre>
| 1 | 1,541 |
Cannot remove Fragment attached to a different FragmentManager. Fragment SupportMapFragment
|
<p>Android Studio 3.4.</p>
<p>in gradle.properties:</p>
<pre><code>android.useAndroidX=true
android.enableJetifier=true
</code></pre>
<p>in <strong>app/build.gradle</strong>:</p>
<pre><code>def AAVersion = '4.6.0'
dependencies {
annotationProcessor "org.androidannotations:androidannotations:$AAVersion"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'commons-io:commons-io:2.6'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'org.apache.commons:commons-lang3:3.8.1'
implementation 'com.google.android.gms:play-services:4.3.23'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.nineoldandroids:library:2.4.0'
implementation 'edu.vt.middleware:vt-password:3.1.2'
implementation "org.androidannotations:androidannotations-api:$AAVersion"
}
</code></pre>
<p>in fragment</p>
<pre><code>import com.google.android.gms.maps.SupportMapFragment;
import androidx.fragment.app.FragmentManager;
public class AgentsFragmentMapTab extends androidx.fragment.app.Fragment {
private SupportMapFragment mapFrag;
@Override
public void onDestroyView() {
super.onDestroyView();
try {
if (mapFrag != null) {
FragmentManager fragmentManager = thisFragmentActivity.getSupportFragmentManager();
fragmentManager.beginTransaction().remove(mapFrag).commit();
thisFragmentActivity = null;
}
} catch (IllegalStateException e) {
}
}
}
</code></pre>
<p>but I get runtime error in this line:</p>
<pre><code>fragmentManager.beginTransaction().remove(mapFrag).commit();
</code></pre>
<p>error:</p>
<pre><code>( 6664): onDestroyView
( 6664): RootFragment#onDestroyView()
(CATCHED)( 6664): Cannot remove Fragment attached to a different FragmentManager. Fragment SupportMapFragment{270ec77 (5411fd0b-1b45-40d3-b306-1452294a4734) id=0x7f0901d1} is already attached to a FragmentManager.
(CATCHED)( 6664): java.lang.IllegalStateException: Cannot remove Fragment attached to a different FragmentManager. Fragment SupportMapFragment{270ec77 (5411fd0b-1b45-40d3-b306-1452294a4734) id=0x7f0901d1} is already attached to a FragmentManager.
(CATCHED)( 6664): at androidx.fragment.app.BackStackRecord.remove(BackStackRecord.java:188)
(CATCHED)( 6664): at com.myproject.AgentsFragmentMapTab.onDestroyView(AgentsFragmentMapTab.java:356)
(CATCHED)( 6664): at androidx.fragment.app.Fragment.performDestroyView(Fragment.java:2852)
(CATCHED)( 6664): at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:947)
(CATCHED)( 6664): at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1228)
(CATCHED)( 6664): at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:434)
(CATCHED)( 6664): at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2066)
(CATCHED)( 6664): at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1856)
(CATCHED)( 6664): at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1811)
(CATCHED)( 6664): at androidx.fragment.app.FragmentManagerImpl.execSingleAction(FragmentManagerImpl.java:1686)
(CATCHED)( 6664): at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:299)
(CATCHED)( 6664): at androidx.fragment.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:230)
(CATCHED)( 6664): at androidx.viewpager.widget.ViewPager.setAdapter(ViewPager.java:513)
(CATCHED)( 6664): at md.qsystems.android.agents.SelectAgentMainFragment.removeViewPager(SelectAgentMainFragment.java:460)
(CATCHED)( 6664): at md.qsystems.android.agents.SelectAgentMainFragment.reloadAgents(SelectAgentMainFragment.java:553)
(CATCHED)( 6664): at md.qsystems.android.agents.SelectAgentMainFragment.access$000(SelectAgentMainFragment.java:54)
(CATCHED)( 6664): at md.qsystems.android.agents.SelectAgentMainFragment$1.onClick(SelectAgentMainFragment.java:114)
(CATCHED)( 6664): at android.view.View.performClick(View.java:5204)
(CATCHED)( 6664): at android.view.View$PerformClick.run(View.java:21153)
(CATCHED)( 6664): at android.os.Handler.handleCallback(Handler.java:739)
(CATCHED)( 6664): at android.os.Handler.dispatchMessage(Handler.java:95)
(CATCHED)( 6664): at android.os.Looper.loop(Looper.java:148)
(CATCHED)( 6664): at android.app.ActivityThread.main(ActivityThread.java:5417)
(CATCHED)( 6664): at java.lang.reflect.Method.invoke(Native Method)
(CATCHED)( 6664): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
(CATCHED)( 6664): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
gment_)( 6664): reloadAgents_existing_fragments: []
</code></pre>
| 1 | 1,863 |
MySQL Group Replication plugin not found in version 5.7.19, 5.7.21
|
<p>I am attempting to enable the MySQL group replication plugin on MySQL 5.7.21, which should be available in 5.7 as per the documentation (<a href="https://dev.mysql.com/doc/refman/5.7/en/group-replication.html" rel="noreferrer">https://dev.mysql.com/doc/refman/5.7/en/group-replication.html</a>)</p>
<pre><code>$ mysql --version
mysql Ver 14.14 Distrib 5.7.21, for Linux (x86_64) using EditLine wrapper
</code></pre>
<p>When I attempt to enable the plugin through MySQL:</p>
<pre><code>$ mysql> INSTALL PLUGIN group_replication SONAME 'group_replication.so';
ERROR 1126 (HY000): Can't open shared library '/usr/lib/mysql/plugin/group_replication.so' (errno: 2 /usr/lib/mysql/plugin/group_replication.so: cannot open shared object file: No such file or directory)
</code></pre>
<p>The output of my plugins in MySQL:</p>
<pre><code>$ mysql> SHOW PLUGINS;
+----------------------------+----------+--------------------+---------+---------+
| Name | Status | Type | Library | License |
+----------------------------+----------+--------------------+---------+---------+
| binlog | ACTIVE | STORAGE ENGINE | NULL | GPL |
| mysql_native_password | ACTIVE | AUTHENTICATION | NULL | GPL |
| sha256_password | ACTIVE | AUTHENTICATION | NULL | GPL |
| CSV | ACTIVE | STORAGE ENGINE | NULL | GPL |
| MEMORY | ACTIVE | STORAGE ENGINE | NULL | GPL |
| InnoDB | ACTIVE | STORAGE ENGINE | NULL | GPL |
| INNODB_TRX | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_LOCKS | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_LOCK_WAITS | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_CMP | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_CMP_RESET | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_CMPMEM | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_CMPMEM_RESET | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_CMP_PER_INDEX | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_CMP_PER_INDEX_RESET | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_BUFFER_PAGE | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_BUFFER_PAGE_LRU | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_BUFFER_POOL_STATS | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_TEMP_TABLE_INFO | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_METRICS | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_FT_DEFAULT_STOPWORD | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_FT_DELETED | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_FT_BEING_DELETED | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_FT_CONFIG | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_FT_INDEX_CACHE | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_FT_INDEX_TABLE | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_SYS_TABLES | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_SYS_TABLESTATS | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_SYS_INDEXES | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_SYS_COLUMNS | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_SYS_FIELDS | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_SYS_FOREIGN | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_SYS_FOREIGN_COLS | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_SYS_TABLESPACES | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_SYS_DATAFILES | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| INNODB_SYS_VIRTUAL | ACTIVE | INFORMATION SCHEMA | NULL | GPL |
| MyISAM | ACTIVE | STORAGE ENGINE | NULL | GPL |
| MRG_MYISAM | ACTIVE | STORAGE ENGINE | NULL | GPL |
| PERFORMANCE_SCHEMA | ACTIVE | STORAGE ENGINE | NULL | GPL |
| ARCHIVE | ACTIVE | STORAGE ENGINE | NULL | GPL |
| BLACKHOLE | ACTIVE | STORAGE ENGINE | NULL | GPL |
| FEDERATED | DISABLED | STORAGE ENGINE | NULL | GPL |
| partition | ACTIVE | STORAGE ENGINE | NULL | GPL |
| ngram | ACTIVE | FTPARSER | NULL | GPL |
+----------------------------+----------+--------------------+---------+---------+
44 rows in set (0.01 sec)
</code></pre>
<p>This is the contents of the plugin directory:</p>
<pre><code>$ ls -lah /usr/lib/mysql/plugin/
total 644K
drwxr-xr-x 2 root root 4.0K Sep 26 23:24 .
drwxr-xr-x 3 root root 4.0K Sep 26 23:24 ..
-rw-r--r-- 1 root root 21K Jul 19 14:10 adt_null.so
-rw-r--r-- 1 root root 6.2K Jul 19 14:10 auth_socket.so
-rw-r--r-- 1 root root 44K Jul 19 14:10 connection_control.so
-rw-r--r-- 1 root root 107K Jul 19 14:10 innodb_engine.so
-rw-r--r-- 1 root root 79K Jul 19 14:10 keyring_file.so
-rw-r--r-- 1 root root 151K Jul 19 14:10 libmemcached.so
-rw-r--r-- 1 root root 9.7K Jul 19 14:10 locking_service.so
-rw-r--r-- 1 root root 11K Jul 19 14:10 mypluglib.so
-rw-r--r-- 1 root root 6.2K Jul 19 14:10 mysql_no_login.so
-rw-r--r-- 1 root root 55K Jul 19 14:10 rewriter.so
-rw-r--r-- 1 root root 56K Jul 19 14:10 semisync_master.so
-rw-r--r-- 1 root root 15K Jul 19 14:10 semisync_slave.so
-rw-r--r-- 1 root root 27K Jul 19 14:10 validate_password.so
-rw-r--r-- 1 root root 31K Jul 19 14:10 version_token.so
</code></pre>
<p>These are the contents of my config:</p>
<blockquote>
<p>cat /etc/mysql/my.cnf</p>
</blockquote>
<pre><code> [mysqld_safe]
nice = 0
socket = /var/run/mysqld/mysqld.sock
[mysqld]
basedir = /usr
bind_address = 123.45.67.89
binlog_checksum = NONE
binlog_format = ROW
datadir = /var/lib/mysql
enforce_gtid_consistency = ON
expire_logs_days = 10
general_log = 1
general_log_file = /var/log/mysql/mysql.log
gtid_mode = ON
key_buffer_size = 8388608
lc_messages_dir = /usr/share/mysql
log_bin = binlog
log_error = /var/log/mysql/mysql_error.log
log_slave_updates = ON
long_query_time = 60
loose-group_replication_bootstrap_group = OFF
loose-group_replication_enforce_update_everywhere_checks= ON
loose-group_replication_group_name = 34dee7cd-d20d-4f59-9500-f56ada9a1abz
loose-group_replication_group_seeds = 123.45.67.88:33061,123.45.67.89:33061
loose-group_replication_ip_whitelist = 123.45.67.88,123.45.67.89
loose-group_replication_local_address = 123.45.67.89:33061
loose-group_replication_recovery_use_ssl= 1
loose-group_replication_single_primary_mode= OFF
loose-group_replication_ssl_mode = REQUIRED
loose-group_replication_start_on_boot = OFF
master_info_repository = TABLE
max_allowed_packet = 16M
max_binlog_size = 100M
max_connect_errors = 100000000
pid-file = /var/run/mysqld/mysqld.pid
port = 3306
query_cache_limit = 1M
query_cache_size = 16M
relay_log = my-project-prod-relay-bin
relay_log_info_repository = TABLE
report_host = 123.45.67.88
require_secure_transport = ON
server_id = 2
skip_external_locking
slow_query_log = 1
slow_query_log_file = /var/log/mysql/mysql-slow-query.log
socket = /var/run/mysqld/mysqld.sock
thread_cache_size = 8
thread_stack = 192K
tmpdir = /tmp
transaction_write_set_extraction = XXHASH64
user = mysql
[mysqldump]
max_allowed_packet = 16M
quick
quote_names
[mysql]
no-auto-rehash
[isamchk]
key_buffer_size = 16M
[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
!includedir /etc/mysql/conf.d/
</code></pre>
<p>I'm wondering if I'm using the wrong version of MySQL or if there is some other step needed to install the group replication plugin?</p>
| 1 | 4,950 |
Destructor causing segmentation fault
|
<p>I have implemented a class string, similar to std::string one.
I have a problem when the destructor is called: the field length has the length of the characters allocated in field.
This is the class:</p>
<pre><code>class indexException:public std::exception
{
public:
virtual const char* what()
{
return "Index is either too long, or negative";
}
};
class string
{
public:
static const unsigned int length_max=100;
string(const char* field=NULL)
{
if(field!=NULL)
{
const unsigned int length=strlen(field);
this->field=new char[length+1];
this->length=length;
for(unsigned int i=0;i<=length;i++)
this->field[i]=field[i];
}
else
{
this->field=NULL;
length=0;
}
}
string(string& str)
{
string(str.field);
}
~string()
{
if(length>0)
delete field;
}
char& operator[] (int i) const throw()
{
try
{
if(i<0 || i>=(int)length)
throw indexException();
}
catch(indexException& e)
{
std::cerr << e.what() << std::endl;
}
return field[i];
}
string& operator=(const char* field)
{
const unsigned int length=strlen(field);
if(this->length>0)
delete this->field;
this->field=new char[length];
this->length=length;
for(unsigned int i=0;i<length;i++)
this->field[i]=field[i];
return *this;
}
string& operator= (const string& str)
{
if(this!=&str)
*this=str.field;
return *this;
}
operator char* ()
{
return field;
}
friend std::ostream& operator<< (std::ostream& out, string& str);
friend std::istream& operator>> (std::istream& in, string& str);
public:
unsigned int length;
char* field;
};
std::ostream& operator<<(std::ostream& out, string& str)
{
out << str.field;
return out;
}
std::istream& operator>> (std::istream& in, string& str)
{
char temp[string::length_max];
in >> temp;
str=temp;
return in;
}
</code></pre>
<p>If I use the assignment operator, this doesn't cause a segmentation fault.
But it undirectly cause it.
I explain how:</p>
<pre><code>int main(int argc,char** argv)
{
string str="hi";
string str2=str;
return 0;
}
</code></pre>
<p>Putting a breakpoint into the assignment operator overloading, I realized that the assigment operator doesn't cause segmentation fault.
The problem is after, when exiting from main.
If I remove the destructor I don't get this segmentation fault, but I would know why I get this problem.</p>
<p>Edit: I have understood where's the problem.
I followed your suggestions but it still goes to segmentation fault.
But now it doesn't crash anymore on the destructor method, but on the assignment operator overloading:</p>
<pre><code> string& operator=(const char* field)
{
unsigned int length=0;
if(field!=NULL)
length=strlen(field);
else
field="";
if(this->length>0)
delete[] this->field;
this->field=new char[length+1];
this->length=length;
strcpy(this->field,field);
return *this;
}
</code></pre>
<p>The problem is when I delete this->field, the debugger stops there.
An example of segmentation fault:</p>
<pre><code>string str("hi");
string str2=str;
</code></pre>
<p>This causes segmentation fault.I suppone it's because str2 is not initialized, and length has an undefined value.
If I instead do this:</p>
<pre><code>string str("hi");
string str2;
str2=str;
</code></pre>
<p>There isn't any segmentation fault.Why?
I thought that calling :</p>
<pre><code>string str2;
</code></pre>
<p>Was also calling the constructor, or is that the "=" operator has the precedence?
How to solve this?</p>
<p>PS: I also changed other things,like the copy constructor.
Full code is here:
<a href="http://pastebin.com/ubRgaVr8" rel="nofollow">http://pastebin.com/ubRgaVr8</a></p>
<p>Solved: I changed the copy constructor as suggested in the accepted reply:</p>
<pre><code> string(const string& str)
{
length=str.length;
field=new char[str.length+1];
memcpy(field,str.field,length+1);
}
</code></pre>
| 1 | 2,008 |
Active Admin on Heroku doesn't work properly
|
<p>Hi I had active admin working fine before but I think it got messed up when I tried merging my github + heroku repositories. It seems to work fine locally but on Heroku I get the generic We're sorry, but something went wrong message. Here is the output of my heroku logs</p>
<blockquote>
<p>2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:385:in
<code>_run_process_action_callbacks' 2012-05-08T08:20:16+00:00 app[web.1]:
vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:405:in
</code>__run_callback' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_controller/metal/instrumentation.rb:30:in
<code>block in process_action' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/abstract_controller/callbacks.rb:17:in</code>process_action' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.3/lib/active_support/notifications.rb:123:in
<code>instrument' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.3/lib/active_support/notifications.rb:123:in
</code>block in instrument' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.3/lib/active_support/notifications/instrumenter.rb:20:in
<code>instrument' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_controller/metal/params_wrapper.rb:205:in
</code>process_action' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_controller/metal/instrumentation.rb:29:in
<code>process_action' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.3/lib/active_record/railties/controller_runtime.rb:18:in
</code>process_action' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/abstract_controller/rendering.rb:45:in <code>process' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/abstract_controller/base.rb:121:in
</code>process' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_controller/metal.rb:203:in
<code>dispatch' 2012-05-08T08:20:16+00:00 heroku[router]: GET
myrealtrip.com/admin/login dyno=web.1 queue=0 wait=0ms service=488ms
status=500 bytes=643 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_controller/metal/rack_delegation.rb:14:in
</code>dispatch' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_controller/metal.rb:246:in
<code>block in action' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/routing/route_set.rb:73:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/routing/route_set.rb:73:in
<code>dispatch' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/routing/route_set.rb:36:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/routing/mapper.rb:40:in
<code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/journey-1.0.3/lib/journey/router.rb:68:in
</code>block in call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/journey-1.0.3/lib/journey/router.rb:56:in
<code>each' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/journey-1.0.3/lib/journey/router.rb:56:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/routing/route_set.rb:600:in
<code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/warden-1.1.1/lib/warden/manager.rb:35:in
</code>block in call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/warden-1.1.1/lib/warden/manager.rb:34:in
<code>catch' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/warden-1.1.1/lib/warden/manager.rb:34:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/middleware/best_standards_support.rb:17:in
<code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/rack-1.4.1/lib/rack/etag.rb:23:in</code>call'
2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/rack-1.4.1/lib/rack/conditionalget.rb:25:in
<code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/middleware/head.rb:14:in</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/middleware/params_parser.rb:21:in
<code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/middleware/flash.rb:242:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/rack-1.4.1/lib/rack/session/abstract/id.rb:205:in
<code>context' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/rack-1.4.1/lib/rack/session/abstract/id.rb:200:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.3/lib/active_record/query_cache.rb:64:in
<code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/middleware/cookies.rb:338:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:467:in
<code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/middleware/callbacks.rb:28:in
</code>block in call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:405:in
<code>__run_callback' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:385:in
</code>_run_call_callbacks' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:405:in
<code>_run__1275827987324005955__call__874682597306149572__callbacks'
2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.3/lib/active_support/callbacks.rb:81:in
</code>run_callbacks' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/middleware/remote_ip.rb:31:in
<code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/middleware/callbacks.rb:27:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/middleware/debug_exceptions.rb:16:in
<code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/middleware/show_exceptions.rb:56:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/railties-3.2.3/lib/rails/rack/logger.rb:26:in
<code>call_app' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/railties-3.2.3/lib/rails/rack/logger.rb:16:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/middleware/request_id.rb:22:in
<code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/rack-1.4.1/lib/rack/methodoverride.rb:21:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/rack-1.4.1/lib/rack/runtime.rb:17:in
<code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.3/lib/active_support/cache/strategy/local_cache.rb:72:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/rack-1.4.1/lib/rack/lock.rb:15:in <code>call'
2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.3/lib/action_dispatch/middleware/static.rb:62:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/rack-cache-1.2/lib/rack/cache/context.rb:136:in
<code>forward' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/rack-cache-1.2/lib/rack/cache/context.rb:245:in
</code>fetch' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/rack-cache-1.2/lib/rack/cache/context.rb:185:in
<code>lookup' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/rack-cache-1.2/lib/rack/cache/context.rb:66:in
</code>call!' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/railties-3.2.3/lib/rails/engine.rb:479:in
<code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/rack-cache-1.2/lib/rack/cache/context.rb:51:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/railties-3.2.3/lib/rails/application.rb:220:in
<code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/rack-1.4.1/lib/rack/content_length.rb:14:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/rack-1.4.1/lib/rack/handler/webrick.rb:59:in
<code>service' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
vendor/bundle/ruby/1.9.1/gems/railties-3.2.3/lib/rails/rack/log_tailer.rb:14:in
</code>call' 2012-05-08T08:20:16+00:00 app[web.1]:<br>
/usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:111:in <code>service'
2012-05-08T08:20:16+00:00 app[web.1]:<br>
/usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:70:in</code>run'
2012-05-08T08:20:16+00:00 app[web.1]:<br>
/usr/local/lib/ruby/1.9.1/webrick/server.rb:183:in `block in
start_thread' 2012-05-08T08:20:16+00:00 app[web.1]:
2012-05-08T08:20:16+00:00 app[web.1]: 2012-05-08T08:20:16+00:00
app[web.1]: Processing by ActiveAdmin::Devise::SessionsController#new
as HTML 2012-05-08T08:20:16+00:00 app[web.1]: Rendered
vendor/bundle/ruby/1.9.1/bundler/gems/active_admin-ecb9ade65394/app/views/active_admin/devise/shared/_links.erb
(1.6ms) 2012-05-08T08:20:16+00:00 app[web.1]: Rendered
vendor/bundle/ruby/1.9.1/bundler/gems/active_admin-ecb9ade65394/app/views/active_admin/devise/sessions/new.html.erb
within layouts/active_admin_logged_out (379.1ms)
2012-05-08T08:20:16+00:00 app[web.1]: Completed 500 Internal Server
Error in 458ms 2012-05-08T08:20:16+00:00 heroku[router]: GET
myrealtrip.com/favicon.ico dyno=web.1 queue=0 wait=0ms service=5ms
status=200 bytes=0 2012-05-08T08:20:20+00:00 heroku[router]: GET
www.myrealtrip.com/assets/twit_icon_s.png dyno=web.1 queue=0 wait=0ms
service=7ms status=200 bytes=2504 2012-05-08T08:20:20+00:00
heroku[router]: GET www.myrealtrip.com/assets/fb_icon_s.png dyno=web.1
queue=0 wait=0ms service=8ms status=200 bytes=2498
2012-05-08T08:20:20+00:00 heroku[router]: GET
myrealtrip.com/assets/application.css dyno=web.1 queue=0 wait=0ms
service=12ms status=200 bytes=74016 2012-05-08T08:20:21+00:00
app[web.1]: 2012-05-08T08:20:21+00:00 app[web.1]:
2012-05-08T08:20:21+00:00 app[web.1]: Started GET "/ko/offers/16" for
125.129.240.184 at 2012-05-08 08:20:21 +0000 2012-05-08T08:20:21+00:00 app[web.1]: Processing by OffersController#show as HTML
2012-05-08T08:20:21+00:00 app[web.1]: Rendered offers/show.html.erb
within layouts/application (7.8ms) 2012-05-08T08:20:21+00:00
app[web.1]: Parameters: {"locale"=>"ko", "id"=>"16"}
2012-05-08T08:20:21+00:00 app[web.1]: Rendered
layouts/_header.html.erb (1.9ms) 2012-05-08T08:20:21+00:00 app[web.1]:
Rendered layouts/_footer.html.erb (0.2ms) 2012-05-08T08:20:21+00:00
app[web.1]: Completed 200 OK in 18ms (Views: 11.4ms | ActiveRecord:
5.3ms) 2012-05-08T08:20:21+00:00 heroku[router]: GET www.myrealtrip.com/ko/offers/16 dyno=web.1 queue=0 wait=0ms
service=57ms status=200 bytes=11374 2012-05-08T08:20:21+00:00
heroku[router]: GET myrealtrip.com/assets/mrt_logo.png dyno=web.1
queue=0 wait=0ms service=5ms status=200 bytes=1985
2012-05-08T08:20:21+00:00 heroku[router]: GET
www.myrealtrip.com/assets/application-e7fd2f7d29fd91d2ef43a8f52446d55e.css
dyno=web.1 queue=0 wait=0ms service=5ms status=304 bytes=0
2012-05-08T08:20:21+00:00 heroku[router]: GET
www.myrealtrip.com/assets/application-970c5c7eca4b286b5184e3caddf2b448.js
dyno=web.1 queue=0 wait=0ms service=23ms status=304 bytes=0
2012-05-08T08:20:21+00:00 heroku[router]: GET
www.myrealtrip.com/assets/fb_icon_s-41437f3d5d3a5b299e347aa41b1757bc.png
dyno=web.1 queue=0 wait=0ms service=6ms status=304 bytes=0
2012-05-08T08:20:21+00:00 heroku[router]: GET
www.myrealtrip.com/assets/twit_icon_s-2a91a32dd31f44cdc2716db595394a4e.png
dyno=web.1 queue=0 wait=0ms service=7ms status=304 bytes=0
2012-05-08T08:20:21+00:00 heroku[router]: GET
www.myrealtrip.com/assets/product_icon-de97603b22ca0e28730a4039f538c986.png
dyno=web.1 queue=0 wait=0ms service=5ms status=304 bytes=0
2012-05-08T08:20:21+00:00 heroku[router]: GET
www.myrealtrip.com/assets/offer_m_16-c77ea7c8aa397099eba93efd10f2ed0e.jpg
dyno=web.1 queue=0 wait=0ms service=7ms status=304 bytes=0
2012-05-08T08:20:21+00:00 heroku[router]: GET
www.myrealtrip.com/assets/guide_icon-0918b097277ab00b11c74d9a29601af1.png
dyno=web.1 queue=0 wait=0ms service=8ms status=304 bytes=0
2012-05-08T08:20:21+00:00 heroku[router]: GET
www.myrealtrip.com/assets/guide_profile_m_10-aae5b6874e3f733c238dde938cc90f09.jpg
dyno=web.1 queue=0 wait=0ms service=6ms status=304 bytes=0
2012-05-08T08:20:22+00:00 heroku[router]: GET
www.myrealtrip.com/assets/mrt_logo.png dyno=web.1 queue=0 wait=0ms
service=5ms status=304 bytes=0 2012-05-08T08:20:22+00:00
heroku[router]: GET www.myrealtrip.com/assets/register_icon.png
dyno=web.1 queue=0 wait=0ms service=13ms status=200 bytes=14694
2012-05-08T08:20:23+00:00 heroku[router]: GET
www.myrealtrip.com/favicon.ico dyno=web.1 queue=0 wait=0ms service=4ms
status=304 bytes=0</p>
</blockquote>
| 1 | 7,071 |
Error when using a DropDownListFor in a foreach loop in an MVC Razor view
|
<p>I am trying to create a simple form in ASP.MVC which shows a list of quotes, and allows the user to create work orders by selecting a person from a drop down list to assign that quote to, and then submitting the form all in one go.</p>
<p>My problem is that my use of DropDownListFor within a foreach loop is causing an error and I don't think I'm going about this the right way.</p>
<p>A (somewhat simplified) quote looks like this:</p>
<pre><code>public class QuoteItem
{
public QuoteItem()
{
this.IsWorkOrder = false;
}
[Key]
public int QuoteItemCostID { get; set; }
public string Item { get; set; }
public decimal? Subtotal { get; set; }
public bool IsWorkOrder { get; set; }
[NotMapped]
public string AssignedTo { get; set; }
}
</code></pre>
<p>I have a View Model configured as follows:</p>
<pre><code>public class UnassignedWorkOrdersViewModel
{
public IEnumerable<QuoteItemCost> QuoteItemCosts { get; set; }
public IEnumerable<SelectListItem> Trades { get; set; }
}
</code></pre>
<p>And a controller action that looks like this:</p>
<pre><code>public ActionResult Unassigned(int id = 0)
{
var trades = db.UserProfiles.Where(u => u.Typpe == "Trade").ToArray().Select(x => new SelectListItem
{
Value = x.FirstName + " " + x.LastName,
Text = x.FirstName + " " + x.LastName
}).ToList();
var quoteItems = db.QuoteItems
.Where(x => x.IsWorkOrder == false)
.ToList();
UnassignedWorkOrdersViewModel viewModel = new UnassignedWorkOrdersViewModel
{
Trades = trades,
QuoteItemCosts = quoteItemCosts
};
return View(viewModel);
}
</code></pre>
<p>My problem is that in my view, I'm trying to show each work order and the drop down list of trades next to it, and the way that I thought I'd do it is to map the class property "AssignedTo" to the value in the drop down list, however this doesn't work, as the DropDownList expects a LINQ expression as the first parameter:</p>
<pre><code>@model Project.ViewModels.UnassignedWorkOrdersViewModel
@if (Model.QuoteItemCosts.Any())
{
using (Html.BeginForm("Unassigned", "WorkOrder", FormMethod.Post, null))
{
@Html.AntiForgeryToken()
<table>
@foreach (var item in Model.QuoteItemCosts)
{
<tr>
<td style="width:100px;">
<b>Item:</b> @item.Item
</td>
<td style="width:200px;">
<b>Total:</b> @item.Subtotal
</td>
<td>
<b>Assign:</b>
@Html.DropDownListFor(
item.AssignedTo, // THIS LINE CAUSES AN ERROR
Model.Trades,
"", new { @id = "ddlStatus", @style = "width:100%" })
</td>
</tr>
}
</table>
}
</code></pre>
<p>How can I resolve this and am I even going about this the right way? On form submit, I should expect to get back the ViewModel which would then return all my QuoteItems, but with an AssignedTo entry if the user has selected a person from the drop down list.</p>
<p>Edit:</p>
<p>Andrei's suggestion below has helped and led me to another solution where my DropDownListFor now looks like this:</p>
<pre><code> @Html.DropDownListFor(
m => m.QuoteItemCosts.First(q => q.QuoteItemCostID == item.QuoteItemCostID).AssignedTo,
Model.Trades,
"", new { @id = "ddlStatus", @style = "width:100%" })
</code></pre>
<p>but when I submit the form the viewmodel is null:</p>
<pre><code> [HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Unassigned(UnassignedWorkOrdersViewModel viewModel)
{
// My viewModel is null
return RedirectToAction("Index");
}
</code></pre>
<p>I've updated my razor code to include a Html.BeginForm as well.</p>
| 1 | 1,711 |
Change color during writing a string into an image with drawstring
|
<p>I'm creating a string out of three smaller strings which I read in from three different text-files and then write the string into an image. I'd like to change the color for the paragraph in the middle of a created image. I can create the image with its three paragraphes, which looks like <a href="http://i50.tinypic.com/4id44y.jpg" rel="nofollow">this.</a></p>
<p>But how could I change the font color of the paragraph in the middle to the color red?</p>
<pre><code>import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.imageio.ImageIO;
public class writeToImage {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int imgnumber = 0;
FileInputStream fstream1 = null;
FileInputStream fstream2 = null;
FileInputStream fstream3 = null;
try {
fstream1 = new FileInputStream("vorlauf.txt");
fstream2 = new FileInputStream("mitte.txt");
fstream3 = new FileInputStream("nachlauf.txt");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Get the object of DataInputStream
DataInputStream vorlauf = new DataInputStream(fstream1);
BufferedReader br1 = new BufferedReader(new InputStreamReader(vorlauf));
DataInputStream mitte = new DataInputStream(fstream2);
BufferedReader br2 = new BufferedReader(new InputStreamReader(mitte));
DataInputStream nachlauf = new DataInputStream(fstream3);
BufferedReader br3 = new BufferedReader(new InputStreamReader(nachlauf));
String vorlauf1 = null;
String mitte1 = null;
String nachlauf1 = null;
try {
while ((vorlauf1 = br1.readLine()) != null && (mitte1 = br2.readLine()) != null && (nachlauf1 = br3.readLine()) != null){
try {
String vorlaufdiv = StringDivider(vorlauf1);
String mittediv = StringDivider(mitte1);
String nachlaufdiv = StringDivider(nachlauf1);
String totalPassage = vorlaufdiv + "\n\n" + mittediv + "\n\n" + nachlaufdiv;
//Image file name
String fileName = "English-translated-";
imgnumber++;
//create a File Object
File newFile = new File("./" + fileName + imgnumber + ".jpg");
//create the font you wish to use
Font font = new Font("Tahoma", Font.PLAIN, 15);
//create the FontRenderContext object which helps us to measure the text
FontRenderContext frc = new FontRenderContext(null, true, true);
//get the height and width of the text
Rectangle2D bounds = font.getStringBounds(totalPassage, frc);
int w = 750;
int h = 430;
//create a BufferedImage object
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
//calling createGraphics() to get the Graphics2D
Graphics2D g = image.createGraphics();
//set color and other parameters
g.setColor(Color.WHITE);
g.fillRect(0, 0, w, h);
g.setColor(Color.BLACK);
g.setFont(font);
int index = 0;
String[] parts = totalPassage.split("\n");
for(String part : parts){
g.drawString(part, (float) bounds.getX(), (float) -bounds.getY() + 20 * index++);
}
//releasing resources
g.dispose();
//creating the file
try {
ImageIO.write(image, "jpg", newFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String StringDivider(String s){
StringBuilder sb = new StringBuilder(s);
int i = 0;
while ((i = sb.indexOf(" ", i + 100)) != -1) {
sb.replace(i, i + 1, "\n");
}
return sb.toString();
}
}
</code></pre>
| 1 | 2,325 |
What is this error? cannot convert 'char**' to 'char*' for argument '1' to 'char* strcpy(char*, const char*)
|
<pre><code>#define NAME_LEN 20
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#pragma warning(disable:4996)
typedef struct bank
{
char *name[NAME_LEN];
int id;
int money;
struct bank *next;
} bank;
bank *head, *tail; // 노드의 처음과 끝
void Init_account(FILE *fp); // 노드의 처음과 끝에 메모리 할당하고, 파일에서 입력을 받도록 하는 함수
void Make_account(FILE *fp); // 계좌를 생성하는 함수
void Deposit(FILE *fp); // 입금 함수
void WithDraw(FILE *fp); // 출금 함수
void WriteAccount(FILE *fp); // 계좌의 정보를 저장하는 함수
void Account_inquire(void); // 계좌를 조회하는 함수
void ReadAccount(int id, char *name, int money); // 텍스트 파일에서 입력을 받는 함수
void Init_account(FILE *fp)
{
int id;
char name[NAME_LEN];
int money;
head = (bank *)malloc(sizeof(bank));
tail = (bank *)malloc(sizeof(bank));
head->next = tail;
tail->next = tail;
while (fscanf(fp, "%d %s %d", &id, name, &money) == 3){ // 정수형, 문자형, 정수형 3개일 때만 입력을 받음
ReadAccount(id, name, money);
}
}
void ReadAccount(int id, char *name, int money)
{
bank *t;
t = (bank *)malloc(sizeof(bank));
t->id = id;
strcpy(t->name, name);
t->money = money; // this code has problem //
t->next = head->next; // 다음 노드를 가리킴
head->next = t; // 노드의 처음을 가리킴
}
void Make_account(FILE *fp)
{
int id;
char name[NAME_LEN];
int money;
bank *t;
t = (bank *)malloc(sizeof(bank));
printf("\n*********계좌 생성*********\n");
printf("계좌번호 : "); scanf("%d", &id);
printf("예 금 주 : "); scanf("%s", name);
printf("입 금 액 : "); scanf("%d", &money);
t->id = id;
strcpy(t->name, name);
t->money = money;
t->next = head->next;
head->next = t;
WriteAccount(fp); // 저장하는 함수로 파일 포인터를 넘겨줌
}
void Deposit(FILE *fp)
{
int id;
int money;
bank *t;
printf("계좌번호 : "); scanf("%d", &id);
printf("입 금 액 : "); scanf("%d", &money);
for (t = head->next; t != tail; t = t->next)
{
if (t->id == id)
{
t->money += money; // 잔액에 입금할 금액을 더해서
WriteAccount(fp); // 저장
return;
}
}
printf("없는 계좌번호입니다.\n");
}
void WithDraw(FILE *fp)
{
int id;
int money;
bank *t;
printf("계좌번호 : "); scanf("%d", &id);
printf("출 금 액 : "); scanf("%d", &money);
for (t = head->next; t != tail; t = t->next)
{
if (t->id == id)
{
if (t->money
{
printf("출금액이 잔액을 초과할 수 없습니다.\n");
return;
}
else
{
t->money -= money; // 잔액에서 출금액을 빼서
}
WriteAccount(fp); // 저장
return;
}
}
printf("없는 계좌번호입니다.\n");
}
void Account_inquire(void)
{
bank *t;
for (t = head->next; t != tail; t = t->next)
{
printf("\n*********잔액 조회*********\n");
printf("계좌번호 : %d\n", t->id);
printf("예 금 주 : %s님\n", t->name);
printf("잔 액 : %d원\n\n", t->money);
}
}
void WriteAccount(FILE *fp)
{
bank *t;
rewind(fp); // 파일 읽는 포인터 지점을 맨 첨으로 돌리는 함수
for (t = head->next; t != tail; t = t->next)
{
fprintf(fp, "%d %s %d\n", t->id, t->name, t->money);
}
}
int main()
{
int input;
FILE *fp;
fp = fopen("data.txt", "r+"); // 파일모드가 r+일 경우 읽고쓰기를 동시에 수행 합니다.
Init_account(fp);
do
{
printf("계좌 생성&관리 프로그램입니다. 원하시는 번호를 입력하세요.\n");
printf("*********************************************\n");
printf("1)계좌 생성 2)계좌 조회 3)입금 4)출금 5)종료\n");
printf("*********************************************\n");
printf("입력 >");
scanf("%d", &input);
switch (input){
case 1:
Make_account(fp);
break;
case 2:
Account_inquire();
break;
case 3:
Deposit(fp);
break;
case 4:
WithDraw(fp);
break;
case 5:
input = 0;
free(head); // 종료하면서 메모리 반환
free(tail);
break;
default:
printf("잘못 입력하셨습니다. \n");
return main();
}
}
while (input != 0);
}
</code></pre>
<p>I am korean.</p>
<p>And i made "bank manage program code" for my homework.</p>
<p>But thers is problem in my code.(please ignore korea)</p>
<p>When i run my code, the error </p>
<p>cannot convert 'char**' to 'char*' for argument '1' to 'char* strcpy(char*, const char*)' happened.</p>
<p>I don't know about this problem.</p>
<p>So I add * to that part.</p>
<p>But the problem doesn't solve.</p>
<p>Is there any problem in my code?</p>
<p>Please help me.</p>
| 1 | 3,310 |
CSS selector is selecting all p elements in page
|
<p>I have a page and I want to style all the <code><p></code> elements inside a class. The problem is that, instead styling only the selected <code><p></code>, it's styling all the <code><p></code> elements in the page. I didn't find any open tags, so I don't know what's going on. Here's the commented codes:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#mainTips {
float: left;
width: 60%;
}
.dicas {
position: relative;
display: inline-block;
background-color: #2980b9;
width: 10em;
margin-left: 2em;
margin-top: 1em;
}
/* Here's where i'm styling the elements */
.dicas h3,
p {
font-family: 'Ubuntu', sans-serif;
font-weight: lighter;
text-align: center;
color: #ecf0f1;
}
.dicas p {
font-size: 0.8em;
margin-top: 6.5em;
}
.dicas:nth-of-type(1) {
background-image: url("../img/tip1.jpg");
background-size: cover;
background-repeat: no-repeat;
}
.dicas:nth-of-type(2) {
background-image: url("../img/tip2.jpg");
background-size: cover;
background-repeat: no-repeat;
}
#othTips {
margin-top: 1em;
width: 100%;
}
#othTips img {
float: left;
margin-left: 2em;
width: 9.5em;
height: 10em;
margin-bottom: 3em;
}
.description {
position: absolute;
background-color: #2980b9;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8" />
<title>Rebecca Bueno</title>
<!-- Chamando o CSS e as fontes do Google -->
<link href='https://fonts.googleapis.com/css?family=Ubuntu:500' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=EB+Garamond' rel='stylesheet' type='text/css'>
<link href="css/main.css" rel="stylesheet" />
<link href="css/dicas.css" rel="stylesheet" />
<link href="css/media.css" rel="stylesheet" />
<link href="css/animations.css" rel="stylesheet" />
</head>
<body>
<h1>Rebecca Bueno</h1>
<div id="menu">
<!-- Início menu -->
<ul>
<a href="index.html">
<li>Home</li>
</a>
<a href="tend.html">
<li>Tendências</li>
</a>
<a href="dicas.html">
<li>Dicas</li>
</a>
<a href="contato.html">
<li>Contato</li>
</a>
</ul>
</div>
<!-- Fim menu -->
<!-- I want to style only that p element. -->
<div id="mainTips">
<section class="dicas">
<article>
<h3> Dicas para... </h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
</p>
</article>
</section>
</div>
<div id="othTips">
<a href="#">
<img src="img/bg2.jpg" />
</a>
<!-- But it's also styling here -->
<div class="description">
<p>Descrição da dica</p>
</div>
<a href="#">
<img src="img/bg2.jpg" />
</a>
<a href="#">
<img src="img/othtm2.jpg" />
</a>
<a href="#">
<img src="img/othtm2.jpg" />
</a>
<a href="#">
<img src="img/tm4.jpg" />
</a>
<a href="#">
<img src="img/tm4.jpg" />
</a>
</div>
<div id="footer">
<!-- Rodapé -->
</div>
</body>
<!-- Chamando o JavaScript -->
<script src="js/styles.js"></script>
<script src="js/pgMan.js"></script>
<script>
window.onload = function() {
carregaFundo("bg");
slideImg();
lgSld(["Teste da legenda da primeira imagem.",
"Teste da legenda da segunda imagem.",
"Teste da legenda da terceira imagem.",
"Teste da legenda da quarta imagem."
]);
}
</script>
</html></code></pre>
</div>
</div>
</p>
| 1 | 2,099 |
InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified error clicking on div ng-click element with Selenium
|
<p>I am trying to select </p>
<pre><code><div ng-click="select('expert')" class="select-exp__item select-exp__item_active" ng-class="{'select-exp__item_active': 'expert'===selected}" style="">
</code></pre>
<p>I have tried a few things</p>
<pre><code>driver.find_element_by_css_selector("div[ng-click='select('expert')']").click()
driver.find_element_by_class_name('select-exp__item-title').click()
WebDriverWait(driver, 10).until(EC.element_to_be_clickable(By.XPATH("//div[@class='select-exp__item select-exp__item_active']").click()
WebDriverWait(driver, 10).until(EC.element_to_be_clickable(By.XPATH("//div[@class='select-exp__item select-exp__item_active' and contains(@ng-click, 'select('expert')')]").click()
</code></pre>
<p>...but I get the same error each time:</p>
<blockquote>
<p>InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified</p>
</blockquote>
<p>Grateful for any guidance, have googled "selenium ng-click" extensively without much luck and still learning Selenium, thank you. </p>
<p>Here's the full HTML:</p>
<pre><code><div class="agmodal__wrapper agmodal onboarding-wrapper ng-scope agmodal__wrapper--visible" ng-controller="OnboardingController as ctrl" ng-class="{'agmodal__wrapper--visible': ctrl.shown}" tabindex="-1" style="">
<div class="onboarding">
<div class="onboarding__body">
<!-- ngIf: ctrl.onboardingService.step === 1 --><section class="select-exp step ng-scope" ng-if="ctrl.onboardingService.step === 1" style="">
<div class="select-exp__header step__header">
<div class="select-exp__title step__title">Welcome to AMZScout PRO Extension</div>
<div class="select-exp__desc step__desc">
PRO Extension helps you find the perfect product to sell on Amazon
</div>
</div>
<div class="select-exp__body">
<div class="select-exp__body-title">
Select your experience level with Amazon</div>
<div class="select-exp__body-desc">
We will adjust the amount of pop up tips and certain parameters based on your experience. You will be able
to
change this choice later in the Settings.</div>
<div class="select-exp__items">
<div ng-click="select('beginner')" class="select-exp__item" ng-class="{'select-exp__item_active': 'beginner'===selected}">
<div class="select-exp__item-title">Beginner</div>
<div class="select-exp__item-desc">If you are new to Amazon research, you’ll see vital parameters that
will help you choose a great
product quickly. Great for learning.</div>
</div>
<div ng-click="select('expert')" class="select-exp__item select-exp__item_active" ng-class="{'select-exp__item_active': 'expert'===selected}" style="">
<div class="select-exp__item-title">Expert</div>
<div class="select-exp__item-desc">As an expert, you’ll see the full data and be able to fine-tune your
research.</div>
</div>
</div>
</div>
</code></pre>
| 1 | 1,404 |
Blocked while scraping goodreads.com
|
<p>I am trying to scrape a large sample (100k+) of the books available at "<a href="https://www.goodreads.com/book/show/" rel="nofollow noreferrer">https://www.goodreads.com/book/show/</a>", but I get continuously blocked.
So far I have tried to implement the following solutions in my code:</p>
<ul>
<li><p>Check the robots.txt to find what sites/elements are not accessible</p></li>
<li><p>Specify a header or multiple headers that randomly change</p></li>
<li><p>Use multiple working proxies to avoid being blocked</p></li>
<li><p>Set a delay up to 20 seconds between each scraping iteration that uses 10 simultaneous threads</p></li>
</ul>
<p>Here is a simplified version of the code that gets blocked while trying to scrape only the title and author of the book, without using multiple simultaneous threads:</p>
<pre><code>import requests
from lxml import html
import random
proxies_list = ["http://89.71.193.86:8080", "http://178.77.206.21:59298", "http://79.106.37.70:48550",
"http://41.190.128.82:47131", "http://159.224.109.140:38543", "http://94.28.90.214:37641",
"http://46.10.241.140:53281", "http://82.147.120.30:56281", "http://41.215.32.86:55561"]
proxies = {"http": random.choice(proxies_list)}
# real header
# headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'}
# multiple headers
headers_list = ['Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.38 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.103 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1623.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36']
headers = {"user-agent": random.choice(headers_list)}
first_url = 1
last_url = 10000 # Last book is 8,630,000
sleep_time = 20
for book_reference_number in range(first_url, last_url):
try:
goodreads_html = requests.get("https://www.goodreads.com/book/show/" + str(book_reference_number), timeout=5, headers=headers, proxies=proxies)
doc = html.fromstring(goodreads_html.text)
book_title = doc.xpath('//div[@id="topcol"]//h1[@id="bookTitle"]')[0].text.strip(", \t\n\r")
try:
author_name = doc.xpath('//div[@id="topcol"]//a[@class="authorName"]//span')[0].text.strip(", \t\n\r")
except:
author_name = ""
time.sleep(sleep_time)
print(str(book_reference_number), book_title, author_name)
except:
print(str(book_reference_number) + " cannot be scraped.")
pass
</code></pre>
| 1 | 1,415 |
DOMDocument::loadXML() error
|
<p>When I use DOMDocument in PHP file, I get the following errors:</p>
<blockquote>
<p>Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag nodes line 7 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77</p>
<p>Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag node line 6 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77</p>
<p>Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag field line 5 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77</p>
<p>Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag field line 5 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77</p>
<p>Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag field line 4 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77</p>
<p>Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag field line 4 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77</p>
<p>Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag node line 3 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77</p>
<p>Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag node line 2 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77</p>
<p>Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag node line 2 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77</p>
<p>Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag nodes line 1 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77
array(0) { }</p>
</blockquote>
<p><strong>The php code is as follows:</strong></p>
<pre><code><?php
class MyDOMDocument extends DOMDocument
{
public function toArray(DOMNode $oDomNode = null)
{
// return empty array if dom is blank
if (is_null($oDomNode) && !$this->hasChildNodes()) {
return array();
}
$oDomNode = (is_null($oDomNode)) ? $this->documentElement : $oDomNode;
if (!$oDomNode->hasChildNodes()) {
$mResult = $oDomNode->nodeValue;
} else {
$mResult = array();
foreach ($oDomNode->childNodes as $oChildNode) {
// how many of these child nodes do we have?
// this will give us a clue as to what the result structure should be
$oChildNodeList = $oDomNode->getElementsByTagName($oChildNode->nodeName);
$iChildCount = 0;
// there are x number of childs in this node that have the same tag name
// however, we are only interested in the # of siblings with the same tag name
foreach ($oChildNodeList as $oNode) {
if ($oNode->parentNode->isSameNode($oChildNode->parentNode)) {
$iChildCount++;
}
}
$mValue = $this->toArray($oChildNode);
$sKey = ($oChildNode->nodeName{0} == '#') ? 0 : $oChildNode->nodeName;
$mValue = is_array($mValue) ? $mValue[$oChildNode->nodeName] : $mValue;
// how many of thse child nodes do we have?
if ($iChildCount > 1) { // more than 1 child - make numeric array
$mResult[$sKey][] = $mValue;
} else {
$mResult[$sKey] = $mValue;
}
}
// if the child is <foo>bar</foo>, the result will be array(bar)
// make the result just 'bar'
if (count($mResult) == 1 && isset($mResult[0]) && !is_array($mResult[0])) {
$mResult = $mResult[0];
}
}
// get our attributes if we have any
$arAttributes = array();
if ($oDomNode->hasAttributes()) {
foreach ($oDomNode->attributes as $sAttrName=>$oAttrNode) {
// retain namespace prefixes
$arAttributes["@{$oAttrNode->nodeName}"] = $oAttrNode->nodeValue;
}
}
// check for namespace attribute - Namespaces will not show up in the attributes list
if ($oDomNode instanceof DOMElement && $oDomNode->getAttribute('xmlns')) {
$arAttributes["@xmlns"] = $oDomNode->getAttribute('xmlns');
}
if (count($arAttributes)) {
if (!is_array($mResult)) {
$mResult = (trim($mResult)) ? array($mResult) : array();
}
$mResult = array_merge($mResult, $arAttributes);
}
$arResult = array($oDomNode->nodeName=>$mResult);
return $arResult;
}
}
$sXml = <<<XML
<nodes>
<node>text<node>
<node>
<field>hello<field>
<field>world<field>
<node>
<nodes>
XML;
$dom = new MyDOMDocument;
$dom -> loadXml($sXml);
var_dump($dom->toArray());
?>
</code></pre>
<p>source location:
<a href="http://bd.php.net/manual/en/class.domdocument.php" rel="nofollow">http://bd.php.net/manual/en/class.domdocument.php</a></p>
| 1 | 2,438 |
Howto call method from OSGI bundle?
|
<p>I have written this OSGI bundle:</p>
<pre><code>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package CryptoLib;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class cryptoSha {
public cryptoSha() {
}
/** method for converting simple string into SHA-256 hash */
public String stringHash(String hash) throws NoSuchAlgorithmException{
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(hash.getBytes());
byte byteData[] = md.digest();
/** convert the byte to hex format */
StringBuilder sb = new StringBuilder();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}
</code></pre>
<p>And this is the Acticator class:</p>
<pre><code> package com.CL_67;
import CryptoLib.cryptoSha;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private static BundleContext context;
public void start(BundleContext context) throws Exception {
Activator.context = context;
context.registerService(cryptoSha.class.getName(), new cryptoSha(), null);
System.out.println("Module CL-67 is Loaded ...");
}
public void stop(BundleContext context) throws Exception {
context.ungetService(context.getServiceReference(cryptoSha.class.getName()));
Activator.context = null;
System.out.println("Module CL-67 is Unloaded ...");
}
}
</code></pre>
<p>This is the EAR package which calls the bundle:</p>
<pre><code>import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.osgi.framework.BundleContext;
@Named("loginController")
@SessionScoped
public class userCheck extends HttpServlet implements Serializable {
public userCheck(){
}
@WebServlet(name = "CL_67", urlPatterns = {"/CL_67"})
public class cryptoSha extends HttpServlet {
@Inject
cryptoSha stringHash;
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println(cryptoSha.stringHash("test"));
}
}
}
</code></pre>
<p>I successfully compile and deploy then on JBoss 7.1.0 but when I start the EAR package nothing happens. Can you help me to find where I'm wrong in the code?</p>
<p>kind regards,
Peter </p>
<p>EDIT:
Unfortunately I'm new to java programming and some of the code in the examples I don't understand how they work. Would you be so kind to help me with the example. I need to see how this code must be written in proper way in order to use it in future time? Would someone repair the code?</p>
<p>Thank you in advance.
Peter</p>
| 1 | 1,137 |
Android - How to set color of a TextView and background together with SharedPreferences
|
<p>in my app I have a menu button called "Settings" in which I can choose what colours set up to the background of some layout. Unfortunately I combine two layouts together to show what I want to show, and the problem is that I can only set background colour (that is in a layout) but not the the colour of TextView (that is in the other layout). </p>
<p>Layout main.xml:</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="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/main_layout">
<EditText
android:id="@+id/editText1"
android:layout_height="65dip"
android:layout_marginTop="2dip"
android:hint="Scrivi"
android:layout_width="fill_parent" />
<ListView android:id="@+id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:fastScrollEnabled="true">
</ListView>
</LinearLayout>
</code></pre>
<p>Layout listitem_row.xml:</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"
android:id="@+id/main_layout">
<TextView
android:id="@+id/textView1"
android:text="TextView"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="fill_parent">
</TextView>
<TextView
android:text="TextView"
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
</code></pre>
<p>MainActivity:</p>
<pre><code>import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class SearchCocktail extends Activity{
EditText ed;
ListView lview;
String[] first = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"};
String[] second = { "Uno", "Due", "Tre", "Quattro", "Cinque", "Sei", "Sette", "Otto", "Nove", "Dieci"};
int textlength = 0;
ArrayList<String> first_sort = new ArrayList<String>();
ArrayList<String> second_sort = new ArrayList<String>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed = (EditText) findViewById(R.id.editText1);
lview = (ListView) findViewById(R.id.list);
lview.setAdapter(new MyCustomAdapter(first, second));
...........
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.listitem_row, parent, false);
TextView textview = (TextView) row.findViewById(R.id.textView1);
TextView textview1 = (TextView) row.findViewById(R.id.textView2);
textview.setText(data_first[position]);
textview1.setText(data_second[position]);
return (row);
}
}
@Override
protected void onResume(){
super.onResume();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();
String colorePref = prefs.getString(PreferencesFromXml.COLORE_PREF, PreferencesFromXml.COLORE_DEFAULT);
int coloreDiSfondo = Color.parseColor(colorePref);
findViewById(R.id.list).setBackgroundColor(coloreDiSfondo);
editor.commit();
}
}
</code></pre>
<p>PreferencesFromXml activity:</p>
<pre><code>import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
public class PreferencesFromXml extends PreferenceActivity{
public static final String COLORE_DEFAULT = "#000000";
public static final String COLORE_PREF = "colore";
public static final String TITOLO_PREF = "titolo";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();
Preference titoloPrefs = findPreference(TITOLO_PREF);
titoloPrefs.setSummary(prefs.getString(TITOLO_PREF, getString(R.string.titolo_custom)));
titoloPrefs.setOnPreferenceChangeListener(new OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference prefs, Object value)
{
prefs.setSummary((CharSequence) value);
return true;
}
});editor.commit();
}
}
</code></pre>
<p>With my code I can change background colour of layout main.xml but I want change also the TextView colour of listitem_row.xml. I'd like to change the colours together (example: black colour for background and white colour for the text or white colour for the background and black colour for the text, etc.). How can I proceed? Thanks to everyone who can answer.</p>
| 1 | 1,926 |
Refused to execute script from '.../bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled
|
<p>I have an application with React/webpack frontend and Django/python backend. It has deployed successfully to heroku in the past. It has been sometime since I did anything in the application and after some recent updates I wanted to update the deployed version. Heroku reports that the application deployed successfully but when I try to access it, I get the error:</p>
<p>Refused to execute script from 'https://pairshead-2020.herokuapp.com/bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.</p>
<p>Here is my webpack.config.js:</p>
<pre><code>const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/app.js',
context: path.resolve(__dirname, 'frontend'),
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'frontend/dist'),
publicPath: '/'
},
devtool: 'source-maps',
module: {
rules: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.css$/, loader: ['style-loader', 'css-loader'] },
{ test: /\.s(a|c)ss$/, loader: ['style-loader', 'css-loader', 'sass-loader'] },
{ test: /\.woff2?$/, loader: 'file-loader' },
{ test: /\.(jpg|png|gif)$/, loader: 'file-loader' }
]
},
devServer: {
contentBase: 'src',
hot: true,
open: true,
port: 8000,
watchContentBase: true,
historyApiFallback: true,
proxy: {
'/api': 'http://localhost:4000'
}
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: 'src/index.html',
filename: 'index.html',
inject: 'body'
})
]
}
</code></pre>
<p>And here is my package.json:</p>
<pre><code>{
"name": "results",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"build": "webpack -p",
"serve:backend": "python manage.py runserver 4000",
"serve:frontend": "webpack-dev-server",
"seed": "python manage.py loaddata results/fixtures.json"
},
"dependencies": {
"@babel/core": "^7.5.5",
"@babel/plugin-transform-runtime": "^7.6.0",
"@babel/preset-env": "^7.6.0",
"@babel/preset-react": "^7.0.0",
"@babel/runtime": "^7.6.0",
"@fortawesome/fontawesome-free": "^5.10.2",
"axios": "^0.19.0",
"babel-loader": "^8.0.6",
"bulma": "^0.7.5",
"copy-webpack-plugin": "^5.0.4",
"css-loader": "^3.2.0",
"file-loader": "^4.2.0",
"html-webpack-plugin": "^3.2.0",
"jsonwebtoken": "^8.5.1",
"moment": "^2.24.0",
"moment-duration-format": "^2.3.2",
"node-sass": "^4.12.0",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-image": "^2.2.0",
"react-router-dom": "^5.0.1",
"react-select": "^3.0.4",
"react-select-async-paginate": "^0.3.13",
"react-toastify": "^5.4.0",
"sass-loader": "^7.3.1",
"style-loader": "^1.0.0",
"webpack": "^4.39.2",
"webpack-cli": "^3.3.7"
},
"devDependencies": {
"babel-eslint": "^10.0.3",
"eslint": "^6.3.0",
"eslint-plugin-react": "^7.14.3",
"webpack-dev-server": "^3.8.0"
},
"engines": {
"node": "12.11.1",
"python": "3.7.5"
}
}
</code></pre>
<p>Settings.py</p>
<pre><code>"""
Django settings for project project.
Generated by 'django-admin startproject' using Django 2.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# import dj_database_url
from dotenv import load_dotenv
import django_heroku
load_dotenv()
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
SECRET_KEY = os.environ['SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['0.0.0.0', 'localhost', 'pairshead-results.herokuapp.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'rest_framework',
'results',
'django_filters',
'computed_property',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
'http://localhost:3030',
]
CORS_ORIGIN_REGEX_WHITELIST = [
'http://localhost:3030',
]
ROOT_URLCONF = 'project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'Europe/London'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 25,
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
'PAGE_SIZE_QUERY_PARAM': 'page_size',
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication'
],
}
django_heroku.settings(locals())
# DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True)
</code></pre>
<p>urls.py (from projects folder)</p>
<pre><code>from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('django-admin/', admin.site.urls),
path('auth/', include('rest_framework.urls')),
path('api/', include('results.urls')),
path('api/', include('jwt_auth.urls')),
path('', include('frontend.urls')),
]
</code></pre>
<p>wsgi.py</p>
<pre><code>"""
WSGI config for project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
application = get_wsgi_application()
</code></pre>
<p>urls.py</p>
<pre><code>from django.urls import path
from .views import clubs
from .views import events
from .views import bands
from .views import crews
from .views import competitors
from .views import times
from .views import results
from .views import masters_adjustments
from .views import original_event_category
urlpatterns = [
path('clubs/', clubs.ClubListView.as_view()),
path('club-data-import/', clubs.ClubDataImport.as_view()),
path('events/', events.EventListView.as_view()),
path('event-data-import/', events.EventDataImport.as_view()),
path('band-data-import/', bands.BandDataImport.as_view()),
path('bands/', bands.BandListView.as_view()),
path('crews/', crews.CrewListView.as_view(), name='crews-list'),
path('crews/<int:pk>', crews.CrewDetailView.as_view(), name='crews-detail'),
path('', crews.CrewListView.as_view()),
path('results/', results.ResultsListView.as_view()),
path('results-export/', results.ResultDataExport.as_view()),
path('crew-update-rankings/', crews.CrewUpdateRankings.as_view()),
path('crew-data-import/', crews.CrewDataImport.as_view()),
path('crew-data-export/', crews.CrewDataExport.as_view()),
path('competitor-data-export/', competitors.CompetitorDataExport.as_view()),
path('competitor-data-import/', competitors.CompetitorDataImport.as_view()),
path('race-times/', times.RaceTimeListView.as_view()),
path('race-times/<int:pk>', times.RaceTimeDetailView.as_view()),
path('crew-race-times/', times.CrewRaceTimesImport.as_view()),
path('masters-adjustments-import/', masters_adjustments.MastersAdjustmentsImport.as_view()),
path('original-event-import/', original_event_category.OriginalEventCategoryImport.as_view()),
]
</code></pre>
<p>I have a views folder with 9 view files:
<strong>init</strong>.py</p>
<pre><code>from .bands import *
from .clubs import *
from .competitors import *
from .crews import *
from .events import *
from .times import *
from .results import *
from .masters_adjustments import *
</code></pre>
<p>procfile</p>
<pre><code>web: python manage.py runserver 0.0.0.0:$PORT --noreload
</code></pre>
<p>Very grateful for any help anyone can offer. After reading a few similar questions, I tried setting {output: publicPath: '/'} and {historyApiFallback: true} in webpack.config.js but didn't seem to make any difference.</p>
| 1 | 4,934 |
ERROR: Failed to resolve: espresso-core and ERROR: Failed to resolve: runner
|
<p>I'm going to build a project. When I create the project, I encounter the following error</p>
<pre><code>ERROR: Failed to resolve: espresso-core
Affected Modules: mvp-app
ERROR: Failed to resolve: runner
Affected Modules: mvp-app
</code></pre>
<p>and my build.gradle(module) file </p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "ir.sabmanage.mvp"
minSdkVersion 16
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support:exifinterface:28.0.0'
implementation 'com.ss.bottomnavigation:bottomnavigation:1.5.2'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.1.14'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
}
</code></pre>
<p>and my build.gradle(project) file</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenCentral()
maven { url 'https://maven.google.com' }
google()
jcenter()
maven { url 'https://jitpack.io' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p>How to fix this error? Has anyone faced this problem?
I found a solution but it did not answer me
<a href="https://stackoverflow.com/q/50899118/8748900">android studio failed to resolve: runner and failed to resolve: espresso-core and failed to resolve: monitor</a> </p>
| 1 | 1,128 |
How to find RC4 key from decrypted and encrypted data?
|
<p>I have some dump analysis in a documentation showing a bunch of encrypted data, and the resulting decrypted data. The algorithm used is explained (simple RC4). The only piece of information missing is the key used to get from the encrypted to the decrypted data.</p>
<p>I'm writing an automated test from this documentation material. I could chose some key of my own and recreate encrypted data from cleartext, but I wonder if there is any easy cryptanalysis way to find the original key that was used to encrypt the original bunch of data. </p>
<p>A brute force approach is probably possible as the key is quite small, but I'm much more interrested to know if any smarter approach exists.</p>
<p>Below is my current C encryption code (using OpenSSL):</p>
<pre><code>unsigned char source[16] = {
0xdb, 0xa3, 0x13, 0x30, 0x79, 0xa3, 0xcd, 0x9e,
0x48, 0xf4, 0x8f, 0x06, 0x37, 0x1b, 0x45, 0xdd};
unsigned char expected_target[16] = {
0x00, 0x00, 0x06, 0x00, 0x0e, 0x00, 0x00, 0x00,
0x6d, 0x69, 0x63, 0x72, 0x6f, 0x73, 0x6f, 0x66};
unsigned char target[16] = {};
unsigned char key[16] = {};
RC4_KEY crypt_key;
RC4_set_key(&crypt_key, 16, key);
RC4(&crypt_key, 16, source, target);
printf("key = [%02x %02x %02x %02x %02x %02x %02x %02x "
"- %02x %02x %02x %02x %02x %02x %02x %02x]\n",
key[0], key[1], key[2], key[3],
key[4], key[5], key[6], key[7],
key[8], key[9], key[10], key[11],
key[12], key[13], key[14], key[15]);
printf("source = [%02x %02x %02x %02x %02x %02x %02x %02x "
"- %02x %02x %02x %02x %02x %02x %02x %02x]\n",
source[0], source[1], source[2], source[3],
source[4], source[5], source[6], source[7],
source[8], source[9], source[10], source[11],
source[12], source[13], source[14], source[15]);
printf("target = [%02x %02x %02x %02x %02x %02x %02x %02x "
"- %02x %02x %02x %02x %02x %02x %02x %02x]\n",
target[0], target[1], target[2], target[3],
target[4], target[5], target[6], target[7],
target[8], target[9], target[10], target[11],
target[12], target[13], target[14], target[15]);
printf("expected_target = [%02x %02x %02x %02x %02x %02x %02x %02x "
"- %02x %02x %02x %02x %02x %02x %02x %02x]\n",
expected_target[0], expected_target[1], expected_target[2], expected_target[3],
expected_target[4], expected_target[5], expected_target[6], expected_target[7],
expected_target[8], expected_target[9], expected_target[10], expected_target[11],
expected_target[12], expected_target[13], expected_target[14], expected_target[15]);
</code></pre>
| 1 | 1,111 |
Remove space between yAxis and data in highcharts
|
<p>I would like to remove the space between y-axis and the chart as shown below:
<img src="https://i.stack.imgur.com/emwkE.png" alt="enter image description here"></p>
<p>Here is a fiddle used to create this chart : <a href="http://jsfiddle.net/basarat/pfkbX/" rel="noreferrer">jsFiddle for this chart</a></p>
<p>Here is the code used to setup (same as jsFiddle): </p>
<pre>
<code>
$(function () {
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
spacingLeft: 2,
spacingRight: 2
},
credits: { enabled: false },
title: { text: '' },
yAxis: {
title: '',
labels: {
style: {
fontSize:'9px'
}
}
},
xAxis: { labels: { enabled: false } }, //hide the x axis labels
series: [{
type: 'area',
name: 'speed',
showInLegend: false,
data: [
71.5, 106.4, 129.2, 144, 176, 135.6, 148.5, 216.4, 194.1, 129.2, 144, 176, 135.6, 148.5, 216.4, 194.1, 129.2, 144, 176, 135.6, 148.5, 216.4, 194.1, 129.2, 144, 176, 135.6, 148.5, 216.4, 194.1, 129.2, 144, 176, 135.6, 148.5, 216.4, 194.1, 129.2, 144, 176, 135.6, 148.5, 216.4, 194.1, 95.6,
71.5, 106.4, 129.2, 144, 176, 135.6, 148.5, 216.4, 194.1, 129.2, 144, 176, 135.6, 148.5, 216.4, 194.1, 129.2, 144, 176, 135.6, 148.5, 216.4, 194.1, 129.2, 144, 176, 135.6, 148.5, 216.4, 194.1, 129.2, 144, 176, 135.6, 148.5, 216.4, 194.1, 129.2, 144, 176, 135.6, 148.5, 216.4, 194.1, 95.6,
54.4]
}],
/* To make it pretty */
plotOptions: {
area: {
animation: false,
lineWidth: 1,
marker: {
enabled: false,
states: {
hover: {
enabled: true,
radius: 5
}
}
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
}
});
});
});
</code>
</pre>
| 1 | 1,796 |
GWT compiler doesn't find javax libraries
|
<p>I'm new to GWT and trying to run my fist GWT app. I have classes that uses API from javax.persistence package. When I try to compile the code using GWT compiler it fails for not being able to find the mentioned package in the classpath. I have the libraries added to the class though.</p>
<pre><code><property name="gwt.sdk" location="C:/gwt-2.4.0" />
<!-- Arguments to gwtc and devmode targets -->
<property name="gwt.args" value="" />
<path id="gwt.class.path">
<fileset dir="${devLib}"> <!-- here is all the dependent libraries-->
<include name="*.jar" />
</fileset>
<pathelement location="${gwt.sdk}/gwt-user.jar"/>
<fileset dir="${gwt.sdk}" includes="gwt-dev*.jar"/>
</path>
<target name="gwtc" description="GWT compile to JavaScript (production mode)">
<echo message="${gwt.class.path}"/>
<java failonerror="true" fork="true" classname="com.google.gwt.dev.Compiler">
<classpath>
<path refid="gwt.class.path"/>
<pathelement location="gwt/project/src"/>
</classpath>
<!-- add jvmarg -Xss16M or similar if you see a StackOverflowError -->
<jvmarg value="-Xmx256M"/>
<arg line="-war"/>
<arg value="web/five/gwtUI"/>
<!-- Additional arguments like -style PRETTY or -logLevel DEBUG -->
<arg line="${gwt.args}"/>
<arg value="org.scheduling.Scheduling"/>
</java>
</target>
</code></pre>
<p>here is the error that I see when run the ant target gwtc. Can someone help me to correct this?</p>
<pre><code>[java] Compiling module org.scheduling.Scheduling
[java] Validating newly compiled units
[java] Ignored 91 units with compilation errors in first pass.
[java] Compile with -strict or with -logLevel set to TRACE or DEBUG to see all errors.
[java] Computing all possible rebind results for 'com.google.gwt.user.client.UserAgentAsserter'
[java] Rebinding com.google.gwt.user.client.UserAgentAsserter
[java] Checking rule <generate-with class='com.google.gwt.editor.rebind.SimpleBeanEditorDriverGenerator'/>
[java] [WARN] Detected warnings related to 'com.google.gwt.editor.client.SimpleBeanEditorDriver'. Are validation-api-<version>.jar and validation-api-<version>-sources.jar on the classpath?
[java] Specify -logLevel DEBUG to see all errors.
[java] [WARN] Unknown type 'com.google.gwt.editor.client.SimpleBeanEditorDriver' specified in deferred binding rule
[java] Scanning for additional dependencies: file:/C:/Tolven_skandula/org.component.scheduling/gwt/project/src/org/scheduling/gwt/common/client/SchedulingEntryPoint.java
[java] Computing all possible rebind results for 'org.scheduling.common.service.SchedulingService'
[java] Rebinding org.scheduling.common.service.SchedulingService
[java] Checking rule <generate-with class='com.google.gwt.user.rebind.rpc.ServiceInterfaceProxyGenerator'/>
[java] [ERROR] Errors in 'file:/C:/Tolven_skandula/org.component.scheduling/gwt/project/src/org/scheduling/common/model/Appointment.java'
[java] [ERROR] Line 5: The import javax.persistence cannot be resolved
[java] [ERROR] Line 6: The import javax.persistence cannot be resolved
[java] [ERROR] Line 7: The import javax.persistence cannot be resolved
[java] [ERROR] Line 8: The import javax.persistence cannot be resolved
[java] [ERROR] Line 9: The import javax.persistence cannot be resolved
</code></pre>
| 1 | 1,514 |
Java signing files with BouncyCastle - Create signature of a file using secret keyring
|
<p>I'm trying to write a Java program that signs a file with a private key. The program takes 3 arguments - file, secret keyring and a password. The output should be in a detached file *.bpg. The problem is that I get the following errors when I try to compile my code:</p>
<pre><code>C:\CNS3\BCastle>javac Sign.java
Note: Sign.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
</code></pre>
<p>My code is as follows:</p>
<pre><code>import java.io.*;
import java.security.*;
import java.util.Iterator;
import org.bouncycastle.bcpg.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.*;
public class Sign {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
FileInputStream keyIn = new FileInputStream(args[1]);
FileOutputStream out = new FileOutputStream(args[0] + ".bpg");
InputStream in = PGPUtil.getDecoderStream(keyIn);
PGPSecretKeyRingCollection pgpSec =
new PGPSecretKeyRingCollection(in);
PGPSecretKey key = null;
Iterator rIt = pgpSec.getKeyRings();
while (key == null && rIt.hasNext()) {
PGPSecretKeyRing kRing = (PGPSecretKeyRing)rIt.next();
Iterator kIt = kRing.getSecretKeys();
while ( key == null && kIt.hasNext() ) {
PGPSecretKey k = (PGPSecretKey)kIt.next();
if ( k.isSigningKey() ) { key = k; }
}
}
if (key == null) {
throw new IllegalArgumentException("Can't find key");
}
PGPPrivateKey pgpPrivKey =
key.extractPrivateKey(args[2].toCharArray(), "BC");
PGPSignatureGenerator sGen = new PGPSignatureGenerator(
key.getPublicKey().getAlgorithm(), PGPUtil.SHA1, "BC");
sGen.initSign(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);
PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(
PGPCompressedDataGenerator.ZLIB);
BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(out));
FileInputStream fIn = new FileInputStream(args[0]);
int ch = 0;
while ( (ch = fIn.read()) >= 0 ) { sGen.update((byte)ch); }
sGen.generate().encode(bOut);
cGen.close();
out.close();
}
}
</code></pre>
<p>The errors come from the following lines:</p>
<pre><code> PGPPrivateKey pgpPrivKey =
key.extractPrivateKey(args[2].toCharArray(), "BC");
PGPSignatureGenerator sGen = new PGPSignatureGenerator(
key.getPublicKey().getAlgorithm(), PGPUtil.SHA1, "BC");
sGen.initSign(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);
</code></pre>
<p>Anyone have any suggestion on how I might fix this? Thanks a lot!</p>
| 1 | 1,080 |
Equality operator overloads: Is (x!=y) == (!(x==y))?
|
<p>Does the C++ standard guarantee that <code>(x!=y)</code> always has the same truth value as <code>!(x==y)</code>?</p>
<hr />
<p>I know there are <em>many</em> subtleties involved here: The operators <code>==</code> and <code>!=</code> may be overloaded. They may be overloaded to have different return types (which only have to be implicitly convertible to <code>bool</code>). Even the <code>!</code>-operator might be overloaded on the return type. That's why I handwavingly referred to the "truth value" above, but trying to elaborate it further, exploiting the implicit conversion to <code>bool</code>, and trying to eliminate possible ambiguities:</p>
<pre><code>bool ne = (x!=y);
bool e = (x==y);
bool result = (ne == (!e));
</code></pre>
<p><strong>Is <code>result</code> guaranteed to be <code>true</code> here?</strong></p>
<p>The C++ standard specifies the equality operators in section 5.10, but mainly seems to define them <em>syntactically</em> (and some semantics regarding pointer comparisons). The <em>concept</em> of being <a href="http://en.cppreference.com/w/cpp/concept/EqualityComparable" rel="nofollow noreferrer">EqualityComparable</a> exists, but there is no dedicated statement about the relationship of its operator <code>==</code> to the <code>!=</code> operator.</p>
<p>There exist <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3950.html" rel="nofollow noreferrer">related documents from C++ working groups</a>, saying that...</p>
<blockquote>
<p>It is vital that equal/unequal [...] behave as boolean negations of each other. After all, the world would make no sense if both operator==() and operator!=() returned false! As such, it is common to implement these operators in terms of each other</p>
</blockquote>
<p>However, this only reflects the Common Sense™, and does not <em>specify</em> that they have to be implemented like this.</p>
<hr />
<p><sub>Some background: I'm just trying to write a function that checks whether two values (of unknown type) are equal, and print an error message if this is not the case. I'd like to say that the required concept here is that the types are <code>EqualityComparable</code>. But for this, one would still have to write <code>if (!(x==y)) {…}</code> and could <strong>not</strong> write <code>if (x!=y) {…}</code>, because this would use a different operator, which is not covered with the concept of <code>EqualityComparable</code> at all, and which might even be overloaded differently...</sub></p>
<hr />
<p>I know that the programmer basically <em>can</em> do whatever he wants in his custom overloads. I just wondered whether he is really <em>allowed</em> to do everything, or whether there are rules imposed by the standard. Maybe one of these subtle statements that suggest that deviating from the usual implementation causes undefined behavior, like the one that <a href="https://stackoverflow.com/questions/35943551/equality-operator-overloads-is-x-y-x-y/35943728?noredirect=1#comment59544090_35943728">NathanOliver mentioned in a comment, but which seemed to only refer to certain types</a>. For example, the standard <strong>explicitly</strong> states that for <em>container types</em>, <code>a!=b</code> is equivalent to <code>!(a==b)</code> (section 23.2.1, table 95, "Container requirements").</p>
<p>But for general, user-defined types, it currently seems that there are no such requirements. The question is tagged <code>language-lawyer</code>, because I hoped for a definite statement/reference, but I know that this may nearly be impossible: While one could point out the section where it said that the operators <em>have</em> to be negations of each other, one can hardly prove that none of the ~1500 pages of the standard says something like this...</p>
<p>In doubt, and unless there are further hints, I'll upvote/accept the corresponding answers later, and for now assume that for comparing not-equality for <code>EqualityComparable</code> types should be done with <code>if (!(x==y))</code> to be on the safe side.</p>
| 1 | 1,166 |
post to SQL Server api with Express.js
|
<p>I´ve been testing Apis with Express.js from SQL Server database. With get i have no problems, but i cannot post.</p>
<p>This is y code so far:</p>
<pre><code> const express = require('express');
const bodyParser = require('body-parser');
const sql = require('mssql');
const app = express();
app.use(bodyParser.json());
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization");
next();
});
const server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
const dbConfig = {
user: "daUser",
password: "daPass",
server: "daServer",
database: "DaDB"
}
const executeQuery = function (res, query) {
sql.connect(dbConfig, function (err) {
if (err) {
console.log(err);
res.send(err);
}
else {
// create Request object
var request = new sql.Request();
// query to the database
request.query(query, function (err, result) {
if (err) {
console.log(err);
res.send(err);
}
else {
res.send(result);
}
});
}
});
}
app.get("/api/HolidayBaseApi", function (req, res) {
var query = "SELECT * FROM [HolidaysBase]";
executeQuery(res, query);
})
app.post("/api/HolidayBaseApi", function (req, res) {
var query = "INSERT INTO [HolidaysBase] (EmployeeNumber, PeriodBegin, PeriodEnd, WorkedYears, DaysPerYear, TakenDays, RemainingDays) VALUES (req.body.EmployeeNumber, req.body.PeriodBegin, req.body.PeriodEnd, req.body.WorkedYears, req.body.DaysPerYear, req.body.TakenDays, req.body.RemainingDays)";
executeQuery(res, query);
})
</code></pre>
<p>When i'm triying to make the post, i get an error which says:</p>
<pre><code>The multi-part identifier \"req.body.RemainingDays\" could not be bound.
</code></pre>
<p>The error list all my fields with the same error. The format of every field it's fine. I'm sending the data like this in postman:</p>
<pre><code>{
"EmployeeNumber": "9",
"PeriodBegin": "2018-10-15",
"PeriodEnd": "2019-10-15",
"WorkedYears": "6",
"DaysPerYear": "18",
"TakenDays": "0",
"RemainingDays": "18"
}
</code></pre>
<p>Someone knows why is not letting me post the info?</p>
<p>I'm using Javascript, Express.js, Node.</p>
<p><strong>--- EDITION ---</strong></p>
<p>I've found two solutions. The first solution next:</p>
<pre><code> app.post("/api/HolidayBaseApi", function (req, res) {
var query = "INSERT INTO [HolidaysBase] (EmployeeNumber, PeriodBegin, PeriodEnd, WorkedYears, DaysPerYear, TakenDays, RemainingDays) VALUES ('"+req.body.EmployeeNumber+"','"+req.body.PeriodBegin+"','"+req.body.PeriodEnd+"','"+req.body.WorkedYears+"','"+req.body.DaysPerYear+"','"+req.body.TakenDays+"','"+req.body.RemainingDays+"')";
executeQuery(res, query);
});
</code></pre>
<p>With my code like this, i could make the post. But there was some comments that this way it's a little dangerous, 'cause it's easier to get an SQL attack injection. And found another solution: On the <code>const executeQuery</code> need to add <code>parameters</code> like this:</p>
<pre><code>const executeQuery = function (res, query, parameters) {
sql.connect(dbConfig, function (err) {
if (err) {
console.log(err);
res.send(err);
}
else {
// create Request object
var request = new sql.Request();
// query to the database
parameters.forEach(function (p) {
request.input(p.name, p.sqltype, p.value);
});
request.query(query, function (err, result) {
if (err) {
console.log("Error al correr query en la base: " + err);
res.send(err);
}
else {
res.send(result);
sql.close();
}
});
}
});
}
</code></pre>
<p>Then, on the <code>app.post</code>:</p>
<pre><code>app.post("/api/HolidayBaseApi", function (req, res) {
var parameters = [
{ name: 'EmployeeNumber', sqltype: sql.Int, value: req.body.EmployeeNumber },
{ name: 'PeriodBegin', sqltype: sql.VarChar, value: req.body.PeriodBegin },
{ name: 'PeriodEnd', sqltype: sql.VarChar, value: req.body.PeriodEnd },
{ name: 'WorkedYears', sqltype: sql.Int, value: req.body.WorkedYears },
{ name: 'DaysPerYear', sqltype: sql.Int, value: req.body.DaysPerYear },
{ name: 'TakenDays', sqltype: sql.Int, value: req.body.TakenDays },
{ name: 'RemainingDays', sqltype: sql.Int, value: req.body.RemainingDays },
];
var query = "INSERT INTO [HolidaysBase] (EmployeeNumber, PeriodBegin, PeriodEnd, WorkedYears, DaysPerYear, TakenDays, RemainingDays) VALUES (@EmployeeNumber, @PeriodBegin, @PeriodEnd, @WorkedYears, @DaysPerYear, @TakenDays, @RemainingDays)";
executeQuery(res, query, parameters);
});
</code></pre>
<p>It works this way too </p>
| 1 | 2,294 |
ORA-02070: database does not support in this context Via DB LINK
|
<p>I have a View and want to insert this via DB Link. But it's give error "ORA-02070: database does not support in this context". How can I solve this error ?</p>
<pre><code>CREATE OR REPLACE FORCE VIEW V_TEST
(
OBJECT_ID,
SEQUENCE,
SCHEMA_NAME,
OBJECT_NAME,
OBJECT_TYPE_NAME,
LINE,
POSITION,
ERROR_MESSAGE,
CREATE_DATE
)
AS
SELECT dbaObjects.OBJECT_ID,
dbaErrors.SEQUENCE,
dbaErrors.OWNER AS SCHEMA_NAME,
dbaErrors.NAME AS OBJECT_NAME,
dbaErrors.TYPE AS OBJECT_TYPE_NAME,
dbaErrors.LINE,
dbaErrors.POSITION,
dbaErrors.TEXT AS ERROR_MESSAGE,
SYSDATE AS CREATE_DATE
FROM SYS.DBA_OBJECTS dbaObjects, SYS.DBA_ERRORS dbaErrors
WHERE dbaObjects.OWNER = dbaErrors.OWNER
AND dbaObjects.OBJECT_NAME = dbaErrors.NAME
AND dbaObjects.OBJECT_TYPE = dbaErrors.TYPE
AND dbaObjects.OWNER != 'SYS'
AND dbaObjects.OWNER = 'HELLO'
AND dbaObjects.STATUS = 'INVALID'
AND dbaErrors.TEXT != 'PL/SQL: SQL Statement ignored'
AND dbaErrors.TEXT != 'PL/SQL: Statement ignored'
ORDER BY dbaErrors.OWNER,
dbaErrors.NAME,
dbaErrors.TYPE,
dbaErrors.SEQUENCE;
</code></pre>
<p>View and Remote Table Types are same</p>
<p><a href="https://i.stack.imgur.com/taIX7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/taIX7.png" alt="enter image description here"></a></p>
<p>Insert Statement:</p>
<pre><code>INSERT INTO HELLO.T_INVALID_OBJECT_2@VADA (OBJECT_ID,
SEQUENCE,
SCHEMA_NAME,
OBJECT_TYPE_NAME,
OBJECT_NAME,
LINE,
POSITION,
ERROR_MESSAGE,
CREATE_DATE)
SELECT V.OBJECT_ID,
V.SEQUENCE,
V.SCHEMA_NAME,
V.OBJECT_TYPE_NAME,
V.OBJECT_NAME,
V.LINE,
V.POSITION,
V.ERROR_MESSAGE,
V.CREATE_DATE
FROM V_TEST V;
</code></pre>
<p>It's give error Insert Statement :(</p>
| 1 | 1,442 |
iPhone Programming from book. incomplete implementation of class 'InstatwitViewController'
|
<p>Hey everyone, im doing an independent study of iphone programming in my high school. i got a book from a teacher "Head First Iphone Programming". I got through the first lesson (hello world with a button) without any problems, but now im onto the second lesson. It is a twitter application that uses a UIPickerview to display options. I have not been able to get anything to show up on the UIPickerview.</p>
<p>my InstatwitViewController.h looks like:</p>
<pre><code> #import <UIKit/UIKit.h>
@interface InstatwitViewController : UIViewController
<UIPickerViewDataSource, UIPickerViewDelegate> {
NSArray* activities;
NSArray* feelings;
}
@end
</code></pre>
<p>and my InstaTwitViewController.m looks like:</p>
<pre><code>#import "InstatwitViewController.h"
@implementation InstatwitViewController
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerViewNumberOfRowsInComponent : (NSInteger)component {
if (component == 0) {
return [activities count];
}
else {
return [feelings count];
}
}
</code></pre>
<p>and ....</p>
<pre><code>// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
activities = [[NSArray alloc] initWithObjects:@"Sleeping", @"eating", @"working", @"thinking", @"crying", @"begging", @"leaving", @"shopping", @"hello worlding", nil];
feelings = [[NSArray alloc] initWithObjects:@"awesome", @"sad", @"happy", @"ambivalent", @"nauseous", @"psyched", @"confused", @"hopeful", @"anxious", nil];
}
</code></pre>
<p>and....</p>
<pre><code>- (void)dealloc {
[activities release];
[feelings release];
[super dealloc];
}
</code></pre>
<p>i went into IB and right-clicked on the picker and dragged the dataSource to the files owner, just like the book told me
then when i ran it.. i got black screen then nothing.</p>
<p>heres my debugger</p>
<pre><code>[Session started at 2011-03-14 18:48:17 -0400.]
GNU gdb 6.3.50-20050815 (Apple version gdb-1469) (Wed May 5 04:36:56 UTC 2010)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin".sharedlibrary apply-load-rules all
Attaching to process 10220.
2011-03-14 18:48:19.411 Instatwit[10220:207] -[InstatwitViewController pickerView:numberOfRowsInComponent:]: unrecognized selector sent to instance 0x5c164e0
2011-03-14 18:48:19.415 Instatwit[10220:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[InstatwitViewController pickerView:numberOfRowsInComponent:]: unrecognized selector sent to instance 0x5c164e0'
*** Call stack at first throw:
(
0 CoreFoundation 0x0238c919 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x024da5de objc_exception_throw + 47
2 CoreFoundation 0x0238e42b -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x022fe1b4 ___forwarding___ + 1124
4 CoreFoundation 0x022fdcd2 _CF_forwarding_prep_0 + 50
5 UIKit 0x002a7072 -[UIPickerView _delegateNumberOfRowsInComponent:] + 159
6 UIKit 0x0045033f -[UITable dataSourceGetRowCount] + 47
7 UIKit 0x004502e9 -[UITable numberOfRows] + 54
8 UIKit 0x0044e9d8 -[UITable floatArray:getValueCount:gapIndexCount:] + 34
9 UIKit 0x0034bbb5 -[UIFloatArray _setupWithDataProvider:valueIsSingleton:singletonValue:isRefresh:] + 68
10 UIKit 0x0034bb6b -[UIFloatArray refreshWithDataProvider:singleValue:] + 64
11 UIKit 0x004500d7 -[UITable setRowHeight:] + 160
12 UIKit 0x002a6201 -[UIPickerTable setRowHeight:] + 61
13 UIKit 0x004520e1 -[UITable _reloadRowHeights] + 199
14 UIKit 0x0044ff71 -[UITable noteNumberOfRowsChanged] + 99
15 UIKit 0x00454a0e -[UITable reloadData] + 439
16 UIKit 0x002ab301 -[UIPickerView layoutSubviews] + 4052
17 QuartzCore 0x0401c0d5 -[CALayer layoutSublayers] + 177
18 QuartzCore 0x0401be05 CALayerLayoutIfNeeded + 220
19 QuartzCore 0x0401b64c _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 302
20 QuartzCore 0x0401b2b0 _ZN2CA11Transaction6commitEv + 292
21 UIKit 0x002b363f -[UIApplication _reportAppLaunchFinished] + 39
22 UIKit 0x002b3a68 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 545
23 UIKit 0x002bd452 -[UIApplication handleEvent:withNewEvent:] + 1958
24 UIKit 0x002b6074 -[UIApplication sendEvent:] + 71
25 UIKit 0x002baac4 _UIApplicationHandleEvent + 7495
26 GraphicsServices 0x02bf2afa PurpleEventCallback + 1578
27 CoreFoundation 0x0236ddc4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
28 CoreFoundation 0x022ce737 __CFRunLoopDoSource1 + 215
29 CoreFoundation 0x022cb9c3 __CFRunLoopRun + 979
30 CoreFoundation 0x022cb280 CFRunLoopRunSpecific + 208
31 CoreFoundation 0x022cb1a1 CFRunLoopRunInMode + 97
32 UIKit 0x002b3226 -[UIApplication _run] + 625
33 UIKit 0x002beb58 UIApplicationMain + 1160
34 Instatwit 0x00001f18 main + 102
35 Instatwit 0x00001ea9 start + 53
36 ??? 0x00000001 0x0 + 1
)
terminate called after throwing an instance of 'NSException'
Program received signal: “SIGABRT”.
(gdb)
</code></pre>
<p>any help would be great, because this is for a class, and im a complete noob and i've been stuck here for around a month.</p>
<p>thanks</p>
| 1 | 3,111 |
How to integrate stripe using paymentIntent and confirmCardPayment
|
<p>I am attempting to integrate stripe into my application. I have completed the following steps so far.</p>
<ol>
<li>Ceate PaymentIntent on the server</li>
<li>Pass client secret to frontend</li>
<li><p>Use Stripe Elements to collect card info</p></li>
<li><p>Use Stripe.js handleCardPayment to process the payment</p></li>
</ol>
<p>During the handleCardPayment i am using react-stripe-elements and the documentation says to pass either the card element or the cardNumber element. <a href="https://stripe.com/docs/stripe-js/reference#stripe-confirm-card-payment" rel="nofollow noreferrer">https://stripe.com/docs/stripe-js/reference#stripe-confirm-card-payment</a></p>
<p>As you can see below im using <code>CardNumberElement, CardExpiryElement, CardCVCElement</code> separately. </p>
<pre><code> render() {
console.log(this.props.paymentIntent);
return (
<div className="checkout-component">
<br/>
<label>
Name:
<input placeholder="Name" />
</label>
<label>
Email:
<input placeholder="Email"></input>
</label>
<label>
Card Number:
<CardNumberElement ref={this.cardNumberRef}/>
</label>
<label>
Expiry Date:
<CardExpiryElement />
</label>
<label>
CVC:
<CardCVCElement />
</label>
<Grid
container
direction="column"
justify="center"
alignItems="flex-start"
spacing={5}
>
<Grid item>
<div>Total: {this.props.paymentIntent.amount / 100}</div>
</Grid>
<Grid item>
<Button variant="contained" color="primary" onClick={this.submit}>
Buy
</Button>
</Grid>
</Grid>
</div>
)
}
</code></pre>
<p>my submit function looks like the following: </p>
<pre><code>
submit = async () => {
try {
const data = {
payment_method: {
card: this.cardNumberRef.current.getElement(),
}
}
const result = await this.props.stripe.confirmCardPayment(this.props.paymentIntent.client_secret, data)
console.log(result);
} catch (err) {
console.log(err);
}
}
</code></pre>
<p>I opted not to use the card element instead using the individual pieces. </p>
<p>Although it succeeds, i am confused why i don't need to pass the cvc or expiry date?</p>
| 1 | 1,683 |
Airflow webserver suddenly stopped starting
|
<p>My airflow webserver suddenly stopped starting. When I try to start webserver it does not come up with UI. </p>
<p>I tried reseting db as <code>airflow resetdb</code> and <code>airflow initdb</code> restarting all the services. Downgrading Gunicorn and upgrading it again. Restarting my linux machine, however, nothing has changed.</p>
<p>Logs of webserver is following: </p>
<pre><code>[2019-05-17 08:08:00 +0000] [14978] [INFO] Starting gunicorn 19.9.0
[2019-05-17 08:08:00 +0000] [14978] [INFO] Listening at: http://0.0.0.0:8081 (14978)
[2019-05-17 08:08:00 +0000] [14978] [INFO] Using worker: sync
[2019-05-17 08:08:00 +0000] [14983] [INFO] Booting worker with pid: 14983
[2019-05-17 08:08:00 +0000] [14984] [INFO] Booting worker with pid: 14984
[2019-05-17 08:08:00 +0000] [14985] [INFO] Booting worker with pid: 14985
[2019-05-17 08:08:00 +0000] [14986] [INFO] Booting worker with pid: 14986
[2019-05-17 08:08:02,179] {__init__.py:51} INFO - Using executor LocalExecutor
[2019-05-17 08:08:02,279] {__init__.py:51} INFO - Using executor LocalExecutor
[2019-05-17 08:08:02,324] {__init__.py:51} INFO - Using executor LocalExecutor
[2019-05-17 08:08:02,342] {models.py:273} INFO - Filling up the DagBag from /root/airflow/dags
[2019-05-17 08:08:02,376] {__init__.py:51} INFO - Using executor LocalExecutor
[2019-05-17 08:08:02,435] {models.py:273} INFO - Filling up the DagBag from /root/airflow/dags
[2019-05-17 08:08:02,521] {models.py:273} INFO - Filling up the DagBag from /root/airflow/dags
[2019-05-17 08:08:02,524] {models.py:273} INFO - Filling up the DagBag from /root/airflow/dags
[2019-05-17 08:10:00 +0000] [14978] [CRITICAL] WORKER TIMEOUT (pid:14984)
[2019-05-17 08:10:00 +0000] [14978] [CRITICAL] WORKER TIMEOUT (pid:14985)
[2019-05-17 08:10:00 +0000] [14978] [CRITICAL] WORKER TIMEOUT (pid:14986)
[2019-05-17 08:10:00 +0000] [14978] [CRITICAL] WORKER TIMEOUT (pid:14983)
[2019-05-17 08:10:01 +0000] [15161] [INFO] Booting worker with pid: 15161
[2019-05-17 08:10:01 +0000] [15164] [INFO] Booting worker with pid: 15164
[2019-05-17 08:10:01 +0000] [15167] [INFO] Booting worker with pid: 15167
[2019-05-17 08:10:01 +0000] [15168] [INFO] Booting worker with pid: 15168
[2019-05-17 08:10:03,953] {__init__.py:51} INFO - Using executor LocalExecutor
[2019-05-17 08:10:04,007] {__init__.py:51} INFO - Using executor LocalExecutor
[2019-05-17 08:10:04,020] {__init__.py:51} INFO - Using executor LocalExecutor
[2019-05-17 08:10:04,036] {__init__.py:51} INFO - Using executor LocalExecutor
</code></pre>
<p>Is there anyone who encountered same problem? or Do you have any suggestions?</p>
| 1 | 1,048 |
Why is my PayPal IPN script failing?
|
<p>I'm developing a lightweight e-commerce solution that uses <em>PayPal</em> as the payment gateway. However, my IPN callback is constantly returning an <code>INVALID</code> response. I even tried using the sample PHP script provided by <em>PayPal</em>:</p>
<pre><code>// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
if (!$fp) {
// HTTP ERROR
}
else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0) {
// check the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
}
else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
}
fclose ($fp);
}
</code></pre>
<p>But as I say, I keep getting an <code>INVALID</code> response. This is in fact the response I get using a PHP class that writes the response to a log file:</p>
<pre><code>[2011-06-02 19:18:49] - FAIL: IPN Validation Failed.
IPN POST data from PayPal:
test_ipn=1,
payment_type=instant,
payment_date=11:07:43 Jun 02, 2011 PDT,
payment_status=Completed,
payer_status=verified,
first_name=John,
last_name=Smith,
payer_email=buyer@paypalsandbox.com,
payer_id=TESTBUYERID01,
business=seller@paypalsandbox.com,
receiver_email=seller@paypalsandbox.com,
receiver_id=TESTSELLERID1,
residence_country=US,
item_name1=something,
item_number1=AK-1234,
quantity1=1,
tax=2.02,
mc_currency=USD,
mc_fee=0.44,
mc_gross=15.34,
mc_gross_1=12.34,
mc_handling=2.06,
mc_handling1=1.67,
mc_shipping=3.02,
mc_shipping1=1.02,
txn_type=cart,
txn_id=4362187,
notify_version=2.4,
custom=xyz123,
invoice=abc1234,
charset=windows-1252,
verify_sign=AjbdIvvDAW2fh1O9jAbEym4myX.WAV7-jCEiEWMqoSkewvM6L3Co6oUQ
</code></pre>
<p>This is from the official <em>PayPal</em> IPN test tool. So something between <em>PayPal</em>'s sample code and test tool is causing my script to fail. Any one have any ideas?</p>
| 1 | 1,117 |
SharePoint Foundation 2013 - Order of loading sp.js and sp.runtime.js
|
<p>I have problem with an order in which I am loading </p>
<pre><code><script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
</code></pre>
<p>on my page</p>
<p>This is the whole head section on my master page.</p>
<pre><code><head runat="server">
<meta name="GENERATOR" content="Microsoft SharePoint" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=10"/>
<meta http-equiv="Expires" content="0" />
<SharePoint:SPPinnedSiteTile runat="server" TileUrl="/_layouts/15/images/SharePointMetroAppTile.png" TileColor="#0072C6" />
<SharePoint:RobotsMetaTag runat="server"/>
<SharePoint:PageTitle runat="server">
<asp:ContentPlaceHolder id="PlaceHolderPageTitle" runat="server">
<SharePoint:ProjectProperty Property="Title" runat="server" />
</asp:ContentPlaceHolder>
</SharePoint:PageTitle>
<SharePoint:SPShortcutIcon runat="server" IconUrl="/_layouts/15/images/favicon.ico?rev=23" />
<SharePoint:StartScript runat="server" />
<SharePoint:CssLink runat="server" Version="15"/>
<SharePoint:CacheManifestLink runat="server"/>
<SharePoint:ScriptLink language="javascript" name="core.js" OnDemand="true" runat="server" Localizable="false" />
<SharePoint:ScriptLink language="javascript" name="menu.js" OnDemand="true" runat="server" Localizable="false" />
<SharePoint:ScriptLink language="javascript" name="callout.js" OnDemand="true" runat="server" Localizable="false" />
<SharePoint:ScriptLink language="javascript" name="sharing.js" OnDemand="true" runat="server" Localizable="false" />
<SharePoint:ScriptLink language="javascript" name="suitelinks.js" OnDemand="true" runat="server" Localizable="false" />
<SharePoint:CustomJSUrl runat="server" />
<SharePoint:SoapDiscoveryLink runat="server" />
<SharePoint:AjaxDelta id="DeltaPlaceHolderAdditionalPageHead" Container="false" runat="server">
<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server" />
<SharePoint:DelegateControl runat="server" ControlId="AdditionalPageHead" AllowMultipleControls="true" />
<asp:ContentPlaceHolder id="PlaceHolderBodyAreaClass" runat="server" />
</SharePoint:AjaxDelta>
<SharePoint:CssRegistration Name="Themable/corev15.css" runat="server" />
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<SharePoint:ScriptLink ID="ScriptLink1" runat="server" Name="~sitecollection/_catalogs/masterpage/Resources/js/jquery-1.11.0.min.js" Language="javascript" />
<SharePoint:ScriptLink ID="ScriptLink3" runat="server" Name="~sitecollection/_catalogs/masterpage/Resources/js/global.js" Language="javascript" />
<link rel="stylesheet" type="text/css" href="Resources/css/quack_1200.css" />
<link rel="stylesheet" type="text/css" href="Resources/css/main.css" />
</head>
</code></pre>
<p>Following order breaks my code like this (when I am trying to work with sp context):</p>
<pre><code><script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
</code></pre>
<p><img src="https://i.stack.imgur.com/bJr9B.png" alt="enter image description here"></p>
<p>However if I switch the order of the scripts like this I don't get the previous error but I get following error if I try to go to a list and click on an "Edit" button.</p>
<pre><code><script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
</code></pre>
<p><img src="https://i.stack.imgur.com/pEzqN.png" alt="enter image description here"></p>
<p><img src="https://i.stack.imgur.com/4OGJz.png" alt="enter image description here"></p>
<p>Any help on this confusing issue would be very much appreciated.</p>
| 1 | 1,684 |
Update multiple rows in mysql with php
|
<p>Here is my code below. The problem is when I try to update info it instead clears all records and does not update. How can I get this script to update and not clear. Also, I have used this before and it worked fine but all the sudden it doesn't.. I might have removed something important.</p>
<pre><code><strong>Update multiple rows in mysql</strong><br>
<?php
$mysql_host = "mysql.com";
$mysql_user = "username";
$mysql_pass = "password";
$mysql_database = "dbname";
$tbl_name="test_mysql"; // Table name
// Connect to server and select databse.
mysql_connect("$mysql_host", "$mysql_user", "$mysql_pass")or die("cannot connect");
mysql_select_db("$mysql_database")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
// Count table rows
$count=mysql_num_rows($result);
$id = array();
?>
<table width="500" border="0" cellspacing="1" cellpadding="0">
<form name="form1" method="post" action="">
<tr>
<td>
<table width="500" border="0" cellspacing="1" cellpadding="0">
<tr>
<td align="center"><strong>Id</strong></td>
<td align="center"><strong>Name</strong></td>
<td align="center"><strong>Lastname</strong></td>
<td align="center"><strong>Email</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td align="center"><? $id[]=$rows['id']; ?><? echo $rows['id']; ?></td>
<td align="center"><input name="name[]" type="text" id="name" value="<? echo $rows['name']; ?>"></td>
<td align="center"><input name="lastname[]" type="text" id="lastname" value="<? echo $rows['lastname']; ?>"></td>
<td align="center"><input name="email[]" type="text" id="email" value="<? echo $rows['email']; ?>"></td>
</tr>
<?php
}
?>
<tr>
<td colspan="4" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</td>
</tr>
</form>
</table>
<?php
// Check if button name "Submit" is active, do this
if(isset($_POST['Submit'])){
for($i=0;$i<$count;$i++){
$sql1="UPDATE $tbl_name SET name='$name[$i]', lastname='$lastname[$i]', email='$email[$i]' WHERE id='$id[$i]'";
$result1=mysql_query($sql1);
}
}
if($result1){
echo "Good";
////header("location:update_multiple.php");
}
mysql_close();
?>
</code></pre>
| 1 | 1,112 |
Managed Type equivalent of [MarshalAs(UnmanagedType.I8)]
|
<p>I have inherited a dll written in C that I access from a windows application (Framework 2.0) in C#. Recently some machines have been upgraded to 64-bit Windows 7, and the dll is no longer returning the correct values on those machines. I believe this is because the C function has parameter types that are expected to be 64-bit.</p>
<p>Here's the signature of the C function</p>
<pre><code>int doFlightCalc_S(double LatA,
double LonA,
double LatB,
double LonB,
int month,
int aircraftCd,
int nbrPsgrs,
int taxiInTm,
int taxiOutTm,
int fuelStopTime,
int *results)
</code></pre>
<p>Here's the definition that accesses the function from C#</p>
<pre><code>[DllImport("doFlightCalc.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int doFlightCalc_S(
[MarshalAs(UnmanagedType.R8)] double latA,
[MarshalAs(UnmanagedType.R8)] double lonA,
[MarshalAs(UnmanagedType.R8)] double latB,
[MarshalAs(UnmanagedType.R8)] double lonB,
[MarshalAs(UnmanagedType.I4)] int month,
[MarshalAs(UnmanagedType.I4)] int aircraftCd,
[MarshalAs(UnmanagedType.I4)] int nbrPsgrs,
[MarshalAs(UnmanagedType.I4)] int taxiInTm,
[MarshalAs(UnmanagedType.I4)] int taxiOutTm,
[MarshalAs(UnmanagedType.I4)] int fuelStopTime,
[MarshalAs(UnmanagedType.LPArray)] [Out] int[] results);
</code></pre>
<p>If I were to compile the C dll as a 64-bit dll while leaving the function as is, what changes would I need to make to the function in C#?</p>
<p>I would assume that I have to change the I4s to I8s but what type would I replace the int and double with? Would the following :</p>
<pre><code> [MarshalAs(UnmanagedType.R8)] double lonB,
[MarshalAs(UnmanagedType.I4)] int month,
</code></pre>
<p>be changed to:</p>
<pre><code> [MarshalAs(UnmanagedType.R8)] (what would go here?) lonB,
[MarshalAs(UnmanagedType.I8)] long (is long correct here?) month,
</code></pre>
<p>Or am I barking up the wrong tree?</p>
| 1 | 1,057 |
Ajax, PHP, MySQL retrieve data
|
<p>i'm trying to auto retrieve data from mysql server in specific DIV without manual refresh the web page.</p>
<p>My PHP code is:</p>
<pre><code>function lastCodes(){
include('mysql.php');
include('config.php');
echo "<div id='content_data'>";
$get = mysql_query("SELECT * FROM scripts ORDER by date_added DESC");
if(mysql_num_rows($get)>0){
while($row = mysql_fetch_assoc($get)){
$get2 = mysql_query("SELECT * FROM accounts WHERE username = '$row[s_owner]'");
while($red = mysql_fetch_assoc($get2)){
echo "<table>
<tr>
<td width='22px'>";
if(!empty($red['avatar'])){
echo "<center>
<img src='$red[avatar]' style='width: 52px; height: 52px; margin-left: -30px; border: 2px solid #fff;' title='$row[s_owner]'/>
</center>
</td>";
} else {
echo "<td width='22px'>
<center>
<img src='/theme/$tema/icons/empty_avatar.png' style='width: 52px; height: 52px;' title='$row[s_owner]'/>
</center>
</td>";
}
echo "<td>
<a style='font-family: IndexName; color: #000; font-size: 14px; margin-left: 5px;'><b>$row[s_owner]</b> написа <a title='$row[s_name], Категория: $row[s_category].' href='#' style='text-decoration: none;'>нов код</a> <a style='font-family: IndexName; color: #000; font-size: 14px; margin-right: 10px;'>в $row[date_added]</a>
</td>
</tr>
</table>";
}
}
}
echo "</div>";
}
</code></pre>
<p>What should be in my case the jquery/ajax code if I want to retrieve this information in DIV called "content_data" in interval of 5 seconds? Thanks a lot!</p>
| 1 | 1,319 |
PySide: Drag and drop files into QListWidget
|
<p>This is my first entry here so apologies for any newbie mistakes. I've searched both here and Google with no luck before posting.</p>
<p>I want to be able to add images to a QListWidget, using drag and drop from a file browser. Dropping a valid file on the list widget also needs to trigger a function in the main class of my app, and pass it the image path. </p>
<p>I found <a href="https://stackoverflow.com/questions/4151637/pyqt4-drag-and-drop-files-into-qlistwidget">this code</a> that does exactly that, but for PyQt4. Importing QtCore and QtGui from PySide instead of PyQt4 produces a segmentation fault when triggering a drag and drop event. There are no error messages. </p>
<p>I think I've traced this to an old way of handling signals and have tried using the new, more pythonic way described <a href="https://qt-project.org/wiki/Signals_and_Slots_in_PySide" rel="nofollow noreferrer">here</a>. I can't seem to get it working, while still passing a list of URLs between classes however. </p>
<p>Any help would be greatly appreciated!</p>
<pre><code>import sys
import os
from PyQt4 import QtGui, QtCore
class TestListView(QtGui.QListWidget):
def __init__(self, type, parent=None):
super(TestListView, self).__init__(parent)
self.setAcceptDrops(True)
self.setIconSize(QtCore.QSize(72, 72))
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(QtCore.SIGNAL("dropped"), links)
else:
event.ignore()
class MainForm(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
self.view = TestListView(self)
self.connect(self.view, QtCore.SIGNAL("dropped"), self.pictureDropped)
self.setCentralWidget(self.view)
def pictureDropped(self, l):
for url in l:
if os.path.exists(url):
print(url)
icon = QtGui.QIcon(url)
pixmap = icon.pixmap(72, 72)
icon = QtGui.QIcon(pixmap)
item = QtGui.QListWidgetItem(url, self.view)
item.setIcon(icon)
item.setStatusTip(url)
def main():
app = QtGui.QApplication(sys.argv)
form = MainForm()
form.show()
app.exec_()
if __name__ == '__main__':
main()
</code></pre>
| 1 | 1,283 |
Fetch data from mysql database using drop down list and then use search function to filter data from selected drop down list option
|
<p>I want to comebine the use of a drop down list (with filters/options) with a search function (a search bar and a "Ok" button).</p>
<p>When I select a filter/option in the drop down list, as for example "Team". The drop down
list then should be aware of that the list has changed to filter/option "Team".
After this, I use the search function where I input the search term, like "USA" then press
the Ok-button.
Once the Ok-button is pressed, a sql-query like: SELECT * FROM mytable WHERE Team = 'USA';
is generated to fetch all the matched rows in the db "mytable".</p>
<ol>
<li>Select a filter, "Team".</li>
<li>Select a team, "USA".</li>
<li>Fetch matched rows with relevant data from the db mytable.</li>
</ol>
<p>Hope I made myself understood better, thank you all for your time!</p>
<p>This is the code I have:</p>
<pre><code><html>
<head>
<title>AiFind</title>
<link rel="stylesheet" href="Style.css">
<script src="logic.js"></script>
</head>
<body>
<h1>AiFind</h1>
</body>
</html>
<?php
include "connection.php";
$sql = "SELECT * FROM mytable";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .= " WHERE F_ar = '$search_term' ";
$sql .= " OR Postnr = '$search_term' ";
$sql .= " OR Postort = '$search_term' ";
$sql .= " OR Vardgivare = '$search_term' ";
$sql .= " OR Team = '$search_term' ";
$sql .= " OR Orsak = '$search_term' ";
$sql .= " OR Planerat_datum = '$search_term' ";
$sql .= " OR fran = '$search_term' ";
$sql .= " OR AAA_diam = '$search_term'; ";
}
$query = mysql_query($sql) or die(mysql_error());
?>
<form name="Select_filter" method="POST" action="VGR_data_display.php">
<select id="dropdown" name="filter">
<option value=""></option>
<option value="1">ID</option>
<option value="2">Alder</option>
<option value="3">Postnummer</option>
<option value="5">Postort</option>
<option value="6">Vårdgivare</option>
<option value="7">Planerat Datum</option>
<option value="8">Status</option>
<option value="9">AAA_diameter</option>
</select>
</form>
<!--search bar for search term input -->
<form name ="search_form" method="POST" action="VGR_data_display.php">
<input id="search_box" type="text" name="search_box" value="" />
<input id="submit" type ="submit" name ="search" value ="Ok">
</form>
<table style="margin:auto;" id="table" border='1'>
<tr>
<th>ID</th>
<th>F_ar</th>
<th>Postnr</th>
<th>Postort</th>
<th>Vardgivare</th>
<th>Team</th>
<th>Orsak</th>
<th>Planerat_datum</th>
<th>fran</th>
<th>AAA_diam</th>
</tr>
<?php while($row = mysql_fetch_array($query)) { ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['F_ar']; ?></td>
<td><?php echo $row['Postnr']; ?></td>
<td><?php echo $row['Postort']; ?></td>
<td><?php echo $row['Vardgivare']; ?></td>
<td><?php echo $row['Team']; ?></td>
<td><?php echo $row['Orsak']; ?></td>
<td><?php echo $row['Planerat_datum']; ?></td>
<td><?php echo $row['fran']; ?></td>
<td><?php echo $row['AAA_diam']; ?></td>
</tr>
<?php } ?>
</code></pre>
| 1 | 1,773 |
How to use multiple JPA persistence contexts with Spring Data JPA?
|
<p>I need two persistence contexts to manage entities in separate databases. </p>
<p>I am using java based config with spring 4.1.4, hibernate 4.3.7 and spring data 1.2. </p>
<p>Basically, CompanyApplicationContext imports two persistence contexts: PersistenceContext and SharedDbPersistenceContext. Each persistence context with its own data source, transaction manager and entity manager factory. The entities and jpa repositories for each persistence context are present in separate packages and are mentioned in persistence context class files.</p>
<p>I get this error:</p>
<pre><code>Not an managed type: class com.company.shared.model.ClientSetting
</code></pre>
<p>Full exception:</p>
<pre><code>Caused by: java.lang.IllegalArgumentException: Not an managed type: class com.company.shared.model.ClientSetting
at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:219)
</code></pre>
<p>What extra configuration do I need to do this to make it work? Why is each context not scanning and registering entities and repositories properly?</p>
<p>Main application context:</p>
<pre><code>package com.company.config;
@Configuration
@ComponentScan(basePackages
= "com.company"
)
@Import({
PersistenceContext.class,
SharedDbPersistenceContext.class})
public class CompanyApplicationContext extends WebMvcConfigurerAdapter {
}
</code></pre>
<p>Persistence Context:</p>
<pre><code> package com.company.config;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
basePackages = {"com.company.todo.repository"})
public class PersistenceContext {
@Resource
private Environment environment;
@Bean
public DataSource dataSource() {
BoneCPDataSource dataSource = new BoneCPDataSource();
//init data source
return dataSource;
}
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setPackagesToScan("com.company.todo.model");
Properties jpaProperties = new Properties();
//init jpa properties
entityManagerFactoryBean.setJpaProperties(jpaProperties);
return entityManagerFactoryBean;
}
}
</code></pre>
<p>Shared Db Persistence Context:</p>
<pre><code> package com.company.config;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
basePackages = {"com.company.shared.repository"})
public class SharedDbPersistenceContext {
@Resource
private Environment environment;
@Bean
public DataSource sharedDataSource() {
//init and return data source
}
@Bean
public JpaTransactionManager sharedDbTransactionManager() {
//init transaction manager
}
@Bean
public LocalContainerEntityManagerFactoryBean sharedEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(sharedDataSource());
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setPackagesToScan("com.company.shared.model");
Properties jpaProperties = new Properties();
//init jpaProperties
entityManagerFactoryBean.setJpaProperties(jpaProperties);
return entityManagerFactoryBean;
}
}
</code></pre>
<p>Repository:</p>
<pre><code>package com.company.shared.repository;
@Repository
public interface ClientSettingsRepository extends JpaRepository<ClientSetting, Integer> {}
</code></pre>
<p>Entity:</p>
<pre><code>package com.company.shared.model;
@Entity
public class ClientSetting implements Serializable {
//props
}
</code></pre>
<p>Service:</p>
<pre><code>package com.company.shared.service;
@Service
public class DataSourceServiceImpl implements DataSourceService{
@Autowired
ClientSettingsRepository clientSettingsRepository;
@Override
public List<ClientSetting> findClientDataSourceSettings() {
return clientSettingsRepository.findClientDataSourceSettings();
}
}
</code></pre>
| 1 | 1,709 |
Why is Nmap Scripting Engine returning an error?
|
<p>When ever I try to run the following Nmap Command:
<code>nmap -sA -sV -T5 -O -A -v -Pn --script afp-brute,ajp-brute,backorifice-brute,cassandra-brute,cvs-brute,dns-brute,domcon-brute,dpap-brute,drda-brute,ftp-brute,http-adobe-coldfusion-apsa1301,http-affiliate-id,http-apache-negotiation,http-apache-server-status,http-aspnet-debug,http-auth-finder,http-auth,http-avaya-ipoffice-users,http-awstatstotals-exec,http-axis2-dir-traversal,http-backup-finder,http-barracuda-dir-traversal,http-brute,http-cakephp-version,http-chrono,http-cisco-anyconnect,http-coldfusion-subzero,http-comments-displayer,http-config-backup,http-cors,http-cross-domain-policy,http-csrf,http-date,http-default-accounts,http-devframework,http-dlink-backdoor,http-dombased-xss,http-domino-enum-passwords,http-drupal-enum-users,http-drupal-enum,http-enum,http-errors,http-exif-spider,http-favicon,http-feed,http-fetch,http-fileupload-exploiter,http-form-brute,http-form-fuzzer,http-frontpage-login,http-generator,http-git,http-gitweb-projects-enum,http-google-malware,http-grep,http-headers,http-huawei-hg5xx-vuln,http-icloud-findmyiphone,http-icloud-sendmsg,http-iis-short-name-brute,http-iis-webdav-vuln,http-internal-ip-disclosure,http-joomla-brute,http-litespeed-sourcecode-download,http-ls,http-majordomo2-dir-traversal,http-malware-host,http-mcmp,http-method-tamper,http-methods,http-mobileversion-checker,http-ntlm-info,http-open-proxy,http-open-redirect,http-passwd,http-php-version,http-phpmyadmin-dir-traversal,http-phpself-xss,http-proxy-brute,http-put,http-qnap-nas-info,http-referer-checker,http-rfi-spider,http-robots.txt,http-robtex-reverse-ip,http-robtex-shared-ns,http-server-header,http-shellshock,http-sitemap-generator,http-slowloris-check,http-slowloris,http-sql-injection,http-stored-xss,http-svn-enum,http-svn-info,http-title,http-tplink-dir-traversal,http-trace,http-traceroute,http-unsafe-output-escaping,http-useragent-tester,http-userdir-enum,http-vhosts,http-virustotal,http-vlcstreamer-ls,http-vmware-path-vuln,http-vuln-cve2006-3392,http-vuln-cve2009-3960,http-vuln-cve2010-0738,http-vuln-cve2010-2861,http-vuln-cve2011-3192,http-vuln-cve2011-3368,http-vuln-cve2012-1823,http-vuln-cve2013-0156,http-vuln-cve2013-6786,http-vuln-cve2013-7091,http-vuln-cve2014-2126,http-vuln-cve2014-2127,http-vuln-cve2014-2128,http-vuln-cve2014-2129,http-vuln-cve2014-3704,http-vuln-cve2014-8877,http-vuln-cve2015-1427,http-vuln-cve2015-1635,http-vuln-misfortune-cookie,http-vuln-wnr1000-creds,http-waf-detect,http-waf-fingerprint,http-webdav-scan,http-wordpress-brute,http-wordpress-enum,http-wordpress-users,http-xssed,iax2-brute,imap-brute,informix-brute,ip-forwarding,ip-geolocation-geoplugin,ip-geolocation-ipinfodb,ip-geolocation-map-bing,ip-geolocation-map-google,ip-geolocation-map-kml,ip-geolocation-maxmind,ip-https-discover,ipidseq,ipmi-brute,ipmi-cipher-zero,ipmi-version,ipv6-multicast-mld-list,ipv6-node-info,ipv6-ra-flood,irc-brute,irc-sasl-brute,iscsi-brute,ldap-brute,membase-brute,metasploit-msgrpc-brute,metasploit-xmlrpc-brute,mikrotik-routeros-brute,mmouse-brute,mongodb-brute,ms-sql-brute,mysql-brute,nessus-brute,nessus-xmlrpc-brute,netbus-brute,nexpose-brute,nje-node-brute,nje-pass-brute,nping-brute,omp2-brute,openvas-otp-brute,oracle-brute,oracle-sid-brute,pcanywhere-brute,pgsql-brute,pop3-brute,redis-brute,rexec-brute,rlogin-brute,rpcap-brute,rsync-brute,rtsp-url-brute,sip-brute,smb-brute,smtp-brute,snmp-brute,socks-brute,svn-brute,targets-asn,targets-ipv6-map4to6,targets-ipv6-multicast-echo,targets-ipv6-multicast-invalid-dst,targets-ipv6-multicast-mld,targets-ipv6-multicast-slaac,targets-ipv6-wordlist,targets-sniffer,targets-traceroute,targets-xml,telnet-brute,telnet-encryption,telnet-ntlm-info,traceroute-geolocation,tso-brute,unusual-port,vmauthd-brute,vnc-brute,whois-domain,whois-ip,xmpp-brute, 192.168.1.226</code></p>
<p>I get this error:</p>
<pre><code> NSE: failed to initialize the script engine:
/usr/local/bin/../share/nmap/nse_main.lua:840: assertion failed!
stack traceback:
[C]: in function 'assert'
/usr/local/bin/../share/nmap/nse_main.lua:840: in local 'get_chosen_scripts'
/usr/local/bin/../share/nmap/nse_main.lua:1271: in main chunk
[C]: in ?
QUITTING!
</code></pre>
<p>Why could this be? I have never had any problem with this before. This is the newest verison of nmap with all excesories installed as well. I am running it on mac osx and it was installed with homebrew.</p>
| 1 | 2,003 |
Can I use parent-child relationships on Kibana?
|
<p>On a relational DB, I have two tables connected by a foreign key, on a typical one-to-many relationship. I would like to translate this schema into ElasticSearch, so I researched and found two options: the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/1.3/mapping-nested-type.html" rel="noreferrer">nested</a> and <a href="https://www.elastic.co/guide/en/elasticsearch" rel="noreferrer">parent-child</a>. My ultimate goal was to visualize this dataset in Kibana 4.</p>
<p>Parent-child seemed the most adequate one, so I'll describe the steps that I followed, based on the official <a href="https://www.elastic.co/guide/en/elasticsearch/guide/current/index.html" rel="noreferrer">ES documentation</a> and a few examples I found on the web.</p>
<pre><code> curl -XPUT http://server:port/accident_struct -d '
{
"mappings" : {
"event" : {
},
"details": {
"_parent": {
"type": "event"
} ,
"properties" : {
}
}
}
}
';
</code></pre>
<p>here I create the index accident_struct, which contains two types (corresponding to the two relational tables): event and details.</p>
<p>Event is the parent, thus each document of details has an event associated to it.</p>
<p>Then I upload the documents using the bulk API. For event:</p>
<pre><code>{"index":{"_index":"accident_struct","_type":"event","_id":"17f14c32-53ca-4671-b959-cf47e81cf55c"}}
{values here...}
</code></pre>
<p>And for details:</p>
<pre><code>{"index":{"_index":"accident_struct","_type":"details","_id": "1", "_parent": "039c7e18-a24f-402d-b2c8-e5d36b8ad220" }}
</code></pre>
<p>The event does not know anything about children, but each child (details) needs to set its parent. In the ES documentation I see the parent being set using "parent", while in other examples I see it using "_parent". I wonder what is the correct option (although at this point, none works for me).</p>
<p>The requests are successfully completed and I can see that the number of documents contained in the index corresponds to the sum of events + types. </p>
<p>I can also query parents for children and children for parents, on ES. For example:</p>
<pre><code>curl -XPOST host:port/accident_struct/details/_search?pretty -d '{
"query" : {
"has_parent" : {
"type" : "event",
"query" : {
"match_all" : {}
}
}
}
}'
</code></pre>
<p>After setting the index on Kibana, I am able to list all the fields from parent and child. However, if I go to the "discover" tab, only the parent fields are listed.</p>
<p>If I uncheck a box that reads "hide missing fields", the fields from the child documents are shown as grey out, along with an error message (see image)</p>
<p><img src="https://i.stack.imgur.com/JjVl9.png" alt="enter image description here"></p>
<p>Am I doing something wrong or is the parent-child not supported in Kibana4? And if it is not supported, what would be the best alternative to represent this type of relationship?</p>
| 1 | 1,046 |
Why is XMLHttpRequest readystate not equal to 4?
|
<p>I'm learning AJAX for the first time and I'm trying to create a simple application that calculates the grade a person needs to get on their final exam based on their previous assessment results. </p>
<p>The user inputs their grades into the form and then using ajax I calculate the response in response.php which should then be output in the callback function in the div with ajax as its id. </p>
<p>For some reason the xhr.readystate property is never reaching 4 so the response is never generated. Can anybody see what I'm doing wrong?</p>
<p>Please bear in mind I'm only learning... </p>
<p>index.php</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Grade Calculator</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<script>
function sendAjax() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
} else {
document.getElementById('ajax').innerHTML = document.write('There was a problem');
}
};
xhr.open("GET","response.php");
xhr.send();
document.getElementById('gradeForm').style.display = "none";
document.write(xhr.readyState);
}
</script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div>
</div>
</div>
<div class="container">
<div class="starter-template">
<h1>Bootstrap starter template</h1><br>
<form action="index.php" method="get" id="gradeForm">
<div class="form-group">
<label for="currentGrade">What is your current Grade</label>
<input type="text" name="currentGrade"><br>
</div>
<div class="form-group">
<label for="targetGrade">What is your target Grade</label>
<input type="text" name="targetGrade"><br>
</div>
<div class="form-group">
<label for="finalWorth">What is your final worth?</label>
<input type="text" name="finalWorth"><br>
</div>
<button type="submit" class="btn btn-default" onclick="sendAjax()">Submit</button>
</form>
<div id="ajax">
</div>
</div>
</div><!-- /.container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</body>
</html>
</code></pre>
<p>Here is response.php </p>
<pre><code><?php
$currentGrade = $_GET['currentGrade'];
$targetGrade = $_GET['targetGrade'];
$finalWorth = $_GET['finalWorth'];
$neededMark = $currentGrade - $targetGrade;
$neededMark = $neededMark / $finalWorth;
$neededMark = $neededMark * 100;
$neededMark = round($neededMark);
if(isset($currentGrade, $targetGrade,$finalWorth)) {
echo $neededMark;
}
?>
</code></pre>
| 1 | 2,598 |
Cannot resolve scoped service dbcontext from root provider
|
<p>I have created an API Logging middleware to log request to DB and to Azure Microsoft insight however for some reason the Dependency Injection for the Database context is not found (gives cannot resolve scoped service from root provider).</p>
<p>API Logging MiddleWare</p>
<pre><code>public class APILoggingMiddleware
{
private readonly TelemetryClient _telemetry;
private readonly ILogger _logger;
private readonly RequestDelegate _next;
private APIsAuditContext db;
public static IConfiguration _configuration;
public APILoggingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, TelemetryClient telemetry, IConfiguration configuration, APIsAuditContext dbContext)
{
_configuration = configuration;
_telemetry = telemetry;
_next = next;
_logger = loggerFactory.CreateLogger<APILoggingMiddleware>();
db = dbContext;
}
//static class to simplify adding the middleware to the application’s pipeline
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
finally
{
Task logReq = logRequest(context);
Task lodRes = logResponse(context);
}
}
}
</code></pre>
<p>DB Context</p>
<pre><code>public class APIsAuditContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
public APIsAuditContext(DbContextOptions<APIsAuditContext> options) : base(options) { }
public DbSet<APIsRequestsAudit> APIsRequestsAudits { get; set; }
}
</code></pre>
<p>Startup</p>
<pre><code> public class Startup
{
public IConfiguration _configuration { get; }
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<APIsAuditContext>(options => options.UseSqlServer(_configuration["ConnectionStrings:APIAuditConnection"]));
services.AddApplicationInsightsTelemetry();
services.AddControllers();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//Pipeline to API Logging
app.UseRequestResponseLogging();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
</code></pre>
<p>Can someone help please?</p>
| 1 | 1,088 |
How to test if a .txt file is already open by anyone?
|
<p>I am trying to test if a .txt or .ini file is open already by anyone. I have several versions of IsFileOpen. Here is one taken directly from <a href="http://www.cpearson.com/excel/ISFILEOPEN.ASPX" rel="nofollow noreferrer">http://www.cpearson.com/excel/ISFILEOPEN.ASPX</a></p>
<pre><code>Option Explicit
Option Compare Text
Public Function isfileopen_test(FileName As String, _
Optional ResultOnBadFile As Variant) As Variant
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' IsFileOpen_test
' This function determines whether a the file named by FileName is
' open by another process. The fuction returns True if the file is open
' or False if the file is not open. If the file named by FileName does
' not exist or if FileName is not a valid file name, the result returned
' if equal to the value of ResultOnBadFile if that parameter is provided.xd
' If ResultOnBadFile is not passed in, and FileName does not exist or
' is an invalid file name, the result is False.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim FileNum As Integer
Dim ErrNum As Integer
Dim V As Variant
On Error Resume Next
''''''''''''''''''''''''''''''''''''''''''''
' If we were passed in an empty string,
' there is no file to test so return FALSE.
''''''''''''''''''''''''''''''''''''''''''''
If VBA.Trim(FileName) = vbNullString Then
If IsMissing(ResultOnBadFile) = True Then
isfileopen_test = False
Else
isfileopen_test = ResultOnBadFile
End If
Exit Function
End If
''''''''''''''''''''''''''''''''''''''''''''
' if the file doesn't exist, it isn't open
' so get out now
''''''''''''''''''''''''''''''''''''''''''''
V = Dir(FileName, vbNormal)
If IsError(V) = True Then
' syntactically bad file name
If IsMissing(ResultOnBadFile) = True Then
isfileopen_test = False
Else
isfileopen_test = ResultOnBadFile
End If
Exit Function
ElseIf V = vbNullString Then
' file doesn't exist.
If IsMissing(ResultOnBadFile) = True Then
isfileopen_test = False
Else
isfileopen_test = ResultOnBadFile
End If
Exit Function
End If
FileNum = FreeFile()
'''''''''''''''''''''''''''''''''''''''
' Attempt to open the file and lock it.
'''''''''''''''''''''''''''''''''''''''
Err.Clear
Open FileName For Input Lock Read As #FileNum
ErrNum = Err.Number
''''''''''''''''''''
' Close the file.
''''''''''''''''''''
Close FileNum
On Error GoTo 0
''''''''''''''''''''''''''''''''''''''
' Check to see which error occurred.
''''''''''''''''''''''''''''''''''''''
Select Case ErrNum
Case 0
''''''''''''''''''''''''''''''''''''''''''''
' No error occurred.
' File is NOT already open by another user.
''''''''''''''''''''''''''''''''''''''''''''
isfileopen_test = False
Case 70
''''''''''''''''''''''''''''''''''''''''''''
' Error number for "Permission Denied."
' File is already opened by another user.
''''''''''''''''''''''''''''''''''''''''''''
isfileopen_test = True
Case Else
''''''''''''''''''''''''''''''''''''''''''''
' Another error occurred. Assume open.
''''''''''''''''''''''''''''''''''''''''''''
isfileopen_test = True
End Select
End Function
</code></pre>
<p>I need to do this via VBA. I can't get it to work for a .txt or .ini file. How can I check if a txt or ini file is already open by someone on the network?</p>
<p>Edit: It returns false for txt and ini files whether they are open or not.</p>
<p>If you are so inclined, I am attempting to build a distributive computing system on a clients network. I've never done this before and I am looking to keep it as simple as possible, so I was thinking of communicating via txt files. MSMQ looks good, but it looks like a long learning curve. I've already read all of the posts on stackoverflow regarding distributive computing.</p>
| 1 | 1,300 |
Post Multiple Data from View to Controller MVC
|
<p>I want to post quantity property to Controller (It's an edit action). I'm editing OrderedProductSet which is connected with ProductSet in my SQL Database (I get the name and price from there). How to pass multiple data from the view to controller? How to write method in controller class to receive the data (I'm asking about method arguments in this specific case).</p>
<p>My view:</p>
<pre><code>@model Shop.Models.ProductViewModel@{
ViewBag.Title = "Edycja zamówienia";
}
<h2>Edycja zamówienie</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<table class="table">
<tr>
<th>
<b>Nazwa produktu</b>
</th>
<th>
<b>Cena</b>
</th>
<th>
<b>Ilość</b>
</th>
<th></th>
</tr>
@foreach (var item in Model.orderedProductSet)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.ProduktSet.name)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProduktSet.price)
</td>
<td>
@Html.EditorFor(model => item.quantity, new { htmlAttributes = new { @class = "form-control" } })
</td>
</tr>
}
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Potwierdź zmiany" class="btn btn-default" />
</div>
</div>
}
<div>
@Html.ActionLink("Powrót", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
</code></pre>
<p>My model (in separated classes of course):</p>
<pre><code> public class ProductViewModel
{
public OrderSet orderSet { get; set; }
public IEnumerable<OrderedProductSet> orderedProduktSet { get; set; }
}
public partial class OrderedProduktSet
{
public int orderNumber{ get; set; }
public int productNumber { get; set; }
public int ilosc { get; set; }
public virtual ProduktSet ProduktSet { get; set; }
public virtual OrderSet OrderSet { get; set; }
}
</code></pre>
| 1 | 1,083 |
JPA dynamic criteria-api query
|
<p>I wonder if there is a generic way to use the criteria api in combination with a little more complex model?</p>
<p>I have an entity class that has one-to-one relationships to other entities. My service wrapper that does the database query via the criteria api gets the parameters from front end to figure out pagination, sorting and filtering.</p>
<p>Entities</p>
<pre><code>@Entity
public class Person implements Serializable {
@Id
private Long id;
private String name;
private String givenName;
@Temporal(TemporalType.DATE)
private Date birthdate;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "INFORMATION_ID")
private Information information;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "ADDRESS_ID")
private Address address;
...
}
</code></pre>
<pre><code>@Entity
public class Information implements Serializable {
@Id
private Long id;
private String detail;
...
}
</code></pre>
<pre><code>@Entity
public class Address implements Serializable {
@Id
private Long id;
private String street;
private String city;
...
}
</code></pre>
<p>Service</p>
<pre><code>@Stateless
public class PersonService {
@PersistenceContext(unitName = "ProblemGenericDatatableFilterPU")
private EntityManager em;
public List<Person> findAllPersons222(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Person> criteriaQuery = builder.createQuery(Person.class);
Root<Person> rootPerson = criteriaQuery.from(Person.class);
Join<Person, Information> joinPersonInformation = rootPerson.join(Person_.information);
Join<Person, Address> joinPersonAddress = rootPerson.join(Person_.address);
// select
criteriaQuery.select(rootPerson);
// filter
List<Predicate> allPredicates = new ArrayList<>();
for(Entry<String, Object> currentEntry : filters.entrySet()) {
Predicate currentPredicate;
if(currentEntry.getKey().startsWith("information_")) {
currentPredicate = builder.like(
builder.lower(joinPersonInformation.<String>get(currentEntry.getKey())),
builder.lower(builder.literal(String.valueOf(currentEntry.getValue())))
);
}
else if(currentEntry.getKey().startsWith("address_")) {
currentPredicate = builder.like(
builder.lower(joinPersonAddress.<String>get(currentEntry.getKey())),
builder.lower(builder.literal(String.valueOf(currentEntry.getValue())))
);
}
else {
currentPredicate = builder.like(
builder.lower(rootPerson.<String>get(currentEntry.getKey())),
builder.lower(builder.literal(String.valueOf(currentEntry.getValue())))
);
}
allPredicates.add(currentPredicate);
}
criteriaQuery.where(builder.and(allPredicates.toArray(new Predicate[0])));
// order
if(sortField != null && !sortField.isEmpty()) {
Order orderBy;
if(sortField.startsWith("information_")) {
orderBy = (sortOrder == SortOrder.DESCENDING
? builder.desc(joinPersonInformation.get(sortField))
: builder.asc(joinPersonInformation.get(sortField)));
}
else if(sortField.startsWith("address_")) {
orderBy = (sortOrder == SortOrder.DESCENDING
? builder.desc(joinPersonAddress.get(sortField))
: builder.asc(joinPersonAddress.get(sortField)));
}
else {
orderBy = (sortOrder == SortOrder.DESCENDING
? builder.desc(rootPerson.get(sortField))
: builder.asc(rootPerson.get(sortField)));
}
criteriaQuery.orderBy(orderBy);
}
Query query = em.createQuery(criteriaQuery);
// pagination
query.setFirstResult(first);
query.setMaxResults(pageSize);
return query.getResultList();
}
}
</code></pre>
<p>I need to do a distinction of cases for filtering and sorting depending on the root/join on which I am accessing the property. Plus I need to use a naming convention in the facelet. The same goes for the <em>count</em>-query except for sorting.</p>
<p>Now I ask myself whether there is some "dot-notation" or anything which makes the case dispensable. In e. g. native SQL I would do something like create a subquery and select all alias values from the inner projection (<code>select * from (select person.name as name, address.street as street, ...) where name = ... and street like ...</code>).</p>
<p>I would be grateful for any advice.</p>
| 1 | 2,064 |
Symfony; SQLSTATE[HY000] [2002] No such file or directory while using 127.0.0.1 as database_host
|
<p>The full error is <code>Doctrine\DBAL\Exception\ConnectionException: An exception occurred in driver: SQLSTATE[HY000] [2002] No such file or directory in /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php on line 113</code>, but that's too long for the title.</p>
<p>I'm trying to set up a Symfony project locally, but I'm struggling to get the database connection to work. My <code>parameters.yml</code> looks as follows</p>
<pre><code>parameters:
database_host: 127.0.0.1
database_port: 3306
database_name: database_name
database_user: username
database_password: password
</code></pre>
<p>I've been googling this issue a lot and most people seem to solve the issue by changing <code>database_host</code> from <code>localhost</code> to <code>127.0.0.1</code>, but this doesn't work for me. The app itself runs via Docker, but I've set up the database connection once via Brew and once with a MySQL server for Mac. In both cases I can connect via the command line and with SequelPro/TablePlus, but whenever I try to access the website through the browser I get the "No such file or directory" error.</p>
<p>I've also tried multiple ways of setting up a Docker MySQL container, but can't get it to work. My <code>docker-compose.yml</code> looks like this;</p>
<pre><code>nginx:
build: nginx
ports:
- "8080:80"
links:
- php
volumes:
- ../:/app
php:
build: php-fpm
volumes:
- ../:/app
working_dir: /app
extra_hosts:
- "site.dev: 172.17.0.1"
services:
db:
image: mysql:5.7
restart: always
environment:
MYSQL_DATABASE: 'database_name'
MYSQL_USER: 'username'
MYSQL_PASSWORD: 'password'
MYSQL_ROOT_PASSWORD: 'password_root'
ports:
- '3306:3306'
expose:
- '3306'
volumes:
- my-db:/var/lib/mysql
</code></pre>
<p>But whenever I run <code>docker-compose up -d</code> I get the error <code>Unsupported config option for services: 'db'</code>.</p>
<p>Another attempt was adding</p>
<pre><code>mysql:
image: mysql:latest
volumes:
- mysql_data:/var/lib/mysql
environment:
- MYSQL_ROOT_PASSWORD='password'
- MYSQL_DATABASE='database_name'
- MYSQL_USER='username'
- MYSQL_PASSWORD='password'
</code></pre>
<p>To the docker-compose file, and while it does build the mysql image, I can't seem to connect to it with SequelPro/TablePlus. I ran <code>docker-inspect</code> on the container to get the IP (172.17.0.3), but can't seem to get access to it. I can <code>exec</code> into it, login using <code>mysql -u root</code> and create the required user and database, but then I'm still struggling to actually connect to it.</p>
<p>Running <code>docker ps</code> does show the sql container running btw;</p>
<pre><code>CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b6de6030791d docker_nginx "nginx -g 'daemon of…" 19 minutes ago Up 14 minutes 0.0.0.0:8080->80/tcp docker_nginx_1
f26b832bb005 docker_php "docker-php-entrypoi…" 19 minutes ago Up 14 minutes 9000/tcp docker_php_1
6c2a9e657435 mysql:latest "docker-entrypoint.s…" 19 minutes ago Up 14 minutes 3306/tcp, 33060/tcp docker_mysql_1
</code></pre>
<p>I also thought it might be an issue with changes to the <code>parameters.yml</code> file not properly syncing with the container as I'm using Mac (at my old workplace we had to use docker-sync to make sync changes between our dev environment and the actual container), but when inspecting the container itself using <code>exec</code> I can see the changes in the <code>parameters.yml</code> file.</p>
<p>Could the issue be it trying to connect to a mysql server running outside the Docker container? I'm still very new to Docker so I wouldn't be surprised if that's the mistake. Any tips are appreciated 'cause I'm at a dead end.</p>
| 1 | 1,524 |
<access origin="http://*" launch-external="yes" /> not working for iOS
|
<p>launch-external does not seems to work for iOS. but it works perfectly for android.</p>
<p>I am looking for a 'launch-external' equivalent for iOS, i am using cardova (version 3.7.0) and phoneGap online build tool.</p>
<p>below is my config.xml </p>
<pre><code><widget xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0" id="com.something.something" version="1.0.3">
<name>something</name>
<description>
something
</description>
<author href="http://something.com" email="something@something.com">Something</author>
<content src="index.html"/>
<preference name="permissions" value="none"/>
<preference name="orientation" value="default"/>
<preference name="target-device" value="universal"/>
<preference name="fullscreen" value="false"/>
<preference name="webviewbounce" value="false"/>
<preference name="prerendered-icon" value="true"/>
<preference name="stay-in-webview" value="false"/>
<preference name="ios-statusbarstyle" value="black-opaque"/>
<preference name="detect-data-types" value="true"/>
<preference name="exit-on-suspend" value="true"/>
<preference name="show-splash-screen-spinner" value="true"/>
<preference name="auto-hide-splash-screen" value="true"/>
<preference name="disable-cursor" value="false"/>
<preference name="android-minSdkVersion" value="7"/>
<preference name="android-installLocation" value="auto"/>
<preference name="DisallowOverscroll" value="true" />
<gap:plugin name="org.apache.cordova.console"/>
<gap:plugin name="org.apache.cordova.device"/>
<gap:plugin name="org.apache.cordova.dialogs"/>
<gap:plugin name="org.apache.cordova.geolocation"/>
<gap:plugin name="org.apache.cordova.globalization"/>
<gap:plugin name="org.apache.cordova.inappbrowser"/>
<gap:plugin name="org.apache.cordova.network-information"/>
<gap:plugin name="org.apache.cordova.vibration"/>
<gap:plugin name="org.apache.cordova.statusbar"/>
<gap:plugin name="org.apache.cordova.splashscreen"/>
<icon src="icon.png"/>
<icon src="res/icon/android/icon-36-ldpi.png" gap:platform="android" gap:qualifier="ldpi"/>
<icon src="res/icon/android/icon-48-mdpi.png" gap:platform="android" gap:qualifier="mdpi"/>
<icon src="res/icon/android/icon-72-hdpi.png" gap:platform="android" gap:qualifier="hdpi"/>
<icon src="res/icon/android/icon-96-xhdpi.png" gap:platform="android" gap:qualifier="xhdpi"/>
<icon src="res/icon/ios/icon-57.png" gap:platform="ios" width="57" height="57"/>
<icon src="res/icon/ios/icon-72.png" gap:platform="ios" width="72" height="72"/>
<icon src="res/icon/ios/icon-57-2x.png" gap:platform="ios" width="114" height="114"/>
<icon src="res/icon/ios/icon-72-2x.png" gap:platform="ios" width="144" height="144"/>
<!-- iPhone 6 / 6+ -->
<icon src="res/icon/ios/icon-60@3x.png" gap:platform="ios" width="180" height="180" />
<!-- iPhone / iPod Touch -->
<icon src="res/icon/ios/icon-60.png" gap:platform="ios" width="60" height="60" />
<icon src="res/icon/ios/icon-60@2x.png" gap:platform="ios" width="120" height="120" />
<!-- iPad -->
<icon src="res/icon/ios/icon-76.png" gap:platform="ios" width="76" height="76" />
<icon src="res/icon/ios/icon-76@2x.png" gap:platform="ios" width="152" height="152" />
<!-- Settings Icon -->
<!--
<icon src="res/icon/ios/icon-small.png" gap:platform="ios" width="29" height="29" />
<icon src="res/icon/ios/icon-small@2x.png" gap:platform="ios" width="58" height="58" />
-->
<!-- Spotlight Icon -->
<!--
<icon src="res/icon/ios/icon-40.png" gap:platform="ios" width="40" height="40" />
<icon src="res/icon/ios/icon-40@2x.png" gap:platform="ios" width="80" height="80" />
-->
<platform name="ios">
<!-- images are determined by width and height. The following are supported -->
<splash src="res/screen/ios/Default~iphone.png" width="320" height="480"/>
<splash src="res/screen/ios/Default@2x~iphone.png" width="640" height="960"/>
<splash src="res/screen/ios/Default-Portrait~ipad.png" width="768" height="1024"/>
<splash src="res/screen/ios/Default-Landscape~ipad.png" width="1024" height="768"/>
<splash src="res/screen/ios/Default-568h@2x~iphone.png" width="640" height="1136"/>
</platform>
<access origin="sms:*" launch-external="yes" />
<access origin="geo:*" launch-external="yes" />
<access origin="mailto:*" launch-external="yes" />
<access origin="tel:*" launch-external="yes" />
<access origin="http://*" launch-external="yes" />
<plugin name="cordova-plugin-whitelist"/>
<allow-intent href="http://*/*"/>
<allow-intent href="https://*/*"/>
<allow-intent href="tel:*"/>
<allow-intent href="sms:*"/>
<allow-intent href="mailto:*"/>
<allow-intent href="geo:*"/>
<platform name="android">
<allow-intent href="market:*"/>
</platform>
<platform name="ios">
<allow-intent href="itms:*"/>
<allow-intent href="itms-apps:*"/>
</platform>
</widget>
</code></pre>
<p>I am using location.href in index.html to open the url in separte browser. This is working in Android as expected but not in iOS</p>
| 1 | 2,320 |
Update MSI package via Wix bootstrapper
|
<p>I have wix bootstapper which includes 4 components: tree exe packages and one msi package. I want to do major update of msi package using bootstrapper below (only main code):</p>
<pre><code><Bundle Name="$(var.Name)" Version="$(var.Version)" Manufacturer="$(var.Manufacture)" UpgradeCode="$(var.UpgradCode)" Copyright="$(var.Copyright)">
....
<Chain>
<!-- TODO: Define the list of chained packages. -->
<PackageGroupRef Id="NetFx4Full"/>
<PackageGroupRef Id="PostgreSQL"/>
<PackageGroupRef Id="AdobeReader"/>
<PackageGroupRef Id="Application"/>
</Chain>
....
<PackageGroup Id="Application">
<MsiPackage Id="MyApplication"
SourceFile=".\MSI_File\application.msi"
DisplayInternalUI="yes"
Permanent="no"
Vital="yes"
Visible="no"/>
others packages...
</PackageGroup>
</code></pre>
<p>and msi code:</p>
<pre><code><Product Id="*"
Name="$(var.Name)"
Language="$(var.InstallerLanguage)"
Version="$(var.Version)"
UpgradeCode="$(var.UpgradeCode)"
Manufacturer="$(var.Manufacture)">
<Package Description="$(var.PackageDescritpion)"
InstallerVersion="200"
Compressed="yes"
InstallScope="perMachine"
InstallPrivileges="elevated"
Platform="x64"/>
<Media Id="1" Cabinet="contents.cab" EmbedCab="yes" CompressionLevel="high"/>
<Directory Id="TARGETDIR" Name="SourceDir">
</Directory>
<Feature Id="Complete"
Level="1"
ConfigurableDirectory="INSTALLDIR">
<ComponentRef Id="Licence"/>
<ComponentRef Id="StartMenuFoldersComponent"/>
<ComponentRef Id="DatabaseConfigFolder"/>
<ComponentGroupRef Id="BinaryFileGroup"/>
<ComponentGroupRef Id="DatabaseConfigFileGroup"/>
<ComponentRef Id="ApplicationConfigFolder"/>
<ComponentRef Id="RemoveFolderOnUninstall"/>
</Feature>
<!-- Custom actions-->
.....
<InstallExecuteSequence>
<RemoveExistingProducts After="InstallValidate"/>
<!--Other custom actions-->
......
</InstallExecuteSequence>
</code></pre>
<p>To build my update msi and bootstrapp I set greater (the same for msi and bootstrapp) product version, for example old version has 1.0.0.0 and newer has 1.0.1.0. Upgrade code as a WIX documentation says remains unchanged. After run my update installer the new version of msi is not installig, in install directory still are old files. Does anyone know what I do wrong?</p>
<p>@Edit
Also I tried by adding MajorUpgrade element but after that bootstrapper doesn't start MSI:</p>
<pre><code><Media Id="1" Cabinet="contents.cab" EmbedCab="yes" CompressionLevel="high"/>
<MajorUpgrade Schedule="afterInstallInitialize" DowngradeErrorMessage="A later version of [ProductName] is already installed. Setup will now exit."/>
<Directory Id="TARGETDIR" Name="SourceDir"/>
</code></pre>
<p>@Edit
Bootstrapper logs: <a href="http://wklej.to/Msczq" rel="nofollow">http://wklej.to/Msczq</a></p>
| 1 | 1,220 |
Display:inline for creating a horizontal navigation bar not working
|
<p>I am relatively new to <code>CSS</code> and I'm having trouble getting my navigation bar aligned horizontally. I tried the display:inline; function with no success. When using the float:left function, I get all the li aligned horizontally, but in this case, I cannot center it on the page. Also the margin:0 auto; does not do it in this case.</p>
<p>The navigation bar is created via an ul inside a DIV, which is also contained inside a "wrapper div".</p>
<p>Is the problem linked to the various ID selectors used and the nesting of the various elements? </p>
<p>Please find the jsfiddle below for visualisation:</p>
<h2><a href="http://jsfiddle.net/Kingleoric/om4692f3/" rel="nofollow">JsFiddle</a></h2>
<p>Any help would be greatly appreciated :)</p>
<p>Thanks, Danny</p>
<p><strong>HTML</strong></p>
<pre><code><div id="wrapper">
<div id="navigation">
<ul>
<li><a href="#">HOME</a></li>
</ul>
<ul>
<li><a href="gallery.html" class="dropdown">GALLERY</a></li>
<li class="sublinks">
<a href="#">PORTRAITURE</a>
<a href="#">NATURE</a>
</li>
</ul>
<ul>
<li><a href="blog.html">BLOG</a></li>
</ul>
<ul>
<li><a href="about.html">ABOUT</a></li>
</ul>
<ul>
<li><a href="ModelReleaseForm.pdf" target="_blank">MODEL RELEASE</a></li>
</ul>
<ul>
<li><a href="contact.html">CONTACT</a></li>
</ul>
</div>
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code> ul {
list-style:none;
margin:0px 5px;}
ul li {
display:inline;}
ul li a {
color:#ffffff;
background:#09F;
padding:0px 0px;
margin:0 auto;
font-weight:bold;
font-size:14px;
font-family:'sans open', Arial, Helvetica, sans-serif;
text-decoration:none;
display:block;
width:auto;
height:40px;
line-height:15px;
text-align:center;
-webkit-border-radius:5px;
-moz-border-radius:5px;
border: 1px solid #560E00;}
ul li a:hover {
color:#cccccc;
background:#06F;
font-weight:bold;
text-decoration:none;
display:block;
width:auto;
text-align:center;
-webkit-border-radius:5px;
-moz-border-radius:5px;
border: 1px solid #000000;}
ul li.sublinks a {
color:#000000;
background:#f6f6f6;
border-bottom:1px solid #cccccc;
font-weight:normal;
text-decoration:none;
display:block;
width:100px;
text-align:center;
margin-top:2px;}
ul li.sublinks a:hover {
color:#000000;
background:#FFEFC6;
font-weight:normal;
text-decoration:none;
display:block;
width:100px;
text-align:center;}
ul li.sublinks {
display:none;}
</code></pre>
| 1 | 1,269 |
prevent php mail sent going to spam gmail
|
<p>this is my complete code that I use to send emails from a contact form on a website.
Despite all the best practices used (headers etc), the results are:</p>
<p>1) the confirmation email to users goes in gmail spam every time and it is flaged as phishing</p>
<p>2) the admin email is flagged as phishing</p>
<p>Could someone help me? Thank you!</p>
<pre><code><?
// -----------------------------------------------------------------------------
// Website info
$SiteName = "www.example.com";
$SiteWork = "Enterprise Name";
$SiteMin = "Ent. name";
$SiteEmail = "info@example.com";
$SecondaryEmail = "admin@example.com";
$ThankYouMessage = "$SiteMin - Message sent!";
$SiteTel = "Tel (+39) 0XX.XXXXXXX";
$SiteFax = "Fax (+39) 0XX.XXXXXXX";
$SiteSocial = "#...";
$SiteAddress = "...";
// -----------------------------------------------------------------------------
// Retrieve contents
$UserSubject = $_POST['UserSubject'];
$UserName = $_POST['UserName'];
$UserCity = $_POST['UserCity'];
$UserEmail = $_POST['UserEmail'];
$UserComments = $_POST['UserComments'];
$UserAuth = $_POST['UserAuth'];
// -----------------------------------------------------------------------------
// Set up user message
$UserMessage = "<html><head></head><body>";
$UserMessage .= "<font size='6px'>";
$UserMessage .= "Ciao $UserName,";
$UserMessage .= "</font><br><br>";
$UserMessage .= "<font size='4px'>";
$UserMessage .= "abbiamo ricevuto il tuo messaggio.<br>";
$UserMessage .= "Grazie per averci scritto, ti risponderemo al più presto.<br><br>";
$UserMessage .= "</font><br>";
$UserMessage .= "<img src='http://www.piazzaimpianti.it/img/logo.svg' width='60px'><br><br>";
$UserMessage .= "$SiteWork $SiteAddress<br>";
$UserMessage .= "$SiteTel - $SiteName - $SiteSocial<br>";
$UserMessage .= "$SiteName<br>";
$UserMessage .= "</body></html>";
$UserHeaders = "From: $SiteEmail\r\n";
$UserHeaders .= "Reply-To: $SiteEmail\r\n";
$UserHeaders .= "Return-Path: $SiteEmail\r\n";
$UserHeaders .= "CC:\r\n";
$UserHeaders .= "BCC:\r\n";
$UserHeaders .= "MIME-Version: 1.0\r\n";
$UserHeaders .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$UserHeaders .= "X-Priority: 3\r\n";
$UserHeaders .= "X-Mailer: PHP". phpversion() ."\r\n";
// -----------------------------------------------------------------------------
// Set up admin message
$AdminMessage = "Messaggio:\n";
$AdminMessage .= "\n";
$AdminMessage .= "$UserComments\n";
$AdminMessage .= "\n\n";
$AdminMessage .= "-------------------------------------------------\n";
$AdminMessage .= "Dati utente:\n";
$AdminMessage .= "-------------------------------------------------\n";
$AdminMessage .= "$UserName \n";
$AdminMessage .= "$UserEmail \n";
$AdminMessage .= "$UserCity \n";
$AdminMessage .= "-------------------------------------------------\n";
$AdminMessage .= "Autorizzi il trattamento dei dati ai sensi del D.lgs.196/03 (*)? $UserAuth \n";
$AdminMessage .= "-------------------------------------------------\n";
$AdminMessage .= "Puoi rispondere al messaggio di $UserName\n";
$AdminMessage .= "scrivendo all'indirizzo: $UserEmail\n\n";
// -----------------------------------------------------------------------------
// Send confirmation to contact page
$array['Sent'] = array('payload' => 'sent');
echo json_encode($array);
// -----------------------------------------------------------------------------
// Send the emails
// confirmation email to user
mail($UserEmail, $ThankYouMessage, $UserMessage, $UserHeaders);
// email to admin
mail("$SiteEmail", "$UserSubject", $AdminMessage, "From: $UserEmail");
?>
</code></pre>
| 1 | 1,418 |
C#.NET Using isAuthenticated
|
<p>Im using the MVC format to create a website. Right now all it does is manage users from an SQL server. What i'm trying to do now is have the user log in and then be able to manage the Users. From the Login page it should go to the Index of the Account but I only want this page to be viewable by authenticated users. It works fine if I: </p>
<p>1)set the function in the controler to [AllowAnonymous] (This is not what i want)</p>
<p>2)Allow Windows Authentication (Which is not what I want because once I deploy, it'll be on the web)</p>
<p>It really just boils down to how do I authenticate a user and then have that authentication persist. </p>
<p>Here is the login page:</p>
<pre><code>@model myWebsite.Models.LoginModel
@{
ViewBag.Title = "Login";
ViewBag.ReturnUrl = "Index";
}
<h2>Login</h2>
@using (Html.BeginForm("Login", "Login", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Login</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger"})
<div class="form-group">
@Html.LabelFor(Model => Model.UserName, new { @class = "control-label col-md-2"})
<div class="col-md-10">
@Html.TextBoxFor(Model => Model.UserName, new { @class = "col-md-2 control-label"})
@Html.ValidationMessageFor(Model => Model.UserName, "" , new { @class = "text-danger"})
</div>
</div>
<div class="form-group">
@Html.LabelFor(Model => Model.Password, new { @class = "control-label col-md-2"})
<div class="col-md-10">
@Html.TextBoxFor(Model => Model.Password, new { @class = "col-md-2 control-label"})
@Html.ValidationMessageFor(Model => Model.Password, "" , new { @class = "text-danger"})
</div>
</div>
<div class="form-group">
<input type="submit" value="Log In" class="btn btn-default" />
</div>
</div>
}
</code></pre>
<p>This is the partial portion of every page</p>
<pre><code>@using Microsoft.AspNet.Identity;
@if (Request.IsAuthenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index" , "Manage", routeValues: null, htmlAttributes: new { title = "Manage" } )</li>
</ul>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Register", "Create", "Login", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Login", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
</code></pre>
<p>This is the controller </p>
<pre><code> [AllowAnonymous]
// GET: Login
public ActionResult Login()
{
return View();
}
[AllowAnonymous]
// GET: Login
public ActionResult Login()
{
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string retunUrl)
{
/*
if (!ModelState.IsValid)
{
Console.WriteLine("IS NOT VALID");
return View(model);
}
*/
String UserName = model.UserName;
String Password = model.Password;
LoginContext LC = new LoginContext();
LoginModel ValidUser = LC.UserList.Single(Person => Person.UserName == UserName && Person.Password == Password);
if (ValidUser != null)
{
return Redirect("Index");
}
return View(model);
}
// GET: Login Index of users
[AllowAnonymous]
public ActionResult Index()
{
return View(db.UserList.ToList());
}
</code></pre>
| 1 | 1,842 |
Java List to Excel Columns
|
<p>Correct me where I'm going wrong. </p>
<p>I'm have written a program in Java which will get list of files from two different directories and make two (Java list) with the file names. I want to transfer the both the list (downloaded files list and Uploaded files list) to an excel. </p>
<p>What the result i'm getting is those list are transferred row wise. I want them in column wise.</p>
<p>Given below is the code:</p>
<pre><code> public class F {
static List<String> downloadList = new ArrayList<>();
static List<String> dispatchList = new ArrayList<>();
public static class FileVisitor extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String name = file.toRealPath().getFileName().toString();
if (name.endsWith(".pdf") || name.endsWith(".zip")) {
downloadList.add(name);
}
if (name.endsWith(".xml")) {
dispatchList.add(name);
}
return FileVisitResult.CONTINUE;
}
}
public static void main(String[] args) throws IOException {
try {
Path downloadPath = Paths.get("E:\\report\\02_Download\\10252013");
Path dispatchPath = Paths.get("E:\\report\\01_Dispatch\\10252013");
FileVisitor visitor = new FileVisitor();
Files.walkFileTree(downloadPath, visitor);
Files.walkFileTree(downloadPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor);
Files.walkFileTree(dispatchPath, visitor);
Files.walkFileTree(dispatchPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor);
System.out.println("Download File List" + downloadList);
System.out.println("Dispatch File List" + dispatchList);
F f = new F();
f.UpDown(downloadList, dispatchList);
} catch (Exception ex) {
Logger.getLogger(F.class.getName()).log(Level.SEVERE, null, ex);
}
}
int rownum = 0;
int colnum = 0;
HSSFSheet firstSheet;
Collection<File> files;
HSSFWorkbook workbook;
File exactFile;
{
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("10252013");
Row headerRow = firstSheet.createRow(rownum);
headerRow.setHeightInPoints(40);
}
public void UpDown(List<String> download, List<String> upload) throws Exception {
List<String> headerRow = new ArrayList<>();
headerRow.add("Downloaded");
headerRow.add("Uploaded");
List<List> recordToAdd = new ArrayList<>();
recordToAdd.add(headerRow);
recordToAdd.add(download);
recordToAdd.add(upload);
F f = new F();
f.CreateExcelFile(recordToAdd);
f.createExcelFile();
}
void createExcelFile() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("E:\\report\\Download&Upload.xls"));
HSSFCellStyle hsfstyle = workbook.createCellStyle();
hsfstyle.setBorderBottom((short) 1);
hsfstyle.setFillBackgroundColor((short) 245);
workbook.write(fos);
} catch (Exception e) {
}
}
public void CreateExcelFile(List<List> l1) throws Exception {
try {
for (int j = 0; j < l1.size(); j++) {
Row row = firstSheet.createRow(rownum);
List<String> l2 = l1.get(j);
for (int k = 0; k < l2.size(); k++) {
Cell cell = row.createCell(k);
cell.setCellValue(l2.get(k));
}
rownum++;
}
} catch (Exception e) {
} finally {
}
}
}
</code></pre>
<p>(The purpose is to verify the files Downloaded and Uploaded for the given date)
Thanks.</p>
| 1 | 1,490 |
jQuery Roundabout: changing the number of items shown
|
<p>I am using the jQuery Roundabout plugin. I am wondering if there is a way to choose the number of pictures that are shown. I have ten pictures, but only three of them should be visible as shown in the second (extention) link within the "square" example.</p>
<p>How is that possible?</p>
<p>Edit with further information:</p>
<p>jquery roundabout-plugin: <a href="http://fredhq.com/projects/roundabout" rel="nofollow">http://fredhq.com/projects/roundabout</a></p>
<p>and extension: <a href="http://fredhq.com/projects/roundabout-shapes/" rel="nofollow">http://fredhq.com/projects/roundabout-shapes/</a></p>
<p>-> I would like to have the "square shape"</p>
<p>relevant code:</p>
<pre><code><head>
<style>
.roundabout-holder {
list-style: none;
padding: 0;
margin: 0 auto;
text-align: center;
height: 500px;
width: 300px;
}
.roundabout-moveable-item {
cursor: pointer;
border: 1px solid #999;
bottom: 0;
}
.roundabout-in-focus {
cursor: auto;
}
</style>
<script type="text/javascript" src="../../js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../../js/jquery.roundabout.js"></script>
<script type="text/javascript" src="../../js/jquery.roundabout-shapes.js"></script>
<script>
$(document).ready(function() {
$('ul.roundabout-holder').roundabout({
shape: 'square',
btnNext: ".next",
btnPrev: ".prev",
btnStopAutoplay: ".stop",
btnStartAutoplay: ".start",
duration: 1000,
autoplay: true,
autoplayDuration: 4000,
autoplayPauseOnHover: true,
reflect: false,
minOpacity: 0.5,
minScale: 0.1
});
});
</script>
</head>
<body>
<ul class="roundabout-holder">
<li class="roundabout-moveable-item"><a href="img/hauptbild-gross.jpg"><img src="img/hauptbild.jpg" width="466" height="500" /></a></li>
<li class="roundabout-moveable-item"><a href="img/baerenfamilie-gross.jpg"><img src="img/baerenfamilie.jpg" width="400" height="196" /></a></li>
<li class="roundabout-moveable-item"><a href="img/hamster-bleistift-gross.jpg"><img src="img/hamster-bleistift.jpg" width="400" height="351" /></a></li>
<li class="roundabout-moveable-item"><a href="img/hamster-schlafend-gross.jpg"><img src="img/hamster-schlafend.jpg" width="400" height="302" /></a></li>
<li class="roundabout-moveable-item"><a href="img/hamster-schmetterling-gross.jpg"><img src="img/hamster-schmetterling.jpg" width="400" height="374" /></a></li>
<li class="roundabout-moveable-item"><a href="img/hase-gross.jpg"><img src="img/hase.jpg" width="384" height="500" /></a></li>
</ul>
</body>
</html>
</code></pre>
<hr>
<p>And here is the project-url:
<a href="http://www.eyes-on-fire.de/test/2/portfolio/tiere/index.php" rel="nofollow">http://www.eyes-on-fire.de/test/2/portfolio/tiere/index.php</a></p>
<p>(I wasn't allowed to post three links as a newbie)</p>
| 1 | 1,490 |
Sending VCF files (Vcard) is failing over WhatsApp or SMS, what am I doing wrong?
|
<p>I'm sending a VCard (VCF file) in the Media URL field of a Send Message Widget but it doesn't work, it happens too with curl.</p>
<p>I'm creating a VCF file, storing it in a bucket and sending that URL with Content-Type text/vcard in the headers. If I try with stock VCF files it doesn't work either. What I'm expecting is to receive the contact file via WhatsApp or SMS and import it to my Address Book.</p>
<pre><code> "sid": "MMxxxxxxxxxx",
"date_created": "Thu, 17 Oct 2019 19:43:44 +0000",
"date_updated": "Thu, 17 Oct 2019 19:43:44 +0000",
"date_sent": null,
"account_sid": "ACxxxxxxxxx",
"to": "whatsapp:+1xxxxxxx",
"from": "whatsapp:+1xxxxxxx",
"messaging_service_sid": null,
"body": "media testing2",
"status": "queued",
"num_segments": "1",
"num_media": "1",
"direction": "outbound-api",
"api_version": "2010-04-01",
"price": null,
"price_unit": null,
"error_code": null,
"error_message": null,
"uri": "/2010-04-01/Accounts/ACxxxxxxxx/Messages/MMxxxxxxx.json",
"subresource_uris": {
"media": "/2010-04-01/Accounts/ACxxxxxxxx/Messages/MMxxxxxxxxx/Media.json"
}
}
</code></pre>
<p>This is the output after using this curl line</p>
<pre><code>--data-urlencode "Body=Your Heart Health Coach contact card" \
--data-urlencode "MediaUrl=https://mighty-health-assets.s3.amazonaws.com/vcf/James%20Li.vcf" \
--data-urlencode "From=<from>" \
--data-urlencode "To=<to>" \
-u <auth>:<auth>
</code></pre>
<p>which is posted somewhere in SO [twilio]</p>
<p>If I send the OWL image it works as expected, but if I send the VCF URL it doesn't work.</p>
<p>first media testing2 message with OWL image, the second one with <a href="http://www.w3.org/2002/12/cal/vcard-examples/john-doe.vcf" rel="nofollow noreferrer">w3 vcf http://www.w3.org/2002/12/cal/vcard-examples/john-doe.vcf</a> and the third one with my constructed VCF file.</p>
<p>The headers are fine in both cases</p>
<pre><code>HTTP/1.1 200 OK
Date: Thu, 17 Oct 2019 22:23:17 GMT
Last-Modified: Sun, 18 Feb 2007 18:25:17 GMT
ETag: "3xxxxxx"
Accept-Ranges: bytes
Content-Length: 940
Cache-Control: max-age=21600
Expires: Fri, 18 Oct 2019 04:23:17 GMT
Vary: upgrade-insecure-requests
Content-Type: text/vcard
</code></pre>
<p>and mine</p>
<pre><code>< x-amz-id-2: xxxxxxx
< x-amz-request-id: xxxxxx
< Date: Thu, 17 Oct 2019 19:15:28 GMT
< Last-Modified: Thu, 17 Oct 2019 19:15:05 GMT
< ETag: "axxxxxxxx7"
< x-amz-version-id: xxxxxxxx
< Accept-Ranges: bytes
< Content-Type: text/vcard
< Content-Length: 165
< Server: AmazonS3
</code></pre>
<p>The file is public (and removed after a while)</p>
<p>The studio flow logs show this:</p>
<pre><code>From: whatsapp:+1xxxxx
Body: Conxxxxxx ⭐⭐⭐
Media URL: http://www.w3.org/2002/12/cal/vcard-examples/john-doe.vcf
SID: MMxxxxxxxxx
Status: queued
</code></pre>
<p>And the MEDIA box with the URL link to Twilio's CDN is present at the logs.</p>
<p>Any ideas??</p>
<p>Thanks</p>
| 1 | 1,240 |
Evaluating a postfix expression using expression tree in C
|
<p>I can't seem to get this program to work, it is a doubly linked list representation of expression tree. After creating the tree I need to evaluate the result but I can't seem to figure out how.</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef struct node
{
char item;
struct node * left;
struct node * right;
}*Btree;
Btree root;
void operandFunc(char);
void operatorFunc(char);
void push(Btree);
Btree pop();
void infix(Btree);
void postfix(Btree);
void prefix(Btree);
int solve(Btree);
int calculate(char,int,int);
int isOperand(char);
char expression[25];
Btree stack[25];
int stackPtr = -1;
int main()
{
int count = 0;
printf("Please enter a postfix expression\n");
while((expression[count++]=getchar())!='\n');
expression[--count] = '\0';
//puts(expression);
for(count = 0;expression[count]!='\0';count++)
{
switch(expression[count])
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '%':
case '$':
operatorFunc(expression[count]);
break;
default:
operandFunc(expression[count]);
}
}
if(stackPtr != 0)
{
printf("Incomplete / Incorrect postfix expression given!\n");
}
else
{
printf("\n\nThe result = %d",solve(stack[stackPtr])+'0');
printf("\n\n");
return 0;
}
}
void prefix(Btree root)
{
Btree temp = root;
if(temp)
{
printf("%c ",temp->item);
prefix(temp->left);
prefix(temp->right);
}
}
void infix(Btree root)
{
Btree temp = root;
if(temp != NULL)
{
infix(temp->left);
printf("%c ",temp->item);
infix(temp->right);
}
}
void postfix(Btree root)
{
Btree temp = root;
if(temp)
{
postfix(temp->left);
postfix(temp->right);
printf("%c ",temp->item);
}
}
void push(Btree root)
{
stack[++stackPtr] = root;
}
Btree pop()
{
return (stack[stackPtr--]);
}
void operandFunc(char var)
{
Btree root = (Btree)malloc(sizeof(struct node));
root->item= var;
root->left= NULL;
root->right= NULL;
push(root);
}
void operatorFunc(char var)
{
Btree root = (Btree)malloc(sizeof(struct node));
root->item = var;
root->right = pop();
root->left = pop();
push(root);
}
int solve(Btree root)
{
Btree temp = root;
char num1,num2;
char operator;
int result;
if(temp)
{
Btree LEFTP = temp->left;
Btree RIGHTP = temp->right;
if(LEFTP)
{
if(isOperand(LEFTP->item))
{
num1 = LEFTP->item;
}
else
{
num1 = solve(LEFTP);
}
}
if(RIGHTP)
{
if(isOperand(RIGHTP->item))
{
num2 = RIGHTP->item;
}
else
{
num2 = solve(RIGHTP);
}
}
operator = temp->item;
printf("Test 1 = %c, num1 = %c, num2 = %c\n",operator,num1,num2);
result = calculate(operator,num1-'0',num2-'0');
printf("Test Result = %d\n",result);
temp->item = (result+'0');
printf("Root Item = %c and %d\n",temp->item,temp->item);
return result;
}
return NULL;
}
int calculate(char operator,int op1,int op2)
{
printf("Operator = %c , num1 = %d, num2 = %d\n",operator,op1,op2);
switch(operator)
{
case '+': return(op1+op2);
break;
case '-': return(op1-op2);
break;
case '*': return(op1*op2);
break;
case '/': return(op1/op2);
break;
case '%': return(op1%op2);
break;
case '$': return pow(op1,op2);
break;
default: printf("\n illegal operation.");
exit;
}
}
int isOperand(char var)
{
switch(var)
{
case '+':
case '-':
case '*':
case '/':
case '$':
case '%':
return 0;
default:
return 1;
}
}
</code></pre>
<p>I'm having trouble converting and returning the characters as integers.</p>
<p>UPDATE 1: I was able to make it solve single digit number inputs to recieve a multi digit result. I'm still working on a new data structure to compute multi digit numbers. Here's the updated code below.</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef struct node
{
char item;
struct node * left;
struct node * right;
}*Btree;
Btree root;
void operandFunc(char);
void operatorFunc(char);
void push(Btree);
Btree pop();
void infix(Btree);
void postfix(Btree);
void prefix(Btree);
int solve(Btree);
int calculate(char,int,int);
int isOperand(char);
char expression[25];
Btree stack[25];
int stackPtr = -1;
int main()
{
int count = 0;
printf("Please enter a postfix expression\n");
while((expression[count++]=getchar())!='\n');
expression[--count] = '\0';
//puts(expression);
for(count = 0;expression[count]!='\0';count++)
{
switch(expression[count])
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '%':
case '$':
operatorFunc(expression[count]);
break;
default:
operandFunc(expression[count]);
}
}
if(stackPtr != 0)
{
printf("Incomplete / Incorrect postfix expression given!\n");
}
else
{
printf("\n\nThe result = %d",solve(stack[stackPtr])-'0');
printf("\n\n");
return 0;
}
}
void prefix(Btree root)
{
Btree temp = root;
if(temp)
{
printf("%c ",temp->item);
prefix(temp->left);
prefix(temp->right);
}
}
void infix(Btree root)
{
Btree temp = root;
if(temp != NULL)
{
infix(temp->left);
printf("%c ",temp->item);
infix(temp->right);
}
}
void postfix(Btree root)
{
Btree temp = root;
if(temp)
{
postfix(temp->left);
postfix(temp->right);
printf("%c ",temp->item);
}
}
void push(Btree root)
{
stack[++stackPtr] = root;
}
Btree pop()
{
return (stack[stackPtr--]);
}
void operandFunc(char var)
{
Btree root = (Btree)malloc(sizeof(struct node));
root->item= var;
root->left= NULL;
root->right= NULL;
push(root);
}
void operatorFunc(char var)
{
Btree root = (Btree)malloc(sizeof(struct node));
root->item = var;
root->right = pop();
root->left = pop();
push(root);
}
int solve(Btree root)
{
Btree temp = root;
char num1,num2;
char operator;
int result;
if(temp)
{
Btree LEFTP = temp->left;
Btree RIGHTP = temp->right;
if(LEFTP)
{
if(isOperand(LEFTP->item))
{
num1 = LEFTP->item;
}
else
{
num1 = solve(LEFTP);
}
}
if(RIGHTP)
{
if(isOperand(RIGHTP->item))
{
num2 = RIGHTP->item;
}
else
{
num2 = solve(RIGHTP);
}
}
operator = temp->item;
printf("Test 1 = %c, num1 = %c, num2 = %c\n",operator,num1,num2);
result = calculate(operator,num1-'0',num2-'0');
printf("Test Result = %d\n",result);
temp->item = (result+'0');
printf("Root Item = %c and %d\n",temp->item,temp->item);
return root->item;
}
return NULL;
}
int calculate(char operator,int op1,int op2)
{
printf("Operator = %c , num1 = %d, num2 = %d\n",operator,op1,op2);
switch(operator)
{
case '+': return(op1+op2);
break;
case '-': return(op1-op2);
break;
case '*': return(op1*op2);
break;
case '/': return(op1/op2);
break;
case '%': return(op1%op2);
break;
case '$': return pow(op1,op2);
break;
default: printf("\n illegal operation.");
exit;
}
}
int isOperand(char var)
{
switch(var)
{
case '+':
case '-':
case '*':
case '/':
case '$':
case '%':
return 0;
default:
return 1;
}
}
</code></pre>
| 1 | 4,856 |
Kendo UI multi select drop down with filter and select all options
|
<p>I need a kendo ui dropdown list with the following features.</p>
<blockquote>
<ol>
<li>Multi select dropdown with a select check box to check multiple options at at time.</li>
<li>Select all checkbox as a header template, on which when I click on it, all the <strong>filtered</strong> search results of the option is selected.</li>
</ol>
</blockquote>
<p><a href="https://i.stack.imgur.com/3La5N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3La5N.png" alt="Required Solution"></a></p>
<p>I have gone through many references and find a close solution from telrik. In which my first requirement is satisfied. I have attached the code snippet here with.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1028/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1028/styles/kendo.rtl.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1028/styles/kendo.silver.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.1028/styles/kendo.mobile.all.min.css" />
<script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2016.3.1028/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example" role="application">
<div class="demo-section k-header">
<h2>Invite Attendees</h2>
<label for="required">Required</label>
<select id="required" multiple="multiple" data-placeholder="Select attendees...">
<option selected>Steven White</option>
<option>Nancy King</option>
<option>Nancy Davolio</option>
<option>Robert Davolio</option>
<option>Michael Leverling</option>
<option>Andrew Callahan</option>
<option>Michael Suyama</option>
<option selected>Anne King</option>
<option>Laura Peacock</option>
<option>Robert Fuller</option>
<option>Janet White</option>
<option>Nancy Leverling</option>
<option>Robert Buchanan</option>
<option>Margaret Buchanan</option>
<option selected>Andrew Fuller</option>
<option>Anne Davolio</option>
<option>Andrew Suyama</option>
<option>Nige Buchanan</option>
<option>Laura Fuller</option>
</select>
</div>
<style>
.k-list .k-item {}
.k-item input {}
</style>
<script>
$(document).ready(function () {
var checkInputs = function (elements) {
elements.each(function () {
var element = $(this);
var input = element.children("input");
input.prop("checked", element.hasClass("k-state-selected"));
});
};
// create MultiSelect from select HTML element
var required = $("#required").kendoMultiSelect({
itemTemplate: "<input type='checkbox'/> #:data.text#",
autoClose: false,
dataBound: function () {
var items = this.ul.find("li");
setTimeout(function () {
checkInputs(items);
});
},
change: function () {
var items = this.ul.find("li");
checkInputs(items);
}
}).data("kendoMultiSelect");
});
</script>
</div>
</body>
</html>
</code></pre>
<p>How can I achieve my second requirement, select all option that selects my filtered search result. I'm looking foe the kend ui Multi Select option itself. I'm not interested in jQuery multi select drop downs. Looking forward for help. Thanks in advance.</p>
| 1 | 2,305 |
Create Image from imageview and textview?
|
<p>I'm making an app that will allow the user to add a photo to an imageview from the gallery of their phone which I have already been able to code successfully. I now want to be able to allow the user to add text on top of the photo and then save the text and image as one back into the gallery. Is there any way to do this?</p>
<p>XML:</p>
<pre><code> <LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView android:id="@+id/image" android:layout_height="400dp" android:layout_width="fill_parent"/>
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="horizontal">
<Button
android:id="@+id/chooseimage"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_width="fill_parent"
android:text="Choose Image"/>
<Button
android:id="@+id/addtext"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_width="fill_parent"
android:text="Add Text"/>
<Button
android:id="@+id/save"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_width="fill_parent"
android:text="Save"/>
</LinearLayout>
</LinearLayout>
</code></pre>
<p>Member.java</p>
<pre><code>public class MemberActivity extends Activity implements OnClickListener {
/**
* Called when the activity is first created.
*/
private static final int SELECT_IMAGE = 1;
Button openGallery;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.design);
openGallery = (Button) findViewById(R.id.chooseimage);
openGallery.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.chooseimage:
Intent gallery = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, SELECT_IMAGE);
break;
default:
break;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == SELECT_IMAGE) {
Uri selectedImage = data.getData();
String path = getPath(selectedImage);
Bitmap bitmapImage = BitmapFactory.decodeFile(path);
ImageView image = (ImageView) findViewById(R.id.image);
image.setImageBitmap(bitmapImage);
}
}
public String getPath(Uri uri) {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
return cursor.getString(columnIndex);
}
}
</code></pre>
| 1 | 1,501 |
Tensorflow 2.1 Failed to get convolution algorithm. This is probably because cuDNN failed to initialize
|
<p>I am using anaconda python 3.7 and tensorflow 2.1 with cuda 10.1 and cudnn 7.6.5, and trying to run the retinaset (<a href="https://github.com/fizyr/keras-retinanet" rel="nofollow noreferrer">https://github.com/fizyr/keras-retinanet</a>): </p>
<pre><code>python keras_retinanet/bin/train.py --freeze-backbone --random-transform --batch-size 8 --steps 500 --epochs 10 csv annotations.csv classes.csv
</code></pre>
<p>Here below are the resultant errors:</p>
<pre><code>Epoch 1/10
2020-02-10 20:34:37.807590: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudnn64_7.dll
2020-02-10 20:34:38.835777: E tensorflow/stream_executor/cuda/cuda_dnn.cc:329] Could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR
2020-02-10 20:34:39.753051: E tensorflow/stream_executor/cuda/cuda_dnn.cc:329] Could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR
2020-02-10 20:34:39.776706: W tensorflow/core/common_runtime/base_collective_executor.cc:217] BaseCollectiveExecutor::StartAbort Unknown: Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above.
[[{{node conv1/convolution}}]]
Traceback (most recent call last):
File "keras_retinanet/bin/train.py", line 530, in <module>
main()
File "keras_retinanet/bin/train.py", line 525, in main
initial_epoch=args.initial_epoch
File "C:\Anaconda\Anaconda3.7\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "C:\Anaconda\Anaconda3.7\lib\site-packages\keras\engine\training.py", line 1732, in fit_generator
initial_epoch=initial_epoch)
File "C:\Anaconda\Anaconda3.7\lib\site-packages\keras\engine\training_generator.py", line 220, in fit_generator
reset_metrics=False)
File "C:\Anaconda\Anaconda3.7\lib\site-packages\keras\engine\training.py", line 1514, in train_on_batch
outputs = self.train_function(ins)
File "C:\Anaconda\Anaconda3.7\lib\site-packages\tensorflow_core\python\keras\backend.py", line 3727, in __call__
outputs = self._graph_fn(*converted_inputs)
File "C:\Anaconda\Anaconda3.7\lib\site-packages\tensorflow_core\python\eager\function.py", line 1551, in __call__
return self._call_impl(args, kwargs)
File "C:\Anaconda\Anaconda3.7\lib\site-packages\tensorflow_core\python\eager\function.py", line 1591, in _call_impl
return self._call_flat(args, self.captured_inputs, cancellation_manager)
File "C:\Anaconda\Anaconda3.7\lib\site-packages\tensorflow_core\python\eager\function.py", line 1692, in _call_flat
ctx, args, cancellation_manager=cancellation_manager))
File "C:\Anaconda\Anaconda3.7\lib\site-packages\tensorflow_core\python\eager\function.py", line 545, in call
ctx=ctx)
File "C:\Anaconda\Anaconda3.7\lib\site-packages\tensorflow_core\python\eager\execute.py", line 67, in quick_execute
six.raise_from(core._status_to_exception(e.code, message), None)
File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.UnknownError: Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above.
[[node conv1/convolution (defined at C:\Anaconda\Anaconda3.7\lib\site-packages\keras\backend\tensorflow_backend.py:3009) ]] [Op:__inference_keras_scratch_graph_12376]
Function call stack:
keras_scratch_graph
</code></pre>
<p>Anyone has experienced similar problems?</p>
| 1 | 1,348 |
Django REST framework url regex patterns not being matched
|
<p>I am writing a RESTful API as an application for a django project.
I have two end points in my application (with urls imported into the main project's urls.py), which are defined as shown below below:</p>
<h2>testrest/urls.py</h2>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'prices/(?P<ticker>[X]{1}[A-Z0-9]{3}:[A-Z0-9]{1}[A-Z09.-]{1,4})/?P<resolution>([0-9]{0,3})/$', views.historyPrices, name='prices'),
url(r'chart/?P<name>([a-zA-Z0-9_\.-]{8,12})/$s', views.chart, name='pchart'),
]
</code></pre>
<h2>testrest/views.py</h2>
<pre><code>from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
# Create your views here.
@api_view(['GET'])
def historyPrices(request, ticker, resolution=1):
if request.method == 'GET':
try:
# do something
return Response({'foo': 'foobar'})
except Exception as e:
print ('Error: {0}'.format(e))
return Response(status = status.HTTP_500_INTERNAL_SERVER_ERROR)
else:
return Response(status = status.HTTP_405_METHOD_NOT_ALLOWED)
@api_view(['GET', 'POST', 'PUT', 'DELETE'])
def chart(request, name=None):
if request.method == 'GET':
if (name is not None):
try:
# do something
except Exception as e:
print('Error:',e)
return Response(status = status.HTTP_404_NOT_FOUND)
return Response({'foo': 'bar')
else:
return Response(status = status.HTTP_400_BAD_REQUEST)
elif request.method == 'POST':
data = request.data
# print(data)
try:
# do something
return Response(status = status.HTTP_201_CREATED)
except Exception as ex:
print('Unhandled exception: {0}'.format(e))
return Response(status = status.HTTP_500_INTERNAL_SERVER_ERROR)
elif request.method == 'PUT':
print('Called with PUT')
return Response(status=status.HTTP_501_NOT_IMPLEMENTED)
elif request.method == 'DELETE':
print('Called with DELETE')
return Response(status=status.HTTP_501_NOT_IMPLEMENTED)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
</code></pre>
<p>I want to be able to call using the following urls (all of those shown below, return a 404 not found error:</p>
<pre><code>curl http://127.0.0.1:8000/testrest/prices/XNAS:GOOG (404)
curl http://127.0.0.1:8000/testrest/prices/XNAS:GOOG/ (404)
curl http://127.0.0.1:8000/testrest/prices/XNAS:GOOG/3 (404)
curl http://127.0.0.1:8000/testrest/prices/XNAS:GOOG/3/ (404)
curl http://127.0.0.1:8000/testrest/prices?ticker=XNAS:GOOG (404)
curl http://127.0.0.1:8000/testrest/prices/?ticker=XNAS:GOOG&resolution=3 (404)
curl http://127.0.0.1:8000/testrest/prices?ticker=XNAS:GOOG&resolution=3/ (404)
</code></pre>
<p>I now try to load a manually created chart (xyz) from the server:</p>
<pre><code>curl http://127.0.0.1:8000/testrest/chart/xyz (404)
curl http://127.0.0.1:8000/testrest/chart/xyz/ (404)
curl http://127.0.0.1:8000/testrest/chart?name=xyz (404)
</code></pre>
<p>I then try to POST (create) a new chart on the server:</p>
<pre><code>curl -H "Content-Type: application/json" -X POST -d '{/* data */}' http://127.0.0.1:8000/testrest/chart (404)
</code></pre>
<p>Why are the patterns not matching?</p>
| 1 | 1,648 |
Errors installing mysqlclient on Max OSX
|
<p>I am trying to install mysqlclient on Mac OSX, as required by Django to use MySql rather than sqlite DB.</p>
<p>I originally tried <code>pip3 install mysqlclient</code> but I was getting an error like this:</p>
<pre><code>Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/3f/1z_bg4h52lz8n0_gc1mp7gwh0000gn/T/pip-install-em4vq6dr/mysqlclient/
</code></pre>
<p>I have done a lot of Googling and tried so many suggestions (this appears a common issue), and I've ended up with even more of a mess of an error message now:</p>
<pre><code>Collecting mysqlclient==1.3.1
Downloading https://files.pythonhosted.org/packages/6b/ba/4729d99e85a0a35bb46d55500570de05b4af10431cef174b6da9f58a0e50/mysqlclient-1.3.1.tar.gz (76kB)
100% |████████████████████████████████| 81kB 2.0MB/s
Building wheels for collected packages: mysqlclient
Building wheel for mysqlclient (setup.py) ... error
Complete output from command /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/private/var/folders/z_/k_j3hrx10gn5w244fpvzw01r0000gn/T/pip-install-4nhdinpy/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /private/var/folders/z_/k_j3hrx10gn5w244fpvzw01r0000gn/T/pip-wheel-41536ku7 --python-tag cp36:
running bdist_wheel
running build
running build_py
creating build
creating build/lib.macosx-10.9-x86_64-3.6
copying _mysql_exceptions.py -> build/lib.macosx-10.9-x86_64-3.6
creating build/lib.macosx-10.9-x86_64-3.6/MySQLdb
copying MySQLdb/__init__.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb
copying MySQLdb/compat.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb
copying MySQLdb/converters.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb
copying MySQLdb/connections.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb
copying MySQLdb/cursors.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb
copying MySQLdb/release.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb
copying MySQLdb/times.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb
creating build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.macosx-10.9-x86_64-3.6
gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -Dversion_info=(1,3,1,'final',1) -D__version__=1.3.1 -I/usr/local/Cellar/mysql/8.0.15/include/mysql -I/Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m -c _mysql.c -o build/temp.macosx-10.9-x86_64-3.6/_mysql.o
_mysql.c:40:10: fatal error: 'my_config.h' file not found
#include "my_config.h"
^~~~~~~~~~~~~
1 error generated.
error: command 'gcc' failed with exit status 1
----------------------------------------
Failed building wheel for mysqlclient
Running setup.py clean for mysqlclient
Failed to build mysqlclient
Installing collected packages: mysqlclient
Running setup.py install for mysqlclient ... error
Complete output from command /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/private/var/folders/z_/k_j3hrx10gn5w244fpvzw01r0000gn/T/pip-install-4nhdinpy/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/z_/k_j3hrx10gn5w244fpvzw01r0000gn/T/pip-record-o9decnbp/install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_py
creating build
creating build/lib.macosx-10.9-x86_64-3.6
copying _mysql_exceptions.py -> build/lib.macosx-10.9-x86_64-3.6
creating build/lib.macosx-10.9-x86_64-3.6/MySQLdb
copying MySQLdb/__init__.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb
copying MySQLdb/compat.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb
copying MySQLdb/converters.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb
copying MySQLdb/connections.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb
copying MySQLdb/cursors.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb
copying MySQLdb/release.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb
copying MySQLdb/times.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb
creating build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.9-x86_64-3.6/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.macosx-10.9-x86_64-3.6
gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -Dversion_info=(1,3,1,'final',1) -D__version__=1.3.1 -I/usr/local/Cellar/mysql/8.0.15/include/mysql -I/Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m -c _mysql.c -o build/temp.macosx-10.9-x86_64-3.6/_mysql.o
_mysql.c:40:10: fatal error: 'my_config.h' file not found
#include "my_config.h"
^~~~~~~~~~~~~
1 error generated.
error: command 'gcc' failed with exit status 1
----------------------------------------
Command "/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/private/var/folders/z_/k_j3hrx10gn5w244fpvzw01r0000gn/T/pip-install-4nhdinpy/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/z_/k_j3hrx10gn5w244fpvzw01r0000gn/T/pip-record-o9decnbp/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/z_/k_j3hrx10gn5w244fpvzw01r0000gn/T/pip-install-4nhdinpy/mysqlclient/
</code></pre>
<p>Anybody have any suggestions as to where I'm going wrong?</p>
<p>Using Python 3.6</p>
<p>Thanks</p>
<p>Chris</p>
| 1 | 3,156 |
Rust diesel orm queries
|
<p>I am new to rust and diesel orm. I am trying to execute below things on my query:</p>
<ul>
<li>count</li>
<li>select</li>
<li>order</li>
<li>limit</li>
</ul>
<p>but I am getting error.<br>
I am using postgres database.<br></p>
<p>I have added the exact error above the queries in comment.<br>
Here are my code:</p>
<p><strong>schema.rs</strong></p>
<pre><code>table! {
employee (employee_id) {
employee_id -> Int4,
name -> Nullable<Text>,
age -> Nullable<Int4>,
address -> Nullable<Text>,
email -> Nullable<Text>,
dept_id -> Int4,
salary -> Nullable<Numeric>,
created_on -> Nullable<Timestamp>,
created_by -> Nullable<Text>,
modified_on -> Nullable<Timestamp>,
modified_by -> Nullable<Text>,
is_active -> Nullable<Bool>,
}
}
</code></pre>
<p><strong>models.rs</strong></p>
<pre><code>#![allow(unused)]
#![allow(clippy::all)]
use super::schema::employee;
use bigdecimal::BigDecimal;
use chrono::NaiveDateTime;
#[derive(Queryable, Debug, Identifiable)]
#[table_name = "employee"]
#[primary_key(employee_id)]
pub struct Employee {
pub employee_id: i32,
pub name: Option<String>,
pub age: Option<i32>,
pub address: Option<String>,
pub email: Option<String>,
pub dept_id: i32,
pub salary: Option<BigDecimal>,
pub created_on: Option<NaiveDateTime>,
pub created_by: Option<String>,
pub modified_on: Option<NaiveDateTime>,
pub modified_by: Option<String>,
pub is_active: Option<bool>,
}
</code></pre>
<p><strong>cargo.toml</strong></p>
<pre><code>[dependencies]
diesel = { version = "1.4.5", features = ["postgres","chrono","numeric"] }
dotenv = "0.15.0"
chrono = { version = "0.4.19" , features = ["serde"] }
bigdecimal = { version = "0.1.0" }
</code></pre>
<p><strong>main.rs</strong></p>
<pre><code>#[macro_use]
extern crate diesel;
extern crate bigdecimal;
extern crate chrono;
extern crate dotenv;
use crate::models::Employee;
use crate::models::Players;
use crate::schema::employee::dsl::*;
use diesel::{pg::PgConnection, prelude::*};
use dotenv::dotenv;
use std::env;
mod models;
mod schema;
fn main() {
dotenv().ok();
let data_url: String = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let connection: PgConnection =
PgConnection::establish(&data_url).expect(&format!("Error connect to {}", data_url));
//get all employees name
//This is working fine
let _employee: Vec<Employee> = employee
.load::<Employee>(&connection)
.expect("Error loading department");
for emp in _employee {
println!("{}", emp.name.unwrap_or_default());
}
//----------------------------------------------
//get employees count
/*
Error: error[E0282]: type annotations needed
^^^^^^^^^^^^^^^ consider giving `total_employees` a type
*/
let total_employees = employee.count().get_result(&connection).expect("Error");
println!("{}", total_employees);
//-----------------------------------------------
//get all names
/*
Error: error[E0277]: the trait bound `*const str: FromSql<diesel::sql_types::Nullable<diesel::sql_types::Text>, _>` is not satisfied
^^^^ the trait `FromSql<diesel::sql_types::Nullable<diesel::sql_types::Text>, _>` is not implemented for `*const str`
*/
let all_names = employee.select(name).load::<String>(&connection)?;
println!("{}", all_names);
//----------------------------------------------
//order name
/*
Error: error[E0277]: the trait bound `*const str: FromSql<diesel::sql_types::Nullable<diesel::sql_types::Text>, _>` is not satisfied
^^^^ the trait `FromSql<diesel::sql_types::Nullable<diesel::sql_types::Text>, _>` is not implemented for `*const str`
*/
let ordered_names = employee
.select(name)
.order(name.desc())
.load::<String>(&connection)?;
println!("{}", ordered_names);
//------------------------------------------------
/*
Error: error[E0277]: the trait bound `*const str: FromSql<diesel::sql_types::Nullable<diesel::sql_types::Text>, _>` is not satisfied
^^^^ the trait `FromSql<diesel::sql_types::Nullable<diesel::sql_types::Text>, _>` is not implemented for `*const str`
*/
let limited = employee
.select(name)
.order(employee_id)
.limit(1)
.load::<String>(&connection)?;
println!("{}", limited);
}
</code></pre>
<p>Am I missing something ?
Can anybody correct me ? <br>
Thanks!</p>
| 1 | 2,137 |
How can I update/delete data in Spark-hive?
|
<p>I don't think my title can explain the problem so here is the problem:</p>
<p>Details build.sbt:</p>
<pre><code>name := "Hello"
scalaVersion := "2.11.8"
version := "1.0"
libraryDependencies += "org.apache.spark" %% "spark-core" % "2.1.0"
libraryDependencies += "org.apache.spark" %% "spark-sql" % "2.1.0"
libraryDependencies += "org.apache.spark" % "spark-hive_2.11" % "2.1.0"
</code></pre>
<p>Code:</p>
<pre><code>val sparkSession = SparkSession.builder().enableHiveSupport().appName("HiveOnSpark").master("local").getOrCreate()
val hiveql : HiveContext = new HiveContext(sparkSession.sparkContext);
hiveql.sql("drop table if exists test")
hiveql.sql("create table test (id int, name string) stored as orc tblproperties(\"transactional\"=\"true\")")
hiveql.sql("insert into test values(1,'Yash')")
hiveql.sql("insert into test values(2,'Yash')")
hiveql.sql("insert into test values(3,'Yash')")
hiveql.sql("select * from test").show()
hiveql.sql("delete from test where id= 1")
</code></pre>
<p>Problem:</p>
<pre><code>Exception in thread "main" org.apache.spark.sql.catalyst.parser.ParseException:
Operation not allowed: delete from(line 1, pos 0)
== SQL ==
delete from test where id= 1
^^^
at org.apache.spark.sql.catalyst.parser.ParserUtils$.operationNotAllowed(ParserUtils.scala:39)
at org.apache.spark.sql.execution.SparkSqlAstBuilder$$anonfun$visitFailNativeCommand$1.apply(SparkSqlParser.scala:925)
at org.apache.spark.sql.execution.SparkSqlAstBuilder$$anonfun$visitFailNativeCommand$1.apply(SparkSqlParser.scala:916)
at org.apache.spark.sql.catalyst.parser.ParserUtils$.withOrigin(ParserUtils.scala:93)
at org.apache.spark.sql.execution.SparkSqlAstBuilder.visitFailNativeCommand(SparkSqlParser.scala:916)
at org.apache.spark.sql.execution.SparkSqlAstBuilder.visitFailNativeCommand(SparkSqlParser.scala:52)
at org.apache.spark.sql.catalyst.parser.SqlBaseParser$FailNativeCommandContext.accept(SqlBaseParser.java:952)
at org.antlr.v4.runtime.tree.AbstractParseTreeVisitor.visit(AbstractParseTreeVisitor.java:42)
at org.apache.spark.sql.catalyst.parser.AstBuilder$$anonfun$visitSingleStatement$1.apply(AstBuilder.scala:66)
at org.apache.spark.sql.catalyst.parser.AstBuilder$$anonfun$visitSingleStatement$1.apply(AstBuilder.scala:66)
at org.apache.spark.sql.catalyst.parser.ParserUtils$.withOrigin(ParserUtils.scala:93)
at org.apache.spark.sql.catalyst.parser.AstBuilder.visitSingleStatement(AstBuilder.scala:65)
at org.apache.spark.sql.catalyst.parser.AbstractSqlParser$$anonfun$parsePlan$1.apply(ParseDriver.scala:54)
at org.apache.spark.sql.catalyst.parser.AbstractSqlParser$$anonfun$parsePlan$1.apply(ParseDriver.scala:53)
at org.apache.spark.sql.catalyst.parser.AbstractSqlParser.parse(ParseDriver.scala:82)
at org.apache.spark.sql.execution.SparkSqlParser.parse(SparkSqlParser.scala:45)
at org.apache.spark.sql.catalyst.parser.AbstractSqlParser.parsePlan(ParseDriver.scala:53)
at org.apache.spark.sql.SparkSession.sql(SparkSession.scala:592)
at org.apache.spark.sql.SQLContext.sql(SQLContext.scala:699)
at main.scala.InitMain$.delayedEndpoint$main$scala$InitMain$1(InitMain.scala:41)
at main.scala.InitMain$delayedInit$body.apply(InitMain.scala:9)
at scala.Function0$class.apply$mcV$sp(Function0.scala:34)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App$$anonfun$main$1.apply(App.scala:76)
at scala.App$$anonfun$main$1.apply(App.scala:76)
at scala.collection.immutable.List.foreach(List.scala:381)
at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35)
at scala.App$class.main(App.scala:76)
at main.scala.InitMain$.main(InitMain.scala:9)
at main.scala.InitMain.main(InitMain.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
</code></pre>
<p>Same Problem with update query.</p>
<p>So now as I have gone through <a href="https://forums.databricks.com/questions/6007/can-we-use-updatedelete-queries-in-databricks-with.html" rel="noreferrer">This</a>, <a href="https://community.hortonworks.com/questions/23836/spark-sql-update-command.html" rel="noreferrer">This</a>, <a href="https://stackoverflow.com/questions/37517371/update-query-in-spark-sql">update query in Spark SQL</a>,<a href="https://stackoverflow.com/questions/42062427/operation-not-allowed-alter-table-add-columnsline-1-pos-0/42394017">This</a>, <a href="https://stackoverflow.com/questions/42062427/operation-not-allowed-alter-table-add-columnsline-1-pos-0">This</a> and many others.</p>
<p>I have come to know that Spark doesn't support update/delete but I am in a situation that need to use these both the operations. Can anyone suggest/help somehow.</p>
| 1 | 1,830 |
C# technique for deleting a file from web server immediately after closing
|
<p>I'm creating PDF invoices in a C# MVC application that I'm attaching to an email and sending, ideally, once the email is sent I'd like to delete the invoice to free up server space and improve privacy/security. I've written code to do it but it fails 50% of the time because the file is locked by another process (I'm not sure if it's the create/write process that's locking it or the email send). I'm sending the email asynchronously (i.e. the code to delete doesn't execute until the email has sent).</p>
<p>I'd appreciate some tips on how to handle this problem. I could run a job to clean up old files but I'd prefer to clean them up as I go...</p>
<p>I forgot to mention I am using iTextSharp to generate the PDF - the crux of it is this code is used to generate the final invoice (I am able to delete the list of files passed in as a param without drama):</p>
<pre><code>/// <summary>
/// http://stackoverflow.com/questions/4276019/itextsharp-pdfcopy-use-examples
/// </summary>
/// <param name="fileNames"></param>
/// <param name="outFile"></param>
private void CombineMultiplePDFs(List<string> files, string outFile)
{
int pageOffset = 0;
int f = 0;
iTextSharp.text.Document document = null;
PdfCopy writer = null;
foreach (string file in files)
{
// we create a reader for a certain document
PdfReader reader = new PdfReader(file);
reader.ConsolidateNamedDestinations();
// we retrieve the total number of pages
int n = reader.NumberOfPages;
pageOffset += n;
if (f == 0)
{
// step 1: creation of a document-object
document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
// step 3: we open the document
document.Open();
}
// step 4: we add content
for (int i = 0; i < n; )
{
++i;
if (writer != null)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
writer.AddPage(page);
}
}
PRAcroForm form = reader.AcroForm;
if (form != null && writer != null)
{
writer.CopyAcroForm(reader);
}
f++;
}
// step 5: we close the document
if (document != null)
{
document.Close();
}
}
</code></pre>
<p>The PDF File is then sitting on the server (e.g. "~/Invoices/0223.pdf") ready to attach to an email like so:</p>
<pre><code>MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(WebConfig.GetWebConfigKey(AppSettingsKey.ReplyEmailAddress.ToString()));
mailMessage.To.Add(new MailAddress(user.Email));
mailMessage.Subject = emailTemplate.TemplateSubject;
mailMessage.Body = emailTemplate.TemplateContent;
mailMessage.IsBodyHtml = false;
mailMessage.Attachments.Add(new Attachment(HttpContext.Current.Server.MapPath("/Invoices/" + invoiceId + ".pdf")));
SmtpClient client = new SmtpClient();
try
{
client.Send(mailMessage);
}
catch{...}{
//Error handling
}
client.Dispose();
</code></pre>
<p>Then I attempt to delete it:</p>
<pre><code>File.Delete(HttpContext.Current.Server.MapPath("/Invoices/" + invoiceId + ".pdf"));
</code></pre>
| 1 | 1,808 |
How to handle ECONNRESET when proxied response includes `connection: close` header?
|
<p>I am attempting to implement a MITM proxy.</p>
<p>I am handing a CONNECT request which is then used to create a connection with an internal HTTPS server.</p>
<p>Upon request, HTTPS server responds with:</p>
<pre><code>connection: close
foo
</code></pre>
<p>I expect the client to receive the response and proxy to close the connection socket.</p>
<p>Instead, <code>client</code> receives the response and proxy server logs an error:</p>
<pre><code>server socket error Error: This socket has been ended by the other party
at Socket.writeAfterFIN [as write] (net.js:407:14)
at Socket.ondata (_stream_readable.js:713:22)
at Socket.emit (events.js:200:13)
at addChunk (_stream_readable.js:294:12)
at readableAddChunk (_stream_readable.js:275:11)
at Socket.Readable.push (_stream_readable.js:210:10)
at TCP.onStreamRead (internal/stream_base_commons.js:166:17) {
code: 'EPIPE'
}
request socket error Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:183:27) {
errno: 'ECONNRESET',
code: 'ECONNRESET',
syscall: 'read'
}
</code></pre>
<p>Here is the subject script:</p>
<pre><code>const net = require('net');
const http = require('http');
const https = require('https');
const sslCertificate = {
ca: '-----BEGIN CERTIFICATE REQUEST-----\n' +
'MIICWTCCAUECAQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0B\n' +
'AQEFAAOCAQ8AMIIBCgKCAQEAuftLzDyJ8dRk71pZ3637tCIZCVLJieLqIlAf7wT5\n' +
'+qesTgu6vWzndZ4ze2V2lkac0xqFlW1djKT9IPUTCPx5dmWdT8mYFNUqB87hRWx9\n' +
'6Ge21bs+KDppujHYrrgNjT8L3+RlHenoG7Qi5WuSzfOqP5nqCyoKFFNHJ0Ds52Uk\n' +
'uvmTLzY/+kx3tFFGi4QXyva3T38uF99D4C2Tqxy7aRHEBJATQYxJgVPResiv31zv\n' +
'qd6H1jYIZGw5s4QJFh5C7VXsoHs1dLIfDoNcV/fO95VQ+wXPxrl8mcVQzNV7RKmX\n' +
'VHKudzx49IvOpRyM3OmN3RV5snOYKGmgwXQUF7JL2VSrSQIDAQABoAAwDQYJKoZI\n' +
'hvcNAQELBQADggEBAIaUryumwXIxMJErT/7B46l2k27+xefaTPCddjERhqk8WH/N\n' +
'95/yhvdzq1i0BSLv74Kh7L68kJiN8vtF6sAORofw42LMo+KzRDE1m1Zl7CVWw2DF\n' +
'wT7SJov22t6dVx6HOcsZZSo5lSN+CMN3xkgt6jyEPbCKfCJzl44Y3eOpqzry6/GM\n' +
'U+hR7nQx3IJmpAHNd7wolRzkf1X0gTifR5iC5S72GSRM9AnLfL2L0zQC6LmcNmZp\n' +
'3deNxIC+w5kTALREiMq3P9McBMCgwRinOJLbhmV9ifPRpLa9e+mFVdHzbR7+09kp\n' +
'6eNS19RndbHn6N1RbgFSNjDz28fMXISSWZFB/X4=\n-----END CERTIFICATE ' +
'REQUEST-----',
cert: '-----BEGIN CERTIFICATE-----\n' +
'MIICpDCCAYwCCQCK9kDE6/eFXDANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAls\n' +
'b2NhbGhvc3QwHhcNMTkwNzE5MTczMzI2WhcNMjAwNzE4MTczMzI2WjAUMRIwEAYD\n' +
'VQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC5\n' +
'+0vMPInx1GTvWlnfrfu0IhkJUsmJ4uoiUB/vBPn6p6xOC7q9bOd1njN7ZXaWRpzT\n' +
'GoWVbV2MpP0g9RMI/Hl2ZZ1PyZgU1SoHzuFFbH3oZ7bVuz4oOmm6MdiuuA2NPwvf\n' +
'5GUd6egbtCLla5LN86o/meoLKgoUU0cnQOznZSS6+ZMvNj/6THe0UUaLhBfK9rdP\n' +
'fy4X30PgLZOrHLtpEcQEkBNBjEmBU9F6yK/fXO+p3ofWNghkbDmzhAkWHkLtVeyg\n' +
'ezV0sh8Og1xX9873lVD7Bc/GuXyZxVDM1XtEqZdUcq53PHj0i86lHIzc6Y3dFXmy\n' +
'c5goaaDBdBQXskvZVKtJAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAGxXxytrNtm+\n' +
'q4NpWtKhy3DL5LOMH+K8lqgJ29SmmDEcqWgevpUnqLYFvb3AOxU/vYId5rFmHb5A\n' +
'WnXyKJ/YYSpNi47EcV+AJCwqDqBgAM4J3Tiiu6BguZ4sU20ZVFl1oQvTlQw8InLI\n' +
'D1ciwwtgWS2z9pRKmQ2ar2TY+2yhnl0L1WCl50XH6PngzzEHSxHiPDnOYPyXQjPs\n' +
'vkoJDmdnAVfWs2DfKfM0l27nIL2IBZr6Gks+nLwaK7FedQVD8ORYg9x/mwXO1oDr\n' +
'sLyCQUlXhhBNBmn+TTLFPbrXetOU6le7iW3JJVMUv84vh8cV8aLtXDuQ0qlKMd8B\n' +
'Mrgha3mM8EM=\n-----END CERTIFICATE-----',
key: '-----BEGIN RSA PRIVATE KEY-----\n' +
'MIIEpAIBAAKCAQEAuftLzDyJ8dRk71pZ3637tCIZCVLJieLqIlAf7wT5+qesTgu6\n' +
'vWzndZ4ze2V2lkac0xqFlW1djKT9IPUTCPx5dmWdT8mYFNUqB87hRWx96Ge21bs+\n' +
'KDppujHYrrgNjT8L3+RlHenoG7Qi5WuSzfOqP5nqCyoKFFNHJ0Ds52UkuvmTLzY/\n' +
'+kx3tFFGi4QXyva3T38uF99D4C2Tqxy7aRHEBJATQYxJgVPResiv31zvqd6H1jYI\n' +
'ZGw5s4QJFh5C7VXsoHs1dLIfDoNcV/fO95VQ+wXPxrl8mcVQzNV7RKmXVHKudzx4\n' +
'9IvOpRyM3OmN3RV5snOYKGmgwXQUF7JL2VSrSQIDAQABAoIBAGnWDuFwBhQ/iR0I\n' +
'rqJy0Q1GZjb/DL/SCOlz7WhIzbUNnClh1WgcxG8TkzqCmASWtIIR0rkhXp49+eq6\n' +
'bJWtj7WHyAjysQAR+nQtD9dBETmjY9GnV4zvCOGzohpzlQqvOSO1RrHKPZMeZMln\n' +
'+UgIhPbisOSfjNLaPWCiOu7HiSp5CgT70mSrylNQWhIa/okt8zjDbpV4QGPYP8J/\n' +
'fi4k3u5C8oHwCt3DYp4Qc6ybKiMuBELVcoI0Ug0CtVriB11uNCYOqMbanj4VfRzq\n' +
'KPTDRtkiF+EYi0PBstW+X9p7rFVB1PaBSF3PxudWMTmNZ1MooqOfkIves/T7YoxA\n' +
'Uh9XUIECgYEA4Y8RU+/lf5GMDKstdwm+OH0NBOT/mrsFAlWnGtQivWddyPxvPVJH\n' +
'LqIYtpqTH2luh7ksTcmTacqRjFx/ebobFAVgvg1zhCzHIdmgedGuxzvhEic1KRgT\n' +
'EJgm4kW9uPFZugd05873uWf0cYjbQZXQhhn1E3bTorTuJJZoJu0R7ZECgYEA0xTb\n' +
'bnFyOgD+c0A+kkirHiYU5RDAvtCS0jyKbZAPTP3fX016JeC2pxQcN4iLvgumm+Iv\n' +
'ugtdrHYDzZTIzMl0pT8HSDqjaW8nNmEMvYaE8FYGlFHqEJQlweGMYeXdCxZSA+1D\n' +
'HAzG8tW0rniMZp6KevZt5GCmBX3q0mH9ZKU/ZjkCgYEA14JTgwhOFXHiBuSyvu6v\n' +
'MdfBTbDiy1rvMUjXLZoMSz1s7TDLtCJd4p97z1SnRzb8JW92dign0cd7A0oJfiuj\n' +
'3aA5y7ycZ2hFJwGBA4OlY7TBmg+eClJ3PL6zQDR0TjVDjqu7NhSYuiwp8SRaoTJc\n' +
'FxTMBTnegbIvawPOJYsTOxECgYEAlVDzyLTHsPBzDuQrXx+4rKMTtNadAl5Y/g+F\n' +
'fOujZztPgAM2nQTRMG+xZjdZYx6qxSrDyD+yDAWPuyW8xeDceuiTJi0U28idXIJa\n' +
'mNdHwxuXm+Q2R3QFIZmDzNzl+KnZap20E2uWcMFsBt+PsigEneck5aDY0Jm6OwjG\n' +
'TyP2LUECgYALK+5AoQYbeUwVd3MhJONl0EdtKzjDq2wI127oXCjqVIe9BoqNedDu\n' +
'zOvo5QjNApRbPZcaJB7e/3XbMFv/jSpeL9jC/AynGQBdpk3meL9KtC7Nm4wwj8XX\n' +
'Ad5ZZkUZLAukbH1BqBuEgFjv3SDJ2g/aqUdqVfwq6qNSNdWzZTQG4w==\n-----END RSA ' +
'PRIVATE KEY-----'
};
const handleConnect = (port, request, requestSocket, head) => {
const {
httpVersion
} = request;
const serverSocket = net.connect({
port
}, () => {
requestSocket.write(
'HTTP/' + httpVersion + ' 200 Connection established\r\n' +
'\r\n'
);
serverSocket.write(head);
serverSocket.pipe(requestSocket);
requestSocket.pipe(serverSocket);
});
serverSocket.on('error', (error) => {
console.log('server socket error', error);
});
requestSocket.on('error', (error) => {
console.log('request socket error', error);
});
};
const requestHandler = (incomingMessage, outgoingMessage) => {
outgoingMessage.writeHead(200, {
connection: 'close'
});
outgoingMessage.end(Buffer.from('foo'));
};
const main = () => {
const httpServer = http.createServer(requestHandler);
const internalHttpsServer = https
.createServer(sslCertificate, requestHandler)
.listen()
.unref();
httpServer.on('connect', (request, requestSocket, head) => {
handleConnect(
internalHttpsServer.address().port,
request,
requestSocket,
head
);
});
httpServer.listen(8080);
};
main();
</code></pre>
<p>This script can be tested with any HTTPS URL, e.g.</p>
<pre><code>curl --proxy http://127.0.0.1:8080 'https://127.0.0.1/' -k
</code></pre>
<p>Alternatively, you can:</p>
<pre><code>git clone https://github.com/gajus/http-proxy-connection-close.git
cd ./http-proxy-connection-close
node ./server.js
curl --proxy http://127.0.0.1:8080 'https://127.0.0.1/' -k
</code></pre>
<p>How to handle <code>ECONNRESET</code> error when proxied response includes <code>connection: close</code> header?</p>
| 1 | 4,212 |
jQuery Expanding & Collapsing lists
|
<p>The code expands and collapses a list in which list items can have sublists. Any ideas to refactor this code - especially the toggling part. Is it necessary to use closures here ? </p>
<pre><code>$(function()
{
$('li:has(ul)')
.click(function(event){
if (this == event.target)
{
var that = this;
$('li:has(ul)').children().filter(':not(:hidden)').parent().each(function(x){
if(this != that)
toggleList(this);
});
toggleList(this);
}
})
.css({cursor:'pointer', 'list-style-image':'url(plus.gif)'})
.children().hide();
$('li:not(:has(ul))').css({cursor: 'default', 'list-style-image':'none'});
});
function toggleList(L)
{
$(L).css('list-style-image', (!$(L).children().is(':hidden')) ? 'url(plus.gif)' : 'url(minus.gif)');
$(L).children().toggle('fast');
}
</code></pre>
<p><strong>EDIT:</strong></p>
<p>The script works on the following HTML snippet (source: jQuery in Action). Actually I was trying to extend the script given in the book. </p>
<pre><code> <ul>
<li>Item 1</li>
<li>Item 2</li>
<li>
Item 3
<ul>
<li>Item 3.1</li>
<li>
Item 3.2
<ul>
<li>Item 3.2.1</li>
<li>Item 3.2.2</li>
<li>Item 3.2.3</li>
</ul>
</li>
<li>Item 3.3</li>
</ul>
</li>
<li>
Item 4
<ul>
<li>Item 4.1</li>
<li>
Item 4.2
<ul>
<li>Item 4.2.1</li>
<li>Item 4.2.2</li>
</ul>
</li>
</ul>
</li>
<li>Item 5</li>
</ul>
</code></pre>
| 1 | 1,212 |
Radio Buttons getting deselected when dragging item using jQuery Sortables
|
<p>I'm using the <a href="http://docs.jquery.com/UI/Sortables" rel="noreferrer">jQuery UI sortables</a> plugin to allow re-ordering of some list items. Inside each list item, I've got a couple of radio buttons which allow the item to be enabled or disabled.</p>
<p>When the item is dragged, both radio buttons get deselected, which doesn't seem like it should be happening. Is this correct behavior, and if not, what is the best way to work around this?</p>
<p>Here is a code sample demonstrating this problem:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>jQuery Sortables Problem</title>
<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="jquery-ui.min.js" type="text/javascript"></script>
<style type="text/css">
.items
{
margin-top: 30px;
margin-left: 0px;
padding-left: 25px;
cursor: move;
}
.items li
{
padding: 10px;
font-size: 15px;
border: 1px solid #666;
background: #eee;
width: 400px;
margin-bottom: 15px;
float: left;
clear:both;
}
</style>
</head>
<body>
<ol id="itemlist" class="items">
<li id="1" class="item">
Item 1
<input name="status_1" type="radio" value="1" checked="checked" />enabled
<input name="status_1" type="radio" value="0" />disabled
</li>
<li id="2" class="item">
Item 2
<input name="status_2" type="radio" value="1" checked="checked" />enabled
<input name="status_2" type="radio" value="0" />disabled
</li>
<li id="3" class="item">
Item 3
<input name="status_3" type="radio" value="1" checked="checked" />enabled
<input name="status_3" type="radio" value="0" />disabled
</li>
<li id="4" class="item">
Item 4
<input name="status_4" type="radio" value="1" checked="checked" />enabled
<input name="status_4" type="radio" value="0" />disabled
</li>
</ol>
<script type="text/javascript">
$('#itemlist').sortable();
</script>
</body>
</html>
</code></pre>
<p>As soon as a list item is grabbed with the mouse, both the radio buttons get deselected.</p>
<p>If this is a bug, one workaround would be to automatically select the 'enabled' radio button when the item is moved, so any advice on how to achieve this would also be most appreciated.</p>
<p>Update: I've tested this in FireFox 3, Internet Explorer 7, Opera 9.5, and Safari 3.1.2, all on Windows XP x64, and this issue occurs in all of them.</p>
| 1 | 1,299 |
Panel data fixed effect issue with R, I don't see my all dummy variables in the summary
|
<p>I'm running a data panel regression with R.
I use those <a href="https://docs.google.com/spreadsheets/d/1fXzrKS0ABn-ygKWnGhKskmoCLNikZCsY_u1yu08uSq4/edit?usp=sharing" rel="nofollow noreferrer">data</a>(sheet 2).</p>
<p>I want to use a fixed effect for my panel data. Please, find below the code for my fixed effect</p>
<pre><code>FE_1 <- plm(GDP_per_capita_growth ~
log(GDP_per_capita) + GF_GDP + MA_GDP +
start_business + Invest_GDP +
second_schooling + Pop_growth +
log(Inflation_CPI) + Trade +
GF_GDP * start_business +
factor(as.character(time_fixed_effect)) +
factor(as.character(regional)) +
factor(as.character(oil_exporting_countries)),
data = Temp_1,
index = c("country",
"year"),
na.action = na.omit,
model = "within")
</code></pre>
<p>When I run the summary for my panel data fixed effect, some variables are missing, such as time_fixed_effect, regional and oil_exporting_countries.
Below, the result I got.</p>
<pre><code>Coefficients:
Estimate Std. Error t-value Pr(>|t|)
log(GDP_per_capita) -1.9676e+01 5.0218e+00 -3.9181 0.0001386 ***
GF_GDP 1.2637e+00 1.9705e+00 0.6413 0.5223695
MA_GDP 1.9337e+01 8.3736e+00 2.3093 0.0223807 *
start_business -1.3378e-07 1.0077e-07 -1.3276 0.1864403
Invest_GDP 1.5166e-08 1.1173e-08 1.3574 0.1768341
second_schooling -4.9808e-01 5.4186e+00 -0.0919 0.9268910
Pop_growth -1.6174e+00 5.9779e-01 -2.7055 0.0076606 **
log(Inflation_CPI) 1.3861e-01 3.2403e-01 0.4278 0.6694806
Trade 1.8669e-02 1.8617e-02 1.0028 0.3176852
factor(as.character(time_fixed_effect))1 3.8295e-01 4.4318e-01 0.8641 0.3890017
GF_GDP:start_business 5.0494e-07 3.4416e-07 1.4672 0.1445566
---
</code></pre>
<p>I would like to know, what should I need to do to display all my dummy variables. Is there an error somewhere in my code?</p>
<p>Instead of having <code>index = c("country", "year"),</code>, I wrote <code>index = c("year", "country"),</code>, and I got this following result: </p>
<pre><code>Coefficients:
Estimate Std. Error t-value Pr(>|t|)
log(GDP_per_capita) -3.3627e+00 2.0642e+00 -1.6291 0.105013
GF_GDP 1.2334e+00 1.8129e+00 0.6804 0.497127
MA_GDP 5.2312e-01 6.4419e+00 0.0812 0.935366
start_business 1.4314e-08 3.0105e-08 0.4755 0.635022
Invest_GDP -9.8744e-10 1.5174e-09 -0.6507 0.516025
second_schooling 1.0860e+00 1.0806e+00 1.0050 0.316205
Pop_growth -6.3753e-01 2.2690e-01 -2.8097 0.005494 **
log(Inflation_CPI) 1.4547e-01 2.5011e-01 0.5816 0.561550
Trade 9.2730e-04 3.8306e-03 0.2421 0.808991
factor(as.character(regional))2 -1.0668e+00 8.3584e-01 -1.2763 0.203441
factor(as.character(regional))3 -2.6186e-01 6.6220e-01 -0.3954 0.692972
factor(as.character(regional))4 1.4760e-01 7.9347e-01 0.1860 0.852639
factor(as.character(regional))5 1.3558e+00 7.2400e-01 1.8727 0.062696 .
factor(as.character(oil_exporting_countries))1 -1.8890e-01 4.4884e-01 -0.4209 0.674344
GF_GDP:start_business -2.9751e-08 1.3526e-07 -0.2199 0.826157
---
</code></pre>
<p>I don't know why I got this result! Can you help me to find out why, please? And also help me to display my "time_fixed-effect" variable, please.</p>
<p>Thank you in advance for your precious help.</p>
<p>PS: This is complete code</p>
<pre><code># Rename column names
colnames(my_data)[4] <- "Invest_GDP" # percentage
colnames(my_data)[9] <- "Pr_sector_GDP" # percentage
colnames(my_data)[12] <- "start_business"
colnames(my_data)[16] <- "second_schooling"
colnames(my_data)[18] <- "GDP_per_capita_growth"
# Transform column "inflation" as numeric
my_data$Inflation_CPI <- as.numeric(my_data$Inflation_CPI)
my_data$second_schooling <- as.numeric(my_data$second_schooling)
Temp_1 <- my_data %>%
select(
-region,
-Pr_sector_GDP,
-Prop_rights,
-T_freedom,
-current_invest
)
</code></pre>
| 1 | 2,754 |
In .Net Core 2.1 Web API for PUT and DELETE only why "No 'Access-Control-Allow-Origin' header is present on the requested resource"
|
<p>I am using .NET Core 2.1. I have configured Startup.cs as follow: </p>
<pre><code>public class Startup
{
public static IConfiguration Configuration { get; private set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
</code></pre>
<p>Web API is deployed on linux machine. <code>GET</code> and <code>POST</code> methods are working fine. When I try to call <code>PUT</code> or <code>DELETE</code> this message is being generated in <code>Chroome</code> console. </p>
<p><code>Access to XMLHttpRequest at 'http://IP' from origin 'http://IP' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.</code> </p>
<p>Initially Kestrel was listing on <code>50001</code> beacuse SSL certificate was present. I configured Kestrel in <code>appsettings.json</code> to listen only on <code>5000</code>. So now its only listing on <code>5000</code>.</p>
<p><strong>appsettings.json</strong></p>
<pre><code>{
"Kestrel": {
"EndPoints": {
"Http": {
"Url": "http://localhost:5000"
}
}
}
}
</code></pre>
<p>I've tried almost every answer given in this thread <a href="https://stackoverflow.com/questions/44379560/how-to-enable-cors-in-asp-net-core-webapi">How to enable CORS in ASP.net Core WebAPI</a></p>
<p>None of them worked in my case. </p>
<p><code>Origin</code> is my localhost and Web API is on Live IP.</p>
<p><strong>EDIT 1</strong></p>
<p><strong>Preflight (OPTIONS) Response Headers</strong></p>
<pre><code>HTTP/1.1 204 No Content
Server: nginx/1.14.0 (Ubuntu)
Date: Sat, 25 Apr 2020 18:50:50 GMT
Connection: keep-alive
Access-Control-Allow-Headers: authtoken,authuser,content-type
Access-Control-Allow-Methods: PUT
Access-Control-Allow-Origin: *
</code></pre>
<p><strong>Preflight (OPTIONS) Request Headers</strong> </p>
<pre><code>OPTIONS /Foo/Controller HTTP/1.1
Host: MY LINUX Machine Live IP
Connection: keep-alive
Access-Control-Request-Method: PUT
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36
Access-Control-Request-Headers: authtoken,authuser,content-type
Accept: */*
Referer: http://localhost:8080/xyz
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
</code></pre>
<p><strong>Actual Request (Request Headers)</strong></p>
<pre><code>PUT /Foo/Controller HTTP/1.1
Host: Linux IP
Connection: keep-alive
Content-Length: 63
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36
Content-Type: application/json
Referer: http://localhost:8080/xyz
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
</code></pre>
<p><strong>Actual Request (Response Headers)</strong></p>
<pre><code>HTTP/1.1 500 Internal Server Error
Content-Type: text/html
Content-Length: 225
Connection: Close
</code></pre>
| 1 | 1,378 |
Deserialize Json to class object using restsharp
|
<p>I have checked out the documentation for restsharp and also googled for a solution, but unable to find a solution for this problem:</p>
<p>I have an asp.net mvc3 app and need to connect to quizlet.com to access public flashcards. I have added a reference to restsharp and created the following classes:</p>
<pre><code>public class QuizletObject
{
public string response_type { get; set; }
public int total_results { get; set; }
public int page { get; set; }
public int total_pages { get; set; }
public int sets_with_images { get; set; }
public Set[] sets { get; set; }
}
public class Set
{
public int id { get; set; }
public string title { get; set; }
public string url { get; set; }
public string creator { get; set; }
public int created { get; set; }
public int term_count { get; set; }
public bool has_images { get; set; }
public int last_modified { get; set; }
}
</code></pre>
<p>I have a class and method that calls the web service like this:</p>
<pre><code>public class Quizlet
{
private string _baseUrl = "http://api.quizlet.com/1.0/sets";
private const string DevKey = "my dev key";
public QuizletObject GetQuizletSets()
{
_baseUrl = _baseUrl + "?dev_key=" + DevKey + "&q=" + "geography";
RestClient client = new RestClient();
client.BaseUrl = _baseUrl;
RestRequest request = new RestRequest(Method.GET);
request.RequestFormat = DataFormat.Json;
RestResponse<QuizletObject> response = client.Execute<QuizletObject>(request);
return response.Data;
}
}
</code></pre>
<p>When I try to access the method using the below code in the view, I get a <strong>NullReference exception (Object reference not set to an instance of an object).</strong></p>
<pre><code>@{
QuizletObject quizletObject = quizlet.GetQuizletSets();
}
@foreach (Set quizletSet in quizletObject.sets)
{
@quizletSet.id.ToString()
<br />
@quizletSet.title
<br />
@quizletSet.creator
<br />
@quizletSet.created
<br />
@Html.Encode(quizletSet.url)
<br />
<br />
}
</code></pre>
<p>If the same method is executed as below, it returns the complete json object without any problem</p>
<pre><code>RestResponse response = client.Execute(request);
</code></pre>
<p>Stack trace:</p>
<pre><code>[NullReferenceException: Object reference not set to an instance of an object.]
ASP._Page_Views_Home_Index_cshtml.Execute() in c:\Users\Girish\Documents\Visual Studio 2010\Projects\RestSharpPoC\RestSharpPoC\Views\Home\Index.cshtml:18
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +81
System.Web.WebPages.StartPage.RunPage() +19
System.Web.WebPages.StartPage.ExecutePageHierarchy() +65
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +220
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +303
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +260
System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8963149
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
</code></pre>
| 1 | 1,838 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.