title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
what is the cause of SMTP.MAIL: the Operation has timed out?
|
<p>I am creating an intranet web-based application that will send notifications to its users depending on the Admin's choice. </p>
<p><strong>I developed the Mailing page correctly and it work fine with 15 or 20 users. Now, I have more than 200 users, so when I run this page I got the following error and I don't know why:</strong></p>
<blockquote>
<p>Exception Details: System.Net.Mail.SmtpException: The operation has
timed out.</p>
</blockquote>
<p>My Code-Behind (C#):</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
SendEmailTOAllUser();
}
protected void SendEmail(string toAddresses, string fromAddress, string MailSubject, string MessageBody, bool isBodyHtml)
{
SmtpClient sc = new SmtpClient("MAIL.companyDomainName.com");
try
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("pssp@companyDomainName.com", "PMOD Safety Services Portal (PSSP)");
// In case the mail system doesn't like no to recipients. This could be removed
//msg.To.Add("pssp@companyDomainName.com");
msg.Bcc.Add(toAddresses);
msg.Subject = MailSubject;
msg.Body = MessageBody;
msg.IsBodyHtml = isBodyHtml;
//Response.Write(msg);
sc.Send(msg);
}
catch (Exception ex)
{
throw ex;
}
}
protected void SendEmailTOAllUser()
{
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspEmail;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connString))
{
var sbEmailAddresses = new System.Text.StringBuilder(1000);
string quizid = "";
// Open DB connection.
conn.Open();
string cmdText = "SELECT MIN (QuizID) As mQuizID FROM dbo.QUIZ WHERE IsSent <> 1";
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
{
while (reader.Read())
{
// There is only 1 column, so just retrieve it using the ordinal position
quizid = reader["mQuizID"].ToString();
}
}
reader.Close();
}
string cmdText2 = "SELECT Username FROM dbo.employee";
using (SqlCommand cmd = new SqlCommand(cmdText2, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
{
while (reader.Read())
{
var sName = reader.GetString(0);
if (!string.IsNullOrEmpty(sName))
{
if (sbEmailAddresses.Length != 0)
{
sbEmailAddresses.Append(",");
}
// Just use the ordinal position for the user name since there is only 1 column
sbEmailAddresses.Append(sName).Append("@companyDomainName.com");
}
}
}
reader.Close();
}
string cmdText3 = "UPDATE dbo.Quiz SET IsSent = 1 WHERE QuizId = @QuizID";
using (SqlCommand cmd = new SqlCommand(cmdText3, conn))
{
// Add the parameter to the command
var oParameter = cmd.Parameters.Add("@QuizID", SqlDbType.Int);
// Get a local copy of the email addresses
var sEMailAddresses = sbEmailAddresses.ToString();
string link = "<a href='http://pmv/pssp/StartQuiz.aspx?testid=" + quizid + "'> Click here to participate </a>";
string body = @"Good day, <br /><br />
<b> Please participate in the new short safety quiz </b>"
+ link +
@"<br /><br />
Also, give yourself a chance to gain more safety culture by reading the PMOD Newsletter.
<br /> <br /><br /> <br />
This email was generated using the <a href='http://pmv/pssp/Default.aspx'>PMOD Safety Services Portal (PSSP) </a>.
Please do not reply to this email.
";
SendEmail(sEMailAddresses, "", "Notification of New Weekly Safety Quiz", body, true);
// Update the parameter for the current quiz
oParameter.Value = quizid;
// And execute the command
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
</code></pre>
<p><strong>Any help please?</strong></p>
| 0 | 2,649 |
error in sqlite "DROP TABLE IF EXISTS" android
|
<p>so i have a problem in my DBAdapter class its just crushes when i try to open the database:
from the LogCat i guess the problem is in the onUpgrade function:</p>
<pre><code> public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w("SingleDBAdapter", "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(db);
}
}
</code></pre>
<p>here is the error:</p>
<pre><code>07-28 11:32:49.443: E/Database(1244): Failure 1 (near "122": syntax error) on 0x2435b0 when preparing 'DROP TABLE IF EXISTS 122'.
07-28 11:32:49.463: D/AndroidRuntime(1244): Shutting down VM
07-28 11:32:49.463: W/dalvikvm(1244): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
07-28 11:32:49.473: E/AndroidRuntime(1244): FATAL EXCEPTION: main
07-28 11:32:49.473: E/AndroidRuntime(1244): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.shop.list/com.shop.list.main}: android.database.sqlite.SQLiteException: near "122": syntax error: **DROP TABLE IF EXISTS 122**
07-28 11:32:49.473: E/AndroidRuntime(1244): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
07-28 11:32:49.473: E/AndroidRuntime(1244): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-28 11:32:49.473: E/AndroidRuntime(1244): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-28 11:32:49.473: E/AndroidRuntime(1244): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-28 11:32:49.473: E/AndroidRuntime(1244): at android.os.Handler.dispatchMessage(Handler.java:99)
07-28 11:32:49.473: E/AndroidRuntime(1244): at android.os.Looper.loop(Looper.java:123)
07-28 11:32:49.473: E/AndroidRuntime(1244): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-28 11:32:49.473: E/AndroidRuntime(1244): at java.lang.reflect.Method.invokeNative(Native Method)
07-28 11:32:49.473: E/AndroidRuntime(1244): at java.lang.reflect.Method.invoke(Method.java:521)
07-28 11:32:49.473: E/AndroidRuntime(1244): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-28 11:32:49.473: E/AndroidRuntime(1244): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-28 11:32:49.473: E/AndroidRuntime(1244): at dalvik.system.NativeStart.main(Native Method)
07-28 11:32:49.473: E/AndroidRuntime(1244): Caused by: android.database.sqlite.SQLiteException: near "122": syntax error: DROP TABLE IF EXISTS 122
07-28 11:32:49.473: E/AndroidRuntime(1244): at android.database.sqlite.SQLiteDatabase.native_execSQL(Native Method)
07-28 11:32:49.473: E/AndroidRuntime(1244): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1727)
07-28 11:32:49.473: E/AndroidRuntime(1244): at com.shop.list.ListDBAdapter$DatabaseHelper.onUpgrade(ListDBAdapter.java:51)
07-28 11:32:49.473: E/AndroidRuntime(1244): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:108)
07-28 11:32:49.473: E/AndroidRuntime(1244): at com.shop.list.ListDBAdapter.open(ListDBAdapter.java:60)
07-28 11:32:49.473: E/AndroidRuntime(1244): at com.shop.list.main.onCreate(main.java:60)
07-28 11:32:49.473: E/AndroidRuntime(1244): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-28 11:32:49.473: E/AndroidRuntime(1244): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-28 11:32:49.473: E/AndroidRuntime(1244): ... 11 more
</code></pre>
<p>i highlighted the problem but i cant solve it :/</p>
| 0 | 1,428 |
What is the difference between [[0 for _ in range(10)] for _ in range(10)] and [0 for _ in range(10)] * 10?
|
<pre><code>>>> CM = [[0 for _ in range(10)]] * 10
>>> CM
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
>>> CM[0][0] = CM[0][0] + 1
>>> CM
[[1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
</code></pre>
<p>I was trying to create a confusion matrix. It basically contains count of the (i, j) pairs.
I first created a list of lists, and then incremented the appropriate variable. However, it didn't work as expected. CM[i][0] got incremented for all values of i.</p>
<p>I found a work around.</p>
<pre><code>>>> CM = [[0 for _ in range(10)] for _ in range(10)]
>>> CM
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
>>> CM[0][0] = CM[0][0] + 1
>>> CM
[[1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
</code></pre>
<p>But I would be grateful if someone could explain why the first method failed.</p>
| 0 | 1,155 |
Kubernetes AutoScaler Not Scaling, HPA shows target <unknown>
|
<p>I'm pretty new to kubernetes, not so much with docker.</p>
<p>I've been working through the example but I am stuck with the autoscaler, (which doesn't seem to scale).</p>
<p>I am working through the example here <a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/#step-one-run--expose-php-apache-server" rel="noreferrer">https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/#step-one-run--expose-php-apache-server</a></p>
<p>You'll find the build at the bottom</p>
<p><code>kubectl create -f https://k8s.io/docs/tasks/run-application/hpa-php-apache.yaml</code></p>
<p>Which looks like this </p>
<pre><code>apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
name: php-apache
namespace: default
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: php-apache
minReplicas: 1
maxReplicas: 10
targetCPUUtilizationPercentage: 50
</code></pre>
<p><code>kubectl get hba</code> shows</p>
<pre><code>NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
php-apache Deployment/php-apache <unknown>/50% 1 10 0 7s
</code></pre>
<p>Clue in the <code><unknown></code> section.</p>
<p>Then <code>kubectl describe hba</code> shows</p>
<pre><code>Name: php-apache
Namespace: default
Labels: <none>
Annotations: <none>
CreationTimestamp: Sat, 14 Apr 2018 23:05:05 +0100
Reference: Deployment/php-apache
Metrics: ( current / target )
resource cpu on pods (as a percentage of request): <unknown> / 50%
Min replicas: 1
Max replicas: 10
Conditions:
Type Status Reason Message
---- ------ ------ -------
AbleToScale False FailedGetScale the HPA controller was unable to get the target's current scale: deployments/scale.extensions "php-apache" not found
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Warning FailedGetScale 12s (x14 over 6m) horizontal-pod-autoscaler deployments/scale.extensions "php-apache" not found
</code></pre>
<p>So then I manually add it in with...</p>
<p><code>kubectl run php-apache --image=k8s.gcr.io/hpa-example --requests=cpu=200m --expose --port=80</code></p>
<p>Then if i run <code>kubectl describe hpa</code> again I get this error..</p>
<pre><code>Name: php-apache
Namespace: default
Labels: <none>
Annotations: <none>
CreationTimestamp: Sat, 14 Apr 2018 23:05:05 +0100
Reference: Deployment/php-apache
Metrics: ( current / target )
resource cpu on pods (as a percentage of request): <unknown> / 50%
Min replicas: 1
Max replicas: 10
Conditions:
Type Status Reason Message
---- ------ ------ -------
AbleToScale True SucceededGetScale the HPA controller was able to get the target's current scale
ScalingActive False FailedGetResourceMetric the HPA was unable to compute the replica count: unable to get metrics for resource cpu: unable to fetch metrics from API: the server could not find the requested resource (get pods.metrics.k8s.io)
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Warning FailedGetScale 1m (x21 over 11m) horizontal-pod-autoscaler deployments/scale.extensions "php-apache" not found
Warning FailedGetResourceMetric 8s (x2 over 38s) horizontal-pod-autoscaler unable to get metrics for resource cpu: unable to fetch metrics from API: the server could not find the requested resource (get pods.metrics.k8s.io)
Warning FailedComputeMetricsReplicas 8s (x2 over 38s) horizontal-pod-autoscaler failed to get cpu utilization: unable to get metrics for resource cpu: unable to fetch metrics from API: the server could not find the requested resource (get pods.metrics.k8s.io)
</code></pre>
| 0 | 2,443 |
method to write in log files in a shell script
|
<p>I'm developing a couple of shell scripts and want to add an easy logging method. But till now the the function created only print the first log line. I have a terrible headache cause I cannot understand where is the problem</p>
<p>The logging functions is so easy to develop and to understand:</p>
<pre><code>LOG_FILE="creation.log"
logit()
{
echo "[${USER}][`date`] - ${*}" >> ${LOG_FILE}
}
</code></pre>
<p>And some lines of the script.</p>
<pre><code> LOG_FILE="creation.log"
logit()
{
echo "[${USER}][`date`] - ${*}" >> ${LOG_FILE}
}
repImport()
{
# création des repertoires pour les répertoires d'export.
mkdir -p acharger
mkdir -p archives
logit "repImport correctement crée."
}
repExport()
{
# création des repertoires pour les répertoires d'import.
mkdir -p archives
mkdir -p atraiter
logit "repExport correctement crée."
}
array=(BNP_CB collection_XTL collection_QT sp xcl xtl pgi qnt visualr)
logit "Array généré"
REP_TEST="/tmp/jorge/modules"
REP=${REP_TEST} # Descomentar para hacer test.
REP_LIV_VX="/tmp/jorge/modules/"
# NOTE IMPORTANTE
#------------------
# Obligatoire créer avec l'user root le répertoire /home/pepsicash, après changer le propietaire pour cash --> root /> chown cash.mersi pepsicash/
# deuxième partir (répertoires pour les fichiers)
#----------------------------------------------------
echo "Création des répertoires pour les fichiers"
mkdir -p "${REP}""/journaux" # originel: /home/pepsicash/journaux
mkdir -p "${REP}""/data" # originel: /home/pepsicash/data
cd $REP/data # originel: /home/pepsicash/data
mkdir -p imports
mkdir -p exports
mkdir -p tmpcft
logit "Création des répertoires sur Exports"
cd exports
repExport
cd ..
logit "Création des répertoires sur Imports"
cd imports
for index in ${!array[*]}
do
if [ $index -eq 0 ];
then
if [ -d ${array[$index]} ]; then
logit "El répertoire ENCAISSEMENTS existe déjà."
else
logit "Le répertoire n'existe pas."
mkdir -p ENCAISSEMENTS
logit "Répertoire ENCAISSEMENTS crée correctement."
fi
cd ENCAISSEMENTS
repImport
logit "Répertoire ENCAISSEMENTS crée, CP -> BNP_CB "
cd ..
if [ -d ${array[$index]} ]; then
logit "El répertoire IMPAYES existe déjà."
else
logit "Le répertoire n'existe pas."
mkdir -p IMPAYES
logit "Répertoire IMPAYES crée correctement."
fi
cd IMPAYES
repImport
logit "Répertoire ENCAISSEMENTS crée, CP -> BNP_CB "
cd ..
logit "Case particulier BNP_CB crée."
continue
fi
if [ -d ${array[$index]} ]; then
# Control will enter here if $DIRECTORY exists.
logit "El répertoire existe déjà."
else
logit "Le répertoire n'existe pas."
mkdir -p ${array[$index]}
logit "Répertoire ${array[$index]} crée correctement."
fi
cd ${array[$index]}
repImport
cd ..
done
echo "Fin création des répertoires."
</code></pre>
<p>The logfile only contains the first <code>logit</code> call. Why don't the other calls to the method work?</p>
<pre><code>[JV07483S][Fri Aug 16 18:19:04 CEST 2013] - Array généré
[JV07483S][Fri Aug 16 18:19:30 CEST 2013] - Array généré
</code></pre>
<p>Searching in the web I saw that I can use the logger command, but it always write in the <code>/var/ folder</code>. Is it possible to adapt my shell function to use logger and to write in a file at the current script's folder? </p>
| 0 | 1,549 |
CLOB value in out/return from plsql (invalid LOB locator specified: ORA-22275)
|
<p>I've got stored plsql procedure, that takes big text from file</p>
<pre><code>create or replace
procedure dbst_load_a_file( p_file_name in varchar2, l_clob out clob )
as
l_bfile bfile;
dst_offset number := 1 ;
src_offset number := 1 ;
lang_ctx number := DBMS_LOB.DEFAULT_LANG_CTX;
warning number;
begin
l_bfile := bfilename( 'SCHEMES_OF_PS', p_file_name );
dbms_lob.fileopen( l_bfile );
dbms_lob.loadclobfromfile(
DEST_LOB => l_clob
, SRC_BFILE => l_bfile
, AMOUNT => dbms_lob.getlength( l_bfile )
, DEST_OFFSET => dst_offset
, SRC_OFFSET => src_offset
, BFILE_CSID => DBMS_LOB.DEFAULT_CSID
, LANG_CONTEXT => lang_ctx
, WARNING => warning);
dbms_lob.fileclose( l_bfile );
end;
</code></pre>
<p>and then I try to use it in this way:</p>
<pre><code> insert into SCHEME_SOURCE (SOURCE, ID, CODE)
values (exec dbst_load_a_file( 'SCHEMES_OF_PS', 'Konotop.svg' ), 15, 'Konotop');
</code></pre>
<p>or more correct:</p>
<pre><code>declare
myVal clob := empty_clob();
begin
DBMS_OUTPUT.PUT_LINE(myVal);
dbst_load_a_file('Konotop.svg', myVal);
DBMS_OUTPUT.PUT_LINE(myVal);
end;
</code></pre>
<p>In the second case I get an error </p>
<blockquote>
<p>PL/SQL: numeric or value error: invalid LOB locator specified:
ORA-22275</p>
</blockquote>
<p>in the first case, I suspect that syntax does not exist.</p>
<p>How can I out/return CLOB parameter form the procedure/function for use it out of stored plsql</p>
<p>If I've got this code</p>
<pre><code>create or replace
function dbst_load_a_file2( p_file_name in varchar2 ) return clob
is
l_clob clob;
l_bfile bfile;
dst_offset number := 1 ;
src_offset number := 1 ;
lang_ctx number := DBMS_LOB.DEFAULT_LANG_CTX;
warning number;
begin
l_bfile := bfilename( 'SCHEMES_OF_PS', p_file_name );
dbms_lob.fileopen( l_bfile );
dbms_lob.loadclobfromfile(
DEST_LOB => l_clob
, SRC_BFILE => l_bfile
, AMOUNT => dbms_lob.getlength( l_bfile )
, DEST_OFFSET => dst_offset
, SRC_OFFSET => src_offset
, BFILE_CSID => DBMS_LOB.DEFAULT_CSID
, LANG_CONTEXT => lang_ctx
, WARNING => warning);
dbms_lob.fileclose( l_bfile );
return l_clob;
end;
insert into SCHEME_SOURCE (SOURCE, ID, CODE)
values (dbst_load_a_file2('Konotop.svg' ), 15, 'Konotop');
</code></pre>
<p>Then again got error</p>
<blockquote>
<p>SQL Error: ORA-06502: PL/SQL: numeric or value error: invalid LOB locator specified: ORA-22275
ORA-06512: at "SYS.DBMS_LOB", line 890
ORA-06512: at "VAG.DBST_LOAD_A_FILE2", line 12</p>
</blockquote>
<p>Thanks</p>
| 0 | 1,471 |
css display table cell requires percentage width
|
<p>I've been put in a position where I need to use the display:table-cell command for div elements.</p>
<p>However I've discovered that the "cells" will only work correctly if a percentage is added to the width.</p>
<p>In this fiddle <a href="http://jsfiddle.net/NvTdw/" rel="noreferrer">http://jsfiddle.net/NvTdw/</a> when I remove the percentage width the cells do not have equal widths, however when a percentage value is added to the width all is well, but only when that percentage is equal to the proportion of max no of divs, so for four columns 25%, five 20% and in this case five at 16.666%.</p>
<p>I thought maybe adding a percentage of less - say 1% would be a good fix all, but the cells fall out of line again.</p>
<p>Why is this?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code> .table {
display: table;
height: 200px;
width: 100%;
}
.cell {
display: table-cell;
height: 100%;
padding: 10px;
width: 16.666%;
}
.grey {
background-color: #666;
height: 100%;
text-align: center;
font-size: 48px;
color: #fff;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 300;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="table">
<div class="cell">
<div class="grey">Block one</div>
</div>
<div class="cell">
<div class="grey">Block two</div>
</div>
<div class="cell">
<div class="grey">Block three</div>
</div>
</div>
<div class="table">
<div class="cell">
<div class="grey">Block</div>
</div>
<div class="cell">
<div class="grey">Block two</div>
</div>
</div>
<div class="table">
<div class="cell">
<div class="grey">Block one</div>
</div>
<div class="cell">
<div class="grey">Block two</div>
</div>
<div class="cell">
<div class="grey">Block three</div>
</div>
<div class="cell">
<div class="grey">Block four</div>
</div>
</div>
<div class="table">
<div class="cell">
<div class="grey">x</div>
</div>
<div class="cell">
<div class="grey">xx</div>
</div>
<div class="cell">
<div class="grey">xxx</div>
</div>
<div class="cell">
<div class="grey">xxxx</div>
</div>
<div class="cell">
<div class="grey">xxxxxx</div>
</div>
<div class="cell">
<div class="grey">Block five test</div>
</div>
</div>
<div class="table">
<div class="cell">
<div class="grey">Block</div>
</div>
<div class="cell">
<div class="grey">Block two</div>
</div>
<div class="cell">
<div class="grey">Block three</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| 0 | 1,520 |
Spring Boot Application failed to start with classpath: []
|
<p>I generated a Spring Boot application with <a href="http://www.jhipster.tech/" rel="noreferrer">jHipster</a>, added some code from my previous project (non-jhipster project) and tried to run it using IDEA. First I got an error message similar to <a href="https://intellij-support.jetbrains.com/hc/en-us/community/posts/206905775-classpath-too-long-classpath-file-mode-does-not-work" rel="noreferrer">this</a>, saying "Command line is too long.." (I am running Windows 10 x64). I clicked enable, but then I got an error like this.:</p>
<pre><code>"C:\Program Files\Java\jdk1.8.0_144\bin\java" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:51351,suspend=y,server=n -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=51350 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true -Dfile.encoding=UTF-8 -classpath C:\Users\User\AppData\Local\Temp\classpath.jar com.test.pc.TestPartsComposerApp
Connected to the target VM, address: '127.0.0.1:51351', transport: 'socket'
The Class-Path manifest attribute in C:\Users\User\AppData\Local\Temp\classpath.jar referenced one or more files that do not exist: .... Extremely long list of jars
07:48:56.779 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
07:48:56.779 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
07:48:56.779 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : []
07:48:57.570 [restartedMain] DEBUG org.springframework.boot.logging.ClasspathLoggingApplicationListener - Application failed to start with classpath: []
</code></pre>
<p>After I tried with .<code>/mvnw</code>:</p>
<pre><code>The Class-Path manifest attribute in C:\Users\User\.m2\repository\com\sun\xml\bind\jaxb-impl\2.2.3-1\jaxb-impl-2.2.3-1.jar referenced one or more files that do not exist: C:\Users\User\.m2\repository\com\sun\xml\bind\jaxb-impl\2.2.3-1\jaxb-api.jar,C:\Users\User\.m2\repository\com\sun\xml\bind\jaxb-impl\2.2.3-1\activation.jar,C:\Users\User\.m2\repository\com\sun\xml\bind\jaxb-impl\2.2.3-1\jsr173_1.0_api.jar,C:\Users\User\.m2\repository\com\sun\xml\bind\jaxb-impl\2.2.3-1\jaxb1-impl.jar
The Class-Path manifest attribute in C:\Users\User\.m2\repository\org\liquibase\liquibase-core\3.5.3\liquibase-core-3.5.3.jar referenced one or more files that do not exist: C:\Users\User\.m2\repository\org\liquibase\liquibase-core\3.5.3\lib\snakeyaml-1.13.jar
07:53:54.295 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
07:53:54.295 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
07:53:54.295 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/C:/workspace/jh-fpc/TestPartsComposer/target/classes/]
07:53:55.295 [restartedMain] DEBUG org.springframework.boot.logging.ClasspathLoggingApplicationListener - Application failed to start with classpath: [file:/C:/workspace/jh-fpc/TestPartsComposer/target/classes/]
</code></pre>
<p>I posted my <code>pom.xml</code> <a href="https://pastebin.com/8YhmF8QL" rel="noreferrer">here</a>.</p>
<p>I created a completely new project, and started adding the maven dependencies I had one by one and Ran the project after every step. The problem with the classpath occurs, when I add <strong>BOTH</strong> spring-batch and guava to the pom.</p>
<pre><code><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava-core.version}</version>
</dependency>
</code></pre>
| 0 | 1,667 |
`Building wheel for opencv-python (PEP 517) ... -` runs forever
|
<p>When I run</p>
<pre><code>!pip install imgaug==0.4.0
</code></pre>
<p>the following is the output</p>
<pre><code>Collecting imgaug==0.4.0
Using cached https://files.pythonhosted.org/packages/66/b1/af3142c4a85cba6da9f4ebb5ff4e21e2616309552caca5e8acefe9840622/imgaug-0.4.0-py2.py3-none-any.whl
Requirement already satisfied: Pillow in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (5.4.1)
Requirement already satisfied: numpy>=1.15 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (1.15.4)
Collecting Shapely (from imgaug==0.4.0)
Using cached https://files.pythonhosted.org/packages/9d/18/557d4f55453fe00f59807b111cc7b39ce53594e13ada88e16738fb4ff7fb/Shapely-1.7.1-cp36-cp36m-manylinux1_x86_64.whl
Requirement already satisfied: six in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (1.12.0)
Requirement already satisfied: matplotlib in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (3.0.2)
Collecting scikit-image>=0.14.2 (from imgaug==0.4.0)
Using cached https://files.pythonhosted.org/packages/0e/ba/53e1bfbdfd0f94514d71502e3acea494a8b4b57c457adbc333ef386485da/scikit_image-0.17.2-cp36-cp36m-manylinux1_x86_64.whl
Requirement already satisfied: imageio in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (2.4.1)
Collecting opencv-python (from imgaug==0.4.0)
Using cached https://files.pythonhosted.org/packages/77/f5/49f034f8d109efcf9b7e98fbc051878b83b2f02a1c73f92bbd37f317288e/opencv-python-4.4.0.42.tar.gz
Installing build dependencies ... done
Getting requirements to build wheel ... done
Preparing wheel metadata ... done
Requirement already satisfied: scipy in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from imgaug==0.4.0) (1.2.0)
Requirement already satisfied: cycler>=0.10 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (0.10.0)
Requirement already satisfied: kiwisolver>=1.0.1 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (1.0.1)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (2.3.1)
Requirement already satisfied: python-dateutil>=2.1 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from matplotlib->imgaug==0.4.0) (2.7.5)
Collecting tifffile>=2019.7.26 (from scikit-image>=0.14.2->imgaug==0.4.0)
Using cached https://files.pythonhosted.org/packages/3c/13/4f873f6b167c2e77288ce8db1c9f742d1e0e1463644e2df4e3bd3c40a422/tifffile-2020.8.25-py3-none-any.whl
Requirement already satisfied: networkx>=2.0 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from scikit-image>=0.14.2->imgaug==0.4.0) (2.2)
Collecting PyWavelets>=1.1.1 (from scikit-image>=0.14.2->imgaug==0.4.0)
Using cached https://files.pythonhosted.org/packages/59/bb/d2b85265ec9fa3c1922210c9393d4cdf7075cc87cce6fe671d7455f80fbc/PyWavelets-1.1.1-cp36-cp36m-manylinux1_x86_64.whl
Requirement already satisfied: setuptools in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from kiwisolver>=1.0.1->matplotlib->imgaug==0.4.0) (40.8.0)
Requirement already satisfied: decorator>=4.3.0 in /opt/conda/envs/Python-3.6/lib/python3.6/site-packages (from networkx>=2.0->scikit-image>=0.14.2->imgaug==0.4.0) (4.3.2)
Building wheels for collected packages: opencv-python
Building wheel for opencv-python (PEP 517) ... -
</code></pre>
<p>But the <code>Building wheel for opencv-python (PEP 517) ... -</code> runs forever, how to resolve this problem?</p>
| 0 | 1,688 |
How to get items row id of repeater when user clicks rows linkbutton control
|
<p>I have a repeater, nested with Html table rows:</p>
<pre><code><asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<HeaderTemplate>
<table id="grid">
<thead>
<tr>
<th>SID</th>
<th>Start Date</th>
<th>End Date</th>..
<th>PDF Text</th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#DataBinder.Eval(Container.DataItem,"ID") %></td>
<td><%#DataBinder.Eval(Container.DataItem,"startDate") %></td>
<td><%#DataBinder.Eval(Container.DataItem,"endDate") %></td
<td>
<asp:LinkButton runat="server" ID="lbtnPDF" Text="PDF Full Text" OnClick="lbtnPDF_Click" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
</code></pre>
<p>When the user clicks on linkbutton, I want to get the ID of that row of repeater item and will display the PDF file which is related to that ID, in another aspx page.</p>
<p>I wrote on itemdatabound event :</p>
<pre><code>protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
LinkButton lnkBtn = (LinkButton)e.Item.FindControl("lbtnPDF");
}
</code></pre>
<p>How can I get column Id of repeater nested with an html table?</p>
| 0 | 1,165 |
How to send file through socket in c#
|
<p>I have server and client console apps which communicate fine as well as sending some string. Here is the code...</p>
<p>Server</p>
<pre><code>public static void Main()
{
try
{
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 1234);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" + myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recieved...");
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
/* clean up */
s.Close();
myList.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
</code></pre>
<p>Client</p>
<pre><code>public static void Main()
{
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting...");
tcpclnt.Connect("127.0.0.1", 1234);
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted: ");
String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine("Transmitting...");
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (Exception e)
{
Console.WriteLine("Error... " + e.StackTrace);
}
}
</code></pre>
<p>Now, I need to add the code algorithm which will send a file through the same apps. The key thing to implement is to use Socket.Send in the client. I am not sure about serialization and de-serialization of the the file.</p>
<p>Any hint, advice, suggestion is more that welcome. Thanks.</p>
| 0 | 1,242 |
Combining a while loop with Task.Run() in C#
|
<p>I'm pretty new to multithread applications in C# and I'm trying to edit my code below so that it runs on multiple threads. Right now it operates synchronously and it takes up very little cpu power. I need it to run much faster on multiple threads. My thought was starting a task for each core and then when a task finishes, allow another to take its place or something like that if it is possible.</p>
<pre><code>static void Main(string[] args)
{
string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
QueueClient Client = QueueClient.CreateFromConnectionString(connectionString, "OoplesQueue");
try
{
while (true)
{
Task.Run(() => processCalculations(Client));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
public static ConnectionMultiplexer connection;
public static IDatabase cache;
public static async Task processCalculations(QueueClient client)
{
try
{
BrokeredMessage message = await client.ReceiveAsync();
if (message != null)
{
if (connection == null || !connection.IsConnected)
{
connection = await ConnectionMultiplexer.ConnectAsync("connection,SyncTimeout=10000,ConnectTimeout=10000");
//connection = ConnectionMultiplexer.Connect("connection,SyncTimeout=10000,ConnectTimeout=10000");
}
cache = connection.GetDatabase();
string sandpKey = message.Properties["sandp"].ToString();
string dateKey = message.Properties["date"].ToString();
string symbolclassKey = message.Properties["symbolclass"].ToString();
string stockdataKey = message.Properties["stockdata"].ToString();
string stockcomparedataKey = message.Properties["stockcomparedata"].ToString();
List<StockData> sandp = cache.Get<List<StockData>>(sandpKey);
DateTime date = cache.Get<DateTime>(dateKey);
SymbolInfo symbolinfo = cache.Get<SymbolInfo>(symbolclassKey);
List<StockData> stockdata = cache.Get<List<StockData>>(stockdataKey);
List<StockMarketCompare> stockcomparedata = cache.Get<List<StockMarketCompare>>(stockcomparedataKey);
StockRating rating = performCalculations(symbolinfo, date, sandp, stockdata, stockcomparedata);
if (rating != null)
{
saveToTable(rating);
if (message.LockedUntilUtc.Minute <= 1)
{
await message.RenewLockAsync();
}
await message.CompleteAsync();
}
else
{
Console.WriteLine("Message " + message.MessageId + " Completed!");
await message.CompleteAsync();
}
}
}
catch (TimeoutException time)
{
Console.WriteLine(time.Message);
}
catch (MessageLockLostException locks)
{
Console.WriteLine(locks.Message);
}
catch (RedisConnectionException redis)
{
Console.WriteLine("Start the redis server service!");
}
catch (MessagingCommunicationException communication)
{
Console.WriteLine(communication.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
</code></pre>
| 0 | 1,760 |
Show form based on radio button select
|
<p>I have the following html which has two forms with form <code>id=cardpayment</code> for first form and form <code>id="intenetpayment"</code> for the second.</p>
<p>Also I have 3 radio buttons named "Debit card","Credit Card","Internet Banking".</p>
<p>All I want to do is,when I select the radio button Debitcard or Credit card,form with <code>id="cardpayment"</code> should be shown and the other form should be hidden and when i click on Internetbanking radio button , form with <code>id="cardpayment"</code> should be hidden and form with <code>id="internetpayment"</code> should be shown. Im new to jquery and javascript.I checked online that this can be done using a css by adding/removing a css class </p>
<pre><code>{
display:none;
}
</code></pre>
<p>But i dont know how to make it work using javascript.</p>
<p>You can find the fiddle at <a href="http://jsfiddle.net/d5qDb/1/" rel="nofollow">http://jsfiddle.net/d5qDb/1/</a></p>
<p>Pardon for the long question,and I havnt included the css here for not confusing the question.It is in the fiddle anyway.thanks in advance for any help.I have given the division to two forms below.</p>
<pre><code> <body>
<div id="credit-card">
<header>
<span class="title" style="background-image: url('images/fethrpowered.png');"><strong>Card Payment:</strong> Enter payment details</span>
<a href="#"><span class="close"><img src="images/close.png"/></span></a>
</header>
<section id="content">
<div class="title"><strong>Payment Mode- Select your payment mode</strong></div>
<input type="radio" id="radio1" name="radios" value="all" checked>
<label for="radio1">Credit Card</label>
<input type="radio" id="radio2" name="radios"value="false">
<label for="radio2">Debit Card</label>
<input type="radio" id="radio3" name="radios"value="false">
<label for="radio3">Internet Banking</label>
<form method="post" id="cardpayment">
<div style="float:right;margin-top:50px;">
<input type='hidden' id='ccType' name='ccType' />
<ul class="cards">
<li class="visa">Visa</li>
<li class="visa_electron">Visa Electron</li>
<li class="mastercard">MasterCard</li>
<li class="maestro">Maestro</li>
</ul>
</div>
<div class="table form-fields">
<div class="row">
<div class="label">Card Number:</div>
<div class="input full"><input type="text" name="ccnumber" id="ccnumber" placeholder="8763125487533457"/><br/></div>
</div>
<div class="row">
<div class="label">Card Type:</div>
<div class="input full">
<select class="styled">
<option selected>Visa</option>
<option>Mastercard</option>
<option>Maestro</option>
<option>SBI Maestro</option>
</select>
</div>
<div class="valid"></div>
</div>
<div class="row">
<div class="label">Your name:</div>
<div class="input full"><input type="text" name="name" id="name" placeholder="Mr. Personality of TV"/></div>
</div>
<div class="row name">
<div class="label">Expires On:</div>
<div class="input size50">
<select class="styled">
<option selected>Select Month</option>
<option value="01">January</option>
<option value="02">February</option>
<option value="03">March</option>
<option value="04">April</option>
<option value="05">May</option>
<option value="06">June</option>
<option value="07">July</option>
<option value="08">August</option>
<option value="09">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select class="styled">
<option selected>Select Year</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
<option value="2023">2023</option>
<option value="2024">2024</option>
<option value="2025">2025</option>
<option value="2026">2026</option> <option value="2027">2027</option>
<option value="2028">2028</option>
<option value="2029">2029</option>
<option value="2030">2030</option>
<option value="2031">2031</option>
<option value="2032">2032</option>
<option value="2033">2033</option>
<option value="2034">2034</option>
<option value="2035">2035</option>
<option value="2036">2036</option>
</select>
</div>
<div class="valid"></div>
</div>
<div class="row name">
<div class="label">CVV Number:</div>
<div class="input size50"><input type="text" name="cvv" id="cvv" placeholder="490" maxlength="3"/></div>
</div>
</div>
<input type="submit" style="float:right" value="Pay Now"/>
</form>
</code></pre>
<hr>
<pre><code> <form method="post" id="internetpayment">
<div class="table form-fields">
<div class="row name">
<div class="label">Name:</div>
<div class="input full"><input type="text" name="name" id="Name" placeholder="Enter your name"/></div>
</div>
<div class="row name">
<div class="label">Email:</div>
<div class="input full"><input type="text" name="email" id="email" placeholder="Enter Email address"/></div>
</div>
<div class="row name">
<div class="label">Mobile Number:</div>
<div class="input size50"><input type="text" name="Mobile Number" id="mobileNo"/></div>
</div>
<div class="row name">
<div class="label">Bank:</div>
<div class="input size50">
<select name="BankId" class="styled" data-required="true" data-trigger="change">
<option value="CORP">Corporation </option>
<option value="HDFC"> HDFC </option>
<option value="ICICI"> ICICI </option>
<option value="IDBI"> IDBI </option>
<option value="SBI"> STATE BANK OF INDIA </option>
<option value="DB"> DEUTSCHE </option>
</select>
</div>
<div class="valid"></div>
</div>
<div class="row name">
<div class="label">Amount:</div>
<div class="input size50"><input type="text" name="amount" id="amount" placeholder="10.00"/></div>
</div>
</div>
<input type="submit" style="float:right" value="Pay Now"/>
</form>
</section>
</div>
</body>
</code></pre>
| 0 | 5,334 |
Unknown data type "JSONB" when running tests in play slick with H2 Database
|
<p>I have evolution problem <strong>Unknown data type: "JSONB"</strong> when running tests in playframework using </p>
<ul>
<li>playframework v2.6.6 for scala</li>
<li>play-slick v3.0.2</li>
<li>play-slick-evolutions v3.0.2</li>
<li>postgresql - 42.0.0</li>
<li>h2database - 1.4.194</li>
</ul>
<p>My H2DbConnector looks like this:</p>
<pre><code>import entities.StubData._
import org.scalatest.{BeforeAndAfterAll, FunSuite}
import play.api.db.DBApi
import play.api.db.evolutions.Evolutions
import play.api.inject.guice.GuiceApplicationBuilder
trait H2DbConnector extends FunSuite with BeforeAndAfterAll {
val appBuilder = new GuiceApplicationBuilder()
.configure(configuration)
val injector = appBuilder.injector
lazy val databaseApi = injector.instanceOf[DBApi]
override def beforeAll() = {
Evolutions.applyEvolutions(databaseApi.database("default"))
}
override def afterAll() = {
Evolutions.cleanupEvolutions(databaseApi.database("default"))
}
}
</code></pre>
<p>In application.test.conf</p>
<pre><code>slick.dbs.default.driver = "slick.driver.H2Driver$"
slick.dbs.default.db.driver = "org.h2.Driver"
slick.dbs.default.db.url = "jdbc:h2:mem:play;MODE=PostgreSQL;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=FALSE"
</code></pre>
<p>I've got one problematic line in evolutions 2.sql file</p>
<pre><code>ALTER TABLE "Messages" ADD COLUMN "metaJson" JSONB NULL;
</code></pre>
<p>When I run dao tests getting error like</p>
<pre><code>2017-12-21 16:08:40,409 [error] p.a.d.e.DefaultEvolutionsApi - Unknown data type: "JSONB"; SQL statement:
ALTER TABLE "Messages" ADD COLUMN "metaJson" JSONB NULL [50004-194] [ERROR:50004, SQLSTATE:HY004]
[info] OptoutsDaoTest *** ABORTED ***
[info] play.api.db.evolutions.InconsistentDatabase: Database 'default' is in an inconsistent state![An evolution has not been applied properly. Please check the problem and resolve it manually before marking it as resolved.]
[info] at play.api.db.evolutions.DatabaseEvolutions.$anonfun$checkEvolutionsState$3(EvolutionsApi.scala:285)
[info] at play.api.db.evolutions.DatabaseEvolutions.$anonfun$checkEvolutionsState$3$adapted(EvolutionsApi.scala:270)
[info] at play.api.db.evolutions.DatabaseEvolutions.executeQuery(EvolutionsApi.scala:317)
[info] at play.api.db.evolutions.DatabaseEvolutions.checkEvolutionsState(EvolutionsApi.scala:270)
[info] at play.api.db.evolutions.DatabaseEvolutions.evolve(EvolutionsApi.scala:239)
[info] at play.api.db.evolutions.Evolutions$.applyEvolutions(Evolutions.scala:193)
[info] at H2DbConnector.beforeAll(H2DbConnector.scala:15)
[info] at H2DbConnector.beforeAll$(H2DbConnector.scala:14)
[info] at OptoutsDaoTest.beforeAll(OptoutsDaoTest.scala:5)
[info] at org.scalatest.BeforeAndAfterAll.liftedTree1$1(BeforeAndAfterAll.scala:212)
[info] ...
</code></pre>
<p>Could you help me please to fix this issue?</p>
| 0 | 1,102 |
Java java.util.ConcurrentModificationException error
|
<p>please can anybody help me solve this problem last so many days I could not able to solve this error. I tried using synchronized method and other ways but did not work so please help me</p>
<h3>Error</h3>
<pre><code>java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.remove(Unknown Source)
at JCA.startAnalysis(JCA.java:103)
at PrgMain2.doPost(PrgMain2.java:235)
</code></pre>
<h3>Code</h3>
<pre><code> public synchronized void startAnalysis() {
//set Starting centroid positions - Start of Step 1
setInitialCentroids();
Iterator<DataPoint> n = mDataPoints.iterator();
//assign DataPoint to clusters
loop1:
while (true) {
for (Cluster c : clusters)
{
c.addDataPoint(n.next());
if (!n.hasNext())
break loop1;
}
}
//calculate E for all the clusters
calcSWCSS();
//recalculate Cluster centroids - Start of Step 2
for (Cluster c : clusters) {
c.getCentroid().calcCentroid();
}
//recalculate E for all the clusters
calcSWCSS();
// List copy = new ArrayList(originalList);
//synchronized (c) {
for (int i = 0; i < miter; i++) {
//enter the loop for cluster 1
for (Cluster c : clusters) {
for (Iterator<DataPoint> k = c.getDataPoints().iterator(); k.hasNext(); ) {
// synchronized (k) {
DataPoint dp = k.next();
System.out.println("Value of DP" +dp);
//pick the first element of the first cluster
//get the current Euclidean distance
double tempEuDt = dp.getCurrentEuDt();
Cluster tempCluster = null;
boolean matchFoundFlag = false;
//call testEuclidean distance for all clusters
for (Cluster d : clusters) {
//if testEuclidean < currentEuclidean then
if (tempEuDt > dp.testEuclideanDistance(d.getCentroid())) {
tempEuDt = dp.testEuclideanDistance(d.getCentroid());
tempCluster = d;
matchFoundFlag = true;
}
//if statement - Check whether the Last EuDt is > Present EuDt
}
//for variable 'd' - Looping between different Clusters for matching a Data Point.
//add DataPoint to the cluster and calcSWCSS
if (matchFoundFlag) {
tempCluster.addDataPoint(dp);
//k.notify();
// if(k.hasNext())
k.remove();
for (Cluster d : clusters) {
d.getCentroid().calcCentroid();
}
//for variable 'd' - Recalculating centroids for all Clusters
calcSWCSS();
}
//if statement - A Data Point is eligible for transfer between Clusters.
// }// syn
}
//for variable 'k' - Looping through all Data Points of the current Cluster.
}//for variable 'c' - Looping through all the Clusters.
}//for variable 'i' - Number of iterations.
// syn
}
</code></pre>
| 0 | 1,802 |
How to preserve form fields in django after unsuccessful submit?
|
<p>Code from views.py:</p>
<pre><code>def feedback(request):
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
form.save()
else:
print("form.errors:", form.errors)
else:
form = CommentForm()
articles = Comment.objects.all()
ResponseDict = {"articles": articles, "form": form}
return render_to_response("feedback.html", ResponseDict,
context_instance = RequestContext(request))
</code></pre>
<p>I've tried this and several modifications from answers to similar questions, but nothing works. When I press submit button, all form fields in html become empty.</p>
<p>EDIT: code from feedback.html:</p>
<pre><code>{% extends "base.html" %}
{% block main %}
<table>
<form action="/feedback/" method="POST">
{% csrf_token %}
<div class="article">
<label for="name">
Ваше имя:
</label>
<br />
<input type="text" name="name" id="name" size="40" class="inputbox" value="" />
<br />
<!-- class="inputbox required" -->
<textarea class="WithoutTinymce" cols="50" rows="10" name="text" id="text"></textarea>
<br />
<input type="submit" name="submit" value="Отправить">
</div> <!-- /article -->
</form>
</table>
{% include "articles.html" %}
{% endblock %}
</code></pre>
<p>I can also paste code from base.html if needed.</p>
<p>EDIT2: minimized code from base.html:</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cs" lang="cs">
...
<body id="body-id" onload="loaded()">
<!-- Main -->
<div id="main" class="box">
<div id="page" class="box">
<div id="page-in" class="box">
<!-- Content -->
<div id="content">
{% block main %}
{% endblock %}
<hr class="noscreen" />
</div> <!-- /content -->
</div> <!-- /page-in -->
</div> <!-- /page -->
</div> <!-- /Main -->
</body>
</html>
</code></pre>
| 0 | 1,210 |
How to create a substitution keyword cipher
|
<p>I am trying to develop a substitution cipher that uses a keyword to create a new cipher alphabet. I am new to Java (as I'm sure you will be able to tell!) and I am finding it
hard to wrap my head around the code for what I need to do. </p>
<p>My understanding is as follows:</p>
<p>If for example, the keyword is <code>javben</code>, I should start by finding the index of the "j" in the plainText string array, which is 9. I then want to shift the plainText[9] into cipherText[0] and move each other element over by 1. So the first pass of this would result in:</p>
<pre><code>cipherText[] = {"j","a","b","c","d","e","f","g","h","i","k","l","m","n","o","p","q","r","s","t","u","v","w","r","x","y","z"}
</code></pre>
<p>Then I would find the "a" and it's it's already where it should be so I'll need to account for this and not shift it -- somehow. The next character is the "v" and so the process would continue.</p>
<p>After shifting everything in the cipher I should end up with:</p>
<pre><code>plainText []= {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","r","x","y","z"}
cipherText[]= {"j","a","v","b","e","n","c","d","f","g","h","i","k","l","m","o","p","q","r","s","t","u","w","r","x","y","z"}
</code></pre>
<p>As you can see, I am reasonably sure that I understand the process of which to go through, however I am really struggling wrap my head around the code required for this. Help please! </p>
<pre><code>import java.util.Scanner;
import java.io.*;
/**
* This program uses a keyword for a simple substitution cipher.
*
* @author Bryan
* @version Programming Project
*/
public class Cipher
{
// The main method removes duplicate characters in a word input by the user.
public static void main(String[] args) throws IOException
{
// Creatae a new scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
// prompt the user to enter a word
System.out.println("Please enter your keyword: ");
// and get their input
String input = keyboard.nextLine();
// the keyword will be built up here
String keyword = "";
while(input.length() > 0)
{
// get the first letter
char letter = input.charAt(0);
// if the letter is not already in the output
if (keyword.indexOf(letter) == -1)
{
// add it to the end
keyword = keyword + letter;
}
// that letter is processed : discard it
input = input.substring(1);
}
//this is just to confirm the duplicate letters in the keyword are removed
System.out.println(keyword);
getFile();
}
/**
* This asks the user to specify a filename which is then
* read into the program for enciphering
*/
public static void getFile()throws IOException
{
// Creatae a new scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
// Get the file name
System.out.println("Enter the file name: ");
String filename = keyboard.nextLine();
//Open the file
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Read the lines from the file until no more are left
while (inputFile.hasNext())
{
//Read the next line
String allText = inputFile.nextLine();
// Display the text
System.out.println(allText);
}
//Close the file
inputFile.close();
}
public static void alphabet()
{
String[] plainText = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
String[] cipherText = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
}
}
</code></pre>
| 0 | 1,330 |
How to add a timeout to a function in Python
|
<p>Many attempts have been made in the past to add timeout functionality in Python such that when a specified time limit expired, waiting code could move on. Unfortunately, previous recipes either allowed the running function to continue running and consuming resources or else killed the function using a platform-specific method of thread termination. The purpose of this wiki is to develop a cross-platform answer to this problem that many programmers have had to tackle for various programming projects.</p>
<pre><code>#! /usr/bin/env python
"""Provide way to add timeout specifications to arbitrary functions.
There are many ways to add a timeout to a function, but no solution
is both cross-platform and capable of terminating the procedure. This
module use the multiprocessing module to solve both of those problems."""
################################################################################
__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'
__date__ = '11 February 2010'
__version__ = '$Revision: 3 $'
################################################################################
import inspect
import sys
import time
import multiprocessing
################################################################################
def add_timeout(function, limit=60):
"""Add a timeout parameter to a function and return it.
It is illegal to pass anything other than a function as the first
parameter. If the limit is not given, it gets a default value equal
to one minute. The function is wrapped and returned to the caller."""
assert inspect.isfunction(function)
if limit <= 0:
raise ValueError()
return _Timeout(function, limit)
class NotReadyError(Exception): pass
################################################################################
def _target(queue, function, *args, **kwargs):
"""Run a function with arguments and return output via a queue.
This is a helper function for the Process created in _Timeout. It runs
the function with positional arguments and keyword arguments and then
returns the function's output by way of a queue. If an exception gets
raised, it is returned to _Timeout to be raised by the value property."""
try:
queue.put((True, function(*args, **kwargs)))
except:
queue.put((False, sys.exc_info()[1]))
class _Timeout:
"""Wrap a function and add a timeout (limit) attribute to it.
Instances of this class are automatically generated by the add_timeout
function defined above. Wrapping a function allows asynchronous calls
to be made and termination of execution after a timeout has passed."""
def __init__(self, function, limit):
"""Initialize instance in preparation for being called."""
self.__limit = limit
self.__function = function
self.__timeout = time.clock()
self.__process = multiprocessing.Process()
self.__queue = multiprocessing.Queue()
def __call__(self, *args, **kwargs):
"""Execute the embedded function object asynchronously.
The function given to the constructor is transparently called and
requires that "ready" be intermittently polled. If and when it is
True, the "value" property may then be checked for returned data."""
self.cancel()
self.__queue = multiprocessing.Queue(1)
args = (self.__queue, self.__function) + args
self.__process = multiprocessing.Process(target=_target,
args=args,
kwargs=kwargs)
self.__process.daemon = True
self.__process.start()
self.__timeout = self.__limit + time.clock()
def cancel(self):
"""Terminate any possible execution of the embedded function."""
if self.__process.is_alive():
self.__process.terminate()
@property
def ready(self):
"""Read-only property indicating status of "value" property."""
if self.__queue.full():
return True
elif not self.__queue.empty():
return True
elif self.__timeout < time.clock():
self.cancel()
else:
return False
@property
def value(self):
"""Read-only property containing data returned from function."""
if self.ready is True:
flag, load = self.__queue.get()
if flag:
return load
raise load
raise NotReadyError()
def __get_limit(self):
return self.__limit
def __set_limit(self, value):
if value <= 0:
raise ValueError()
self.__limit = value
limit = property(__get_limit, __set_limit,
doc="Property for controlling the value of the timeout.")
</code></pre>
<hr>
<p><strong>Edit:</strong> This code was written for Python 3.x and was not designed for class methods as a decoration. The <code>multiprocessing</code> module was not designed to modify class instances across the process boundaries.</p>
| 0 | 1,687 |
how to fix: 'MongoError: authentication fail' @MongoDB Atlas
|
<p>I am connecting to MongoDB Atlas and getting authentication fail error.</p>
<p>that is my connection string:</p>
<pre><code>mongodb://user:<password>@mongo-cluster-shard-00-00-ixqtu.mongodb.net:27017,mongo-cluster-shard-00-01-ixqtu.mongodb.net:27017,mongo-cluster-shard-00-02-ixqtu.mongodb.net:27017/test?ssl=true&replicaSet=mongo-cluster-shard-0&authSource=admin&retryWrites=true
</code></pre>
<p>That is what I get:</p>
<pre><code>------------------------------------------------
Mongoose connection "error" event fired with:
{ MongoError: authentication fail
at Function.MongoError.create (/mnt/c/WEB/keystone-md2/node_modules/mongoose/node_modules/mongodb-core/lib/error.js:31:11)
at /mnt/c/WEB/keystone-md2/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/replset.js:1245:38
at /mnt/c/WEB/keystone-md2/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:760:7
at /mnt/c/WEB/keystone-md2/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:736:20
at finish (/mnt/c/WEB/keystone-md2/node_modules/mongoose/node_modules/mongodb-core/lib/auth/scram.js:168:16)
at handleEnd (/mnt/c/WEB/keystone-md2/node_modules/mongoose/node_modules/mongodb-core/lib/auth/scram.js:178:7)
at /mnt/c/WEB/keystone-md2/node_modules/mongoose/node_modules/mongodb-core/lib/auth/scram.js:269:11
at /mnt/c/WEB/keystone-md2/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:469:18
at process._tickCallback (internal/process/next_tick.js:61:11)
name: 'MongoError',
message: 'authentication fail',
errors:
[ { name: 'mongo-cluster-shard-00-01-ixqtu.mongodb.net:27017',
err: [Error] },
{ name: 'mongo-cluster-shard-00-00-ixqtu.mongodb.net:27017',
err: [Error] } ] }
Error: KeystoneJS (Keystone Demo) failed to start - Check that you are running `mongod` in a separate process.
at NativeConnection.<anonymous> (/mnt/c/WEB/keystone-md2/node_modules/keystone/lib/core/openDatabaseConnection.js:62:10)
at NativeConnection.emit (events.js:189:13)
at /mnt/c/WEB/keystone-md2/node_modules/mongoose/lib/connection.js:824:17
at connectCallback (/mnt/c/WEB/keystone-md2/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js:527:5)
at /mnt/c/WEB/keystone-md2/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js:459:13
at process._tickCallback (internal/process/next_tick.js:61:11)
</code></pre>
| 0 | 1,148 |
The correct way to declare, alloc, load, and dealloc an NSMutableArray
|
<p>I declare my array in my *.h file:</p>
<pre>
@interface aViewController: UIViewController
{
NSMutableArray *anArray; // You will need to later change this many times.
}
@end
</pre>
<p>I alloc memory for it my *.m file:</p>
<pre>
-(void) viewDidLoad
{
anArray = [[NSMutableArray alloc] init];
}
</pre>
<p>I click a test-button to load my array (eventually it will need to load DIFFERNT values
on each click):</p>
<pre>
anArray = [NSMutableArray arrayWithObjects:@"one", @"two", @"three", nil];
</pre>
<p>And I free it here:</p>
<pre>
-(void) dealloc
{
[anArray release];
[super dealloc];
}
</pre>
<p>Does that all look ok? </p>
<p>Because it crashes when I later run this code:</p>
<pre>
NSLog(@"%d", [anArray count]);
</pre>
<p>Not sure why a simple "NSLog() and count" would crash everything.</p>
<hr>
<p>Dirk,</p>
<p>Let me put it this way: I have a <em>HUGE</em> misunderstanding of pointers, arrays, strings, and memory.</p>
<p>I've read everything I can find on it... but (yet) to find a simple, clear, easy-to-understand description.</p>
<p>Can you suggest one? (Hopefully less than 10 pages of reading.)
Is there a reference that explains <em>JUST</em> this topic... and from a standpoint of "you have 12 years of coding experience... but NONE that ever dealt with allocating memory or pointers".) </p>
<p>So the variable-name is <em>NOT</em> the way I refer to the object?
Then why have it?</p>
<p>I'm used to many other languages that just do this:</p>
<pre>
myString = "this"
myString = "that"
myInt = 5
myInt = 15
</pre>
<p>(What could be simpler.)</p>
<hr>
<p>Looks to me like this would be the easiest way to do this.
(And it seems to work. But it is truly correct?)</p>
<pre>
Don't alloc any memory for my NSMutableArray initially.
Don't re-alloc any memory repeatedly. (When I change my array's values.)
Don't release it repeatedly. (Before I change my array's values.)
Don't release it when I exit the program.
But:
Always remember to use RETAIN when I initially assign
(and repeatedly reassign) new values to my anArray variable.
</pre>
<hr>
<blockquote>
<p>You are not loading your array with
anArray = [NSMutableArray arrayWithObjects:@"one", @"two", @"three", nil];
Instead, you are replacing it with a new instance, and worse: with an instance, whose
reference is actually owned by some entity you do not control </p>
</blockquote>
<p>Wow. So I could have 20 arrays... all called the same name: anArray... and they would be all different? (There's no such thing as a GLOBAL array?)</p>
<blockquote>
<p>etc. In order to clear out old values, the method removeAllObject may be handy.
There are also mutation methods, which may be used to add multiple values at once.</p>
</blockquote>
<p>So... first I have to "remove all the objects"... and then I can call <em>ONE</em> method it re-add all my new values.</p>
<blockquote>
<p>anArray = [[NSMutableArray arrayWithObjects:@"one", @"two", @"three", nil] retain];
instead of the alloc/init sequence.</p>
</blockquote>
<p>Wow. I thought nothing could be stored in an array without alloc'ing space for it.</p>
<blockquote>
<p>If you really intend to replace the entire array, you may want to consider
using properties</p>
</blockquote>
<p>How would I do that using properties?<br>
What would be the correct way to do something like this:</p>
<pre>
> anArray = [NSMutableArray arrayWithObjects:@"one", @"two", @"three", nil];
> anArray = [NSMutableArray arrayWithObjects:@"four", @"five", @"six", nil];
</pre>
<p>Just like I would do:</p>
<pre>
x = 12;
x = 24;
</pre>
<hr>
<p>Wow. I <em>REALLY</em> have totally misunderstand everything about strings, arrays, and memory.
I thought the "easy way" was to alloc ONCE... use the mutable array... change it as much as you want... and free it ONCE.</p>
<blockquote>
<p>The problem with doing so is that this new array isn't retained, </p>
</blockquote>
<p>I would think the old array would be gone... and the new array could be used.
(But I guess not.)</p>
<blockquote>
<p>Further, you have a memory leak because you never freed the original array.</p>
</blockquote>
<p>I was thinking the old array wasn't suppose to be freed... I'm not done with it... I just wish to CHANGE it to contain my new values. (But I guess not.)</p>
<blockquote>
<p>but one is to use [anArray release]; </p>
</blockquote>
<p>I was thinking that would cause me to release the memory I allocated... (but I guess not)... and then I'd have to re-alloc more memory. (But I guess not.)</p>
<blockquote>
<p>anArray = [[NSMutableArray arrayWithObjects:@"one", @"two", @"three", nil] retain];</p>
</blockquote>
<p>So I have to "retain" it... so it doesn't disappear out from under me?
(Not sure why it would. Until <em>I</em> tell it to... in my final dealloc call.)</p>
<blockquote>
<p>Another, probably more correct way to fix it would be to use the addObject: or
addObjectsFromArray: NSMutableArray methods instead of constantly creating new arrays.</p>
</blockquote>
<p>I only want to create <em>ONE</em> array... and just use it as I want to.
I never want to <em>ADD</em> to the array. I want to set it to my new values.</p>
| 0 | 1,760 |
How to fix "Too many arguments"-error
|
<p>im working on this point of sale system in vb and im stuck on an error</p>
<blockquote>
<p>Error 2 Too many arguments to 'Public Overridable Overloads Function
Insert(ItemName As String, BuyPrice As Integer?, SellPrice As
Integer?) As Integer'.</p>
</blockquote>
<p>how can i clear it?</p>
<p>the double stared <code>**</code> is where the error is</p>
<p>my code: add item window</p>
<pre><code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Public Class AddItem
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.DialogResult = Windows.Forms.DialogResult.Cancel
End Sub
'used to insert the item
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'perform validation for barcode
If TextBox1.Text.Trim = "" Then
MsgBox("You should enter a barcode number", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
TextBox1.Focus()
Exit Sub
End If
If Not IsNumeric(TextBox1.Text) Then
MsgBox("You should enter a numeric barcode number", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
TextBox1.Focus()
Exit Sub
End If
If TextBox1.Text.Contains(".") Or TextBox1.Text.Contains("-") Then
MsgBox("The barcode number should not contain special characters", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
TextBox1.Focus()
Exit Sub
End If
'perform check for the item name
If TextBox2.Text.Trim = "" Then
MsgBox("You should enter a name for the item", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
TextBox2.Focus()
Exit Sub
End If
'perform a check for the buy price
If TextBox3.Text.Trim = "" Then
MsgBox("You should enter the buying price", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
TextBox3.Focus()
Exit Sub
End If
If Not IsNumeric(TextBox3.Text) Then
MsgBox("You should enter a numeric buying price", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
TextBox3.Focus()
Exit Sub
End If
Dim BuyPrice As Decimal = Decimal.Parse(TextBox3.Text)
If BuyPrice < 0 Then
MsgBox("The buying price cannot be negative", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
TextBox3.Focus()
Exit Sub
End If
'perform a check for the selling price
If TextBox4.Text.Trim = "" Then
MsgBox("You should enter the selling price", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
TextBox4.Focus()
Exit Sub
End If
If Not IsNumeric(TextBox4.Text) Then
MsgBox("You should enter a numeric selling price", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
TextBox4.Focus()
Exit Sub
End If
Dim SellPrice As Decimal = Decimal.Parse(TextBox4.Text)
If SellPrice < 0 Then
MsgBox("The selling price cannot be negative", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
TextBox4.Focus()
Exit Sub
End If
If SellPrice <= BuyPrice Then
MsgBox("The selling price cannot be less than buying price", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
TextBox4.Focus()
Exit Sub
End If
'perform check for quantity
'If Not IsNumeric(TextBox5.Text) Then
'MsgBox("You should enter a numeric digits", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
'TextBox5.Focus()
'Exit Sub
'End If
'Dim Quantity As Decimal = Decimal.Parse(TextBox5.Text)
'If Quantity < 0 Then
'MsgBox("Quantity cant be negative", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
' TextBox5.Focus()
'Exit Sub
'End If
'insert the item
Try
'create the adapter
Dim TA As New POSDSTableAdapters.ItemsTableAdapter
'insert the item
'TA.Insert(TextBox1.Text, TextBox2.Text, BuyPrice, SellPrice, Quantity)
TA.Insert(TextBox2.Text, BuyPrice, SellPrice)
Me.DialogResult = Windows.Forms.DialogResult.OK
Catch ex As Exception
'display error message
'handle error
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
End Try
End Sub
Private Sub AddItem_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
</code></pre>
<p>End Class</p>
<p>main window code:
Public Class MainWindow</p>
<pre><code>Private Sub MainWindow_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MyDataset.Items' table. You can move, or remove it, as needed.
Me.ItemsTA.Fill(Me.MyDataset.Items)
Try
'get the username from the user
'Dim USRWin As New PasswordPicker
'get the password from the user
' Dim PSWWin As New PasswordPicker
'if the user hits the exit button then stop executing the program
'If PSWWin.ShowDialog <> Windows.Forms.DialogResult.OK Then
'End
' End If
'get the usernme
'Dim USR As String = USRWin.TextBox1.text
'get the password
'Dim PSW As String = PSWWin.TextBox2.text
'get the password from the database
' Dim TA As New POSDSTableAdapters.ValuesTableAdapter
'Dim TB = TA.GetDataByKey("password")
' Dim DBPSW As String = TB.Rows(0).Item(1)
'check the passwords match
' If PSW <> DBPSW Then
'MsgBox("Invalid password", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
' End If
'get the username
' Dim TK = TA.GetDataByKey("username")
'Dim DBUSR As String = TK.Rows(0).Item(2)
'check the username match
'If USR <> DBUSR Then
'MsgBox("Invalid username", MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
'End If
'load the items info from db into the dataset
ItemsTA.Fill(MyDataset.Items)
Catch ex As Exception
'handle error
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
End Try
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs)
End Sub
'add item to the db
Private Sub AddItemToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddItemToolStripMenuItem.Click
Dim AddItemWindow As New AddItem
If AddItemWindow.ShowDialog = Windows.Forms.DialogResult.OK Then
'load the info of items from db
ItemsTA.Fill(MyDataset.Items)
End If
End Sub
'used to select an item
Private Sub EditItemToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EditItemToolStripMenuItem.Click
'make sure an item is selected
If DataGridView1.SelectedRows.Count = 0 Then
Exit Sub
End If
'get the barcode of the item
Dim Barcode = DataGridView1.SelectedRows(0).Cells(0).Value
'create the edit window
Dim EditItemWindow As New EditItem
'fill the window with information
EditItemWindow.FillItemInfo(Barcode)
If EditItemWindow.ShowDialog = Windows.Forms.DialogResult.OK Then
'load the info of items from db
ItemsTA.Fill(MyDataset.Items)
End If
End Sub
</code></pre>
<p>End Class</p>
| 0 | 2,801 |
Programmatically log a user in to asp.net membership and roles?
|
<p>I'm working on an Asp.Net 4.0 web application which is using the Membership and Roles features of Asp.Net.</p>
<p>In the application, there will be three roles which have access to the login page and one role which doesn't.</p>
<p>The way it is supposed to work is as follows.</p>
<p>Back end user (in one of the three privileged roles) creates a user. In the code, this is done programmatically rather than using the Register User page. When the user is created, they are added to the unprivileged role, which, for the sake of clarity is called the Visitor role.</p>
<p>Back end user then creates a link for the new user which is in the form of <a href="https://www.example.com?link=cc82ae24-df47-4dbf-9440-1a6923945cf2" rel="nofollow noreferrer">https://www.example.com?link=cc82ae24-df47-4dbf-9440-1a6923945cf2</a></p>
<p>When the link is visited, the application will locate the user associated with the query string, get the username and password (which are suitably hashed and salted) and logs the user in.</p>
<p>This is where I'm coming undone. So far, the user creation is working just fine, the database query based on the value of the query string is doing its job and returning the relevant bits of information, it all seems to be flowing pretty well, except for the actual logging in. There doesn't seem to be a clear method of logging a user in programmatically, without going through the rigmarole of getting the user to log themselves in, which I have been explicitly told to avoid.</p>
<p>Here is my code, the "pers" object is a class which is populated from the database when they land on the default page of the link:</p>
<pre><code>protected void LogUserIn(string p)
{
SqlConnection conn = UtilityMethods.GetConnection();
Guid par = Guid.Parse(p);
BioProspect pers= new BioProspect(conn);
pers.FillDetailsFromDb(par);
testlable.Text = pers.ToString();
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
try
{
if (Membership.ValidateUser(pers.Email, pers.Pword))
{
FormsAuthentication.SetAuthCookie(pers.Email, true);
Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Host + "/About.aspx");
testlable.Text = "Logged in!";
}
else
{
throw new Exception("Something went wrong");
}
}
catch (Exception ex)
{
StringBuilder sb = new StringBuilder();
foreach (DictionaryEntry d in ex.Data)
{
sb.Append(d.Key.ToString());
sb.Append(": ");
sb.Append(d.Value.ToString());
sb.Append("\r\n");
}
AMessage(sb.ToString());
}
}
</code></pre>
<p>Now, I've checked the values of the username and password against the database table itself and it is all correct. I understand the password stored in the aspnet tables has been salted and hashed, so I'm checking the values in a temporary table I created to hold the clear text. It's right. In addition, in the code above, the FormsAuthentication.SetAuthCookie method is asking for a username and password - in this instance, the username is the email address. This information is also correct when inspected during debugging.</p>
<p>I should point out, the links we are sending are pretty much one time links. Every time a change is made relevant to that particular user, the value of the link parameter will change and the old link will be come completely useless. The page they will be redirected to will hold documents which are directly relevant to that particular user and to no others.</p>
<p>However, we still need the benefits of the Asp.Net Membership, Profiles and Roles framework, since the "Visitor" may well have several links sent to them, with different documents and versions of documents being added and changed over time.</p>
<p>Can anyone think of a better way? I have so far looked at most of the relevant entries <a href="https://stackoverflow.com/search?q=[asp.net]+auto+login">here</a> and <a href="https://stackoverflow.com/search?q=[asp.net]+automated+login">here</a> but they all seem somewhat incomplete.</p>
<p><strong>EDIT</strong></p>
<p>I seem to have at least partially resolved this, using information gleaned from the accepted answer <a href="https://stackoverflow.com/questions/2730020/membership-validateuser-always-returns-false-after-upgrade-to-vs-2010-net-4-0">here</a></p>
<p>Essentially, the problem was my web.config membership section needed to be told which hashing algorithm to use. At the moment, I have no idea what the default one is, if there is one, but adding</p>
<pre><code><membership hashAlgorithmType="SHA1">
</code></pre>
<p>to the web.config has at least allowed me to log in users created after the above line was added. The next step is for me to understand why I can't get the other users logged in.</p>
<p>I am however still getting a ThreadAbortException as suggested by Joe, which I am now busily working to resolve. </p>
| 0 | 1,564 |
Enable SOAP on Plesk
|
<p>This question has been asked before but none of the solutions work for me. I was mainly following this one - <a href="https://stackoverflow.com/questions/11014431/enable-soap-on-php">enable SOAP on PHP</a> to no avail. I have a php script which is giving the following error:</p>
<pre><code>Error message: Fatal error: Class 'SoapClient' not found in /var/www/pathtofile/file.php on line 90
</code></pre>
<p>I guess need to install soap on a Plesk 11.0.9 and CentOS 5.6 (Final). This is what I have by default in the php.ini file:</p>
<pre><code>[soap]
; Enables or disables WSDL caching feature.
soap.wsdl_cache_enabled=1
; Sets the directory name where SOAP extension will put cache files.
soap.wsdl_cache_dir="/tmp"
; (time to live) Sets the number of second while cached file will be used
; instead of original one.
soap.wsdl_cache_ttl=86400
</code></pre>
<p>and <strong>php -i | grep soap</strong> gives me:</p>
<pre><code>'--enable-soap=shared'
</code></pre>
<p>if I run <strong>yum install php-soap</strong> I get the following:</p>
<pre><code>Resolving Dependencies
--> Running transaction check
---> Package php-soap.i386 0:5.1.6-32.el5 set to be updated
--> Processing Dependency: php-common = 5.1.6-32.el5 for package: php-soap
--> Running transaction check
---> Package php-common.i386 0:5.1.6-32.el5 set to be updated
--> Processing Conflict: php53-common conflicts php-common
--> Finished Dependency Resolution
php53-common-5.3.3-13.el5_8.i386 from installed has depsolving problems
--> php53-common conflicts with php-common
Error: php53-common conflicts with php-common
</code></pre>
<p>if I run <strong>yum install php53-soap</strong> I get the following:</p>
<pre><code>Resolving Dependencies
--> Running transaction check
---> Package php53-soap.i386 0:5.3.3-5.el5 set to be updated
--> Processing Dependency: php53-common = 5.3.3-5.el5 for package: php53-soap
--> Finished Dependency Resolution
php53-soap-5.3.3-5.el5.i386 from base has depsolving problems
--> Missing Dependency: php53-common = 5.3.3-5.el5 is needed by package php53-soap-5.3.3-5.el5.i386 (base)
Error: Missing Dependency: php53-common = 5.3.3-5.el5 is needed by package php53-soap- 5.3.3-5.el5.i386 (base)
</code></pre>
<p>If I run <strong>yum list available | grep soap</strong> I get:</p>
<pre><code>php-soap.i386 5.1.6-32.el5 base
php53-soap.i386 5.3.3-5.el5 base
</code></pre>
<p>if I run <strong>yum list available | grep soap</strong> I get the following:</p>
<pre><code>php53-common-5.3.3-13.el5_8
php53-mysql-5.3.3-13.el5_8
php53-xml-5.3.3-13.el5_8
psa-php53-configurator-1.6.2-cos5.build110120608.16
php5-ioncube-loader-4.0.14-12042719
php53-5.3.3-13.el5_8
php53-mbstring-5.3.3-13.el5_8
php-pear-1.4.9-8.el5
psa11-php-fakepackage-11.0.9-cos5.build110120608.16
php53-pdo-5.3.3-13.el5_8
php53-imap-5.3.3-13.el5_8
php53-sqlite2-5.3.2-11070811
php53-cli-5.3.3-13.el5_8
php53-gd-5.3.3-13.el5_8
php53-devel-5.3.3-13.el5_8
</code></pre>
<p>If I run <strong>yum list | grep php</strong> I get:</p>
<pre><code>php-pear.noarch 1:1.4.9-8.el5 installed
php5-ioncube-loader.i386 4.0.14-12042719 installed
php53.i386 5.3.3-13.el5_8 installed
php53-cli.i386 5.3.3-13.el5_8 installed
php53-common.i386 5.3.3-13.el5_8 installed
php53-devel.i386 5.3.3-13.el5_8 installed
php53-gd.i386 5.3.3-13.el5_8 installed
php53-imap.i386 5.3.3-13.el5_8 installed
php53-mbstring.i386 5.3.3-13.el5_8 installed
php53-mysql.i386 5.3.3-13.el5_8 installed
php53-pdo.i386 5.3.3-13.el5_8 installed
php53-sqlite2.i386 5.3.2-11070811 installed
php53-xml.i386 5.3.3-13.el5_8 installed
psa-php53-configurator.i386 1.6.2-cos5.build110120608.16 installed
psa11-php-fakepackage.i386 11.0.9-cos5.build110120608.16 installed
graphviz-php.i386 2.12-8.el5.centos extras
php.i386 5.1.6-32.el5 base
php-bcmath.i386 5.1.6-32.el5 base
php-cli.i386 5.1.6-32.el5 base
php-common.i386 5.1.6-32.el5 base
php-dba.i386 5.1.6-32.el5 base
php-dbase.i386 5.1.6-15.el5.centos.1 extras
php-devel.i386 5.1.6-32.el5 base
php-gd.i386 5.1.6-32.el5 base
php-imap.i386 5.1.6-32.el5 base
php-ldap.i386 5.1.6-32.el5 base
php-mbstring.i386 5.1.6-32.el5 base
php-mcrypt.i386 5.1.6-15.el5.centos.1 extras
php-mhash.i386 5.1.6-15.el5.centos.1 extras
php-mssql.i386 5.1.6-15.el5.centos.1 extras
php-mysql.i386 5.1.6-32.el5 base
php-ncurses.i386 5.1.6-32.el5 base
php-odbc.i386 5.1.6-32.el5 base
php-pdo.i386 5.1.6-32.el5 base
php-pear-Auth-SASL.noarch 1.0.2-4.el5.centos extras
php-pear-DB.noarch 1.7.13-1.el5.centos extras
php-pear-Date.noarch 1.4.7-2.el5.centos extras
php-pear-File.noarch 1.2.2-1.el5.centos extras
php-pear-HTTP-Request.noarch 1.4.2-1.el5.centos extras
php-pear-Log.noarch 1.9.13-1.el5.centos extras
php-pear-MDB2.noarch 2.4.1-2.el5.centos extras
php-pear-MDB2-Driver-mysql.noarch 1.4.1-3.el5.centos extras
php-pear-Mail.noarch 1.1.14-1.el5.centos extras
php-pear-Mail-Mime.noarch 1.4.0-1.el5.centos extras
php-pear-Net-SMTP.noarch 1.2.10-1.el5.centos extras
php-pear-Net-Sieve.noarch 1.1.5-2.el5.centos extras
php-pear-Net-Socket.noarch 1.0.8-1.el5.centos extras
php-pear-Net-URL.noarch 1.0.15-1.el5.centos extras
php-pecl-Fileinfo.i386 1.0.4-3.el5.centos extras
php-pecl-memcache.i386 2.2.3-1.el5_2 extras
php-pgsql.i386 5.1.6-32.el5 base
php-readline.i386 5.1.6-15.el5.centos.1 extras
php-snmp.i386 5.1.6-32.el5 base
php-soap.i386 5.1.6-32.el5 base
php-tidy.i386 5.1.6-15.el5.centos.1 extras
php-xml.i386 5.1.6-32.el5 base
php-xmlrpc.i386 5.1.6-32.el5 base
php53-bcmath.i386 5.3.3-5.el5 base
php53-dba.i386 5.3.3-5.el5 base
php53-intl.i386 5.3.3-5.el5 base
php53-ldap.i386 5.3.3-5.el5 base
php53-odbc.i386 5.3.3-5.el5 base
php53-pgsql.i386 5.3.3-5.el5 base
php53-process.i386 5.3.3-5.el5 base
php53-pspell.i386 5.3.3-5.el5 base
php53-snmp.i386 5.3.3-5.el5 base
php53-soap.i386 5.3.3-5.el5 base
php53-xmlrpc.i386 5.3.3-5.el5 base
</code></pre>
<p>Any ideas on how to fix this problem with soap please?</p>
| 0 | 5,382 |
Undefined Reference to
|
<p>When I compile my code for a linked list, I get a bunch of undefined reference errors. The code is below. I have been compiling with both of these statements:</p>
<pre><code>g++ test.cpp
</code></pre>
<p>as well as </p>
<pre><code>g++ LinearNode.h LinearNode.cpp LinkedList.h LinkedList.cpp test.cpp
</code></pre>
<p>I really do not understand why I am getting these errors because I am really rusty on classes in C++. I could really use some help.</p>
<p>LinearNode.h:</p>
<pre><code>#ifndef LINEARNODE_H
#define LINEARNODE_H
#include<iostream>
using namespace std;
class LinearNode
{
public:
//Constructor for the LinearNode class that takes no arguments
LinearNode();
//Constructor for the LinearNode class that takes the element as an argument
LinearNode(int el);
//returns the next node in the set.
LinearNode* getNext();
//returns the previous node in the set
LinearNode* getPrevious();
//sets the next element in the set
void setNext(LinearNode* node);
//sets the previous element in the set
void setPrevious(LinearNode* node);
//sets the element of the node
void setElement(int el);
//gets the element of the node
int getElement();
private:
LinearNode* next;
LinearNode* previous;
int element;
};//ends the LinearNode class
#endif
</code></pre>
<p>LinearNode.cpp:</p>
<pre><code>#ifndef LINEARNODE_cpp
#define LINEARNODE_cpp
#include<iostream>
#include"LinearNode.h"
using namespace std;
//Constructor for LinearNode, sets next and element to initialized states
LinearNode::LinearNode()
{
next = NULL;
element = 0;
}//ends LinearNode default constructor
//Constructor for LinearNode takes an element as argument.
LinearNode::LinearNode(int el)
{
next = NULL;
previous = NULL;
element = 0;
}//ends LinearNode constructor
//returns the next element in the structure
LinearNode* LinearNode::getNext()
{
return next;
}//ends getNext function
//returns previous element in structure
LinearNode* LinearNode::getPrevious()
{
return previous;
}//ends getPrevious function
//sets the next variable for the node
void LinearNode::setNext(LinearNode* node)
{
next = node;
}//ends the setNext function
//sets previous for the node
void LinearNode::setPrevious(LinearNode* node)
{
previous = node;
}//ends the setPrevious function
//returns element of the node
int LinearNode::getElement()
{
return element;
}//ends the getelement function
//sets the element of the node
void LinearNode::setElement(int el)
{
element = el;
}//ends the setElement function
#endif
</code></pre>
<p>LinkedList.h:</p>
<pre><code>#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include<iostream>
#include"LinearNode.h"
using namespace std;
class LinkedList
{
public:
LinkedList();
void add(int element);
int removie (int element);
private:
int count;
LinearNode *contents;
};//ends the class linked list
#endif
</code></pre>
<p>LinkedList.cpp:</p>
<pre><code>#ifndef LINKEDLIST_CPP
#define LINKEDLIST_CPP
#include<iostream>
#include"LinearNode.h"
#include"LinkedList.h"
using namespace std;
//linkedlist constructor for an empty linked list
LinkedList::LinkedList()
{
count = 0;
contents = NULL;
}//ends the constructor
//adds an element to the front of the linked list
void LinkedList::add(int element)
{
int found = 0, current = 0;
while( (found == 0) && (current !=count) )
{
if (contents.getElement() == element)
found = 1;
else
{
contents = contents.getNext();
current++;
}//ends the else statement
}//ends the while loop
if (found == 0)
{
LinearNode node = new LinearNode(element);
node.setNext(contents);
contents.setPrevious(node);
count++;
}//ends the found == 0 if statment
}//ends the add function
//this function removes one element from the linked list.
int LinearNode::remove(int element)
{
int found = 0;
if (count == 0)
cout << "The list is empty" << endl;
else
{
if (contents.getElement() == element)
{
result = contents.getElement();
contents = contents.getNext();
}//ends the contents.getElement() == element
else
{
previous = contents;
current = contents.getNext();
for (int index = 0; ( (index < count) && (found == 0) )index++)
if (current.getElement() = element)
found = 1;
else
{
previous = current;
current = current.getNext();
}//ends the else statement
if (found == 0)
cout << "The element is not in the list" << endl;
else
{
result = current.getElement();
previous.setNext(current.getNext());
}//ends else statement
}//ends the else stamtement
count--;
}//ends the else statement of count == 0
return result;
}//ends the remove function
#endif
</code></pre>
<p>test.cpp:</p>
<pre><code>#include<iostream>
#include"LinearNode.h"
#include"LinkedList.h"
using namespace std;
int main()
{
LinearNode node1, node2, node3, move;
LinkedList list;
node1.setElement(1);
node2.setElement(2);
node3.setElement(3);
}
</code></pre>
| 0 | 2,317 |
How to use ts-node ESM with node modules?
|
<p>Note: I am aware that the following question is about an experimental feature. I have created a <a href="https://github.com/TypeStrong/ts-node/discussions/1321" rel="noreferrer">clone on the ts-node discussion forum</a>. However, I believe StackOverflow has a wider exposure and would lead to a solution in less time.</p>
<p>I am trying to make a simple script that reads a file from one location and processes it. Here is what I have so far, having followed <a href="https://github.com/TypeStrong/ts-node/issues/1007" rel="noreferrer">#1007</a>:</p>
<p>Node: v12.22.1</p>
<pre><code>my-app
├── .eslintrc.cjs
├── .gitignore
├── in
│ └── given.txt
├── node_modules
├── out
├── package-lock.json
├── package.json
├── src
│ ├── helper.ts
│ └── main.ts
└── tsconfig.json
</code></pre>
<p>package.json</p>
<pre class="lang-json prettyprint-override"><code>{
"name": "my-app",
"version": "1.0.0",
"type": "module",
"scripts": {
"lint": "eslint ./src --ext .js,.jsx,.ts,.tsx --max-warnings=0",
"start": "node --experimental-specifier-resolution=node --experimental-modules --no-warnings --loader ts-node/esm ./src/main.ts"
},
"author": "Kaustubh Badrike",
"devDependencies": {
"@types/node": "^15.3.0",
"@typescript-eslint/eslint-plugin": "^4.24.0",
"@typescript-eslint/parser": "^4.24.0",
"eslint": "^7.26.0",
"ts-node": "^9.1.1",
"typescript": "^4.2.4"
}
}
</code></pre>
<p>tsconfig.json</p>
<pre><code>{
"compilerOptions": {
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "ESNext", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
</code></pre>
<p>main.ts</p>
<pre class="lang-js prettyprint-override"><code>import { readFileSync } from "fs";
const contents = readFileSync('../in/given.txt');
</code></pre>
<p>However, when I try <code>npm run start</code>, I get the following</p>
<pre><code>TypeError [ERR_INVALID_RETURN_PROPERTY_VALUE]: Expected string to be returned for the "format" from the "loader getFormat" function but got type
object.
at Loader.getFormat (internal/modules/esm/loader.js:125:13)
at Loader.getModuleJob (internal/modules/esm/loader.js:247:20)
at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:49:17)
at async Promise.all (index 0)
at link (internal/modules/esm/module_job.js:53:9)
</code></pre>
<p>The error does not occur if I remove the import from fs. Importing items from helper.ts works as well.</p>
<p><strong>What do I need to do to get it to work?</strong></p>
| 0 | 1,689 |
MySQL: How to Combine multiple SELECT queries, using different WHERE criteria on the same table?
|
<p>I have been trying many different ways to solve this problem from this forum and from many others. I can't seem to find a solution to this problem or any documentation that will give me a straight answer.</p>
<p>I wondered if you could have a look at it for me.</p>
<p>Thanks</p>
<p><strong>THE PROBLEM:</strong></p>
<p>I've got a database with the following tables
participant_scores
leagues
rounds</p>
<p>I am currently able to display the scores of a single round, one round at a time... which is exactly how I want it.
But I also want to display the score that each participant got for all rounds.
Lets say we have 2 rounds. I want the output on my results screen to look something like this:</p>
<pre><code> Currently viewing league 20, Round 1
of 2:
User Name | Score | Total Score
Tom | 10 | 200
James | 50 | 300
</code></pre>
<p>username - the participant's name
score = the score for this current round
total score = all of the round scores for this league added together.</p>
<p>My Mysql query is below. Apologies for the messyness of it, I've rewritten it about 100 times and this current way is the only way that works fully.</p>
<h1>>> league_participants_query (mysql)</h1>
<pre><code> # FIELDS
SELECT
participants.participant_id, # ID - used for functions
participants.participant_name, # NAME
participants.participant_gender, # Participant info
classes.class_name, # Class name
schools.school_name, # School name
participant_scores.participant_score, # Participant score
participant_scores.participant_score_id
# TABLES
FROM participant_scores, participants, classes, league_schools, schools, leagues, rounds
# filter leagues
WHERE leagues.league_id = 51
AND rounds.league_id = 51 # the current league we are viewing
AND rounds.round_id = 25 # the current round of the league we are viewing
# filter league schools
AND participant_scores.round_id = 25 # the current round of the league we are viewing
# filter schools allowed
AND league_schools.league_id = 51 # the current league we are viewing
# Filter schools
AND schools.school_id = league_schools.school_id
# Filter classes
AND classes.school_id = schools.school_id
AND classes.year_group_id = leagues.year_group_id
# Filter participants
AND participants.class_id = classes.class_id
# Filter participant_scores
AND participant_scores.participant_id = participants.participant_id
#Grouping
GROUP BY participants.participant_id
</code></pre>
| 0 | 1,415 |
how to convert double to string in android
|
<p>i want to convert string in my constructor into double, i can't change it in my constructor, because in one process, the variable must in double, and other class must be string, can you tell me the way to convert it..? this is my constructor :</p>
<pre><code>public class DataItem {
String ijiInvest, ijiId;
String tanggal;
double persenHmint1,inuNilai selisih,persen_hke1;
public DataItem(String ijiInvest, double persenHmint1, Double inuNilai,
double selisih,double persen_hke1, String tanggal,String ijiId) {
// TODO Auto-generated constructor stub
this.ijiInvest = ijiInvest;
this.persenHmint1 = persenHmint1;
this.inuNilai = inuNilai;
this.selisih = selisih;
this.ijiId = ijiId;
this.tanggal = tanggal;
this.persen_hke1=persen_hke1;
}
public String getIjiInvest() {
return ijiInvest;
}
public String getIjiId() {
return ijiId;
}
public String getTanggal() {
return tanggal;
}
public double getPersenHmint1() {
return persenHmint1;
}
public Double getInuNilai() {
return inuNilai;
}
public double getSelisih() {
return selisih;
}
public double persen_hke1(){
return persen_hke1;
}
</code></pre>
<p>in my base adapter, i want to change getInuNilai() into string this is my base adapter :</p>
<pre><code>public class TabelAdapter extends BaseAdapter{
Context context;
ArrayList<DataItem> listData;//stack
int count;
public TabelAdapter(Context context, ArrayList<DataItem>listData){
this.context=context;
this.listData=listData;
this.count=listData.size();
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return count;
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
View view= v;
ViewHolder holder= null;
if(view==null){
LayoutInflater inflater=(LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view= inflater.inflate(R.layout.main, null);
holder=new ViewHolder();
holder.nama=(TextView)view.findViewById(R.id.name);
holder.email=(TextView)view.findViewById(R.id.email);
view.setTag(holder);
}
else{
holder=(ViewHolder)view.getTag();
}
holder.nama.setText(listData.get(position).getTanggal());
// holder.email.setText(listData.get(position).getInuNilai());
return view;
}
static class ViewHolder{
TextView nama, email;
}
</code></pre>
<p>i can't setText getInuNilai() because its return into double, can you tell me how to convert it?</p>
| 0 | 1,067 |
Qt 5 : Mouse Wheel event behaviour for zooming image
|
<p>I have a window, in which is a QGraphicsView, which will be displaying an image. I have implemented the wheelEvent(). My images are mostly going to be bigger than the window, so I get scroll bars in the window.</p>
<p>What we normally observe when we rotate the wheel while viewing an image in Windows Photo Viewer is that when we move the wheel up (towards it's wire), the image zooms in and when we move it down (towards out body), the image zooms out.</p>
<p>What I am getting instead is when I move the wheel towards myself (to zoom out) the image instead of zooming out , first scrolls down, and starts zooming out only when the scroll bar touches its bottom most point.</p>
<p><strong>It would be better to understand the problem by trying out the code. I am not able to explain in I guess.</strong></p>
<p>I want the standard behavior. What to do?</p>
<p><strong>Code</strong></p>
<pre><code>#include "viewer.h"
#include "ui_viewer.h"
#include <QGraphicsView>
#include <QGraphicsItem>
#include <QGraphicsPixmapItem>
#include <QWheelEvent>
#include <QDebug>
#include <QImage>
#include <QImageReader>
#include <QApplication>
#include <QDesktopWidget>
viewer::viewer(QWidget *parent) : QWidget(parent),ui2(new Ui::viewer)
{
ui2->setupUi(this);
}
viewer::~viewer()
{
delete ui2;
}
int viewer::show_changes(QString folder)
{
QDesktopWidget *desktop = QApplication::desktop();
int screenWidth = desktop->width();
int screenHeight = desktop->height();
QString filename = "image_bigger_than_window.jpg";
QPixmap pixmap = QPixmap(filename);
QImageReader reader(filename);
QImage image = reader.read();
QSize size = image.size();
int width = 800;
int height = (width * size.height()) / size.width();
int x = (screenWidth - width) / 2;
int y = (screenHeight - height) / 2 - 30;
setGeometry(x,y,width, height);
setWindowTitle("OUTPUT");
ui2->graphicsView->setGeometry(0,0,width,height);
QGraphicsScene* viewScene = new QGraphicsScene(QRectF(0, 0,width, height), 0);
QGraphicsPixmapItem *item = viewScene->addPixmap(pixmap.scaled(QSize((int)viewScene->width(), (int)viewScene->height()),
Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
viewScene->addItem(item);
ui2->graphicsView->fitInView(QRectF(0, 0, width, height),Qt::IgnoreAspectRatio);
ui2->graphicsView->setScene(viewScene);
ui2->graphicsView->show();
return 0;
}
void viewer::wheelEvent(QWheelEvent * event)
{
const int degrees = event->delta() / 8;
qDebug() << degrees;
int steps = degrees / 15;
double scaleFactor = 1.0;
const qreal minFactor = 1.0;
const qreal maxFactor = 10.0;
qreal h11 = 1.0, h22 = 0;
if(steps > 0)
{
h11 = (h11 >= maxFactor) ? h11 : (h11 + scaleFactor);
h22 = (h22 >= maxFactor) ? h22 : (h22 + scaleFactor);
}
else
{
h11 = (h11 <= minFactor) ? minFactor : (h11 - scaleFactor);
h22 = (h22 <= minFactor) ? minFactor : (h22 - scaleFactor);
}
ui2->graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
ui2->graphicsView->setTransform(QTransform(h11, 0, 0,0, h22, 0, 0,0,1));
}
</code></pre>
<p><strong>EDIT</strong></p>
<p>1)Removed function <code>void viewer::wheelEvent(QWheelEvent * event)</code> from <code>viewer.cpp</code> </p>
<p>2)Put <code>bool viewer::eventFilter(QObject *obj, QEvent *event)</code> in its place as a protected function and <code>void viewer::handleWheelOnGraphicsScene(QGraphicsSceneWheelEvent* scrollevent)</code> as a public slot in <code>viewer.h</code></p>
<pre><code>bool viewer::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::GraphicsSceneWheel)
{
QGraphicsSceneWheelEvent *scrollevent = static_cast<QGraphicsSceneWheelEvent *>(event);
handleWheelOnGraphicsScene(scrollevent);
return true;
}
// Other events should propagate - what do you mean by propagate here?
return false;
}
void viewer::handleWheelOnGraphicsScene(QGraphicsSceneWheelEvent* scrollevent)
{
const int degrees = scrollevent->delta() / 8;
qDebug() << degrees;
int steps = degrees / 15;
qDebug() << steps;
double scaleFactor = 1.0; //How fast we zoom
const qreal minFactor = 1.0;
const qreal maxFactor = 10.0;
if(steps > 0)
{
h11 = (h11 >= maxFactor) ? h11 : (h11 + scaleFactor);
h22 = (h22 >= maxFactor) ? h22 : (h22 + scaleFactor);
}
else
{
h11 = (h11 <= minFactor) ? minFactor : (h11 - scaleFactor);
h22 = (h22 <= minFactor) ? minFactor : (h22 - scaleFactor);
}
ui2->graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
ui2->graphicsView->setTransform(QTransform(h11, 0, 0,0, h22, 0, 0,0,1));
}
</code></pre>
| 0 | 1,978 |
How to use Key Bindings instead of Key Listeners
|
<p>I'm using <a href="https://docs.oracle.com/javase/8/docs/api/java/awt/event/KeyListener.html" rel="noreferrer"><code>KeyListener</code></a>s in my code (game or otherwise) as the way for my on-screen objects to react to user key input. Here is my code:</p>
<pre><code>public class MyGame extends JFrame {
static int up = KeyEvent.VK_UP;
static int right = KeyEvent.VK_RIGHT;
static int down = KeyEvent.VK_DOWN;
static int left = KeyEvent.VK_LEFT;
static int fire = KeyEvent.VK_Q;
public MyGame() {
// Do all the layout management and what not...
JLabel obj1 = new JLabel();
JLabel obj2 = new JLabel();
obj1.addKeyListener(new MyKeyListener());
obj2.addKeyListener(new MyKeyListener());
add(obj1);
add(obj2);
// Do other GUI things...
}
static void move(int direction, Object source) {
// do something
}
static void fire(Object source) {
// do something
}
static void rebindKey(int newKey, String oldKey) {
// Depends on your GUI implementation.
// Detecting the new key by a KeyListener is the way to go this time.
if (oldKey.equals("up"))
up = newKey;
if (oldKey.equals("down"))
down = newKey;
// ...
}
public static void main(String[] args) {
new MyGame();
}
private static class MyKeyListener extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
Object source = e.getSource();
int action = e.getExtendedKeyCode();
/* Will not work if you want to allow rebinding keys since case variables must be constants.
switch (action) {
case up:
move(1, source);
case right:
move(2, source);
case down:
move(3, source);
case left:
move(4, source);
case fire:
fire(source);
...
}
*/
if (action == up)
move(1, source);
else if (action == right)
move(2, source);
else if (action == down)
move(3, source);
else if (action == left)
move(4, source);
else if (action == fire)
fire(source);
}
}
}
</code></pre>
<p>I have problems with the responsiveness:</p>
<ul>
<li>I need to click on the object for it to work.</li>
<li>The response I get for pressing one of the keys is not how I wanted it to work - too responsive or too unresponsive.</li>
</ul>
<p>Why does this happen and how do I fix this?</p>
| 0 | 1,263 |
Timer/Stopwatch GUI
|
<p>I am trying to make a simple java application that counts time, with the ability to stop and start the timer. However, the label won't update, and when I press start, it freezes.</p>
<p>Could you help me figure out what the problem is?</p>
<pre><code>package random;
import javax.swing.JFrame;
public class Timer {
boolean shouldCount=false;
int int_sec=0;
int int_min=0;
int int_mil=0;
public static void main(String[] args) {
TimeFrame t = new TimeFrame();
JFrame f = new JFrame("Timer");
f.setSize(300,200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.getContentPane().add(t);
f.setVisible(true);
}
public void count(){
TimeFrame t = new TimeFrame();
if(shouldCount){
long now = System.currentTimeMillis();
while(true){
if(System.currentTimeMillis()-now>=100){
now=System.currentTimeMillis();
String sec = Integer.toString(int_sec);
String min = Integer.toString(int_min);
String mil = Integer.toString(int_mil);
t.update(sec,int_sec,min,mil,int_mil);
int_mil++;
if(int_mil>9){
int_mil=0;
int_sec++;
if(int_sec>=60){
int_sec=1;
int_min++;
}
}
}
}
}
}
}
</code></pre>
<p>And here is TimeFrame.java<br></p>
<pre><code> package random;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TimeFrame extends JPanel{
JLabel time = new JLabel("Time goes here", JLabel.CENTER);
Timer t = new Timer();
JButton pause = new JButton ("Pause");
JButton start = new JButton ("Start");
public TimeFrame(){
start.addActionListener(new starts());
pause.addActionListener(new starts());
add(time);
add(start);
add(pause);
}
public void update(String sec,int s, String min,String mil,int m){
if (s<=10){
sec="0"+sec;
}
System.out.println(min+":"+sec+","+mil);
time.setText(min+":"+sec+","+mil);
}
public class starts implements ActionListener{
public void actionPerformed(ActionEvent event){
if(event.getSource() == start){
t.shouldCount=true;
}else{
t.shouldCount=false;
}
t.count();
}
}
}
</code></pre>
| 0 | 1,283 |
Authentication in jQuery Mobile and PhoneGap
|
<p>I have a web application built with jQuery Mobile and PHP (CodeIgniter framework). Now I'm trying to make a PhoneGap version of it as well, to make it distributable as a standalone app. However, the PHP web app. version uses Ion Auth, a CodeIgniter plugin for authentication. So when you go to a page that requires authentication, the app redirects you to the authentication controller login method. And after authentication it redirects you back to the home page (the jQuery Mobile page in this case). This works fine in the web app., since the home page is opened by the home controller in the first place anyway.</p>
<p>But here's the crux: in the PhoneGap version, the "home" page needs to be the index.html file in PhoneGap. Apparently you can load another url on startup by adding a value in PhoneGap.plist, but that is not acceptable by apple for submitting to app store. And if I do a redirect in the authentication, I can't get back to the index.html file after authentication...</p>
<p>So how should one go about authentication in a PhoneGap/jQuery Mobile app?</p>
<p>UPDATE:</p>
<p>I have tried this according to one of the answers, but the app still tries to navigate to the account/login page (which doesn't exist), when I just want to login through the post and return a value from the method:</p>
<pre><code> $('#login_form').bind('submit', function () {
event.preventDefault();
//send a post request to your web-service
$.post('http://localhost/app_xcode/account/login', $(this).serialize(), function (response) {
//parse the response string into an object
var response = response;
//check if the authorization was successful or not
if (response == true) {
$.mobile.changePage('#toc', "slide");
} else {
alert('login failed');
$.mobile.changePage('#toc', "slide");
}
});
});
</code></pre>
<p>Here's the controller method:</p>
<pre><code>function login()
{
//validate form input
$this->form_validation->set_rules('identity', 'Identity', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$base_url = $this->config->item('base_url');
$mobile = $this->detect_mobile();
if ($mobile === false && $base_url != 'http://localhost/app_xcode/') //Only restrict if not developing
redirect('account/notAMobile');
else if ($this->form_validation->run() == true) { //check to see if the user is logging in
//check for "remember me"
$remember = (bool)$this->input->post('remember');
if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember)) { //if the login is successful
//redirect them back to the home page
$this->session->set_flashdata('message', $this->ion_auth->messages());
echo true;
/*redirect($this->config->item('base_url'), 'refresh');*/
}
else
{ //if the login was un-successful
//redirect them back to the login page
$this->session->set_flashdata('message', $this->ion_auth->errors());
/*redirect('account/login', 'refresh');*/ //use redirects instead of loading views for compatibility with MY_Controller libraries
}
}
else
{ //the user is not logging in so display the login page
//set the flash data error message if there is one
$this->data['message'] = (validation_errors()) ? validation_errors()
: $this->session->flashdata('message');
$this->data['identity'] = array('name' => 'identity',
'id' => 'identity',
'type' => 'text',
'value' => $this->form_validation->set_value('identity'),
);
$this->data['password'] = array('name' => 'password',
'id' => 'password',
'type' => 'password',
);
}
}
</code></pre>
<p>I think I have removed or commented out any redirects that were there. So I don't know why it tries to load the view still? Does it have something to do with jQuery Mobile trying to navigate there because I post to that url?</p>
| 0 | 1,924 |
android scale bitmap to screen dimension
|
<p>actually I'm trying to create simple app with wallpapers.</p>
<p>I'm trying to scale my image to user device screen size.
I'm using code like bellow:</p>
<pre><code>/*
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
*/
Display metrics = getWindowManager().getDefaultDisplay();
int height = metrics.getHeight();
int width = metrics.getWidth();
float fourToThree;
int wymiar;
Bitmap mbitmap; //definicja zmiennej przechowującej bitmapę
try {
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), cardBase.cardImages[position]);
//UP - zapisanie obrazu z tablicy do zmiennej bitmapy
/*if(height>=width) {
fourToThree = height * 0.75f; //height
wymiar = (int)Math.round(fourToThree);
mbitmap = Bitmap.createScaledBitmap(myBitmap, height, wymiar, true);
} else {
fourToThree = height * 0.75f;
wymiar = (int)Math.round(fourToThree);
mbitmap = Bitmap.createScaledBitmap(myBitmap, width, wymiar, true);
}*/
mbitmap = Bitmap.createScaledBitmap(myBitmap, width, height, true);
myWallpaper.setBitmap(mbitmap);
Toast.makeText(SelectedCard.this, "Wallpaper changed", Toast.LENGTH_LONG).show();
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(SelectedCard.this, "Sorry, an error occurred", Toast.LENGTH_LONG).show();
}
</code></pre>
<p>I was trying many other ways but still have my image larger then device screen :(</p>
<p>I'm testing it on <code>virtual phone</code> and I was trying to create image dit 160 dpi as a device screen, it's not working too.</p>
<p>Can anyone tell me, how can I scale my image (jpg - 320 x 480 px, 300 dpi) to set it as a wallpaper on device ?</p>
<p>Any ideas ?</p>
<p>thanks :)</p>
<p>Ps. sorry for text mistakes, English is my second language ;p</p>
<hr>
<p>Ok, i have something like that:</p>
<p>imgView.setOnClickListener(new View.OnClickListener() {</p>
<pre><code> @Override
public void onClick(View v) {
WallpaperManager myWallpaper = WallpaperManager.getInstance(getApplicationContext());
try
/*{
myWallpaper.setResource(HdImageBase.HdImages[position]);
Toast.makeText(ImageMini.this, "Wallpaper changed", Toast.LENGTH_LONG).show();
}*/
{
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
float fourToThree;
int wymiar;
Bitmap mbitmap; //definicja zmiennej przechowującej bitmapę
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), cardBase.cardImages[position]);
mbitmap = Bitmap.createScaledBitmap(myBitmap, width, height, true);
myWallpaper.setBitmap(mbitmap);
Toast.makeText(SelectedCard.this, "Wallpaper changed \n" + width + "\n" + height, Toast.LENGTH_LONG).show();
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(SelectedCard.this, "Sorry, an error occurred", Toast.LENGTH_LONG).show();
}
}
});
</code></pre>
<p>Width and height values are correct 320 x 480 but image which I'm setting as a wallpaper is still more bigger then my device scren.</p>
<p>After test on my real phone LG L5 with new android (not sure which version). Image is set as wallpaper correct (in portrait mode - 1 image for all 5 "roll screens" without scaling).</p>
<p>How can i tested it on other devices ?
Mean... is this portrait mode for wallpapers is available only in new android version ?</p>
| 0 | 1,571 |
How to get jasperreport file (.JRXML) exact location to load to the system?
|
<p>I trying to load jasper report (.jrxml) that i created, i named the report "JREmp1.xml". but i got this error </p>
<blockquote>
<p>"HTTP Status 500 - Request processing failed; nested exception is
net.sf.jasperreports.engine.JRException:
java.io.FileNotFoundException:
D:\printpdf.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\JasperExample\jasper\JREmp1.jrxml
(The system cannot find the path specified)"</p>
</blockquote>
<p>how to got the exact location? here is my JREmp1.xml file location :
<a href="https://i.stack.imgur.com/6XpWf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6XpWf.png" alt="enter image description here"></a></p>
<p>and here is code in my controller class :</p>
<pre><code>@RequestMapping(value = "/generateReport", method = RequestMethod.POST)
public String generateReport(
@Valid @ModelAttribute("jasperInputForm") JasperInputForm jasperInputForm,
BindingResult result, Model model, HttpServletRequest request,
HttpServletResponse response) throws JRException, IOException,
NamingException {
if (result.hasErrors()) {
System.out.println("validation error occured in jasper input form");
return "loadJasper";
}
String reportFileName = "JREmp1";
JasperReportDAO jrdao = new JasperReportDAO();
Connection conn = null;
try {
conn = jrdao.getConnection();
String rptFormat = jasperInputForm.getRptFmt();
String noy = jasperInputForm.getNoofYears();
System.out.println("rpt format " + rptFormat);
System.out.println("no of years " + noy);
HashMap<String, Object> hmParams = new HashMap<String, Object>();
hmParams.put("noy", new Integer(noy));
hmParams.put("Title", "Employees working more than " + noy
+ " Years");
JasperReport jasperReport = jrdao.getCompiledFile(reportFileName,
request);
if (rptFormat.equalsIgnoreCase("html")) {
JasperPrint jasperPrint = JasperFillManager.fillReport(
jasperReport, hmParams, conn);
jrdao.generateReportHtml(jasperPrint, request, response); // For
// HTML
// report
}
else if (rptFormat.equalsIgnoreCase("pdf")) {
jrdao.generateReportPDF(response, hmParams, jasperReport, conn); // For
// PDF
// report
}
} catch (SQLException sqlExp) {
System.out.println("Exception::" + sqlExp.toString());
} finally {
if (conn != null) {
try {
conn.close();
conn = null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
</code></pre>
<p>Here is the code in my <code>JasperReportDAO</code> class :</p>
<pre><code>public JasperReport getCompiledFile(String fileName, HttpServletRequest request) throws JRException {
System.out.println("path " + request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
File reportFile = new File( request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
// If compiled file is not found, then compile XML template
if (!reportFile.exists()) {
JasperCompileManager.compileReportToFile(request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jrxml"),request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
}
JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(reportFile.getPath());
return jasperReport;
}
public void generateReportHtml( JasperPrint jasperPrint, HttpServletRequest req, HttpServletResponse resp) throws IOException, JRException {
HtmlExporter exporter=new HtmlExporter();
List<JasperPrint> jasperPrintList = new ArrayList<JasperPrint>();
jasperPrintList.add(jasperPrint);
exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
exporter.setExporterOutput( new SimpleHtmlExporterOutput(resp.getWriter()));
SimpleHtmlReportConfiguration configuration =new SimpleHtmlReportConfiguration();
exporter.setConfiguration(configuration);
exporter.exportReport();
}
public void generateReportPDF (HttpServletResponse resp, Map parameters, JasperReport jasperReport, Connection conn)throws JRException, NamingException, SQLException, IOException {
byte[] bytes = null;
bytes = JasperRunManager.runReportToPdf(jasperReport,parameters,conn);
resp.reset();
resp.resetBuffer();
resp.setContentType("application/pdf");
resp.setContentLength(bytes.length);
ServletOutputStream ouputStream = resp.getOutputStream();
ouputStream.write(bytes, 0, bytes.length);
ouputStream.flush();
ouputStream.close();
}
</code></pre>
<p>and here is my <code>JasperInputForm</code> class :</p>
<pre><code>public class JasperInputForm {
@NotEmpty
private String noofYears;
private String rptFmt="Html";
public String getRptFmt() {
return rptFmt;
}
public void setRptFmt(String rptFmt) {
this.rptFmt = rptFmt;
}
public String getNoofYears() {
return noofYears;
}
public void setNoofYears(String noofYears) {
this.noofYears = noofYears;
}
}
</code></pre>
<p>how to get my <code>JREmp1.jrxml</code> file location properly? I develop this report for Spring MVC application</p>
<p>UPDATE :
Here is my complete function code after i update with @Wilson answer (i go with second option that @Wilson said) :
this function is inside JasperReportDAO :</p>
<pre><code>public JasperReport getCompiledFile(String fileName, HttpServletRequest request) throws JRException, MalformedURLException, URISyntaxException {
System.out.println("path " + request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
//File reportFile = new File( request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
URL resourceUrl = request.getSession().getServletContext().getResource("/WEB-INF/jasper/" + fileName + ".jrxml");
File reportFile = new File(resourceUrl.toURI());
// If compiled file is not found, then compile XML template
if (!reportFile.exists()) {
JasperCompileManager.compileReportToFile(request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jrxml"),request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
}
JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(reportFile.getPath());
return jasperReport;
}
</code></pre>
<p>and i got this error </p>
<blockquote>
<p>"HTTP Status 500 - Request processing failed; nested exception is
java.lang.IllegalArgumentException: URI scheme is not "file""</p>
</blockquote>
<p>How to solve this?</p>
| 0 | 2,649 |
Trying to change main activity background color on button click
|
<p>Here's my main:</p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
Button btn = (Button) findViewById(R.id.newgame_button);
btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
changeBackground(v);
}
});
}
</code></pre>
<p>I've tried the follow methods, both of which have failed:</p>
<pre><code>public void changeBackground(View v)
{
View someView = findViewById(R.id.main);
View root = someView.getRootView();
root.setBackgroundColor(getResources().getColor(R.color.red));
}
public void changeBackground(View v)
{
View root = v.getRootView();
root.setBackgroundColor(getResources().getColor(R.color.red));
}
</code></pre>
<p>I searched and found the solution for how to solve this in <a href="https://stackoverflow.com/questions/4761686/how-to-set-background-color-of-activity-to-white-programmatically">How to set background color of Activity to white programmatically?</a>; the solution posted was:</p>
<pre><code> // Now get a handle to any View contained
// within the main layout you are using
View someView = findViewById(R.id.randomViewInMainLayout);
// Find the root view
View root = someView.getRootView()
// Set the color
root.setBackgroundColor(android.R.color.red);
</code></pre>
<p>When I try <code>android.R.color.red</code>, eclipse tells me that it should be in the form in my examples.</p>
<p>I did manage to change the background of my button with:</p>
<pre><code>public void changeBackground(View v)
{
v.setBackgroundColor(getResources().getColor(R.color.red));
}
</code></pre>
<p>So, I'm pretty confident that the issue is not with: <code>getResources().getColor(R.color.red)</code>. I've tried many different ways, and I'm not getting anywhere. For reference, here's my xml:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/LightCyan"
android:id="@+id/main">
<TextView
android:layout_width="fill_parent"
android:layout_height="0dip"
android:text="@string/welcome"
android:gravity="center"
android:layout_weight="3" />
<LinearLayout
android:layout_width="200dp"
android:layout_height="0dip"
android:orientation="vertical"
android:layout_gravity="center"
android:layout_weight="2" >
<Button
android:id="@+id/resume_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/resume"
android:background="@color/Plum"/>
<Button
android:id="@+id/newgame_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/new_game"
android:background="@color/Plum"
android:onClick="changeBackground"/>
</LinearLayout>
</LinearLayout>
</code></pre>
<p>Any help would be appreciated. Thanks in advance.</p>
| 0 | 1,359 |
Webpack Dev Server (webpack-dev-server) Hot Module Replacement (HMR) Not Working
|
<p>I have gone through many answers on StackOverflow & on GitHub issues as well but, I am still stuck in Hot Module Replacement in Webpack. I am using <code>npm start</code> to run my server with <code>webpack-dev-server --hot --inline</code>. <strong>I am trying to change code in my React component, but nothing happens in the browser</strong>.</p>
<p>I am using Google Chrome Version 49.0.2623.87 (64-bit) on Ubuntu 14.04LTS.</p>
<p>In my browser <code>console</code>, I am getting log messages as</p>
<blockquote>
<p>[HMR] Waiting for update signal from WDS...</p>
<p>[WDS] Hot Module Replacement enabled.</p>
</blockquote>
<p>But, no hot/live reload is happening. Nothing gets displayed when I change code in my React component file. I was following first video of this tutorial, <a href="https://egghead.io/lessons/react-react-fundamentals-development-environment-setup" rel="nofollow noreferrer">Egghead.io/ReactFundamentals</a> where everything worked fine.</p>
<p>Following are my package.json & webpack.config.js files.</p>
<p><strong>package.json</strong></p>
<pre><code>{
"name": "react-fundamentals",
"version": "1.0.0",
"description": "Fundamentals of ReactJS",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --hot --inline"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^15.0.0-rc.2",
"react-dom": "^15.0.0-rc.2"
},
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.7.2",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"react-hot-loader": "^1.3.0",
"webpack": "^1.12.14",
"webpack-dev-server": "^1.14.1"
}
}
</code></pre>
<p><strong>webpack.config.js</strong></p>
<pre><code>module.exports = {
context: __dirname,
entry: "./main.js",
output: {
path: __dirname,
filename: "bundle.js"
},
devServer: {
port: 7777
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel",
query: {
presets: ["es2015", "react"]
}
}
]
}
}
</code></pre>
<p>It will be great if someone can guide me through this issue as I am not able to proceed further efficiently with the tutorial.</p>
<blockquote>
<p><strong>Update</strong> I have posted the answer below.</p>
</blockquote>
| 0 | 1,232 |
how to hide templatefield in gridview
|
<p>I am repeating this question because i am not able to find answer from anywhere.</p>
<p>I Have a <code>GridView</code> in .aspx page. I want to hide columns based on aspx.cs <code>BindData()</code> method.</p>
<p>I have tried using below code but not able to hide. I am using Asp.net with C#.</p>
<p>Below is my <code>GridView</code> with columns and I have also included the <code>Button</code> click code.</p>
<p>If I <code>select "T-L"</code> which is in below <code>else-if Ladder</code> i am getting this <code>error</code></p>
<p><strong>DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'tutorial'.</strong><br>
I have marked a test case error in .aspx</p>
<p>For temporary to make my program work i am using 4 gridview to bind 4 query,which is not feasible...How can i hide templatefield invisible based on conditions...
plz help me..</p>
<pre><code><GridView>
<Columns>
<asp:BoundField DataField="id" HeaderText="Id" SortExpression="id"
Visible="false" />
<asp:TemplateField HeaderText="RollNo" >
<ItemTemplate>
<%# Eval("st_rollno")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbsturollno" runat="Server"
Text='<%# Eval("st_rollno") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("st_name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbstuname" runat="Server"
Text='<%# Eval("st_name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Theory">
<ItemTemplate>
<%# Eval("theory")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtheory" runat="Server"
Text='<%# Eval("theory") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<%# Eval("ttotal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtheorytotal" runat="Server"
Text='<%# Eval("ttotal") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lab" >
<ItemTemplate>
<%# Eval("lab")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tblab" runat="Server"
Text='<%# Eval("lab") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<%# Eval("ltotal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tblabtotal" runat="Server"
Text='<%# Eval("ltotal") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tutorial" >
<ItemTemplate>
*Error is HERE <%# Eval("tutorial")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtutorial" runat="Server"
Text='<%# Eval("tutorial") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<%# Eval("tutotal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbtutorialtotal" runat="Server"
Text='<%# Eval("tutotal") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</GridView>
private void BindData()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
if (stype.Equals("L"))
{
query = "SELECT [id], [st_rollno], [st_name], [lab], [ltotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = @branch_name) AND ([scode] = @scode) AND ([sem_no] = @sem_no) AND ([sess_no] = @sess_no)) ORDER BY [st_rollno]";
GridView1.Columns[3].Visible = false;
GridView1.Columns[4].Visible = false;
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
}
else if (stype.Equals("T"))
{
query = "SELECT [id], [st_rollno], [st_name], [theory], [ttotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = @branch_name) AND ([scode] = @scode) AND ([sem_no] = @sem_no) AND ([sess_no] = @sess_no)) ORDER BY [st_rollno]";
GridView1.Columns[5].Visible = false;
GridView1.Columns[6].Visible = false;
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
}
else if (stype.Equals("T-L"))
{
GridView1.Columns[7].Visible = false;
GridView1.Columns[8].Visible = false;
query = "SELECT [id], [st_rollno], [st_name], [theory], [ttotal], [lab], [ltotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = @branch_name) AND ([scode] = @scode) AND ([sem_no] = @sem_no) AND ([sess_no] = @sess_no)) ORDER BY [st_rollno]";
}
else
{
query = "SELECT [id], [st_rollno], [st_name],[theory], [ttotal], [lab], [ltotal], [tutorial], [tutotal] FROM [Attendence_Subject_Wise] WHERE (([branch_name] = @branch_name) AND ([scode] = @scode) AND ([sem_no] = @sem_no) AND ([sess_no] = @sess_no)) ORDER BY [st_rollno]";
}
com = new SqlCommand(query);
com.Parameters.Add("@branch_name", dept);
com.Parameters.Add("@scode", dpsubject.SelectedItem.Text.ToString());
com.Parameters.Add("@sem_no", Int32.Parse(dpsemno.SelectedItem.Text.ToString()));
com.Parameters.Add("@sess_no",Int32.Parse(dpsessional.SelectedItem.Text.ToString()));
using (SqlDataAdapter sda = new SqlDataAdapter())
{
com.Connection = con;
con.Open();
sda.SelectCommand = com;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
}
}
protected void bsubmit_Click(object sender, EventArgs e)
{
this.BindData();
}
</code></pre>
| 0 | 3,719 |
MVVM DataGrid SelectedItem binding doesn’t get updated
|
<p>I’m new to .Net and C# and a little bit confused with bindings. I have application that implements MVVM and displays DataGrid. What I want to implement is when user presses certain key combination then the content of currently selected cell gets copied to the cell in the row below.
I have tried binding the SelectedItem of DataGrid to the ViewModel property but it never gets updated. CommandParameter also didn’t work, item count is always 0.
So I cannot extract what cell the user has selected and cannot read the content of the selected cell.
Does anyone have suggestions how to solve this problem or implement this functionality?
Thanks in advance.
code:
xaml:</p>
<pre><code><DataGrid Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="9"
AutoGenerateColumns="False"
Height="Auto"
HorizontalAlignment="Left"
Name="dataGrid"
VerticalAlignment="Top"
Width="{Binding ElementName=grid4,Path=Width}"
ScrollViewer.CanContentScroll="False"
FrozenColumnCount="1"
SelectionUnit="Cell"
SelectionMode="Extended"
CanUserSortColumns = "False"
CanUserReorderColumns="False"
CanUserResizeRows="False"
RowHeight="25"
RowBackground="LightGray"
AlternatingRowBackground="White"
ScrollViewer.VerticalScrollBarVisibility="Visible"
ScrollViewer.HorizontalScrollBarVisibility="Visible"
ItemsSource="{Binding Layers, Mode=TwoWay}"
SelectedItem="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.Selection, Mode=TwoWay}">
<DataGrid.InputBindings>
<KeyBinding Gesture="Shift"
Command="{Binding ItemHandler}"
CommandParameter="{Binding ElementName=dataGrid, Path=SelectedItems}">
</KeyBinding>
</DataGrid.InputBindings>
</DataGrid>
</code></pre>
<p>ViewModel:</p>
<pre><code>private float _selection = 0.0f;
public float Selection
{
get
{
return _selection;
}
set
{
if (_selection != value)
{
_selection = value;
NotifyPropertyChanged("Selection");
}
}
}
</code></pre>
<p>...</p>
<pre><code> public DelegateCommand<IList> SelectionChangedCommand = new DelegateCommand<IList>(
items =>
{
if (items == null)
{
NumberOfItemsSelected = 0;
return;
}
NumberOfItemsSelected = items.Count;
});
public ICommand ItemHandler
{
get
{
return SelectionChangedCommand;
}
}
</code></pre>
| 0 | 1,267 |
angularjs filter (not working)
|
<p>The following HTML, Javascript and JSON render correctly, but the filter does not work at all. What are we doing wrong?</p>
<pre class="lang-html prettyprint-override"><code><div data-ng-controller="dashboard_controller">
<h1>
Catalogs
<input type="text" data-ng-model="catalog_filter" placeholder="Filter Distributors">
</h1>
<div class="catalogs_listing">
<ul data-ng-repeat="catalog in catalogs | filter:catalog_filter">
<li><a href="{{catalog.distributor_id}}/d/products/catalog_view/{{catalog.uid}}">
<div class="catalog_thumb">
<div class="catalog_thumb_image">
<img src="{{catalog.thumb_image}}" />
</div>
</div>
<div class="catalog_info">
<h2>{{distributors[catalog.distributor_id].name}}
<span>{{catalog.products_count}}p</span>
</h2>
<p>{{catalog.name}}</p>
</div>
</a>
</li>
</ul>
</div>
</div>
</code></pre>
<p>The Javascript:</p>
<pre class="lang-js prettyprint-override"><code>app.controller('dashboard_controller', function ($scope, $http) {
$http.get('./api/distributors/my').then(function (res) {
$scope.distributors = res.data;
});
$http.get('./api/dashboard/catalogs').then(function (res) {
$scope.catalogs = res.data;
});
});
</code></pre>
<p>And these 2 JSONs:</p>
<p><strong>api/distributors/my:</strong></p>
<pre class="lang-js prettyprint-override"><code>{
"data": {
"9kkE1sL8vXSZMVaL": {
"created": "1346840145.22",
"uid": "9kkE1sL8vXSZMVaL",
"created_by": "3W7AoIQHTtvPauaK",
"name": "Nikee",
"description": "Just do it",
"image_file": "LogoNike.jpg",
"modified": "1368443518.3894",
"modified_by": "3W7AoIQHTtvPauaK",
"currency": "gbp"
},
"1OBKUhpb8srwHVVb": {
"created": "1346840213.41",
"uid": "1OBKUhpb8srwHVVb",
"created_by": "3W7AoIQHTtvPauaK",
"name": "Zappos",
"description": "The webs most popular shoe store",
"image_file": "zappos.jpg",
"modified": "1347006513.93",
"modified_by": "3W7AoIQHTtvPauaK",
"currency": null
},
"qHPXDp5lSQuz9z3Q": {
"created": "1346840305.78",
"uid": "qHPXDp5lSQuz9z3Q",
"created_by": "3W7AoIQHTtvPauaK",
"name": "Kitchenaid",
"description": "For the way it's made",
"image_file": "kitchenaid_logo.gif",
"modified": "1346840305.78",
"modified_by": "3W7AoIQHTtvPauaK",
"currency": null
},
"9K4G8gE1sh4qpVG2": {
"created": "1346840443.32",
"uid": "9K4G8gE1sh4qpVG2",
"created_by": "3W7AoIQHTtvPauaK",
"name": "Unilever",
"description": "Create a better future",
"image_file": "Unilever-logo.jpg",
"modified": "1346842125.2",
"modified_by": "3W7AoIQHTtvPauaK",
"currency": null
},
"55ORaD7h0EMcaX82": {
"created": "1346840529.93",
"uid": "55ORaD7h0EMcaX82",
"created_by": "3W7AoIQHTtvPauaK",
"name": "Dell",
"description": "The power to do more",
"image_file": "dell-logo.jpg",
"modified": "1346840529.93",
"modified_by": "3W7AoIQHTtvPauaK",
"currency": null
},
"2LHf5ZipYjA2PdXu": {
"created": "1352084334.37",
"uid": "2LHf5ZipYjA2PdXu",
"created_by": "3MO4JyiB9rMWTfBu",
"name": "Online Retailer",
"description": "Online Retailer",
"image_file": "Home and Giftware.gif",
"modified": "1352954806.28",
"modified_by": "cu3OraVD7WclpLrX",
"currency": null
},
"MdTDL72ynFySuUCR": {
"created": "1352870158.83",
"uid": "MdTDL72ynFySuUCR",
"created_by": "1JiAF71w5VPHGgJe",
"name": "Uniuniform",
"description": "Uniform Suppliers",
"image_file": "CWLogo.png",
"modified": "1358317144.85",
"modified_by": "sv3HuiiRbiuHWkul",
"currency": null
},
"oyYmdDcod9fseZng": {
"created": "1352934703.42",
"uid": "oyYmdDcod9fseZng",
"created_by": "cu3OraVD7WclpLrX",
"name": "Heidy Pharmaceuticals",
"description": "Pharmaceutical Solutions",
"image_file": "heidy.jpg",
"modified": "1352934703.43",
"modified_by": "cu3OraVD7WclpLrX",
"currency": null
},
"Kfs4HdFUfz6j2l2I": {
"created": "1352953682.22",
"uid": "Kfs4HdFUfz6j2l2I",
"created_by": "cu3OraVD7WclpLrX",
"name": "xxx",
"description": "Online Retailer",
"image_file": "xxx.gif",
"modified": "1352953828.34",
"modified_by": "cu3OraVD7WclpLrX",
"currency": null
},
"g2qRqUWvPSLRvLQr": {
"created": "1352953924.68",
"uid": "g2qRqUWvPSLRvLQr",
"created_by": "cu3OraVD7WclpLrX",
"name": "ddd",
"description": "Natural Product Retailer",
"image_file": "yes-to.jpg",
"modified": "1352953924.68",
"modified_by": "cu3OraVD7WclpLrX",
"currency": null
},
"bbSu3jpFhdkG3TJR": {
"created": "1352954016.22",
"uid": "bbSu3jpFhdkG3TJR",
"created_by": "cu3OraVD7WclpLrX",
"name": "llll",
"description": "Artificial Product Retailer",
"image_file": "l.jpg",
"modified": "1352954016.23",
"modified_by": "cu3OraVD7WclpLrX",
"currency": null
},
"X9xWF9VrRDqGWZ6S": {
"created": "1352954722.97",
"uid": "X9xWF9VrRDqGWZ6S",
"created_by": "cu3OraVD7WclpLrX",
"name": "zzz",
"description": "Toy Manufacturer",
"image_file": "zzz.jpg",
"modified": "1352954722.97",
"modified_by": "cu3OraVD7WclpLrX",
"currency": null
},
"02CCPuWtM6ZJVgiQ": {
"created": "1367741881.7113",
"uid": "02CCPuWtM6ZJVgiQ",
"created_by": "3W7AoIQHTtvPauaK",
"name": "test brand",
"description": "xxxx",
"image_file": null,
"modified": "1367741882.5129",
"modified_by": "3W7AoIQHTtvPauaK",
"currency": null
},
"GjsdgMCzp1n379j0": {
"created": "1369136484.1802",
"uid": "GjsdgMCzp1n379j0",
"created_by": "3W7AoIQHTtvPauaK",
"name": "testing all products",
"description": "just a test",
"image_file": null,
"modified": "1369136484.5298",
"modified_by": "3W7AoIQHTtvPauaK",
"currency": "usd"
},
"spVsxtJVroMkXQ1N": {
"created": "1370508658.353",
"uid": "spVsxtJVroMkXQ1N",
"created_by": "3W7AoIQHTtvPauaK",
"name": "pppp Import",
"description": "",
"image_file": null,
"modified": "1370508658.4394",
"modified_by": "3W7AoIQHTtvPauaK",
"currency": "usd"
}
}
</code></pre>
<p><strong>api/dashboard/catalogs</strong></p>
<pre class="lang-js prettyprint-override"><code>{
"data": {
"UPf17vFhMhiM2yYl": {
"created": "1352960014.4",
"uid": "UPf17vFhMhiM2yYl",
"created_by": "3MO4JyiB9rMWTfBu",
"name": "All Products",
"description": "This catalog contains all of your products",
"modified": "1352960014.4",
"modified_by": "3MO4JyiB9rMWTfBu",
"distributor_id": "9kkE1sL8vXSZMVaL",
"image": null,
"start": null,
"end": null,
"is_archived": null,
"products_count": "0",
"thumb_image": "resources/media/default_image.jpg.thumbs/165x165.jpg"
},
"ZUfcKpz0VrJZZZvW": {
"created": "1354172792.79",
"uid": "ZUfcKpz0VrJZZZvW",
"created_by": "ORIGWlEFxbuE945J",
"name": "test catalog",
"description": "",
"modified": "1354172792.79",
"modified_by": "ORIGWlEFxbuE945J",
"distributor_id": "9kkE1sL8vXSZMVaL",
"image": null,
"start": null,
"end": null,
"is_archived": null,
"products_count": "0",
"thumb_image": "resources/media/default_image.jpg.thumbs/165x165.jpg"
},
"6YoSSDCzLH8gEokf": {
"created": "1360706477.5283",
"uid": "6YoSSDCzLH8gEokf",
"created_by": "3W7AoIQHTtvPauaK",
"name": "xxxx",
"description": "",
"modified": "1360706477.5312",
"modified_by": "3W7AoIQHTtvPauaK",
"distributor_id": "9kkE1sL8vXSZMVaL",
"image": null,
"start": null,
"end": null,
"is_archived": null,
"products_count": "3",
"thumb_image": "resources/media/default_image.jpg.thumbs/165x165.jpg"
},
"4AwqE7iTNQmjSBED": {
"created": "1360794567.8451",
"uid": "4AwqE7iTNQmjSBED",
"created_by": "3W7AoIQHTtvPauaK",
"name": "All Products",
"description": null,
"modified": "1360794567.8454",
"modified_by": "3W7AoIQHTtvPauaK",
"distributor_id": "4AwqE7iTNQmjSBED",
"image": null,
"start": null,
"end": null,
"is_archived": null,
"products_count": "1",
"thumb_image": "resources/media/default_image.jpg.thumbs/165x165.jpg"
},
"02CCPuWtM6ZJVgiQ": {
"created": "1367741881.7916",
"uid": "02CCPuWtM6ZJVgiQ",
"created_by": "3W7AoIQHTtvPauaK",
"name": "All Products",
"description": null,
"modified": "1367741881.7919",
"modified_by": "3W7AoIQHTtvPauaK",
"distributor_id": "02CCPuWtM6ZJVgiQ",
"image": null,
"start": null,
"end": null,
"is_archived": null,
"products_count": "2095",
"thumb_image": "resources/media/default_image.jpg.thumbs/165x165.jpg"
},
"9kkE1sL8vXSZMVaL": {
"created": "1368165852.0352",
"uid": "9kkE1sL8vXSZMVaL",
"created_by": "3W7AoIQHTtvPauaK",
"name": "All Products",
"description": null,
"modified": "1368165852.0361",
"modified_by": "3W7AoIQHTtvPauaK",
"distributor_id": "9kkE1sL8vXSZMVaL",
"image": null,
"start": null,
"end": null,
"is_archived": null,
"products_count": "26",
"thumb_image": "resources/media/default_image.jpg.thumbs/165x165.jpg"
},
"ZmSiqOK2C2Sq3MWB": {
"created": "1368958571.9548",
"uid": "ZmSiqOK2C2Sq3MWB",
"created_by": "3W7AoIQHTtvPauaK",
"name": "Test Catalog",
"description": "",
"modified": "1368958571.9581",
"modified_by": "3W7AoIQHTtvPauaK",
"distributor_id": "02CCPuWtM6ZJVgiQ",
"image": null,
"start": "0",
"end": "0",
"is_archived": "1",
"products_count": "0",
"thumb_image": "resources/media/default_image.jpg.thumbs/165x165.jpg"
},
"flzoMbizDDTDpjgc": {
"created": "1368958778.8623",
"uid": "flzoMbizDDTDpjgc",
"created_by": "3W7AoIQHTtvPauaK",
"name": "xzczxc",
"description": "",
"modified": "1368958778.8637",
"modified_by": "3W7AoIQHTtvPauaK",
"distributor_id": "02CCPuWtM6ZJVgiQ",
"image": null,
"start": "0",
"end": "0",
"is_archived": "0",
"products_count": "29",
"thumb_image": "resources/media/default_image.jpg.thumbs/165x165.jpg"
},
"KfRJHxp7jBnBGCJ5": {
"created": "1369219487.4418",
"uid": "KfRJHxp7jBnBGCJ5",
"created_by": "3W7AoIQHTtvPauaK",
"name": "hhh",
"description": "",
"modified": "1369219487.4433",
"modified_by": "3W7AoIQHTtvPauaK",
"distributor_id": "9kkE1sL8vXSZMVaL",
"image": null,
"start": "0",
"end": "0",
"is_archived": "0",
"products_count": "7",
"thumb_image": "resources/media/default_image.jpg.thumbs/165x165.jpg"
},
"spVsxtJVroMkXQ1N": {
"created": "1370508658.3567",
"uid": "spVsxtJVroMkXQ1N",
"created_by": "3W7AoIQHTtvPauaK",
"name": "All Products",
"description": null,
"modified": "1370508658.3575",
"modified_by": "3W7AoIQHTtvPauaK",
"distributor_id": "spVsxtJVroMkXQ1N",
"image": null,
"start": "0",
"end": "0",
"is_archived": "0",
"products_count": "343",
"thumb_image": "resources/media/default_image.jpg.thumbs/165x165.jpg"
},
"1OBKUhpb8srwHVVb": {
"created": "1370857435.5606",
"uid": "1OBKUhpb8srwHVVb",
"created_by": "3W7AoIQHTtvPauaK",
"name": "All Products",
"description": null,
"modified": "1370857435.5612",
"modified_by": "3W7AoIQHTtvPauaK",
"distributor_id": "1OBKUhpb8srwHVVb",
"image": null,
"start": "0",
"end": "0",
"is_archived": "0",
"products_count": "4",
"thumb_image": "resources/media/default_image.jpg.thumbs/165x165.jpg"
},
"wXMHFdPyiXFBuRjJ": {
"created": "1370864864.1247",
"uid": "wXMHFdPyiXFBuRjJ",
"created_by": "3W7AoIQHTtvPauaK",
"name": "x",
"description": "",
"modified": "1370864864.1278",
"modified_by": "3W7AoIQHTtvPauaK",
"distributor_id": "spVsxtJVroMkXQ1N",
"image": null,
"start": "0",
"end": "0",
"is_archived": "0",
"products_count": "10",
"thumb_image": "resources/media/default_image.jpg.thumbs/165x165.jpg"
},
"GjsdgMCzp1n379j0": {
"created": "1371116610.6898",
"uid": "GjsdgMCzp1n379j0",
"created_by": "3W7AoIQHTtvPauaK",
"name": "All Products",
"description": null,
"modified": "1371116610.6902",
"modified_by": "3W7AoIQHTtvPauaK",
"distributor_id": "GjsdgMCzp1n379j0",
"image": null,
"start": "0",
"end": "0",
"is_archived": "0",
"products_count": "2095",
"thumb_image": "resources/media/default_image.jpg.thumbs/165x165.jpg"
},
"gvWLNWwsI3B7mnCU": {
"created": "1371116669.5872",
"uid": "gvWLNWwsI3B7mnCU",
"created_by": "3W7AoIQHTtvPauaK",
"name": "All Products",
"description": null,
"modified": "1371116669.5877",
"modified_by": "3W7AoIQHTtvPauaK",
"distributor_id": "gvWLNWwsI3B7mnCU",
"image": null,
"start": "0",
"end": "0",
"is_archived": "0",
"products_count": 0,
"thumb_image": "resources/media/default_image.jpg.thumbs/165x165.jpg"
}
}
</code></pre>
| 0 | 9,986 |
PostgreSQL error 'Could not connect to server: No such file or directory'
|
<p>Like some others I am getting this error when I run rake db:migrate in my project or even try most database tasks for my <a href="http://en.wikipedia.org/wiki/Ruby_on_Rails" rel="noreferrer">Ruby on Rails</a> 3.2 applications.</p>
<blockquote>
<p>PGError (could not connect to server: No such file or directory. Is the
server running locally and accepting connections on Unix domain socket
"/tmp/.s.PGSQL.5432"?</p>
</blockquote>
<p>I installed <a href="http://en.wikipedia.org/wiki/PostgreSQL" rel="noreferrer">PostgreSQL</a> with <a href="https://en.wikipedia.org/wiki/Homebrew_%28package_management_software%29" rel="noreferrer">Homebrew</a> a long time ago and following an attempted installation of <a href="http://en.wikipedia.org/wiki/MongoDB" rel="noreferrer">MongoDB</a> recently my PostgreSQL install has never been the same. I'm running OS X v10.6 Snow Leopard.</p>
<p>What's wrong and how do I better understand how PostgreSQL is and should be setup on my Mac?</p>
<p>So far (I think) this tells me that PostgreSQL is not running(?).</p>
<pre><code>ps -aef|grep postgres (ruby-1.9.2-p320@jct-ana) (develop) ✗
501 17604 11329 0 0:00.00 ttys001 0:00.00 grep postgres
</code></pre>
<p>But does this tell me that PostgreSQL is running?</p>
<pre><code>✪ launchctl load -w /usr/local/Cellar/postgresql/9.1.4/homebrew.mxcl.postgresql.plist (ruby-1.9.2-p136)
homebrew.mxcl.postgresql: Already loaded
</code></pre>
<p>How do I fix this? what am I not seeing?</p>
<p>PS: <code>~/Library/LaunchAgents</code> includes two PostgreSQL .plist files. I am not sure if that's relevant.</p>
<pre><code>org.postgresql.postgres.plist
homebrew.mxcl.postgresql.plist
</code></pre>
<p>I tried the following and got a result as below.</p>
<p><strong>$ psql -p 5432 -h localhost</strong> </p>
<pre><code>psql: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "localhost" (fe80::1) and accepting
TCP/IP connections on port 5432?
</code></pre>
<p>I've read since that this is occuring because OS X installs its own version of PostgreSQL and Homebrew installs a different version in a different place and the PostgreSQL commands are looking in the /tmp/ directory. You'll need to search more on Stack Overflow, but basically you symlink PostgreSQL so that anything looking in that tmp path actually finds the real path, if that makes sense.</p>
<p>This is the link where I found a few more things to try, specifically doing the symlink as per above, <em><a href="https://stackoverflow.com/questions/17240516">Mac OSX Lion Postgres does not accept connections on /tmp/.s.PGSQL.5432</a></em>. I still wish someone would put together a decent explanation of the concepts behind installing PostgreSQL on OS X and why it's all so difficult.</p>
<p>Latest insights to help with troubleshooting:</p>
<pre><code>$ which psql // This tells you which PostgreSQL you are using when you run $ psql.
</code></pre>
<p>Then run:</p>
<pre><code>$ echo $PATH
</code></pre>
<p>The key thing to take into account is this:</p>
<p><strong>Ensure that the path entry for the copy of PostgreSQL you want to run COMES BEFORE the path to the OS X system's PostgreSQL.</strong></p>
<p>This is a core requirement which decides which PostgreSQL gets run and is what I'm told leads to most of these issues.</p>
| 0 | 1,349 |
Application context being loaded twice - Spring Boot
|
<p>I have a fairly simple setup. A maven project with 3 modules : core/webapp/model. I'm using Spring boot to gear up my application. In webapp, i have a simple class WebappConfig as follows:</p>
<pre><code>@Configuration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = @ComponentScan.Filter(Configuration.class))
public class WebappConfig {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(WebappConfig.class);
app.setAdditionalProfiles("dev");
app.run(args);
}
}
</code></pre>
<p>and few classes in core/model module. My container-application point is :</p>
<pre><code>public class AbcdXml extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WebappConfig.class);
}
}
</code></pre>
<p>And no web.xml! My model's pom has following spring boot related dependency :</p>
<pre><code><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</code></pre>
<p>Core's pom.xml :</p>
<pre><code><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
</code></pre>
<p>Now running WebappConfig via Run as -> Java application works perfectly but i need to deploy the project as a war on tomcat7. Webapp's packaging is war. There is no tomcat provided jar's in lib except tomcat-jdbc and tomcat-tuli jar(Shouldn't be an issue?).</p>
<p>When i deploy my abcd.war, applicationcontext is getting loaded twice and result in following error stracktrace :</p>
<pre><code>2014-06-27 11:06:08.445 INFO 23467 --- [ost-startStop-1] o.a.c.c.C.[.[localhost].[/abcd] : Initializing Spring embedded WebApplicationContext
2014-06-27 11:06:08.446 INFO 23467 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 19046 ms
2014-06-27 11:06:21.308 INFO 23467 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2014-06-27 11:06:21.313 INFO 23467 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'errorPageFilter' to: [/*]
2014-06-27 11:06:21.314 INFO 23467 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2014-06-27 11:06:26.073 INFO 23467 --- [ost-startStop-1] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2014-06-27 11:06:26.127 INFO 23467 --- [ost-startStop-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2014-06-27 11:06:26.511 INFO 23467 --- [ost-startStop-1] org.hibernate.Version : HHH000412: Hibernate Core {4.3.1.Final}
2014-06-27 11:06:26.521 INFO 23467 --- [ost-startStop-1] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2014-06-27 11:06:26.527 INFO 23467 --- [ost-startStop-1] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
//some info messages from spring boot
2014-06-27 11:07:31.664 INFO 23467 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-06-27 11:07:33.095 INFO 23467 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-06-27 11:07:33.096 INFO 23467 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-06-27 11:07:36.080 INFO 23467 --- [ost-startStop-1] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2014-06-27 11:08:49.583 INFO 23467 --- [ost-startStop-1] o.s.boot.SpringApplication : Started application in 183.152 seconds (JVM running for 210.258)
2014-06-27 11:12:29.229 ERROR 23467 --- [ost-startStop-1] o.a.c.c.C.[.[localhost].[/abcd] : Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:277)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4937)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:976)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1653)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
</code></pre>
<p>There is no web.xml as i mentioned earlier.</p>
<p>Few interesting things that i can't figure out why :</p>
<ol>
<li>After exploding the war, tomcat somehow create a ROOT folder with default web.xml[Must be Spring boot misconfiguration. How can i correct it? Pointers please?]</li>
<li>Even if i return same 'application' SpringApplicationBuilder in AbcdXml.java, i am facing the same issue of applicationcontext being loaded twice.</li>
</ol>
<p>Thanks for your help!</p>
<p>EDIT 1:</p>
<p>Content of web.xml that is generated in ROOT folder :</p>
<pre><code><?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" version="2.5">
</web-app>
</code></pre>
| 0 | 2,775 |
Angularjs: Displaying array of objects
|
<p>For the life of me I cannot extract and print out the data in my array. I've generated JSON in PHP and I've wired up Angularjs to retrieve this data. The Angularjs development tool within Chrome is telling me that I have a variable "user" that is an array of objects (see below) when I run the code. I made user a rootScope variable "$rootScope.user = data;" so I can get at it. I'm a newb so none of this is probably best practice.</p>
<pre><code>{
user : [{"user_id":"1","firstname":"John","lastname":"Doe","email":"john.doe@email.com","age":"29","height":"74.5","weight":"200","gender":"M","birthdate":"2013-12-31","username":"john.doe","hash":"$2a$10$MECYLWuu6AwRxzBF\/CUys.AuqVm7Lf4BYRGezeusvLe6wNTkU3FEy"}]
}
</code></pre>
<p>This is the <code>ng-repeat</code> I use on the same page that shows the above "user" is within its scope:</p>
<pre><code><ul id="biometrics" ng-repeat="info in user">
<li>Age: {{info.age}}</li>
</ul>
</code></pre>
<p>What am I doing wrong? Perhaps what am I NOT doing wrong. I'm new to Angularjs to say the least.</p>
<hr>
<p>I tried what was suggested but to no avail. I just want to try and clarify my code/situation just to be sure I didn't screw up. I think I may have been unclear as this is also my first time posting on StackOverflow.</p>
<p>This is literally what my login.php file returns: </p>
<blockquote>
<p>[{"user_id":"1","firstname":"John","lastname":"Doe","email":"john.doe@email.com","age":"29","height":"74.5","weight":"200","gender":"M","birthdate":"2013-12-31","photoURL":"john.doe.jpg","username":"john.doe","hash":"$2a$10$MECYLWuu6AwRxzBF/CUys.AuqVm7Lf4BYRGezeusvLe6wNTkU3FEy"}]</p>
</blockquote>
<p>This is my login controller:</p>
<pre><code>app.controller("LoginController", ['$scope', '$rootScope', '$http', '$location', function($scope, $rootScope, $http, $location) {
$scope.errorMessage = "Wrong password or username";
$scope.login = function() {
$http({
url: "./login.php",
method: "POST",
data: { cache: false, username: $scope.username, password: $scope.password },
headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function(data, status, headers, config) {
$rootScope.user = data;
$location.path('/dashboard');
}).error(function(data, status, headers, config) {
$scope.statusMessage = status;
alert($scope.errorMessage);
});
}
}]);
</code></pre>
<p>This is in my view HTML:</p>
<pre><code><ul id="biometrics" ng-repeat="info in user">
<li>Age: {{info}}</li>
</ul>
</code></pre>
<p>I get nothing when I try this and I tried data.user and got nothing.</p>
| 0 | 1,129 |
How can I use another mapping from different class in mapstruct
|
<p>I would like to mapping a model object to dto model. I already have mapper for one of the object.
How can I reuse this mapper in another mapper which is in another class?</p>
<p>I have below as model</p>
<pre><code> @Getter
@AllArgsConstructor
@ToString
public class History {
@JsonProperty("identifier")
private final Identifier identifier;
@JsonProperty("submitTime")
private final ZonedDateTime submitTime;
@JsonProperty("method")
private final String method;
@JsonProperty("reason")
private final String reason;
@JsonProperty("dataList")
private final List<Data> dataList;
}
@DynamoDBTable(tableName = "history")
@Data
@NoArgsConstructor
public class HistoryDynamo {
@DynamoDBRangeKey(attributeName = "submitTime")
@DynamoDBTypeConverted(converter = ZonedDateTimeType.Converter.class)
private ZonedDateTime submitTime;
@DynamoDBAttribute(attributeName = "identifier")
@NonNull
private Identifier identifier;
@DynamoDBAttribute(attributeName = "method")
private String method;
@DynamoDBAttribute(attributeName = "reason")
private String reason;
@DynamoDBAttribute(attributeName = "dataList")
private List<Data> dataList;
}
@Data
@DynamoDBDocument
@NoArgsConstructor
public class Identifier implements Serializable {
@DynamoDBAttribute(attributeName = "number")
private String number;
@DynamoDBAttribute(attributeName = "cityCode")
@NonNull
private String cityCode;
@DynamoDBAttribute(attributeName = "countryCode")
@NonNull
private String countryCode;
@DynamoDBTypeConverted(converter = LocalDateType.Converter.class)
private LocalDate mydate;
}
@Data
@EqualsAndHashCode
@NoArgsConstructor
@RequiredArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Identifier implements Serializable {
@NonNull
@lombok.NonNull
@NotNull
private String number;
@NonNull
@lombok.NonNull
@NotNull
private City city;
@NonNull
@lombok.NonNull
@NotNull
private Country country;
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'Z'")
@DateTimeFormat(pattern = "yyyy-MM-dd'Z'")
@NonNull
@lombok.NonNull
@NotNull
private LocalDate mydate;
}
</code></pre>
<p>And here is my mapping</p>
<pre><code> @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.WARN, injectionStrategy = InjectionStrategy.CONSTRUCTOR, nullValueMappingStrategy = NullValueMappingStrategy.RETURN_NULL)
public interface IdentifierMapper {
IdentifierMapper MAPPER = Mappers.getMapper(IdentifierMapper.class);
@Mappings({@Mapping(source = "identifier.number", target = "number"),
@Mapping(source = "identifier.city.code", target = "cityCode"),
@Mapping(source = "identifier.country.code", target = "countryCode"),
@Mapping(source = "identifier.mydate", target = "mydate")})
@Named("toIdentifierDynamo")
myproject.entity.dynamo.Identifier toIdentifierDynamo(myproject.model.Identifier identifier);
}
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.WARN, injectionStrategy = InjectionStrategy.CONSTRUCTOR,
nullValueMappingStrategy = NullValueMappingStrategy.RETURN_NULL, uses = {IdentifierMapper.class})
public interface HistoryMapper {
HistoryMapper MAPPER = Mappers.getMapper(HistoryMapper.class);
@Mappings({@Mapping(source = "identifier", target = "identifier", qualifiedByName = "toIdentifierDynamo"),
@Mapping(source = "method", target = "method"),
@Mapping(source = "reason", target = "reason"),
@Mapping(source = "timestamp", target = "timestamp")})
HistoryDynamo toHistoryDynamo(History history);
}
</code></pre>
<p>I would like to map History to HistoryDynamo and reuse IdentifierMapper to map one of the object in HistoryDynamo.
How can I use toIdentifierDynamo in toHistoryDynamo?</p>
| 0 | 2,146 |
Javascript object get code as string
|
<p>First off, I am sorry if this is a duplicate, but every time I googled for 'object' and 'code' I got tutorial pages.</p>
<p>I want to know if there is any easy way to get the code associated with an object. Something like</p>
<pre><code>function A(){
this.name = 'Kaiser Sauze';
}
a = new A();
console.log(a.displayCode());
//OUTPUT
"function A(){ this.name = 'Kaiser Sauze';}"
</code></pre>
<p>I want to be able to view the code, modify it and reload the function, all from within the browser. I wanted to know if there was some way to do this, or if I have to prime the pump by doing something like this:</p>
<pre><code>function A(){
this.name = 'Kaiser Sauze';
this.code = "function A(){ this.name = 'Kaiser Sauze';}"
}
</code></pre>
<p>then every time the user loads up the text editor to view <code>this.code</code> I connect the onchange to update <code>this.code</code>.</p>
<p>EDIT</p>
<p>turns out yankee suggested a simple solution to this</p>
<pre><code>function A(x){
this.x = x ;
}
console.log(A.toString());
//OUTPUT
"function A(x){
this.x = x ;
}"
</code></pre>
<p>but in my implementation the variable 'x' can be a function (actually a complicated object with variables, functions and sub objects which I mix in via a call to dojo.mixin), so what I really want is to know the code when instantiated, something like so</p>
<pre><code>function A(x){
this.x = x ;
}
var a = new A(function(){/*DO SOMETHING*/);
console.log(a.toString());
//OUTPUT
"var a = new A(function(){/*DO SOMETHING*/);"
</code></pre>
<p>but, as most of you already know, all that gets output is something like "Object". I have almost found a way around this, by putting the initialization in a function like so</p>
<pre><code>function A(x){
this.x = x ;
}
function _A(){
var a = new A(function(){/*DO SOMETHING*/);
}
console.log(_A.toString());
//OUTPUT
"function _A(){
var a = new A(function(){/*DO SOMETHING*/);
}"
</code></pre>
<p>but that is confusing, and then I have to go in and start parsing the string which I do not want to do.</p>
<p>EDIT: The reason I ask all of this is b/c I want to make code that is both dynamically executable and highly modular. I am dealing with the canvas. I want the user to be able to click on a, for example, rectangle, view its code, and modify and then load/execute it. I have a series of rules but basically I have a shape class and everything that defines that shape (color, transparency, fills, strokes...) has to get passed as a parameter to the object cosntructor, something like:</p>
<pre><code>rect = new Shape({color : 'rgba(0,0,0,1)' ,
x : 0 ,
y : 0 ,
w : 100 ,
h : 100 ,
draw : function() {ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,this.w,this.h);
}
});
</code></pre>
<p>This way the code is automatically modular, I don't have to worry about the color being defined at the top of the page, and then the height being defined half way down the page, and so on. Now the only thing I need is to somehow, pass as a parameter, the entire above string representation of the initialization. I could wrap it in a function and call toString on that, like so</p>
<pre><code>function wrapper(){
rect = new Shape({color : 'rgba(0,0,0,1)' ,
x : 0 ,
y : 0 ,
w : 100 ,
h : 100 ,
draw : function() {ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,this.w,this.h);
},
code : wrapper.toString()
});
}
</code></pre>
<p>but then there are two problems. 1) I have to manually remove the <code>function wrapper()</code> and trailing <code>}</code> as well as moving every line to the left by one tab. 2) there is no guarantee that a user will remember to include the wrapper function as it is totally unecessary for purposes of drawing. I am trying to think of a way where the wrapper would seem natural, but I can't think of any. But then again I haven't slept in over 30 hours.</p>
| 0 | 1,305 |
"Unexpected token in JSON at position 0" using JSON.parse in Node with valid JSON
|
<p>I've been tearing my hair out over this one for hours now.</p>
<p>I have a simple Node server that's making a call to an external API to get a (massive, like 4+ MB) bit of JSON. I'm using about as boilerplate a request as you can get, taken straight from the Node docs:</p>
<pre><code>const muniURL = `http://api.511.org/transit/vehiclemonitoring?api_key=${API_KEYS.API_KEY_511}&format=json&agency=sf-muni`;
http.get(muniURL, (res) => {
const statusCode = res.statusCode;
const contentType = res.headers['content-type'];
console.log('Status Code:', statusCode);
console.log('Content Type:', contentType);
let error;
if (statusCode !== 200) {
error = new Error(`Request Failed.\n` +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error(`Invalid content-type.\n` +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.log(`Request error: ${error.message}`);
// consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => rawData += chunk);
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log('parsedData:', parsedData);
} catch (e) {
console.log(`Caught error: ${e.message}`);
}
});
}).on('error', (e) => {
console.log(`Got error: ${e.message}`);
});
</code></pre>
<p>...and every single time, it hits the <code>catch</code> statement with:
<code>Caught error: Unexpected token in JSON at position 0</code>. (Note the two spaces between 'token' and 'in'.)</p>
<p>I've checked the JSON returned from both Chrome and Postman with two different web-based JSON validators, and it comes back as valid. While writing <code>rawData</code> to a file looks something like a buffer(?)...</p>
<pre><code>1fef bfbd 0800 0000 0000 0400 efbf bdef
bfbd efbf bd72 efbf bdc8 b62d efbf bd2b
0c3f 7547 1cef bfbd 00ef bfbd efbf bd0b
efbf bd5b 49ef bfbd 2def bfbd 6c6b efbf
bd5c 55ef bfbd efbf bd44 3fef bfbd 126c
71ef bfbd 021c 2029 6def bfbd 13ef bfbd
efbf bdef bfbd 437f 52ef bfbd 4227 48ef
bfbd efbf bd4d efbf bd31 13ef bfbd 09ef
bfbd 5d2f 7bef bfbd efbf bde5 aa81 745e
efbf bd65 efbf bd31 efbf bdef bfbd efbf
...
</code></pre>
<p>...<code>Buffer.isBuffer</code> comes back false.</p>
<p>Thus far I've tried <code>JSON.stringify</code>ing first, <code>toString</code>ing, converting to a <code>new Buffer</code> and then stringifying, <code>.trim</code>ing white space, and <code>replace</code>ing all sorts of escaped characters, all to no avail.</p>
<p>What am I missing here?</p>
<hr>
<p>EDIT: I realized that I was validating JSON fetched by Chrome and Postman, which apparently are doing some pre-processing of some sort. <code>curl</code>ing the URL yields a whole bunch of mess that's definitely not JSON. Still left with the questions of what data type that mess actually is, and why I'm not getting JSON when I'm specifically requesting it.</p>
| 0 | 1,174 |
How to compile C# DLL on the fly, Load, and Use
|
<p>A) compiling C# EXE's and DLL's on the fly are relatively easy.<br>
B) Executing an EXE means that a new application is run. Loading a DLL means that methods and functions can be used in cases that may be shared between applications or projects.<br>
<br>
Now, the quickest and easiest way to compile your EXE (or with mild modifications, DLL) can be found from the <a href="http://msdn.microsoft.com/en-us/library/saf5ce06%28v=vs.110%29.aspx" rel="nofollow">MSDN</a> or for your convenience:<br></p>
<pre><code>private bool CompileCSharpCode(string script)
{
lvErrors.Items.Clear();
try
{
CSharpCodeProvider provider = new CSharpCodeProvider();
// Build the parameters for source compilation.
CompilerParameters cp = new CompilerParameters
{
GenerateInMemory = false,
GenerateExecutable = false, // True = EXE, False = DLL
IncludeDebugInformation = true,
OutputAssembly = "eventHandler.dll", // Compilation name
};
// Add in our included libs.
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
cp.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll");
// Invoke compilation. This works from a string, but you can also load from a file using FromFile()
CompilerResults cr = provider.CompileAssemblyFromSource(cp, script);
if (cr.Errors.Count > 0)
{
// Display compilation errors.
foreach (CompilerError ce in cr.Errors)
{
//I have a listview to display errors.
lvErrors.Items.Add(ce.ToString());
}
return false;
}
else
{
lvErrors.Items.Add("Compiled Successfully.");
}
provider.Dispose();
}
catch (Exception e)
{
// never really reached, but better safe than sorry?
lvErrors.Items.Add("SEVERE! "+e.Message + e.StackTrace.ToString());
return false;
}
return true;
}
</code></pre>
<p>Now that you can compile on the fly, there are a few variances between how to load the DLL. Typically speaking, you would add it as a reference in Visual Studios to be compiled into the project. This is rather easy and you have probably done it many times over, but we want to use it in our current project, and we can't very well require the user to recompile the entire project every time they want to test out their new DLL. Therefor, I will simply discuss how one loads a library 'on the fly'. Another term here would by "programmatically". To do this, after a successful compile, we load up an Assembly as follows:<br></p>
<pre><code>Assembly assembly = Assembly.LoadFrom("yourfilenamehere.dll");
</code></pre>
<p>If you have an AppDomain, you can try this:<br></p>
<pre><code>Assembly assembly = domain.Load(AssemblyName.GetAssemblyName("yourfilenamehere.dll"));
</code></pre>
<p><br>
Now that the lib is "referenced", we can open it up and use it. There are 2 ways to do this. One requires you to know if the method has parameters, another will check for you. I'll do the later, you can check the <a href="http://msdn.microsoft.com/en-us/library/25y1ya39.aspx" rel="nofollow">MSDN</a> for the other.<br></p>
<pre><code>// replace with your namespace.class
Type type = assembly.GetType("company.project");
if (type != null)
{
// replace with your function's name
MethodInfo method = type.GetMethod("method");
if (method != null)
{
object result = null;
ParameterInfo[] parameters = method.GetParameters();
object classInstance = Activator.CreateInstance(type, null);
if (parameters.Length == 0) // takes no parameters
{
// method A:
result = method.Invoke(classInstance, null);
// method B:
//result = type.InvokeMember("method", BindingFlags.InvokeMethod, null, classInstance, null);
}
else // takes 1+ parameters
{
object[] parametersArray = new object[] { }; // add parameters here
// method A:
result = method.Invoke(classInstance, parametersArray);
// method B:
//result = type.InvokeMember("method", BindingFlags.InvokeMethod, null, classInstance, parametersArray);
}
}
}
</code></pre>
<p>PROBLEM:
First compile works fine. First execution works fine. However, the recompile attempt will error, saying that your *.PDP (debugger database) is in use. I've heard some hints about marshaling, and AppDomains, but I haven't quite cleared up the problem. Recompile will only fail after the DLL has been loaded.</p>
<hr>
<p>Current attempt at Marshaling && AppDomain:</p>
<pre><code>class ProxyDomain : MarshalByRefObject
{
private object _instance;
public object Instance
{
get { return _instance; }
}
private AppDomain _domain;
public AppDomain Domain
{
get
{
return _domain;
}
}
public void CreateDomain(string friendlyName, System.Security.Policy.Evidence securityinfo)
{
_domain = AppDomain.CreateDomain(friendlyName, securityinfo);
}
public void UnloadDomain()
{
try
{
AppDomain.Unload(_domain);
}
catch (ArgumentNullException dne)
{
// ignore null exceptions
return;
}
}
private Assembly _assembly;
public Assembly Assembly
{
get
{
return _assembly;
}
}
private byte[] loadFile(string filename)
{
FileStream fs = new FileStream(filename, FileMode.Open);
byte[] buffer = new byte[(int)fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
return buffer;
}
public void LoadAssembly(string path, string typeName)
{
try
{
if (_domain == null)
throw new ArgumentNullException("_domain does not exist.");
byte[] Assembly_data = loadFile(path);
byte[] Symbol_data = loadFile(path.Replace(".dll", ".pdb"));
_assembly = _domain.Load(Assembly_data, Symbol_data);
//_assembly = _domain.Load(AssemblyName.GetAssemblyName(path));
_type = _assembly.GetType(typeName);
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.ToString());
}
}
private Type _type;
public Type Type
{
get
{
return _type;
}
}
public void CreateInstanceAndUnwrap(string typeName)
{
_instance = _domain.CreateInstanceAndUnwrap(_assembly.FullName, typeName);
}
}
</code></pre>
<p>Errors on _instance = _domain.CreateInstanceAndUnwrap(_assembly.FullName, typeName); saying that my Assembly isn't serializable. Tried adding [Serializable] tag to my class with no luck. Still researching fixes.</p>
<p>Seems things can get a bit confusing when you can't see how they're being used, so here's making it easy?</p>
<pre><code>private void pictureBox1_Click(object sender, EventArgs e)
{
pd.UnloadDomain();
if (CompileCSharpCode(header + tScript.Text + footer))
{
try
{
pd.CreateDomain("DLLDomain", null);
pd.LoadAssembly("eventHandler.dll", "Events.eventHandler");
pd.CreateInstanceAndUnwrap("Events.eventHandler"); // Assembly not Serializable error!
/*if (pd.type != null)
{
MethodInfo onConnect = pd.type.GetMethod("onConnect");
if (onConnect != null)
{
object result = null;
ParameterInfo[] parameters = onConnect.GetParameters();
object classInstance = Activator.CreateInstance(pd.type, null);
if (parameters.Length == 0)
{
result = pd.type.InvokeMember("onConnect", BindingFlags.InvokeMethod, null, classInstance, null);
//result = onConnect.Invoke(classInstance, null);
}
else
{
object[] parametersArray = new object[] { };
//result = onConnect.Invoke(classInstance, parametersArray);
//result = type.InvokeMember("onConnect", BindingFlags.InvokeMethod, null, classInstance, parametersArray);
}
}
}*/
//assembly = Assembly.LoadFrom(null);
}
catch (Exception er)
{
MessageBox.Show("There was an error executing the script.\n>" + er.Message + "\n - " + er.StackTrace.ToString());
}
finally
{
}
}
}
</code></pre>
| 0 | 4,137 |
java.awt.image.DataBufferByte cannot be cast to java.awt.image.DataBufferInt
|
<p>I have some errors atm while im coding with JAVA, I have been trying to fix this for along time, also trying to find oterh ppl who have same problem and fixed it but nothing work...</p>
<p>Well.. here is the code</p>
<pre><code> package ca.vanzeben.game;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
private static final long serialVerisionUID = 1L;
public static final int WIDTH = 160;
public static final int HEIGHT = WIDTH / 12*9;
public static final int SCALE = 3;
public static final String NAME = "Game";
public boolean running = false;
public int tickCount = 0;
private JFrame frame;
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_3BYTE_BGR);
private int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
public Game(){
setMinimumSize(new Dimension(WIDTH*SCALE, HEIGHT * SCALE));
setMaximumSize(new Dimension(WIDTH*SCALE, HEIGHT * SCALE));
setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT * SCALE));
frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public synchronized void start() {
running = true;
new Thread(this).start();
}
public synchronized void stop() {
running = false;
}
public void run(){
long lastTime = System.nanoTime();
double nsPerTick = 1000000000D/60D;
int ticks = 0;
int frames = 0;
long lastTimer = System.currentTimeMillis();
double delta = 0;
while(running){
long now = System.nanoTime();
delta +=(now - lastTime) / nsPerTick;
lastTime = now;
boolean shouldRender = true;
while(delta >= 1){
ticks++;
tick();
delta -= 1;
shouldRender = true;
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (shouldRender){
frames++;
render();
}
if(System.currentTimeMillis() - lastTimer >= 1000){
lastTimer += 1000;
System.out.println(ticks + " ticks, " + frames + " frames");
frames = 0;
ticks = 0;
}
}
}
public void tick() {
tickCount++;
}
public void render(){
BufferStrategy bs = getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
g.dispose();
bs.show();
}
public static void main(String[] args) {
new Game().start();
}
}
</code></pre>
<p>And the error is: </p>
<pre><code> Exception in thread "main" java.lang.ClassCastException: java.awt.image.DataBufferByte cannot be cast to java.awt.image.DataBufferInt
at ca.vanzeben.game.Game.<init>(Game.java:30)
at ca.vanzeben.game.Game.main(Game.java:122)
</code></pre>
| 0 | 1,680 |
MyBatis doesn't return all the results from the query
|
<h1>The Problem</h1>
<p>I have a query that returns 17 records. When I use MyBatis with a map that has an <code><association></code> it returns 6 records. <em>Note that this doesn't happen with my other maps, I have many other maps with associations that all work fine.</em></p>
<p><strong>Query:</strong></p>
<pre><code> with leave_counts as
(
select leave_type_id, count(llm.leave_id) as count
from lw_leave_master llm
group by leave_type_id
)
select llt.leave_type_id, llt.leave_type_abbr_tx,
llt.leave_type_desc_tx, lc.count as count_nm
from lw_leave_type llt
join leave_counts lc on lc.leave_type_id=llt.leave_type_id
order by llt.leave_type_abbr_tx
</code></pre>
<p><strong>Map:</strong></p>
<pre><code><resultMap id="typeCountMap" type="mypackage.myclass">
<result property="count" column="count_nm"/>
<association property="type" resultMap="package.myMap"/>
</resultMap>
<resultMap id="myMap" type="mypackage.myclass2">
<result property="id" column="leave_type_id"/>
<result property="abbr" column="leave_type_abbr_tx"/>
<result property="description" column="leave_type_desc_tx"/>
</resultMap>
</code></pre>
<p>The <code><association></code> in <code>typeCountMap</code> refers to the map <code>myMap</code>.</p>
<p>This returns 6 records every time. Grabbing the actual query run from the logger and running it manually returns 17 records.</p>
<h1>Solutions?</h1>
<p><strong>There are two things I can do to get MyBatis to return all 17 records</strong></p>
<p><strong>#1</strong></p>
<p>If I remove the <code>lc.count as count_nm</code> from my query I get all 17 records returned (just with no values associated with them)</p>
<pre><code> with leave_counts as
(
select leave_type_id, count(llm.leave_id) as count
from lw_leave_master llm
group by leave_type_id
)
select llt.leave_type_id, llt.leave_type_abbr_tx,
llt.leave_type_desc_tx
from lw_leave_type llt
join leave_counts lc on lc.leave_type_id=llt.leave_type_id
order by llt.leave_type_abbr_tx
</code></pre>
<p>This is obviously not a good solution, but I wanted to include this in case it would help you figure out what I'm doing wrong.</p>
<p><strong>#2</strong></p>
<p>If I replace the association with the contents of the other map everything works as expected.</p>
<pre><code><resultMap id="typeCountMap" type="mypackage.myclass1">
<result property="count" column="count_nm"/>
<result property="type.id" column="leave_type_id"/>
<result property="type.abbr" column="leave_type_abbr_tx"/>
<result property="type.description" column="leave_type_desc_tx"/>
</resultMap>
</code></pre>
<p>This obviously is what I'll do if I don't find another solution, since this does work. It would just be nice to use the <code><association></code> like I have in other maps.</p>
<p>I should note that I am using MyBatis 3.1.1</p>
| 0 | 1,233 |
How to gray out HTML form inputs?
|
<p>What is the best way to gray out text inputs on an HTML form? I need the inputs to be grayed out when a user checks a check box. Do I have to use JavaScript for this (not very familiar with JavaScript) or can I use PHP (which I am more familiar with)?</p>
<p><strong>EDIT:</strong></p>
<p>After some reading I have got a little bit of code, but it is giving me problems. For some reason I cannot get my script to work based on the state of the form input (enabled or disabled) or the state of my checkbox (checked or unchecked), but my script works fine when I base it on the values of the form inputs. I have written my code exactly like several examples online (mainly <a href="http://www.javascriptkit.com/javatutors/deform3.shtml" rel="nofollow noreferrer">this one</a>) but to no avail. None of the stuff that is commented out will work. What am I doing wrong here?</p>
<pre><code><label>Mailing address same as residental address</label>
<input name="checkbox" onclick="disable_enable()" type="checkbox" style="width:15px"/><br/><br/>
<script type="text/javascript">
function disable_enable(){
if (document.form.mail_street_address.value==1)
document.form.mail_street_address.value=0;
//document.form.mail_street_address.disabled=true;
//document.form.mail_city.disabled=true;
//document.form.mail_state.disabled=true;
//document.form.mail_zip.disabled=true;
else
document.form.mail_street_address.value=1;
//document.form.mail_street.disabled=false;
//document.form.mail_city.disabled=false;
//document.form.mail_state.disabled=false;
//document.form.mail_zip.disabled=false;
}
</script>
</code></pre>
<p><strong>EDIT:</strong></p>
<p>Here is some updated code based upon what @Chief17 suggested. Best I can tell none of this is working. I am using <code>value</code> as a test because it works for some reason</p>
<pre><code> <label>Mailing address same as residental address</label>
<input name="checkbox" onclick="disable_enable()" type="checkbox" style="width:15px"/><br/><br/>
<script type="text/javascript">
function disable_enable(){
if (document.getElementById("mail_street_address").getAttribute("disabled")=="disabled")
document.form.mail_street_address.value=0;
//document.getElementById("mail_street_address").removeAttribute("disabled");
//document.getElementById("mail_city").removeAttribute("disabled");
//document.getElementById("mail_state").removeAttribute("disabled");
//document.getElementById("mail_zip").removeAttribute("disabled");
else
document.form.mail_street_address.value=1;
//document.getElementById("mail_street_address").setAttribute("disabled","disabled");
//document.getElementById("mail_city").setAttribute("disabled","disabled");
//document.getElementById("mail_state").setAttribute("disabled","disabled");
//document.getElementById("mail_zip").setAttribute("disabled","disabled");
}
</script>
</code></pre>
| 0 | 1,323 |
The 'compilation' argument must be an instance of Compilation
|
<p>Been getting this error when running 'ng build' on my Angular 12.0.2 project</p>
<pre><code>./src/polyfills.ts - Error: Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):
TypeError: The 'compilation' argument must be an instance of Compilation
at getCompilationHooks (D:\Dev\Git_Merc\mercury\node_modules\webpack\lib\javascript\JavascriptModulesPlugin.js:125:10)
at D:\Dev\Git_Merc\mercury\node_modules\webpack\lib\javascript\CommonJsChunkFormatPlugin.js:43:19
at Hook.eval [as call] (eval at create (D:\Dev\Git_Merc\mercury\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:7:1)
at Hook.CALL_DELEGATE [as _call] (D:\Dev\Git_Merc\mercury\node_modules\tapable\lib\Hook.js:14:14)
at Compiler.newCompilation (D:\Dev\Git_Merc\mercury\node_modules\@angular-devkit\build-angular\node_modules\webpack\lib\Compiler.js:1030:30)
at D:\Dev\Git_Merc\mercury\node_modules\@angular-devkit\build-angular\node_modules\webpack\lib\Compiler.js:1073:29
at Hook.eval [as callAsync] (eval at create (D:\Dev\Git_Merc\mercury\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:15:1)
at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (D:\Dev\Git_Merc\mercury\node_modules\tapable\lib\Hook.js:18:14)
at Compiler.compile (D:\Dev\Git_Merc\mercury\node_modules\@angular-devkit\build-angular\node_modules\webpack\lib\Compiler.js:1068:28)
at Compiler.runAsChild (D:\Dev\Git_Merc\mercury\node_modules\@angular-devkit\build-angular\node_modules\webpack\lib\Compiler.js:520:8)
</code></pre>
<p>I've been googling around but can't find anything that solves my issue. I'm not sure what's triggering this.</p>
<p>Versions:</p>
<pre><code>Angular CLI: 12.0.2
Node: 14.17.0
Package Manager: npm 7.14.0
OS: win32 x64
Angular: 12.0.1
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router
Package Version
-----------------------------------------------------------
@angular-devkit/architect 0.1200.2
@angular-devkit/build-angular 12.0.2
@angular-devkit/build-optimizer 0.1200.2
@angular-devkit/core 12.0.2
@angular-devkit/schematics 12.0.2
@angular/cli 12.0.2
@schematics/angular 12.0.2
ng-packagr 12.0.2
rxjs 7.1.0
typescript 4.2.4
webpack 5.38.0
</code></pre>
<hr />
<h2>Update 1 - adding requested information from @Heretic Monkey</h2>
<p>The command I'm running is <code>ng build</code>.</p>
<p>My <code>angular.json</code> is as follows:</p>
<pre><code>{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"Agent-Angular": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/Agent-Angular",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets",
"src/web.config"
],
"styles": [
"src/styles.scss",
"node_modules/@mercury/merc-pattern-lib/styles.scss"
],
"scripts": [
"node_modules/popper.js/dist/umd/popper.min.js"
],
"vendorChunk": true,
"extractLicenses": false,
"buildOptimizer": false,
"sourceMap": true,
"optimization": false,
"namedChunks": true
},
"configurations": {
"local": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.local.ts"
}
]
},
"nonprod": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.nonprod.ts"
}
]
},
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "Agent-Angular:build"
},
"configurations": {
"local": {
"browserTarget": "Agent-Angular:build:local"
},
"nonprod": {
"browserTarget": "Agent-Angular:build:nonprod"
},
"production": {
"browserTarget": "Agent-Angular:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "Agent-Angular:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets",
"src/web.config"
],
"styles": [
"src/styles.scss"
],
"scripts": [
"node_modules/popper.js/dist/umd/popper.min.js"
]
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"tsconfig.app.json",
"tsconfig.spec.json",
"e2e/tsconfig.json"
],
"exclude": [
"**/node_modules/**"
]
}
},
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "Agent-Angular:serve"
},
"configurations": {
"production": {
"devServerTarget": "Agent-Angular:serve:production"
}
}
}
}
},
"cee-ctilib": {
"projectType": "library",
"root": "projects/cee-ctilib",
"sourceRoot": "projects/cee-ctilib/src",
"prefix": "lib",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:ng-packagr",
"options": {
"tsConfig": "projects/cee-ctilib/tsconfig.lib.json",
"project": "projects/cee-ctilib/ng-package.json"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "projects/cee-ctilib/src/test.ts",
"tsConfig": "projects/cee-ctilib/tsconfig.spec.json",
"karmaConfig": "projects/cee-ctilib/karma.conf.js"
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"projects/cee-ctilib/tsconfig.lib.json",
"projects/cee-ctilib/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
},
"entities": {
"projectType": "library",
"root": "projects/entities",
"sourceRoot": "projects/entities/src",
"prefix": "lib",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:ng-packagr",
"options": {
"tsConfig": "projects/entities/tsconfig.lib.json",
"project": "projects/entities/ng-package.json"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "projects/entities/src/test.ts",
"tsConfig": "projects/entities/tsconfig.spec.json",
"karmaConfig": "projects/entities/karma.conf.js"
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"projects/entities/tsconfig.lib.json",
"projects/entities/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
}
},
"defaultProject": "Agent-Angular",
"cli": {
"analytics": false,
"defaultCollection": "@ngrx/schematics"
}
}
</code></pre>
<hr />
<h2>Update 2 - adding package.json</h2>
<pre><code>{
"name": "agent-angular",
"version": "0.0.0",
"description": "Mercury Chat Application",
"scripts": {
"ng": "ng",
"format:src": "prettier --config ./prettier.config.js --ignore-path ./.prettierignore --write \"src/**/*.\"{ts,js,json,scss,less,css}",
"format:projects": "prettier --config ./prettier.config.js --ignore-path ./.prettierignore --write \"projects/**/*.\"{ts,js,json,scss,less,css}",
"format:e2e": "prettier --config ./prettier.config.js --ignore-path ./.prettierignore --write \"e2e/**/*.\"{ts,js,json,scss,less,css}",
"format:root": "prettier --config ./prettier.config.js --ignore-path ./.prettierignore --write \"*.\"{ts,js,json,scss,less,css}",
"format:all": "npm run format:src && npm run format:projects && npm run format:e2e && npm run format:root",
"lint": "ng lint",
"e2e": "ng e2e",
"start": "npm run && ng serve --prod",
"build": "npm run && ng build --prod --base-href=./",
"build:dev": "npm run && ng build",
"unit:test": "ng test",
"unit:test:main": "ng test Agent-Angular --code-coverage",
"unit:test:entities": "ng test entities --code-coverage",
"unit:test:cee-ctilib": "ng test cee-ctilib --code-coverage",
"unit:test:debug": "ng test --browsers Chrome --watch true",
"unit:test:entities:debug": "ng test entities --browsers Chrome --watch true",
"start:local": "ng serve -c local --host local.mercury.comcast.net --port 443 --ssl --ssl-key ./cert/local.mercury.comcast.net.key --ssl-cert ./cert/local.mercury.comcast.net.crt",
"start:dev": "ng serve -c dev --host dev.mercury.comcast.net --port 443 --ssl --ssl-key ./cert/localhost.key --ssl-cert ./cert/localhost.crt",
"build:cti": "ng-packagr -p ./projects/cee-ctilib/ng-package.json && cd ./dist && npm pack ./cee-ctilib",
"build:header": "ng-packagr -p ./projects/header/ng-package.json && cd ./dist && npm pack ./header",
"build:convo-header": "ng-packagr -p ./projects/convo-header/ng-package.json && cd ./dist && npm pack ./convo-header",
"build:convo-details": "ng-packagr -p ./projects/convo-details/ng-package.json && cd ./dist && npm pack ./convo-details",
"build:convo-list": "ng-packagr -p ./projects/convo-list/ng-package.json && cd ./dist && npm pack ./convo-list",
"build:convo-window": "ng-packagr -p ./projects/convo-window/ng-package.json && cd ./dist && npm pack ./convo-window",
"build:agent-settings": "ng-packagr -p ./projects/agent-settings/ng-package.json && cd ./dist && npm pack ./agent-settings",
"build:entities": "ng-packagr -p ./projects/entities/ng-package.json && cd ./dist && npm pack ./entities",
"build:all-libraries": "npm run build:cti && npm run build:header && npm run build:convo-header && npm run build:convo-details && npm run build:convo-list && npm run build:convo-window && npm run build:agent-settings && npm run build:entities",
"refreshNpmrc": "vsts-npm-auth -config .npmrc",
"prepareForPr": "ng lint --fix && ng build --prod && ng test"
},
"private": false,
"dependencies": {
"@angular/animations": "12.0.1",
"@angular/common": "12.0.1",
"@angular/compiler": "12.0.1",
"@angular/core": "12.0.1",
"@angular/forms": "12.0.1",
"@angular/platform-browser": "12.0.1",
"@angular/platform-browser-dynamic": "12.0.1",
"@angular/router": "12.0.1",
"@auth0/angular-jwt": "^5.0.2",
"@azure/msal-angular": "^2.0.0-beta.1",
"@azure/msal-browser": "^2.12.1",
"@ctrl/ngx-emoji-mart": "^5.1.0",
"@jsier/retrier": "^1.2.4",
"@mercury/merc-ng-core": "^5.1.0",
"@mercury/merc-pattern-lib": "^2.11.0",
"@microsoft/applicationinsights-web": "^2.5.11",
"@microsoft/signalr": "^5.0.6",
"@ngrx/effects": "^12.0.0",
"@ngrx/entity": "^12.0.0",
"@ngrx/store": "^12.0.0",
"angular-oauth2-oidc": "^10.0.3",
"dayjs": "^1.10.4",
"guid-typescript": "^1.0.9",
"ngx-quill": "^13.2.0",
"npm": "^6.14.11",
"popper": "^1.0.1",
"popper.js": "1.16.0",
"quill": "^1.3.7",
"quill-placeholder-module": "^0.3.1",
"rxjs": "^7.0.1",
"ts-retry": "^2.3.1",
"tslib": "^2.2.0",
"vsts-npm-auth": "^0.41.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "^12.0.0",
"@angular-devkit/build-optimizer": "^0.1200.0",
"@angular/cli": "^12.0.1",
"@angular/compiler-cli": "12.0.1",
"@angular/language-service": "12.0.1",
"@ngrx/schematics": "^12.0.0",
"@ngrx/store-devtools": "^12.0.0",
"@types/deep-freeze": "^0.1.2",
"@types/jasmine": "~3.6.0",
"@types/jasminewd2": "2.0.8",
"@types/node": "^12.11.1",
"codelyzer": "^6.0.0",
"deep-freeze": "^0.0.1",
"jasmine-core": "~3.7.1",
"jasmine-json-test-reporter": "1.0.0-beta",
"jasmine-marbles": "0.6.0",
"jasmine-spec-reporter": "~5.0.0",
"karma": "^6.3.2",
"karma-chrome-launcher": "^3.1.0",
"karma-cli": "^2.0.0",
"karma-coverage-istanbul-reporter": "^3.0.3",
"karma-htmlfile-reporter": "^0.3.8",
"karma-jasmine": "^4.0.1",
"karma-jasmine-html-reporter": "^1.6.0",
"karma-json-reporter": "^1.2.1",
"karma-typescript-es6-transform": "^5.5.1",
"karma-webpack": "^5.0.0",
"mockdate": "^3.0.5",
"ng-packagr": "^12.0.0",
"prettier": "1.18.2",
"protractor": "~7.0.0",
"protractor-jasmine2-html-reporter": "0.0.7",
"rxjs-marbles": "^7.0.0",
"ts-node": "8.4.1",
"tslint": "^6.1.3",
"typescript": "4.2.4",
"webpack": "^5.37.1"
},
"author": "Mercury Team",
"license": ""
}
</code></pre>
| 0 | 11,225 |
Crash : terminate called after throwing an instance of 'std::system_error' what(): Resource deadlock avoided
|
<p>I have a simple client /server application the code of which is mentioned below.
Please run the server in one shell and the client in another shell in linux.
First start the server and then the client.
When the server is done with it's work, it crashes with following exception:</p>
<p><em>terminate called after throwing an instance of 'std::system_error'
what(): Resource deadlock avoided</em></p>
<p>This happens from the line m_thread->join() from inside the function Service::HandleClient
I have no clue on what's going on.. Can someone please check the code.. I just want that the server application should also get closed correctly the way the client application got closed.</p>
<p>**Server Code : **</p>
<pre><code>#include <boost/asio.hpp>
#include <thread>
#include <atomic>
#include <memory>
#include <iostream>
using namespace boost;
class Service {
public:
Service(){}
void StartHandligClient(
std::shared_ptr<asio::ip::tcp::socket> sock) {
m_thread.reset(new std::thread (([this, sock]() {
HandleClient(sock);
})) );
}
private:
void HandleClient(std::shared_ptr<asio::ip::tcp::socket> sock) {
while(1)
{
try {
asio::streambuf request;
std::cout << "Waiting to read \n";
asio::read_until(*sock.get(), request, '\n');
std::string s( (std::istreambuf_iterator<char>(&request)), std::istreambuf_iterator<char>() );
std::cout << "Server got : " << s << "\n";
// Emulate request processing.
int i = 0;
while (i != 1000000)
i++;
std::this_thread::sleep_for(
std::chrono::milliseconds(500));
// Sending response.
std::string response = "Response\n";
asio::write(*sock.get(), asio::buffer(response));
}
catch (system::system_error &e) {
boost::system::error_code ec = e.code();
if(ec == asio::error::eof)
{
std::cout << "Breaking loop \n";
break;
}
std::cout << "Error occured! Error code = "
<< e.code() << ". Message: "
<< e.what();
}
}
m_thread->join();
// Clean-up.
delete this;
}
std::unique_ptr<std::thread> m_thread;
};
class Acceptor {
public:
Acceptor(asio::io_service& ios, unsigned short port_num) :
m_ios(ios),
m_acceptor(m_ios,
asio::ip::tcp::endpoint(
asio::ip::address_v4::any(),
port_num))
{
m_acceptor.listen();
}
void Accept() {
std::cout << "Server Accept() \n" << std::flush;
std::shared_ptr<asio::ip::tcp::socket>
sock(new asio::ip::tcp::socket(m_ios));
std::cout << "BEFORE calling acceptor's accept function \n" << std::flush;
m_acceptor.accept(*sock.get());
std::cout << "AFTER calling acceptor's accept function \n" << std::flush;
(new Service)->StartHandligClient(sock);
}
void close()
{
std::cout << "Inside Acceptor.close() \n" << std::flush;
m_acceptor.close();
}
private:
asio::io_service& m_ios;
asio::ip::tcp::acceptor m_acceptor;
};
class Server {
public:
Server() : m_stop(false) {}
void Start(unsigned short port_num) {
m_thread.reset(new std::thread([this, port_num]() {
Run(port_num);
}));
}
void Stop() {
m_stop.store(true);
m_thread->join();
}
private:
void Run(unsigned short port_num) {
Acceptor acc(m_ios, port_num);
while (!m_stop.load()) {
std::cout << "Server accept\n" << std::flush;
acc.Accept();
}
acc.close();
}
std::unique_ptr<std::thread> m_thread;
std::atomic<bool> m_stop;
asio::io_service m_ios;
};
int main()
{
unsigned short port_num = 3333;
try {
Server srv;
srv.Start(port_num);
std::this_thread::sleep_for(std::chrono::seconds(4));
srv.Stop();
}
catch (system::system_error &e) {
std::cout << "Error occured! Error code = "
<< e.code() << ". Message: "
<< e.what();
}
return 0;
}
</code></pre>
<p>**Client Code : **</p>
<pre><code>#include <boost/asio.hpp>
#include <iostream>
using namespace boost;
class SyncTCPClient {
public:
SyncTCPClient(const std::string& raw_ip_address,
unsigned short port_num) :
m_ep(asio::ip::address::from_string(raw_ip_address),
port_num),
m_sock(m_ios) {
m_sock.open(m_ep.protocol());
}
void connect() {
m_sock.connect(m_ep);
}
void close() {
m_sock.shutdown(
boost::asio::ip::tcp::socket::shutdown_both);
m_sock.close();
}
std::string emulateLongComputationOp(
unsigned int duration_sec) {
std::string request = "EMULATE_LONG_COMP_OP "
+ std::to_string(duration_sec)
+ "\n";
sendRequest(request);
return receiveResponse();
};
private:
void sendRequest(const std::string& request)
{
std::cout << "Inside sendRequest : " << request << "\n";
asio::write(m_sock, asio::buffer(request));
}
std::string receiveResponse() {
asio::streambuf buf;
asio::read_until(m_sock, buf, '\n');
std::istream input(&buf);
std::string response;
std::getline(input, response);
return response;
}
private:
asio::io_service m_ios;
asio::ip::tcp::endpoint m_ep;
asio::ip::tcp::socket m_sock;
};
int main()
{
const std::string raw_ip_address = "127.0.0.1";
const unsigned short port_num = 3333;
try {
SyncTCPClient client(raw_ip_address, port_num);
// Sync connect.
client.connect();
std::cout << "Sending request to the server... " << std::endl;
std::string response = client.emulateLongComputationOp(10);
std::cout << "Response received: " << response << std::endl;
sleep(2);
// Close the connection and free resources.
client.close();
}
catch (system::system_error &e) {
std::cout << "Error occured! Error code = " << e.code()
<< ". Message: " << e.what();
return e.code().value();
}
return 0;
}
</code></pre>
| 0 | 3,347 |
Creating a custom Jasypt PropertySource in Springboot
|
<p>I'm using Spring Boot to create a simple web application which accesses a database. I'm taking advantage of the autoconfiguration functionality for the DataSource by setting up <code>spring.datasource.*</code> properties in <code>application.properties</code>. That all works brilliantly and was very quick - great work guys @ Spring! </p>
<p>My companys policy is that there should be no clear text passwords. Therefore I need to have the <code>sping.datasource.password</code> encrypted. After a bit of digging around I decided to create a <code>org.springframework.boot.env.PropertySourceLoader</code> implementation which creates a jasypt <code>org.jasypt.spring31.properties.EncryptablePropertiesPropertySource</code> as follows:</p>
<pre><code>public class EncryptedPropertySourceLoader implements PropertySourceLoader
{
private final StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
public EncryptedPropertySourceLoader()
{
//TODO: this could be taken from an environment variable
this.encryptor.setPassword("password");
}
@Override
public String[] getFileExtensions()
{
return new String[]{"properties"};
}
@Override
public PropertySource<?> load(final String name, final Resource resource, final String profile) throws IOException
{
if (profile == null)
{
final Properties props = PropertiesLoaderUtils.loadProperties(resource);
if (!props.isEmpty())
{
return new EncryptablePropertiesPropertySource(name, props, this.encryptor);
}
}
return null;
}
}
</code></pre>
<p>I then packaged this in it's own jar with a <code>META-INF/spring.factories</code> file as follows:</p>
<pre><code>org.springframework.boot.env.PropertySourceLoader=com.mycompany.spring.boot.env.EncryptedPropertySourceLoader
</code></pre>
<p>This works perfectly when run from maven using <code>mvn spring-boot:run</code>. The problem occurs when I run it as a standalone war using <code>java -jar my-app.war</code>. The application still loads but fails when I try to connect to the database as the password value is still encrypted. Adding logging reveals that the <code>EncryptedPropertySourceLoader</code> is never loaded. </p>
<p>To me this sounds like a classpath issue. When run under maven the jar loading order is strict but once under the embebed tomcat there is nothing to say that my custom jar should be loaded before Spring Boot.</p>
<p>I've tried adding the following to my pom.xml to ensure the classpth is preserved but it doesn't seem to have had any effect.</p>
<pre><code><build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<archive>
<manifest>
<mainClass>${start-class}</mainClass>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</code></pre>
<p>Does anyone have any ideas? Thanks in advance.</p>
<p><b>UPDATE:</b></p>
<p>A step forward: I've managed to fix this by having the <code>EncryptedPropertySourceLoader</code> class implement <code>org.springframework.core.PriorityOrdered</code> interface and returning <code>HIGHEST_PRECEDENCE</code> from <code>getOrder()</code>. This has now fixed the issue of the PropertySourceLoader not being used. However it's now throwing the following error when it tries to decrypt the properties:</p>
<pre><code>org.jasypt.exceptions.EncryptionInitializationException: java.security.NoSuchAlgorithmException: PBEWithMD5AndDES SecretKeyFactory not available
at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.initialize(StandardPBEByteEncryptor.java:716)
at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.initialize(StandardPBEStringEncryptor.java:553)
at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.decrypt(StandardPBEStringEncryptor.java:705)
at org.jasypt.properties.PropertyValueEncryptionUtils.decrypt(PropertyValueEncryptionUtils.java:72)
at org.jasypt.properties.EncryptableProperties.decode(EncryptableProperties.java:230)
at org.jasypt.properties.EncryptableProperties.get(EncryptableProperties.java:209)
at org.springframework.core.env.MapPropertySource.getProperty(MapPropertySource.java:36)
at org.springframework.boot.env.EnumerableCompositePropertySource.getProperty(EnumerableCompositePropertySource.java:49)
at org.springframework.boot.context.config.ConfigFileApplicationListener$ConfigurationPropertySources.getProperty(ConfigFileApplicationListener.java:490)
</code></pre>
<p>Again this doesn't happen when running from <code>mvn spring-boot:run</code> but does happen when running from the executable war file. Both scenarios use the same JVM (jdk1.6.0_35). Results on Google/Stackoverflow suggest this is an issue with the java security policy but as it does work when run from maven I think I can discount that. Possibly a packaging issue...</p>
| 0 | 2,082 |
How to forcefully set IE's Compatibility Mode off from the server-side?
|
<p>In a domain-controlled environment I'm finding that the compatibility mode is triggered on certain clients (winXP/Win7, IE8/IE9) even when we are providing a X-UA tags, a !DOCTYPE definition and "IE=Edge" response headers. These clients have the "display intranet sites in compatibility view" checkbox ticked. Which is precisely what I'm trying to override.</p>
<p>The following is the documentation that I've used to try understand how IE decides to actually trigger the compatibility mode.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ff406036%28v=VS.85%29.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ff406036%28v=VS.85%29.aspx</a></p>
<p><a href="http://blogs.msdn.com/b/ie/archive/2009/02/16/just-the-facts-recap-of-compatibility-view.aspx" rel="noreferrer">http://blogs.msdn.com/b/ie/archive/2009/02/16/just-the-facts-recap-of-compatibility-view.aspx</a></p>
<blockquote>
<p><b>Site owners are <em>always</em> in control of their content.</b> Site owners can choose to use the X-UA-Compatible tag to be absolutely declarative about how they’d like their site to display and to map Standards mode pages to IE7 Standards. <em>Use of the X-UA-Compatible tag overrides Compatibility View on the client.</em></p>
</blockquote>
<p>Google for <strong>"Defining Document Compatibility"</strong>, sadly the SPAM engine doesn't let me post more than 2 urls.</p>
<p>This is an <code>ASP .NET</code> web app and includes the following definitions on the master page:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
</head>
</code></pre>
<p>and <code>web.config</code></p>
<pre><code><system.webServer>
<httpProtocol>
<customHeaders>
<clear />
<add name="X-UA-Compatible" value="IE=Edge" />
</customHeaders>
</httpProtocol>
</system.webServer>
</code></pre>
<p>I've used Fiddler to check that the header is indeed being injected correctly.</p>
<p>My understanding is that with these settings I should be able override the "Display intranet sites in Compatibility View" browser setting. But depending on the client I've found that some of them will still trigger compatibility mode.
It also seems to be down to the machine level rather a policy group setting, since I obtain different results even when I use with the same set of credentials on different clients.</p>
<p>Disabling the Compatibility View Settings checkbox does the trick. But the actual purpose is to make sure that the app is rendered exactly the same way regardless of the client settings.</p>
<p>Any thoughts and what I could be possibly missing? Is it possible at all to force IE to always render the pages without triggering Compat mode? </p>
<p>thanks a million,</p>
<p>Jaume</p>
<p><strong>PS:</strong> the site is currently in development and is of course not in Microsoft's compatibility list, but I've also checked just in case.</p>
<p>Google for <strong>"Understanding the Compatibility View List"</strong>, sadly the SPAM engine doesn't let me post more than 2 urls.</p>
| 0 | 1,038 |
Java - IndexOutOfBoundsException: Index: 1, Size: 0
|
<pre><code>public static boolean play123(ArrayList<Card>list){
boolean win=false;
int round=1;
for(int i = 0;i<=list.size();i++){
Deck.handOutNextCard(list);
if(list.get(i)==Card.AceClub ||list.get(i)== Card.AceDiamond ||list.get(i)== Card.AceHeart ||list.get(i)== Card.AceSpade){
if(round==1){
System.out.println("You loose! " +list.get(i)+"From round: "+round);
i = list.size()+1;
win = false;
}
}
else if(list.get(i)==Card.TwoClub ||list.get(i)== Card.TwoDiamond ||list.get(i)== Card.TwoHeart ||list.get(i)== Card.TwoSpade){
if(round==2){
System.out.println("You loose! " + list.get(i)+"From round: " +round);
i = list.size()+1;
win = false;
}
}else if(list.get(i)==Card.ThreeClub ||list.get(i)== Card.ThreeDiamond ||list.get(i)== Card.ThreeHeart ||list.get(i)== Card.ThreeSpade){
if(round==3){
System.out.println("You loose! " + list.get(i)+"From round: " +round);
i = list.size()+1;
win=false;
}
}else{
if(round<3){
list.remove(0);
i=0;
round++;
}else{
list.remove(0);
i=0;
round=1;
}
}
if(list.isEmpty()){
System.out.println("You win ! ");
win = true;
}
}
return win;
}
</code></pre>
<p>I got sometimes IndexOutOfBoundsException: Index: 1, Size: 0 error when using the method for example about 100 times, what could be the problem ://
I have tried to fix it through using different loop types but it was not possible, and the index and the size are different sometimes, and this is the handOutNextCard(list) method:
public static Card handOutNextCard(ArrayListlist){</p>
<pre><code> Card current = list.get(0);
list.remove(0);
return current;
}
</code></pre>
| 0 | 1,025 |
Conversion failed when converting datetime from character string
|
<p>I am developing a C# VS 2008 / SQL Server 2005 Express website application. I have tried some of the fixes for this problem but my call stack differs from others. And these fixes did not fix my problem. What steps can I take to troubleshoot this?</p>
<p>Here is my error:</p>
<pre><code>System.Data.SqlClient.SqlException was caught
Message="Conversion failed when converting datetime from character string."
Source=".Net SqlClient Data Provider"
ErrorCode=-2146232060
LineNumber=10
Number=241
Procedure="AppendDataCT"
Server="\\\\.\\pipe\\772EF469-84F1-43\\tsql\\query"
State=1
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at ADONET_namespace.ADONET_methods.AppendDataCT(DataTable dt, Dictionary`2 dic) in c:\Documents and Settings\Admin\My Documents\Visual Studio 2008\WebSites\Jerry\App_Code\ADONET methods.cs:line 102
</code></pre>
<p>And here is the related code. When I debugged this code, "dic" only looped through the 3 column names, but did not look into row values which are stored in "dt", the Data Table.</p>
<pre><code>public static string AppendDataCT(DataTable dt, Dictionary<string, string> dic)
{
if (dic.Count != 3)
throw new ArgumentOutOfRangeException("dic can only have 3 parameters");
string connString = ConfigurationManager.ConnectionStrings["AW3_string"].ConnectionString;
string errorMsg;
try
{
using (SqlConnection conn2 = new SqlConnection(connString))
{
using (SqlCommand cmd = conn2.CreateCommand())
{
cmd.CommandText = "dbo.AppendDataCT";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn2;
foreach (string s in dic.Keys)
{
SqlParameter p = cmd.Parameters.AddWithValue(s, dic[s]);
p.SqlDbType = SqlDbType.VarChar;
}
conn2.Open();
cmd.ExecuteNonQuery();
conn2.Close();
errorMsg = "The Person.ContactType table was successfully updated!";
}
}
}
</code></pre>
<p>Here is my SQL stored proc:</p>
<pre><code>ALTER PROCEDURE [dbo].[AppendDataCT]
@col1 VARCHAR(50),
@col2 VARCHAR(50),
@col3 VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @TEMP DATETIME
SET @TEMP = (SELECT CONVERT (DATETIME, @col3))
INSERT INTO Person.ContactType (Name, ModifiedDate)
VALUES( @col2, @TEMP)
END
</code></pre>
<p>The input file has 3 columns. The first two are varchars, but the 3rd one is also varchar I think, but it's represented as "3/11/2010". In this input file, a sample row looks like:
"Benjamin|breakfast|3/11/2010".
And I am trying to convert this date field from a string to a datetime here in my SP. Am I going about it the wrong way? </p>
<p>DataRow:
col1|col2|col3
11|A2|1/10/1978
12|b2|2/10/1978
13|c2|3/10/1978
14|d2|4/10/1978</p>
| 0 | 1,563 |
how to get row values when checkbox is checked in gridview
|
<p>before I asked this I did some checking around to make sure that this doesn't turn out to be a duplicate and ways to get the row values from a row that has a checkbox in its template field...but I can't seem to get it working...So far I have tried</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
Entities NW = new Entities();
var customers =
from c in NW.Customers
where (c.ContactName.StartsWith("Ma") || c.ContactName.StartsWith("An")
|| c.ContactName.StartsWith("T")
|| c.ContactName.StartsWith("V")
)
orderby c.ContactName ascending
select new
{
c.CustomerID,
c.ContactName,
c.CompanyName,
c.City
};
gv1.DataSource = customers.ToList();
gv1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gv1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("CB") as CheckBox);
if (chkRow.Checked)
{
Label1.Text = row.Cells[2].Text;
}
}
}
}
</code></pre>
<p>I have stepped through the button click event and when it gets to </p>
<blockquote>
<p>if (chkRow.Checked)</p>
</blockquote>
<p>its showing as null and skips over it..</p>
<p>my markup is </p>
<pre><code><asp:GridView ID="gv1" runat="server">
<HeaderStyle BackColor="SkyBlue" />
<AlternatingRowStyle BackColor="Yellow" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CB" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</code></pre>
<p>when I look at the source after I run, the checkboxes are all named differently than what I gave them the ID of "CB", attached is the pic of the source when its running</p>
<p><img src="https://i.stack.imgur.com/MaiWI.png" alt="Source when ran"></p>
<p>I am not sure what I am doing wrong with this</p>
| 0 | 1,163 |
NgIf not updating when variable changes
|
<p>Right, so i have a header component (navbar) which contains the following template:</p>
<pre><code><ng-template [ngIf] = "authService.isAuthenticated()">
<li>
<a routerLink="Landing" class="navbar-brand" (click)="Logout()"><span class="xvrfont">Logout</span><i class="fa fa-sign-in" aria-hidden="true"></i></a>
</li>
<li>
<a routerLink="Profile" class="navbar-brand"><span class="xvrfont">{{authService.getUsername()}}</span><i class="fa fa-user-circle" aria-hidden="true"></i></a>
</li>
</ng-template>
</code></pre>
<p>This part of the nav should be visible when the user is authenticated. to find out it checks via authService.</p>
<p>To check if a user is authenticated, the following code is ran on every route change:</p>
<pre><code>checkAuthenticated(){
if (localStorage.getItem('token') != null){ this.authenticated = true; }
else { this.authenticated = false; }
console.log(this.authenticated); // for Debugging.
}
</code></pre>
<p>The NgIf statement calls this method: </p>
<pre><code>public isAuthenticated(){
return this.authenticated;
}
</code></pre>
<p>According to the logs, 'authenticated' <strong>is</strong> changing between true and false correctly, but the Ngif isn't responding to the changes somehow.</p>
<p>the header component.ts looks like this: </p>
<pre><code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import {AuthService} from "../auth/auth.service";
@Component({
selector: 'app-header',
providers: [AuthService],
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
encapsulation: ViewEncapsulation.None
})
export class HeaderComponent implements OnInit {
constructor(private authService: AuthService) { }
ngOnInit() {
}
Logout(){
this.authService.Logout();
}
}
</code></pre>
<p>Any help would be appreciated. Thanks.</p>
<p><strong>Edit:</strong></p>
<p>auth.service.ts:</p>
<pre><code>import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Router} from "@angular/router";
import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
public apiroot = 'http://localhost:3100/';
public loginResponseMessage = '';
public registerResponseMessage = '';
public authenticated = false;
public constructor(private http: HttpClient,
private router: Router) {
}
SignUp(username: string, password: string) {
const User = JSON.stringify({username: username, password: password});
let response: any;
this.http.post(this.apiroot + 'register', User, {headers: new HttpHeaders()
.set('content-type', 'application/json; charset=utf-8')})
.subscribe(res => {
response = res;
this.registerResponseMessage = response.message;
console.log(this.registerResponseMessage);
});
}
Login(username: string, password: string) {
const User = JSON.stringify({username: username, password: password});
let response: any;
this.http.post(this.apiroot + 'authenticate', User, {headers: new HttpHeaders()
.set('content-type', 'application/json; charset=utf-8')})
.subscribe(res => {
response = res;
this.loginResponseMessage = response.message;
if (response.token) {
localStorage.setItem('token', response.token);
this.authenticated = true;
localStorage.setItem('user', response.username);
this.router.navigate(['/']);
}
else{ /* Do Nothing */ }
});
}
Logout(): void{
this.authenticated = false;
localStorage.removeItem('token');
console.log(this.isAuthenticated());
this.router.navigate(['/Landing']);
}
isAuthenticated(){
return this.authenticated;
}
checkAuthenticated(){
if (localStorage.getItem('token') != null){ this.authenticated = true; }
else { this.authenticated = false; }
console.log(this.authenticated); // for Debugging.
}
getUsername(){
var result = localStorage.getItem('user');
return result;
}
}
</code></pre>
| 0 | 1,556 |
Login form and Registration form without using database
|
<p>My Instructor gave me and my classmates some three activities and of those activities is to make a simple login form with a registration form without using database (well its obvious that we need to do this activity before proceeding with database).....</p>
<p>Here is the codes:
Form1:</p>
<pre><code> public partial class Form1 : Form
{
string Username;
string Password;
string NAME;
string Age;
Form2 Frm = new Form2();
//Here is where you get the value of the String from Form2
public void PassValue(string strValue)
{
Username = strValue;
}
public void PassAnotherValue(string strValue2)
{
Password = strValue2;
}
public void PassAnotherValueAgain(string strValue3)
{
NAME = strValue3;
}
public void PassAnotherValueAgainAndAgain(string strvalue4)
{
Age = strvalue4;
}
//------------------------------------------------------------------
public Form1()
{
InitializeComponent();
}
private void LoginBtn_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(LoginUserNameTB.Text))
{
MessageBox.Show("Please input proper Username...!");
}
if (string.IsNullOrWhiteSpace(LoginPasswordTB.Text))
{
MessageBox.Show("Please input proper Password...!");
}
else if ((LoginUserNameTB.Text != Username) && (LoginPasswordTB.Text != Password))
{
MessageBox.Show("Welcome" + NAME + "!");
}
else if ((LoginUserNameTB.Text == Username) && (LoginPasswordTB.Text == Password))
{
MessageBox.Show("Please input proper Username and/or Password...!");
}
}
private void RegisterBtn1_Click(object sender, EventArgs e)
{
Frm.Show();
}
}
}
</code></pre>
<p>Form2:</p>
<pre><code>//Form2 has four textboxes, four labels, and a button
private void RegisterBtn2_Click(object sender, EventArgs e)
{
Form1 obj1 = new Form1();
Form1 obj2 = new Form1();
Form1 obj3 = new Form1();
Form1 obj4 = new Form1();
Form1 obj5 = new Form1();
//This is where you pass the String value back to Form1
obj1.PassValue(RegUserNameTB.Text);
obj2.PassAnotherValue(RegPasswordTB.Text);
obj3.PassAnotherValueAgain(NTB.Text);
obj4.PassAnotherValueAgainAndAgain(ATB.Text);
if (string.IsNullOrWhiteSpace(NTB.Text) && string.IsNullOrWhiteSpace(ATB.Text) && string.IsNullOrWhiteSpace(RegUserNameTB.Text) && string.IsNullOrWhiteSpace(RegPasswordTB.Text))
{
MessageBox.Show("Please enter the following:" + "\n" + "Name" + "\n" + "Age" + "\n" + "\n" + "UserName" + "\n" + "Password");
}
Close();
}
}
}
</code></pre>
<p>Now to the problem of this program.....
The program is working just fine and every time I enter a Username and a Password it worked but the value of the 'NAME' is missing and every time I clicked the Register Button it will only perform its action once and never again (probably needs an Exception).... And to sum it up our Instructor told us that the user will have a limit of 3 of entering its username and password and after that the program will close.... Any ideas?</p>
| 0 | 1,676 |
Why do I get an InstantiationException if I try to start a service?
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/5027147/android-runtimeexception-unable-to-instantiate-the-service">Android RuntimeException: Unable to instantiate the service</a> </p>
</blockquote>
<p>I have been trying to fix the following problem all day but nothing seems to work.</p>
<p>I have a widget which gets it's views updated via an IntentService. But i keep getting an InstantiationException when trying to start this service. Below is the stack trace of the error and the code i use to launch the service. I don't believe i need to post the code of the service as it is never even started, but if someone thinks otherwise i will of course do so. </p>
<p><strong>STACKTRACE</strong></p>
<pre><code>05-30 13:58:47.150: ERROR/AndroidRuntime(1163): FATAL EXCEPTION: main
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): java.lang.RuntimeException: Unable to instantiate service syrligt.cashtrack.widgets.StatisticsWidgetUpdateService: java.lang.InstantiationException: syrligt.cashtrack.widgets.StatisticsWidgetUpdateService
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): at android.app.ActivityThread.handleCreateService(ActivityThread.java:1904)
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): at android.app.ActivityThread.access$2500(ActivityThread.java:117)
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:982)
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): at android.os.Handler.dispatchMessage(Handler.java:99)
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): at android.os.Looper.loop(Looper.java:123)
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): at android.app.ActivityThread.main(ActivityThread.java:3647)
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): at java.lang.reflect.Method.invokeNative(Native Method)
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): at java.lang.reflect.Method.invoke(Method.java:507)
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): at dalvik.system.NativeStart.main(Native Method)
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): Caused by: java.lang.InstantiationException: syrligt.cashtrack.widgets.StatisticsWidgetUpdateService
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): at java.lang.Class.newInstanceImpl(Native Method)
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): at java.lang.Class.newInstance(Class.java:1409)
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): at android.app.ActivityThread.handleCreateService(ActivityThread.java:1901)
05-30 13:58:47.150: ERROR/AndroidRuntime(1163): ... 10 more
</code></pre>
<p><strong>WIDGET CODE</strong></p>
<pre><code> public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for(int i = 0; i<appWidgetIds.length ; i++){
Intent intent = new Intent(context,StatisticsWidgetUpdateService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
context.startService(intent);
}
}
</code></pre>
<p><strong>SERVICE CODE</strong></p>
<pre><code>public class StatisticsWidgetUpdateService extends IntentService {
public StatisticsWidgetUpdateService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
AppWidgetManager appWidgetManager=AppWidgetManager.getInstance(this);
int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID);
CashDB cdb = new CashDB(this);
cdb.open();
RemoteViews updatedViews = new RemoteViews(getPackageName(), R.layout.statistics_widget);
updatedViews.removeAllViews(R.id.list);
PendingIntent pendingIntent = null;
Cursor c = null;
Intent i = null;
SharedPreferences sp = getSharedPreferences(Preferences.PREFERENCES, 0);
double incomeAmount = cdb.sumTransactions(null, new TimeFrame(sp.getInt(Preferences.DEFAULT_TIME_FRAME, TimeFrame.ALL_TIME)), 1);
double expenseAmount = Math.abs(cdb.sumTransactions(null, new TimeFrame(sp.getInt(Preferences.DEFAULT_TIME_FRAME, TimeFrame.ALL_TIME)), -1));
int value = StatisticsWidgetConfig.getConfig(this, appWidgetId);
c = cdb.fetchCategoriesWithSums(new TimeFrame(sp.getInt(Preferences.DEFAULT_TIME_FRAME, TimeFrame.ALL_TIME)), value, 3);
updatedViews.setTextViewText(R.id.balance, StringConversion.formatAmount(incomeAmount - expenseAmount));//balance text
updatedViews.setViewVisibility(R.id.value_bar, incomeAmount - expenseAmount < 0 ? R.drawable.list_item_value_red_medium : R.drawable.list_item_value_green_medium);//value bar
updatedViews.setTextViewText(R.id.income, StringConversion.formatAmount(incomeAmount));//income text
updatedViews.setTextViewText(R.id.expense, StringConversion.formatAmount(expenseAmount));//expense text
updatedViews.setTextViewText(R.id.popularity, Integer.toString(cdb.fetchAllTransactions(new TimeFrame(sp.getInt(Preferences.DEFAULT_TIME_FRAME, TimeFrame.ALL_TIME)), null, null,null).getCount()));//popularity text
for(int j = 0; j<c.getCount();j++){
c.moveToPosition(j);
RemoteViews statisticsView = new RemoteViews(getPackageName(), R.layout.statistics_widget_list);
statisticsView.setTextViewText(R.id.name, c.getString(c.getColumnIndexOrThrow(CashDB.CATEGORY_NAME)));//category name
statisticsView.setImageViewResource(R.id.icon, c.getInt(c.getColumnIndexOrThrow(CashDB.CATEGORY_IMAGE)));//category icon
statisticsView.setViewVisibility(R.id.starred, c.getInt(c.getColumnIndexOrThrow(CashDB.CATEGORY_STARRED)) == 1 ? View.VISIBLE : View.GONE);//starred icon
double procent = c.getLong(c.getColumnIndexOrThrow(CashDB.TRANSACTION_SUM));
procent = procent/(value == -1 ? expenseAmount : incomeAmount);
procent = Math.abs(procent * 100);
if((procent%1) < 0.1){
statisticsView.setTextViewText( R.id.procent, String.format("%.0f%s",procent," %"));//procentage
}else{
statisticsView.setTextViewText( R.id.procent, String.format("%.1f%s",procent," %"));//procentage
}
Bitmap bmp;
if(value == -1){
bmp=BitmapFactory.decodeResource(getResources(), R.drawable.progress_bar_red);
}else{
bmp=BitmapFactory.decodeResource(getResources(), R.drawable.progress_bar_green);
}
int width=(int) (procent*4.056); // kankse fuckar upp på andra display storlekar
if(width<2){
width=2;
}
width = (int) getResources().getDisplayMetrics().density * width;
int height=10;
Bitmap resizedbitmap=Bitmap.createScaledBitmap(bmp, width, height, true);
statisticsView.setImageViewBitmap(R.id.progress_bar, resizedbitmap);//procent bar
i = new Intent(this, ViewCategory.class);
i.putExtra(CashDB.CATEGORY_ID, c.getLong(c.getColumnIndexOrThrow(CashDB.CATEGORY_ID)));
i.setAction("cashtrackViewCategory"+c.getLong(c.getColumnIndexOrThrow(CashDB.CATEGORY_ID)));
pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
statisticsView.setOnClickPendingIntent(R.id.statistics_widget_list_layout, pendingIntent);
updatedViews.addView(R.id.list, statisticsView);
}
c.close();
cdb.close();
appWidgetManager.updateAppWidget(appWidgetId, updatedViews);
}
</code></pre>
<p>}</p>
| 0 | 2,864 |
Which permissions are required for Flashlight?
|
<p>I've used <code><uses-permission android:name="android.permission.FLASHLIGHT" /></code> but my app keeps crashing. I'm making a Torch app. Here's my Manifest code:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.Torch">
<uses-permission android:name="android.permission.FLASHLIGHT" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name="com.Torch.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
</code></pre>
<p>Error log:</p>
<pre><code>03-28 15:29:23.439 7163-7163/com.Torch E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.Torch, PID: 7163
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Torch/com.Torch.MainActivity}: java.lang.RuntimeException: Fail to connect to camera service
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2555)
at android.app.ActivityThread.access$800(ActivityThread.java:176)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1437)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5576)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
Caused by: java.lang.RuntimeException: Fail to connect to camera service
at android.hardware.Camera.<init>(Camera.java:637)
at android.hardware.Camera.open(Camera.java:496)
at com.Torch.MainActivity.onCreate(MainActivity.java:33)
at android.app.Activity.performCreate(Activity.java:6005)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2446)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2555)
at android.app.ActivityThread.access$800(ActivityThread.java:176)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1437)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5576)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
</code></pre>
| 0 | 1,269 |
java.util.zip.ZipException: error in opening zip file
|
<p>i am geting this strange exception below:</p>
<pre><code>INFO: Deploying web application archive ZangV3Spring.war
10-Sep-2010 08:46:38 org.apache.catalina.startup.ContextConfig init
SEVERE: Exception fixing docBase for context [/ZangV3Spring]
java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:114)
at java.util.jar.JarFile.<init>(JarFile.java:135)
at java.util.jar.JarFile.<init>(JarFile.java:72)
at sun.net.www.protocol.jar.URLJarFile.<init>(URLJarFile.java:72)
at sun.net.www.protocol.jar.URLJarFile.getJarFile(URLJarFile.java:48)
at sun.net.www.protocol.jar.JarFileFactory.get(JarFileFactory.java:80)
at sun.net.www.protocol.jar.JarURLConnection.connect(JarURLConnection.java:104)
at sun.net.www.protocol.jar.JarURLConnection.getJarFile(JarURLConnection.java:71)
at org.apache.catalina.startup.ExpandWar.expand(ExpandWar.java:110)
at org.apache.catalina.startup.ContextConfig.fixDocBase(ContextConfig.java:709)
at org.apache.catalina.startup.ContextConfig.init(ContextConfig.java:838)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:331)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:89)
at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:312)
at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:292)
at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:100)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:129)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:785)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:763)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:558)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:987)
at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:778)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:540)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1458)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:338)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:89)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1186)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1340)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1349)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1329)
at java.lang.Thread.run(Thread.java:619)
10-Sep-2010 08:46:38 org.apache.catalina.core.StandardContext resourcesStart
SEVERE: Error starting static Resources
java.lang.IllegalArgumentException: Invalid or unreadable WAR file : error in opening zip file
at org.apache.naming.resources.WARDirContext.setDocBase(WARDirContext.java:141)
at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4432)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4582)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:138)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:785)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:763)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:558)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:987)
at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:778)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:540)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1458)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:338)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:89)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1186)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1340)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1349)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1329)
at java.lang.Thread.run(Thread.java:619)
</code></pre>
<p>If i remove this bean from my xml it will build and deploy fine:</p>
<pre><code><bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
</code></pre>
<p>The rest of my xml content is this:</p>
<pre><code><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
<!-- http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd -->
<!-- Config properties files -->
<!-- Hibernate database stuff -->
<bean id="fileDownload" class="com.kc.models.FileManipulator"></bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>properties/jdbc.properties</value>
</list>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
<property name="maxActive" value="${database.maxConnections}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionsFactory" ref="sessionFactory"></property>
</bean>
-->
</beans>
</code></pre>
| 0 | 2,794 |
Angularjs simple datepicker using controller as not $scope
|
<p>I am trying to use the angular-ui bootstrap for dateranges.</p>
<p><a href="http://angular-ui.github.io/bootstrap/#/datepicker" rel="nofollow">http://angular-ui.github.io/bootstrap/#/datepicker</a> </p>
<p>The link contains some good examples. However I want to use <code>controller as</code> syntax and not the scope as it shows in the link above. </p>
<p>I have attempted it as seen below. But its not showing the calendar box when its clicked on. Its not returning any errors either so im a bit lost as to what I need to do. I think my example is close.</p>
<p>Here is my attempt on <a href="http://plnkr.co/edit/lANpSw?p=preview" rel="nofollow">fiddle</a></p>
<p>Code snippets below..</p>
<p><strong>js_file.js</strong></p>
<pre><code>angular.module('ui.bootstrap.demo', ['ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('DatepickerDemoCtrl', function() {
self = this;
self.someProp = 'Check This value displays.. confirms controller initalised'
self.opened = {};
self.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
self.opened = {};
self.opened[$event.target.id] = true;
// log this to check if its setting the log
console.log(self.opened);
};
self.format = 'dd-MM-yyyy'
});
</code></pre>
<p><strong>index.html</strong></p>
<pre><code><body>
<div ng-controller="DatepickerDemoCtrl as demo">
<style>
#dateFrom, #dateTo { width: 200px;}
</style>
{{ demo.someProp }}
<div class="form-group">
<div class="input-group">
<input type="text"
class="form-control date"
id="dateFrom"
placeholder="From"
ng-click="demo.open($event)"
datepicker-popup="{{demo.format}}"
ng-model="demo.dtFrom"
is-open="demo.dateFrom"
min-date="minDate"
max-date="'2015-06-22'"
datepicker-options="dateOptions"
date-disabled="disabled(date, mode)"
ng-required="true"
close-text="Close" >
<input type="text"
class="form-control date"
id="dateTo"
placeholder="To"
ng-click="demo.open($event)"
datepicker-popup="{{demo.format}}"
ng-model="demo.dtTo"
is-open="demo.dateTo"
min-date="minDate"
max-date="'2015-06-22'"
datepicker-options="dateOptions"
date-disabled="disabled(date, mode)"
ng-required="true"
close-text="Close" >
</div>
</div>
</div>
</body>
</code></pre>
| 0 | 1,242 |
How to fix 'getter "documents" was called on null.' in flutter
|
<p>I am using flutter and firebase to create a mobile app. I have 2 collections on my firestore and i wanna read all documents in a the collection "posts". However, when I do that, an error saying the getter "documents" was called on null.</p>
<pre><code> Widget getContent(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection("posts").snapshots(),
builder: (context, snap) {
return CarouselSlider(
enlargeCenterPage: true,
height: MediaQuery.of(context).size.height,
items: getItems(context, snap.data.documents),
);
},
);
}
List<Widget> getItems(BuildContext context, List<DocumentSnapshot>
docs){
return docs.map(
(doc) {
String content = doc.data["content"];
return Text(content);
}
).toList();
}
</code></pre>
<p>I expected to be delivered with the data in all documents, nut instead got this error:</p>
<pre><code>I/flutter (30878): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (30878): The following NoSuchMethodError was thrown building StreamBuilder<QuerySnapshot>(dirty,
I/flutter (30878): dependencies: [MediaQuery], state: _StreamBuilderBaseState<QuerySnapshot,
I/flutter (30878): AsyncSnapshot<QuerySnapshot>>#72d38):
I/flutter (30878): The getter 'documents' was called on null.
I/flutter (30878): Receiver: null
I/flutter (30878): Tried calling: documents
I/flutter (30878): When the exception was thrown, this was the stack:
V/NativeCrypto(30878): Registering com/google/android/gms/org/conscrypt/NativeCrypto's 284 native methods...
I/flutter (30878): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
I/flutter (30878): #1 PostsPageState.getContent.<anonymous closure>
package:reach_out_kef_global/main.dart:140
I/flutter (30878): #2 StreamBuilder.build
package:flutter/…/widgets/async.dart:423
I/flutter (30878): #3 _StreamBuilderBaseState.build
package:flutter/…/widgets/async.dart:125
I/flutter (30878): #4 StatefulElement.build
package:flutter/…/widgets/framework.dart:3825
I/flutter (30878): #5 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:3736
I/flutter (30878): #6 Element.rebuild
package:flutter/…/widgets/framework.dart:3559
I/flutter (30878): #7 ComponentElement._firstBuild
package:flutter/…/widgets/framework.dart:3716
I/flutter (30878): #8 StatefulElement._firstBuild
package:flutter/…/widgets/framework.dart:3864
I/flutter (30878): #9 ComponentElement.mount
package:flutter/…/widgets/framework.dart:3711
I/flutter (30878): #10 Element.inflateWidget
package:flutter/…/widgets/framework.dart:2956
I/flutter (30878): #11 Element.updateChild
package:flutter/…/widgets/framework.dart:2759
I/flutter (30878): #12 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:3747
I/flutter (30878): #13 Element.rebuild
package:flutter/…/widgets/framework.dart:3559
I/flutter (30878): #14 ComponentElement._firstBuild
package:flutter/…/widgets/framework.dart:3716
I/flutter (30878): #15 StatefulElement._firstBuild
package:flutter/…/widgets/framework.dart:3864
I/flutter (30878): #16 ComponentElement.mount
package:flutter/…/widgets/framework.dart:3711
...
</code></pre>
<p>PLEASE HELP!</p>
| 0 | 1,390 |
LDAP Authentication using Java
|
<p>I need to do LDAP Authentication for an application.</p>
<p>I tried the following program:</p>
<pre><code>import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
public class LdapContextCreation {
public static void main(String[] args) {
LdapContextCreation ldapContxCrtn = new LdapContextCreation();
LdapContext ctx = ldapContxCrtn.getLdapContext();
}
public LdapContext getLdapContext(){
LdapContext ctx = null;
try{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "Simple");
//it can be <domain\\userid> something that you use for windows login
//it can also be
env.put(Context.SECURITY_PRINCIPAL, "username@domain.com");
env.put(Context.SECURITY_CREDENTIALS, "password");
//in following property we specify ldap protocol and connection url.
//generally the port is 389
env.put(Context.PROVIDER_URL, "ldap://server.domain.com");
ctx = new InitialLdapContext(env, null);
System.out.println("Connection Successful.");
}catch(NamingException nex){
System.out.println("LDAP Connection: FAILED");
nex.printStackTrace();
}
return ctx;
}
}
</code></pre>
<p>Getting following exception:</p>
<pre>
LDAP Connection: FAILED
javax.naming.AuthenticationException: [LDAP: error code 49 - Invalid Credentials]
at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3053)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2999)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2801)
at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2715)
at com.sun.jndi.ldap.LdapCtx.(LdapCtx.java:305)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:187)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:205)
at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:148)
at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:78)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:235)
at javax.naming.InitialContext.initializeDefaultInitCtx(InitialContext.java:318)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:348)
at javax.naming.InitialContext.internalInit(InitialContext.java:286)
at javax.naming.InitialContext.init(InitialContext.java:308)
at javax.naming.ldap.InitialLdapContext.(InitialLdapContext.java:99)
at LdapContextCreation.getLdapContext(LdapContextCreation.java:27)
at LdapContextCreation.main(LdapContextCreation.java:12)
</pre>
<p>Few more points to consider:</p>
<ol>
<li><p>Earlier I was using <code>tomcat 5.3.5</code> but somebody told me that only tomcat 6 supports it so I downloaded <code>tomcat 6.0.35</code> and currently using this version only.</p></li>
<li><p>Configured <code>server.xml</code> and added the following code -</p>
<pre><code><Realm className="org.apache.catalina.realm.JNDIRealm"
debug="99"
connectionURL="ldap://server.domain.com:389/"
userPattern="{0}" />
</code></pre></li>
<li><p>Commented the following code from <code>server.xml</code> -</p>
<pre><code><!-- Commenting for LDAP
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/> -->
</code></pre></li>
<li><p>Steps 2 and 3 from <a href="http://viralpatel.net/blogs/implement-ldap-authentication-in-tomcat-jboss-server-for-java-app/" rel="noreferrer">article</a> </p></li>
<li><p>Someone suggested that there are some jar files that are supposed to be copied to tomcat in order to run <code>ldap</code> authentication, is that something I need to do? And which <code>jar</code> files?</p></li>
<li><p>Also, I am using the correct credentials for sure, then what is causing this issue?</p></li>
<li><p>Is there a way I can figure out the correct attributes for LDAP in case I am using incorrect ones?</p></li>
</ol>
| 0 | 1,878 |
Spring Boot: java.sql.SQLException: Access denied for user
|
<p>While trying to connect to MySQL database using Spring Boot, I am getting the following stacktrace:</p>
<pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
at com.tawila.erpproject.AppStarter.main(AppStarter.java:10) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:373) ~[spring-orm-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:362) ~[spring-orm-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
... 16 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to open JDBC connection for schema management target
at org.hibernate.tool.schema.internal.TargetDatabaseImpl.prepare(TargetDatabaseImpl.java:42) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:57) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:134) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:101) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:472) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
... 22 common frames omitted
Caused by: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964) ~[mysql-connector-java-5.1.40.jar:5.1.40]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3970) ~[mysql-connector-java-5.1.40.jar:5.1.40]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3906) ~[mysql-connector-java-5.1.40.jar:5.1.40]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:873) ~[mysql-connector-java-5.1.40.jar:5.1.40]
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1710) ~[mysql-connector-java-5.1.40.jar:5.1.40]
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1226) ~[mysql-connector-java-5.1.40.jar:5.1.40]
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2253) ~[mysql-connector-java-5.1.40.jar:5.1.40]
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284) ~[mysql-connector-java-5.1.40.jar:5.1.40]
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083) ~[mysql-connector-java-5.1.40.jar:5.1.40]
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806) ~[mysql-connector-java-5.1.40.jar:5.1.40]
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47) ~[mysql-connector-java-5.1.40.jar:5.1.40]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_66]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_66]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_66]
at java.lang.reflect.Constructor.newInstance(Constructor.java:422) ~[na:1.8.0_66]
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.40.jar:5.1.40]
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410) ~[mysql-connector-java-5.1.40.jar:5.1.40]
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328) ~[mysql-connector-java-5.1.40.jar:5.1.40]
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:310) ~[tomcat-jdbc-8.5.6.jar:na]
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:203) ~[tomcat-jdbc-8.5.6.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:718) ~[tomcat-jdbc-8.5.6.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:650) ~[tomcat-jdbc-8.5.6.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:468) ~[tomcat-jdbc-8.5.6.jar:na]
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:143) ~[tomcat-jdbc-8.5.6.jar:na]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:118) ~[tomcat-jdbc-8.5.6.jar:na]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:107) ~[tomcat-jdbc-8.5.6.jar:na]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:131) ~[tomcat-jdbc-8.5.6.jar:na]
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.tool.schema.internal.TargetDatabaseImpl.prepare(TargetDatabaseImpl.java:38) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
... 28 common frames omitted
</code></pre>
<p>Here's my configuration:</p>
<p>application.properties:</p>
<pre><code>spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/app
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update
</code></pre>
<p>AppStarter.java:</p>
<pre><code>@SpringBootApplication
public class AppStarter {
public static void main(String[] args) {
SpringApplication.run(AppStarter.class, args);
}
}
</code></pre>
<p>ApplicationContextConfig.java:</p>
<pre><code>@Configuration
public class ApplicationContextConfig {
@Bean
public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf) {
HibernateJpaSessionFactoryBean factory = new HibernateJpaSessionFactoryBean();
factory.setEntityManagerFactory(emf);
return factory;
}
}
</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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tawila</groupId>
<artifactId>erp-project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>My ERP Project</name>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<!-- <version>4.3.4.RELEASE</version> -->
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
</project>
</code></pre>
<p>I tried all of the solutions for similar problems here but none of them seem to work.</p>
| 0 | 5,423 |
TypeError: Dimension value must be integer or None or have an __index__ method, got TensorShape([None, 1])
|
<p>I am trying to convert a bot tutorial I found that uses tflearn to use keras. Right now the output should be data for the models prediction. However, I get the error:</p>
<p>TypeError: Dimension value must be integer or None or have an __index__ method, got TensorShape([None, 1])</p>
<p>my code:</p>
<pre><code>with open("intents.json") as file:
data = json.load(file)
try:
with open("data.pickle", "rb") as f:
words, lables, training, output = pickle.load(f)
except:
words = []
labels = []
docs_x = []
docs_y = []
for intent in data["intents"]:
for pattern in intent["patterns"]:
wrds = nltk.word_tokenize(pattern)
words.extend(wrds)
docs_x.append(wrds)
docs_y.append(intent["tag"])
if intent["tag"] not in labels:
labels.append(intent["tag"])
words = [stemmer.stem(w.lower()) for w in words if w != "?"]
words = sorted(list(set(words)))
labels = sorted(labels)
training = []
output = []
out_empty = [0 for _ in range(len(labels))]
for x, doc in enumerate(docs_x):
bag = []
wrds = [stemmer.stem(w) for w in doc]
# marks if a word is present in the input (1=yes, 0=no)
for w in words:
if w in wrds:
bag.append(1)
else:
bag.append(0)
output_row = out_empty[:]
output_row[labels.index(docs_y[x])] = 1
training.append(bag)
output.append(output_row)
training = numpy.array(training)
output = numpy.array(output)
with open("data.pickle", "wb") as f:
pickle.dump((words, labels, training, output), f)
tf.keras.backend.clear_session()
model = tf.keras.Sequential()
model.add(keras.layers.Dense(len(training[0])))
model.add(keras.layers.Dense(8))
model.add(keras.layers.Dense(8))
model.add(keras.layers.Dense(len(output[0]), activation="softmax"))
try:
keras.models.load_model("model.tflearn")
except:
model.compile(optimizer="adam", loss="categorical_crossentropy", metrics="accuracy")
model.fit(training, output, epochs=1000, batch_size=8)
model.save("model.tflearn")
def bag_of_words(s, words):
bag = [0 for _ in range(len(words))]
s_words = nltk.word_tokenize(s)
s_words = [stemmer.stem(word.lower()) for word in s_words]
for se in s_words:
for i, w in enumerate(words):
if w == se:
bag[i] = 1
return numpy.array(bag)
def chat():
print("Ready to chat! (type quit to stop)")
while True:
inp = input("You: ")
if inp.lower() == "quit":
break
results = model.predict([bag_of_words(inp, words)])
print(results)
chat()
</code></pre>
<p>When using the debugging mode it tells me the error is the line(inside of chat()):</p>
<p>results = model.predict([bag_of_words(inp, words)])</p>
| 0 | 1,313 |
2-column TableLayout with 50% exactly for each column
|
<p>This one puzzles me since my first steps with Android. I can't make both columns in a 2-column TableLayout exact 50% each.</p>
<p>Here's an example:</p>
<pre><code><ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent" >
<TableLayout
android:id="@+id/tablelayout"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:paddingRight="2dip" >
<TableRow>
<TextView
style="@style/TextViewStandard"
android_layout_span="2"
android:layout_weight="1"
android:text="Bla" />
</TableRow>
<TableRow>
<TextView
style="@style/TextViewStandard"
android:layout_weight="1"
android:text="Name:" />
<EditText
style="@style/EditTextStandard"
android:id="@+id/et_name"
android:layout_weight="1" />
</TableRow>
<TableRow>
<TextView
style="@style/TextViewStandard"
android:layout_weight="1"
android:text="URL:" />
<EditText
style="@style/EditTextStandard"
android:id="@+id/et_url"
android:layout_weight="1" />
</TableRow>
<TableRow>
<Button
style="@style/ButtonStandard"
android:layout_column="0"
android:layout_marginTop="6dip"
android:onClick="onClickOk"
android:text="@android:string/ok" />
</TableRow>
</TableLayout>
</ScrollView>
</code></pre>
<p>And here's the corresponding style definition:</p>
<pre><code><resources>
<style name="ButtonStandard" parent="@android:style/Widget.Button">
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">fill_parent</item>
</style>
<style name="EditTextStandard" parent="@android:style/Widget.EditText">
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">2dip</item>
<item name="android:layout_marginRight">2dip</item>
<item name="android:layout_marginTop">2dip</item>
<item name="android:layout_width">fill_parent</item>
</style>
<style name="TextViewStandard" parent="@android:style/Widget.TextView">
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">2dip</item>
<item name="android:layout_marginRight">2dip</item>
<item name="android:layout_marginTop">2dip</item>
<item name="android:layout_width">fill_parent</item>
<item name="android:textColor">@android:color/white</item>
</style>
</resources>
</code></pre>
<p>This becomes really messed up with a CheckBox involved.</p>
<p>What's wrong with my definition?</p>
<p>Many thanks in advance.
HJW</p>
| 0 | 1,684 |
Vuejs nested slots: how to pass slot to grandchild
|
<p>I use different vuetify components, for example <a href="https://vuetifyjs.com/en/components/menus" rel="noreferrer">v-menu</a>. It has a template like this:</p>
<pre><code><v-menu>
<a slot="activator">menu</a>
<v-list>
<v-list-tile>Menu Entry 1</v-list-tile>
<v-list-tile>Menu Entry 2</v-list-tile>
</v-list>
</v-menu>
</code></pre>
<p>Suppose I want to add another wrapper around it. That is my special menu component that has some predefined menu options. And I want it to has an activator slot as well. And the last should be somehow assigned to the original v-menu activator slot. Is it possible?</p>
<p>Example:</p>
<pre><code>// index.vue:
<template>
<my-special-menu>
<button>My special menu trigger</button>
</my-special-menu>
</template>
// MySpecialMenu.vue
<template>
<v-menu>
<slot slot="activator"/> <-- I don't know how to write this line
<v-list>...</v-list>
</v-menu>
</template>
</code></pre>
<p><code><slot slot="activator"></code> is an incorrect equation. The goal is to pull the content from the parent (that is <code><button>..</button></code> in the example), and use it as <code>slot="activator"</code> in v-menu.</p>
<p>I can write it like this:</p>
<pre><code><v-menu>
<a slot="activator"><slot/></a>
...
</v-menu>
</code></pre>
<p>But this case the result template will be:</p>
<pre><code><div class="v-menu__activator">
<a>
<button>My special menu trigger</button>
</a>
</div>
</code></pre>
<p>That's not exactly what I want. Is it possible to get rid off <code><a></code> wrapper here?</p>
<p>Update:
We can use a construction like <code><template slot="activator"><slot name="activator"/></template></code> to throw some slot to a grand child. But what if we have multiple slots and we want to proxy them all? That's like inheritAttrs and <code>v-bind="$attrs"</code> for slots. Is it currently possible?</p>
<p>For example, there's <code><v-autocomplete></code> component in vuetify that has append, prepend, label, no-data, progress, item, selection etc slots. I write some wrapper component around this, it currently looks like:</p>
<pre><code><template>
<v-autocomplete ..>
<template slot="append"><slot name="append"/></template>
<template slot="prepend"><slot name="prepend"/></template>
<template slot="label"><slot name="label"/></template>
...
<template slot="item" slot-scope="props"><slot name="item" v-bind="props"/></template>
</v-autocomplete>
</template>
</code></pre>
<p>Is it possible to avoid all slots enumeration here?</p>
| 0 | 1,198 |
Laravel & Docker: The stream or file "/var/www/html/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied
|
<p>This is my folder structure:</p>
<pre><code>+-- root-app-dir
| +-- docker
| | +-- Dockerfile
| | +-- nginx.conf
| +-- src // this is where the Laravel app lives
| +-- docker-compose.yml
</code></pre>
<p>This is my <code>docker-compose.yml</code></p>
<pre><code>version: '2'
services:
app:
build:
context: ./docker
dockerfile: Dockerfile
image: lykos/laravel
volumes:
- ./src/:/var/www/html/
networks:
- app-network
nginx:
image: nginx:latest
volumes:
- ./src/:/var/www/html/
- ./docker/nginx.conf:/etc/nginx/conf.d/default.conf
ports:
- 8000:80
networks:
- app-network
mysql:
image: mysql:5.7
ports:
- "4306:3306"
environment:
MYSQL_DATABASE: homestead
MYSQL_USER: homestead
MYSQL_PASSWORD: secret
MYSQL_ROOT_PASSWORD: secret
volumes:
- mysqldata:/var/lib/mysql
networks:
- app-network
phpmyadmin:
image: phpmyadmin/phpmyadmin
ports:
- 8080:80
links:
- mysql
environment:
PMA_HOST: mysql
volumes:
mysqldata:
driver: "local"
networks:
app-network:
driver: "bridge"
</code></pre>
<p>This is my nginx.conf</p>
<pre><code>server {
root /var/www/html/public;
index index.html index.htm index.php;
server_name _;
charset utf-8;
location = /favicon.ico { log_not_found off; access_log off; }
location = /robots.txt { log_not_found off; access_log off; }
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
# include snippets/fastcgi-php.conf;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_pass app:9000;
fastcgi_index index.php;
}
error_page 404 /index.php;
location ~ /\.ht {
deny all;
}
}
</code></pre>
<p>When I run <code>docker-compose up -d</code> and try to access the Laravel app through the <code>htts://localhost:8000</code> I get this error on my screen</p>
<pre><code>UnexpectedValueException
The stream or file "/var/www/html/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied
</code></pre>
<p>I have run <code>sudo chown lykos:lykos -R ./src</code> from my <code>root-app-dir</code> but the issue is still there. How can I fix this?</p>
| 0 | 1,061 |
How to support ES7 in ESLint
|
<p>I have a project setup with WebPack to use ESLint and I'm wanting to use ES7 for the inline bind operator <code>::</code>. Currently I'm getting the parse errors shown below</p>
<pre><code>/Users/ryanvice/Documents/Code/pluralsight-redux-starter/src/components/project/ProjectsPage.js (1/0)
✖ 7:27 Parsing error: Unexpected token :
/Users/ryanvice/Documents/Code/pluralsight-redux-starter/src/routes.js (2/2)
✖ 6:26 Parse errors in imported module './components/project/ProjectsPage': Unexpected token : (7:27) import/namespace
✖ 6:26 Parse errors in imported module './components/project/ProjectsPage': Unexpected token : (7:27) import/default
! 6:26 Parse errors in imported module './components/project/ProjectsPage': Unexpected token : (7:27) import/no-named-as-default
! 6:26 Parse errors in imported module './components/project/ProjectsPage': Unexpected token : (7:27) import/no-named-as-default-member
✖ 3 errors ! 2 warnings (4:45:40 PM)
</code></pre>
<p>using the following <code>.eslintrc</code> configuration which include <code>"ecmaVersion": 7</code></p>
<pre><code>{
"extends": [
"eslint:recommended",
"plugin:import/errors",
"plugin:import/warnings"
],
"plugins": [
"react"
],
"parserOptions": {
"ecmaVersion": 7,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"env": {
"es6": true,
"browser": true,
"node": true,
"jquery": true,
"mocha": true
},
"rules": {
"quotes": 0,
"no-console": 1,
"no-debugger": 1,
"no-var": 1,
"semi": [1, "always"],
"no-trailing-spaces": 0,
"eol-last": 0,
"no-unused-vars": 0,
"no-underscore-dangle": 0,
"no-alert": 0,
"no-lone-blocks": 0,
"jsx-quotes": 1,
"react/display-name": [ 1, {"ignoreTranspilerName": false }],
"react/forbid-prop-types": [1, {"forbid": ["any"]}],
"react/jsx-boolean-value": 1,
"react/jsx-closing-bracket-location": 0,
"react/jsx-curly-spacing": 1,
"react/jsx-indent-props": 0,
"react/jsx-key": 1,
"react/jsx-max-props-per-line": 0,
"react/jsx-no-bind": 1,
"react/jsx-no-duplicate-props": 1,
"react/jsx-no-literals": 0,
"react/jsx-no-undef": 1,
"react/jsx-pascal-case": 1,
"react/jsx-sort-prop-types": 0,
"react/jsx-sort-props": 0,
"react/jsx-uses-react": 1,
"react/jsx-uses-vars": 1,
"react/no-danger": 1,
"react/no-did-mount-set-state": 1,
"react/no-did-update-set-state": 1,
"react/no-direct-mutation-state": 1,
"react/no-multi-comp": 1,
"react/no-set-state": 0,
"react/no-unknown-property": 1,
"react/prefer-es6-class": 1,
"react/prop-types": 1,
"react/react-in-jsx-scope": 1,
"react/require-extension": 1,
"react/self-closing-comp": 1,
"react/sort-comp": 1,
"react/wrap-multilines": 1
}
}
</code></pre>
| 0 | 1,263 |
Dynamically resizing a container containing a Handsontable
|
<p>This is the HTML I got:</p>
<pre><code><div class="preview-content">
<h1 class="preview-content-header">Vorschau - Notiz1.txt <img src="icons/cross.png" /></h2>
<div>
<h2>Notiz1.txt</h2>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
</div>
</div>
<img id="preview-toggle" src="icons/preview.png">
<div class="main-content">
<h2 class="main-content-header">Datenbank</h2>
<div id="table">
</div>
</div>
</code></pre>
<p>This is the corresponding CSS:</p>
<pre><code>/* General Style */
html, body {
margin: 0px;
padding: 0px;
background: $background-color;
font-family: $font;
overflow-x: hidden;
}
/* Main Content */
div.main-content {
padding: 50px 0px 20px 70px;
width: 45%;
overflow: auto;
h2.main-content-header {
margin: 0;
}
}
#preview-toggle {
display: none ;
position: fixed;
z-index: 3;
top: 50px;
right: 0;
width: 40px;
height: 40px;
padding: 5px;
background-color: $nav-color;
color: $font-color-secondary;
cursor: pointer;
transition: .3s background-color;
-webkit-transition: .3s background-color;
}
#preview-toggle:hover {
background-color: $main-color;
}
/* Preview */
div.preview-content {
position: fixed;
z-index: 3;
right: 0px;
margin: 0;
width: 50%;
height: 100%;
font-size: 70%;
img {
float: right;
height: 25px;
padding: 0px 15px 0px 0px;
cursor: pointer;
}
h1 {
position: relative;
z-index: 3;
width: 100%;
margin: 0;
padding: 5px 5px 5px 10px;
background-color: $preview-header-color;
color: $font-color-secondary;
white-space: nowrap;
}
div {
position: fixed;
z-index: 3;
height: 100%;
margin: 0;
padding: 10px;
background-color: $data-background-color;
overflow-y: auto;
overflow-x: hidden;
white-space: pre-line;
word-wrap: break-word;
}
}
/* Database table */
#table {
z-index: 1;
}
</code></pre>
<p>Here is the animation to toggle the preview container on/off:</p>
<pre><code>$(document).ready(function() {
$(' .preview-content-header img').click(function() {
$('.main-content').animate({
width: "100%"
});
$('.preview-content').animate({
width: "0%"
}, 300, function() {
$('#preview-toggle').toggle();
});
$('.preview-content img').toggle();
});
$('#preview-toggle').click(function() {
$('.main-content').animate({
width: "45%"
});
$('#preview-toggle').toggle();
$('.preview-content').animate({
width: "50%"
}, 300, function() {
$('.preview-content img').toggle();
});
});
});
</code></pre>
<p>Here is the code for the Handsontable:</p>
<pre><code>$(document).ready(function() {
var data = [
["Dateiname", "Benutzer", "Erstelldatum", "Änderungsdatum", "Erste Zeile", "Kategorie", "Projekt"],
["Rechnung1.doc", "SB", "01.01.2010", "-", "Internetrechnung", "Rechnungen", "Haushalt"],
["Rechnung2.doc", "SB", "01.01.2012", "-", "Stromrechnung", "Rechnungen", "Haushalt"]
];
var container = $('#table');
container.handsontable({
data: data,
minSpareRows: 1,
rowHeaders: true,
colHeaders: true,
contextMenu: true
});
});
</code></pre>
<p>The scenario is as follows: </p>
<p>I've got a <code>.main-content</code> which takes up the whole window containing a Handsontable and a <code>.preview-content</code> which expands it width and shows content as soon as you click on the toggle button within the <code>.main-content</code>. The <code>.preview-content</code> is fixed and doesn't scroll with the <code>.main-content</code>.</p>
<p>The problem is that when the screen displaying the website is not big enough the <code>.preview-content</code> will cover parts of the Handsontable within the <code>.main-content</code>.
To prevent this from happening I wanted to change the width and height of the container containing the Handsontable dynamically so that I get scrollbars in case the table gets covered in parts.</p>
<p>I've tried many things so far but nothing seems to work. And it seems like Handsontable only likes absolute pixel dimensions for its width and height, otherwise <code>overflow: hidden</code> doesn't seem to work. </p>
<p>I've tried to change the width of the <code>.main-content</code> from 100% to 45% and added <code>overflow: auto</code> to the <code>.main-content</code> as you can see in the code, but that doesn't work as it behaves very strange.</p>
<p>Maybe someone has any idea how I can change the width of a Handsontable dynamically?</p>
<p>Your help is very appreciated. And if you need any more info to help me just say it I will see if I can provide the right info.</p>
| 0 | 2,165 |
Google Maps API Multiple Markers with Infowindows
|
<p>I am trying to add multiple markers each with its own infowindow that comes up when clicked on. I am having trouble with getting the infowindows coming up, when I try it either shows up only one marker without an infowindow. </p>
<p>Thanks, let me know if you need some more information</p>
<pre><code><meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<style type="text/css">
html {
height: 100%
}
body {
height: 100%;
margin: 0;
padding: 0
}
#map_canvas {
height: 100%
}
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyB1tbIAqN0XqcgTR1-FxYoVTVq6Is6lD98&sensor=false">
</script>
<script type="text/javascript">
var locations = [
['loan 1', 33.890542, 151.274856, 'address 1'],
['loan 2', 33.923036, 151.259052, 'address 2'],
['loan 3', 34.028249, 151.157507, 'address 3'],
['loan 4', 33.80010128657071, 151.28747820854187, 'address 4'],
['loan 5', 33.950198, 151.259302, 'address 5']
];
function initialize() {
var myOptions = {
center: new google.maps.LatLng(33.890542, 151.274856),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("default"),
myOptions);
setMarkers(map, locations)
}
function setMarkers(map, locations) {
var marker, i
for (i = 0; i < locations.length; i++) {
var loan = locations[i][0]
var lat = locations[i][1]
var long = locations[i][2]
var add = locations[i][3]
latlngset = new google.maps.LatLng(lat, long);
var marker = new google.maps.Marker({
map: map, title: loan, position: latlngset
});
map.setCenter(marker.getPosition())
var content = "Loan Number: " + loan + '</h3>' + "Address: " + add
var infowindow = new google.maps.InfoWindow()
google.maps.AddListener(marker, 'click', function (map, marker) {
infowindow.setContent(content)
infowindow.open(map, marker)
});
}
}
</script>
</head>
<body onload="initialize()">
<div id="default" style="width:100%; height:100%"></div>
</body>
</html>
</code></pre>
| 0 | 1,026 |
SQL returns less results when using UNION?
|
<p>I have a SQL Server stored procedure that doesn't give me all the results when I add in the union and the second half. The first half will give me all 6 results, using the union, I only get 5. </p>
<p>There are 3 patients with their own [chart number], each have 2 items that should be displayed. if the [CPTCode] is the same for both entries of a patient, only one of the two entries show up when i add the union (it gives me all 6 with the same [cptcode] without the union). The second half isn't actually pulling any information with what i'm doing right now, but it is needed.</p>
<pre><code>select /*Patients with chart numbers*/
B1.[chart Number],
'0' as newPatient,
isnull(Lytec.[Last Name],'') as [Last Name],
isnull(Lytec.[First Name],'') as [First Name],
isnull(Address.[Name],
Lytec.[Facility Code]) as [Facility],
isnull(B1.DOS,'') as [DOS],
isnull(Ins.[Name],
Lytec.[Primary Code]) as [Primary Code],
isnull(B1.[CPTCode],'') as cptCode,
isnull(B1.[Units],'') as [Units],
isnull(B1.[Modifiers],'') as [Modifiers],
isnull(B1.[cptCodeOther],'') as [cptCodeOther],
isnull(B1.[cptCode2],'') as cptCode2,
isnull(B1.[Units],'') as [Units2],
isnull(B1.[Modifiers2],'') as [Modifiers2],
isnull(B1.[cptCodeOther2],'') as [cptCodeOther2],
'name' as ProviderName
from
[sandboxmr].dbo.patient Lytec
left join [dbo].[Billing] B1 on B1.[Chart Number] = Lytec.[Chart Number]
left join [sandboxmr].dbo.[Address] Address on Lytec.[Facility Code] = Address.[Code]
left join [sandboxmr].dbo.[Insurance] Ins on Lytec.[Primary Code] = Ins.[Code]
where
b1.[userid] = 54
and (b1.[DateSubmitted] >= convert(varchar(25),'2011-8-31',101)
and b1.[DateSubmitted] <= convert(varchar(25),'2011-9-22',101))
union
select /*Patients without chart numbers*/
cast(P.id as varchar(15)) as [chart number],
'1' as newPatient,
isnull(P.[Last Name],'') as [Last Name],
isnull(P.[First Name],'') as [First Name],
isnull(Address.[Name],
P.[Facility Code]) as [Facility],
isnull(IV.DOS,isnull(SV.DOS,'')) as [DOS],
isnull(Ins.[Name],P.[Primary_Code]) as [Primary Code],
isnull(IV.[cptCode],isnull(SV.[cptCode],'')) as cptCode,
isnull(IV.[Units],isnull(SV.[Units],'')) as [Units],
isnull(IV.[Modifiers],isnull(SV.[Modifiers],'')) as [Modifiers],
isnull(IV.[cptcodeother],isnull(SV.[cptcodeother],'')) as [cptCodeOther],
isnull(IV.[cptCode2],isnull(SV.[cptCode2],'')) as cptCode2,
isnull(IV.Units2,isnull(SV.Units2,'')) as [Units2],
isnull(IV.[Modifiers2],isnull(SV.[Modifiers2],'')) as [Modifiers2],
isnull(IV.[cptCodeOther2],isnull(SV.[cptCodeOther2],'')) as [cptCodeOther2],
'Name' as ProviderName
from
[DNSList].[dbo].[Patient] P
left join [dbo].[InitialVisits] IV on p.emr_id = IV.patientid
left join [dbo].[SubsequentVisits] SV on p.emr_id = SV.patientid
left join [sandboxmr].dbo.[Address] Address on P.[Facility Code] = Address.[Code]
left join [sandboxmr].dbo.[Insurance] Ins on P.[Primary_Code] = Ins.[Code]
where
p.[userid] = 54
and p.[Chart Number] is null
and (p.[DateSubmitted] >= convert(varchar(25),'2011-8-31',101)
and p.[DateSubmitted] <= convert(varchar(25),'2011-9-22',101))
order by
[Last Name]
</code></pre>
<p>Why does it do this, and how can I fix it? I've tried adding a <code>distinct</code> to the [cptcode] area, but it of course generates an error.</p>
<p>Thanks for any help you can provide!</p>
| 0 | 1,396 |
W/IInputConnectionWrapper(1066): showStatusIcon on inactive InputConnection
|
<p>Here is my class:</p>
<pre><code>public class Insert extends Activity
{
EditText name,surname,age;
Button insert;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.insert);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
name =(EditText)findViewById(R.id.name);
surname =(EditText)findViewById(R.id.surname);
age =(EditText)findViewById(R.id.age);
insert=(Button)findViewById(R.id.click);
insert.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
// TODO Auto-generated method stub
String nm = name.getText().toString();
String ct = surname.getText().toString();
String emailid = age.getText().toString();
insertRecords(nm, ct, emailid);
}
private void insertRecords(String nm,String ct,String emailid)
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("name", nm));
nameValuePairs.add(new BasicNameValuePair("surname",ct));
nameValuePairs.add(new BasicNameValuePair("age",emailid));
sendData(nameValuePairs);
}
private void sendData(ArrayList<NameValuePair> data)
{
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:81/new/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
}
catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error: "+e.toString());
}
}
});
}
...
}
</code></pre>
<p>In LogCat</p>
<pre><code>04-23 12:12:10.263: W/IInputConnectionWrapper(1066): showStatusIcon on inactive InputConnection
</code></pre>
| 0 | 1,185 |
MS SQL Server and JDBC: closed connection
|
<p>Im getting </p>
<blockquote>
<p><strong>I/O Error: DB server closed connection.</strong></p>
</blockquote>
<p>while connecting to MS SQL server 2008 from java code .</p>
<hr>
<p>SQL server is in mixed mode and its in local machine.My connection string is
<strong>jTDS</strong> </p>
<blockquote>
<p><strong>jdbc:jtds:sqlserver://machineName:1433;databaseName=DB;integratedSecurity=true</strong></p>
</blockquote>
<hr>
<p>stack trace is</p>
<blockquote>
<p>java.sql.SQLException: I/O Error: DB server closed connection.
at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2311)
at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:610)
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.(ConnectionJDBC2.java:345)
at net.sourceforge.jtds.jdbc.ConnectionJDBC3.(ConnectionJDBC3.java:50)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.app.hibernate.test.(test.java:22)
at com.app.hibernate.test.main(test.java:53)
Caused by: java.io.IOException: DB server closed connection.
at net.sourceforge.jtds.jdbc.SharedSocket.readPacket(SharedSocket.java:848)
at net.sourceforge.jtds.jdbc.SharedSocket.getNetPacket(SharedSocket.java:727)
at net.sourceforge.jtds.jdbc.ResponseStream.getPacket(ResponseStream.java:466)
at net.sourceforge.jtds.jdbc.ResponseStream.read(ResponseStream.java:103)
at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2206)
... 8 more
Exception in thread "main" java.lang.NullPointerException
at com.app.hibernate.test.db(test.java:36)
at com.app.hibernate.test.main(test.java:54)</p>
</blockquote>
<p><strong>JDBC Driver</strong></p>
<blockquote>
<p>String url ="jdbc:sqlserver://machine:1433;instance=SQLEXPRESS;databaseName=db";</p>
</blockquote>
<p>stacktrace</p>
<blockquote>
<p>com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'username'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:156)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:240)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:78)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2636)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2046)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2034)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4003)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1550)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1207)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.loginWithoutFailover(SQLServerConnection.java:1054)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:758)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:842)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.app.hibernate.test.(test.java:22)
at com.app.hibernate.test.main(test.java:53)
Exception in thread "main" java.lang.NullPointerException
at com.app.hibernate.test.db(test.java:36)
at com.app.hibernate.test.main(test.java:54)</p>
</blockquote>
| 0 | 1,498 |
Android: Java code output "NaN"
|
<p>So here I have this first time app I'm working on. When I run this code in the emulator for some reason I get a "NaN" output. The program essentially is meant to find the lowest price out of several choices (of quantity and price combined). I can't figure out what I'm doing wrong. Any advice?</p>
<p>(Note: The NaN output occurs only when NOT all of the EditText fields have a number in them)</p>
<p>main class:</p>
<pre><code>import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class worthit extends Activity implements OnClickListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button)this.findViewById(R.id.btn_calculate);
b.setOnClickListener(this);
}
public void onClick(View v){
//Declaring all of our variables that we will use in
//future calculations
EditText price1 = (EditText)this.findViewById(R.id.price1);
EditText price2 = (EditText)this.findViewById(R.id.price2);
EditText price3 = (EditText)this.findViewById(R.id.price3);
EditText price4 = (EditText)this.findViewById(R.id.price4);
EditText quant1 = (EditText)this.findViewById(R.id.quant1);
EditText quant2 = (EditText)this.findViewById(R.id.quant2);
EditText quant3 = (EditText)this.findViewById(R.id.quant3);
EditText quant4 = (EditText)this.findViewById(R.id.quant4);
//TextView box used to present the results
TextView tv = (TextView)this.findViewById(R.id.result);
//Declaring two arrays of the values from
//all of our EditText fields
double[] price = new double[4];
double[] quantity = new double[4];
try{
price[0] = Double.parseDouble(price1.getText().toString());
price[1] = Double.parseDouble(price2.getText().toString());
price[2] = Double.parseDouble(price3.getText().toString());
price[3] = Double.parseDouble(price4.getText().toString());
quantity[0] = Double.parseDouble(quant1.getText().toString());
quantity[1] = Double.parseDouble(quant2.getText().toString());
quantity[2] = Double.parseDouble(quant3.getText().toString());
quantity[3] = Double.parseDouble(quant4.getText().toString());
if
} catch(NumberFormatException nfe) {
tv.setText("Parsing Error");
}
//Creating a Optimize class and using our
//price and quantity arrays as our parameters
Calculate optimize = new Calculate(price, quantity);
//Calling the optimize method to compute the cheapest
//choice
optimize.optimize();
//Composing a string to display the results
String result = "The best choice is the $" +
optimize.getResultInDollars() + " choice.";
//Setting the TextView to our result string
tv.setText(result);
}
}
</code></pre>
<p>And here is my class that does all the crunching:</p>
<pre><code>//Work class used for computing whether
//one choice is cheaper than another given
//a choice of several options af different
//prices and quantities
//Ex. Coffee- $1-10oz, $1.2-12oz, $1.4-16oz
public class Calculate {
//declaring variables
private double[] dollarValue;
private double[] ounce;
private int indexNumber; //Index number of the lowest ratio
private double minValue; //Lowest ratio
private double resultInDollars;
private double resultInOunces;
//class constructor
public Calculate(double[] dol, double[] oun){
//initializing our variables
dollarValue=new double[dol.length];
ounce=new double[oun.length];
//passing the values from the parameter
//arrays in our arrays
for(int i=0;i < dol.length;i++){
dollarValue[i]=dol[i];
ounce[i]=oun[i];
}
}
//Optimize method used to compute the
//cheapest price per quantity
public void optimize(){
//finding the ratio of the dollar value
//and the quantity (ounces)
double[] ratio=new double[dollarValue.length];
for(int i=0;i<dollarValue.length;i++)
ratio[i]=dollarValue[i]/ounce[i];
//finding the smallest value in the ratio
//array and its location (indexNumber)
minValue = ratio[0];
for(int i=1;i < dollarValue.length; i++){
if(ratio[i] < minValue){
minValue=ratio[i];
indexNumber=i;
}
}
//finding the dollar value of the smallest
//ratio that we found above
//e.g. most cost effective choice
setResultInDollars(minValue*ounce[indexNumber]);
setResultInOunces(ounce[indexNumber]);
}
public void setResultInDollars(double dollarValueChoiche) {
this.resultInDollars = dollarValueChoiche;
}
public void setResultInOunces(double resultInOunces) {
this.resultInOunces = resultInOunces;
}
public double getResultInDollars() {
return resultInDollars;
}
public double getResultInOunces() {
return resultInOunces;
}
}
</code></pre>
<p>Cheers.</p>
<p>EDIT: Apparently I also seem to be having a logic error somewhere. For example, if I choose the following prices: 1.4, 1.6, and I choose the following quantities (respectively) 18, 20, The output tells me that the $1.6 is the best choice; when you do the calculation by hand (1.4/18, 1/6,20) you get that 1.4 has the lowest ratio, thus it has to be the best choice. If anyone could tell me what I'm doing wrong that would be much appreciated.</p>
<p>Thank you.</p>
| 0 | 1,959 |
Chrome driver exception NoSuchMethodError
|
<p>I am trying to write test case, using ChromeDriver but while trying to initialise ChromeDriver instance getting exception as, </p>
<pre><code>java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkState(ZLjava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V
at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:111)
at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:32)
at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:137)
at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:302)
at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:124)
at DemoTests.test(DemoTests.java:12)
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 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code></pre>
<p>struggling on it, but unable to fix it. How can I fix this issue? Following is my code base,</p>
<pre><code>@Test
public void test() {
ChromeDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("www.google.com");
}
</code></pre>
| 0 | 1,111 |
Adding space between columns of a TableLayout
|
<p>I have a TableLayout where I add dynamically TableRows. In each TableRow, I add a Button.</p>
<p>I just would like to add some space between my columns (which are my buttons) but I can't figure out how...
I've tried to change all the possible margins but it doesn't work :(
So maybe I made a mistake in my code where I inflate them from XML files:</p>
<pre><code>private void createButtons(final CategoryBean parentCategory) {
final List<CategoryBean> categoryList = parentCategory.getCategoryList();
title.setText(parentCategory.getTitle());
// TODO à revoir
int i = 0;
TableRow tr = null;
Set<TableRow> trList = new LinkedHashSet<TableRow>();
for (final CategoryBean category : categoryList) {
TextView button = (TextView) inflater.inflate(R.layout.button_table_row_category, null);
button.setText(category.getTitle());
if (i % 2 == 0) {
tr = (TableRow) inflater.inflate(R.layout.table_row_category, null);
tr.addView(button);
} else {
tr.addView(button);
}
trList.add(tr);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CategoryBean firstChild = category.getCategoryList() != null && !category.getCategoryList().isEmpty() ? category
.getCategoryList().get(0) : null;
if (firstChild != null && firstChild instanceof QuestionsBean) {
Intent intent = new Intent(CategoryActivity.this, QuestionsActivity.class);
intent.putExtra(MainActivity.CATEGORY, category);
startActivityForResult(intent, VisiteActivity.QUESTION_LIST_RETURN_CODE);
} else {
Intent intent = new Intent(CategoryActivity.this, CategoryActivity.class);
intent.putExtra(MainActivity.CATEGORY, category);
startActivityForResult(intent, VisiteActivity.CATEGORY_RETURN_CODE);
}
}
});
i++;
}
for (TableRow tableRow : trList) {
categoryLaout.addView(tableRow);
}
}
</code></pre>
<p>My button_table_row_category.xml:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/buttonTableRowCategory"
style="@style/ButtonsTableRowCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/validate" />
</code></pre>
<p>My table_row_category.xml:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tableRowCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="100dp"
android:gravity="center"
android:padding="5dp" >
</TableRow>
</code></pre>
<p>Thank you for your help.</p>
| 0 | 1,297 |
Change Matplotlib's default font
|
<p>I'm trying to change matplotlib's default font to Helvetica Neue. On my Mac with EPD/Canopy everything worked fine some time ago. </p>
<p>Trying to do the same on ubuntu now and it's not working. </p>
<p>This is what I did:</p>
<ol>
<li><p>Installed Helvetica Neue </p>
<pre><code>$ fc-match 'Helvetica Neue':Light
HelveticaNeue-Light.otf: "Helvetica Neue" "細體"
</code></pre></li>
<li><p>Converted the odt/dfont into ttf:</p>
<pre><code>fondu -show HelveticaNeue.dfont
</code></pre></li>
<li><p>changed matplotlibrc to </p>
<pre><code>$ cat ~/.config/matplotlib/matplotlibrc
...
font.family: Helvetica Neue
</code></pre>
<p>I also tried with:</p>
<pre><code>font.family: sans-serif
font.sans-serif: Helvetica Neue
</code></pre></li>
<li><p>I removed the font cache</p>
<pre><code>rm ~/.config/matplotlib/fontList.cache
</code></pre></li>
</ol>
<p>But none of these steps are working for me.</p>
<pre><code> $ python -c 'from matplotlib import pyplot as plt; plt.plot(1); plt.savefig("/tmp/test.png")'
/usr/local/lib/python2.7/dist-packages/matplotlib-1.3.0-py2.7-linux-x86_64.egg/matplotlib/font_manager.py:1236:
UserWarning: findfont: Font family ['Helvetica Neue'] not found. Falling back to Bitstream Vera Sans
</code></pre>
<p>(prop.get_family(), self.defaultFamily[fontext]))</p>
<p>Version is 1.3.0</p>
<pre><code> $ python -c 'import matplotlib; print matplotlib.__version__'
1.3.0
</code></pre>
<p>I also tried moving the fonts to <code>~/.config/matplotlib/fonts/ttf</code> but it didn't work. </p>
<hr>
<p><strong>EDIT:</strong>
As suggested I tried selecting a specific font for a specific text. </p>
<pre><code>import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
path = '/home/<myusername>/.fonts/HelveticaNeue.ttf'
prop = font_manager.FontProperties(fname=path)
prop.set_weight = 'light'
mpl.rcParams['font.family'] = prop.get_name()
mpl.rcParams['font.weight'] = 'light'
fig, ax = plt.subplots()
ax.set_title('Text in a cool font', fontproperties=prop, size=40)
plt.savefig('/tmp/test2.png')
</code></pre>
<p>But it makes no difference.</p>
<pre><code>/usr/local/lib/python2.7/dist-packages/matplotlib-1.3.0-py2.7-linux-x86_64.egg/matplotlib/font_manager.py:1236:
UserWarning: findfont: Font family ['Helvetica Neue'] not found. Falling back to Bitstream Vera Sans
</code></pre>
<p>However I seem to experience this problem only with this Helvetica/Helvetica Neue font.
(prop.get_family(), self.defaultFamily[fontext]))</p>
| 0 | 1,026 |
Height of ListView fills the whole screen, although set as wrap_content
|
<p>i have this ListView inside a LinearLayout:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
.../>
<EditText />
...
</EditText>
<ListView
android:id="@+id/words_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
</code></pre>
<p>The List is populated programmatically by a SimpleCursorAdapter:</p>
<pre><code>adapter = new SimpleCursorAdapter(this, R.layout.list_row_search, mCursor, from, to);
</code></pre>
<p>list_row_search has a TableLayout with two TableRows:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/TableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<View
android:layout_height="1dip"
android:background="#FF33B5E5" />
<TableRow
android:id="@+id/tableRow1"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/list_lesson"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="1dip"
android:textSize="12sp" />
<TextView
android:id="@+id/list_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5.25"
android:padding="1dip"
android:paddingRight="10dp"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="@+id/list_flex"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="12.5"
android:padding="1dip"
android:paddingRight="10dp" />
<TextView
android:id="@+id/list_rom"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="6.25"
android:padding="1dip"
android:paddingRight="10dp" />
</TableRow>
<View
android:layout_height="0.1dip"
android:background="#404040" />
<TableRow
android:id="@+id/tableRow2"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/list_related"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:paddingRight="10dp"
android:textStyle="italic" />
<TextView
android:id="@+id/list_ant"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="10dp" />
<TextView
android:id="@+id/list_engl"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="10dp" />
</TableRow>
<View
android:layout_height="1dip"
android:background="#FF33B5E5" />
</TableLayout>
</code></pre>
<p>Now when the list gets populated, the ListView occupies the hole screen, even if only one element was found in the database. The HierarchyView in eclipse shows pretty clear, that the ListView is the one that fills out the screen.</p>
<p>Can you tell, where the problem is? Thanks for your time!</p>
| 0 | 1,867 |
ubuntu - mysql start and restart issue on ubuntu 16.04 server
|
<p>i installed mysql 5.7 but then found out I need mysql 5.6 so i deleted all mysql related packages with </p>
<pre><code>apt-get remove --purge mysql*
</code></pre>
<p>so it gotten removed. then i issued:</p>
<pre><code>apt-get install mysql-server-5.6 mysql-client-5.6
</code></pre>
<p>so the mentioned packages gotten installed.
but its not starting using <code>systemctl start mysql</code> or <code>service mysql start</code> or even restart. the result is this:</p>
<pre><code>service mysql restart
or
service mysql start
or
systemctl restart mysql
or
systemctl start mysql
</code></pre>
<p>returns:</p>
<pre><code>Job for mysql.service failed because the control process exited with error code. See "systemctl status mysql.service" and "journalctl -xe" for details.
</code></pre>
<p>but</p>
<pre><code>systemctl status mysql
</code></pre>
<p>returns</p>
<pre><code> mysql.service - LSB: Start and stop the mysql database server daemon
Loaded: loaded (/etc/init.d/mysql; bad; vendor preset: enabled)
Active: failed (Result: exit-code) since Mon 2017-04-10 13:24:00 EDT; 29s ago
Docs: man:systemd-sysv-generator(8)
Process: 15820 ExecStart=/etc/init.d/mysql start (code=exited, status=1/FAILURE)
Main PID: 1323 (code=exited, status=0/SUCCESS)
Apr 10 13:23:30 server mysqld[15926]: 2017-04-10 13:23:30 15925 [Note] InnoDB: Compressed tables use zlib 1.2.8
Apr 10 13:23:30 server mysqld[15926]: 2017-04-10 13:23:30 15925 [Note] InnoDB: Using Linux native AIO
Apr 10 13:23:30 server mysqld[15926]: 2017-04-10 13:23:30 15925 [Note] InnoDB: Using CPU crc32 instructions
Apr 10 13:23:30 server mysqld[15926]: 2017-04-10 13:23:30 15925 [Note] InnoDB: Initializing buffer pool, size = 128.0M
Apr 10 13:23:30 server mysqld[15926]: 2017-04-10 13:23:30 15925 [Note] InnoDB: Completed initialization of buffer pool
Apr 10 13:24:00 server mysql[15820]: ...fail!
Apr 10 13:24:00 server systemd[1]: mysql.service: Control process exited, code=exited status=1
Apr 10 13:24:00 server systemd[1]: Failed to start LSB: Start and stop the mysql database server daemon.
Apr 10 13:24:00 server systemd[1]: mysql.service: Unit entered failed state.
Apr 10 13:24:00 server systemd[1]: mysql.service: Failed with result 'exit-code'.
</code></pre>
<p>what is <code>Failed to start LSB: Start and stop the mysql database server daemon.</code>
before installing 5.6 the 5.7 version was working fine but now its like this.</p>
<p>the <code>/var/log/mysql/errors.log</code> is empty and these are the <code>/var/log/syslog</code> last lines</p>
<pre><code>Apr 10 13:23:30 server mysqld: 2017-04-10 13:23:30 15925 [Note] InnoDB: Completed initialization of buffer pool
Apr 10 13:23:30 server mysqld_safe: mysqld from pid file /var/lib/mysql/server.pid ended
Apr 10 13:24:00 server /etc/init.d/mysql[16277]: 0 processes alive and '/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf ping' resulted in
Apr 10 13:24:00 server /etc/init.d/mysql[16277]: #007/usr/bin/mysqladmin: connect to server at 'localhost' failed
Apr 10 13:24:00 server /etc/init.d/mysql[16277]: error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
Apr 10 13:24:00 server /etc/init.d/mysql[16277]: Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!
Apr 10 13:24:00 server /etc/init.d/mysql[16277]:
Apr 10 13:24:00 server mysql[15820]: ...fail!
Apr 10 13:24:00 server systemd[1]: mysql.service: Control process exited, code=exited status=1
Apr 10 13:24:00 server systemd[1]: Failed to start LSB: Start and stop the mysql database server daemon.
Apr 10 13:24:00 server systemd[1]: mysql.service: Unit entered failed state.
Apr 10 13:24:00 server systemd[1]: mysql.service: Failed with result 'exit-code'.
</code></pre>
<p>output of <code>mysqld_safe</code> </p>
<pre><code>170410 13:33:28 mysqld_safe Logging to syslog.
170410 13:33:28 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
170410 13:33:28 mysqld_safe mysqld from pid file /var/lib/mysql/server.pid ended
</code></pre>
<p>and this is my <code>/etc/mysql/my.cnf</code> and there is no <code>/etc/my.cnf</code></p>
<pre><code>#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html
# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.
# Here is entries for some specific programs
# The following values assume you have at least 32M ram
!includedir /etc/mysql/conf.d/
</code></pre>
| 0 | 1,719 |
Could not create service of type ScriptPluginFactory using BuildScopeServices.createScriptPluginFactory()
|
<p>I am using IntelliJ and am able to build and run my Gradle project via the GUI by pressing the play button, and yet running this command from the terminal </p>
<pre><code>./gradlew --stacktrace deploy
</code></pre>
<p>produces this console output, and the build fails:</p>
<pre><code>FAILURE: Build failed with an exception.
* What went wrong:
Could not create service of type ScriptPluginFactory using BuildScopeServices.createScriptPluginFactory().
> Could not create service of type PluginResolutionStrategyInternal using BuildScopeServices.createPluginResolutionStrategy().
* Try:
Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Exception is:
org.gradle.internal.service.ServiceCreationException: Could not create service of type ScriptPluginFactory using BuildScopeServices.createScriptPluginFactory().
at org.gradle.internal.service.DefaultServiceRegistry$FactoryMethodService.invokeMethod(DefaultServiceRegistry.java:816)
at org.gradle.internal.service.DefaultServiceRegistry$FactoryService.create(DefaultServiceRegistry.java:767)
at org.gradle.internal.service.DefaultServiceRegistry$ManagedObjectServiceProvider.getInstance(DefaultServiceRegistry.java:571)
at org.gradle.internal.service.DefaultServiceRegistry$SingletonService.get(DefaultServiceRegistry.java:628)
at org.gradle.internal.service.DefaultServiceRegistry$FactoryService.assembleParameters(DefaultServiceRegistry.java:780)
at org.gradle.internal.service.DefaultServiceRegistry$FactoryService.create(DefaultServiceRegistry.java:766)
at org.gradle.internal.service.DefaultServiceRegistry$ManagedObjectServiceProvider.getInstance(DefaultServiceRegistry.java:571)
at org.gradle.internal.service.DefaultServiceRegistry$SingletonService.get(DefaultServiceRegistry.java:628)
at org.gradle.internal.service.DefaultServiceRegistry$FactoryService.assembleParameters(DefaultServiceRegistry.java:780)
at org.gradle.internal.service.DefaultServiceRegistry$FactoryService.create(DefaultServiceRegistry.java:766)
at org.gradle.internal.service.DefaultServiceRegistry$ManagedObjectServiceProvider.getInstance(DefaultServiceRegistry.java:571)
at org.gradle.internal.service.DefaultServiceRegistry$SingletonService.get(DefaultServiceRegistry.java:628)
at org.gradle.internal.service.DefaultServiceRegistry.find(DefaultServiceRegistry.java:295)
at org.gradle.internal.service.DefaultServiceRegistry.get(DefaultServiceRegistry.java:284)
at org.gradle.internal.service.DefaultServiceRegistry.get(DefaultServiceRegistry.java:279)
at org.gradle.initialization.DefaultGradleLauncherFactory.doNewInstance(DefaultGradleLauncherFactory.java:179)
at org.gradle.initialization.DefaultGradleLauncherFactory.newInstance(DefaultGradleLauncherFactory.java:108)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:40)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:31)
at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:61)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:34)
at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:64)
at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:29)
at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:46)
at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
at org.gradle.util.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.internal.service.ServiceCreationException: Could not create service of type PluginResolutionStrategyInternal using BuildScopeServices.createPluginResolutionStrategy().
at org.gradle.internal.service.DefaultServiceRegistry$FactoryMethodService.invokeMethod(DefaultServiceRegistry.java:816)
at org.gradle.internal.service.DefaultServiceRegistry$FactoryService.create(DefaultServiceRegistry.java:767)
at org.gradle.internal.service.DefaultServiceRegistry$ManagedObjectServiceProvider.getInstance(DefaultServiceRegistry.java:571)
at org.gradle.internal.service.DefaultServiceRegistry$SingletonService.get(DefaultServiceRegistry.java:628)
at org.gradle.internal.service.DefaultServiceRegistry$FactoryService.assembleParameters(DefaultServiceRegistry.java:780)
at org.gradle.internal.service.DefaultServiceRegistry$FactoryService.create(DefaultServiceRegistry.java:766)
at org.gradle.internal.service.DefaultServiceRegistry$ManagedObjectServiceProvider.getInstance(DefaultServiceRegistry.java:571)
at org.gradle.internal.service.DefaultServiceRegistry$SingletonService.get(DefaultServiceRegistry.java:628)
at org.gradle.internal.service.DefaultServiceRegistry.find(DefaultServiceRegistry.java:295)
at org.gradle.internal.service.DefaultServiceRegistry.get(DefaultServiceRegistry.java:284)
at org.gradle.internal.service.DefaultServiceRegistry.get(DefaultServiceRegistry.java:279)
at org.gradle.internal.service.scopes.BuildScopeServices.defaultScriptPluginFactory(BuildScopeServices.java:301)
at org.gradle.internal.service.scopes.BuildScopeServices.createScriptPluginFactory(BuildScopeServices.java:293)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
at org.gradle.internal.service.ReflectionBasedServiceMethod.invoke(ReflectionBasedServiceMethod.java:35)
at org.gradle.internal.service.DefaultServiceRegistry$FactoryMethodService.invokeMethod(DefaultServiceRegistry.java:814)
... 61 more
Caused by: org.gradle.api.GradleException: Could not generate a proxy class for class org.gradle.plugin.management.internal.DefaultPluginResolutionStrategy.
at org.gradle.api.internal.AbstractClassGenerator.generateUnderLock(AbstractClassGenerator.java:228)
at org.gradle.api.internal.AbstractClassGenerator.generate(AbstractClassGenerator.java:80)
at org.gradle.api.internal.ClassGeneratorBackedInstantiator.newInstance(ClassGeneratorBackedInstantiator.java:36)
at org.gradle.plugin.internal.PluginUsePluginServiceRegistry$BuildScopeServices.createPluginResolutionStrategy(PluginUsePluginServiceRegistry.java:106)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
at org.gradle.internal.service.ReflectionBasedServiceMethod.invoke(ReflectionBasedServiceMethod.java:35)
at org.gradle.internal.service.DefaultServiceRegistry$FactoryMethodService.invokeMethod(DefaultServiceRegistry.java:814)
... 79 more
Caused by: java.lang.NoSuchMethodError: sun.misc.Unsafe.defineClass(Ljava/lang/String;[BIILjava/lang/ClassLoader;Ljava/security/ProtectionDomain;)Ljava/lang/Class;
at org.gradle.internal.classloader.ClassLoaderUtils.define(ClassLoaderUtils.java:104)
at org.gradle.model.internal.asm.AsmClassGenerator.define(AsmClassGenerator.java:58)
at org.gradle.model.internal.asm.AsmClassGenerator.define(AsmClassGenerator.java:54)
at org.gradle.api.internal.AsmBackedClassGenerator$ClassBuilderImpl.generate(AsmBackedClassGenerator.java:967)
at org.gradle.api.internal.AbstractClassGenerator.generateUnderLock(AbstractClassGenerator.java:226)
... 88 more
</code></pre>
| 0 | 4,230 |
Including .NET installer in WiX Bundle not detecting if already installed
|
<p>I'm on WiX 3.7, and I can't get the simple <PackageGroupRef Id="NetFx40Web"/> bundle element to work, as it doesn't bring across the Net FX installer package, or embed it in the setup.exe. I've resorted to creating my own package for this in my <code>Bundle.wxs</code> file, but I am still having trouble. It seems to always try to install .NET 4, even if the machine already has .NET installed.</p>
<p>I'm not quite sure of the difference between <em>InstallCondition</em> and <em>DetectCondition</em>. I think <em>InstallCondition</em> is used to install the package if the evaluation is true, otherwise uninstall it. How does this work with things that are typically <em>permanent=yes</em>, such as most pre-requisites? <em>DetectCondition</em> is almost the opposite, I think, in that it checks if it's already on the system, and if so, doesn't install it.</p>
<p>Below is my full <code>Bundle.wxs</code> file which is in a Visual Studio WiX Bootstrapper project. I'm attempting to look at the registry and scope out of .NET 4.0 registry key is there. If it is present, then I don't want to install .NET 4., and if it's not there, then install it. But, this isn't working, and it always attempts to install .NET.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<Bundle
Name="MyProgramBootstrapper"
Version="1.0.0.0"
Manufacturer="Microsoft"
UpgradeCode="{2299B51D-9FD8-4278-90C8-2B79DB37F402}">
<BootstrapperApplicationRef Id="WixStandardBootstrapperApplication.RtfLicense" />
<Chain>
<PackageGroupRef Id="Netfx4Full"/>
<MsiPackage
Id="MyProgramInstaller"
SourceFile="$(var.MyProgramInstaller.TargetPath)"
Compressed="no"/>
</Chain>
</Bundle>
<Fragment>
<Property Id="NET40_FULL_INSTALL_32">
<RegistrySearch
Id ="SearchNet40_32bit"
Root="HKLM"
Key="SOFTWARE\Microsoft\Net Framework Setup\NDP\v4\Full"
Name="Version"
Type ="raw"/>
</Property>
<Property
Id="NET40_FULL_INSTALL_64">
<RegistrySearch
Id ="SearchNet40_64bit"
Root="HKLM"
Key="SOFTWARE\Microsoft\Net Framework Setup\NDP\v4\Full"
Name="Version"
Type ="raw"
Win64="yes" />
</Property>
<WixVariable
Id="WixMbaPrereqPackageId"
Value="Netfx4Full" />
<WixVariable
Id="WixMbaPrereqLicenseUrl"
Value="NetfxLicense.rtf" />
<PackageGroup
Id="Netfx4Full">
<ExePackage
Id="Netfx4Full"
Cache="no"
Compressed="no"
PerMachine="yes"
Permanent="yes"
Vital="yes"
SourceFile="C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bootstrapper\Packages\DotNetFX40\dotNetFx40_Full_x86_x64.exe"
DetectCondition="NET40_FULL_INSTALL_32 OR NET40_FULL_INSTALL_64"
DownloadUrl="http://go.microsoft.com/fwlink/?LinkId=164193"/>
</PackageGroup>
</Fragment>
</Wix>
</code></pre>
<p>Bootstrapper installer log:</p>
<pre><code>[010C:2FB0][2013-05-10T12:07:07]w120: Detected partially cached package: Netfx4Full, invalid payload: Netfx4Full, reason: 0x80070570
[010C:2FB0][2013-05-10T12:07:07]i052: Condition 'NETFRAMEWORK40' evaluates to false.
[010C:2FB0][2013-05-10T12:07:07]w120: Detected partially cached package: MyInstaller, invalid payload: f4832BA0972BDE9B6FA8A19FBB614A7BA, reason: 0x80070570
[010C:2FB0][2013-05-10T12:07:07]i101: Detected package: Netfx4Full, state: Absent, cached: Partial
</code></pre>
<hr/>
<p>Update, with solution. I used the built-in WiX RegistrySearch to determine if it's installed. I had to reference the WixUtilExtension.dll in my Bundle project. Here's the updated Bundle.wxs:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
xmlns:netfx="http://schemas.microsoft.com/wix/NetFxExtension"
xmlns:util="http://schemas.microsoft.com/wix/UtilExtension"
>
<Bundle
Name="MyProgramBootstrapper"
Version="1.0.0.0"
Manufacturer="Microsoft"
UpgradeCode="{2299B51D-9FD8-4278-90C8-2B79DB37F402}">
<BootstrapperApplicationRef Id="WixStandardBootstrapperApplication.RtfLicense" />
<Chain>
<PackageGroupRef Id="Netfx4Full"/>
<!-- TODO: Define the list of chained packages. -->
<!-- <MsiPackage SourceFile="path\to\your.msi" /> -->
<MsiPackage
Id="MyProgramInstaller"
SourceFile="$(var.MyProgramInstaller.TargetPath)"
Compressed="no" />
</Chain>
</Bundle>
<Fragment>
<util:RegistrySearchRef Id="NETFRAMEWORK40"/>
<PackageGroup
Id="Netfx4Full">
<ExePackage
Id="Netfx4FullExe"
Cache="no"
Compressed="no"
PerMachine="yes"
Permanent="yes"
Vital="yes"
SourceFile="C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bootstrapper\Packages\DotNetFX40\dotNetFx40_Full_x86_x64.exe"
InstallCommand="/q /norestart /ChainingPackage FullX64Bootstrapper"
DetectCondition="NETFRAMEWORK40"
DownloadUrl="http://go.microsoft.com/fwlink/?LinkId=164193"/>
</PackageGroup>
</Fragment>
</Wix>
</code></pre>
| 0 | 2,800 |
Data source rejected establishment of connection, message from server: "Too many connections"
|
<p>I am trying to make connections to my database using connection pooling library: <a href="http://www.snaq.net/java/DBPool/" rel="noreferrer">DBPool</a>. Here's my source code. <br></p>
<h3>DBUtils.java</h3>
<pre><code>package DB;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.sql.ConnectionPoolDataSource;
import snaq.db.ConnectionPool;
import com.mysql.jdbc.Driver;
/**
* @author decorrea
*/
public class DBUtils {
public static String jdbc_driver_name = "com.mysql.jdbc.Driver";
private static String server_name ;
private static String database;
private static String username;
private static String password;
public String getServer_name() {
return server_name;
}
public void setServer_name(String serverName) {
server_name = serverName;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/*
* Creates a MySQL DB connection from a pool
*/
public Connection createConnection(ConnectionPool pool){
Connection connection = null;
try {
// Load the JDBC driver
Class driver_class = Class.forName(jdbc_driver_name);
Driver driver = (Driver)driver_class.newInstance();
DriverManager.registerDriver(driver);
connection = pool.getConnection();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return connection;
}
/*
* Creates a MySQL DB connection
*/
public Connection createConnection(){
Connection connection = null;
try {
// Load the JDBC driver
Class driver_class = Class.forName(jdbc_driver_name);
Driver driver = (Driver)driver_class.newInstance();
DriverManager.registerDriver(driver);
String url = "jdbc:mysql://" + server_name + "/" + database;
connection = DriverManager.getConnection(url);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return connection;
}
}
</code></pre>
<h3>TwitterAPI.java</h3>
<pre><code>/**
* @author decorrea
*/
public class TwitterAPI {
private static String server_name = "127.0.0.1";
private static String twitter_databse = "twitter";
private static String username = "root";
private static String password = "password";
public static Connection startDBConnection(String server_name, String database, String username, String password) {
//Set DB parameters
DBUtils mysql_obj = setDBParams(server_name, database, username, password);
String url = "jdbc:mysql://" + server_name + "/" + database;
ConnectionPool pool = new ConnectionPool("local",1, 1, 1, 180000, url, username, password);
Connection connection = mysql_obj.createConnection(pool);
return connection;
}
public static DBUtils setDBParams(String server_name, String database, String username, String password){
DBUtils mysql_obj = new DBUtils();
mysql_obj.setServer_name(server_name);
mysql_obj.setDatabase(database);
mysql_obj.setUsername(username);
mysql_obj.setPassword(password);
return mysql_obj;
}
public static String getTweets(BigInteger id){
Connection connection = startDBConnection(server_name,twitter_databse,username,password);
ResultSet resultSet = null;
String tweet = new String();
try {
Statement statement = connection.createStatement();
String query = SQL_queries.get_tweets_on_id + id.toString();
//Execute the query
resultSet = statement.executeQuery(query);
while(resultSet.next()){
tweet = resultSet.getString("content");
}
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return tweet;
}
}
</code></pre>
<p>I am new to the business of connection pooling and decided to do so only because I was receiving a "Communications Link failure" without it. </p>
<p><strong>Update 1:</strong> To add I also tried Apache <a href="http://commons.apache.org/dbcp/" rel="noreferrer"> DBCP </a> and tried this <a href="http://ezinearticles.com/?How-To-Create-A-Standalone-Connection-Pool-In-Java?&id=924710" rel="noreferrer">example</a> but still receive the same error.</p>
<pre><code>org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Data source rejected establishment of connection, message from server: "Too many connections")
at org.apache.commons.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1549)
at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1388)
at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at Twitter.TwitterAPI.startDBConnection(TwitterAPI.java:55)
at Twitter.TwitterAPI.getTweets(TwitterAPI.java:84)
at Twitter.TwitterAPI.main(TwitterAPI.java:235)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections"
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:45)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:528)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:984)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1105)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2186)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:787)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:49)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:45)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:528)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:357)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582)
at org.apache.commons.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1556)
at org.apache.commons.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1545)
... 5 more
Exception in thread "main" java.lang.NullPointerException
at Twitter.TwitterAPI.getTweets(TwitterAPI.java:108)
at Twitter.TwitterAPI.main(TwitterAPI.java:235)
</code></pre>
<p>I also checked the max_connections variable in the my.ini file in MySQL. Here's it's value:</p>
<blockquote>
<p>The maximum amount of concurrent sessions the MySQL server will
allow. One of these connections will be reserved for a user with
SUPER privileges to allow the administrator to login even if the
connection limit has been reached.
<code>max_connections=100</code></p>
</blockquote>
<p>The <em>show processlist</em> command on the MySQL terminal shows 101 processes in sleep. </p>
<p>Any kind of help/comments will be appreciated</p>
<p><strong>Update 2 -- Solution::</strong>
So, I figured out the solution. I hadn't mentioned the port name in the url connection to the database.</p>
<pre><code>String url = "jdbc:mysql://" + server_name + "/" + database;
</code></pre>
<p>Probably, hence it led to many <em>leaking</em> connections. Once done, I tried with the example given <a href="http://ezinearticles.com/?How-To-Create-A-Standalone-Connection-Pool-In-Java?&id=924710" rel="noreferrer">here</a>. It now doesn't throw any error. Thanks to BalusC, as I figured this out only due to his comment on changing the port number on MySQL. To add, the way to change the MySQL port number is <strong>NOT</strong> by changing the <em>my.ini</em> file but by running the <em>MySQL instance config wizard</em> under Start -> Programs -> MySQL Server 5.1 -> MySQL Server Instance Config Wizard. It was also interesting to note the code didn't throw any error when the port number wasn't specified and the program ran smoothly. Probably, JDBC connects to 3306 by default. If anyone has any particular idea about the same, please share.</p>
<p>For my complete source code <a href="https://stackoverflow.com/a/3212907/281545">see my answer below</a></p>
| 0 | 3,874 |
Chooser with camera intent and image picker intent
|
<p>I have created a chooser for either picking an image from file or for making a picture.</p>
<p>The code I use works fine on a Nexus 5, however when I try it on a Samsung S5, the chooser does not display the camera icons.</p>
<pre><code>public Intent makePhotoIntent(String title, Context ctx, String uniqueImageId){
//Build galleryIntent
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
//Create chooser
Intent chooser = Intent.createChooser(galleryIntent,title);
if (checkexCameraHardware()){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mTempImage = null;
try {
mTempImage = createImageFile(uniqueImageId);
} catch (IOException e) {
e.printStackTrace();
}
if (mTempImage != null){
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempImage)); //add file ure (photo is saved here)
Intent[] extraIntents = {cameraIntent};
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
}
}
return chooser;
}
</code></pre>
<p><img src="https://i.stack.imgur.com/mZTaf.png" alt="Samsung"><img src="https://i.stack.imgur.com/5CS4x.png" alt="Nexus"></p>
<p>When I change the order in which the intents are added to the chooser the Samsung device does show the camera but only shows android-system as the file option.</p>
<pre><code>public Intent makePhotoIntent(String title, Context ctx, String uniqueImageId){
//Build galleryIntent
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
//Create chooser
Intent chooser = Intent.createChooser(galleryIntent,title);
if (checkexCameraHardware()){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mTempImage = null;
try {
mTempImage = createImageFile(uniqueImageId);
} catch (IOException e) {
e.printStackTrace();
}
if (mTempImage != null){
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempImage)); //add file ure (photo is saved here)
//I have to re-create the chooser here or the Samsung will not show the 'camera' icons.
//I have to add the cameraIntent first.
chooser = Intent.createChooser(cameraIntent,title);
Intent[] extraIntents = {galleryIntent};
//Intent[] extraIntents = {cameraIntent};
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
}
}
return chooser;
}
</code></pre>
<p><img src="https://i.stack.imgur.com/VpQOf.png" alt="Samsung"> <img src="https://i.stack.imgur.com/QsILj.png" alt="Nexus"></p>
<p>Ideally I would like the Samsung device to show the same as the Nexus one when I add the gallery intent first. I can however not get this to work.</p>
| 0 | 1,393 |
What exactly is join() in Boost::thread? (C++)
|
<p>In Java, I would do something like:</p>
<pre><code>Thread t = new MyThread();
t.start();
</code></pre>
<p>I start thread by calling start() method. So later I can do something like:</p>
<pre><code>for (int i = 0; i < limit; ++i)
{
Thread t = new MyThread();
t.start();
}
</code></pre>
<p>To create a group of threads and execute the code in run() method. </p>
<p>However, in C++, there's no such thing as start() method. Using Boost, if I want a thread to start running, I have to call the join() method in order to make a thread running. </p>
<pre><code>#include <iostream>
#include <boost/thread.hpp>
class Worker
{
public:
Worker()
{
// the thread is not-a-thread until we call start()
}
void start(int N)
{
m_Thread = boost::thread(&Worker::processQueue, this, N);
}
void join()
{
m_Thread.join();
}
void processQueue(unsigned N)
{
float ms = N * 1e3;
boost::posix_time::milliseconds workTime(ms);
std::cout << "Worker: started, will work for "
<< ms << "ms"
<< std::endl;
// We're busy, honest!
boost::this_thread::sleep(workTime);
std::cout << "Worker: completed" << std::endl;
}
private:
boost::thread m_Thread;
};
int main(int argc, char* argv[])
{
std::cout << "main: startup" << std::endl;
Worker worker, w2, w3, w5;
worker.start(3);
w2.start(3);
w3.start(3);
w5.start(3);
worker.join();
w2.join();
w3.join();
w5.join();
for (int i = 0; i < 100; ++i)
{
Worker w;
w.start(3);
w.join();
}
//std::cout << "main: waiting for thread" << std::endl;
std::cout << "main: done" << std::endl;
return 0;
}
</code></pre>
<p>On the code above, the for loop to create 100 threads, normally I must use a boost::thread_group to add the thread function, and finally run all with join_all(). However, I don't know how to do it with thread function putting in a class which uses various class members.</p>
<p>On the other hand, the loop above will not behave like the loop in Java. It will make each thread execute sequentially, not all at once like the other separated threads, whose own join() is called. </p>
<p>What is join() in Boost exactly? Also please help me to create a group of threads which share the same class.</p>
| 0 | 1,043 |
Angularjs: transclude directive template
|
<p>How to use transclusion in the below case. The intention is to use markup in the html (partials) file, than defining it in template (within the directive).</p>
<p>I found a great tree directive here. (<a href="https://groups.google.com/forum/#!msg/angular/vswXTes_FtM/kfT_CufjLjgJ">source</a>)
Original: <a href="http://jsfiddle.net/n8dPm/">http://jsfiddle.net/n8dPm/</a></p>
<p>Instead of defining the template in the directive, I was trying to use a transcluded content. I also updated Angular to 1.2.0.rc2.
Updated: <a href="http://jsfiddle.net/aZx7B/2/">http://jsfiddle.net/aZx7B/2/</a></p>
<p>got below error</p>
<blockquote>
<p>TypeError: Property '$transclude' of object [object Object] is not a
function</p>
</blockquote>
<p>code:</p>
<pre><code>module.directive("tree", function($compile) {
return {
restrict: "E",
transclude: true,
scope: {family: '='},
template:
'<ul>' +
'<li ng-transclude></li>' +
'<li ng-repeat="child in family.children">' +
'<tree family="child"></tree>' +
'</li>' +
'</ul>',
compile: function(tElement, tAttr) {
var contents = tElement.contents().remove();
var compiledContents;
return function(scope, iElement, iAttr) {
if(!compiledContents) {
compiledContents = $compile(contents);
}
compiledContents(scope, function(clone, scope) {
iElement.append(clone);
});
};
}
};
});
<div ng-app="myapp">
<div ng-controller="TreeCtrl">
<tree family="family">
<p>{{ family.name }}</p>
</tree>
</div>
</div>
</code></pre>
<h2>Edit:</h2>
<p>With David's suggestion, made some changes. <a href="http://jsfiddle.net/aZx7B/3/">http://jsfiddle.net/aZx7B/3/</a>
now, it prints, Parent. changing, <code>family</code> -> <code>treeFamily</code> didn't work though</p>
| 0 | 1,053 |
undefined reference with shared library using cmake
|
<p>I have looked a lot of placed to find this answer, but I have not been able to find anything that pertains to my situation. It seems so easy, which is why this is so frustrating.</p>
<p>I am building a project with CMAKE. I am generating two shared libraries. One includes the other. I am also generating an executable. The executable is linking to the shared library that encapsulates the other one. Here is the relevant portion of the code:</p>
<pre><code>################################################################################
# Make the shared libraries
################################################################################
# Standard stuff
add_library(er SHARED src/std_math.cc src/snapshot.cc)
include_directories(hdr)
target_link_libraries(er rt)
# DSP library
add_library(dsp SHARED src/dsp.cc)
include_directories(hdr)
target_link_libraries(dsp er /usr/lib/libfftw3f.so /usr/lib/libfftw3.so)
################################################################################
# Make an Executable
################################################################################
message("-- Making executable for testing --")
add_executable(er_test test/dsp_test.cc)
include_directories(hdr)
target_link_libraries(er_test dsp)
################################################################################
# What to do with make install
################################################################################
message ("-- Writting install scripts --")
# See if there is an install directory already assigned. If not, set it to the
# system default.
if (NOT DEFINED INSTALL_DIR)
set (INSTALL_DIR /usr/local/)
endif (NOT DEFINED INSTALL_DIR)
message (" -- install_dir = ${INSTALL_DIR}")
# Install the libraries and header files to the appropriate places
install (TARGETS er dsp DESTINATION ${INSTALL_DIR}/bin)
install (FILES hdr/dsp.hh hdr/snapshot.hh hdr/std_math.hh DESTINATION ${INSTALL_DIR}/include)
</code></pre>
<p>Here is the error I get. </p>
<pre><code>CMakeFiles/er_test.dir/test/dsp_test.cc.o: In function `main':
dsp_test.cc:(.text.startup+0x11e): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& operator<< <int>(std::basic_ostream<char, std::char_traits<char> >&, std::vector<int, std::allocator<int> > const&)'
dsp_test.cc:(.text.startup+0x142): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& operator<< <int>(std::basic_ostream<char, std::char_traits<char> >&, std::vector<int, std::allocator<int> > const&)'
dsp_test.cc:(.text.startup+0x166): undefined reference to `std::vector<int, std::allocator<int> > subvec<int>(std::vector<int, std::allocator<int> > const&, int, int, int)'
dsp_test.cc:(.text.startup+0x182): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& operator<< <int>(std::basic_ostream<char, std::char_traits<char> >&, std::vector<int, std::allocator<int> > const&)'
dsp_test.cc:(.text.startup+0x1b6): undefined reference to `std::vector<int, std::allocator<int> > subvec<int>(std::vector<int, std::allocator<int> > const&, int, int, int)'
</code></pre>
<p>and there are many more where those came from. I have tried using static libraries, but then it just delays the problem until the next executable I try to include these libraries into. I have also tried using g++ instead of c++. I've tried swapping around library orders. Also, it is not a template issue since at least one of the references it can't find is not a templated function. I have searched the libraries for the symbols, and I was able to find them, although they were prepended and postpended by random characters.</p>
<p>I don't understand what's going on. Please help.</p>
<p>Thanks,</p>
<p>UPDATE</p>
<p>I found another link, specifically <a href="https://stackoverflow.com/questions/6891447/cmake-variable-scope-add-subdirectory">this one</a>, that mentioned potential problems with add_subdirectory. This is a subproject to another project. So I sent into the project and built there. It worked! It still doesn't work in the parent directory though. Maybe that can give clues to someone. </p>
<p>Thanks again,</p>
| 0 | 2,472 |
android imageButton onClick method not calling
|
<p>EDIT: Posting full code (except XML as it a bunch of ridiculous table formatting!) Please ignore the code that doesn't pertain to my question! I am just getting functionality right now. I'll clean it up later.</p>
<p>First app and first question. I've researched here a while and usually find my answer but I have a bugger that is probably very obvious. I have an imageButton that doesn't seem to be calling the method assigned.</p>
<p>My XML for my imageButton:</p>
<pre><code><ImageButton
android:background="@null"
android:onClick="click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton1"
android:src="@drawable/stats"
android:layout_gravity="center_vertical">
</ImageButton>
</code></pre>
<p>My code:</p>
<pre><code>package com.talismancs;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class sheet extends Activity{
private String selection;
private String pick;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sheet);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
// Get extra from .main and remove spaces
String pick = extras.getString(selection);
pick = pick.replace(" ", "");
//Convert extra from string to int as ID and make image
int imageResource = getResources().getIdentifier(pick, "drawable", getPackageName());
ImageView iv = (ImageView) findViewById(R.id.imageView1);
final Drawable image = getResources().getDrawable(imageResource);
iv.setImageDrawable(image);
// Populate tv's from string
TextView tv1 = (TextView) findViewById(R.id.textView4);
TextView tv2 = (TextView) findViewById(R.id.textView5);
TextView tv3 = (TextView) findViewById(R.id.textView6);
TextView tv4 = (TextView) findViewById(R.id.textView7);
TextView tv5 = (TextView) findViewById(R.id.textView8);
int arrayresource = getResources().getIdentifier(pick, "array", getPackageName());
String[] CharString = getResources().getStringArray(arrayresource);
tv1.setText(CharString[0]);
tv2.setText(CharString[1]);
tv3.setText(CharString[2]);
tv4.setText(CharString[3]);
tv5.setText(CharString[4]);
}
}
public void onClick(View view) {
Intent i = new Intent(sheet.this, stats.class);
i.putExtra(pick, pick);
startActivity(i);
}
</code></pre>
<p>}</p>
<p>Seems simple right? When I click the imageButton it does absolutely nothing!</p>
<p>Please help.</p>
<p>EDIT: LOGCAT After selecting a spinner item which gets us to this activity .sheet</p>
<pre><code>> 03-16 06:15:38.977:
> INFO/ActivityManager(563): Displayed
> activity com.talismancs/.sheet: 766 ms
> 03-16 06:15:42.907:
> DEBUG/dalvikvm(1735): GC freed 448
> objects / 39160 bytes in 58ms 03-16
> 06:15:43.847:
> INFO/NotificationService(563):
> enqueueToast pkg=com.talismancs
> callback=android.app.ITransientNotification$Stub$Proxy@43773720
> duration=1 03-16 06:15:43.877:
> INFO/ActivityManager(563): Starting
> activity: Intent {
> comp={com.talismancs/com.talismancs.sheet} (has extras) } 03-16 06:15:43.917:
> WARN/InputManagerService(563): Window
> already focused, ignoring focus gain
> of:
> com.android.internal.view.IInputMethodClient$Stub$Proxy@43718320
> 03-16 06:15:44.527:
> INFO/ActivityManager(563): Displayed
> activity com.talismancs/.sheet: 646 ms
</code></pre>
<p>After that is does nothing when I click the imageButton</p>
| 0 | 1,462 |
ASP.NET with OpenIdAuthentication: redirect to url if not authorized
|
<p>I am attempting to write an ASP.NET application that uses a hybrid authentication scheme.
A user can either have his username and password hash stored in the UserStore, or he can authenticate via Azure Active Directory.</p>
<p>I have created the login form pictured. It has the standard <code>UserName</code> and <code>Password</code> inputs, but also has a "Login via Active Directory" button.</p>
<p><a href="https://i.stack.imgur.com/pYc8C.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pYc8C.png" alt="enter image description here"></a></p>
<p>This works well.</p>
<p>Now for the problem: The application's home page has the <code>[Authorize]</code> attribute. </p>
<pre><code>public class DefaultController : Controller
{
[Authorize]
public ViewResult Index()
{
// Implementation
}
}
</code></pre>
<p>If the user is not logged in, I want it to redirect to the page <code>Account/Login</code>, allowing the user to choose the authentication method.</p>
<p>Once I added <code>IAppBuilder.UseOpenIdConnectAuthentication</code> to the pipeline setup, it no longer redirects to that page. Instead, it goes straight to the Microsoft Login page.</p>
<p>How do I configure it so that OpenID authentication is part of the system, but allow me to specify how to perform redirections when the user is not authenticated?</p>
<p>Here's the code where I set up the pipeline:</p>
<pre><code>appBuilder.SetDefaultSignInAsAuthticationType(CookieAuthenticationDefaults.AuthenticationType_;
var cookieAuthenticationOptions = new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationType.ApplicationCookie,
LoginPath = new Microsoft.Owin.PathString("/Account/Login"),
Provider = new Security.CookieAuthenticationProvider()
};
appBuilder.UseCookieAuthentication(cookieAuthenticationOptions);
// Now the OpenId authentication
var notificationHandlers = new OpenIdConnectAuthenticationNotificationHandlers
{
AuthorizationCodeReceived = async(context) => {
var jwtSecurityToken = context.JwtSecurityToken;
// I've written a static method to convert the claims
// to a user
var user = await GetOrCreateUser(context.OwinContext, jwtSecurityToken.Claims);
var signInManager = context.OwinContext.Get<SignInManager>();
await signInManager.SignInAsync(user, true, false);
}
}
var openIdOptions = new OpenIdConnectAuthenticationOptions
{
ClientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx",
Authority = "https://login.microsoftonline.com/xxxxx.onmicrosoft.com",
PostLogoutRedirectUri = "https://localhost:52538/Account/Login",
Notifications = notifcationHandlers
}
appBuilder.UseOpenIdConnectAuthentication(openIdOptions);
</code></pre>
<p>When you click "Active Directory Signin", it posts to "Account/SignInWithOpenId"</p>
<pre><code>public ActionResult SignInWithOpenId()
{
// Send an OpenID Connect sign-in request.
if (!Request.IsAuthenticated)
{
var authenticationProperties = new AuthenticationProperties
{
RedirectUri = "/"
};
HttpContext.GetOwinContext().Authentication.Challenge
(
authenticationProperties,
OpenIdConnectAuthenticationDefaults.AuthenticationType
);
return new EmptyResult();
}
else
{
return RedirectToAction("Index", "Default");
}
}
</code></pre>
| 0 | 1,119 |
ASP.NET MVC4 FormCollection.GetValues not returning correct values
|
<p>I'm building a mobile webiste using ASP.NET MVC4.
One of the pages in my solution contains a table where all the rows in the table can be edited and saved in one batch. To do this I am using FormCollection in the Action in the Controller. This works as expected for most of the fields, exept one: item.IsPercent. This field is a boolean, and FormCollection.GetValues("item.IsPercent") returns twice the number of rows in the table and the list always alternates between true and false, no matter what the actual values are.</p>
<p>How can I collect the right value for the Percent checkboxes?</p>
<p><strong>An Example</strong></p>
<p><img src="https://i.stack.imgur.com/ZxPNc.png" alt="enter image description here"></p>
<p><strong>My View</strong></p>
<pre><code>@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
foreach (var group in Model.GroupBy(i => i.Exercise.Name)) {
<table>
<tr>
<th colspan="4">@Html.Label(group.Key)</th>
</tr>
<tr>
<td>Load</td>
<td>Percent</td>
<td> </td>
<td>Reps</td>
</tr>
@foreach (var item in group.OrderBy(i => i.Order))
{
@Html.HiddenFor(modelItem => item.Id)
<tr>
<td>
@Html.EditorFor(modelItem => item.Load)
@Html.ValidationMessageFor(modelItem => item.Load)
</td>
<td>
@Html.EditorFor(modelItem => item.IsPercent)
</td>
<td>
x
</td>
<td>
@Html.EditorFor(modelItem => item.Repetitions)
@Html.ValidationMessageFor(modelItem => item.Repetitions)
</td>
</tr>
}
</table>
<br />
}
<p>
<input type="submit" value="Save" />
</p>
}
</code></pre>
<p><strong>My Controller</strong></p>
<pre><code>[HttpPost]
public ActionResult EditProgramTemplateLines(FormCollection c)
{
int i = 0;
int ptId = 0;
if (ModelState.IsValid)
{
var ptIdArray = c.GetValues("item.id"); // [1,2,3,4]
var ptLoadArray = c.GetValues("item.Load"); // [50, 55, 60, 80]
var ptPercentArray = c.GetValues("item.IsPercent"); // [true, false, true, false, true, false, true, false]
var ptRepsArray = c.GetValues("item.Repetitions"); // [13, 10, 5, 2]
for (i = 0; i < ptIdArray.Count(); i++) {
var ptLine = factory.GetProgramTemplateLine(Convert.ToInt32(ptIdArray[i]));
if(ptId == 0)
ptId = ptLine.ProgramTemplateId;
ptLine.Load = ConvertToDouble(ptLoadArray[i]);
ptLine.IsPercent = Convert.ToBoolean(ptPercentArray[i]);
ptLine.Repetitions = ConvertToInt(ptRepsArray[i]);
factory.SetEntryAsModified(ptLine);
}
factory.SaveChanges();
return RedirectToAction("Details", new { id = ptId });
}
return View();
}
</code></pre>
<p><strong>Updated solution</strong>
Considering the link posted in comment below <a href="https://stackoverflow.com/questions/1714989/formcollection-for-a-checkbox">FormCollection for a checkbox</a> my solution is to loop throug the array like this:</p>
<pre><code>var percentId = 0;
for(i = 0;i<ptIdArray.Count();i++){
if(ptPercentArray[percentId] == true){
item.IsPercent = true;
percentId = percentId + 2;
}
else{
item.IsPercent = false;
percentId++;
}
}
</code></pre>
| 0 | 1,671 |
Failed to marshal EJB parameters --- IllegalArgumentException: Can not set org.apache.commons.collections.FastHashMap field
|
<p>I'm getting the below error while trying to save a search results using the Remote interface for <code>SearchFacade.java</code></p>
<pre><code>"Failed to marshal EJB parameters"
</code></pre>
<blockquote>
<p>Can not set org.apache.commons.collections.FastHashMap field
org.apache.commons.validator.Field.hMsgs to
org.apache.commons.collections.FastHashMap at
sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146)
at</p>
</blockquote>
<p>I'm Using struts 1.1, EJB 2.1 using xdoclet 1.2.3 jars for generating the dependency files.(which is inevitable to use), Where my Local,Home interfaces are being generated using Xdoclet..</p>
<p>I'm also using Java 6, Jboss EAP 6.1 Alpha in my project.</p>
<p>Note: The same code works fine when running in Jboss 4.0</p>
<p>So wonder is my remote calling is correct.</p>
<p>Any help is welcome.</p>
<p>Error Logs</p>
<blockquote>
<p>java.lang.RuntimeException: JBAS014154: Failed to marshal EJB parameters at org.jboss.as.ejb3.remote.LocalEjbReceiver.clone(LocalEjbReceiver.java:270) at org.jboss.as.ejb3.remote.LocalEjbReceiver.clone(LocalEjbReceiver.java:259) at org.jboss.as.ejb3.remote.LocalEjbReceiver.processInvocation(LocalEjbReceiver.java:170) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:181) at org.jboss.ejb.client.EJBHomeCreateInterceptor.handleInvocation(EJBHomeCreateInterceptor.java:79) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183) at org.jboss.ejb.client.TransactionInterceptor.handleInvocation(TransactionInterceptor.java:42) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183) at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:125) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183) at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:177) at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:161) at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:124) at $Proxy25.saveSearch(Unknown Source) at com.web.history.SearchFormDelegate.saveSearch(SearchFormDelegate.java:177) at com.history.SaveSearchAction.createNewSavedSearch(SaveSearchAction.java:109) at com.history.SaveSearchAction.executeSynchronized(SaveSearchAction.java:296) at com.dispatch.SynchronizedAction.execute(SynchronizedAction.java:206) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432) at javax.servlet.http.HttpServlet.service(HttpServlet.java:754) at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:295) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at com.security.AuthenticationFilter.doFilter(AuthenticationFilter.java:672) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at com.planetj.servlet.filter.compression.CompressingFilter.doFilter(CompressingFilter.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:149) at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:169) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:145) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:97) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:102) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:336) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:653) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:920) at java.lang.Thread.run(Thread.java:662) Caused by: java.lang.IllegalArgumentException: Can not set org.apache.commons.collections.FastHashMap field org.apache.commons.validator.Field.hMsgs to org.apache.commons.collections.FastHashMap at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146) at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:150) at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:63) at java.lang.reflect.Field.set(Field.java:657) at org.jboss.marshalling.cloner.SerializingCloner.storeFields(SerializingCloner.java:368) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:313) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner$StepObjectInput.doReadObject(SerializingCloner.java:836) at org.jboss.marshalling.AbstractObjectInput.readObject(AbstractObjectInput.java:37) at org.jboss.marshalling.MarshallerObjectInputStream.readObjectOverride(MarshallerObjectInputStream.java:57) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:344) at java.util.HashMap.readObject(HashMap.java:1030) at sun.reflect.GeneratedMethodAccessor119.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.jboss.marshalling.reflect.SerializableClass.callReadObject(SerializableClass.java:218) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:302) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:285) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.as.ejb3.remote.LocalEjbReceiver.clone(LocalEjbReceiver.java:268) ... 42 more </p>
</blockquote>
<p>Code:</p>
<pre><code>saveAction.java
protected void newSavedSearch(final SrchFrmDelegate sfd,
final String userId, final HttpServletRequest request,
final SaveSearchForm form) throws RemoteException,
UsrNotFoundException {
BseSrchValue srchValue = SrchResultsAction.retrieveSrchCriteria(request);
FrmLayout frmLayout = (FrmLayout) request.getSession().getAttribute(
FrmBuilderAction.FRM_LAYOUT_KEY);
Integer resultCount = null;
SrchResultValue srchResult = SearchResultsAction.retrieveSearchResults(request);
if (srchResult != null) {
resultCount = new Integer(srchResult.getTotal());
}
sfd.saveSearch(userGuid,
form.getTitle(),
form.getDesc(),
form.getNewTtle(),
srchValue,
frmLayout,
resultCount,
form.getSearches());
}
</code></pre>
<p>SrchFrmDelegate.java</p>
<pre><code>/**
* Reference to the remote interface.
*/
private SrhFrmFacadeRemote srhFacadeRemote;
public String saveSearch(final String userId, final String srchTtle,
final String srchDesc, final Boolean newTtle,
final BsSearchValue srchValue, final FrmLay frmLay,
final Integer resultCount, final List alerts)
throws UsrNotFoundException,
RemoteException {
return srhFacadeRemote.saveSearch(userId, srchTtle,
srchDesc, newTtle, srchValue, frmLay,
resultCount, alerts);
}
SrchFrmFacadeRemote.java
/**
* Remote interface for SrchFrmFacade.
*/
public java.lang.String saveSearch( java.lang.String userId,java.lang.String srchTtle,java.lang.String srchDesc,java.lang.Boolean newTtle,com.common.search.BsSearchValue srchValue,com.common.search.advanced.FrmLay frmLay,java.lang.Integer resultCount,java.util.List alerts ) throws com.common.admin.UserNotFoundException, java.rmi.RemoteException;
</code></pre>
| 0 | 3,605 |
How to download the files in magento
|
<p>I uploaded some files for each customer in magento....</p>
<p>Then i listed the customers details with the uploaded file name ..</p>
<p>I need to download the file using magento code </p>
<p>This is the code:</p>
<pre><code>public function downloadAction() {
$entityid = $this->getRequest()->getParam('entity_id');
$customer_data = Mage::getModel('customer/customer')->load($entityid);
$filename = '';
if($customer_data){
$filename = $customer_data->getFileuploadname();
}
$filepath = '../uploads/'.$filename;
if (! is_file ( $filepath ) || ! is_readable ( $filepath )) {
throw new Exception ( );
}
$this->getResponse ()
->setHttpResponseCode ( 200 )
->setHeader ( 'Pragma', 'public', true )
->setHeader ( 'Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true )
->setHeader ( 'Content-type', 'application/force-download' )
->setHeader ( 'Content-Length', filesize($filepath) )
->setHeader ('Content-Disposition', 'inline' . '; filename=' . basename($filepath) );
$this->getResponse ()->clearBody ();
$this->getResponse ()->sendHeaders ();
readfile ( $filepath );
//exit(0);
}
</code></pre>
<p>But it didsplays errors something like:</p>
<pre><code>Trace:
#0 D:\wamp\www\mysite\app\code\core\Mage\Core\Controller\Varien\Action.php(419): Managecustomers_Users_IndexController->downloadAction()
#1 D:\wamp\www\mysite\app\code\core\Mage\Core\Controller\Varien\Router\Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('download')
#2 D:\wamp\www\mysite\app\code\core\Mage\Core\Controller\Varien\Front.php(176): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#3 D:\wamp\www\mysite\app\code\core\Mage\Core\Model\App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
#4 D:\wamp\www\mysite\app\Mage.php(683): Mage_Core_Model_App->run(Array)
#5 D:\wamp\www\mysite\index.php(87): Mage::run('', 'store')
#6 {main}
</code></pre>
<p>The <code>uploads</code> folder is in magento root folder...</p>
<p>How can i download the file....</p>
<p>The <code>$filename</code> have the filename uploaded that is coming from database...</p>
<p><strong>EDIT :</strong></p>
<p>When i removed the code:</p>
<pre><code> if (! is_file ( $filepath ) || ! is_readable ( $filepath )) {
throw new Exception ( );
}
</code></pre>
<p>Then changed the filepath as :</p>
<pre><code>$filepath = 'http://localhost/mysite/uploads/'.$filename;
</code></pre>
<p>Then downloading done perfectly....</p>
| 0 | 1,189 |
MySQL Server shuts down frequently and won't start again now
|
<p><strong>OS:</strong> Ubuntu 16.04.1 LTS xenial</p>
<p>I installed MySQL on my server on AWS and it was working fine, but after we started getting much traffic on-site, it started failing frequently. To fix it, I usually restart the service or server which works but for only a few minutes/hours and then it fails again. Now MySQL doesn't start again even after I restart the server.</p>
<p>Running <code>sudo systemctl start mysql</code> i get this message</p>
<blockquote>
<p>Job for mysql.service failed because the control process exited with error code. See "systemctl status mysql.service" and "journalctl -xe" for details.</p>
</blockquote>
<p>And this is the content logged in <code>/var/log/mysql/error.log</code></p>
<pre><code>2017-02-08T11:35:32.352942Z 0 [Warning] Changed limits: max_open_files: 1024 (requested 5000)
2017-02-08T11:35:32.352975Z 0 [Warning] Changed limits: table_open_cache: 431 (requested 2000)
2017-02-08T11:35:32.509812Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-02-08T11:35:32.510752Z 0 [Note] /usr/sbin/mysqld (mysqld 5.7.17-0ubuntu0.16.04.1) starting as process 3060 ...
2017-02-08T11:35:32.514030Z 0 [Note] InnoDB: PUNCH HOLE support available
2017-02-08T11:35:32.514046Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-02-08T11:35:32.514049Z 0 [Note] InnoDB: Uses event mutexes
2017-02-08T11:35:32.514054Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2017-02-08T11:35:32.514057Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.8
2017-02-08T11:35:32.514060Z 0 [Note] InnoDB: Using Linux native AIO
2017-02-08T11:35:32.514265Z 0 [Note] InnoDB: Number of pools: 1
2017-02-08T11:35:32.514359Z 0 [Note] InnoDB: Using CPU crc32 instructions
2017-02-08T11:35:32.515647Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2017-02-08T11:35:32.522465Z 0 [Note] InnoDB: Completed initialization of buffer pool
2017-02-08T11:35:32.524160Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2017-02-08T11:35:32.535815Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2017-02-08T11:35:32.536689Z 0 [Note] InnoDB: Log scan progressed past the checkpoint lsn 30903245
2017-02-08T11:35:32.536703Z 0 [Note] InnoDB: Doing recovery: scanned up to log sequence number 30904484
2017-02-08T11:35:32.536738Z 0 [ERROR] InnoDB: Ignoring the redo log due to missing MLOG_CHECKPOINT between the checkpoint 30903245 and the end 30904484.
2017-02-08T11:35:32.536747Z 0 [ERROR] InnoDB: Plugin initialization aborted with error Generic error
2017-02-08T11:35:33.137801Z 0 [ERROR] Plugin 'InnoDB' init function returned error.
2017-02-08T11:35:33.137835Z 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2017-02-08T11:35:33.137841Z 0 [ERROR] Failed to initialize plugins.
2017-02-08T11:35:33.137843Z 0 [ERROR] Aborting
2017-02-08T11:35:33.137848Z 0 [Note] Binlog end
2017-02-08T11:35:33.137893Z 0 [Note] Shutting down plugin 'MyISAM'
2017-02-08T11:35:33.137914Z 0 [Note] Shutting down plugin 'CSV'
2017-02-08T11:35:33.138111Z 0 [Note] /usr/sbin/mysqld: Shutdown complete
</code></pre>
| 0 | 1,225 |
How do I create and sign certificates with Python's pyOpenSSL?
|
<p>I would like to use python to create a CA certificate, and client certificates that I sign with it. I will be using these with OpenVPN. After several days of research, and trial and error, this is what I've come up with:</p>
<pre><code>#!/usr/bin/env python
import os
import sys
import random
from OpenSSL import crypto
###########
# CA Cert #
###########
ca_key = crypto.PKey()
ca_key.generate_key(crypto.TYPE_RSA, 2048)
ca_cert = crypto.X509()
ca_cert.set_version(2)
ca_cert.set_serial_number(random.randint(50000000,100000000))
ca_subj = ca_cert.get_subject()
ca_subj.commonName = "My CA"
ca_cert.add_extensions([
crypto.X509Extension("subjectKeyIdentifier", False, "hash", subject=ca_cert),
])
ca_cert.add_extensions([
crypto.X509Extension("authorityKeyIdentifier", False, "keyid:always", issuer=ca_cert),
])
ca_cert.add_extensions([
crypto.X509Extension("basicConstraints", False, "CA:TRUE"),
crypto.X509Extension("keyUsage", False, "keyCertSign, cRLSign"),
])
ca_cert.set_issuer(ca_subj)
ca_cert.set_pubkey(ca_key)
ca_cert.sign(ca_key, 'sha256')
ca_cert.gmtime_adj_notBefore(0)
ca_cert.gmtime_adj_notAfter(10*365*24*60*60)
# Save certificate
with open("ca.crt", "wt") as f:
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, ca_cert))
# Save private key
with open("ca.key", "wt") as f:
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, ca_key))
###############
# Client Cert #
###############
client_key = crypto.PKey()
client_key.generate_key(crypto.TYPE_RSA, 2048)
client_cert = crypto.X509()
client_cert.set_version(2)
client_cert.set_serial_number(random.randint(50000000,100000000))
client_subj = client_cert.get_subject()
client_subj.commonName = "Client"
client_cert.add_extensions([
crypto.X509Extension("basicConstraints", False, "CA:FALSE"),
crypto.X509Extension("subjectKeyIdentifier", False, "hash", subject=client_cert),
])
client_cert.add_extensions([
crypto.X509Extension("authorityKeyIdentifier", False, "keyid:always", issuer=ca_cert),
crypto.X509Extension("extendedKeyUsage", False, "clientAuth"),
crypto.X509Extension("keyUsage", False, "digitalSignature"),
])
client_cert.set_issuer(ca_subj)
client_cert.set_pubkey(client_key)
client_cert.sign(ca_key, 'sha256')
client_cert.gmtime_adj_notBefore(0)
client_cert.gmtime_adj_notAfter(10*365*24*60*60)
# Save certificate
with open("client.crt", "wt") as f:
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, client_cert))
# Save private key
with open("client.key", "wt") as f:
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, client_key))
</code></pre>
<p>This generates the certificates and private keys, but unfortunately, I must be doing something wrong because they do not verify:</p>
<pre><code>$ openssl verify -verbose -CAfile ca.crt client.crt
client.crt: CN = Client
error 7 at 0 depth lookup:certificate signature failure
139823049836448:error:04091068:rsa routines:INT_RSA_VERIFY:bad signature:rsa_sign.c:293:
139823049836448:error:0D0C5006:asn1 encoding routines:ASN1_item_verify:EVP lib:a_verify.c:241:
</code></pre>
<p>What am I doing wrong?</p>
| 0 | 1,184 |
Flutter - Trouble launching app for debug on macOS
|
<p>I've recently tried to migrate code from <code>main.dart</code> to the beginning of <code>home_page.dart</code> so as to steam line my application. Since doing this, my app now won't compile, I suspect as it doesn't know where to launch the application.</p>
<p>This is the error I'm receiving, <code>Set the 'program' value in your launch config (eg 'bin/main.dart') then launch again</code> <strong>(in VSCode)</strong> but since migrating the code I don't have <code>main.dart</code>, below is the last used version before deletion including the current version of <code>home_page.dart</code></p>
<p><strong>Also, below is the result of <code>$ flutter doctor -v</code></strong></p>
<p><code>main.dart</code>;</p>
<pre><code>import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:cryptick_nice_ui/dependency_injection.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:cryptick_nice_ui/home_page.dart';
void main() async {
Injector.configure(Flavor.PROD);
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
theme: new ThemeData(
primarySwatch: Colors.pink,
primaryColor: defaultTargetPlatform == TargetPlatform.iOS
? Colors.grey[100]
: null),
debugShowCheckedModeBanner: false,
home: new HomePage(),
);
}
}
</code></pre>
<p><code>home_page.dart</code>;</p>
<pre><code>import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:cryptick_nice_ui/data/crypto_data.dart';
import 'package:cryptick_nice_ui/modules/crypto_presenter.dart';
import 'background.dart';
import 'package:cryptick_nice_ui/dependency_injection.dart';
void main() async {
Injector.configure(Flavor.PROD);
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
theme: new ThemeData(
primarySwatch: Colors.pink,
primaryColor: defaultTargetPlatform == TargetPlatform.iOS
? Colors.grey[100]
: null),
debugShowCheckedModeBanner: false,
home: new HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => new _HomePageState();
}
class _HomePageState extends State<HomePage> implements CryptoListViewContract {
CryptoListPresenter _presenter;
List<Crypto> _currencies;
bool _isLoading;
final List<MaterialColor> _colors = [Colors.blue, Colors.indigo, Colors.red];
_HomePageState() {
_presenter = new CryptoListPresenter(this);
}
@override
void initState() {
super.initState();
_isLoading = true;
_presenter.loadCurrencies();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(".",
style: new TextStyle(
fontFamily: 'PlayfairDisplay',
letterSpacing: 0.8,
color: const Color(0xFF273A48),
)
),
backgroundColor: const Color(0xFF273A48),
elevation: 0.0,
),
body: _isLoading
? new Center(
child: new CircularProgressIndicator(),
)
: _cryptoWidget()
);
}
Widget _cryptoWidget() {
final _width = MediaQuery.of(context).size.width;
final _height = MediaQuery.of(context).size.height;
return new Container(
decoration: new BoxDecoration(
color: const Color(0xFF273A48),
),
child: new Column(
children: <Widget>[
new CustomPaint(
size: new Size(_width, _height),
painter: new Background(),
),
new Flexible(
child: new ListView.builder(
itemCount: _currencies.length,
itemBuilder: (BuildContext context, int index) {
final int i = index ~/ 2;
final Crypto currency = _currencies[i];
final MaterialColor color = _colors[i % _colors.length];
if (index.isOdd) {
return new Divider();
}
return _getListItemUi(context, currency, color);
},
),
)
],
)
);
}
Widget _getListItemUi(BuildContext context, Crypto currency, MaterialColor color) {
final _width = MediaQuery.of(context).size.width;
final _height = MediaQuery.of(context).size.height;
_presenter.loadCurrencies();
final headerList = new ListView.builder(
itemBuilder: (context, index) {
EdgeInsets padding = index == 0?const EdgeInsets.only(
left: 20.0, right: 10.0, top: 4.0, bottom: 30.0):const EdgeInsets.only(
left: 10.0, right: 10.0, top: 4.0, bottom: 30.0);
return new Padding(
padding: padding,
child: new InkWell(
onTap: () {
print('Card selected');
},
child: new Container(
decoration: new BoxDecoration(
borderRadius: new BorderRadius.circular(10.0),
color: Colors.lightGreen,
boxShadow: [
new BoxShadow(
color: Colors.black.withAlpha(70),
offset: const Offset(3.0, 10.0),
blurRadius: 15.0)
],
image: new DecorationImage(
image: new ExactAssetImage(
''),
fit: BoxFit.fitHeight,
),
),
// height: 200.0,
width: 200.0,
child: new Stack(
children: <Widget>[
new Align(
alignment: Alignment.bottomCenter,
child: new Container(
decoration: new BoxDecoration(
color: const Color(0xFF273A48),
borderRadius: new BorderRadius.only(
bottomLeft: new Radius.circular(10.0),
bottomRight: new Radius.circular(10.0))),
height: 30.0,
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'hi',
style: new TextStyle(color: Colors.white),
)
],
)),
)
],
),
),
),
);
},
scrollDirection: Axis.horizontal,
itemCount: _currencies.length,
);
final body = new Scaffold(
appBar: new AppBar(
title: new Text('cryp'),
elevation: 0.0,
backgroundColor: Colors.transparent,
actions: <Widget>[
new IconButton(icon: new Icon(Icons.shopping_cart, color: Colors.white,), onPressed: (){})
],
),
backgroundColor: Colors.transparent,
body: new Container(
child: new Stack(
children: <Widget>[
new Padding(
padding: new EdgeInsets.only(top: 10.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
new Align(
alignment: Alignment.centerLeft,
child: new Padding(
padding: new EdgeInsets.only(left: 8.0),
child: new Text(
'Trending News',
style: new TextStyle(
color: Colors.white70,
fontSize: 15.0,
),
)),
),
new Container(
height: 300.0, width: _width, child: headerList),
new Expanded(child:
ListView.builder(itemBuilder: (context, index) {
return new ListTile(
title: new Column(
children: <Widget>[
new Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Container(
height: 72.0,
width: 72.0,
decoration: new BoxDecoration(
color: Colors.lightGreen,
boxShadow: [
new BoxShadow(
color:
Colors.black.withAlpha(70),
offset: const Offset(2.0, 2.0),
blurRadius: 2.0)
],
borderRadius: new BorderRadius.all(
new Radius.circular(12.0)),
image: new DecorationImage(
image: new ExactAssetImage(
"cryptoiconsBlack/"+currency.symbol.toLowerCase()+"@2x.png",
),
fit: BoxFit.cover,
)),
),
new SizedBox(
width: 8.0,
),
new Expanded(
child: new Column(
mainAxisAlignment:
MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
new Text(
'My item header',
style: new TextStyle(
fontSize: 14.0,
color: Colors.black87,
fontWeight: FontWeight.bold),
),
new Text(
'Item Subheader goes here\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry',
style: new TextStyle(
fontSize: 12.0,
color: Colors.black54,
fontWeight: FontWeight.normal),
)
],
)),
new Icon(
Icons.shopping_cart,
color: const Color(0xFF273A48),
)
],
),
new Divider(),
],
),
);
}))
],
),
),
],
),
),
);
return new Container(
decoration: new BoxDecoration(
color: const Color(0xFF273A48),
),
child: new Stack(
children: <Widget>[
new CustomPaint(
size: new Size(_width, _height),
painter: new Background(),
),
body,
],
),
);
}
Widget _getSubtitleText(String priceUSD, String percentageChange) {
TextSpan priceTextWidget = new TextSpan(
text: "\$$priceUSD\n", style: new TextStyle(color: Colors.black));
String percentageChangeText = "1 hour: $percentageChange%";
TextSpan percentageChangeTextWidget;
if (double.parse(percentageChange) > 0) {
percentageChangeTextWidget = new TextSpan(
text: percentageChangeText,
style: new TextStyle(color: Colors.green));
} else {
percentageChangeTextWidget = new TextSpan(
text: percentageChangeText, style: new TextStyle(color: Colors.red));
}
return new RichText(
text: new TextSpan(
children: [priceTextWidget, percentageChangeTextWidget]));
}
@override
void onLoadCryptoComplete(List<Crypto> items) {
// TODO: implement onLoadCryptoComplete
setState(() {
_currencies = items;
_isLoading = false;
});
}
@override
void onLoadCryptoError() {
// TODO: implement onLoadCryptoError
}
}
</code></pre>
<p>Result of <code>$flutter doctor -v</code></p>
<pre><code>[✓] Flutter (Channel beta, v0.5.1, on Mac OS X 10.13.6 17G65, locale en-GB)
• Flutter version 0.5.1 at /Users/Jake/flutter
• Framework revision c7ea3ca377 (3 months ago), 2018-05-29 21:07:33 +0200
• Engine revision 1ed25ca7b7
• Dart version 2.0.0-dev.58.0.flutter-f981f09760
[✓] Android toolchain - develop for Android devices (Android SDK 28.0.2)
• Android SDK at /Users/jake/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-28, build-tools 28.0.2
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b01)
• All Android licenses accepted.
[✓] iOS toolchain - develop for iOS devices (Xcode 9.4.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 9.4.1, Build version 9F2000
• ios-deploy 1.9.2
• CocoaPods version 1.5.3
[✓] Android Studio (version 3.1)
• Android Studio at /Applications/Android Studio.app/Contents
✗ Flutter plugin not installed; this adds Flutter specific functionality.
✗ Dart plugin not installed; this adds Dart specific functionality.
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b01)
[✓] Connected devices (1 available)
• Nokia 3310 • b689ec530586d0c681cac2136a29548cfbe7c9a6 • ios • iOS 11.4.1
• No issues found!
</code></pre>
| 0 | 8,055 |
Simple tutorial example (lambda expression) doesn't run
|
<p>Finally decided to start a bit of experimentation on the new features of jdk8, namely the <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html" rel="nofollow">lambda expressions following the tutorial</a>. For convenience, I stripped-down the example, see SSCCE below. </p>
<p>Typing out the predicate just runs fine, refactoring it to a lambda expression as suggested (and actually done) by Netbeans compiles (?) without errors, but doesn't run. The laconic console printout is </p>
<blockquote>
<p>Fehler: Hauptklasse simple.Simple konnte nicht gefunden oder geladen
werden</p>
</blockquote>
<p>("Error: main class couldn't be found or loaded")</p>
<p>Environment:</p>
<ul>
<li>jdk: jdk-8-ea-bin-b102-windows-i586-08_aug_2013.exe</li>
<li>Netbeans 7.4 beta, bundle from 14.7.2013. Not sure if that's the latest, couldn't download from the Netbeans site (got a "content encoding error" when clicking on its download link)</li>
</ul>
<p>BTW, thought of using Netbeans only because it already has support for jdk8 (if not netbeans, who else ;-) - the eclipse beta preview from efxclipse has a similar issue (compiling but not running the example). So being definitely out off my comfort zone, possibly some very stupid mistake on my part... ? </p>
<pre><code>package simple;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class Simple {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
List<Member> members = createMembers();
// implement predicate directly, runs fine
// Predicate<Member> predicate = new Predicate<Member>() {
// public boolean test(Member member) {
// return member.getAge() >= 18;
// }
// };
// predicate converted to lambda, fails to run
// "class couldn't be found"
Predicate<Member> predicate = (Member member) -> member.getAge() >= 18;
for (Member member : members) {
if (predicate.test(member)) {
member.printMember();;
}
}
}
public static class Member {
private String name;
private int age;
public Member(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void printMember() {
System.out.println(name + ", " + getAge());
}
}
private static List<Member> createMembers() {
List<Member> members = new ArrayList<>();
members.add(new Member("Mathilda", 45));
members.add(new Member("Clara", 15));
members.add(new Member("Gloria", 18));
return members;
}
}
</code></pre>
| 0 | 1,108 |
MatPlotLib, datetimes, and TypeError: ufunc 'isfinite' not supported for the input types…
|
<p>Here is a tiny piece of code that produces a filled in region between two lines of a graph:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0.0, 2, 0.01)
y1 = np.sin(2 * np.pi * x)
y2 = 1.2 * np.sin(4 * np.pi * x)
fig, ax1 = plt.subplots(1, 1, sharex=True)
# Test support for masked arrays.
ax1.fill_between(x, 0, y1)
ax1.set_ylabel('between y1 and 0')
y2 = np.ma.masked_greater(y2, 1.0)
ax1.plot(x, y1, x, y2, color='black')
ax1.fill_between(
x, y1, y2, where=y2 >= y1,
facecolor='green',
interpolate=True)
ax1.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', interpolate=True)
ax1.set_title('Now regions with y2>1 are masked')
# Show the plot.
plt.show()
</code></pre>
<p>It looks like so:</p>
<p><a href="https://i.stack.imgur.com/mMF5im.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mMF5im.png" alt="Plot generated by the code"></a></p>
<p>Now, changing the start so that <code>x</code> is now a collections of date times objects like so:</p>
<pre><code>import datetime
x1 = np.arange(0.0, 2, 0.01)
now = np.datetime64(datetime.datetime.now())
x = np.array([now - np.timedelta64(datetime.timedelta(seconds=i)) for i in range(200)])
y1 = np.sin(2 * np.pi * x1)
y2 = 1.2 * np.sin(4 * np.pi * x1)
</code></pre>
<p>yields:</p>
<pre><code>Traceback (most recent call last): File "fill_between_demo.py", line 21, in <module>
ax1.fill_between(x, 0, y1)
File "/home/usr/.virtualenvs/raiju/lib/python3.6/site-packages/matplotlib/__init__.py", line 1898, in inner
return func(ax, *args, **kwargs)
File "/home/usr/.virtualenvs/raiju/lib/python3.6/site-packages/matplotlib/axes/_axes.py", line 4778, in fill_between
x = ma.masked_invalid(self.convert_xunits(x))
File "/home/usr/.virtualenvs/raiju/lib/python3.6/site-packages/numpy/ma/core.py", line 2388, in masked_invalid
condition = ~(np.isfinite(a))
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
</code></pre>
<p><em>Why is that happening and how to fix it?</em></p>
<p>Note that plotting the data (aka not using <code>fill*</code>) works just fine.</p>
| 0 | 1,333 |
Hibernate Exception - could not resolve property:
|
<p>I am trying to retrieve an object and its children. The request comes up with an exception.</p>
<p>Models - The staff class is a self reference class where the checker with a checker_id is also a staff. And also both the staff and checker has a one to many relationship with the module model.</p>
<pre><code> public class Staff implements Serializable,
@Id
@Column(name = "staff_id")
private String staffId;
@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="checker_id")
private Staff checker;
@OneToMany(mappedBy="checker", orphanRemoval=true, cascade = CascadeType.ALL)
private Set<Staff> setters = new HashSet<Staff>();
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="setter")
private Set<Module> sModule = new HashSet<Module>();
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="checker")
private Set<Module> cModule = new HashSet<Module>();
//getters and setters}
</code></pre>
<p>Module model</p>
<pre><code> public class Module implements Serializable{
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="staff_id", insertable=false, updatable=false)
private Staff setter;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="checker_id", insertable=false, updatable=false)
private Staff checker;
//getters and setters }
</code></pre>
<p>DAO code</p>
<pre><code> @Transactional
@SuppressWarnings("unchecked")
public Staff getWithModules(String staffId){
//Retrieve Staff
Criteria crit = getCurrentSession().createCriteria(Staff.class);
crit.add(Restrictions.eq("staffId", staffId));
Staff staff = get(crit);
//Retrieve the modules for the staff
crit = getCurrentSession().createCriteria(Module.class);
crit.add(Restrictions.eq("Staff.staffId", staffId));
crit.add(Restrictions.isNull("checkerId"));
crit.addOrder(Order.asc("moduleId"));
Set<Module> sModule = new LinkedHashSet<Module>(crit.list());
staff.setsModule(sModule);
//Set<Module> modules = new LinkedHashSet<Module>(crit.list());
//staff.setModules(modules);
return staff;
}
</code></pre>
<p>When I try to get any staff id and along with it the modules attached to it. I get this error in the stacktrace:</p>
<pre><code> org.hibernate.QueryException: could not resolve property: Staff of: com.project.professional.model.Module
org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:77)
org.hibernate.persister.entity.AbstractEntityPersister.getSubclassPropertyTableNumber(AbstractEntityPersister.java:1945)
org.hibernate.persister.entity.BasicEntityPropertyMapping.toColumns(BasicEntityPropertyMapping.java:61)
org.hibernate.persister.entity.AbstractEntityPersister.toColumns(AbstractEntityPersister.java:1920)
org.hibernate.loader.criteria.CriteriaQueryTranslator.getColumns(CriteriaQueryTranslator.java:523)
org.hibernate.loader.criteria.CriteriaQueryTranslator.findColumns(CriteriaQueryTranslator.java:538)
org.hibernate.criterion.SimpleExpression.toSqlString(SimpleExpression.java:66)
org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:419)
org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:123)
org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:92)
org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:95)
org.hibernate.internal.SessionImpl.list(SessionImpl.java:1602)
org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)
com.project.professional.dao.StaffDAO.getWithModules(StaffDAO.java:60)
com.project.professional.dao.StaffDAO$$FastClassByCGLIB$$d033d033.invoke(<generated>)
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
com.project.professional.dao.StaffDAO$$EnhancerByCGLIB$$58379429.getWithModules(<generated>)
com.project.professional.service.StaffServiceImpl.getWithModules(StaffServiceImpl.java:54)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
$Proxy46.getWithModules(Unknown Source)
com.project.professional.controller.StaffController.showStaffModules(StaffController.java:83)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
</code></pre>
<p>I would appreciate knowing what the problem is. </p>
| 0 | 3,201 |
free() invalid pointer
|
<p>I'm getting the familiar free(): invalid pointer error. In trying to debug, I ended up commenting out each free() in my code, one by one, <em>until there were none left</em> and I'm still getting this runtime error. Has anyone else run into a similar issue?</p>
<p>By the way - it's difficult for me to debug this using gdb, because the entire server doesn't actually crash when the error message is printed, just the particular forked process that was handling the single client.</p>
<p>Thank you.</p>
<pre><code>==============================
*** glibc detected *** ./server: free(): invalid pointer: 0x08641a38 ***
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(+0x6b961)[0xefe961]
/lib/i386-linux-gnu/libc.so.6(+0x6d28b)[0xf0028b]
/lib/i386-linux-gnu/libc.so.6(cfree+0x6d)[0xf0341d]
/usr/lib/i386-linux-gnu/libstdc++.so.6(_ZdlPv+0x21)[0x4c74d1]
./server[0x804b499]
./server[0x804b2ad]
./server[0x804aecd]
./server[0x804ad36]
./server[0x804a3a3]
/lib/i386-linux-gnu/libc.so.6(+0x2fa6f)[0xec2a6f]
/lib/i386-linux-gnu/libc.so.6(+0x2facf)[0xec2acf]
./server[0x804966b]
/lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xe7)[0xea9e37]
./server[0x8049331]
======= Memory map: ========
00338000-00352000 r-xp 00000000 08:01 394236 /lib/i386-linux-gnu/libgcc_s.so.1
00352000-00353000 r--p 00019000 08:01 394236 /lib/i386-linux-gnu/libgcc_s.so.1
00353000-00354000 rw-p 0001a000 08:01 394236 /lib/i386-linux-gnu/libgcc_s.so.1
003c1000-003c2000 r-xp 00000000 00:00 0 [vdso]
0041d000-004fc000 r-xp 00000000 08:01 792946 /usr/lib/i386-linux-gnu/libstdc++.so.6.0.14
004fc000-00500000 r--p 000de000 08:01 792946 /usr/lib/i386-linux-gnu/libstdc++.so.6.0.14
00500000-00501000 rw-p 000e2000 08:01 792946 /usr/lib/i386-linux-gnu/libstdc++.so.6.0.14
00501000-00508000 rw-p 00000000 00:00 0
00664000-00688000 r-xp 00000000 08:01 394245 /lib/i386-linux-gnu/libm-2.13.so
00688000-00689000 r--p 00023000 08:01 394245 /lib/i386-linux-gnu/libm-2.13.so
00689000-0068a000 rw-p 00024000 08:01 394245 /lib/i386-linux-gnu/libm-2.13.so
00793000-007af000 r-xp 00000000 08:01 394195 /lib/i386-linux-gnu/ld-2.13.so
007af000-007b0000 r--p 0001b000 08:01 394195 /lib/i386-linux-gnu/ld-2.13.so
007b0000-007b1000 rw-p 0001c000 08:01 394195 /lib/i386-linux-gnu/ld-2.13.so
00960000-0096a000 r-xp 00000000 08:01 394254 /lib/i386-linux-gnu/libnss_files-2.13.so
0096a000-0096b000 r--p 00009000 08:01 394254 /lib/i386-linux-gnu/libnss_files-2.13.so
0096b000-0096c000 rw-p 0000a000 08:01 394254 /lib/i386-linux-gnu/libnss_files-2.13.so
00e93000-00fed000 r-xp 00000000 08:01 394208 /lib/i386-linux-gnu/libc-2.13.so
00fed000-00fee000 ---p 0015a000 08:01 394208 /lib/i386-linux-gnu/libc-2.13.so
00fee000-00ff0000 r--p 0015a000 08:01 394208 /lib/i386-linux-gnu/libc-2.13.so
00ff0000-00ff1000 rw-p 0015c000 08:01 394208 /lib/i386-linux-gnu/libc-2.13.so
00ff1000-00ff4000 rw-p 00000000 00:00 0
08048000-08056000 r-xp 00000000 08:01 1084793 /home/mwrosen/cpe464/prog2/server
08056000-08057000 r--p 0000d000 08:01 1084793 /home/mwrosen/cpe464/prog2/server
08057000-08058000 rw-p 0000e000 08:01 1084793 /home/mwrosen/cpe464/prog2/server
08641000-08662000 rw-p 00000000 00:00 0 [heap]
b7600000-b7621000 rw-p 00000000 00:00 0
b7621000-b7700000 ---p 00000000 00:00 0
b7718000-b771b000 rw-p 00000000 00:00 0
b7729000-b772c000 rw-p 00000000 00:00 0
bfacf000-bfaf0000 rw-p 00000000 00:00 0 [stack]
</code></pre>
| 0 | 1,650 |
Unable to npm install Angular-cli after proxy configuration
|
<p>I am trying to download Angular in Windows 10 using npm install. As I am on corporate proxy, I configured the proxy to username:password@server:port</p>
<p>However, I am facing this issue when running</p>
<p><code>npm ERR! code E407
npm ERR! 407 Proxy Authorization Required: @angular/cli@latest</code></p>
<p>The debug log as followed:</p>
<pre><code>0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli '--proxy',
1 verbose cli 'http://XXXXX', //Removed my proxy details
1 verbose cli '--without-ssl',
1 verbose cli '--insecure',
1 verbose cli '-g',
1 verbose cli 'install',
1 verbose cli '@angular/cli' ]
2 info using npm@5.4.2
3 info using node@v8.8.1
4 verbose npm-session 40ab1dc3dabb6029
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 http fetch GET 407 http://registry.npmjs.org/@angular%2fcli 109ms
8 silly fetchPackageMetaData error for @angular/cli@latest 407 Proxy Authorization Required: @angular/cli@latest
9 verbose stack Error: 407 Proxy Authorization Required: @angular/cli@latest
9 verbose stack at fetch.then.res (C:\Program Files\nodejs\node_modules\npm\node_modules\pacote\lib\fetchers\registry\fetch.js:42:19)
9 verbose stack at tryCatcher (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)
9 verbose stack at Promise._settlePromiseFromHandler (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:512:31)
9 verbose stack at Promise._settlePromise (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:569:18)
9 verbose stack at Promise._settlePromise0 (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:614:10)
9 verbose stack at Promise._settlePromises (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:693:18)
9 verbose stack at Async._drainQueue (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:133:16)
9 verbose stack at Async._drainQueues (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:143:10)
9 verbose stack at Immediate.Async.drainQueues (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:17:14)
9 verbose stack at runCallback (timers.js:785:20)
9 verbose stack at tryOnImmediate (timers.js:747:5)
9 verbose stack at processImmediate [as _immediateCallback] (timers.js:718:5)
10 verbose cwd C:\Users\XXXXX
11 verbose Windows_NT 10.0.14393
12 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "--proxy" "http://XXXXX" "--without-ssl" "--insecure" "-g" "install" "@angular/cli"
13 verbose node v8.8.1
14 verbose npm v5.4.2
15 error code E407
16 error 407 Proxy Authorization Required: @angular/cli@latest
17 verbose exit [ 1, true ]
</code></pre>
<p>Any idea what could have cause the issue? Thanks!</p>
| 0 | 1,143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.