title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
Qlikview Macro VBScript to print pdf and email will not run consistently - Fails in email
|
<p>I have been tearing my hair out over the last few days in trying to get this macro to work consistantly on the Windows scheduler.</p>
<p>Basically the workflow is as follows:</p>
<p>1) Windows Scheduler - Daily, uses Admin user credentials</p>
<p>2) Batch file - Reloads using /l</p>
<p>3) Reloads Qlikview application, which has triggers on post reload to save a pdf and email it using PDF Xchange and an html formatted e-mail to cover mobile.</p>
<p>I am getting such inconsistent behaviour that I cannot isolate the problem to any particular one thing. Sometimes it works, sometimes it doesn't. More often than not it fails on the Windows scheduler. There is no error since QV has just thrown up the VBScript window in the hidden process.</p>
<p>I've been changing permissions, which helped me reach a level of inconsistent performance as opposed to no performance.</p>
<p>In addition, it appears that you cannot pass variables to the PDF Xchange printer.</p>
<p>The code in the macro is as follows:</p>
<pre><code>sub ExportPDF
printReportPDF "\\SGH-SRV-FPS1\S-Drive\eCommerce\Data Analyst\Reporting\Daily E-Commerce Report\E-Commerce Daily Report.pdf"
ActiveDocument.GetApplication.Sleep 2000
ActiveDocument.PrintReport "RP01", "PDF-XChange 3.0"
ActiveDocument.GetApplication.Sleep 8000
end sub
Function printReportPDF(pdfOutputFile)
Set WSHShell = CreateObject("WScript.Shell")
WSHShell.RegWrite "HKCU\Software\Tracker Software\PDF-XChange 3.0\OutputFile", pdfOutputFile, "REG_SZ"
WSHShell.RegWrite "HKCU\Software\Tracker Software\PDF-XChange 3.0\BypassSaveAs", "1", "REG_SZ"
Set WSHShell = nothing
End function
Sub ExportEmail
Dim strvDest 'as string
strvDest = ActiveDocument.Variables("vDestination").GetContent().String
msgbox(strvDestination)
Define report variables
get the date as a serial for the filename output
Export an Object
Set obj = ActiveDocument.ActiveSheet.SheetObjects("TX25")
Set obj1 = ActiveDocument.ActiveSheet.SheetObjects("TX17")
Set obj2 = ActiveDocument.ActiveSheet.SheetObjects("TX18")
Set obj3 = ActiveDocument.ActiveSheet.SheetObjects("TX15")
Set obj5 = ActiveDocument.ActiveSheet.SheetObjects("CH62")
Set obj6 = ActiveDocument.ActiveSheet.SheetObjects("TX16")
Set obj8 = ActiveDocument.ActiveSheet.SheetObjects("CH58")
Set obj9 = ActiveDocument.ActiveSheet.SheetObjects("TX31")
Set obj10 = ActiveDocument.ActiveSheet.SheetObjects("CH69")
msgbox("defined objects")
obj.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\MainLogo.jpg"
obj1.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\MainHeader.jpg"
obj2.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\DateRange.jpg"
obj3.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader.jpg"
obj5.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\DailySiteDetail.jpg"
obj6.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader2.jpg"
obj8.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\WeeklySiteDetail.jpg"
obj9.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader3.jpg"
obj10.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\WeeklySiteDetailLW.jpg"
msgbox("created objects")
Dim objEmail
Const cdoSendUsingPort = 2 Send the message using SMTP
Const cdoAnonymous = 0 Do not authenticate
Const cdoBasic = 1 basic (clear-text) authentication
Const cdoNTLM = 2 NTLM
Const SMTPServer = "xxxx" ' changed for public consumption
Const SMTPPort = 25 ' Port number for SMTP
Const SMTPTimeout = 120 ' Timeout for SMTP in seconds
Set objEmail = CreateObject("CDO.Message")
Set objConf = objEmail.Configuration
Set objFlds = objConf.Fields
With objFlds
βββββββββββββββββββββββ
SMTP server details
removed the html links down to this being my first post
.Update
βββββββββββββββββββββββ
End With
allow the passing of a variable from the load script to define the distribution list
if len(strvDest) > 0 then
msgbox("variable exists "&strvDest)
objEmail.To = strvDest
else
msgbox("variable does not exist")
objEmail.To = "xxxx" 'changed for public consumption
end if
objEmail.From = "xxxx" 'changed for public consumption
objEmail.Subject = "Daily Reporting"
HTML = "<!DOCTYPE HTML PUBLIC ""-//IETF//DTD HTML//EN"">" & chr(13) & chr(10)
HTML = HTML & "<html>"
HTML = HTML & "<head>"
HTML = HTML & "<meta http-equiv=""Content-Type"" content=""text/html; charset=iso-8859-1"">"
HTML = HTML & "<title>Automated Emails!</title>"
HTML = HTML & "</head>"
HTML = HTML & "<body bgcolor=""#FFFFFF"">"
HTML = HTML & "<br>&nbsp;&nbsp;&nbsp;<img src=""cid:MainLogo.jpg"" >"
HTML = HTML & "<br>&nbsp;&nbsp;&nbsp;<img src=""cid:MainHeader.jpg"" >"
HTML = HTML & "<br>&nbsp;&nbsp;&nbsp;<img src=""cid:DateRange.jpg"" >"
HTML = HTML & "<br>&nbsp;&nbsp;&nbsp;<img src=""cid:SecondaryHeader.jpg"" >"
HTML = HTML & "<br>&nbsp;&nbsp;&nbsp;<img src=""cid:DailySiteDetail.jpg"" >"
HTML = HTML & "<br>&nbsp;&nbsp;&nbsp;<img src=""cid:SecondaryHeader2.jpg"" >"
HTML = HTML & "<br>&nbsp;&nbsp;&nbsp;<img src=""cid:WeeklySiteDetail.jpg"" >"
HTML = HTML & "<br>&nbsp;&nbsp;&nbsp;<img src=""cid:SecondaryHeader3.jpg"" >"
HTML = HTML & "<br>&nbsp;&nbsp;&nbsp;<img src=""cid:WeeklySiteDetailLW.jpg"" >"
HTML = HTML & "<p>"
HTML = HTML & "</p>"
HTML = HTML & "</body>"
HTML = HTML & "</html>"
Set objBP = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\MainLogo.jpg", "MainLogo.jpg", CdoReferenceTypeName)
objBP.Fields.Item("urn:schemas:mailheader:Content-ID") = "<MainLogo.jpg>"
objBP.Fields.Update
Set objBP1 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\MainHeader.jpg", "MainHeader.jpg", CdoReferenceTypeName)
objBP1.Fields.Item("urn:schemas:mailheader:Content-ID") = "<MainHeader.jpg>"
objBP1.Fields.Update
Set objBP2 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\DateRange.jpg", "DateRange.jpg", CdoReferenceTypeName)
objBP2.Fields.Item("urn:schemas:mailheader:Content-ID") = "<DateRange.jpg>"
objBP2.Fields.Update
Set objBP3 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader.jpg", "SecondaryHeader.jpg", CdoReferenceTypeName)
objBP3.Fields.Item("urn:schemas:mailheader:Content-ID") = "<SecondaryHeader.jpg>"
objBP3.Fields.Update
Set objBP5 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\DailySiteDetail.jpg", "DailySiteDetail.jpg", CdoReferenceTypeName)
objBP5.Fields.Item("urn:schemas:mailheader:Content-ID") = "<DailySiteDetail.jpg>"
objBP5.Fields.Update
Set objBP6 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader2.jpg", "SecondaryHeader2.jpg", CdoReferenceTypeName)
objBP6.Fields.Item("urn:schemas:mailheader:Content-ID") = "<SecondaryHeader2.jpg>"
objBP6.Fields.Update
Set objBP8 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\WeeklySiteDetail.jpg", "WeeklySiteDetail.jpg", CdoReferenceTypeName)
objBP8.Fields.Item("urn:schemas:mailheader:Content-ID") = "<WeeklySiteDetail.jpg>"
objBP8.Fields.Update
Set objBP9 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader3.jpg", "SecondaryHeader3.jpg", CdoReferenceTypeName)
objBP9.Fields.Item("urn:schemas:mailheader:Content-ID") = "<SecondaryHeader3.jpg>"
objBP9.Fields.Update
Set objBP10 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\WeeklySiteDetailLW.jpg", "WeeklySiteDetailLW.jpg", CdoReferenceTypeName)
objBP10.Fields.Item("urn:schemas:mailheader:Content-ID") = "<WeeklySiteDetailLW.jpg>"
objBP10.Fields.Update
Set objBPDoc = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\Qlikview Printing.pdf", "Qlikview Printing.pdf", CdoReferenceTypeName)
objBPDoc.Fields.Item("urn:schemas:mailheader:Content-ID") = "<Qlikview Printing.pdf>"
objBPDoc.Fields.Update
objEmail.HTMLBody = HTML
msgbox("attached objects")
objEmail.Send
Set objFlds = Nothing
Set objConf = Nothing
Set objEmail = Nothing
ActiveDocument.Save
Application.Quit
</code></pre>
<p>End Sub </p>
| 0 | 3,351 |
How do I find why I get "Exception of type 'System.Web.HttpUnhandledException' was thrown"?
|
<p>I'm getting</p>
<pre><code>System.Web.HttpException
Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper'.
Stack is
at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage)
at System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm)
at System.Web.Mvc.ViewPage.RenderView(ViewContext viewContext)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
</code></pre>
<p>and inner exception is</p>
<pre><code>System.Web.HttpUnhandledException
Exception of type 'System.Web.HttpUnhandledException' was thrown.
Stack is
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.Mvc.ViewPage.ProcessRequest(HttpContext context)
at System.Web.Mvc.ViewUserControl.ViewUserControlContainerPage.ProcessRequest(HttpContext context)
at System.Web.Mvc.ViewPage.RenderView(ViewContext viewContext)
at System.Web.Mvc.ViewUserControl.RenderView(ViewContext viewContext)
at System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper htmlHelper, String partialViewName)
at ASP.views_mycontroller_myaction_aspx.__RendermyactionContent(HtmlTextWriter __w, Control parameterContainer)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at ASP.views_shared_my_master.__Render__control1(HtmlTextWriter __w, Control parameterContainer)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.Mvc.ViewPage.ProcessRequest(HttpContext context)
at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.<>c__DisplayClass4.<Wrap>b__3()
at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.Wrap[TResult](Func`1 func)
at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
</code></pre>
<p>I've seen similar stuff in many other questions and usually there's some more or less clear message from which the problem cause can be deduced.</p>
<p>In my case there's just <code>Exception of type 'System.Web.HttpUnhandledException' was thrown.</code></p>
<p>How do I extract additional information from that <code>HttpUnhandledException</code> to try find why it was thrown?</p>
| 0 | 1,166 |
How to set plot size in ggplot or ggarrange?
|
<p>I work with Rmarkdown and I am creating many figures composed of different ggplot2 charts, using ggarrange. The problem is that I am not able to set different sizes for figures inside a single chunk. The only way I managed to set figure size is within chunk options, like:</p>
<p>{r Figure1, fig.height = 4, fig.width = 7}</p>
<p>Is there a way of setting the plot/grid size within each ggplot() or within ggarrange() function?</p>
<p><strong>Details, data & code:</strong></p>
<p>All my primary plots have the same size of the grid area, but the size of the final figures changes depending on the number of primary plots they contain. In addition, for annotation purposes (e.g. with annotation_figures() function), charts in the first row must have a larger top margin (for the title), while charts in the last row must have a larger bottom margin (for captions). The extra margins, to make room for title and captions (e.g. text grobs) should not alter the plot grid size, which I want to be the same for all plots inside a figure.</p>
<p>One example of a dataframe called "A1" that I have:</p>
<pre><code>library("pacman")
p_load(ggplot2, ggpubr, hrbrthemes, tidyverse)
year <- rep(seq(2010,2019, 1), each=3)
name <- rep(c("A", "B", "C"), times=10)
n1 <- c(0,0,1,0,2,1,1,1,1,2,0,2,0,2,1,3,2,0,1,4,2,2,9,4,8,11,8,7,9,8)
n2 <- c(7,3,1,14,1,1, 15,4,4,19,9,4,26,9,4,46,4,3,52,12,3,37,12,5,45,10,5,47,18,4)
name2 <- name
A1 <-data.frame(year,name,n1,n2,name2)
</code></pre>
<p>With this data frame, I build the first row of plots inside a chunk with specifications {fig.height = 4.3, fig.width = 7}. This plot row has three plots (made with facet_wrap) and a top margin of 0.3 inches to make room for title annotation in the final figure, and no bottom margin. This plot row also has its own title, which will function like a subtitle or a tag in the final figure.</p>
<pre><code>AA.1 <- A1 %>%
ggplot( aes(x=year, y=n1)) +
geom_line( data=A1 %>% dplyr::select(-name), aes(group=name2), color="grey", size=1.0, alpha=0.6) +
geom_line( aes(color=name), color="black", size=1.5 ) +
theme_ipsum() +
theme(
axis.text.x = element_text(size=12, angle=45),
axis.text.y = element_text(size=12),
legend.position="none",
plot.title = element_text(size=16),
panel.grid = element_blank(),
plot.margin = unit(c(0.3, 0.2, 0, 0.2), "in")) + #Top row charts have a 0.3 top margin
labs(title="A. TAK") +
scale_x_continuous(name ="",
limits=c(2010,2019),
breaks=c(seq(2010,2019,2)))+
scale_y_continuous(name ="",
limits=c(0,12),
breaks=c(seq(0,12,3)))+
facet_wrap(~name) +
theme(strip.text = element_text(size=13))
AA.1
</code></pre>
<p>Then I create the bottom row plots, inside another chunk, with a different figure height specification: {fig.height = 4.1, fig.width = 7}. This row is also made of three plots, which should be similar in all aesthetics aspects to the first row, although I am plotting a different variable, with different values (ref). This row has no top margins and a 0.1 inches bottom margin, to make room for captions.</p>
<pre><code>AA.2 <- A1 %>%
ggplot( aes(x=year, y=n2)) +
geom_line( data=A1 %>% dplyr::select(-name), aes(group=name2), color="grey", size=1.0, alpha=0.6) +
geom_line( aes(color=name), color="black", size=1.5 )+
theme_ipsum() +
theme(
axis.text.x = element_text(size=12, angle=45),
axis.text.y = element_text(size=12),
legend.position="none",
plot.title = element_text(size=16),
panel.grid = element_blank(),
plot.margin = unit(c(0, 0.2, 0.1, 0.2), "in")) + #Margins are different
ggtitle("B. REF") +
scale_x_continuous(name ="",
limits=c(2010,2019),
breaks=c(seq(2010,2019,2)))+
scale_y_continuous(name ="",
limits=c(0,60),
breaks=c(seq(0,60,10)))+
facet_wrap(~name) +
theme(strip.text = element_text(size=13))
AA.2
</code></pre>
<p>Finally, I arrange both sets of plots within a figure using ggarange(), and write the final title and captions with annotate_figure(). In this chunk, I set the total fig.height to 8.4 (the sum of two previous chunks).</p>
<pre><code>
figureA1 <- ggarrange(AA.1, AA.2,
ncol=1, nrow=2,
heights=c(1,1))
annotate_figure(
figureA1,
top = text_grob("Figura A.1 - TAK & REF",
color = "black", face = "bold", size = 18),
bottom = text_grob("Source: My.Data (2020)", face="italic", color = "black",
hjust = 1, x = 1, size = 12),)
</code></pre>
<p><strong>Possible solutions:</strong></p>
<ol>
<li><p>I would like that each plot had a total plot grid area of 4 inches. As the first plot has a top margin of 0.3 and a bottom margin of 0, I set fig.height to 4.3. As the second plot has a top margin of 0 and a bottom margin of 0.1, I set fig.height to 0.1. However, the plot grid area does not seem to be of the same size in both plots. Any ideas on how to fix this?</p>
</li>
<li><p>As the fig.height parameters are different for each plot, I need to split the code to build a figure into different chunks. I have many figures that are made in a similar fashion, and therefore, I would like to write a function to build and arrange plots within figures. However, I cannot write a function across different chunks.</p>
</li>
</ol>
<p>I think of two possible solutions for this second problem:</p>
<ol>
<li>Some way of setting the grid plot size within ggplot function (or the total plot area); or</li>
<li>Some way of setting each of the grid plots sizes within the ggarrange function;</li>
</ol>
<p>Anyone has an idea of how can I do that?</p>
<p>Perhaps the second would be even better. I tried to set the heights of the rows in ggarrange to be the same with the same, with heights argument ("heights=c(1,1)"). Also tried to make them proportional to each fig.height ("heights=c(5.3/5.1,1)"), but the second plot row grid still looks taller than the first one.</p>
<p><a href="https://i.stack.imgur.com/Y9ZPQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y9ZPQ.png" alt="FigureA1 - heights=c(5.3/5.1,1" /></a></p>
| 0 | 2,654 |
Hibernate Query Syntax exception : org.hibernate.hql.ast.QuerySyntaxException: unexpected token
|
<p>I have a query where i am joining two tables ROuteMaster and RouteHalts.
When i perform inner join i am getting </p>
<pre><code>org.hibernate.hql.ast.QuerySyntaxException: unexpected token: on near line 1,
column 169 [SELECT rm.id , rm.routeCode , rm.startPlaceId , rm.endPlaceId ,
rm.active, rm.linkedRoute FROM com.oprs.pojo.routes.RouteMaster rm INNER JOIN
RouteHalts rh on rm.id = rh.routeId WHERE rh.placeId = :PlaceId
ORDER BY rm.id ASC]
</code></pre>
<p>I searched through the site and found similar question and the response for it. the question referred was</p>
<pre><code>Hibernate: org.hibernate.hql.ast.QuerySyntaxException: unexpected token
</code></pre>
<p>I have many-to-one mapping in RouteHalts for RouteMaster, I have defined getter and setter methods for RouteMaster in RouteHalts</p>
<pre><code><many-to-one name="RouteMaster" class="com.oprs.pojo.routes.RouteMaster"
fetch="join"
foreign-key="id" column="ROUTE_ID" insert="false"
update="false" lazy="false" />
</code></pre>
<p>but still getting the same error. Can please some one guide me.</p>
<p>Mapping files</p>
<pre><code><hibernate-mapping package="com.oprs.pojo.routes">
<!-- Hibernate mapping for RouteMaster table -->
<class name="RouteMaster" table="OPRS_ROUTE_MASTER">
<id name="id" column="ROUTE_ID" type="java.lang.Long">
<generator class="assigned" />
</id>
<property name="startPlaceId" column="START_PLACE_ID"/>
<property name="endPlaceId" column="END_PLACE_ID"/>
<property name="routeCode" column="ROUTE_CODE"/>
<property name="routeName" column="ROUTE_NAME"/>
<property name="active" column="IS_ACTIVE"/>
<property name="linkedRoute" column="LINKED_ROUTE"/>
<property name="returnRouteId" column="RET_ROUTE_ID"/>
<!-- Auditor Information -->
<component name="auditor" class="com.oprs.pojo.base.Auditor">
<property name="createdBy" column="CREATED_BY" />
<property name="createdDate" column="CREATED_DATE" />
<property name="modifiedBy" column="MODIFIED_BY" />
<property name="modifiedDate" column="MODIFIED_DATE" />
</component>
<many-to-one name="RouteHalts" class="com.oprs.pojo.routes.RouteHalts" fetch="join"
foreign-key="routeId" column="ROUTE_ID" insert="false"
update="false" lazy="false" />
</class>
<!-- Hibernate mapping for RouteHalts table -->
<class name="RouteHalts" table="OPRS_ROUTE_HALTS">
<id name="id" column="HALTS_ID" type="java.lang.Long">
<generator class="assigned" />
</id>
<property name="routeId" column="ROUTE_ID"/>
<property name="placeId" column="PLACE_ID"/>
<property name="seqNo" column="SEQ_NO"/>
<property name="distanceKM" column="DISTANCE_KM"/>
<property name="border" column="IS_BORDER"/>
<property name="tolls" column="NO_OF_TOLLS"/>
<!-- Auditor Information -->
<component name="auditor" class="com.oprs.pojo.base.Auditor">
<property name="createdBy" column="CREATED_BY" />
<property name="createdDate" column="CREATED_DATE" />
<property name="modifiedBy" column="MODIFIED_BY" />
<property name="modifiedDate" column="MODIFIED_DATE" />
</component>
</class>
POJO of Route Master
</code></pre>
<p>public class RouteMaster extends Persistent {</p>
<pre><code>private static final long serialVersionUID = -5710336066048392949L;
private Long startPlaceId;
private Long endPlaceId;
private Long returnRouteId;
private String startPlaceCode;
private String endPlaceCode;
private String startPlaceName;
private String endPlaceName;
private String routeCode;
private String routeName;
private String active;
private Auditor auditor;
private boolean revervseRoute;
private String linkedRoute = AppConstants.N;
private Map<Double, RouteHalts> haltsMap;
private RouteHalts routeHalts;
public RouteHalts getRouteHalts() {
return routeHalts;
}
public void setRouteHalts(RouteHalts routeHalts) {
this.routeHalts = routeHalts;
}
public Long getStartPlaceId() {
return startPlaceId;
}
public void setStartPlaceId(Long startPlaceId) {
this.startPlaceId = startPlaceId;
}
public Long getEndPlaceId() {
return endPlaceId;
}
public void setEndPlaceId(Long endPlaceId) {
this.endPlaceId = endPlaceId;
}
public String getStartPlaceCode() {
return startPlaceCode;
}
public void setStartPlaceCode(String startPlaceCode) {
this.startPlaceCode = startPlaceCode;
}
public String getEndPlaceCode() {
return endPlaceCode;
}
public void setEndPlaceCode(String endPlaceCode) {
this.endPlaceCode = endPlaceCode;
}
public Long getReturnRouteId() {
return returnRouteId;
}
public void setReturnRouteId(Long returnRouteId) {
this.returnRouteId = returnRouteId;
}
public String getRouteCode() {
return routeCode;
}
public void setRouteCode(String routeCode) {
this.routeCode = routeCode;
}
public Auditor getAuditor() {
return auditor;
}
public void setAuditor(Auditor auditor) {
this.auditor = auditor;
}
public String getStartPlaceName() {
return startPlaceName;
}
public void setStartPlaceName(String startPlaceName) {
this.startPlaceName = startPlaceName;
}
public String getEndPlaceName() {
return endPlaceName;
}
public void setEndPlaceName(String endPlaceName) {
this.endPlaceName = endPlaceName;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public Map<Double, RouteHalts> getHaltsMap() {
return haltsMap;
}
public void setHaltsMap(Map<Double, RouteHalts> haltsMap) {
this.haltsMap = haltsMap;
}
public boolean isRevervseRoute() {
return revervseRoute;
}
public void setRevervseRoute(boolean revervseRoute) {
this.revervseRoute = revervseRoute;
}
public String getLinkedRoute() {
return linkedRoute;
}
public void setLinkedRoute(String linkedRoute) {
this.linkedRoute = linkedRoute;
}
public String getRouteName() {
return routeName;
}
public void setRouteName(String routeName) {
this.routeName = routeName;
}
</code></pre>
<p>}</p>
<pre><code>POJO of RouteHalts
</code></pre>
<p>public class RouteHalts extends Persistent {</p>
<pre><code>private static final long serialVersionUID = -1491637903595290895L;
private Long placeId;
private Long routeId;
private String placeCode;
private Double seqNo;
private Double distanceKM;
private boolean border;
private Auditor auditor;
private String placeName;
private String stateCode;
private String stopType;
private String departureTime;
private Integer tolls;
private String platformNo;
private Long stopTypeId;
private Integer linkSequenceNo;
private String actualTime;
private int arrivalDay;
public String getStateCode() {
return stateCode;
}
public void setStateCode(String stateCode) {
this.stateCode = stateCode;
}
public Long getRouteId() {
return routeId;
}
public void setRouteId(Long routeId) {
this.routeId = routeId;
}
public Long getPlaceId() {
return placeId;
}
public void setPlaceId(Long placeId) {
this.placeId = placeId;
}
public String getPlaceCode() {
return placeCode;
}
public void setPlaceCode(String placeCode) {
this.placeCode = placeCode;
}
public Double getDistanceKM() {
return distanceKM;
}
public void setDistanceKM(Double distanceKM) {
this.distanceKM = distanceKM;
}
public boolean isBorder() {
return border;
}
public void setBorder(boolean border) {
this.border = border;
}
public Auditor getAuditor() {
return auditor;
}
public void setAuditor(Auditor auditor) {
this.auditor = auditor;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public Double getSeqNo() {
return seqNo;
}
public void setSeqNo(Double seqNo) {
this.seqNo = seqNo;
}
public String getStopType() {
return stopType;
}
public void setStopType(String stopType) {
this.stopType = stopType;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public Integer getTolls() {
return tolls;
}
public void setTolls(Integer tolls) {
this.tolls = tolls;
}
public String getPlatformNo() {
return platformNo;
}
public void setPlatformNo(String platformNo) {
this.platformNo = platformNo;
}
public Long getStopTypeId() {
return stopTypeId;
}
public void setStopTypeId(Long stopTypeId) {
this.stopTypeId = stopTypeId;
}
public Integer getLinkSequenceNo() {
return linkSequenceNo;
}
public void setLinkSequenceNo(Integer linkSequenceNo) {
this.linkSequenceNo = linkSequenceNo;
}
public int getArrivalDay() {
return arrivalDay;
}
public void setArrivalDay(int arrivalDay) {
this.arrivalDay = arrivalDay;
}
public String getActualTime() {
return actualTime;
}
public void setActualTime(String actualTime) {
this.actualTime = actualTime;
}
</code></pre>
<p>}</p>
| 0 | 3,586 |
Cant get value of hidden field after ajax Jquery
|
<p>I have a page that when a link is clicked it opens a pop up box to insert new charges. When this pop up box opens I use jquery load() function to insert a table with all the current charges (loaded from mysql) from a script on another page called load_charges.php. </p>
<p>The problem I am having is I can not access any of the hidden values from the content I just loaded I use: </p>
<pre><code>var charge_id = $(':hidden:first', $(this)).val();
</code></pre>
<p>this normally gets me the value of the first hidden element but it does not work if I am trying get the info from the page load from load_charges.php. I will list my code below:</p>
<p>case_cpanel.php:</p>
<p>//HTML Table with Form elememt</p>
<pre><code><table>
<tr class="lead_hover">
<td>
<form class="calc" title="Case Expense Calculator" style="cursor:pointer;">
<input type="hidden" id="lead_id" value="21946295" />
<input type="hidden" id="final_id" value="74" />
<input name="order" type="hidden" id="final_id" value="3" />
</form>
</td>
</tr>
<tr class="lead_hover">
<td>
<form class="calc" title="Case Expense Calculator" style="cursor:pointer;">
<input type="hidden" id="lead_id" value="21978679" />
<input type="hidden" id="final_id" value="79" />
<input name="order" type="hidden" id="final_id" value="1" />
</form>
</td>
</tr>
</table>
</code></pre>
<p>// Jquery to load popup form box</p>
<pre><code>$(".calc").click(function () {
var value = $(':hidden:eq(0)', $(this)).val();
$('input[name=lead_id]').val(value);
var value = $(':hidden:eq(1)', $(this)).val();
$('input[name=final_id]').val(value);
var value = $(':hidden:eq(2)', $(this)).val();
$('.order').val(value);
var lead_id = $(':hidden:eq(0)', $(this)).val();
var string1 = "token=<? echo $_SESSION['token']; ?>&lead_id=";
var url = "../ajax/load_charges.php";
var datastring = string1.concat(lead_id);
$('#calc_right_display').html('<div><img src="../imgs/loading4.gif" align="center" /></div>').load(url, datastring).show();
$("#calc_div").overlay().load();
});
</code></pre>
<p><strong>load_charges.php:</strong>
// table that is load with new form elements</p>
<pre><code><table width="266" border="0" cellpadding="5">
<? do { ?>
<tr>
<td width="163">
<? echo $row_charges[ 'rows'][ 'title']; ?>
</td>
<td width="83">$
<? echo $row_charges[ 'rows'][ 'charge']; ?>
</td>
<td width="27">
<form class="delete_charge" title="Delete Charge" style="cursor:pointer;">
<input type="hidden" id="id1" value "<? echo $row_charges['rows']['id']; ?>">
</form>
</td>
</tr>
<? } while ($row_charges[ 'rows']=m ysql_fetch_assoc($row_charges[ 'query'])); ?>
</table>
</code></pre>
<p>//Jquery Code on load_charges.php</p>
<pre><code><script>
$(".delete_charge").click(function () { * *
var charge_id = $(':hidden:first', $(this)).val(); * *
var str2 = "token=<? echo $_REQUEST['token']; ?>&delete_charge=true&id=";
var str_lead_id = "&lead_id=<? echo $_REQUEST['lead_id']; ?>";
var url2 = "../ajax/cm_expenses_delete.php";
var datastring2 = str2.concat(charge_id, str_lead_id);
$('#calc_right_display').html('<div><img src="../imgs/loading4.gif" align="center" /></div>').load(url2, datastring2).show();
});
</script>
</code></pre>
<p>The problem is var charge_id = $(':hidden:first', $(this)).val(); is not returning any value from the new page that just loaded. Any Help would be greatly appreciated.</p>
<p>Thank you in advance.
Ryan </p>
| 0 | 1,841 |
How to do instancing the right way in OpenGL.
|
<p>I am trying to use VBO and Instancing mechanism the most efficent way. I have a world based on voxels and I would like to draw them using least possible number of draw-calls. The code below prepares VBO with a quad: </p>
<pre><code>void VoxelView::initVBOs() {
/*--------------------- Main OpenGL Program ---------------------*/
/* Vertices of a triangle (counter-clockwise winding) */
float data[6][3] = {
// Left bottom triangle
{ -0.5f, 0.5f, 0.0f },
{ -0.5f, -0.5f, 0.0f },
{ 0.5f, -0.5f, 0.0f },
// Right top triangle
{ 0.5f, -0.5f, 0.0f },
{ 0.5f, 0.5f, 0.0f },
{ -0.5f, 0.5f, 0.0f }
};
/*---------------------- Initialise VBO - (Note: do only once, at start of program) ---------------------*/
/* Create a new VBO and use the variable "triangleVBO" to store the VBO id */
glGenBuffers(1, &triangleVBO);
/* Make the new VBO active */
glBindBuffer(GL_ARRAY_BUFFER, triangleVBO);
/* Upload vertex data to the video device */
glBufferData(GL_ARRAY_BUFFER, 6 * 3 * sizeof(float), data, GL_STATIC_DRAW);
/* Specify that our coordinate data is going into attribute index 0(shaderAttribute), and contains three floats per vertex */
glVertexAttribPointer(shaderAttribute, 3, GL_FLOAT, GL_FALSE, 0, 0);
/* Enable attribute index 0(shaderAttribute) as being used */
glEnableVertexAttribArray(shaderAttribute);
/* Make the new VBO active. */
glBindBuffer(GL_ARRAY_BUFFER, triangleVBO);
/*-------------------------------------------------------------------------------------------------------*/
/*--------------------- Load Vertex and Fragment shaders from files and compile them --------------------*/
/* Read our shaders into the appropriate buffers */
vertexSource = filetobuf("Shaders/exampleVertexShader1.vert");
fragmentSource = filetobuf("Shaders/exampleFragmentShader1.frag");
/* Assign our handles a "name" to new shader objects */
vertexShader = glCreateShader(GL_VERTEX_SHADER);
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
/* Associate the source code buffers with each handle */
glShaderSource(vertexShader, 1, (const GLchar**)&vertexSource, 0);
glShaderSource(fragmentShader, 1, (const GLchar**)&fragmentSource, 0);
/* Free the temporary allocated memory */
free(vertexSource);
free(fragmentSource);
/* Compile our shader objects */
glCompileShader(vertexShader);
glCompileShader(fragmentShader);
/*-------------------------------------------------------------------------------------------------------*/
/*-------------------- Create shader program, attach shaders to it and then link it ---------------------*/
/* Assign our program handle a "name" */
shaderProgram = glCreateProgram();
/* Attach our shaders to our program */
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
/* Bind attribute index 0 (shaderAttribute) to in_Position*/
/* "in_Position" will represent "data" array's contents in the vertex shader */
glBindAttribLocation(shaderProgram, shaderAttribute, "in_Position");
/* Link shader program*/
glLinkProgram(shaderProgram);
</code></pre>
<p>I am rendering the quad the following way: </p>
<pre><code>void VoxelView::renderVBO()
{
/* Set shader program as being actively used */
glUseProgram(shaderProgram);
/* Set background colour to BLACK */
glClearColor(0.0, 0.0, 0.0, 1.0);
/* Clear background with BLACK colour */
glClear(GL_COLOR_BUFFER_BIT);
/* Actually draw the triangle, giving the number of vertices provided by invoke glDrawArrays
while telling that our data is a triangle and we want to draw 0-3 vertexes
*/
glDrawArrays(GL_TRIANGLES, 0, 6);
}
</code></pre>
<p>I would like to draw this quad (which uses VBO) multiple times using the instancing mechanizm. I would like it to fe fairly simple as I want to implement it for more sophisticated code. I know that I should use <strong>glDrawElementsInstanced</strong> method to use instancing but I don't know how to do it. Does anybody know how to do it?</p>
| 0 | 1,580 |
Is it intended by the C++ standards committee that in C++11 unordered_map destroys what it inserts?
|
<p>I've just lost three days of my life tracking down a very strange bug where unordered_map::insert() destroys the variable you insert. This highly non-obvious behaviour occurs in very recent compilers only: I found that clang 3.2-3.4 and GCC 4.8 are the <strong>only</strong> compilers to demonstrate this "feature".</p>
<p>Here's some reduced code from my main code base which demonstrates the issue:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <memory>
#include <unordered_map>
#include <iostream>
int main(void)
{
std::unordered_map<int, std::shared_ptr<int>> map;
auto a(std::make_pair(5, std::make_shared<int>(5)));
std::cout << "a.second is " << a.second.get() << std::endl;
map.insert(a); // Note we are NOT doing insert(std::move(a))
std::cout << "a.second is now " << a.second.get() << std::endl;
return 0;
}
</code></pre>
<p>I, like probably most C++ programmers, would expect output to look something like this:</p>
<pre><code>a.second is 0x8c14048
a.second is now 0x8c14048
</code></pre>
<p>But with clang 3.2-3.4 and GCC 4.8 I get this instead:</p>
<pre><code>a.second is 0xe03088
a.second is now 0
</code></pre>
<p>Which might make no sense, until you examine closely the docs for unordered_map::insert() at <a href="http://www.cplusplus.com/reference/unordered_map/unordered_map/insert/" rel="noreferrer">http://www.cplusplus.com/reference/unordered_map/unordered_map/insert/</a> where overload no 2 is:</p>
<pre class="lang-cpp prettyprint-override"><code>template <class P> pair<iterator,bool> insert ( P&& val );
</code></pre>
<p>Which is a greedy universal reference move overload, consuming anything not matching any of the other overloads, and <em>move constructing</em> it into a value_type. So why did our code above choose this overload, and not the unordered_map::value_type overload as probably most would expect?</p>
<p>The answer stares you in the face: unordered_map::value_type is a pair<<em>const</em> int, std::shared_ptr> and the compiler would correctly think that a pair<<em>int</em>, std::shared_ptr> isn't convertible. Therefore the compiler chooses the move universal reference overload, and that destroys the original, <strong>despite</strong> the programmer not using std::move() which is the typical convention for indicating you are okay with a variable getting destroyed. Therefore the insert destroying behaviour is in fact <em>correct</em> as per the C++11 standard, and older compilers were <em>incorrect</em>.</p>
<p>You can probably see now why I took three days to diagnose this bug. It was not at all obvious in a large code base where the type being inserted into unordered_map was a typedef defined far away in source code terms, and it never occurred to anyone to check if the typedef was identical to value_type.</p>
<p>So my questions to Stack Overflow:</p>
<ol>
<li><p>Why do older compilers not destroy variables inserted like newer compilers? I mean, even GCC 4.7 doesn't do this, and it's pretty standards conforming.</p></li>
<li><p>Is this problem widely known, because surely upgrading compilers will cause code which used to work to suddenly stop working?</p></li>
<li><p>Did the C++ standards committee intend this behaviour?</p></li>
<li><p>How would you suggest that unordered_map::insert() be modified to give better behaviour? I ask this because if there is support here, I intend to submit this behaviour as a N note to WG21 and ask them to implement a better behaviour.</p></li>
</ol>
| 0 | 1,125 |
How To Use List Adapter
|
<p>My app displays information from a database in a ListView. </p>
<p>In the ListView, there is also a VideoView which is supposed to load and play a video from my website.</p>
<p>In a separate app with only this function, I got it to work. The difference is that in the working app the videoview is located IN the <em>activity_main.xml</em> file, whereas in my new app, the videoview is located in a separate list_item.xml file which is loaded into activity_main.xml as a ListView.</p>
<p>I was told by another stack overflow user that because the VideoView is not in activity_main.xml, I'd have to create a ListAdapter and have the getView() method of the list adapter reference my list_item.xml layout file.</p>
<p>I found a tutorial on ListAdapters but it seemed that the context was too different from what I'm trying to achieve for me to be able to adapt it to my use.</p>
<p>Can someone help me understand how I might go about implementing a ListAdapter that would work with my current code?</p>
<p>Thanks in advance, I really appreciate the help.</p>
<p><strong>BELOW ARE MY FILES</strong></p>
<p><strong>activity_main.xml:</strong></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="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(@android:id/list)
-->
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</code></pre>
<p><strong>list_item.xml:</strong></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" >
<!-- Name Label -->
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:textStyle="bold" />
<VideoView
android:id="@+id/videoView"
android:layout_width="100dp"
android:layout_height="100dp"
/>
<ImageButton
android:id="@+id/imageButton2"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="@drawable/ic_videobutton"
android:onClick="sendMessage" />
</LinearLayout>
</code></pre>
<p><strong>AllProductsActivity.java:</strong></p>
<pre><code>package com.example.androidhive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.VideoView;
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// get video url
private static final String MOVIE_URL ="http://mywebsite.com/mycameraapp/android_connect/videos/testvideo.mkv";
// url to get all products list
private static String url_all_products = "http://mywebsite.com/mycameraapp/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// **MY VIDEOVIEW CODE THAT DOESN'T WORK BECAUSE THIS VIDEOVIEW IS IN list_item.xml**
VideoView vid = (VideoView) findViewById(R.id.videoView);
Uri video = Uri.parse(MOVIE_URL);
vid.setMediaController(new MediaController(this));
vid.setVideoURI(video);
vid.start();
vid.requestFocus();
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
/** CALLED WHEN THE USER CLICKS THE RECORD BUTTON */
public void sendMessage(View view) {
Intent videoIntent = new Intent(this, PhotoIntentActivity.class);
startActivity(videoIntent);
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String description = c.getString(TAG_DESCRIPTION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_DESCRIPTION, description);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID, TAG_NAME, TAG_DESCRIPTION},
new int[] { R.id.pid, R.id.name, R.id.description });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
</code></pre>
| 0 | 3,890 |
Trying to return the value from std::variant using std::visit and a lambda expression
|
<p>Suppose there exists a variant v defined as follows:</p>
<pre><code>std::variant<int,char,double,bool,std::string> v;
</code></pre>
<p>I am trying to get the underlying value from a std::variant using std::visit or std::get.</p>
<p>I tried doing this naively:</p>
<pre><code>constexpr size_t idx = v.index();
auto k = std::get<idx>(v);
</code></pre>
<p>But then learned that this will fail if the variant v is not a constexpr itself. And even then there may be problems with using std::string (due to the definition of the destructor for std::string).</p>
<p>My 2nd attempt was to try and do the following:</p>
<pre><code>auto k = std::visit([](auto arg){return arg;}, v);
</code></pre>
<p>But received this:</p>
<pre><code>$g++ -o main *.cpp --std=c++17
In file included from main.cpp:5:0:
/usr/include/c++/7/variant: In instantiation of βstatic constexpr auto std::__detail::__variant::__gen_vtable_impl<std::__detail::__variant::_Multi_array<_Result_type (*)(_Visitor, _Variants ...)>, std::tuple<_Tail ...>, std::integer_sequence<long unsigned int, __indices ...> >::_S_apply() [with _Result_type = int; _Visitor = main()::<lambda(auto:1)>&&; _Variants = {std::variant<int, char, double, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&}; long unsigned int ...__indices = {1}]β:
/usr/include/c++/7/variant:663:61: required from βstatic constexpr void std::__detail::__variant::__gen_vtable_impl<std::__detail::__variant::_Multi_array<_Result_type (*)(_Visitor, _Variants ...), __dimensions ...>, std::tuple<_Variants ...>, std::integer_sequence<long unsigned int, __indices ...> >::_S_apply_single_alt(_Tp&) [with long unsigned int __index = 1; _Tp = std::__detail::__variant::_Multi_array<int (*)(main()::<lambda(auto:1)>&&, std::variant<int, char, double, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&)>; _Result_type = int; _Visitor = main()::<lambda(auto:1)>&&; long unsigned int ...__dimensions = {5}; _Variants = {std::variant<int, char, double, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&}; long unsigned int ...__indices = {}]β
/usr/include/c++/7/variant:651:39: required from βconstexpr const std::__detail::__variant::_Multi_array<int (*)(main()::<lambda(auto:1)>&&, std::variant<int, char, double, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&), 5> std::__detail::__variant::__gen_vtable<int, main()::<lambda(auto:1)>&&, std::variant<int, char, double, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&>::_S_vtableβ
/usr/include/c++/7/variant:704:29: required from βstruct std::__detail::__variant::__gen_vtable<int, main()::<lambda(auto:1)>&&, std::variant<int, char, double, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&>β
/usr/include/c++/7/variant:1239:23: required from βconstexpr decltype(auto) std::visit(_Visitor&&, _Variants&& ...) [with _Visitor = main()::<lambda(auto:1)>; _Variants = {std::variant<int, char, double, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&}]β
main.cpp:89:49: required from here
/usr/include/c++/7/variant:704:49: in constexpr expansion of βstd::__detail::__variant::__gen_vtable<int, main()::<lambda(auto:1)>&&, std::variant<int, char, double, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&>::_S_apply()β
/usr/include/c++/7/variant:701:38: in constexpr expansion of βstd::__detail::__variant::__gen_vtable_impl<std::__detail::__variant::_Multi_array<int (*)(main()::<lambda(auto:1)>&&, std::variant<int, char, double, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&), 5>, std::tuple<std::variant<int, char, double, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&>, std::integer_sequence<long unsigned int> >::_S_apply()β
/usr/include/c++/7/variant:641:19: in constexpr expansion of βstd::__detail::__variant::__gen_vtable_impl<std::__detail::__variant::_Multi_array<int (*)(main()::<lambda(auto:1)>&&, std::variant<int, char, double, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&), 5>, std::tuple<std::variant<int, char, double, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&>, std::integer_sequence<long unsigned int> >::_S_apply_all_alts<0, 1, 2, 3, 4>(\xe2\x80\x98result_dec\xe2\x80\x99 not supported by dump_expr#<expression error>, (std::make_index_sequence<5>(), std::make_index_sequence<5>()))β
/usr/include/c++/7/variant:686:43: error: invalid conversion from βstd::__success_type<char>::type (*)(main()::<lambda(auto:1)>&&, std::variant<int, char, double, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&) {aka char (*)(main()::<lambda(auto:1)>&&, std::variant<int, char, double, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&)}β to βint (*)(main()::<lambda(auto:1)>&&, std::variant<int, char, double, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&)β [-fpermissive]
{ return _Array_type{&__visit_invoke}; }
^
</code></pre>
<p>I'm stuck as to why the std::visit call does not work. I thought I supplied a trivial lambda expression which takes all possible types for the variant and returns the underlying value but it appears I am misunderstanding something.</p>
<p>I want to use std::variant now (after initially considering std::any (see <a href="https://stackoverflow.com/questions/52085547/avoid-writing-the-same-repetitive-type-checking-code-with-stdany">avoid writing the same repetitive type-checking code with std::any</a>) but I need a way to return the contained value. Any help would be greatly appreciated. Thank you very much.</p>
| 0 | 2,791 |
C socket client
|
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(const char *msg) {
perror(msg);
exit(0);
}
int main(int argc, char *argv[]) {
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc < 3) {
fprintf(stderr, "usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr, "ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof (serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *) server->h_addr,
(char *) &serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof (serv_addr)) < 0) error("ERROR connecting");
while (1) {
printf("Please enter the message: ");
bzero(buffer, 256);
fgets(buffer, 255, stdin);
// n = write(sockfd, buffer, strlen(buffer));
n = send(sockfd, buffer, strlen(buffer), 0);
if (n < 0) error("ERROR writing to socket");
bzero(buffer, 256);
// n = read(sockfd, buffer, 255);
n = recv(sockfd, buffer, 255, 0);
if (n < 0) error("ERROR reading from socket");
printf("%s\n", buffer);
}
close(sockfd);
return 0;
}
</code></pre>
<p>The code shown above works only at the first iteration. However, At second iteration it blocks at <code>recv()</code> or <code>read()</code>.</p>
<p>Could someone please explain the reason for this behaviour? </p>
<p><strong>Update:</strong> here is the server code (not the one I'm using, but the same principles) and it works like the one I mentioned above:</p>
<pre><code>/* A simple server in the internet domain using TCP
The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
void error(const char *msg) {
perror(msg);
exit(1);
}
int main(int argc, char *argv[]) {
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr, "ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
memset((char*) &serv_addr, 0, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof (serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd, 5);
clilen = sizeof (cli_addr);
while (1) {
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
error("ERROR on accept");
memset(buffer, 0, sizeof(buffer));
n = read(newsockfd, buffer, 255);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n", buffer);
n = write(newsockfd, "I got your message", 18);
if (n < 0) error("ERROR writing to socket");
}
close(newsockfd);
close(sockfd);
return 0;
}
</code></pre>
| 0 | 1,739 |
recording and saving audio on Android
|
<p>I'm developing an android (2.2) app to record audio. The code seems to run fine and even saves the files on the SD Card, but when I try and play the audio files on my Mac nothing happens. Almost like the files are empty. I've tried saving them as .mp3 and .wav but no luck. My code is below:</p>
<pre><code>import java.io.File;
import java.io.IOException;
import android.media.MediaRecorder;
import android.os.Environment;
public class AudioRecorder {
private MediaRecorder recorder = new MediaRecorder();
private File outfile = null;
public AudioRecorder(){}
public void startRecording(String audioFile) throws IOException {
String state = android.os.Environment.getExternalStorageState();
if(!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
throw new IOException("SD Card is not mounted. It is " + state + ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
try{
File storageDir = new File(Environment
.getExternalStorageDirectory(), "/audio/");
storageDir.mkdir();
outfile=File.createTempFile(audioFile, ".wav",storageDir);
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(outfile.getAbsolutePath());
}catch(IOException e){
e.printStackTrace();
}
try{
recorder.prepare();
}catch(IllegalStateException e){
e.printStackTrace();
}
recorder.start();
}
public void stop() throws IOException {
recorder.stop();
recorder.release();
}
}
</code></pre>
<p>My Activity:</p>
<pre><code>/**
* Recording Activity
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.seekika.android.app.helpers.AudioRecorder;
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
public class Record extends Activity {
private static final String TAG="RecordActivity";
private int SETTINGS=Menu.FIRST;
private int LOGOUT=Menu.FIRST + 1;
private int EXIT=Menu.FIRST + 2;
//components
private Button mBtnStartRecording;
private Button mBtnStopRecording;
private Chronometer mChronometer;
private String audioFileName="";
final AudioRecorder recorder = new AudioRecorder();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recordstory);
initComponents();
}
public void initComponents(){
mChronometer=(Chronometer)findViewById(R.id.chrono);
mBtnStopRecording=(Button)findViewById(R.id.btn_stop_recording);
mBtnStopRecording.setEnabled(false);
mBtnStopRecording.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//stop timer
stopRecording();
//stop recording and save audio file to SD card
}
});
mBtnStartRecording=(Button)findViewById(R.id.btn_start_recording);
mBtnStartRecording.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startRecording();
mBtnStartRecording.setEnabled(false);
mBtnStopRecording.setEnabled(true);
//start recording audio
//start timer
}
});
}
private void startRecording(){
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
try{
String myRecording="Seekika-" + System.currentTimeMillis();
Log.i(TAG, "Start Recording");
recorder.startRecording(myRecording);
}catch(IOException e){
Log.e(TAG,"IOException error");
e.printStackTrace();
}
}
private void stopRecording(){
mChronometer.stop();
try{
recorder.stop();
}catch(IOException e){
e.printStackTrace();
}
}
}
</code></pre>
| 0 | 1,989 |
how to use enum with DescriptionAttribute in asp.net mvc
|
<p>I am new to asp.net MVC. I am trying to use dropdown control on my view page, which populates from enum. I also want to add custom descriptions to dropdown values. I searched so many examples, but no one posted how to populated description on view page. Here is my code:</p>
<p>ViewModel:</p>
<pre><code>public enum SearchBy
{
[Description("SID/PID")]
SID = 1,
[Description("Name")]
Name,
[Description("Birth Date")]
DOB,
[Description("Cause#")]
Cause
}
</code></pre>
<p>Index.cshtml</p>
<pre><code><div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group form-inline">
@Html.LabelFor(model => model.searchBy, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EnumDropDownListFor(model => model.searchBy, "Search By", htmlAttributes: new { @class = "form-control" })
@Html.TextBox("searchByVal", null, htmlAttributes: new { @placeholder = "SID / PID ", @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @placeholder = "First Name", @class = "form-control" } })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @placeholder = "Last Name", @class = "form-control" } })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DOB, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.DOB, new { htmlAttributes = new { @placeholder = "Birth Date", @class = "form-control" } })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CauseNumber, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CauseNumber, new { htmlAttributes = new { @placeholder = "Cause#", @class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Search" class="btn btn-block btn-primary" />
</div>
</div>
</div>
</code></pre>
<p>It is not populating the with description fields as mentioned in my SearchBy enum. see the image here.
<a href="http://postimg.org/image/phdxgocj7/" rel="noreferrer">http://postimg.org/image/phdxgocj7/</a>
Please help me, where I am making mistake. Thank you</p>
<p><strong>UPDATE:</strong>
I got solution for this from Nico. And I researched little bit on this. I am updating this post with solution because it may useful to others, who are new to MVC
<a href="http://weblogs.asp.net/jongalloway//looking-at-asp-net-mvc-5-1-and-web-api-2-1-part-1-overview-and-enums" rel="noreferrer">http://weblogs.asp.net/jongalloway//looking-at-asp-net-mvc-5-1-and-web-api-2-1-part-1-overview-and-enums</a></p>
<p>Thank you all. Enjoy coding..</p>
| 0 | 1,569 |
Stacking multiple plots, vertically with the same x axis but different Y axes in R
|
<p>I have a data.frame with multiple time series vectors against a date:time vector. I would like to plot all of the relevant vectors, vertically stacked on separate graphs with the same X axis but unique Y axes. A graph similar to this one: <img src="https://i.stack.imgur.com/fYaHe.jpg" alt="enter image description here"></p>
<p>my data looks like this:</p>
<pre><code> dt <- structure(list(DEPTH = c(156, 156.5, 157.4, 158.15, 158.8, 159.2,
159.75, 160.35, 160.85, 161.1, 161.6, 162.05, 162.5, 162.65,
163.15, 163.45, 163.55, 163.8, 163.65, 163.75, 163.8, 163.8,
163.75, 164.45, 164.8, 165.35, 165.65, 165.75, 166.1, 166.75,
167, 167.2, 167.65, 168, 168.8, 169.3, 169.7, 170.2, 170.65,
170.9, 171.45, 171.65, 172, 172.1, 172.25, 173, 173.4, 173.9,
174.2, 174.6, 175, 175.25, 175.45, 175.9, 176.25, 176.7, 177,
177.15, 177.5, 178, 178.5, 179.05, 179.2, 180.7, 181.05, 181.25,
181.5, 181.7, 182.1, 182.3, 182.35, 182.75, 183.1, 183.65, 184.3,
184.6, 185.1, 185.15, 185.3, 185.15, 185.25, 185.3, 185.15),
Smooth.Vert.Speed = c(-0.550000000000011, -0.5, -0.900000000000006,
-0.75, -0.650000000000006, -0.399999999999977, -0.550000000000011,
-0.599999999999994, -0.5, -0.25, -0.5, -0.450000000000017,
-0.449999999999989, -0.150000000000006, -0.5, -0.299999999999983,
-0.100000000000023, -0.25, 0.150000000000006, -0.0999999999999943,
-0.0500000000000114, 0, 0.0500000000000114, -0.699999999999989,
-0.350000000000023, -0.549999999999983, -0.300000000000011,
-0.0999999999999943, -0.349999999999994, -0.650000000000006,
-0.25, -0.199999999999989, -0.450000000000017, -0.349999999999994,
-0.800000000000011, -0.5, -0.399999999999977, -0.5, -0.450000000000017,
-0.25, -0.549999999999983, -0.200000000000017, -0.349999999999994,
-0.0999999999999943, -0.150000000000006, -0.75, -0.400000000000006,
-0.5, -0.299999999999983, -0.400000000000006, -0.400000000000006,
-0.25, -0.199999999999989, -0.450000000000017, -0.349999999999994,
-0.449999999999989, -0.300000000000011, -0.150000000000006,
-0.349999999999994, -0.5, -0.5, -0.550000000000011, -0.149999999999977,
-1.5, -0.350000000000023, -0.199999999999989, -0.25, -0.199999999999989,
-0.400000000000006, -0.200000000000017, -0.049999999999983,
-0.400000000000006, -0.349999999999994, -0.550000000000011,
-0.650000000000006, -0.299999999999983, -0.5, -0.0500000000000114,
-0.150000000000006, 0.150000000000006, -0.0999999999999943,
-0.0500000000000114, 0.150000000000006), DIVE_SURF = c("dive21",
"dive21", "dive21", "dive21", "dive21", "dive21", "dive21",
"dive21", "dive21", "dive21", "dive21", "dive21", "dive21",
"dive21", "dive21", "dive21", "dive21", "dive21", "dive21",
"dive21", "dive21", "dive21", "dive21", "dive21", "dive21",
"dive21", "dive21", "dive21", "dive21", "dive21", "dive21",
"dive21", "dive21", "dive21", "dive21", "dive21", "dive21",
"dive21", "dive21", "dive21", "dive21", "dive21", "dive21",
"dive21", "dive21", "dive21", "dive21", "dive21", "dive21",
"dive21", "dive21", "dive21", "dive21", "dive21", "dive21",
"dive21", "dive21", "dive21", "dive21", "dive21", "dive21",
"dive21", "dive21", "dive21", "dive21", "dive21", "dive21",
"dive21", "dive21", "dive21", "dive21", "dive21", "dive21",
"dive21", "dive21", "dive21", "dive21", "dive21", "dive21",
"dive21", "dive21", "dive21", "dive21"), X = c(2050L, 2062L,
2026L, 2078L, 2058L, 2076L, 2050L, 2068L, 2060L, 2078L, 2058L,
2088L, 2080L, 2065L, 2088L, 2076L, 2084L, 2105L, 2084L, 2102L,
2123L, 2096L, 2074L, 2054L, 2090L, 2089L, 2080L, 2078L, 2068L,
2092L, 2084L, 2082L, 2094L, 2056L, 2062L, 2067L, 2082L, 2084L,
2091L, 2058L, 2076L, 2098L, 2104L, 2090L, 2058L, 2050L, 2080L,
2074L, 2074L, 2082L, 2070L, 2088L, 2062L, 2062L, 2082L, 2086L,
2070L, 2081L, 2092L, 2058L, 2060L, 2076L, 2094L, 2083L, 2072L,
2107L, 2104L, 2066L, 2110L, 2104L, 2072L, 2076L, 2065L, 2042L,
2066L, 2093L, 2080L, 2083L, 2108L, 2107L, 2086L, 2096L, 2126L
), Y = c(2036L, 2000L, 2049L, 1966L, 2042L, 2078L, 2072L,
2055L, 2036L, 2128L, 2044L, 2112L, 2066L, 2051L, 2102L, 2060L,
2054L, 2043L, 2034L, 2086L, 1980L, 2076L, 2003L, 2033L, 2107L,
1992L, 2028L, 2027L, 2024L, 2005L, 2050L, 2010L, 1944L, 2010L,
2046L, 2020L, 2088L, 2086L, 2034L, 2066L, 2060L, 2152L, 2044L,
2078L, 2040L, 2067L, 2080L, 2072L, 2073L, 2028L, 2066L, 2082L,
2030L, 2042L, 1990L, 2076L, 2054L, 2064L, 2016L, 2048L, 2029L,
2008L, 2090L, 2038L, 2026L, 2096L, 2002L, 2025L, 2001L, 2098L,
2061L, 2022L, 2054L, 2064L, 2043L, 2090L, 2042L, 2086L, 2073L,
2066L, 2040L, 2081L, 2087L), Z = c(2488L, 2484L, 2490L, 2486L,
2488L, 2492L, 2498L, 2490L, 2492L, 2484L, 2491L, 2494L, 2497L,
2493L, 2488L, 2493L, 2494L, 2484L, 2486L, 2487L, 2478L, 2490L,
2478L, 2493L, 2490L, 2486L, 2488L, 2486L, 2488L, 2482L, 2488L,
2480L, 2480L, 2488L, 2490L, 2490L, 2490L, 2489L, 2492L, 2490L,
2486L, 2480L, 2488L, 2491L, 2486L, 2488L, 2488L, 2494L, 2490L,
2488L, 2492L, 2498L, 2484L, 2491L, 2480L, 2491L, 2497L, 2487L,
2482L, 2490L, 2490L, 2478L, 2488L, 2492L, 2492L, 2482L, 2484L,
2489L, 2482L, 2484L, 2485L, 2492L, 2488L, 2493L, 2487L, 2490L,
2492L, 2488L, 2490L, 2487L, 2484L, 2486L, 2478L)), .Names = c("DEPTH",
"Smooth.Vert.Speed", "DIVE_SURF", "X", "Y", "Z"), row.names = 7222:7304, class = "data.frame")
</code></pre>
<p>and I am looking to plot DEPTH, X, Y and Z on separate graphs with a common X axis.</p>
| 0 | 2,924 |
BroadcastReceiver for ACTION_MEDIA_BUTTON not working
|
<p>I am writing an Android application for version 4.0.3 (ICS) of the Android OS. The issue is that I am not getting the output from my Log.d() in the onReceive() method of the BroadcastReceiver which means my application is not properly handling the broadcast.</p>
<p>I have read countless questions about how to run code upon a ACTION_MEDIA_BUTTON being clicked. I have even copy + pasted code when mine did not work, just to see if it would work.</p>
<p>The ACTION_MEDIA_BUTTON I want to handle is the <strong>single</strong> button on earphones that allow a user to pickup / end calls, play / pause music. <strong>Instead of my application handling this button, when I click it, the stock music player on my Nexus S Android starts playing a song</strong>.</p>
<p>I have not placed my code in another class, maybe this is why it's not working?</p>
<p>Here's the code found on the onCreate() method (this specific code I copied off a website after the code I wrote didn't work):</p>
<pre><code>IntentFilter mediaButtonFilter = new IntentFilter(
Intent.ACTION_MEDIA_BUTTON);
mediaButtonFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
BroadcastReceiver brMediaButton = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.d("Event", "Media button!");
this.abortBroadcast();
KeyEvent key = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if(key.getAction() == KeyEvent.ACTION_UP) {
int keycode = key.getKeyCode();
if(keycode == KeyEvent.KEYCODE_MEDIA_NEXT) {
Log.d("TestApp", "Next Pressed");
} else if(keycode == KeyEvent.KEYCODE_MEDIA_PREVIOUS) {
Log.d("TestApp", "Previous pressed");
} else if(keycode == KeyEvent.KEYCODE_HEADSETHOOK) {
Log.d("TestApp", "Head Set Hook pressed");
}
}
}
};
registerReceiver(brMediaButton, mediaButtonFilter);
</code></pre>
<p>All I really need to test for is the KEYCODE_HEADSETHOOK but it doesn't hurt to have the other code there for testing, I'll fix it up once I can get everything working correctly.</p>
<p>In my manifest:</p>
<pre><code><intent-filter android:priority="2147483647" >
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</code></pre>
<p>I originally thought this may be a permissions issue since I didn't specify any permissions for this however I didn't receive any error message.</p>
<p>Like I said earlier, I have tried many variations of this. One example was the use of the code at this link <a href="https://stackoverflow.com/questions/6603170/broadcastreceiver-onreceive-problem-action-media-button-android">broadcastreceiver onReceive problem ACTION_MEDIA_BUTTON Android</a> with CommonsWare's corrections. Again, however, I modified it so it wasn't in a seperate class.</p>
<p>Thank you in advance for your help.</p>
| 0 | 1,086 |
Can someone explain the Spring web.xml file?
|
<p>I'm new to Java Enterprise and to Spring but I have a strong grasp of standard Java. I am looking through an existing web application project. The project uses Tomcat/Spring/Hibernate which I understand is fairly common. It also uses DWR for remote method invocations. I'm finding it somewhat difficult to separate responsibilities: what Tomcat is responsible for, what Spring is responsible for, how a request gets from one to the other, and how the major pieces of Spring fit together. I've read a great deal of documentation on Spring, particularly about beans and bean factory and am still in process of reading more. Any advice you guys have would be welcome, but I'll provide some specific questions.</p>
<p>Question 1: Where does the web.xml fit into things (when is it used/called, and where is it called from)? </p>
<p>Code sample 1:</p>
<pre><code> <servlet>
<servlet-name>qrst</servlet-name>
<display-name>qrst Servlet</display-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
</code></pre>
<p>What does the above snippet do (or, what does it cause to happen)? At some point in my web app qrst.jsp gets used; is it the DispatcherServlet that calls qrst.jsp using the servlet name? Else what is the significance of the servlet name? What is load on startup?</p>
<p>Code sample 2:</p>
<pre><code><context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/someLocation/some-servlet.xml
</param-value>
</context-param>
</code></pre>
<p>Links or explanation of what the above does? I can see from looking at the XML file that it contains bean definitions and I do understand what beans are and how they are used, but I don't know any other details about this and would like to.</p>
<p>Code sample 3:</p>
<pre><code><servlet>
<servlet-name>dwr-invoker</servlet-name>
<display-name>DWR</display-name>
<servlet-class>
org.directwebremoting.servlet.DwrServlet
</servlet-class>
<init-param>
<param-name>classes</param-name>
<param-value>
somepackage.someclass
</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
</code></pre>
<p>From what I read about beans, I believe those init-param elements are just parameters that get set in the servlet's java class. What's the significance of the servlet name, and what about the load on startup? The web app somehow "knows" when an AJAX (dwr) call is happening versus when the web app is being loaded for the first time (when its loading for the first time it should use qrst.jsp). How does it know this? How does it decide to route the request to DWR instead of to qrst.jsp? Where does it do this?</p>
<p>Thanks. </p>
| 0 | 1,059 |
Cannot create PoolableConnectionFactory (Access denied for user ''@'localhost'
|
<p>I have been trying to set up a DatabaseConnectionPool for a web app for the last couple of days with no success. I have read the relevant sections of the Tomcat docs and a great deal around the subject and think I'm doing everything right, but obviously not because I keep on getting the following error:</p>
<pre><code>Cannot create PoolableConnectionFactory (Access denied for user ''@'localhost' (using password: YES))
</code></pre>
<p>I'm not getting the error when I start Tomcat running, but when I try to run the following servlet:</p>
<pre><code>package twittersearch.web;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import twittersearch.model.*;
public class ConPoolTest extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
Context ctx = null;
DataSource ds = null;
Connection conn = null;
try {
ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/twittersearchdb");
conn = ds.getConnection();
if(conn != null) {
System.out.println("have a connection from the pool");
}
} catch(SQLException e) {
e.printStackTrace();
} catch(NamingException e) {
e.printStackTrace();
} finally {
try {
if(conn!=null) {
conn.close();
}
} catch(SQLException e) {
e.printStackTrace();
}
}
}
}
</code></pre>
<p>The context for the webapp is:</p>
<pre><code><?xml version='1.0' encoding='utf-8'?>
<Context>
<!-- Configure a JDBC DataSource for the user database -->
<Resource name="jdbc/twittersearchdb"
type="javax.sql.DataSource"
auth="Container"
user="root"
password="mypwd"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/twitter"
maxActive="8"
maxIdle="4"/>
</Context>
</code></pre>
<p>What I really don't understand is why the error isn't saying that the access is denied to 'root'@'localhost' when I've specified that that's the user.</p>
<p>What I've tried:</p>
<p>Do I have a duplicate context.xml? No. I deleted the default on in Tomcat 6.0/conf. I tried putting a context.xml in [mywebappname]/META-INF/context.xml but not only did this not work, but resulted in the creation of a file named TwitterSearch.xml which was autogenerated and put in the Tomcat 6.0/conf/Catalina/localhost directory. So now I'm just editing that one and thats the only one I have.</p>
<p>Is it the version of Tomcat? Well, I completely reinstalled the latest version of Tomcat 6.0 so I don't think it's that.</p>
<p>Are we missing some jars? I have the tomcat-dbcp.jar, jconnector.jar and all the other ones that I think I'm meant to have in the Tomcat 6.0/lib directory.</p>
<p>When I look at the passwords in the MySQL database they seem to have been coded for security purposes into a long alpha-numeric string. Is this normal? Should I have this in my context.xml or just the normal password?</p>
<p>I really don't know how I can sort this out and would really appreciate some expert advice.</p>
<p>Many thanks in advance.</p>
<p>Joe</p>
| 0 | 1,351 |
No service for type 'Microsoft.AspNetCore.Identity.RoleManager error
|
<p>I'm setting up user roles on a ASP.NET CORE 2.1 application. But when I try to use the RoleManager it shoots into error. The error I get is: </p>
<pre><code>No service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]' has been registered.)'
</code></pre>
<p>I've looked through the whole application to see if <code>IdentityUser</code> is still anywhere, since I've created a class that inherits from it ( ApplicationUser ), but everything else seems correct. Adding <code>services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();</code>
gives a runtime error stating: <code>NotSupportedException: Store does not implement IUserRoleStore<TUser>.</code> Adding <code>Service.AddDefaultIdentity()</code>instead of <code>AddIdentity()</code>doesn't work either.</p>
<pre><code>public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//services.AddDbContext<ApplicationDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ApplicationDBContextConnection")));
//services.AddDefaultIdentity<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDBContext>();
services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = 6;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;
// User settings
options.User.RequireUniqueEmail = true;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, UserManager<ApplicationUser> userManager)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
CreateUserRoles(userManager).GetAwaiter().GetResult();
}
private async Task CreateUserRoles( UserManager<ApplicationUser> userManager)
{
var UserManager = userManager;
//Assign Admin role to the main User here we have given our newly registered
//login id for Admin management
ApplicationUser user = await UserManager.FindByEmailAsync("test@test.com");
UserManager.AddToRoleAsync(user, "Admin").GetAwaiter().GetResult();
}
}
</code></pre>
| 0 | 1,530 |
Running powershell script within python script, how to make python print the powershell output while it is running
|
<p>I am writing a python script which checks various conditions and runs a powershell script accordingly to help me automate migration from windows XP to windows 7. The powershell script gives its own output giving the user updates as to what is happening. I would like to take the output of the powershell script and print it as output of the python script. I have looked around at some questions which seem to want to do the same thing but they don't seem to be working for me. Initially I tried using</p>
<pre><code>import subprocess
subprocess.call(["C:\Users\gu2124\Desktop\helloworld.ps1"])
</code></pre>
<p>As was suggested here <a href="https://stackoverflow.com/questions/14508809/run-powershell-function-from-python-script">Run PowerShell function from Python script</a> but I found out that this waits for the program to execute first and does not give output so I found out I need to use <code>subprocess.Popen()</code> as was suggusted here <a href="https://stackoverflow.com/questions/4668610/use-popen-to-execute-a-powershell-script-in-python-how-can-i-get-the-powershell">Use Popen to execute a Powershell script in Python, how can I get the Powershell script's output and update it to web page?</a> so I tried this</p>
<pre><code>import subprocess
subprocess.Popen(["C:\Users\gu2124\Desktop\helloworld.ps1"], stdout=sys.stdout)
</code></pre>
<p>and I get this error </p>
<pre><code>Traceback (most recent call last):
File "C:\Users\gu2124\Desktop\pstest.py", line 5, in <module>
subprocess.Popen(["C:\Users\gu2124\Desktop\helloworld.py1"], stdout=sys.stdout)
File "C:\Python27\lib\subprocess.py", line 701, in __init__
errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
File "C:\Python27\lib\subprocess.py", line 848, in _get_handles
c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
File "<string>", line 523, in __getattr__
File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\netref.py", line 150, in __getattr__
return syncreq(self, consts.HANDLE_GETATTR, name)
File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\netref.py", line 71, in syncreq
return conn.sync_request(handler, oid, *args)
File "C:\Program Files\PyScripter\Lib\rpyc.zip\rpyc\core\protocol.py", line 434, in sync_request
raise obj
AttributeError: DebugOutput instance has no attribute 'fileno'
</code></pre>
<p>I'm not completely sure what this means but from what I think I understand after reading this <a href="https://stackoverflow.com/questions/5903501/attributeerror-stringio-instance-has-no-attribute-fileno">AttributeError: StringIO instance has no attribute 'fileno'</a> is that it is because I am messing with the stdout incorrectly. I looked a around more and I found this <a href="https://stackoverflow.com/questions/16544362/why-wont-my-python-subprocess-code-work">Why won't my python subprocess code work?</a> where the answers said to use <code>stdout=subprocess.PIPE</code> so I tried this </p>
<pre><code>import subprocess
subprocess.Popen(["C:\Users\gu2124\Desktop\helloworld.ps1"], stdout=subprocess.PIPE)
</code></pre>
<p>which also does not give me output
Finally I saw this <a href="http://www.pythonforbeginners.com/os/subprocess-for-system-administrators" rel="noreferrer">http://www.pythonforbeginners.com/os/subprocess-for-system-administrators</a> and changed my code to this </p>
<pre><code>import subprocess
p = subprocess.Popen(["powershell","C:\Users\gu2124\Desktop\helloworld.ps1"], stdout=subprocess.PIPE)
print p.communicate
</code></pre>
<p>I thought that it may because I am initially trying to run a powershell script from the command line so I have to open powershell first. When I type these commands directly into the command line it works the way it should but when I run it through the python script it gives this </p>
<pre><code><bound method Popen.communicate of <subprocess.Popen object at 0x00000000026E4A90>>
</code></pre>
<p>which is an improvement I guess but not the "Hello world" I was expecting.
I have no idea what I should try to do next to get this to work. Any help would be greatly appreciated</p>
<p>Also if the powershell script I am using is needed here it is </p>
<pre><code>$strString = "Hello World"
write-host $strString
function ftest{
$test = "Test"
write-host $test
}
</code></pre>
<p>EDIT: I tried upgrading to python 3.3 like was suggested in the first answer but I still can't get it to work. I used the command <code>p = subprocess.Popen(['powershell.exe', "C:\\Users\\gu2124\\Desktop\\helloworld.ps1"], stdout=sys.stdout)</code> and am sure the file is there but am getting this error:</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
p = subprocess.Popen(['powershell.exe', "C:\\Users\\gu2124\\Desktop\\helloworld.ps1"], stdout=sys.stdout)
File "C:\Python27\lib\subprocess.py", line 701, in __init__
errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
File "C:\Python27\lib\subprocess.py", line 848, in _get_handles
c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
UnsupportedOperation: fileno
</code></pre>
| 0 | 1,743 |
JavaScript with Spring MVC doesn't work
|
<p>I downloaded login template which uses css and JavaScript. When I start it in default html format it displays ok, but when I put the same code to my Spring MVC 3 app and change format to jsp, javascript part is disabled. I can access external js files through my web browser, so I don't know where may be the problem.</p>
<p>This is the right look:
<img src="https://i.stack.imgur.com/l94Le.jpg" alt="right"></p>
<p>but this is what i get:
<img src="https://i.stack.imgur.com/RNTSg.png" alt="wrong"></p>
<pre><code><script language="javascript" type="text/javascript" src="js/niceforms.js"></script>
<link rel="stylesheet" type="text/css" media="all" href="css/niceforms-default.css" />
</code></pre>
<p>I only changed the location of external js and css resources but these files are accessable as I said.</p>
<p>This is my structure:</p>
<p><img src="https://i.stack.imgur.com/uKETE.png" alt="enter image description here"></p>
<p>In my <code>web.xml</code> I have these lines:</p>
<pre><code><!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/root-context.xml,
/WEB-INF/spring/security-context.xml,
</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.txt</url-pattern>
</servlet-mapping>
</code></pre>
<p>I also use Apache tiles2</p>
<pre><code><tiles-definitions>
<definition name="base.definition" template="/WEB-INF/views/layout/layout.jsp">
<put-attribute name="body" value="" />
</definition>
<definition name="contact" extends="base.definition">
<put-attribute name="body" value="/WEB-INF/views/contact.jsp" />
</definition>
<definition name="login" template="/WEB-INF/views/login/login.jsp">
</definition>
</code></pre>
<p></p>
<p>Thanks.</p>
<p>Edit:</p>
<p>I know where is the problem now, but still don't know how to solve it... Problem is in paths in external css files. I have something like this: <code>body {background-image:url('images/bg.jpg');}</code> but I get not found error in firebug because it tries to find the resource in <em>localhost:8080/sheedo/css/images/bg.jpg</em> and when I set absolute path of resource like <code>body {background-image:url('/images/bg.jpg');}</code> I get the same error too but it tries to find it in <em>localhost:8080/images/bg.jpg</em>. When I use <code>./images/bg.jpg</code> it's ok, but does exist any other solution instead of rewrite all paths in css files? I mean something like <code><mvc:resources ... ></code> is it possible ?</p>
| 0 | 1,961 |
how create a service for installed STUNNEL on CentOS 5.10
|
<p>i have installed stunnel in my centos machine like below : </p>
<p><code>yum install stunnel -y</code></p>
<pre><code>openssl genrsa -out privkey.pem 2048
openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1095
cat privkey.pem cacert.pem >> /etc/stunnel/stunnel.pem
chmod 600 /etc/stunnel/stunnel.pem
chown nobody.nobody /var/run/stunnel
</code></pre>
<p><code>nano -K /etc/stunnel/stunnel.conf</code></p>
<pre><code>cert = /etc/stunnel/stunnel.pem
chroot = /var/run/stunnel/
pid = /stunnel.pid
setuid = nobody
setgid = nobody
output = stunnel.log
[squid]
# Ensure the βconnectβ line matches your squid port. Default is 3128
accept = 8088
connect = 127.0.0.1:1945
</code></pre>
<p><HR></p>
<p>my problem is after stunnel installation <strong>there is no</strong> <strong>service</strong> for installed stunnel.<br>
so i wrote this : </p>
<p><HR></p>
<p><code>nano -K /etc/init.d/stunnel</code></p>
<pre><code>#!/bin/bash
# /etc/rc.d/init.d/stunnel
#
# Starts the stunnel daemon
#
# chkconfig: 345 70 30
# description: Stunnel Server is a ...
# processname: stunnel
# config: /etc/stunnel/stunnel.conf
# Source function library.
. /etc/init.d/functions
test -x /usr/sbin/stunnel || exit 0
RETVAL=0
#
# See how we were called.
#
prog="stunnel"
start() {
# Check if stunnel is already running
if [ ! -f /var/lock/subsys/stunnel ];
then
echo -n $"Starting $prog: "
daemon /usr/sbin/stunnel
RETVAL=$?
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/stunnel
echo
fi
return $RETVAL
}
stop() {
echo -n $"Stopping $prog: "
killproc /usr/sbin/stunnel
RETVAL=$?
[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/stunnel
echo
return $RETVAL
}
restart() {
stop
start
}
reload() {
restart
}
status() {
status /usr/sbin/stunnel
}
case "$1" in
start)
start
;;
stop)
stop
;;
reload|restart)
restart
;;
status)
status
;;
*)
echo $"Usage: $0 {start|stop|restart|reload|status}"
exit 1
esac
exit $?
exit $RETVAL
</code></pre>
<p><code>chmod +x /etc/init.d/stunnel</code></p>
<p><code>chkconfig --add stunnel</code></p>
<p><HR></p>
<p>the start command for the written service works fine : <strong>service stunnel start</strong> : <strong>OK</strong>. </p>
<p>but i have error during stop command : <strong>service stunnel stop</strong> : <strong>FAILED</strong> </p>
<p>and i have error during status command : <strong>service stunnel status</strong> :<br>
<strong>/sbin/service: line 66: 7456 Segmentation fault env -i LANG="$LANG" PATH="$PATH" TERM="$TERM" "${SERVICEDIR}/${SERVICE}" ${OPTIONS}</strong> </p>
<p>what did i do wrong and how can i fix the problem?<br>
is there a better way for getting that service? </p>
<p>thanks in advance</p>
| 0 | 1,214 |
"Dead letters encountered" as soon as actors are placed into router
|
<p>Here's what I'm finding, and for the life of me I can't navigate to the reason. I'm creating "printer" actors that basically either do nothing, or print a message based on the type of message they receive.</p>
<pre><code>class Printer extends Actor {
def receive = {
case m: SomeMessage => println( m.text )
case _ =>
}
}
</code></pre>
<p>I'm creating several of these actors:</p>
<pre><code>val actor4 = system.actorOf(Props[Printer], "t-4")
val actor5 = system.actorOf(Props[Printer], "t-5")
val actor6 = system.actorOf(Props[Printer], "t-6")
</code></pre>
<p>and throwing them into a vector:</p>
<pre><code>val routees2 = Vector[ActorRef](actor4, actor5, actor6)
</code></pre>
<p>I'm doing the above so that I can throw them into a router (and they will be under the router's control). When I run the spec up to this point I'm not having any issues. As soon as I place them in a router and run the spec I'm having problems. Here's the router:</p>
<pre><code>val router = system.actorOf(Props[Printer].withRouter(
BroadcastRouter(routees = routees2)), "router-to-transformers")
</code></pre>
<p>Now when I run the spec I have all sorts of dead letters...</p>
<pre><code>[INFO] [09/23/2013 17:10:21.468] [spider-akka.actor.default-dispatcher-6] [akka://spider/user/router-to-transformers] Message [akka.dispatch.sysmsg.DeathWatchNotification] from Actor[akka://spider/user/router-to-transformers#-1845250548] to Actor[akka://spider/user/rout
er-to-transformers#-1845250548] was not delivered. [1] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
[INFO] [09/23/2013 17:10:21.468] [spider-akka.actor.default-dispatcher-6] [akka://spider/user/router-to-transformers] Message [akka.dispatch.sysmsg.DeathWatchNotification] from Actor[akka://spider/user/router-to-transformers#-1845250548] to Actor[akka://spider/user/rout
er-to-transformers#-1845250548] was not delivered. [2] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
[INFO] [09/23/2013 17:10:21.468] [spider-akka.actor.default-dispatcher-6] [akka://spider/user/router-to-transformers] Message [akka.dispatch.sysmsg.DeathWatchNotification] from Actor[akka://spider/user/router-to-transformers#-1845250548] to Actor[akka://spider/user/rout
er-to-transformers#-1845250548] was not delivered. [3] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
</code></pre>
<p>For the life of me I can't figure out what is going on here. I've added a link to a snippet of the test. The numbering, in the snippet, is weird because I've cut a bunch of different attempts that were commented out so as to not clutter the snippet. I'm focused on this dead-letters issue because I feel like when I added a more actors and actually started passing messages around, things weren't getting delivered...
<a href="http://snipt.org/AhVf0" rel="nofollow noreferrer">http://snipt.org/AhVf0</a></p>
<p>It's worth calling out that these actors are local. I've read something about actorFor being depreciated and I'm wondering if that is being used and is partly what is causing my issues? There are so many moving parts here though and not a lot of stable, COMPREHENSIVE, documentation. Any help would be greatly appreciated.</p>
| 0 | 1,167 |
OpenCV 4.x+ requires enabled C++11 support compilation darknet fatal error
|
<p>I just compiled and installed the last version of OpenCV 3.4.0 and I would like to compile darknet (for yolo object detection), but at compilation, I have</p>
<pre><code>gcc -Iinclude/ -Isrc/ -DOPENCV `pkg-config --cflags opencv` -DGPU -I/usr/local/cuda-9.1/include/ -Wall -Wno-unused-result -Wno-unknown-pragmas -Wfatal-errors -fPIC -Ofast -DOPENCV -DGPU -c ./src/gemm.c -o obj/gemm.o
In file included from /usr/local/include/opencv2/core/types_c.h:59:0,
from /usr/local/include/opencv2/core/core_c.h:48,
from /usr/local/include/opencv2/highgui/highgui_c.h:45,
from include/darknet.h:25,
from ./src/utils.h:5,
from ./src/gemm.c:2:
/usr/local/include/opencv2/core/cvdef.h:421:4: error: #error "OpenCV 4.x+ requires enabled C++11 support"
# error "OpenCV 4.x+ requires enabled C++11 support"
^
compilation terminated due to -Wfatal-errors.
Makefile:86: recipe for target 'obj/gemm.o' failed
make: *** [obj/gemm.o] Error 1
</code></pre>
<p>How it is possible, because in Makefile (below), I compile C </p>
<pre><code>GPU=1
CUDNN=0
OPENCV=1
OPENMP=0
DEBUG=0
ARCH= -gencode arch=compute_30,code=sm_30 \
-gencode arch=compute_35,code=sm_35 \
-gencode arch=compute_50,code=[sm_50,compute_50] \
-gencode arch=compute_52,code=[sm_52,compute_52]
# -gencode arch=compute_20,code=[sm_20,sm_21] \ This one is deprecated?
# This is what I use, uncomment if you know your arch and want to specify
# ARCH= -gencode arch=compute_52,code=compute_52
VPATH=./src/:./examples
SLIB=libdarknet.so
ALIB=libdarknet.a
EXEC=darknet
OBJDIR=./obj/
CC=gcc
NVCC=nvcc
NVCCFLAGS += -D_FORCE_INLINES -ccbin=$(CXX) -Xcompiler -fPIC $(COMMON_FLAGS)
AR=ar
ARFLAGS=rcs
OPTS=-Ofast
LDFLAGS= -lm -pthread
COMMON= -Iinclude/ -Isrc/
CFLAGS=-Wall -Wno-unused-result -Wno-unknown-pragmas -Wfatal-errors -fPIC
ifeq ($(OPENMP), 1)
CFLAGS+= -fopenmp
endif
ifeq ($(DEBUG), 1)
OPTS=-O0 -g
endif
CFLAGS+=$(OPTS)
ifeq ($(OPENCV), 1)
COMMON+= -DOPENCV
CFLAGS+= -DOPENCV
LDFLAGS+= `pkg-config --libs opencv`
COMMON+= `pkg-config --cflags opencv`
endif
ifeq ($(GPU), 1)
COMMON+= -DGPU -I/usr/local/cuda-9.1/include/
CFLAGS+= -DGPU
LDFLAGS+= -L/usr/local/cuda-9.1/lib64 -lcudart -lcublas -lcurand
endif
ifeq ($(CUDNN), 1)
COMMON+= -DCUDNN
CFLAGS+= -DCUDNN
LDFLAGS+= -lcudnn
endif
OBJ=gemm.o utils.o cuda.o deconvolutional_layer.o convolutional_layer.o list.o image.o activations.o im2col.o col2im.o blas.o crop_layer.o dropout_layer.o maxpool_layer.o softmax_layer.o data.o matrix.o network.o connected_layer.o cost_layer.o parser.o option_list.o detection_layer.o route_layer.o upsample_layer.o box.o normalization_layer.o avgpool_layer.o layer.o local_layer.o shortcut_layer.o logistic_layer.o activation_layer.o rnn_layer.o gru_layer.o crnn_layer.o demo.o batchnorm_layer.o region_layer.o reorg_layer.o tree.o lstm_layer.o l2norm_layer.o yolo_layer.o
EXECOBJA=captcha.o lsd.o super.o art.o tag.o cifar.o go.o rnn.o segmenter.o regressor.o classifier.o coco.o yolo.o detector.o nightmare.o darknet.o
ifeq ($(GPU), 1)
LDFLAGS+= -lstdc++
OBJ+=convolutional_kernels.o deconvolutional_kernels.o activation_kernels.o im2col_kernels.o col2im_kernels.o blas_kernels.o crop_layer_kernels.o dropout_layer_kernels.o maxpool_layer_kernels.o avgpool_layer_kernels.o
endif
EXECOBJ = $(addprefix $(OBJDIR), $(EXECOBJA))
OBJS = $(addprefix $(OBJDIR), $(OBJ))
DEPS = $(wildcard src/*.h) Makefile include/darknet.h
#all: obj backup results $(SLIB) $(ALIB) $(EXEC)
all: obj results $(SLIB) $(ALIB) $(EXEC)
$(EXEC): $(EXECOBJ) $(ALIB)
$(CC) $(COMMON) $(CFLAGS) $^ -o $@ $(LDFLAGS) $(ALIB)
$(ALIB): $(OBJS)
$(AR) $(ARFLAGS) $@ $^
$(SLIB): $(OBJS)
$(CC) $(CFLAGS) -shared $^ -o $@ $(LDFLAGS)
$(OBJDIR)%.o: %.c $(DEPS)
$(CC) $(COMMON) $(CFLAGS) -c $< -o $@
$(OBJDIR)%.o: %.cu $(DEPS)
$(NVCC) $(ARCH) $(COMMON) --compiler-options "$(CFLAGS)" -c $< -o $@
obj:
mkdir -p obj
backup:
mkdir -p backup
results:
mkdir -p results
.PHONY: clean
clean:
rm -rf $(OBJS) $(SLIB) $(ALIB) $(EXEC) $(EXECOBJ) $(OBJDIR)
</code></pre>
<p>And what's the solution for this error ? How I can enable C++11 support ?</p>
<p>Thank for your help !</p>
| 0 | 1,941 |
Using a QThread in PyQT for serial communication (w. pyserial)
|
<p>I am pretty much a beginner when it comes to GUI programming.
I am using QT in combination with python bindings (PyQT4).</p>
<p><strong>What I am trying to do:</strong></p>
<ul>
<li>Setting up a <code>QThread</code> to read from & write to a Serial Port with
pyserial.</li>
<li>The main application should be able to emit new serial data via a
signal to the running <code>QThread</code>. and receive serial data from the
<code>QThread</code> with a signal.</li>
</ul>
<p>I started my own test implementation based on this code (<a href="https://stackoverflow.com/a/6789205/2706668" title="Link">Link</a>).
Prior to this I read the basics about <code>QThread</code>s and tried to understand how they are intended to be used.
The following test code is what I have come up with. I m sorry, I tried to keep it minmal,
but it is still 75 lines of code:</p>
<pre><code>from PyQt4 import QtCore, QtGui
import time
import sys
class SerialData(QtCore.QObject):
def __init__(self, message):
super(SerialData, self).__init__()
self.__m = message
def getMsg(self):
return self.__m
class SerialCon(QtCore.QObject):
finished = QtCore.pyqtSignal()
received = QtCore.pyqtSignal(SerialData)
def init(self):
super(SerialCon, self).__init__()
# TODO setup serial connection:
# setting up a timer to check periodically for new received serial data
self.timer = QtCore.QTimer()
self.timer.setInterval(400)
self.timer.timeout.connect(self.readData)
self.timer.start(200)
# self.finished.emit()
def readData(self):
self.received.emit(SerialData("New serial data!"))
print "-> serial.readLine() ..."
@QtCore.pyqtSlot(SerialData)
def writeData(self, data):
print "-> serial.write(), ", data.getMsg()
class MyGui(QtGui.QWidget):
serialWrite = QtCore.pyqtSignal(SerialData)
def __init__(self):
super(MyGui, self).__init__()
self.initUI()
def initUI(self):
bSend = QtGui.QPushButton("Send",self)
bSend.clicked.connect(self.sendData)
self.show()
@QtCore.pyqtSlot(SerialData)
def updateData(self, data):
print "Gui:", data.getMsg()
def sendData(self, pressed):
data = SerialData("Send me!")
self.serialWrite.emit(data)
def usingMoveToThread():
app = QtGui.QApplication(sys.argv)
guui = MyGui()
thread = QtCore.QThread()
serialc = SerialCon()
serialc.moveToThread(thread)
# connecting signals to slots
serialc.finished.connect(thread.quit)
guui.serialWrite.connect(serialc.writeData)
serialc.received.connect(guui.updateData)
thread.started.connect(serialc.init)
thread.finished.connect(app.exit)
thread.start()
sys.exit(app.exec_())
if __name__ == "__main__":
usingMoveToThread()
</code></pre>
<p><strong>My Problems:</strong></p>
<ul>
<li><p>In test code the signal emitted from the <code>SerialCon</code> object (which has
been moved to the <code>QThread</code>) seems to be not received by the
corresponding slot (in <code>MyGui</code>, <code>updateData</code>)</p></li>
<li><p>Sooner or later the running test code always causes a <code>Segmentation
fault (core dumped)</code>. Which makes me believe that I missed some
important bits.</p></li>
</ul>
<p>What could cause this?</p>
<p>Maybe I m taking a completely wrong approach? -
so if you have a better idea how to achieve this, I d be very grateful to hear about it!</p>
<p>Thanks a lot!</p>
| 0 | 1,331 |
Is still GWT pertinent for new projects?
|
<p>The question <a href="https://stackoverflow.com/questions/1205278">Why should I use jQuery instead of GWT?</a> may be outdated (as its answers). And <a href="https://stackoverflow.com/questions/812401">most</a> <a href="https://stackoverflow.com/questions/4673612">of</a> <a href="https://stackoverflow.com/questions/4886397">the</a> other SO related questions may also be outdated nowadays. So, let's update the <a href="http://en.wikipedia.org/wiki/State_of_the_art" rel="noreferrer">state of the art</a> about GWT relevance for new projects.</p>
<p><strong>GWT is more mature nowadays</strong></p>
<p>Since 2009 questions/answers, GWT has evolved and some JS frameworks are available in Java:</p>
<ul>
<li><a href="http://code.google.com/p/gwtquery/" rel="noreferrer">GwtQuery</a> for jQuery (gQuery)</li>
<li><a href="http://www.sencha.com/products/gxt/" rel="noreferrer">GXT</a> for ExtJS (former ExtGWT)</li>
<li><a href="http://code.google.com/p/smartgwt/" rel="noreferrer">Smart GWT</a> has superseded <a href="http://gwt-ext.com/" rel="noreferrer">GWT-ext</a></li>
<li>... and surely more ... (please feel free to append)</li>
</ul>
<p>And even more, Java code can be converted to standalone JS libraries: <a href="http://code.google.com/p/gwt-exporter/" rel="noreferrer">gwt-exporter</a></p>
<p><strong>But low-level JS frameworks may be enough</strong></p>
<p>But more I read, more I see web developers advising to turn his back on GWT and use directly JS frameworks (<a href="https://getfirebug.com/" rel="noreferrer">Firebug</a>, IDE plugins for JS frameworks...).</p>
<p><strong>Productivity</strong></p>
<p>However I like the idea of developing and debugging using the same IDE (Eclipse, Netbeans, IntelliJ IDEA...). I <em>think</em> I will be more productive... I should also think about Documentation and Community (forum reactivity as for this SO question)...</p>
<p><strong>Questions</strong></p>
<ol>
<li>For what kind of new 2014 project GWT should be (or not) considered?</li>
<li>Are there <em>pertinent</em> alternatives to GWT for easy AJAX web application development & deployment?</li>
<li>What are the current mode and trend?</li>
</ol>
<p><strong>My specific case</strong></p>
<p>I have just completed a POC (of an intranet web app) based on Python3 (<code>http.server.HTTPServer</code>) calling (POST) <code>bash</code> scripts (some processing in C++) and retrieving JSON data. Some JS (no framework) in the web page for rendering. So I am wondering the best option for next iteration.</p>
<p>But please answer this question about other cases too. I would prefer a general question/answer to be useful to many more people.</p>
<hr />
<p><strong>UPDATE October 2015</strong></p>
<p>GWT looks less active because no new release since 11 month. But in the past until <a href="https://en.wikipedia.org/wiki/Google_Web_Toolkit#History" rel="noreferrer">13 months between versions 2.4 and 2.5</a>. The <a href="https://github.com/gwtproject/gwt" rel="noreferrer">Git repo mirror</a> is still very active. Moreover GWT is extensible, and new features can come from GWT libraries without requiring new GWT framework release. See for example the <a href="https://en.wikipedia.org/wiki/Google_Web_Toolkit#Mobile" rel="noreferrer">most common mobile GWT libraries</a> and there corresponding release cycles. In the mean time the trend is to use Node.js everywhere! Adoption of GWT for new projects really depends on developers skills/motivation and project lifetime (turnover/training/maintenance). Some other criteria as reuse of available source code and time-to-market may also be taken into account... See excellent below answers.</p>
| 0 | 1,113 |
Spring annotation @Retryable - how to set an interceptor
|
<p>I am using a <code>@Retryable</code> annotation on a method in a <code>@Service</code>class</p>
<pre><code>@Service
@EnableRetry
public class PushService {
@Retryable(maxAttempts=5)
public Result pushIt(myMessage messageIn) {
...
}
}
</code></pre>
<p>and it works like a charme: I am getting a message directly from RabbitMQ, it is not acknowledged until either there is no error, or the number of attempts reach 5, and at that time the messages goes straight to the DLQ, right as I wanted.</p>
<p>My only problem is that I need to set the maxAttempts dynamically, from a property file. The solution should be setting an interceptor, but the only fact of having one causes an error, for example when I have :</p>
<pre><code>@Service
@EnableRetry
public class PushService {
@Retryable(interceptor="myInterceptor")
public Result pushIt(myMessage messageIn) {
...
}
}
</code></pre>
<p>where myInterceptor is defined as :</p>
<pre><code>@Bean
public StatefulRetryOperationsInterceptor myInterceptor() {
return RetryInterceptorBuilder.stateful().maxAttempts(5).build();
}
</code></pre>
<p>I get an infinite loop with the following exception:</p>
<pre><code>2015-04-08 07:12:10,970 GMT [SimpleAsyncTaskExecutor-1] (ConditionalRejectingErrorHandler.java:67) WARN listener.ConditionalRejectingErrorHandler: Execution of Rabbit message listener failed.
org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Listener threw exception
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.wrapToListenerExecutionFailedExceptionIfNeeded(AbstractMessageListenerContainer.java:864)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:802)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:690)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$001(SimpleMessageListenerContainer.java:82)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$1.invokeListener(SimpleMessageListenerContainer.java:167)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.invokeListener(SimpleMessageListenerContainer.java:1241)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:660)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:1005)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:989)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$700(SimpleMessageListenerContainer.java:82)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1103)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 1
at org.springframework.amqp.rabbit.config.StatefulRetryOperationsInterceptorFactoryBean$3.getKey(StatefulRetryOperationsInterceptorFactoryBean.java:103)
at org.springframework.retry.interceptor.StatefulRetryOperationsInterceptor.invoke(StatefulRetryOperationsInterceptor.java:132)
at org.springframework.retry.annotation.AnnotationAwareRetryOperationsInterceptor.invoke(AnnotationAwareRetryOperationsInterceptor.java:118)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at com.acme.push.service.PushService$$EnhancerBySpringCGLIB$$9d503bc1.pushMessage(<generated>)
at com.acme.push.receiver.PushListener.onMessage(PushListener.java:42)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:799)
... 10 more
</code></pre>
<p>I am pretty sure I am keeping it too simple, but I just have no clues on what could cause this error and how to solve it, anybody has an idea of what is going on ?</p>
| 0 | 1,345 |
How to solve error java.io.IOException: Input/output error in nativeavailable for Serial Communication?
|
<p>I have Arm processor which is AllWinner A13 ,RAM- 512mb, and OS- Linaro 13.01 Ubuntu (means debian). Now i m making Serial Communication program for /dev/ttyS0. i made simple program for Two Way Serial Communication in java with netbeans. In my processor i short rx-tx of ttyS0 for loop back coonection checking. Means what ever i send through Serial port that i get return back. but i get error. i installed openjdk-7, librxtx-java on my processor. my code and error is below. If any have idea or solution then please suggest to me.</p>
<pre><code>package serialcomm_linaro;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class TwoWaySerialComm
{
public TwoWaySerialComm()
{
super();
}
void connect ( String portName ) throws Exception
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Error: Port is currently in use");
}
else
{
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
if ( commPort instanceof SerialPort )
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
(new Thread(new SerialReader(in))).start();
(new Thread(new SerialWriter(out))).start();
}
else
{
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
/** */
public static class SerialReader implements Runnable
{
InputStream in;
public SerialReader ( InputStream in )
{
this.in = in;
}
public void run ()
{
byte[] buffer = new byte[1024];
int len = -1;
try
{
while ( ( len = this.in.read(buffer)) > -1 )
{
System.out.print(new String(buffer,0,len));
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
/** */
public static class SerialWriter implements Runnable
{
OutputStream out;
public SerialWriter ( OutputStream out )
{
this.out = out;
}
public void run ()
{
try
{
int c = 0;
while ( ( c = System.in.read()) > -1 )
{
this.out.write(c);
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
public static void main ( String[] args )
{
try
{
(new TwoWaySerialComm()).connect("/dev/ttyS0");
}
catch ( Exception e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
</code></pre>
<p>my out is below . In this out i just send 123 and i get return back 23 first and then 1111... more time, and then errore. Instead of 111111.... i want only return back 123.</p>
<pre><code>enter code here
RXTX Warning: Removing stale lock file. /var/lock/LCK..ttyS0
123
23
111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
java.io.IOExcepti on: Input/output error in nativeavailable
at gnu.io.RXTXPort.nativeavailable(Native Method)
at gnu.io.RXTXPort$SerialInputStream.read(RXTXPort.java:1429)
at gnu.io.RXTXPort$SerialInputStream.read(RXTXPort.java:1341)
at serialcomm_linaro.TwoWaySerialComm$SerialReader.run(TwoWaySerialComm.java:66)
at java.lang.Thread.run(Thread.java:722)
</code></pre>
| 0 | 2,032 |
How to set up a proxy location for all paths except some with apache2?
|
<p>I've got several webapps running on my webserver:</p>
<ul>
<li>SVN Repository Browser, accessible via <code>https://beta.mydomain.tld/svn/repos</code></li>
<li>Trac instance, accesible via <code>https://beta.mydomain.tld/trac</code></li>
<li>My own java web application, accessible via <code>http://beta.mydomain.tld/</code>, using a Proxy for the local Apache Tomcat on port 8080</li>
</ul>
<p>Please note that the first two are available via SSL, the third is not (yet). Now I need to make my web app available via https, but I want Trac and SVN Browser still to be accessible in their current location.</p>
<p>I.e. I am trying to configure apache2 to proxy all requests not starting with <code>svn</code> or <code>trac</code> to Tomcat.</p>
<p>For the existing SSL web apps, there's the following configuration</p>
<pre><code> <Location /svn/repos>
DAV svn
SVNParentPath /home/myuser/svn
SVNListParentPath on
AuthType Basic
AuthName "Subversion repository"
AuthUserFile /home/myuser/.htpasswd
Require valid-user
</Location>
<Location /trac>
SetHandler mod_python
PythonHandler trac.web.modpython_frontend
PythonOption TracEnvParentDir /home/myuser/trac
PythonOption TracUriRoot /trac
AuthType Basic
AuthName "Trac"
AuthUserFile /home/myuser/.htpasswd
Require valid-user
</Location>
</code></pre>
<p>I tried to add the following location, but it did not help anything...</p>
<pre><code> <Location />
ProxyPass http://localhost:8080
ProxyPassReverse http://localhost:8080/
</Location>
</code></pre>
<p>For further information, here is the complete apache2 configuration regarding the SSL part (without any of my failed trials in it - I think it is default trac configuration):</p>
<p></p>
<pre><code><VirtualHost *:443>
ServerAdmin webmaster@localhost
ServerName beta.mydomain.tld:443
DocumentRoot /var/www/
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>
ErrorLog /var/log/apache2/error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog /var/log/apache2/ssl_access.log combined
Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
Options Indexes MultiViews FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
SSLEngine on
SSLCertificateFile /etc/ssl/certs/ssl.crt
SSLCertificateKeyFile /etc/ssl/private/ssl.key
BrowserMatch ".*MSIE.*" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
<Location /svn/repos>
DAV svn
SVNParentPath /home/myuser/svn
SVNListParentPath on
AuthType Basic
AuthName "Subversion repository"
AuthUserFile /home/myuser/.htpasswd
Require valid-user
</Location>
<Location /trac>
SetHandler mod_python
PythonHandler trac.web.modpython_frontend
PythonOption TracEnvParentDir /home/myuser/trac
PythonOption TracUriRoot /trac
AuthType Basic
AuthName "Trac"
AuthUserFile /home/myuser/.htpasswd
Require valid-user
</Location>
</code></pre>
<p></p>
| 0 | 1,658 |
Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3
|
<p>I'm trying to deploy my website on somee.com but keeps getting this error<br/><br/>
<img src="https://i.stack.imgur.com/QT9h9.png" alt="enter image description here"> </p>
<p>I've tried googling and it says I have to change my App Pool to ASP.NET 4.0. I've tried that already but with no luck:( <br/><br/>
<strong>Informations:</strong> </p>
<p>-My site was coded in 4.0 Framework<br/>
-I'm using .NET Framework v4.0 Integrated<br/>
-I have checked needed things already in Windows Features<br/>
-Im using ASP.NET MVC3<br/>
-I already typed cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319 then aspnet_regiis -ir to cmd<br/>
-64 bit OS<br/><br/></p>
<p><strong>This is the steps how I publish my site</strong></p>
<ol>
<li><p>First I manually added this things to my Reference then changed the Copy Local to True</p>
<p>Microsoft.Web.Infrastructure<br/>
System.Web.Helpers<br/>
System.Web.Mvc<br/>
System.Web.Razor<br/>
System.Web.WebPages<br/>
System.Web.WebPages.Deployment<br/>
System.Web.WebPages.Razor<br/></p></li>
<li><p>I Editted this on my Web Config</p>
<p><code><configuration></code><br/>
<code><system.web></code><br/>
<code><customErrors mode="Off"/></code><br/>
<code><compilation debug="true" targetFramework="4.0"/></code><br/>
<code><authentication mode="None"/></code><br/>
<code></system.web></code><br/>
<code></configuration></code><br/></p></li>
<li><p>I add Deployable Dependencies that created _bin_deployableAssemblies which have this inside<br/><br/></p>
<p>Microsoft.Web.Infrastructure.dll<br/>
System.Web.Helpers.dll<br/>
System.Web.Mvc.dll<br/>
System.Web.Razor.dll<br/>
System.Web.WebPages.dll<br/>
System.Web.WebPages.Deployment.dll<br/>
System.Web.WebPages.Razor.dll<br/></p></li>
<li><p>I then click Publish and have this settings<br/><br/>
<strong>This is how I Publish is this ok or I have to change something here?</strong>
<img src="https://i.stack.imgur.com/4J2VI.png" alt="enter image description here"><br/><br/></p></li>
<li><p>I went to my IIS Manager. I right click on Default Web site Under Sites and choose Add Application with this settings
<img src="https://i.stack.imgur.com/hpsf1.png" alt="enter image description here"></p></li>
<li><p>This resulted to this<br/>
<img src="https://i.stack.imgur.com/G97NF.png" alt="enter image description here">
<img src="https://i.stack.imgur.com/4IE4H.png" alt="enter image description here"></p></li>
<li><p>I went to C:/inetpub/wwwroot and sees this files<br/>
<img src="https://i.stack.imgur.com/WcLRB.png" alt="enter image description here"></p></li>
<li><p>I then compressed it as zip then uploaded it in my account in somee.com then checked my site and now I'm getting the Configuration Error above.<br/><br/>
<strong>ABOVE IS MY UPDATED QUESTION I REPUBLISHED MY SITE AND INCLUDED STEPS HOW I PUBLISHED IT . I INCLUDED IT SO THAT YOU GUYS COULD SUGGEST IF I'M DOING SOMETHING WRONG ON HOW I'M PUBLISHING MY SITE AND COULD BE THE REASON OF THE ERROR ABOVE. THANKS IN ADVANCE :)</strong></p>
<p><br/>
My site works fine in the iis of the localhost of my machine it only gets that error when deployed on the internet.
Btw I'm following the tutorials from these sites <a href="http://drew-prog.blogspot.com/2011/01/how-to-deploy-aspnet-mvc-3-app-to-web.html" rel="noreferrer">How to Deploy an ASP.NET MVC 3 App to Web Hosting with "\bin Deployment"</a> <a href="http://ofps.oreilly.com/titles/9781449320317/ch_Deployment.html#SelectIISApplicationPoolDialog" rel="noreferrer">Programming ASP.NET MVC 4 Chapter 19. Deployment</a> <a href="http://www.youtube.com/watch?v=JXp30_yxyLM" rel="noreferrer">Deployment ASP.NET MVC 3 project to IIS and somee</a><br/><br/>
<strong>Question: What could be the cause of this issue :(</strong> It's my first time to deploy a website on the internet. Hopefully you could help me guys.. If you need more info please tell me. <br/><br/></p></li>
</ol>
<p><strong>My IIS Manager</strong>
<img src="https://i.stack.imgur.com/aA6PA.png" alt="enter image description here"><br/><br/>
<strong>My configuration</strong>
<img src="https://i.stack.imgur.com/4kqVo.png" alt="enter image description here"><br/><br/></p>
<p><strong>or could this be the reason of my issue?</strong><br/><br/>
<img src="https://i.stack.imgur.com/0yn8E.png" alt="enter image description here"><br/><br/> </p>
<hr>
<p><strong>OK THIS PROBLEM WAS SOLVED. I FOUND OUT THERE'S NO PROBLEM ON MY SETTINGS. THE PROBLEM IS ON THE SETTINGS OF THE WEBHOSTING SITE. I CHANGED THE ASP.NET VERSION FROM 2.0 TO 4.0 BUT FORGOT TO CLICK THE UPDATE BUTTON :( I FEEL BAD I HAVEN'T REALIZED THAT. I'M NOW FACING ANOTHER ERROR BUT IT HAS NOTHING TO DO WITH THIS QUESTION. THANKS GUYS FOR TRYING TO HELP ME :)</strong></p>
| 0 | 1,738 |
Getting No loop matching the specified signature and casting error
|
<p>I'm a beginner to python and machine learning . I get below error when i try to fit data into statsmodels.formula.api OLS.fit()</p>
<p>Traceback (most recent call last):</p>
<blockquote>
<p>File "", line 47, in
regressor_OLS = sm.OLS(y , X_opt).fit()</p>
<p>File
"E:\Anaconda\lib\site-packages\statsmodels\regression\linear_model.py",
line 190, in fit
self.pinv_wexog, singular_values = pinv_extended(self.wexog)</p>
<p>File "E:\Anaconda\lib\site-packages\statsmodels\tools\tools.py",
line 342, in pinv_extended
u, s, vt = np.linalg.svd(X, 0)</p>
<p>File "E:\Anaconda\lib\site-packages\numpy\linalg\linalg.py", line
1404, in svd
u, s, vt = gufunc(a, signature=signature, extobj=extobj)</p>
<p>TypeError: No loop matching the specified signature and casting was
found for ufunc svd_n_s</p>
</blockquote>
<p>code</p>
<pre><code>#Importing Libraries
import numpy as np # linear algebra
import pandas as pd # data processing
import matplotlib.pyplot as plt #Visualization
#Importing the dataset
dataset = pd.read_csv('Video_Games_Sales_as_at_22_Dec_2016.csv')
#dataset.head(10)
#Encoding categorical data using panda get_dummies function . Easier and straight forward than OneHotEncoder in sklearn
#dataset = pd.get_dummies(data = dataset , columns=['Platform' , 'Genre' , 'Rating' ] , drop_first = True ) #drop_first use to fix dummy varible trap
dataset=dataset.replace('tbd',np.nan)
#Separating Independent & Dependant Varibles
#X = pd.concat([dataset.iloc[:,[11,13]], dataset.iloc[:,13: ]] , axis=1).values #Getting important variables
X = dataset.iloc[:,[10,12]].values
y = dataset.iloc[:,9].values #Dependant Varible (Global sales)
#Taking care of missing data
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values = 'NaN' , strategy = 'mean' , axis = 0)
imputer = imputer.fit(X[:,0:2])
X[:,0:2] = imputer.transform(X[:,0:2])
#Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.2 , random_state = 0)
#Fitting Mutiple Linear Regression to the Training Set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train,y_train)
#Predicting the Test set Result
y_pred = regressor.predict(X_test)
#Building the optimal model using Backward Elimination (p=0.050)
import statsmodels.formula.api as sm
X = np.append(arr = np.ones((16719,1)).astype(float) , values = X , axis = 1)
X_opt = X[:, [0,1,2]]
regressor_OLS = sm.OLS(y , X_opt).fit()
regressor_OLS.summary()
</code></pre>
<p>Dataset</p>
<p><a href="https://www.dropbox.com/s/w2hq4t0utbvk7bu/Video_Games_Sales_as_at_22_Dec_2016.csv?dl=0" rel="noreferrer">dataset link</a></p>
<p>Couldn't find anything helpful to solve this issue on stack-overflow or google . </p>
| 0 | 1,121 |
throw exception without breaking loop in java
|
<p>I need to handle custom exception in java inside loop so i am throwing new custom exception but it breaks the loop. How we can manage to throw loop without breaking loop. Here is my code</p>
<pre><code> for (int i = 0; i < j; i++) {
File currFile = arrayOfFile1[i];
if (currFile.isFile()) {
if (currFile.exists()) {
try {
String fileName = currFile.getName();
if (fileName.startsWith("~$")) {
continue;
} else {
if ((fileName.endsWith(".xlsx")) || (fileName.endsWith(".xls"))) {
if (fileName.endsWith("_arch.xlsx") || fileName.endsWith("_arch.xls")) {
continue;
}
try {
IDSOutputGenerator.generateOutput(currFile.getAbsolutePath(), "", outputType,
false);
} catch (CheckErrorHandle e) {
throw new CheckErrorHandle();
}
}
else if (fileName.endsWith(".xml")) {
try {
IDSOutputGenerator.generateOutput(currFile.getAbsolutePath(), "", outputType,
false);
} catch (CheckErrorHandle e) {
throw new CheckErrorHandle();
}
} else {
throw new CheckErrorHandle(currFile.getAbsolutePath(), "File type not supported");
}
}
} catch (CheckErrorHandle e) {
throw new CheckErrorHandle();
} catch (Exception e) {
throw new CheckErrorHandle("", e.getMessage());
}
} else {
throw new CheckErrorHandle(currFile.getAbsolutePath(), "File does not exist");
}
}
}
</code></pre>
| 0 | 1,295 |
Ternary operator in LINQ where clause
|
<p>I am using linq for join multiple tables and write complex query. Here when i will have '0' as any parameter i.e. <code>CategoryId</code>, <code>GameId</code>, <code>LimitVariantId</code>, that means user has selected "All" from interface.</p>
<p>My Sql query, when I will pass parameter values greater than '0' is : </p>
<pre><code>select * from dbo.GameCombinations gc
inner join dbo.StakeBuyInByStakeCategories sbsc
on sbsc.StakeBuyInByStakeCategoryId = gc.StakeBuyInByStakeCategoryId
inner join dbo.GameTables gt
on gc.GameCombinationId = gt.GameCombinationId
where gc.CurrencyId=1 and gc.GameTypeId=2
and sbsc.StakeBuyInId=gt.BuyIn
and gc.CategoryId=4
and gc.GameId=7
and gc.LimitVariantId=23
and gc.StakeCategoryId in (3,5,6)
</code></pre>
<p>When I will pass CategoryId as <code>0</code> then My Sql query will be : </p>
<pre><code>select * from dbo.GameCombinations gc
inner join dbo.StakeBuyInByStakeCategories sbsc
on sbsc.StakeBuyInByStakeCategoryId = gc.StakeBuyInByStakeCategoryId
inner join dbo.GameTables gt
on gc.GameCombinationId = gt.GameCombinationId
where gc.CurrencyId=1 and gc.GameTypeId=2
and sbsc.StakeBuyInId=gt.BuyIn
--and gc.CategoryId=4
and gc.GameId=7
and gc.LimitVariantId=23
and gc.StakeCategoryId in (3,5,6)
</code></pre>
<p>So I don't need to include that fields in where clause. For that I had written the following LINQ:</p>
<pre><code>ProviderDB db = new ProviderDB();
try
{
IQueryable<dynamic> query;
if (StakeCategoryIdsByStakeBuyIn != null)
{
query = (from gc in db.GameCombinations.Where(x => x.CurrencyId == CurrencyId && x.GameTypeId == GameTypeId
&& CategoryId <= 0 ? true : x.CategoryId == CategoryId
&& GameId <= 0 ? true : x.GameId == GameId
&& LimitVariantId <= 0 ? true : x.LimitVariantId == LimitVariantId
&& StakeCategoryIdsByStakeBuyIn.Contains(x.StakeCategoryId)
)
join sbsc in db.StakeBuyInByStakeCategories
on gc.StakeBuyInByStakeCategoryId equals sbsc.StakeBuyInByStakeCategoryId
join gt in db.GameTables
on gc.GameCombinationId equals gt.GameCombinationId
join gx in db.Games
on gc.GameId equals gx.GameId into joined
from gx in joined.DefaultIfEmpty()
where gt.BuyIn == sbsc.StakeBuyInId
select new
{
GameTableId = gt.GameTableId,
Description = gt.Description,
BuyIn = gt.BuyIn,
Table = gx.GameName,
MaxAllowPlayer = gt.MaxAllowPlayer
}).Distinct();
}
else
{
query = (from gc in db.GameCombinations.Where(x => x.CurrencyId == CurrencyId && x.GameTypeId == GameTypeId
&& CategoryId == 0 ? true : x.CategoryId == CategoryId
&& GameId == 0 ? true : x.GameId == GameId
&& LimitVariantId == 0 ? true : x.LimitVariantId == LimitVariantId
&& StakeCategoryIdsByStakeBuyIn == null
)
join sbsc in db.StakeBuyInByStakeCategories
on gc.StakeBuyInByStakeCategoryId equals sbsc.StakeBuyInByStakeCategoryId
join gt in db.GameTables
on gc.GameCombinationId equals gt.GameCombinationId
join sb in db.StakeBuyIns
on gt.BuyIn equals sb.StakeBuyInId
join gx in db.Games
on gc.GameId equals gx.GameId into joined
from gx in joined.DefaultIfEmpty()
where gt.BuyIn == sbsc.StakeBuyInId
select new
{
GameTableId = gt.GameTableId,
Description = gt.Description,
BuyIn = sb.StakeBuyInValue,
Table = gx.GameName,
MaxAllowPlayer = gt.MaxAllowPlayer
}).Distinct();
}
</code></pre>
<p>But this will return all fields from my database. So Can any one help me to write these queries in LINQ with ternary condition that will return my filtered fields' records?</p>
| 0 | 2,209 |
Avoid using document.write() occurs when trying to load a dashboard page in Chrome
|
<p>So I have been stuck on this problem for longer than i'd care to admit but as a Angular newbie I am completely baffled.</p>
<p>So I am following some online tutorials in order to implement Gulp into an application I am working on and whenever I run the Gulp tasks I get an error in Chrome which states: </p>
<blockquote>
<p><strong>"[Violation] Avoid using document.write().(anonymous) @ (index):13"</strong></p>
</blockquote>
<p>and: </p>
<blockquote>
<p><strong>//\/script>".replace("HOST",
location.hostname)); //]]></strong></p>
</blockquote>
<p>I am even more confused as the index.html doesn't actually contain a document.write reference before execution. Also despite mostly following a tutorial when integrating Gulp I cannot seem to have the CSS background changes reflected on screen, could this be related to the previously mentioned error?</p>
<p><strong>index.html</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<title>SmartSystemOverviewWeb</title>
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="app/css/styles.css" rel="stylesheet">
</head>
<body>
<sso-dashboard>
Loading...
<i class="fa fa-spinner fa-spin"></i>
</sso-dashboard>
<script type="text/typescript" src="app/vendor.ts"></script>
<!-- <script src="app/app.component.js"></script> -->
</body>
</html></code></pre>
</div>
</div>
</p>
<p><strong>gulpfile.js</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var tsc = require('gulp-typescript');
var tslint = require('gulp-tslint');
var tsProject = tsc.createProject('tsconfig.json');
var config = require('./gulp.config')();
var browserSync = require('browser-sync').create();
var superstatic = require('superstatic');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var minifyCSS = require('gulp-minify-css');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var del = require('del');
var runSequence = require('run-sequence');
/*
-- TOP LEVEL FUNCTIONS --
gulp.task - Define tasks
gulp.src - point to files to use
gulp.dest - point to folder to output
gulp.watch - watch files + folders for changes
*/
// Logs Message
gulp.task('message', function(){
return console.log('Gulp is running...');
});
gulp.task('ts-lint', function() {
console.log('ts-lint task running...');
return gulp.src(config.allTs)
.pipe(tslint())
.pipe(tslint({
formatter: "verbose"
}))
// .pipe(tslint.report("verbose"))
})
gulp.task('compile-ts', function() {
console.log('compile-ts task running...');
var sourceTsFiles = [
config.allTs,
config.typings
];
var tsResult = gulp
.src(sourceTsFiles)
.pipe(sourcemaps.init())
.pipe(tsProject())
return tsResult.js
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(config.tsOutputPath));
});
gulp.task('sass', function(){
console.log('sass is running...');
// return gulp.src('src/app/styles.scss')
return gulp.src('src/app/**/*.scss')
.pipe(sass()) // Using gulp-sass
.pipe(gulp.dest('src/app/css'))
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('browserSync', function() {
console.log('browserSync is running...');
browserSync.init({
// port: 4200,
// file: ['index.html', '**/*.js'],
// injectChanges: true,
// logFileChanges: true,
// logLevel: 'verbose',
// notify: true,
// reloadDelay: 0,
server: {
baseDir: 'src',
middleware: superstatic({debug: false})
},
})
})
gulp.task('watch', ['browserSync', 'sass'], function(){
gulp.watch('src/app/**/*.scss', ['sass']);
gulp.watch('src/app/component/**/*.scss', ['sass']);
// Reloads the browser whenever HTML or JS files change
gulp.watch('src/app/**/*.html', browserSync.reload);
gulp.watch('src/app/component/**/*.html', browserSync.reload);
gulp.watch('src/app/**/*.js', browserSync.reload);
gulp.watch('src/app/component/**/*.js', browserSync.reload);
gulp.watch('src/*.html', browserSync.reload);
})
gulp.task('useref', function() {
var assets = useref.assets();
return gulp.src('app/*.html')
.pipe(assets)
.pipe(gulpIf('*.css', minifyCSS()))
.pipe(gulpIf('*.js', uglify()))
.pipe(assets.restore())
.pipe(useref())
.pipe(gulp.dest('dist'))
});
gulp.task('images', function() {
return gulp.src('app/images/**/*.+(png|jpg|jpeg|gif|svg)')
.pipe(cache(imagemin( {
interlaced: true
})))
.pipe(gulp.dest('dist/images'))
});
gulp.task('fonts', function() {
return gulp.src('app/fonts/**/*')
.pipe(gulp.dest('dist/fonts'))
});
// Cleaning
gulp.task('clean', function(callback) {
del('dist');
return cache.clearAll(callback);
})
gulp.task('clean:dist', function(callback) {
del(['dist/**/*', '!dist/images', '!dist/images/**/*'], callback)
});
// Build Sequences
gulp.task('build', function (callback) {
runSequence('clean:dist',
['sass', 'useref', 'images', 'fonts'],
callback
)
})
gulp.task('default', function (callback) {
runSequence(['message', 'ts-lint', 'sass', 'browserSync', 'watch'],
callback
)
})</code></pre>
</div>
</div>
</p>
<p><strong>styles.css</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.testing {
width: 71.42857%; }
.head {
background: red; }
.body {
background: #177794; }
.html {
background: green; }</code></pre>
</div>
</div>
</p>
<p>Any tips or advice to solve these issues would be greatly appreciated! </p>
<p>Thanks in advance!</p>
| 0 | 2,587 |
Spring / Hibernate / JUnit - No Hibernate Session bound to Thread
|
<p>I'm trying to access the current hibernate session in a test case, and getting the following error:</p>
<blockquote>
<p>org.hibernate.HibernateException: No
Hibernate Session bound to thread, and
configuration does not allow creation
of non-transactional one here at
org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
at
org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:574)</p>
</blockquote>
<p>I've clearly missed some sort of setup, but not sure what.</p>
<p>Any help would be greatly appreciated. This is my first crack at Hibernate / Spring etc, and the learning curve is certainly steep!</p>
<p>Code follows:</p>
<p>The offending class:</p>
<pre><code>public class DbUnitUtil extends BaseDALTest {
@Test
public void exportDtd() throws Exception
{
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Connection hsqldbConnection = session.connection();
IDatabaseConnection connection = new DatabaseConnection(hsqldbConnection);
// write DTD file
FlatDtdDataSet.write(connection.createDataSet(), new FileOutputStream("test.dtd"));
}
}
</code></pre>
<p>Base class:</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class BaseDALTest extends AbstractJUnit4SpringContextTests {
public BaseDALTest()
{
super();
}
@Resource
protected SessionFactory sessionFactory;
}
</code></pre>
<p>applicationContext.xml:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>org.hsqldb.jdbcDriver</value>
</property>
<property name="url">
<value>jdbc:hsqldb:mem:sample</value>
</property>
<property name="username">
<value>sa</value>
</property>
<property name="password">
<value></value>
</property>
</bean>
<bean id="sessionFactory" class="com.foo.spring.AutoAnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="entityPackages">
<list>
<value>com.sample.model</value>
</list>
</property>
<property name="schemaUpdate">
<value>true</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</beans>
</code></pre>
| 0 | 1,479 |
How to execute a long dynamic query (greater than 4000) characters - again
|
<p>Note: I'm running under SQL Server 2008 R2...</p>
<p>I've taken the time to read dozens of posts on this site and other sites on how to execute dynamic SQL where the query is more than 4000 characters. I've tried more than a dozen solutions proposed. The consensus seems to be to split the query into 4000-character variables and then do:</p>
<pre><code>EXEC (@SQLQuery1 + @SQLQuery2)
</code></pre>
<p>This doesn't work for me - the query is truncated at the end of @SQLQuery1.</p>
<p>Now, I've seen samples how people "force" a long query by using REPLICATE a bunch of spaces, etc., but this is a real query - but it gets a little more sophisticated than that.</p>
<p>I have SQL View with a name of "Company_A_ItemView".</p>
<p>I have 10 companies that I want to create the same exact view, with different names, e.g.
"Company_B_ItemView"
"Company_C_ItemView"
..etc.</p>
<p>If you offer help, please don't ask why there are multiple views - just accept that I need to do it this way, OK?</p>
<p>Each company has its own set of tables, and the CREATE VIEW statement references several tables by name. Here's BRIEF sample, but remember, the total length of the query is around 6000 characters:</p>
<pre><code>CREATE view [dbo].[Company_A_ItemView] as
select
WE.[Item No_],
WE.[Location Code],
LOC.[Bin Number],
[..more fields, etc.]
from
[Company_A_Warehouse_Entry] WE
left join
[Company_A_Location] LOC
</code></pre>
<p>...you get the idea</p>
<p>So, what I am currently doing is:</p>
<p>a. Pulling the contents of the CREATE VIEW statement into 2 Declared Variables, e.g.</p>
<pre><code>Set @SQLQuery1 = (select text
from syscomments
where ID = 1382894081 and colid = 1)
Set @SQLQuery2 = (select
from syscomments
where ID = 1382894081 and colid = 2)
</code></pre>
<p>Note that this is how SQL stores long definitions - when you create the view, it stores the text into multiple syscomments records. In my case, the view is split into a text chunk of 3591 characters into the first syscomment record and the rest of the text is in the second record. I have no idea why SQL doesn't use all 4000 characters in the syscomment field. And the statement is broken in the middle of a word.</p>
<p>Please note in all my examples, all @SQLQueryxxx variables are declared as varchar(max). I've also tried declaring them as nvarchar(max) and varchar(8000) and nvarchar(8000) with the same results.</p>
<p>b. I then do a "Search and Replace" for "Company_A" and replace it with "Company_B". In the code below, the variable "@CompanyID" is first set to "Company_B":</p>
<pre><code>SET @SQLQueryNew1 = @SQLQuery1
SET @SQLQueryNew1 = REPLACE(@SQLQueryNew1, 'Company_A', @CompanyID)
SET @SQLQueryNew2 = @SQLQuery2
SET @SQLQueryNew2 = REPLACE(@SQLQueryNew2, 'Company_A',@CompanyID)
</code></pre>
<p>c. I then try:</p>
<pre><code>EXEC (@SQLQueryNew1 + @SQLQueryNew2)
</code></pre>
<p>The message returned indicates that it's trying to execute the statement truncated at the end of @SQLQueryNew1, e.g. 80% (approx) of the query's text.</p>
<p>I've tried CAST'ing the final result into a new varchar(max) and nvarchar(max) - no luck
I've tried CAST'ing the original query a new varchar(max) and nvarchar(max)- no luck</p>
<p>I've looked at the result of retrieving the original CREATE VIEW statement, and it's fine.</p>
<p>I've tried various other ways of retrieving the original CREATE VIEW statement, such as:</p>
<pre><code>Set @SQLQuery1 = (select VIEW_DEFINITION)
FROM [MY_DATABASE].[INFORMATION_SCHEMA].[VIEWS]
where TABLE_NAME = 'Company_A_ItemView')`
</code></pre>
<p>This one returns only the first 4000 characters of the CREATE VIEW </p>
<pre><code>Set @SQLQuery1 = (SELECT (OBJECT_DEFINITION(@ObjectID))
</code></pre>
<p>If I do a </p>
<pre><code>SELECT LEN(OBJECT_DEFINITION(@ObjectID))
</code></pre>
<p>it returns the correct length of the query (e.g. 5191), but if I look at @SQLQuery1, or try to </p>
<pre><code>EXEC(@SQLQuery1), the statement is still truncated.
</code></pre>
<p>c. There are some references that state that since I'm manipulating the text of the query after retrieving it, the resulting variables are then truncated to 4000 characters. I've tried CAST'ing the result as I do the REPLACE, e.g.</p>
<pre><code>SET @SQLQueryNew1 = SELECT (CAST(REPLACE(@SQLQueryNew1,
'Company_A',
@CompanyID) AS varchar(max))
</code></pre>
<p>Same result.</p>
<p>I know there are other methods, such as creating stored procedures for creating the views. But the views are being developed and are somewhat "in flux", so placing the text of the CREATE VIEW inside a stored proc is cumbersome. My goal is to be able to take Company_A's view and replicate it exactly - multiple times, except reference Company_B's view name and table names, Company_C's view name and table names, etc.</p>
<p>I'm wondering if there is anyone out there who has done this type of manipulation of a long SQL "CREATE VIEW" statement and try to execute it.</p>
| 0 | 1,792 |
Error:This class should provide a default constructor (a public constructor with no arguments) [Instantiatable] in Android
|
<p>I am generating the file apk with Generated Signed APK in Android Studio, but I have this error:</p>
<blockquote>
<p>Error:Error: This class should provide a default constructor (a public constructor with no arguments) (com.actua.actuaconsultores.actuamindfulness.GridImagenAdaptar) [Instantiatable]</p>
</blockquote>
<p>my class is:</p>
<pre><code>public class GridImagenAdaptar extends BaseAdapter {
private final Context mContext;
private final ArrayList<ModelImage> mGridItems;
public GridImagenAdaptar(Context mContext, ArrayList<ModelImage> mGridItems) {
this.mContext = mContext;
this.mGridItems = mGridItems;
}
public int getCount() {
return mGridItems.size();
}
public Object getItem(int position) {
return mGridItems.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
if( convertView == null)
{ // If ReusedView doesn't exist
convertView = inflatedViewWithContextInParentView(R.layout.activity_grid_imagen_adaptar, mContext, parent);
convertView.setTag("HomeMenuCell"); // Reuse Identifier
}
fillViewWithItemAtIndex(convertView, position);
return convertView;
}
private View inflatedViewWithContextInParentView(int id, Context context, ViewGroup parentView)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Service.LAYOUT_INFLATER_SERVICE);
View inflatedView = inflater.inflate(id, parentView, false);
return inflatedView;
}
private void fillViewWithItemAtIndex(View reusedView, int index)
{
ModelImage item = mGridItems.get(index);
item.setId(index);
TextView title = (TextView) reusedView.findViewById(R.id.title);
title.setText(item.title);
ImageView picture = (ImageView) reusedView.findViewById(R.id.image);
int resourceID = getIDForResourceName(item.imageName);
picture.setImageResource(resourceID);
}
private int getIDForResourceName(String name)
{
try {
Class res = R.drawable.class;
Field field = res.getField(name);
int drawableId = field.getInt(null);
return drawableId;
}
catch (Exception e) {
Log.e("GridItemsAdapter", "Error: Couldn't get a drawable id.", e);
}
return -1;
}
}
</code></pre>
<p>What is the problem?</p>
<p>Thanks</p>
| 0 | 1,041 |
How can I make viewpager loop?
|
<p>I want my ViewPager implementation to cycle between views instead of stopping at the last view. For example, if I have 3 views to display via a ViewPager, it should return back to the first View after the third View on fling instead of stopping at that third view. I want it to return to the first page/view when the user flings forward on the last page</p>
<p>Loop example;</p>
<p>A,B,C,D <--- A,B,C,D ---> A,B,C,D</p>
<p>Thanks a lot,</p>
<p>Mypageradapter;</p>
<pre><code>package com.example.pictures;
import android.content.Context;
import android.media.AudioManager;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
public class MyPagerAdapter extends PagerAdapter{
public int getCount() {
return 6;
}
public Object instantiateItem(View collection, int position) {
View view=null;
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.picture1;
view = inflater.inflate(resId, null);
break;
case 1:
resId = R.layout.picture2;
view = inflater.inflate(resId, null);
break;
case 2:
resId = R.layout.picture3;
view = inflater.inflate(resId, null);
break;
case 3:
resId = R.layout.picture4;
view = inflater.inflate(resId, null);
break;
case 4:
resId = R.layout.picture5;
view = inflater.inflate(resId, null);
break;
case 5:
resId = R.layout.picture6;
view = inflater.inflate(resId, null);
break;
}
((ViewPager) collection).addView(view, 0);
return view;
}
@SuppressWarnings("unused")
private Context getApplicationContext() {
// TODO Auto-generated method stub
return null;
}
private void setVolumeControlStream(int streamMusic) {
// TODO Auto-generated method stub
}
@SuppressWarnings("unused")
private Context getBaseContext() {
// TODO Auto-generated method stub
return null;
}
@SuppressWarnings("unused")
private PagerAdapter findViewById(int myfivepanelpager) {
// TODO Auto-generated method stub
return null;
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
@Override
public Parcelable saveState() {
return null;
}
public static Integer getItem(int position) {
// TODO Auto-generated method stub
return null;
}
}
</code></pre>
<p>OnPageChangeListener;</p>
<pre><code>package com.example.pictures;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class Pictures extends Activity implements OnPageChangeListener{
SoundManager snd;
int sound1,sound2,sound3;
View view=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.picturespage);
MyPagerAdapter adapter = new MyPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
myPager.setOnPageChangeListener(this);
snd = new SoundManager(this);
sound1 = snd.load(R.raw.sound1);
sound2 = snd.load(R.raw.sound2);
sound3 = snd.load(R.raw.sound3);
}
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
public void onPageSelected(int position) {
// TODO Auto-generated method stub
switch (position) {
case 0:
snd.play(sound1);
break;
case 1:
snd.play(sound2);
break;
case 2:
snd.play(sound3);
break;
case 3:
Toast.makeText(this, "1", Toast.LENGTH_SHORT).show();
break;
case 4:
Toast.makeText(this, "2", Toast.LENGTH_SHORT).show();
break;
case 5:
Toast.makeText(this, "3", Toast.LENGTH_SHORT).show();
break;
}
}
};
</code></pre>
| 0 | 1,770 |
Save SSRS Report as PDF in C# programmatically
|
<p>I've read through multiple articles regarding this issue however they have all ended up with it not working, or are in vb.net. </p>
<p><strong>What I currently have:</strong></p>
<p>The reports are accessed via a URL which renders them as a PDF and saves them in the downloads folder when the user clicks on a button, these are given generic names such as OrderReport, OrderReport(1)... and so on.</p>
<pre><code>var orderNum = 1;
"http://Server/ReportServer_Name/Pages/ReportViewer.aspx?%2fOrderReport&rs:Command=Render&OrderID=" + orderNum + "&rs:ClearSession=true&rs:Format=PDF"
</code></pre>
<p><strong>What I am trying to acheive:</strong></p>
<ul>
<li>I would like to use C# to fetch this report if possible, and then specify a name for the PDF file and save it in the correct location. </li>
</ul>
<p>so for example I would like to save this report in a temporary folder for now "<strong>C:\temp</strong>" with the name <strong>OrderID-1</strong>. I am using C#</p>
<p>I have added in a ServiceReference into the Project i am using called ReportTestings so the reference is </p>
<pre><code>using ReportTestings;
</code></pre>
<p>and the Web Reference URL:</p>
<p><a href="http://Server/ReportServer_Name/ReportExecution2005.asmx" rel="noreferrer">http://Server/ReportServer_Name/ReportExecution2005.asmx</a></p>
<p>(removed the actual names for security reasons) </p>
<p>so based on all of this information above could someone point me in the right direction or give an example part of code, Thankyou for all that read this post or help</p>
<p>using this code i get this error :(+ e </p>
<pre><code>{"Access to the path 'C:\\Program Files (x86)\\IIS Express\\report1one.pdf' is denied."} System.Exception {System.UnauthorizedAccessException})
</code></pre>
<p>code:</p>
<pre><code> ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = new NetworkCredential("username", "password", "domain");
rs.Url = "http://Server/ReportServer_Name/reportexecution2005.asmx";
// Render arguments
byte[] result = null;
string reportPath = "/Invoice";
string format = "PDF";
string historyID = null;
string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
// Prepare report parameter.
ParameterValue[] parameters = new ParameterValue[3];
parameters[0] = new ParameterValue();
parameters[0].Name = "InvoiceID";
parameters[0].Value = "2";
DataSourceCredentials[] credentials = null;
string showHideToggle = null;
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
ParameterValue[] reportHistoryParameters = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, historyID);
rs.SetExecutionParameters(parameters, "en-us");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
Console.WriteLine("SessionID: {0}", rs.ExecutionHeaderValue.ExecutionID);
try
{
result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
Console.WriteLine("Execution date and time: {0}", execInfo.ExecutionDateTime);
}
catch (SoapException e)
{
Console.WriteLine(e.Detail.OuterXml);
}
// Write the contents of the report to an MHTML file.
try
{
FileStream stream = File.Create("report1one.pdf", result.Length);
Console.WriteLine("File created.");
stream.Write(result, 0, result.Length);
Console.WriteLine("Result written to the file.");
stream.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
</code></pre>
| 0 | 1,344 |
How to add Custom Column in sales/order grid in Magento?
|
<p>I am trying to add custom columns to my sales/order grid. My columns will be the tracking number and the tile. The title is basically the courier code which shows you through which courier you have send you product.
So i have done some following things for this.</p>
<ol>
<li>I have copied the file from <code>magento/app/code/core/Mage/Adminhtml/Block/Sales/Order/Grid.php</code> to</li>
</ol>
<p>magento/app/code/local/Mage/Adminhtml/Block/Sales/Order/Grid.php</p>
<p>so that i can add columns and customize my sales/order grid.</p>
<ol start="2">
<li>In the file Grid.php, There is _prepareCollections() functions.</li>
</ol>
<p>Here the code goes into it. </p>
<pre><code>protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
$this->setCollection($collection);
$collection->getSelect();
$collection->getSelect()->join('sales_flat_shipment_track', 'main_table.entity_id =sales_flat_shipment_track.order_id',array('track_number'=> new Zend_Db_Expr('group_concat(sales_flat_shipment_track.track_number SEPARATOR ",")'),'title' => new Zend_Db_Expr('group_concat(sales_flat_shipment_track.title SEPARATOR ",")')));
return parent::_prepareCollection();
}
</code></pre>
<p>And Now i will add my columns here in my _prepareColumns() function. Code for that is</p>
<pre><code>protected function _prepareColumns()
{
$this->addColumn('track_number', array(
'header'=> Mage::helper('sales')->__(' Track Number'),
'width' => '80px',
'type' => 'text',
'index' => 'track_number',
));
$this->addColumn('title', array(
'header'=> Mage::helper('sales')->__('Title'),
'width' => '80px',
'index' => 'title',
));
</code></pre>
<p>The file Grid.php is here.</p>
<pre><code><?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Adminhtml
* @copyright Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Adminhtml sales orders grid
*
* @category Mage
* @package Mage_Adminhtml
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Adminhtml_Block_Sales_Order_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
parent::__construct();
$this->setId('sales_order_grid');
$this->setUseAjax(true);
$this->setDefaultSort('created_at');
$this->setDefaultDir('DESC');
$this->setSaveParametersInSession(true);
}
/**
* Retrieve collection class
*
* @return string
*/
protected function _getCollectionClass()
{
return 'sales/order_grid_collection';
}
protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
$this->setCollection($collection);
$collection->getSelect();
$collection->getSelect()->join('sales_flat_shipment_track', 'main_table.entity_id =sales_flat_shipment_track.order_id',array('track_number'=> new Zend_Db_Expr('group_concat(sales_flat_shipment_track.track_number SEPARATOR ",")'),'title' => new Zend_Db_Expr('group_concat(sales_flat_shipment_track.title SEPARATOR ",")')));
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
$this->addColumn('track_number', array(
'header'=> Mage::helper('sales')->__(' Track Number'),
'width' => '80px',
'type' => 'text',
'index' => 'track_number',
));
$this->addColumn('title', array(
'header'=> Mage::helper('sales')->__('Title'),
'width' => '80px',
'index' => 'title',
));
$this->addColumn('real_order_id', array(
'header'=> Mage::helper('sales')->__('Order #'),
'width' => '80px',
'type' => 'text',
'index' => 'increment_id',
));
if (!Mage::app()->isSingleStoreMode()) {
$this->addColumn('store_id', array(
'header' => Mage::helper('sales')->__('Purchased From (Store)'),
'index' => 'store_id',
'type' => 'store',
'store_view'=> true,
'display_deleted' => true,
));
}
$this->addColumn('created_at', array(
'header' => Mage::helper('sales')->__('Purchased On'),
'index' => 'created_at',
'type' => 'datetime',
'width' => '100px',
));
$this->addColumn('billing_name', array(
'header' => Mage::helper('sales')->__('Bill to Name'),
'index' => 'billing_name',
));
$this->addColumn('shipping_name', array(
'header' => Mage::helper('sales')->__('Ship to Name'),
'index' => 'shipping_name',
));
$this->addColumn('base_grand_total', array(
'header' => Mage::helper('sales')->__('G.T. (Base)'),
'index' => 'base_grand_total',
'type' => 'currency',
'currency' => 'base_currency_code',
));
$this->addColumn('grand_total', array(
'header' => Mage::helper('sales')->__('G.T. (Purchased)'),
'index' => 'grand_total',
'type' => 'currency',
'currency' => 'order_currency_code',
));
$this->addColumn('status', array(
'header' => Mage::helper('sales')->__('Status'),
'index' => 'status',
'type' => 'options',
'width' => '70px',
'options' => Mage::getSingleton('sales/order_config')->getStatuses(),
));
if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/view')) {
$this->addColumn('action',
array(
'header' => Mage::helper('sales')->__('Action'),
'width' => '50px',
'type' => 'action',
'getter' => 'getId',
'actions' => array(
array(
'caption' => Mage::helper('sales')->__('View'),
'url' => array('base'=>'*/sales_order/view'),
'field' => 'order_id',
'data-column' => 'action',
)
),
'filter' => false,
'sortable' => false,
'index' => 'stores',
'is_system' => true,
));
}
$this->addRssList('rss/order/new', Mage::helper('sales')->__('New Order RSS'));
$this->addExportType('*/*/exportCsv', Mage::helper('sales')->__('CSV'));
$this->addExportType('*/*/exportExcel', Mage::helper('sales')->__('Excel XML'));
return parent::_prepareColumns();
}
protected function _prepareMassaction()
{
$this->setMassactionIdField('entity_id');
$this->getMassactionBlock()->setFormFieldName('order_ids');
$this->getMassactionBlock()->setUseSelectAll(false);
if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/cancel')) {
$this->getMassactionBlock()->addItem('cancel_order', array(
'label'=> Mage::helper('sales')->__('Cancel'),
'url' => $this->getUrl('*/sales_order/massCancel'),
));
}
if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/hold')) {
$this->getMassactionBlock()->addItem('hold_order', array(
'label'=> Mage::helper('sales')->__('Hold'),
'url' => $this->getUrl('*/sales_order/massHold'),
));
}
if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/unhold')) {
$this->getMassactionBlock()->addItem('unhold_order', array(
'label'=> Mage::helper('sales')->__('Unhold'),
'url' => $this->getUrl('*/sales_order/massUnhold'),
));
}
$this->getMassactionBlock()->addItem('pdfinvoices_order', array(
'label'=> Mage::helper('sales')->__('Print Invoices'),
'url' => $this->getUrl('*/sales_order/pdfinvoices'),
));
$this->getMassactionBlock()->addItem('pdfshipments_order', array(
'label'=> Mage::helper('sales')->__('Print Packingslips'),
'url' => $this->getUrl('*/sales_order/pdfshipments'),
));
$this->getMassactionBlock()->addItem('pdfcreditmemos_order', array(
'label'=> Mage::helper('sales')->__('Print Credit Memos'),
'url' => $this->getUrl('*/sales_order/pdfcreditmemos'),
));
$this->getMassactionBlock()->addItem('pdfdocs_order', array(
'label'=> Mage::helper('sales')->__('Print All'),
'url' => $this->getUrl('*/sales_order/pdfdocs'),
));
$this->getMassactionBlock()->addItem('print_shipping_label', array(
'label'=> Mage::helper('sales')->__('Print Shipping Labels'),
'url' => $this->getUrl('*/sales_order_shipment/massPrintShippingLabel'),
));
return $this;
}
public function getRowUrl($row)
{
if (Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/view')) {
return $this->getUrl('*/sales_order/view', array('order_id' => $row->getId()));
}
return false;
}
public function getGridUrl()
{
return $this->getUrl('*/*/grid', array('_current'=>true));
}
}
</code></pre>
<p>Now I am getting the columns Tracking Number and Title on my Grid. But in my tracking number ,its showing me the duplicate entries.
For example, If my tracking number is 12345678, It shows me two values which are same, Like this. 12345678,12345678. </p>
<p>Also in my title, It shows Federal Express,Federal express for two times. </p>
<p>What i want is two things, </p>
<p>a. First There can be 2 tracking nos, or more than that. But it should be shown like this. ex. 12345678,12345678900. It should be distinct. </p>
<p>For some of my order no it shows distinct. But most of them have duplicate entries.</p>
<p>b. Secondly if the courier is send by federal express and then if the product returns and we send by bluedart
then it should show federal express, bluedart .
But what i am getting is federal express,federal express, blue dart,blue dart. </p>
<p>It is showing me 4 times. </p>
<p>I don't know what exactly problem i am facing. Is der any database problem or the query i have written. </p>
<p>Please let me know whether </p>
<pre><code>protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
$this->setCollection($collection);
$collection->getSelect();
$collection->getSelect()->join('sales_flat_shipment_track', 'main_table.entity_id =sales_flat_shipment_track.order_id',array('track_number'=> new Zend_Db_Expr('group_concat(sales_flat_shipment_track.track_number SEPARATOR ",")'),'title' => new Zend_Db_Expr('group_concat(sales_flat_shipment_track.title SEPARATOR ",")')));
return parent::_prepareCollection();
}
</code></pre>
<p>This function is correct and also the query written in it. </p>
<p><strong>Edited PArt</strong></p>
<p>I also want to filter the track_number and title in my grid.php. I have tried some of the things. </p>
<p>This code goes in grid.php, </p>
<pre><code>protected function spaceSeparatedFilter($collection, $column)
{
$value = $column->getFilter()->getValue();
if (!$value) {
return $this;
}
//if there was a space input
else if(preg_match('/s+/', $value))
{
//explode by space, getting array of IDs
$val = explode(" ", $value);
//filter the collection, where collection index (order_id) is present in $val array
$this->getCollection()->addAttributeToFilter($column->getData('index'), array('in'=>$val));
}
else
{
//else use default grid filter functionality (like $value input)
$this->getCollection()->addAttributeToFilter($column->getData('index'), array('like' => '%'.$value.'%'));
}
return $this;
}
</code></pre>
<p>Now i have added filter condition to my addcolumn,</p>
<pre><code>$this->addColumn('track_number', array(
'header'=> Mage::helper('sales')->__(' Track Number'),
'width' => '80px',
'type' => 'text',
'index' => 'track_number',
'filter_condition_callback' => array($this, 'spaceSeparatedFilter'),
));
$this->addColumn('title', array(
'header'=> Mage::helper('sales')->__('Title'),
'width' => '80px',
'index' => 'title',
'filter_condition_callback' => array($this, 'spaceSeparatedFilter'),
));
</code></pre>
<p>But i am not able to filter in my sales/order grid. Please let me know the solution for this.</p>
<p>Thanks and Regards.</p>
| 0 | 6,815 |
LiveData is not updating its value after first call
|
<p>I have been beating my head against the wall and I cannot understand why this is happening. I am working with the new Architectural Components for Android and I am having problems updating a LiveData with a List of Objects.
I have two spinners. When i change the option in the first one, The second one must have its content changed. But this last part is not happening.
Can anyone help me?</p>
<p><strong>State.java</strong></p>
<pre><code>@Entity(tableName = "states")
public class State{
@PrimaryKey(autoGenerate = false)
private int id;
private String name;
@ColumnInfo(name = "countryId")
private String CountryId;
@Ignore
private Object geoCenter, geoLimit;
public State(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountryId() {
return CountryId;
}
public void setCountryId(String countryId) {
CountryId = countryId;
}
}
</code></pre>
<p><strong>StateDAO</strong></p>
<pre><code>@Dao
public interface StateDao {
@Query("SELECT * FROM states")
LiveData<List<State>> getAllStates();
@Query("SELECT * FROM states WHERE countryId = :countryID")
LiveData<List<State>> getStatesFromCountry(String countryID);
@Query("SELECT COUNT(*) FROM states")
int getNrStates();
@Query("SELECT COUNT(*) FROM states WHERE countryId = :countryID")
int getNrStatesByCountry(String countryID);
@Insert(onConflict = IGNORE)
void insertAll(List<State> states);
@Delete
void delete(State state);
}
</code></pre>
<p><strong>StateRepository</strong></p>
<pre><code>@Singleton
public class StatesRepository {
private final WebServices services;
private final StateDao stateDao;
private final Executor executor;
@Inject
public StatesRepository(Executor executor, StateDao stateDao, WebServices services) {
this.services = services;
this.stateDao = stateDao;
this.executor = executor;
}
public LiveData<List<State>> getStates(String token){
refreshStates(token);
return stateDao.getAllStates();
}
public LiveData<List<State>> getStatesFromCountry(String countryID){
return stateDao.getStatesFromCountry(countryID);
}
private void refreshStates(final String token){
executor.execute(() -> {
Log.d("oooooo", stateDao.getNrStates() + "");
if(stateDao.getNrStates() == 0){
try {
Response<List<State>> response = services.getStates("Bearer "+token).execute();
stateDao.insertAll(response.body());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
</code></pre>
<p><strong>StateViewModel</strong></p>
<pre><code>public class StatesViewModel extends ViewModel {
private LiveData<List<State>> states;
private StatesRepository repo;
@Inject
public StatesViewModel(StatesRepository repository){
this.repo = repository;
}
public void init(String token){
states = repo.getStates(token);
}
public void getStatesFromCountry(String countryID){
states = repo.getStatesFromCountry(countryID);
}
public LiveData<List<State>> getStates(){
return this.states;
}
}
</code></pre>
<p><strong>Fragment</strong></p>
<pre><code>public class EditAddressFragment extends LifecycleFragment implements View.OnClickListener, Injectable{
private Spinner country, city, state, zip_code;
private String token;
private List<Country> countries;
private List<City> cities;
private List<State> states;
@Inject ViewModelFactory viewModelFactory;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.addresses_edit_layout, container, false);
city = view.findViewById(R.id.city);
state = view.findViewById(R.id.state);
country = view.findViewById(R.id.country);
...
countries = new ArrayList<>();
cities = new ArrayList<>();
states = new ArrayList<>();
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
CountrySpinnerAdapter adapter = new CountrySpinnerAdapter(getActivity(), android.R.layout.simple_spinner_item, countries);
country.setAdapter(adapter);
CitySpinnerAdapter cityAdapter = new CitySpinnerAdapter(getActivity(), android.R.layout.simple_spinner_item, cities);
city.setAdapter(cityAdapter);
StateSpinnerAdapter stateAdapter = new StateSpinnerAdapter(getActivity(), android.R.layout.simple_spinner_item, states);
state.setAdapter(stateAdapter);
CountriesViewModel countriesViewModel = ViewModelProviders.of(this, viewModelFactory).get(CountriesViewModel.class);
countriesViewModel.init(token);
countriesViewModel.getCountries().observe(this, adapter::setValues);
CityViewModel cityViewModel = ViewModelProviders.of(this, viewModelFactory).get(CityViewModel.class);
cityViewModel.init(token);
cityViewModel.getCities().observe(this, cityAdapter::setValues);
StatesViewModel statesViewModel = ViewModelProviders.of(this, viewModelFactory).get(StatesViewModel.class);
statesViewModel.init(token);
statesViewModel.getStates().observe(this, states -> {
Log.d("called", states.toString());
stateAdapter.setValues(states); } );
country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Country c = (Country) adapterView.getItemAtPosition(i);
Log.d("cd", c.getId());
//states = new ArrayList<State>();
statesViewModel.getStatesFromCountry(c.getId());
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
</code></pre>
<p>....</p>
<p><strong>Adapter</strong></p>
<pre><code>public void setValues(List<State> states)
{
this.states = states;
Log.d("s", states.isEmpty()+" "+states.toString());
notifyDataSetChanged();
}
</code></pre>
| 0 | 2,239 |
How to Get ImageView Bring to front on touch event of ImageView?
|
<p>I have two <code>ImageView</code> in two different layouts, the One <code>ImageView</code> is on another <code>ImageView</code> and I am using <code>RelativeLayout</code> & the Both <code>ImageView</code> size is Wrap Content But the problem is if I click on <code>ImageView2</code> that time the <code>Imageview2</code> is displayed on the <code>Imageview1</code> and if I click on <code>ImageView1</code> that time the <code>Imageview1</code> is displayed on the <code>Imageview2</code> I am using bring-to-front method but this is not working. Sorry for bad English Communication. Please Help Me.</p>
<p>Thanks in Advance</p>
<p>Following is My Code.</p>
<p>Main.xml:-</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<RelativeLayout android:layout_width="fill_parent" android:id="@+id/mRlayout1"
android:layout_height="fill_parent">
<ImageView android:layout_width="wrap_content"
android:scaleType="matrix" android:layout_height="wrap_content"
android:id="@+id/mImageView1" android:src="@drawable/icon1" />
</RelativeLayout>
<RelativeLayout android:layout_width="fill_parent" android:id="@+id/mRlayout2"
android:layout_height="fill_parent" >
<ImageView android:layout_width="wrap_content"
android:scaleType="matrix" android:layout_height="wrap_content"
android:id="@+id/mImageView2" android:src="@drawable/icon" />
</RelativeLayout>
</RelativeLayout>
</code></pre>
<p>Java File:-</p>
<pre><code>public class BodyTemp extends Activity {
ImageView mImageView1, mImageView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageView1 = (ImageView) findViewById(R.id.mImageView1);
mImageView1.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
mImageView1.bringToFront();
return true;
}
});
mImageView2 = (ImageView) findViewById(R.id.mImageView2);
mImageView2.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
mImageView2.bringToFront();
return true;
}
});
}
}
</code></pre>
| 0 | 1,143 |
voice chat or audio call using socket in java
|
<p><strong>Scenario 1:</strong> Voice Chat between two user/client working well, If and only If, both of them use headphone.</p>
<p><strong>Scenario 2:</strong> If any one of them don't use headphone, then voice chat is working but noise is increased gradually.</p>
<p><strong>How it work</strong></p>
<p>Client 1's microphone sound recorded and send to Client 2. But Client 1's speaker sound also recorded and send to Client 2. So, Client 2 hear his own sound and Client 1's sound repeatedly. And noise is increasing and increasing.</p>
<p><strong>Purpose</strong></p>
<p>I need to stop recording of speakers sound. How can I read/ record only microphone's input sound by filtering speaker's sound? Please help.</p>
<p>Here is my code:</p>
<pre><code>public class Server {
ServerSocket MyService;
Socket clientSocket = null;
InputStream input;
TargetDataLine targetDataLine;
OutputStream out;
AudioFormat audioFormat;
SourceDataLine sourceDataLine;
byte tempBuffer[] = new byte[10000];
static Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
Server() throws LineUnavailableException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.show();
try {
Mixer mixer_ = AudioSystem.getMixer(mixerInfo[0]);
audioFormat = getAudioFormat();
DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
MyService = new ServerSocket(500);
clientSocket = MyService.accept();
captureAudio();
input = new BufferedInputStream(clientSocket.getInputStream());
out = new BufferedOutputStream(clientSocket.getOutputStream());
while (input.read(tempBuffer) != -1) {
sourceDataLine.write(tempBuffer, 0, 10000);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private AudioFormat getAudioFormat() {
float sampleRate = 8000.0F;
int sampleSizeInBits = 8;
int channels = 1;
boolean signed = true;
boolean bigEndian = false;
return new AudioFormat(
sampleRate,
sampleSizeInBits,
channels,
signed,
bigEndian);
}
public static void main(String s[]) throws LineUnavailableException {
Server s2 = new Server();
}
private void captureAudio() {
try {
audioFormat = getAudioFormat();
DataLine.Info dataLineInfo = new DataLine.Info(
TargetDataLine.class, audioFormat);
Mixer mixer = null;
System.out.println("Available mixers:");
for (int cnt = 0; cnt < mixerInfo.length; cnt++) {
mixer = AudioSystem.getMixer(mixerInfo[3]);
if (mixer.isLineSupported(dataLineInfo)) {
System.out.println(mixerInfo[cnt].getName());
targetDataLine = (TargetDataLine) mixer.getLine(dataLineInfo);
}
}
targetDataLine.open(audioFormat);
targetDataLine.start();
Thread captureThread = new CaptureThread();
captureThread.start();
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
}
class CaptureThread extends Thread {
byte tempBuffer[] = new byte[10000];
@Override
public void run() {
try {
while (true) {
int cnt = targetDataLine.read(tempBuffer, 0, tempBuffer.length);
out.write(tempBuffer);
out.flush();
}
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
}
}}
</code></pre>
<p>And </p>
<pre><code>public class Client {
boolean stopCapture = false;
ByteArrayOutputStream byteArrayOutputStream;
AudioFormat audioFormat;
TargetDataLine targetDataLine;
AudioInputStream audioInputStream;
BufferedOutputStream out = null;
BufferedInputStream in = null;
Socket sock = null;
SourceDataLine sourceDataLine;
public static void main(String[] args) {
Client tx = new Client();
tx.captureAudio();
}
private void captureAudio() {
try {
sock = new Socket("192.168.1.3", 500);
out = new BufferedOutputStream(sock.getOutputStream());
in = new BufferedInputStream(sock.getInputStream());
Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
System.out.println("Available mixers:");
for (int cnt = 0; cnt < mixerInfo.length; cnt++) {
System.out.println(mixerInfo[cnt].getName());
}
audioFormat = getAudioFormat();
DataLine.Info dataLineInfo = new DataLine.Info(
TargetDataLine.class, audioFormat);
Mixer mixer = AudioSystem.getMixer(mixerInfo[2]);
targetDataLine = (TargetDataLine) mixer.getLine(dataLineInfo);
targetDataLine.open(audioFormat);
targetDataLine.start();
Thread captureThread = new CaptureThread();
captureThread.start();
DataLine.Info dataLineInfo1 = new DataLine.Info(
SourceDataLine.class, audioFormat);
sourceDataLine = (SourceDataLine) AudioSystem
.getLine(dataLineInfo1);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
Thread playThread = new PlayThread();
playThread.start();
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
}
class CaptureThread extends Thread {
byte tempBuffer[] = new byte[10000];
@Override
public void run() {
byteArrayOutputStream = new ByteArrayOutputStream();
stopCapture = false;
try {
while (!stopCapture) {
int cnt = targetDataLine.read(tempBuffer, 0,
tempBuffer.length);
out.write(tempBuffer);
if (cnt > 0) {
byteArrayOutputStream.write(tempBuffer, 0, cnt);
}
}
byteArrayOutputStream.close();
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
}
}
private AudioFormat getAudioFormat() {
float sampleRate = 8000.0F;
int sampleSizeInBits = 8;
int channels = 1;
boolean signed = true;
boolean bigEndian = false;
return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed,
bigEndian);
}
class PlayThread extends Thread {
byte tempBuffer[] = new byte[10000];
@Override
public void run() {
try {
while (in.read(tempBuffer) != -1) {
sourceDataLine.write(tempBuffer, 0, 10000);
}
sourceDataLine.drain();
sourceDataLine.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>}</p>
| 0 | 2,852 |
How to fix "java.io.NotSerializableException: org.apache.kafka.clients.consumer.ConsumerRecord" in Spark Streaming Kafka Consumer?
|
<ul>
<li>Spark 2.0.0</li>
<li>Apache Kafka 0.10.1.0</li>
<li>scala 2.11.8</li>
</ul>
<hr>
<p>When I use <a href="http://spark.apache.org/docs/latest/streaming-kafka-0-10-integration.html" rel="noreferrer">spark streaming and kafka integration with kafka broker version 0.10.1.0</a> with the following Scala code it fails with the following exception:</p>
<pre><code>16/11/13 12:55:20 ERROR Executor: Exception in task 0.0 in stage 0.0 (TID 0)
java.io.NotSerializableException: org.apache.kafka.clients.consumer.ConsumerRecord
Serialization stack:
- object not serializable (class: org.apache.kafka.clients.consumer.ConsumerRecord, value: ConsumerRecord(topic = local1, partition = 0, offset = 10000, CreateTime = 1479012919187, checksum = 1713832959, serialized key size = -1, serialized value size = 1, key = null, value = a))
- element of array (index: 0)
- array (class [Lorg.apache.kafka.clients.consumer.ConsumerRecord;, size 11)
at org.apache.spark.serializer.SerializationDebugger$.improveException(SerializationDebugger.scala:40)
</code></pre>
<p>Why? How to fix it?</p>
<hr>
<p>Code :</p>
<pre><code>import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.streaming.kafka010._
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark._
import org.apache.commons.codec.StringDecoder
import org.apache.spark.streaming._
object KafkaConsumer_spark_test {
def main(args: Array[String]) {
val conf = new SparkConf().setAppName("KafkaConsumer_spark_test").setMaster("local[4]")
val ssc = new StreamingContext(conf, Seconds(1))
ssc.checkpoint("./checkpoint")
val kafkaParams =Map[String, Object](
"bootstrap.servers" -> "localhost:9092",
"key.deserializer" -> classOf[StringDeserializer],
"value.deserializer" -> classOf[StringDeserializer],
"group.id" -> "example",
"auto.offset.reset" -> "latest",
"enable.auto.commit" -> (false: java.lang.Boolean)
)
val topics = Array("local1")
val stream = KafkaUtils.createDirectStream[String, String](
ssc,
PreferConsistent,
Subscribe[String, String](topics, kafkaParams)
)
stream.map(record => (record.key, record.value))
stream.print()
ssc.start()
ssc.awaitTermination()
}
}
</code></pre>
<hr>
<p>Exception:</p>
<pre><code>16/11/13 12:55:20 ERROR Executor: Exception in task 0.0 in stage 0.0 (TID 0)
java.io.NotSerializableException: org.apache.kafka.clients.consumer.ConsumerRecord
Serialization stack:
- object not serializable (class: org.apache.kafka.clients.consumer.ConsumerRecord, value: ConsumerRecord(topic = local1, partition = 0, offset = 10000, CreateTime = 1479012919187, checksum = 1713832959, serialized key size = -1, serialized value size = 1, key = null, value = a))
- element of array (index: 0)
- array (class [Lorg.apache.kafka.clients.consumer.ConsumerRecord;, size 11)
at org.apache.spark.serializer.SerializationDebugger$.improveException(SerializationDebugger.scala:40)
at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:46)
at org.apache.spark.serializer.JavaSerializerInstance.serialize(JavaSerializer.scala:100)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
16/11/13 12:55:20 ERROR TaskSetManager: Task 0.0 in stage 0.0 (TID 0) had a not serializable result: org.apache.kafka.clients.consumer.ConsumerRecord
Serialization stack:
- object not serializable (class: org.apache.kafka.clients.consumer.ConsumerRecord, value: ConsumerRecord(topic = local1, partition = 0, offset = 10000, CreateTime = 1479012919187, checksum = 1713832959, serialized key size = -1, serialized value size = 1, key = null, value = a))
- element of array (index: 0)
- array (class [Lorg.apache.kafka.clients.consumer.ConsumerRecord;, size 11); not retrying
16/11/13 12:55:20 ERROR JobScheduler: Error running job streaming job 1479012920000 ms.0
org.apache.spark.SparkException: Job aborted due to stage failure: Task 0.0 in stage 0.0 (TID 0) had a not serializable result: org.apache.kafka.clients.consumer.ConsumerRecord
Serialization stack:
- object not serializable (class: org.apache.kafka.clients.consumer.ConsumerRecord, value: ConsumerRecord(topic = local1, partition = 0, offset = 10000, CreateTime = 1479012919187, checksum = 1713832959, serialized key size = -1, serialized value size = 1, key = null, value = a))
- element of array (index: 0)
- array (class [Lorg.apache.kafka.clients.consumer.ConsumerRecord;, size 11)
at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1450)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1438)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1437)
at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1437)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:811)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:811)
at scala.Option.foreach(Option.scala:257)
at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:811)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1659)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1618)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1607)
at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:632)
at org.apache.spark.SparkContext.runJob(SparkContext.scala:1871)
at org.apache.spark.SparkContext.runJob(SparkContext.scala:1884)
at org.apache.spark.streaming.kafka010.KafkaRDD.take(KafkaRDD.scala:122)
at org.apache.spark.streaming.kafka010.KafkaRDD.take(KafkaRDD.scala:50)
at org.apache.spark.streaming.dstream.DStream$$anonfun$print$2$$anonfun$foreachFunc$3$1.apply(DStream.scala:734)
at org.apache.spark.streaming.dstream.DStream$$anonfun$print$2$$anonfun$foreachFunc$3$1.apply(DStream.scala:733)
at org.apache.spark.streaming.dstream.ForEachDStream$$anonfun$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(ForEachDStream.scala:51)
at org.apache.spark.streaming.dstream.ForEachDStream$$anonfun$1$$anonfun$apply$mcV$sp$1.apply(ForEachDStream.scala:51)
at org.apache.spark.streaming.dstream.ForEachDStream$$anonfun$1$$anonfun$apply$mcV$sp$1.apply(ForEachDStream.scala:51)
at org.apache.spark.streaming.dstream.DStream.createRDDWithLocalProperties(DStream.scala:415)
at org.apache.spark.streaming.dstream.ForEachDStream$$anonfun$1.apply$mcV$sp(ForEachDStream.scala:50)
at org.apache.spark.streaming.dstream.ForEachDStream$$anonfun$1.apply(ForEachDStream.scala:50)
at org.apache.spark.streaming.dstream.ForEachDStream$$anonfun$1.apply(ForEachDStream.scala:50)
at scala.util.Try$.apply(Try.scala:192)
at org.apache.spark.streaming.scheduler.Job.run(Job.scala:39)
at org.apache.spark.streaming.scheduler.JobScheduler$JobHandler$$anonfun$run$1.apply$mcV$sp(JobScheduler.scala:245)
at org.apache.spark.streaming.scheduler.JobScheduler$JobHandler$$anonfun$run$1.apply(JobScheduler.scala:245)
at org.apache.spark.streaming.scheduler.JobScheduler$JobHandler$$anonfun$run$1.apply(JobScheduler.scala:245)
at scala.util.DynamicVariable.withValue(DynamicVariable.scala:58)
at org.apache.spark.streaming.scheduler.JobScheduler$JobHandler.run(JobScheduler.scala:244)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Exception in thread "main" org.apache.spark.SparkException: Job aborted due to stage failure: Task 0.0 in stage 0.0 (TID 0) had a not serializable result: org.apache.kafka.clients.consumer.ConsumerRecord
Serialization stack:
- object not serializable (class: org.apache.kafka.clients.consumer.ConsumerRecord, value: ConsumerRecord(topic = local1, partition = 0, offset = 10000, CreateTime = 1479012919187, checksum = 1713832959, serialized key size = -1, serialized value size = 1, key = null, value = a))
- element of array (index: 0)
- array (class [Lorg.apache.kafka.clients.consumer.ConsumerRecord;, size 11)
at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1450)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1438)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1437)
at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1437)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:811)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:811)
at scala.Option.foreach(Option.scala:257)
at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:811)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1659)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1618)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1607)
at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:632)
at org.apache.spark.SparkContext.runJob(SparkContext.scala:1871)
at org.apache.spark.SparkContext.runJob(SparkContext.scala:1884)
at org.apache.spark.streaming.kafka010.KafkaRDD.take(KafkaRDD.scala:122)
at org.apache.spark.streaming.kafka010.KafkaRDD.take(KafkaRDD.scala:50)
at org.apache.spark.streaming.dstream.DStream$$anonfun$print$2$$anonfun$foreachFunc$3$1.apply(DStream.scala:734)
at org.apache.spark.streaming.dstream.DStream$$anonfun$print$2$$anonfun$foreachFunc$3$1.apply(DStream.scala:733)
at org.apache.spark.streaming.dstream.ForEachDStream$$anonfun$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(ForEachDStream.scala:51)
at org.apache.spark.streaming.dstream.ForEachDStream$$anonfun$1$$anonfun$apply$mcV$sp$1.apply(ForEachDStream.scala:51)
at org.apache.spark.streaming.dstream.ForEachDStream$$anonfun$1$$anonfun$apply$mcV$sp$1.apply(ForEachDStream.scala:51)
at org.apache.spark.streaming.dstream.DStream.createRDDWithLocalProperties(DStream.scala:415)
at org.apache.spark.streaming.dstream.ForEachDStream$$anonfun$1.apply$mcV$sp(ForEachDStream.scala:50)
at org.apache.spark.streaming.dstream.ForEachDStream$$anonfun$1.apply(ForEachDStream.scala:50)
at org.apache.spark.streaming.dstream.ForEachDStream$$anonfun$1.apply(ForEachDStream.scala:50)
at scala.util.Try$.apply(Try.scala:192)
at org.apache.spark.streaming.scheduler.Job.run(Job.scala:39)
at org.apache.spark.streaming.scheduler.JobScheduler$JobHandler$$anonfun$run$1.apply$mcV$sp(JobScheduler.scala:245)
at org.apache.spark.streaming.scheduler.JobScheduler$JobHandler$$anonfun$run$1.apply(JobScheduler.scala:245)
at org.apache.spark.streaming.scheduler.JobScheduler$JobHandler$$anonfun$run$1.apply(JobScheduler.scala:245)
at scala.util.DynamicVariable.withValue(DynamicVariable.scala:58)
at org.apache.spark.streaming.scheduler.JobScheduler$JobHandler.run(JobScheduler.scala:244)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
| 0 | 4,992 |
Calling a function without clicking anything
|
<p>I'm new in programming and I'm trying to call a function without any button or click event. I'm doing a table within a table using javascript function. Here's my code so far: <br><br></p>
<pre><code><html>
<head> <title> Hello </title> </head>
<body>
<table border=1>
<tr>
<td> Hello! <input type='hidden' value='0' id='theValue' /> <script> add(); </script> <div id='myDiv'> </div> </td>
</tr>
<script>
$ctra = 1;
$ctr1a = 1;
function add() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = "<table border=1>"+
"<tr>"+
"<td> Hello! <input type='hidden' value='0' id='theValue' /> <script> add(); </script> <div id=('" + divIdName + "')> </div> </td>"+
"</tr>"+
"</table>";
if($ctra<100){
ni.appendChild(newdiv);
$ctra++;
}
}
</script>
</table>
</body>
</html>
</code></pre>
<p><br>
When I run it, it displays<br></p>
<pre><code>"+ ""+ "
Hello!
"; if($ctra<100){ ni.appendChild(newdiv); $ctra++; } }
</code></pre>
<p><br>
in the browser. What could the problem be? Thank you in advance!<br><br>
<strong>EDIT</strong><br></p>
<pre><code>function add() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = "<table border=1><tr><td> Hello! <input type='hidden' value=0 id='theValue' /><div id='" + divIdName + "'></td></tr></table>";
ni.appendChild(newdiv);
for(var i=1;i<100;i++) {
var ni = document.getElementById(divIdName);
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = "<table border=1><tr><td> Hello! <input type='hidden' value='" + i + "' id='theValue' /><div id='" + divIdName + "'></td></tr></table>";
ni.appendChild(newdiv);
}
}
</code></pre>
| 0 | 1,338 |
C++: get Boost working; questions on include path and linking library
|
<p>I was trying to use Boost.Tokenizer library. In my <code>PROG.cpp</code>, I have the following:</p>
<pre><code>#include <boost/tokenizer.hpp>
</code></pre>
<p>And my <code>Makefile</code> was initially something like</p>
<pre><code>CXX = g++-4.8
CXXFLAGS = ## some irrelevant flags
LDFLAGS = ## some irrelevant flags
SOURCES = PROG.cpp
OBJECTS = $(SOURCES:.cpp=.o)
TARGETS = PROG
$(TARGETS) : $(OBJECTS)
$(CXX) $(CXXFLAGS) -o $@ $^ $(LDFLAGS)
## other targets
</code></pre>
<p>It won't compile, since <code>boost/tokenizer.hpp</code> cannot be found:</p>
<pre><code>fatal error: boost/tokenizer.hpp: No such file or directory
</code></pre>
<p>Then I manually added the boost include path to <code>CXXFLAGS</code>:</p>
<pre><code>-I/opt/local/include/
</code></pre>
<p>(which is the path from MacPorts.)</p>
<p>Then I tried to include the Tokenizer library, but in <code>/opt/local/lib/</code> I have <code>libboost_atomic-mt.dylib</code>, <code>libboost_chrono-mt.dylib</code>, etc., but nothing like <code>tokenizer</code>. I was rather confused at the time. I supposed that still wouldn't work since the library was not linked against. Surprisingly, the program built, linked, and ran perfectly.</p>
<p>So I'm really confused now. Here are some questions:</p>
<p>(1) I did not link against boost explicitly, so boost is treated like standard library by the linker?</p>
<p>(2) If boost is treated like standard, why the headers are not standard?</p>
<p>(3) Why there are <code>libboost_atomic-mt.dylib</code>, <code>libboost_chrono-mt.dylib</code>, etc. but not <code>tokenizer</code>? Which dynamic library does <code>tokenizer</code> belong to?</p>
<p>I'm not very familiar with <code>g++</code> linking mechanism; speaking of boost, this is my very first program with boost. <strong>So I'd really appreciate detailed explanation.</strong> Thanks in advance!</p>
<p>For reference, this is what I extracted by <code>gcc -print-search-dirs</code>:</p>
<pre><code>install: /usr/gcc-4.8.0/lib/gcc/x86_64-apple-darwin12.3.0/4.8.0/
programs: =/usr/gcc-4.8.0/libexec/gcc/x86_64-apple-darwin12.3.0/4.8.0/:/usr/gcc-4.8.0/libexec/gcc/x86_64-apple-darwin12.3.0/4.8.0/:/usr/gcc-4.8.0/libexec/gcc/x86_64-apple-darwin12.3.0/:/usr/gcc-4.8.0/lib/gcc/x86_64-apple-darwin12.3.0/4.8.0/:/usr/gcc-4.8.0/lib/gcc/x86_64-apple-darwin12.3.0/:/usr/gcc-4.8.0/lib/gcc/x86_64-apple-darwin12.3.0/4.8.0/../../../../x86_64-apple-darwin12.3.0/bin/x86_64-apple-darwin12.3.0/4.8.0/:/usr/gcc-4.8.0/lib/gcc/x86_64-apple-darwin12.3.0/4.8.0/../../../../x86_64-apple-darwin12.3.0/bin/
libraries: =/usr/gcc-4.8.0/lib/gcc/x86_64-apple-darwin12.3.0/4.8.0/:/usr/gcc-4.8.0/lib/gcc/x86_64-apple-darwin12.3.0/4.8.0/../../../../x86_64-apple-darwin12.3.0/lib/x86_64-apple-darwin12.3.0/4.8.0/:/usr/gcc-4.8.0/lib/gcc/x86_64-apple-darwin12.3.0/4.8.0/../../../../x86_64-apple-darwin12.3.0/lib/:/usr/gcc-4.8.0/lib/gcc/x86_64-apple-darwin12.3.0/4.8.0/../../../x86_64-apple-darwin12.3.0/4.8.0/:/usr/gcc-4.8.0/lib/gcc/x86_64-apple-darwin12.3.0/4.8.0/../../../:/lib/x86_64-apple-darwin12.3.0/4.8.0/:/lib/:/usr/lib/x86_64-apple-darwin12.3.0/4.8.0/:/usr/lib/
</code></pre>
| 0 | 1,411 |
How to clear v-model used with a select when options change
|
<p>I have a cascading select (two part select) where the options in the second dropdown are determined by the value of the first dropdown. I do this by having a computed property which is based off of the first select. This then feeds the options into the second select. This mostly works fine.</p>
<p>The problem I'm having is if I have selected an option in the second select (which through v-model sets the value of the bound variable in Vue), and then I change the value of the first select. The options for the second select then update, and in that second select I appear to be selected to the empty option. However, the bound variable still has the previously selected value. I'm assuming this is because updating the option values for the second select doesn't actually trigger an input or change event so v-model doesn't respond to anything. I suppose I could fix this with a watcher, but I was hoping for a more elegant solution.</p>
<p>Coded example is here: <a href="https://codepen.io/Slotheroo/pen/ajwNKO/" rel="noreferrer">https://codepen.io/Slotheroo/pen/ajwNKO/</a></p>
<p><strong>JS/Vue:</strong></p>
<pre><code>new Vue({
el: '#app',
data: {
selectedFruit: null,
selectedVariety: null,
fruits: {
"apples": [
{
name: "honeycrisp",
madeBy: "applebees",
},
{
name: "macintosh",
madeBy: "the steves",
},
{
name: "gala",
madeBy: "ac/dc",
},
{
name: "pink lady",
madeBy: "Alecia Beth Moore",
},
],
"pears": [
{
name: "d'anjou",
madeBy: "Maya D'Anjoulou",
},
{
name: "bartlett",
madeBy: "Anton Yelchin",
}
],
},
},
computed: {
fruitVarieties: function() {
return this.fruits[this.selectedFruit]
}
},
});
</code></pre>
<p><strong>HTML:</strong></p>
<pre><code><div id="app">
<div>
<select v-model="selectedFruit">
<option value=""></option>
<option v-for="fruitName in Object.keys(fruits)" :value ="fruitName">{{fruitName}}</option>
</select>
</div>
<select v-model="selectedVariety">
<option value=""></option>
<option v-for="fruitVariety in fruitVarieties" :value="fruitVariety">{{ fruitVariety.name }}</option>
</select>
<div>
</div>
<p>Selected variety: {{ selectedVariety }}</p>
</div>
</code></pre>
<p><strong>Steps to reproduce:</strong></p>
<ol>
<li>Select 'apples' in the first select</li>
<li>Select 'honeycrisp' in the second select</li>
<li>Select 'pears' or 'blank' in the first select</li>
</ol>
<p><strong>Hoped for result</strong></p>
<p>selectedVariety returns to null</p>
<p><strong>Actual result</strong></p>
<p>selectedVariety still equals honeycrisp</p>
| 0 | 1,226 |
spring Kafka integration testing with embedded Kafka
|
<p>I have spring boot application that had a consumer consumes from topic in one cluster and produces to another topic in different cluster.</p>
<p>Now I'm trying to write integration test case using spring embedded Kafka but having an issue <code>KafkaTemplate could not be registered. A bean with that name has already been defined in class path resource</code></p>
<p><strong>Consumer Class</strong></p>
<pre><code>@Service
public class KafkaConsumerService {
@Autowired
private KafkaProducerService kafkaProducerService;
@KafkaListener(topics = "${kafka.producer.topic}")
public void professor(List<Professor> pro) {
pro.forEach(kafkaProducerService::produce);
}
}
</code></pre>
<p><strong>Producer Class</strong></p>
<pre><code>@Service
public class KafkaProducerService {
@Value("${kafka.producer.topic}")
private String topic;
@Autowired
private KafkaTemplate<String, Object> kafkaTemplate;
public void produce(Professor pro) {
kafkaTemplate.send(topic,"professor",pro);
}
}
</code></pre>
<p>In my Test cases I want to override <code>KafkaTemplate</code> so that when i call <code>kafkaConsumerService.professor</code> method in <code>Test</code> it should produce the data into embedded Kafka and i should validate it.</p>
<p><strong>Test config</strong></p>
<pre><code>@TestConfiguration
@EmbeddedKafka(partitions = 1, controlledShutdown = false,
brokerProperties = {"listeners=PLAINTEXT://localhost:3333", "port=3333"})
public class KafkaProducerConfigTest {
@Autowired
KafkaEmbedded kafkaEmbeded;
@Autowired
KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;
@Before
public void setUp() throws Exception {
for (MessageListenerContainer messageListenerContainer : kafkaListenerEndpointRegistry.getListenerContainers()) {
ContainerTestUtils.waitForAssignment(messageListenerContainer,
kafkaEmbeded.getPartitionsPerTopic());
}
}
@Bean
public ProducerFactory<String, Object> producerFactory() {
return new DefaultKafkaProducerFactory<>(KafkaTestUtils.producerProps(kafkaEmbeded));
}
@Bean
public KafkaTemplate<String, Object> kafkaTemplate() {
KafkaTemplate<String, Object> kafkaTemplate = new KafkaTemplate<>(producerFactory());
return kafkaTemplate;
}
}
</code></pre>
<p><strong>Test class</strong></p>
<pre><code>@EnableKafka
@SpringBootTest(classes = {KafkaProducerConfigTest.class})
@RunWith(SpringRunner.class)
public class KafkaProducerServiceTest {
@Autowired
private KafkaConsumerService kafkaConsumerService;
@Test
public void testReceive() throws Exception {
kafkaConsumerService.professor(Arrays.asList(new Professor()));
//How to check messages is sent to kafka?
}
}
</code></pre>
<p><strong>Error</strong></p>
<pre><code> The bean 'kafkaTemplate', defined in com.kafka.configuration.KafkaProducerConfigTest, could not be registered.
A bean with that name has already been defined in class path resource [com/kafka/configuration/KafkaProducerConfig.class] and overriding is disabled.
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
</code></pre>
<hr />
<p>And also can some one help me how to validate messages sent into embedded Kafka server?</p>
<p><strong>Note</strong> I'm having some deprecated warnings</p>
<blockquote>
<p>The type KafkaEmbedded is deprecated</p>
<p>The method getPartitionsPerTopic() from the type KafkaEmbedded is deprecated</p>
<p>The method producerProps(KafkaEmbedded) from the type KafkaTestUtils is deprecated</p>
</blockquote>
| 0 | 1,156 |
WPF ToggleButton IsChecked Trigger
|
<p>This is driving me batty. I have a simple WPF toggle button, with two triggers for IsChecked. One for the value being true, and the other for the value being false. It works fine when the button is not checked, my style for false is applied; however, the system never applies the style for when IsChecked is true. It always just uses the default blue chrome windows style. Any ideas?</p>
<pre><code><ToggleButton Content="Control 1" Width="200" Margin="0,0,0,10" Focusable="False">
<ToggleButton.Resources>
<Style TargetType="{x:Type ToggleButton}">
<Style.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#FFF3F3F3" Offset="1"/>
<GradientStop Color="LawnGreen" Offset="0.307"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsChecked" Value="False">
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#FFF3F3F3" Offset="1"/>
<GradientStop Color="Red" Offset="0.307"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</ToggleButton.Resources>
</ToggleButton>
</code></pre>
<p>Any help would be greatly appreciated. I'm sure it's something obvious that I'm just overlooking.</p>
| 0 | 1,097 |
closing all windows in python tkinter
|
<p>I am working with tkinter library in python. I have a main window which has several buttons and when clicked those buttons a new window will popup which also has a button called cancel. I want to make that cancel button to all the windows.</p>
<p>I tried the following solution, which only closes the current window.</p>
<pre><code>from tkinter import *
from tkinter import ttk
import tkinter.messagebox
import datetime
import tkinter as tk
class AlertDialog:
def __init__(self):
self.invalidDiag = tk.Toplevel()
invalidInput = tk.Label(master=self.invalidDiag,
text='Error: Invalid Input').grid(row=1, column=1)
closeButton = tk.Button(master=self.invalidDiag,
text='Close',
command=self.invalidDiag.destroy).grid(row=2, column=1)
def start(self):
# self.invalidDiag.grab_set() #takes control over the dialog (makes it active)
self.invalidDiag.wait_window()
class QuitDialog():
def __init__(self, ):
self.quitDialog = tk.Toplevel()
warnMessage = tk.Label(master=self.quitDialog,
text='Are you sure that you want to quit? ').grid(row=1, column=1)
cancelButton = tk.Button(master= self.quitDialog ,
text='Cancel',
command = self.quitALL).grid(row=2, column=1)
def start(self):
# self.invalidDiag.grab_set() #takes control over the dialog (makes it active)
self.quitDialog.wait_window()
def quitALL(self):
self.quitDialog.destroy()
tc =TimeConverter()
tc.destroyit()
class TimeConverter:
def __init__(self):
self.mainWindow = tk.Tk()
self.mainWindow.title("Seconds Converter")
self.results = tk.StringVar()
self.inputSecs = tk.StringVar()
secLabel = tk.Label(master=self.mainWindow,
text="Seconds:").grid(row=0, sticky="W")
resultLabel = tk.Label(master=self.mainWindow,
text="Converted Time:\n(H:M:S)").grid(row=1, sticky="W")
calcResults = tk.Label(master=self.mainWindow,
background='light gray', width=20,
textvariable=self.results,
anchor="w").grid(row=1, column=1)
secEntry = tk.Entry(master=self.mainWindow,
width=24,
textvariable=self.inputSecs).grid(row=0, column=1)
calcButton = tk.Button(master=self.mainWindow,
text='Calculate',
command=self.SecondsToHours).grid(row=2,
column=0, sticky="w")
# quitButton = tk.Button(master=self.mainWindow,
# text='Quit',
# command=self.mainWindow.destroy).grid(row=2, column=1, sticky="E")
quitButton = tk.Button(master=self.mainWindow,
text='Quit',
command=self.showQuitDialog).grid(row=3, column=1, sticky="E")
def invalidInputEntered(self):
errorDiag = AlertDialog()
errorDiag.start()
def showQuitDialog(self):
quitdialog = QuitDialog()
quitdialog.start()
def startDisplay(self) -> None:
self.mainWindow.mainloop()
def destroyit(self):
self.mainWindow.destroy()
def SecondsToHours(self):
try:
inputseconds = int(self.inputSecs.get())
seconds = int(inputseconds % 60)
minutes = int(((inputseconds - seconds) / 60) % 60)
hours = int((((inputseconds - seconds) / 60) - minutes) / 60)
tempResults = str(hours) + ':' + str(minutes) + ':' + str(seconds)
self.results.set(tempResults)
return
except ValueError:
self.invalidInputEntered()
#self.showQuitDialog()
if __name__ == '__main__':
TimeConverter().startDisplay()
</code></pre>
| 0 | 2,070 |
Install OpenGL ES and compile code for android
|
<p>I've just started learning OpenGL ES on android (using <a href="https://rads.stackoverflow.com/amzn/click/com/1430226471" rel="noreferrer" rel="nofollow noreferrer">this book</a>) and came across an issue of adopting <a href="http://apress.com/book/view/9781430226475" rel="noreferrer">source</a> code from chapter 5 to existing methods of using jni in android (actually, it also concerns simply running a native GL app). I'm trying to compile the native code to get the .so lib and use it further in .apk archive. But compilation is not possible if certain libs are not present (which are GLES/gl.h, EGL/egl.h, GLES/gl.h, GLES/glext.h). </p>
<p>So the question is how do I install those libs (AFAIU, OpenGL ES and EGL installation) and compile the most trivial native code? (tutorials are highly admired).</p>
<p>Thanks in advance.</p>
<p>EDIT: I've tried the <a href="https://github.com/richq/glbuffer" rel="noreferrer">glbuffer</a> example as was suggested (slightly changed .mk file), but still no success. Compiler gives me the same result as before: </p>
<blockquote>
<p>ndk-build</p>
<p>Compile thumb: egl <= cube.c</p>
<p>/path/jni/cube.c:5:21: error: GLES/gl.h: No such file or directory // same message for glbuffer when gl.h is being included</p>
</blockquote>
<p>Here is the cube.c code:</p>
<pre><code>#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <GLES/gl.h>
#define FIXED_ONE 0x10000
#define one 1.0f
typedef unsigned char byte;
extern void jni_printf(char *format, ...);
// Cube static
GLfloat vertices[24] = { -one, -one, -one, one, -one,
-one, one, one, -one, -one, one, -one, -one, -one, one, one, -one, one, one, one, one, -one, one, one, };
static GLfloat colors[] = { 0, 0, 0, one, one, 0, 0, one, one, one, 0, one, 0, one, 0> , one, 0, 0, one, one, one, 0, one, one, one, one, one, one, 0, one, one, one, };
static byte indices[] = { 0, 4, 5, 0, 5, 1, 1, 5, 6, 1, 6, 2, 2, 6, 7, 2, 7, 3, 3, 7, 4, 3, 4, 0, 4, 7, 6, 4, 6, 5, 3, 0, 1, 3, 1, 2 };
void Cube_draw() {
glFrontFace(GL_CW);
glVertexPointer(3, GL_FLOAT, 0, vertices);
glColorPointer(4, GL_FLOAT, 0 , colors);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_BYTE, indices); }
</code></pre>
<p>It's awfully trivial and not working, yet.</p>
<p>Android.mk:</p>
<pre><code>LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_LDLIBS := -lGLESv1_CM.so
LOCAL_MODULE := egl
LOCAL_SRC_FILES := cube.c cuberenderer.c
include $(BUILD_SHARED_LIBRARY)
</code></pre>
| 0 | 1,211 |
com.google.android.gms.common.api.ApiException: 12500
|
<p>This is my first attempt.... trying to find the issue for last 2 days.
I am trying to integrate google sign in to android app, however getting below:
com.google.android.gms.common.api.ApiException: 12500</p>
<p>Followed the code from:
<a href="https://firebase.google.com/docs/auth/android/google-signin" rel="nofollow noreferrer">https://firebase.google.com/docs/auth/android/google-signin</a></p>
<ul>
<li><p>Made sure oauth client id is present in dev console with correct SHA-1 fingerprint from ~/.android/debug.keystore as suggested in other posts.</p></li>
<li><p>Using latest play services 49 and in build.gradle at app level: implementation 'com.google.android.gms:play-services-auth:16.0.1'</p></li>
<li><p>Using below in project level build.gradle:</p></li>
</ul>
<h2>buildscript { // ... dependencies { // ... classpath 'com.google.gms:google-services:4.1.0' // google-services plugin } }</h2>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>public class SignUpActivity extends AppCompatActivity {
private GoogleSignInClient gsc;
private FirebaseAuth firebaseAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
GoogleSignInOptions gso = new GoogleSignInOptions
.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(String.valueOf(R.string.gplus_api_client_id))
.requestEmail()
.build();
gsc = GoogleSignIn.getClient(this, gso);
//Initialize firebase authentication
firebaseAuth = FirebaseAuth.getInstance();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task < GoogleSignInAccount > task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task < GoogleSignInAccount > completedTask) {
try {
//Sign in Successful
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
Log.w("SignUpActivity/handleSignInResult", "Trying signing in with Google... " + account);
firebaseAuthWithGoogle(account);
// Signed in successfully, show authenticated UI.
// Log.w("SignUpActivity/handleSignInResult", "Google sign in successful for account " + account);
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w("SignUpActivity/handleSignInResult", "Google sign in failed with exception: " + e);
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
Log.i("SignUpActivity/firebaseAuthWithGoogle", "Signed in as : " + account.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener < AuthResult > () {
@Override
public void onComplete(@NonNull Task < AuthResult > task) {
if (task.isSuccessful()) {
FirebaseUser user = firebaseAuth.getCurrentUser();
Log.i("SignUpActivity/firebaseAuthWithGoogle", "Sign in successful for user : " + user);
} else {
Log.e("SignUpActivity/firebaseAuthWithGoogle", "User Authentication failed.");
Snackbar.make(findViewById(R.id.view_signup), "Authentication failed.", Snackbar.LENGTH_SHORT);
}
}
});
}
}</code></pre>
</div>
</div>
</p>
| 0 | 1,401 |
Updating ModelState with model object
|
<p>The problem: How to update ModelState in posting+validation scenario.</p>
<p>I've got a simple form:</p>
<pre><code><%= Html.ValidationSummary() %>
<% using(Html.BeginForm())%>
<%{ %>
<%=Html.TextBox("m.Value") %>
<input type="submit" />
<%} %>
</code></pre>
<p>When user submits I want to validate input and in some circumstances I want to fix the error for user, letting him know that he made an error that is already fixed:</p>
<pre><code>[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(M m)
{
if (m.Value != "a")
{
ModelState.AddModelError("m.Value", "should be \"a\"");
m.Value = "a";
return View(m);
}
return View("About");
}
</code></pre>
<p>Well the problem is, MVC will simply ignore the model passed to the view and will re-render whatever the user typed -- and not my value ("a").
This happens, because the TextBox renderer checkes if there is a ModelState and if it's not null - ModelState's value is used. That value is of course the one user typed before posting.</p>
<p>Since I can't change the behaviour of TextBox renderer the only solution I found would be to update the ModelState by myself. The quick'n'dirty way is to (ab)use the DefaultModelBinder and override the method that assigns the values from forms to model by simply changing the assignment direction ;). Using DefaultModelBinder I don't have to parse the ids.
The following code (based on original implementation of DefaultModelBinder) is my solution to this:</p>
<pre><code>/// <summary>
/// Updates ModelState using values from <paramref name="order"/>
/// </summary>
/// <param name="order">Source</param>
/// <param name="prefix">Prefix used by Binder. Argument name in Action (if not explicitly specified).</param>
protected void UpdateModelState(object model, string prefix)
{
new ReversedBinder().BindModel(this.ControllerContext,
new ModelBindingContext()
{
Model = model,
ModelName = prefix,
ModelState = ModelState,
ModelType = model.GetType(),
ValueProvider = ValueProvider
});
}
private class ReversedBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
string prefix = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name);
object val = typeof(Controller)
.Assembly.GetType("System.Web.Mvc.DictionaryHelpers")
.GetMethod("DoesAnyKeyHavePrefix")
.MakeGenericMethod(typeof(ValueProviderResult))
.Invoke(null, new object[] { bindingContext.ValueProvider, prefix });
bool res = (bool)val;
if (res)
{
IModelBinder binder = new ReversedBinder();//this.Binders.GetBinder(propertyDescriptor.PropertyType);
object obj2 = propertyDescriptor.GetValue(bindingContext.Model);
ModelBindingContext context2 = new ModelBindingContext();
context2.Model = obj2;
context2.ModelName = prefix;
context2.ModelState = bindingContext.ModelState;
context2.ModelType = propertyDescriptor.PropertyType;
context2.ValueProvider = bindingContext.ValueProvider;
ModelBindingContext context = context2;
object obj3 = binder.BindModel(controllerContext, context);
if (bindingContext.ModelState.Keys.Contains<string>(prefix))
{
var prefixKey = bindingContext.ModelState.Keys.First<string>(x => x == prefix);
bindingContext.ModelState[prefixKey].Value
= new ValueProviderResult(obj2, obj2.ToString(),
bindingContext.ModelState[prefixKey].Value.Culture);
}
}
}
}
</code></pre>
<p>So the question remains: am I doing something extremely uncommon or am I missing something? If the former, then how could I implement such functionality in a better way (using existing MVC infrastructure)?</p>
| 0 | 1,792 |
How to subtract one dataframe from another?
|
<p>First, let me set the stage.</p>
<p>I start with a <code>pandas</code> dataframe <code>klmn</code>, that looks like this:</p>
<pre><code>In [15]: klmn
Out[15]:
K L M N
0 0 a -1.374201 35
1 0 b 1.415697 29
2 0 a 0.233841 18
3 0 b 1.550599 30
4 0 a -0.178370 63
5 0 b -1.235956 42
6 0 a 0.088046 2
7 0 b 0.074238 84
8 1 a 0.469924 44
9 1 b 1.231064 68
10 2 a -0.979462 73
11 2 b 0.322454 97
</code></pre>
<p>Next I split <code>klmn</code> into two dataframes, <code>klmn0</code> and <code>klmn1</code>, according to the value in the 'K' column:</p>
<pre><code>In [16]: k0 = klmn.groupby(klmn['K'] == 0)
In [17]: klmn0, klmn1 = [klmn.ix[k0.indices[tf]] for tf in (True, False)]
In [18]: klmn0, klmn1
Out[18]:
( K L M N
0 0 a -1.374201 35
1 0 b 1.415697 29
2 0 a 0.233841 18
3 0 b 1.550599 30
4 0 a -0.178370 63
5 0 b -1.235956 42
6 0 a 0.088046 2
7 0 b 0.074238 84,
K L M N
8 1 a 0.469924 44
9 1 b 1.231064 68
10 2 a -0.979462 73
11 2 b 0.322454 97)
</code></pre>
<p>Finally, I compute the mean of the <code>M</code> column in <code>klmn0</code>, grouped by the value in the <code>L</code> column:</p>
<pre><code>In [19]: m0 = klmn0.groupby('L')['M'].mean(); m0
Out[19]:
L
a -0.307671
b 0.451144
Name: M
</code></pre>
<p>Now, my question is, <strong><em>how can I subtract <code>m0</code> from the <code>M</code> column of the <code>klmn1</code> sub-dataframe, respecting the value in the <code>L</code> column?</em></strong> (By this I mean that <code>m0['a']</code> gets subtracted from the <code>M</code> column of each row in <code>klmn1</code> that has <code>'a'</code> in the <code>L</code> column, and likewise for <code>m0['b']</code>.)</p>
<p>One could imagine doing this in a way that replaces the the values in the <code>M</code> column of <code>klmn1</code> with the new values (after subtracting the value from <code>m0</code>). Alternatively, one could imagine doing this in a way that leaves <code>klmn1</code> unchanged, and instead produces a new dataframe <code>klmn11</code> with an updated <code>M</code> column. <em>I'm interested in both approaches.</em></p>
| 0 | 1,034 |
Storing Data from WinCC Flex to Excel file using VBScript
|
<p>Am trying to log data of some tags of WinCC Flex into Excel file using VB Script.
I've searched on Siemens forums and have got an script according to my needs.
But there is an error while executing the script in WinCC Flex.</p>
<p>The script is as:</p>
<pre><code>Dim wsh, XLSrunning, TargetBookrunning, objExcelApp, objWorkbook, TheTargetBook, TheTargetBookName
Dim TheCount
Dim objFSO
Const OverwriteExisting = 1
Set wsh = CreateObject("WScript.Shell")
TheTargetBookName = "report.xls"
TheTargetBook = "D:\Out\" & TheTargetBookName
'---------------[Modification#1_Begin]-------------------------------------------
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(TheTargetBook) Then
objFSO.CopyFile "D:\Out\Template.xls", TheTargetBook, OverwriteExisting
'HMIRuntime.Trace "The file," & TheTargetBook & ", does not exist." & vbCrLf & "I've just created one for you!"
End If
Set objFSO = Nothing
'---------------[Modification#1_End]--------------------------------------------
TheCount = GetObject("winmgmts:root\CIMV2").ExecQuery("SELECT * FROM Win32_Process WHERE Name='EXCEL.EXE'").Count
'While TheCount is bigger than 0, it means the Excel Application is running..., but doesn't mean the workbook is open for sure!
If TheCount > 0 Then
Set objExcelApp = GetObject(,"Excel.Application")
' Using GetObject(,"Excel.Application") to point to the running Excel Application.
TargetBookrunning = 0
For Each XLSrunning In objExcelApp.Workbooks
If XLSrunning.name = TheTargetBookName Then
TargetBookrunning = 1
End If
Next
If TargetBookrunning = 1 Then
Set objWorkbook = GetObject(TheTargetBook)
Else
Set objWorkbook = objExcelApp.Workbooks.Open(TheTargetBook)
End If
Else
Set objExcelApp = CreateObject("Excel.Application")
Set objWorkbook = objExcelApp.Workbooks.Open(TheTargetBook)
End If
objExcelApp.Visible = True
objExcelApp.ScreenUpdating = True
objExcelApp.DisplayAlerts = True
Dim TheTargetRow ' <------[Modification#2]-------
With objWorkbook.ActiveSheet
TheTargetRow = .Cells(65535, 2).End(-4162).Row
.cells(TheTargetRow + 1, 2) = SmartTags("Tag_1")
.cells(TheTargetRow + 1, 3) = SmartTags("Tag_2")
.cells(TheTargetRow + 1, 4) = SmartTags("Tag_3")
End With
objWorkbook.Save
'objWorkbook.Close
Set objWorkbook = Nothing
'objExcelApp.Quit
Set objExcelApp = Nothing
'MsgBox "Done"
Set wsh = Nothing
</code></pre>
<p>When, I try to execute this script, the compiler shows the error in following line:</p>
<pre><code> TheTargetRow = .Cells(65535, 2).End(-4162).Row
</code></pre>
<p>Am unable to determine the error. Please do the needful.</p>
| 0 | 1,103 |
How to download a video while playing it, using ExoPlayer?
|
<h2>Background</h2>
<p>I'm working on an app that can play some short videos.</p>
<p>I want to avoid accessing the Internet every time the user plays them, to make it faster and to lower the data usage.</p>
<h2>The problem</h2>
<p>Currently I've only found how to either play or download (it's just a file so I could download it like any other file). </p>
<p>Here's the code of playing a video file from URL (sample available <strong>here</strong>):</p>
<p><strong>gradle</strong></p>
<pre><code>...
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.exoplayer:exoplayer-core:2.8.4'
implementation 'com.google.android.exoplayer:exoplayer-ui:2.8.4'
...
</code></pre>
<p><strong>manifest</strong></p>
<pre><code><manifest package="com.example.user.myapplication" xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"
tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<activity
android:name=".MainActivity" android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
</code></pre>
<p><strong>activity_main.xml</strong></p>
<pre><code><FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">
<com.google.android.exoplayer2.ui.PlayerView
android:id="@+id/playerView" android:layout_width="match_parent" android:layout_height="match_parent"
app:resize_mode="zoom"/>
</FrameLayout>
</code></pre>
<p><strong>MainActivity.kt</strong></p>
<pre><code>class MainActivity : AppCompatActivity() {
private var player: SimpleExoPlayer? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onStart() {
super.onStart()
playVideo()
}
private fun playVideo() {
player = ExoPlayerFactory.newSimpleInstance(this@MainActivity, DefaultTrackSelector())
playerView.player = player
player!!.addVideoListener(object : VideoListener {
override fun onVideoSizeChanged(width: Int, height: Int, unappliedRotationDegrees: Int, pixelWidthHeightRatio: Float) {
}
override fun onRenderedFirstFrame() {
Log.d("appLog", "onRenderedFirstFrame")
}
})
player!!.addListener(object : PlayerEventListener() {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
super.onPlayerStateChanged(playWhenReady, playbackState)
when (playbackState) {
Player.STATE_READY -> Log.d("appLog", "STATE_READY")
Player.STATE_BUFFERING -> Log.d("appLog", "STATE_BUFFERING")
Player.STATE_IDLE -> Log.d("appLog", "STATE_IDLE")
Player.STATE_ENDED -> Log.d("appLog", "STATE_ENDED")
}
}
})
player!!.volume = 0f
player!!.playWhenReady = true
player!!.repeatMode = Player.REPEAT_MODE_ALL
player!!.playVideoFromUrl(this@MainActivity, "https://sample-videos.com/video123/mkv/720/big_buck_bunny_720p_1mb.mkv")
}
override fun onStop() {
super.onStop()
playerView.player = null
player!!.release()
player = null
}
abstract class PlayerEventListener : Player.EventListener {
override fun onPlaybackParametersChanged(playbackParameters: PlaybackParameters?) {}
override fun onSeekProcessed() {}
override fun onTracksChanged(trackGroups: TrackGroupArray?, trackSelections: TrackSelectionArray?) {}
override fun onPlayerError(error: ExoPlaybackException?) {}
override fun onLoadingChanged(isLoading: Boolean) {}
override fun onPositionDiscontinuity(reason: Int) {}
override fun onRepeatModeChanged(repeatMode: Int) {}
override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) {}
override fun onTimelineChanged(timeline: Timeline?, manifest: Any?, reason: Int) {}
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {}
}
companion object {
@JvmStatic
fun getUserAgent(context: Context): String {
val packageManager = context.packageManager
val info = packageManager.getPackageInfo(context.packageName, 0)
val appName = info.applicationInfo.loadLabel(packageManager).toString()
return Util.getUserAgent(context, appName)
}
}
fun SimpleExoPlayer.playVideoFromUri(context: Context, uri: Uri) {
val dataSourceFactory = DefaultDataSourceFactory(context, MainActivity.getUserAgent(context))
val mediaSource = ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri)
prepare(mediaSource)
}
fun SimpleExoPlayer.playVideoFromUrl(context: Context, url: String) = playVideoFromUri(context, Uri.parse(url))
fun SimpleExoPlayer.playVideoFile(context: Context, file: File) = playVideoFromUri(context, Uri.fromFile(file))
}
</code></pre>
<h2>What I've tried</h2>
<p>I've tried reading on the docs, and got those links (by asking about it <a href="https://github.com/google/ExoPlayer/issues/4650" rel="noreferrer"><strong>here</strong></a> ) :</p>
<p><a href="https://medium.com/google-exoplayer/downloading-streams-6d259eec7f95" rel="noreferrer">https://medium.com/google-exoplayer/downloading-streams-6d259eec7f95</a>
<a href="https://medium.com/google-exoplayer/downloading-adaptive-streams-37191f9776e" rel="noreferrer">https://medium.com/google-exoplayer/downloading-adaptive-streams-37191f9776e</a></p>
<p>So sadly, currently the only solution I can come up with, is to download the file on another thread, which will cause the device to have 2 connections to it, thus using twice the bandwidth.</p>
<h2>The questions</h2>
<ol>
<li>How can I use ExoPlayer to play a video file, while also downloading it to some filepath ?</li>
<li>Is there a way to enable a caching mechanism (which uses the disk) on ExoPlayer to be activated for the exact same purpose?</li>
</ol>
<p>Note: To make it clear. I do not want to download the file and only then play it. </p>
<hr>
<p>EDIT: I've found a way to get&use the file from the API's cache (wrote about it <a href="https://stackoverflow.com/a/53704530/878126"><strong>here</strong></a>), but it appears that this is considered as unsafe (written <a href="https://github.com/google/ExoPlayer/issues/5569#issuecomment-470081053" rel="noreferrer"><strong>here</strong></a>). </p>
<p>So, given the simple cache mechanism that the API of ExoPlayer supports, my current questions are: </p>
<ol>
<li>If a file was cached, how can I use it in a safe manner?</li>
<li>If a file was partially cached (meaning we've downloaded a part of it), how can I continue preparing it (without actually playing it or waiting for the whole playback to finish) till I can use it (in a safe manner of course) ? </li>
</ol>
<p>I've made a Github repository for this <a href="https://github.com/AndroidDeveloperLB/ExoPlayerCacheSample" rel="noreferrer"><strong>here</strong></a>. You can try it out.</p>
| 0 | 3,117 |
Using GraphServiceClient to get refresh tokens when authenticating using UserPasswordCredential in AuthenticationContext
|
<p>Sincere apologies if I miss something from this post, as I'm at my wits end after reading around for hours.</p>
<p>I'm attempting to write a back-end service (Windows) which will connect to the MS Graph API via Azure AD. I'm using C# to knock up a proof-of-concept but have run into numerous issues with the MS docs, blogs etc. being fairly convoluted and poor quality. They all seem to assume that the consumers of their API are front-end desktop or browser based apps.</p>
<p>Anyway, having managed to get connected to the Graph using the UserPasswordCredential for the service account, I receive a token in the AuthenticationContext response, but no refresh token information. MSDN suggests that the method <em>may</em> return refresh info, but hey ho, it may not. </p>
<p>Furthermore, reading (or attempting to read) this blog post on ADAL 3 (from 2015): </p>
<p><a href="http://www.cloudidentity.com/blog/2015/08/13/adal-3-didnt-return-refresh-tokens-for-5-months-and-nobody-noticed/" rel="noreferrer">http://www.cloudidentity.com/blog/2015/08/13/adal-3-didnt-return-refresh-tokens-for-5-months-and-nobody-noticed/</a></p>
<p>Left me confused in terms of how the refresh now works. The article seems to be suggesting that almost magically the tokens are refreshed in the cache for you, but after testing with my POC this is not the case.</p>
<p>I also came across this article from MS which seemed to nail it in the title:</p>
<p><a href="https://msdn.microsoft.com/en-us/office/office365/howto/building-service-apps-in-office-365" rel="noreferrer">https://msdn.microsoft.com/en-us/office/office365/howto/building-service-apps-in-office-365</a></p>
<p>However, goes off on a bit of a tangent requiring you to register apps, jump through pop-up hoops permitting access etc. etc.</p>
<p>Since I have my sample running, I've tried scheduling a re-auth to hopefully get a new token 50mins after getting the initial token (which lasts 60mins) however I just get the same token. This means at 60mins 1sec any calls via the client throw an exception (ServiceException where I have to examine the text inside to see the token expiry related info). It doesn't make sense to me to not be able to re-auth and refresh the token to carry on with a more "seamless" use of the client. </p>
<p>Here's a stripped down sample version of my code:</p>
<pre><code>namespace O365GraphTest
{
using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Nito.AsyncEx;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Linq;
using System.Threading;
using System.Security;
public class Program
{
// Just use a single HttpClient under the hood so we don't hit any socket limits.
private static readonly HttpProvider HttpProvider = new HttpProvider(new HttpClientHandler(), false);
public static void Main(string[] args)
{
try
{
AsyncContext.Run(() => MainAsync(args));
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
}
private static async Task MainAsync(string[] args)
{
var tenant = "mytenant.onmicrosoft.com";
var username = $"test.user@{tenant}";
var password = "fooooooo";
var token = await GetAccessToken(username, password, tenant);
var client = GetClient(token)
// Example of graph call
var skusResult = await client.SubscribedSkus.Request().GetAsync();
}
private static async Task<string> GetAccessToken(string username, string password, string tenant = null)
{
var authString = tenant == null ?
$"https://login.microsoftonline.com/common/oauth2/token" :
$"https://login.microsoftonline.com/{tenant}/oauth2/token";
var authContext = new AuthenticationContext(authString);
var creds = new UserPasswordCredential(username, password);
// Generic client ID
var clientId = "1950a258-227b-4e31-a9cf-717495945fc2";
var resource = "https://graph.microsoft.com";
// NOTE: There's no refresh information here, and re-authing for a token pre-expiry doesn't give a new token.
var authenticationResult = await authContext.AcquireTokenAsync(resource, clientId, creds);
return authenticationResult.AccessToken;
}
private static GraphServiceClient GetClient(string accessToken, IHttpProvider provider = null)
{
var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
return Task.FromResult(0);
});
var graphClient = new GraphServiceClient(delegateAuthProvider, provider ?? HttpProvider);
return graphClient;
}
}
}
</code></pre>
<p>If anyone can help me with this, without just saying "do it a different way" I'd be most grateful as there seems to be little discussion about this online (Freenode, IRC) and the blogs are old, the docs on MSDN terse and for specific previous versions of the library etc. e.g. </p>
<p><code>Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenAsync</code> </p>
<p>the refresh method for the AuthenticationContext class has now been removed.</p>
<p>Thanks for any advice.</p>
<p>Peter</p>
<p><strong>UPDATE</strong></p>
<p>Firstly apologies an thanks to @Fei Xue who answered my question, but I couldn't get the gist of what they were saying to begin with.</p>
<p>After chatting with Fei Xue, it does seem that if you keep the auth context around you can use the AcquireTokenSilentAsync to get new tokens going forward, you don't need to handle scheduling any refresh/reauth etc. Just bake in a check in the delegate handler (as to which method you're calling) that is part of getting the client.</p>
<p>Here's the updated version of my sample code that I've tested and it seems to work.</p>
<pre><code>namespace O365GraphTest
{
using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Nito.AsyncEx;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
public class Program
{
private const string Resource = "https://graph.microsoft.com";
// Well known ClientID
private const string ClientId = "1950a258-227b-4e31-a9cf-717495945fc2";
private static readonly string Tenant = "mytenant.onmicrosoft.com";
private static readonly HttpProvider HttpProvider = new HttpProvider(new HttpClientHandler(), false);
private static readonly AuthenticationContext AuthContext = GetAuthenticationContext(Tenant);
public static void Main(string[] args)
{
try
{
AsyncContext.Run(() => MainAsync(args));
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
}
private static async Task MainAsync(string[] args)
{
var userName = $"test.user@{Tenant}";
var password = "fooooooo";
var cred = new UserPasswordCredential(userName, password);
// Get the client and make some graph calls with token expiring delays in between.
var client = GetGraphClient(cred);
var skusResult = await client.SubscribedSkus.Request().GetAsync();
await Task.Delay(TimeSpan.FromMinutes(65));
var usersResult = await client.Users.Request().GetAsync();
}
private static AuthenticationContext GetAuthenticationContext(string tenant = null)
{
var authString = tenant == null ?
$"https://login.microsoftonline.com/common/oauth2/token" :
$"https://login.microsoftonline.com/{tenant}/oauth2/token";
return new AuthenticationContext(authString);
}
private static GraphServiceClient GetGraphClient(UserPasswordCredential credential)
{
var delegateAuthProvider = new DelegateAuthenticationProvider(async (requestMessage) =>
{
var result = AuthContext.TokenCache?.Count > 0 ?
await AuthContext.AcquireTokenSilentAsync(Resource, ClientId) :
await AuthContext.AcquireTokenAsync(Resource, ClientId, credential);
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);
});
return new GraphServiceClient(delegateAuthProvider, HttpProvider);
}
}
}
</code></pre>
<p>I was also given 2 MS articles to reference:</p>
<p><a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-authentication-scenarios" rel="noreferrer">Authentication scenarios</a></p>
<p><a href="https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_service" rel="noreferrer">Azure AD V2.0 endpoint - client credentials flow</a></p>
<p>I hope this helps anyone else in the same situation as me, as before this I was pulling my hair out!</p>
| 0 | 3,466 |
resolving font path in scss file when using webpack
|
<p>I'm using webpack with my asp.net mvc core project. I'm able to bundle js files. But I can't resolve my font paths. </p>
<p>I have this I'm scss file:</p>
<pre><code>$font-path: '../fonts' !global;
/*fonts*/
/* roboto-300 - latin */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 300;
src: url('#{$font-path}/roboto-v15-latin-300.eot'); /* IE9 Compat Modes */
src: local('Roboto Light'), local('Roboto-Light'), url('#{$font-path}/roboto-v15-latin-300.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('#{$font-path}/roboto-v15-latin-300.woff2') format('woff2'), /* Super Modern Browsers */
url('#{$font-path}/roboto-v15-latin-300.woff') format('woff'), /* Modern Browsers */
url('#{$font-path}/roboto-v15-latin-300.ttf') format('truetype'), /* Safari, Android, iOS */
url('#{$font-path}/roboto-v15-latin-300.svg#Roboto') format('svg'); /* Legacy iOS */
}
</code></pre>
<p>File structure: </p>
<pre><code>βββ Project
βββ assets
βΒ βββ scripts
β βββ main.ts
βΒ βββ scss
β βββ fonts
β βββ roboto-condensed-v13-latin-700.eot
β βββ main.scss
β
βββ webpack.config.js
var path = require('path');
var extractTextPlugin = require("extract-text-webpack-plugin");
var cleanWebpackPlugin = require('clean-webpack-plugin');
var webpack = require('webpack');
module.exports = {
entry: {
'role/role': './assets/scripts/role/roleVM.ts',
main: './assets/scripts/main.ts',
vendor: ["bootstrap", "popper.js", "jquery"]
},
output: {
filename: 'js/[name].js',
path: path.resolve(__dirname, 'wwwroot/dist/')
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.scss$/,
use: extractTextPlugin.extract({
use: [{
loader: "css-loader", options: {
sourceMap: true
}
}, {
loader: "resolve-url-loader"
},
{
loader: "sass-loader", options: {
sourceMap: true
},
}],
fallback: 'style-loader'
}),
exclude: /node_modules/
},
{
test: /.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}]
}
]
},
plugins: [
new cleanWebpackPlugin(['dist'], {
root: path.resolve(__dirname, 'wwwroot'),
verbose: true,
dry: false
}),
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'js/vendor.js' }),
new extractTextPlugin("./css/main.css"),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'Popper': 'popper.js'
})
],
resolve: {
extensions: [".tsx", ".ts", ".js", '.scss'],
modules: [
path.resolve('./'),
path.resolve('./node_modules'),
]
}
};
</code></pre>
<p>When I build webpack, I get an error: </p>
<blockquote>
<p>ERROR in ./node_modules/css-loader?{"sourceMap":true}!./node_modules/resolve-url-loader!./node_modules/sass-loader/lib/loader.js?{"sourceMap":true}!./assets/scss/main.scss
Module not found: Error: Can't resolve '../fonts/roboto-condensed-v13-latin-700.eot' in
'C:\project\src\project\assets\scss'
@ ./node_modules/css-loader?{"sourceMap":true}!./node_modules/resolve-url-loader!./node_modules/sass-loader/lib/loader.js?{"sourceMap":true}!./assets/scss/main.scss
6:215433-215491</p>
</blockquote>
| 0 | 2,207 |
Accessing Coordinates in a nested geojson file to draw polygons with Google Maps API v3
|
<p>I am having a real pain of trying to draw multiple polygons from a geojson file. Below I have pasted a sample of the geojson file and the javascript used to access it. It seems the main problem I am running into is that I cannot get into that array of coordinates nested in each record as it either returns the error that "coordinates" is undefined or that there is no method "setMap" for undefined. I have been able to return other nested aspects of a similar JSON file (this is a test file, the real one actually has data, just trying to get the polygon drawing here), but getting those coordinates is not working. I am not a javascript master so I can't tell where the code is failing to make the proper access.</p>
<p>thanks in advance.</p>
<p>the json data looks like this:</p>
<pre><code>var data={
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": 1,
"properties": {
"Name": "",
"description": "",
"timestamp": "",
"begin": "",
"end": "",
"altitudeMode": "clampToGround",
"tessellate": 1,
"extrude": -1,
"visibility": -1
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-83.126571,
42.348706
],
[
-83.126520,
42.348634
],
[
-83.126516,
42.348635
],
[
-83.126147,
42.348778
],
[
-83.126144,
42.348780
],
[
-83.126195,
42.348852
],
[
-83.126199,
42.348851
],
[
-83.126568,
42.348708
],
[
-83.126571,
42.348706
]
]
]
}
},
{
"type": "Feature",
"id": 2,
"properties": {
"Name": "",
"description": "",
"timestamp": "",
"begin": "",
"end": "",
"altitudeMode": "clampToGround",
"tessellate": 1,
"extrude": -1,
"visibility": -1
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-83.132805,
42.356496
],
[
-83.132753,
42.356423
],
[
-83.132751,
42.356424
],
[
-83.132243,
42.356624
],
[
-83.132241,
42.356625
],
[
-83.132294,
42.356698
],
[
-83.132296,
42.356697
],
[
-83.132802,
42.356497
],
[
-83.132805,
42.356496
]
]
]
}
},
{
"type": "Feature",
"id": 3,
"properties": {
"Name": "",
"description": "",
"timestamp": "",
"begin": "",
"end": "",
"altitudeMode": "clampToGround",
"tessellate": 1,
"extrude": -1,
"visibility": -1
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-83.126776,
42.351813
],
[
-83.126492,
42.351413
],
[
-83.126189,
42.351525
],
[
-83.126191,
42.351528
],
[
-83.126376,
42.351807
],
[
-83.126776,
42.351813
]
]
]
}
}
etc...
]
}
</code></pre>
<p>I've got the javascript as below, using the example used at geojason.info: <a href="http://demos.geojason.info/complex-geojson-polygons-google-maps-demo.php" rel="nofollow">http://demos.geojason.info/complex-geojson-polygons-google-maps-demo.php</a></p>
<pre><code>var points;
var pointsMore;
var polygon;
var map;
function initializeMap() {
map = new google.maps.Map(document.getElementById("map_canvas"), {
zoom: 11,
center: new google.maps.LatLng(42.347727, -83.058014),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var polygon = createPolygons(pointsMore);
//this is where the problem is...check nesting.
polygon.setMap(map);
}
function createPolygons(pointsMore) {
for (var y = 0; y < data.features.length; y++) {
var points = data.features[y];
for (var z = 0; points.geometry.length; z++) {
var pointsMore = points.geometry[z];
var coords = pointsMore.coordinates;
var paths = [];
$.each(coords,function(i,n){
$.each(n, function(j,o){
var path = [];
$.each(o,function(k,p){
var ll = new google.maps.LatLng(p[1],[0]);
path.push(ll);
});
paths.push(path);
});
});
var polygon = new google.maps.Polygon({
paths: paths,
strokeColor: "#FF7800",
strokeOpacity: 1,
strokeWeight: 2,
fillColor: "#46461F",
fillOpacity: 0.25
});
return polygon;
}
}
}
</code></pre>
| 0 | 5,035 |
Angular 6 StaticInjectorError (Platform: core) No provider for
|
<p>I have a project with a angular version of 4. *. \ *.
I tried to update the project to 6 angular versions.
I fixed all the errors that the compiler told me when I build a prod. There were a lot of them.
Now the project compiles without errors, but it does not work in the browser.
And now I'm stuck. Can someone help me with this problem?<br>
I think this is somehow connected with lazy loading, but I have not been able to find a solution for a long time.<br>
Added a code that can help in the answer. If you need something else, tell me.
<br><br>
<strong>Error:</strong></p>
<pre><code>Uncaught Error: StaticInjectorError(Platform: core)[t]:
NullInjectorError: No provider for t!
at t.get (app.cc6edb9a8a038b005e52.bundle.js:1)
at O (app.cc6edb9a8a038b005e52.bundle.js:1)
at C (app.cc6edb9a8a038b005e52.bundle.js:1)
at t.get (app.cc6edb9a8a038b005e52.bundle.js:1)
at t.bootstrapModule (app.cc6edb9a8a038b005e52.bundle.js:1)
at Object.<anonymous> (app.cc6edb9a8a038b005e52.bundle.js:1)
at n (polyfills.cc6edb9a8a038b005e52.bundle.js:1)
at window.webpackJsonp (polyfills.cc6edb9a8a038b005e52.bundle.js:1)
at app.cc6edb9a8a038b005e52.bundle.js:1
</code></pre>
<p><strong>webpack.config:</strong></p>
<pre><code>var path = require('path');
var webpack = require('webpack');
const fse = require('fs-extra')
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
try {
fse.copySync(
'./node_modules/primeng/components',
'./aot/node_modules/primeng/components',
{
overwrite: false,
errorOnExist: false
}
);
}
catch (err) {
console.error(err)
}
module.exports = {
entry: {
'vendor': './angularApp/vendor.ts',
'polyfills': './angularApp/polyfills.ts',
'app': './angularApp/main-aot.ts' // AoT compilation
},
output: {
path: path.resolve(__dirname, 'wwwroot'),
filename: 'dist/[name].[hash].bundle.js',
chunkFilename: 'dist/[id].[hash].chunk.js',
publicPath: '/'
},
resolve: {
extensions: ['.ts', '.js', '.json', '.css', '.scss', '.html']
},
devServer: {
historyApiFallback: true,
stats: 'minimal',
outputPath: path.join(__dirname, 'wwwroot/')
},
module: {
rules: [
{
test: /\.ts$/,
loaders: [
'awesome-typescript-loader',
'angular-router-loader'
]
},
{
test: /\.(png|jpg|gif|woff|woff2|ttf|svg|eot)$/,
loader: 'file-loader?name=assets/[name]-[hash:6].[ext]'
},
{
test: /favicon.ico$/,
loader: 'file-loader?name=/[name].[ext]'
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
},
{
test: /\.scss$/,
exclude: /node_modules/,
loaders: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.html$/,
loader: 'raw-loader'
}
],
exprContextCritical: false
},
plugins: [
new CleanWebpackPlugin(
[
'./wwwroot/dist',
'./wwwroot/assets'
]
),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
output: {
comments: false
},
sourceMap: false
}),
new webpack.optimize.CommonsChunkPlugin(
{
name: ['vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
filename: 'index.html',
inject: 'body',
template: 'angularApp/index.html'
}),
new CopyWebpackPlugin([
{ from: './angularApp/images/*.*', to: 'assets/', flatten: true }
]),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
'window.jQuery': 'jquery',
'window.Tether': 'tether',
tether: 'tether',
Tether: 'tether',
Popper: ['popper.js', 'default']
})
]
};
</code></pre>
<p><strong>package.json</strong></p>
<pre><code>"dependencies": {
"@angular/common": "^6.1.3",
"@angular/compiler": "^6.1.3",
"@angular/compiler-cli": "^6.1.3",
"@angular/platform-server": "^6.1.3",
"@angular/core": "^6.1.3",
"@angular/forms": "^6.1.3",
"@angular/http": "^6.1.3",
"@angular/platform-browser": "^6.1.3",
"@angular/platform-browser-dynamic": "^6.1.3",
"@angular/router": "^6.1.3",
"@angular/upgrade": "^6.1.3",
"@angular/animations": "^6.1.3",
"angular-in-memory-web-api": "0.6.1",
"core-js": "^2.5.0",
"reflect-metadata": "^0.1.10",
"rxjs": "^6.2.2",
"zone.js": "0.8.26",
"ie-shim": "~0.1.0"
},
"devDependencies": {
"@types/node": "7.0.22",
"@types/jasmine": "2.5.47",
"@types/file-saver": "0.0.0",
"alertify.js": "^1.0.12",
"file-saver": "^1.3.3",
"angular2-template-loader": "0.6.2",
"angular-router-loader": "^0.6.0",
"awesome-typescript-loader": "^3.2.2",
"clean-webpack-plugin": "^0.1.16",
"concurrently": "^3.5.0",
"copy-webpack-plugin": "^4.0.1",
"css-loader": "^0.28.4",
"file-loader": "^0.11.2",
"html-webpack-plugin": "^2.30.1",
"json-loader": "^0.5.7",
"node-sass": "^4.5.3",
"raw-loader": "^0.5.1",
"rimraf": "^2.6.1",
"sass-loader": "^6.0.6",
"source-map-loader": "^0.2.1",
"style-loader": "^0.18.2",
"ts-helpers": "^1.1.2",
"tslint": "^5.5.0",
"tslint-loader": "^3.5.3",
"typescript": "2.7.2",
"url-loader": "^0.5.9",
"webpack": "^3.4.1",
"webpack-dev-server": "^2.6.1",
"jasmine-core": "^2.7.0",
"karma": "^1.7.0",
"karma-chrome-launcher": "^2.2.0",
"karma-jasmine": "^1.1.0",
"karma-sourcemap-loader": "0.3.7",
"karma-spec-reporter": "^0.0.31",
"karma-webpack": "^2.0.4",
"bootstrap": "4.0.0-beta",
"popper.js": "^1.12.5",
"jquery": "^3.2.1",
"jquery-ui-dist": "^1.12.1",
"tether": "^1.4.0",
"primeng": "^6.1.2",
"font-awesome": "^4.7.0",
"ng2-file-upload": "^1.2.1",
"fs-extra": "7.0.0"
}
</code></pre>
<p><strong>main-aot.ts:</strong></p>
<pre><code>import { platformBrowser } from '@angular/platform-browser';
import { enableProdMode } from '@angular/core';
import { AppModule } from "./app/app.module";
enableProdMode();
const platform = platformBrowser();
platform.bootstrapModule(AppModule);
</code></pre>
<p><strong>app.module.ts:</strong></p>
<pre><code>// modules ------------------
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutes } from './app.routes';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MainPipeModule } from './common/mainPipe.module';
import { FilterModule } from './filter/filter.module';
// components
import { Configuration } from './app.constants';
import { AppComponent } from './app.component';
// services ----------------
import { MembershipService } from './services/membership.service';
import { DataService } from './services/data.service';
import { NotificationService } from './services/notification.service';
import { UtilityService } from './services/utility.service';
import { User1cService } from './services/user1c.service';
import { UserSystemService } from './services/userSystem.service';
import { SchetFactureService } from './services/schetFacture.service';
import { GraphicPaymentService } from './services/graphicPayment.service';
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
AppRoutes,
HttpModule,
HttpClientModule,
MainPipeModule,
FilterModule,
],
declarations: [
AppComponent
],
providers: [
MembershipService, NotificationService,
UtilityService, DataService, UserSystemService,
User1cService,
SchetFactureService,
GraphicPaymentService,
Configuration
],
bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>
<p><strong>app.routes.ts:</strong></p>
<pre><code>import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{
path: '',
redirectTo: '/zayavki',
pathMatch: 'full'
},
{ path: 'account', loadChildren: './account/account.module#AccountModule' },
{ path: 'zayavki', loadChildren: './zayavka/zayavka.module#ZayavkaModule' },
{ path: 'scheta', loadChildren: './schet/schet.module#SchetModule' },
{ path: 'graphic-payment', loadChildren: './graphicPayment/graphicPayment.module#GraphicPaymentModule' },
{ path: 'schet-facture', loadChildren: './schetFacture/schetFacture.module#SchetFactureModule' },
{ path: 'report', loadChildren: './reports/report.module#ReportModule' },
{ path: 'about', loadChildren: './about/about.module#AboutModule' },
{ path: 'realisation', loadChildren: './realisation/realisation.module#RealisationModule' },
{ path: 'storage', loadChildren: './storage/storage.module#StorageModule' },
];
export const AppRoutes: any = RouterModule.forRoot(routes);
</code></pre>
| 0 | 4,629 |
Change content based on select dropdown id in jquery
|
<p>I am trying to update content within divs based on a select box option.</p>
<p>If selected the id of the option should be used to display or hide the appropriate divs witin the area.</p>
<pre><code><select class=" outtaHere">
<option class="selected" value="australia_new_zealand_holidays"> Australasia</option>
<option value="central_america_and_caribbean"> Central America &amp; the Caribbean</option>
<option value="europe"> Europe</option>
<option value="indian_subcontinent_holidays"> Indian Subcontinent</option>
<option value="north_central_asia"> North &amp; Central Asia</option>
<option value="north_africa_middle_east"> North Africa &amp; Middle East</option>
<option value="north_america"> North America</option>
<option value="polar_regions"> Polar Regions</option>
<option value="south_america"> South America</option>
<option value="south_east_asia"> South East Asia</option>
<option value="sub_saharan_africa"> Sub Saharan Africa</option>
</select>
</code></pre>
<p>All should be hidden unless one of the above is selected:</p>
<pre><code><div class="scroll-content">
<ul class="countrylist australia_new_zealand_holidays">
<li><a href="countries/australia-holidays">Australia</a></li>
<li><a href="countries/papua-new-guinea-holidays">Papua New Guinea</a></li>
<li><a href="countries/new-zealand">New Zealand</a></li>
</ul>
<ul class="countrylist central_america_and_caribbean">
<li><a href="countries/costa-rica-holidays">Costa Rica</a></li>
</ul>
<ul class="countrylist europe">
<li><a href="countries/finland-holidays">Finland</a></li>
<li><a href="countries/france-adventure-holiday">France</a></li>
</ul>
<ul class="countrylist indian_subcontinent_holidays">
<li><a href="countries/bhutan-holidays">Bhutan</a></li>
<li><a href="countries/india-holidays">India</a></li>
<li><a href="countries/nepal-adventure-holidays">Nepal</a></li>
<li><a href="countries/sri-lanka-holidays">Sri Lanka</a></li>
</ul>
</div>
</code></pre>
<p>At the same time as the select box is chosen i need to update the following div with the value also like so:</p>
<pre><code><div class="desrarea optionvalue">
</code></pre>
| 0 | 1,252 |
how to code json array without array name?
|
<p>I'm new to JSON android java eclipse. I am doing a listview with images and parsing json array. I followed this tutorial: <a href="http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/" rel="nofollow">http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/</a> . In that tutorial, their JSON array contains the array name.However, mine doesn't contain the array name. So my question is how to code JSON Array without the array name? </p>
<p>Below is my JSON code. </p>
<pre><code>[
{ "event_id": "EV00000001",
"event_title": "Movie 1",
},
{
"event_id": "EV00000002",
"event_title": "Movie2",
}
]
</code></pre>
<p>Below is my JSON coding for parsing the JSON.</p>
<pre><code> protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Events event = new Events();
event.setevent_title(object.getString("event_title"));
eventList.add(event);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
</code></pre>
<p>What am i suppose to do?</p>
<p>This problem is solved. Thus, i will be posting the correct code. </p>
<pre><code>protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray array = new JSONArray(data);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
Events event = new Events();
event.setevent_title(obj.getString("event_title"));
eventList.add(event);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
</code></pre>
| 0 | 1,417 |
Could we destroy/invalidate JWT token in Asp.NET Core?
|
<p>I use ASP.NET Core & ASP.NET core Identity to generate a JWT token.</p>
<p>On the client-side, my React (SPA) app calls API to create the token then include <code>Authorization: Bearer</code> <code>token from API</code> in subrequests.</p>
<p>When I want to logout, how can I immediately invalidate the token on the server-side?</p>
<p>Currently, I just delete the <code>bear</code> token on the client-side and not included in the next request?</p>
<p><strong>Reference</strong>: <a href="https://blogs.msdn.microsoft.com/webdev/2017/04/06/jwt-validation-and-authorization-in-asp-net-core/" rel="noreferrer">https://blogs.msdn.microsoft.com/webdev/2017/04/06/jwt-validation-and-authorization-in-asp-net-core/</a></p>
<hr />
<p>Code in <code>Configure</code> section in <code>Startup.cs</code></p>
<pre><code>app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "MySite",
ValidAudience = "MySite",
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("VERYL0NGKEYV@LUETH@TISSECURE")),
ValidateLifetime = true
}
});
</code></pre>
<p>API to create a token</p>
<pre><code>[HttpPost("Token")]
public async Task<IActionResult> CreateToken([FromBody] LoginModel model)
{
try
{
var user = await userManager.FindByNameAsync(model.Email);
if (passwordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Email, user.Email)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("VERYL0NGKEYV@LUETH@TISSECURE"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
"MySite",
"MySite",
claims,
expires: DateTime.UtcNow.AddMinutes(45),
signingCredentials: creds);
return Ok(new
{
Token = new JwtSecurityTokenHandler().WriteToken(token),
Expiration = token.ValidTo,
});
}
return BadRequest();
}
catch (Exception ex)
{
logger.LogError(ex.ToString());
return StatusCode((int)HttpStatusCode.InternalServerError);
}
}
</code></pre>
| 0 | 1,206 |
How to set the state_pressed of a button
|
<p>I use a xml file to color my button. In the xml a have this code to define the color of my button when it's clicked.</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape>
<gradient
android:startColor="@color/mainRaddoppiaButtonBackgroundEnd"
android:endColor="@color/mainRaddoppiaButtonBackgroundStart"
android:angle="270" />
<stroke
android:width="0dp"
android:color="@color/mainRaddoppiaButtonBackgroundStart" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item android:state_focused="true" >
<shape>
<gradient
android:startColor="@color/mainRaddoppiaButtonBackgroundEnd"
android:endColor="@color/mainRaddoppiaButtonBackgroundStart"
android:angle="270" />
<stroke
android:width="0dp"
android:color="@color/mainRaddoppiaButtonBackgroundStart" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="@color/mainRaddoppiaButtonBackgroundStart"
android:endColor="@color/mainRaddoppiaButtonBackgroundEnd"
android:angle="270" />
<stroke
android:width="0dp"
android:color="@color/mainRaddoppiaButtonBackgroundStart" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
</selector>
</code></pre>
<p>Is it possibile from java to keep my button pressed and color it with "state_pressed" values set in my xml file?</p>
<p>Someting like: </p>
<pre><code> public void onClick(View button) {
button.seLayout(R.xml.xmlFileName.state_pressed)
}
</code></pre>
<p>Of course this code has no sense, i just made it up to let you understand what i want to do</p>
| 0 | 1,461 |
c# - How to use DateTimeOffset in MongoDB
|
<pre><code>public class ScheduledEvent : Event
{
public DateTimeOffset StartDateTime { get; set; }
}
</code></pre>
<p>StartDateTime = 5/27/2013 2:09:00 AM +00:00 representing 05/26/2013 07:09 PM PST</p>
<p>What's recorded in MongoDB:</p>
<pre><code>db.ScheduledEvent.find().toArray()[
{
"_id": BinData(3, "ZE2p31dh00qb6kglsgHgAA=="),
"Title": "Today 26th at 7:09pm",
"Length": "00:00:00",
"MoreInformation": "http://1.com",
"Speakers": [{
"_id": BinData(3, "ndzESsQGukmYGmMgKK0EqQ=="),
"Name": "Mathias Brandewinder"
}
],
"Location": {
"_id": BinData(3, "AAAAAAAAAAAAAAAAAAAAAA=="),
"Name": "Somwhere "
},
"Organizers": [{
"_id": BinData(3, "AAAAAAAAAAAAAAAAAAAAAA=="),
"Name": null
}],
"CreatedOn": [
NumberLong("635052144104050898"),
0
],
"StartDateTime": [
NumberLong("635052173400000000"),
0
]
}
]
</code></pre>
<hr />
<p>I realize that StartDateTime is stored as Ticks in MongoDB.</p>
<pre><code>var dateMarker = DateTimeOffset.UtcNow;
var nextDay = dateMarker.AddDays(1);
</code></pre>
<p>This query does not work:</p>
<pre><code>var today = EventRepoistory
.All()
.Where(z => z.StartDateTime >= dateMarker
&& z.StartDateTime < nextDay)
.OrderByDescending(z => z.StartDateTime)
.ToList();
</code></pre>
<p>I have added a query display to the Mongo C# driver which shows the following query:</p>
<pre><code>{ "$query" : { "StartDateTime" : { "$gte" : [NumberLong("635052168609734070"), 0], "$lt" : [NumberLong("635053032609734070"), 0] } }, "$orderby" : { "StartDateTime" : -1 } }
</code></pre>
<blockquote>
<p><code>Lower bound = 6350521 68609734070</code></p>
</blockquote>
<blockquote>
<p><code>Server = 6350521 73400000000</code></p>
</blockquote>
<blockquote>
<p><code>Upper bound = 6350530 32609734070</code></p>
</blockquote>
<p><strong>Question: Why this MongoDB query doesn't return anything?</strong></p>
<pre><code>db.ScheduledEvent.find({
"$query": {
"StartDateTime": {
"$gte": [NumberLong("635052168609734070"), 0],
"$lt": [NumberLong("635053032609734070"), 0]
}
},
"$orderby": {
"StartDateTime": -1
}
})
</code></pre>
<p>I have researched about this topic and I found this solution :
<a href="https://stackoverflow.com/questions/10480127/mongodb-and-datetimeoffset-type">MongoDB and DateTimeOffset type</a></p>
<p>But it seams that LINQ provider is doing what it's supposed to?</p>
<hr />
<p>I have also tried code:</p>
<pre><code>db.ScheduledEvent.find({
"StartDateTime": {
"$gte": [NumberLong("1"), 0]
}
})
</code></pre>
<p>But it doesn't return any result.</p>
| 0 | 1,596 |
Load balancer does not have available server for client: meeting
|
<p>While I am trying to reach the service <code>meeting</code> via Zuul gateway, Zuul is unable to forward the request to the respective service. The following errors are what I am facing:</p>
<blockquote>
<ol>
<li>nettflix.zuul.exception.ZuulException: Forwarding error</li>
<li>Caused by: com.netflix.client.ClientException: Load balancer does not have available server for client: meeting</li>
</ol>
</blockquote>
<p>Let me share the application.yml for the service, eureka and zuul gateway.</p>
<p><strong>EurekaClient:</strong>
<code>Application.yml</code></p>
<pre class="lang-yaml prettyprint-override"><code>server:
port: 8761
eureka:
instance:
hostname: localhost
lease-renewal-interval-in-seconds: 300
client:
register-with-eureka: false
fetch-registry: true
serviceUrl:
defaultZone: http://localhost:8761/eureka/
</code></pre>
<p><strong>ZuulGateWay:</strong>
<code>application.yml</code></p>
<pre class="lang-yaml prettyprint-override"><code>server:
port: 8085
spring:
application:
name: gatekeeper
zuul:
routes:
meeting: /meeting/**
serviceId: meeting
ribbon:
eureka:
enabled: false
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
</code></pre>
<p><strong>ZuulGateWay:</strong> <code>SpringBootApplication</code></p>
<pre><code>package com.sagarp.gatekeeper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class MeetingApplication {
public static void main(String[] args) {
SpringApplication.run(MeetingApplication.class, args);
}
}
</code></pre>
<p><strong>My Service class (meeting):</strong> <code>Application.yml</code></p>
<pre class="lang-yaml prettyprint-override"><code>server:
port: 0
spring:
application:
name: meeting
datasource:
url: jdbc:mysql://localhost:3306/sagarp?useSSL=false
username: myUserName
password: myPassWord
jpa:
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
hibernate:
ddl-auto: update
eureka:
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://localhost:8761/eureka/
instance:
lease-renewal-interval-in-seconds: 5
</code></pre>
<p><strong>My Service class (meeting):</strong> <code>SpringBootApplication</code></p>
<pre><code>package com.sagarp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class MeetingApplication {
public static void main(String[] args) {
SpringApplication.run(MeetingApplication.class, args);
}
}
</code></pre>
<p>As you can see, the configuration ensures that all my services are discovered by eureka client.</p>
<p>In the eureka console, I have verified the same, the <code>zuul gateway</code> and <code>my service(meeting)</code> both are visible.</p>
<p>For better view, you can visit my git repo. <a href="https://github.com/sagar-patro/demo-microservices" rel="noreferrer">https://github.com/sagar-patro/demo-microservices</a></p>
<p>Any help would be very much appreciable</p>
| 0 | 1,262 |
Java HTTPPost Request with Apache HttpClient
|
<p>I need a java program to generate the following request.
I am using Apache HttpClient Library but still not able to produce a request like this:</p>
<p>This is what my python program generates and i wrote an equivalent java program. but its throwing 403.</p>
<p>2012-09-10 15:12:05G INFO: G2OAuth auth data = "3, 0.0.0.0, 0.0.0.0, 1347289925, 3223833979, crlakamai"
2012-09-10 15:12:05G INFO: G2OAuth sign string = "3, 0.0.0.0, 0.0.0.0, 1347289925, 3223833979, akamai/182228\nx-akamai-acs-action:version=1&action=dir&format=xml\n"</p>
<pre><code> send: 'POST /182228 HTTP/1.1\r\nHost: crl.api.akamailab.com\r\nAccept-Encoding: identity\r\nX-Akamai-ACS-Auth-Data: 3, 0.0.0.0, 0.0.0.0, 1347289925, 3223833979, crlsymc\r\nX-Akamai-ACS-Auth-Sign: eFnWtJBIyj4rxV3V0axF3w==\r\nX-Akamai-ACS-Action: version=1&action=dir&format=xml\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Server: Apache
header: Content-Type: text/html
header: Date: Mon, 10 Sep 2012 15:12:09 GMT
header: Content-Length: 31
header: Connection: keep-alive
</code></pre>
<p>The response looks like this:</p>
<pre><code><?xml version="1.0" encoding="ISO-8859-1"?>
<stat directory="/182232">
Β Β Β Β Β Β Β <file type="file" name="log4j.properties" mtime="1346780907" size="301" md5="c92268157f1732a05c2027d151fc539a"/>
</stat>
</code></pre>
<p>Here is My Java Code:</p>
<pre><code> final HttpHost targetHost = new HttpHost("a.host.com", 80, "http");
final DefaultHttpClient httpClient = new DefaultHttpClient();
final Credentials credentials = new UsernamePasswordCredentials("user","pass");
httpClient.getCredentialsProvider().setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), credentials);
final HttpPost httpPostRequest = new HttpPost("akamai/182232");
//Add your Data
final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);
nameValuePairs.add(new BasicNameValuePair("Host: ", "a.host.com");
nameValuePairs.add(new BasicNameValuePair("Accept-Encoding: ", "identity"));
nameValuePairs.add(new BasicNameValuePair("Content-Length: ", "6"));
httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
final HttpResponse response = httpClient.execute(targetHost, httpPostRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
</code></pre>
<p>My response looks like this.</p>
<pre><code>2012-09-10 11:31:22,600 DEBUG [wire] >> "POST /182228/a.crl HTTP/1.1[\r][\n]"
2012-09-10 11:31:22,601 DEBUG [wire] >> "Content-Length: 394[\r][\n]"
2012-09-10 11:31:22,601 DEBUG [wire] >> "Content-Type: application/x-www-form-urlencoded; charset=ISO-8859-1[\r][\n]"
2012-09-10 11:31:22,601 DEBUG [wire] >> "Host: crl.api.symclab.com:80[\r][\n]"
2012-09-10 11:31:22,601 DEBUG [wire] >> "Connection: Keep-Alive[\r][\n]"
2012-09-10 11:31:22,601 DEBUG [wire] >> "User-Agent: Apache-HttpClient/4.1.3 (java 1.5)[\r][\n]"
2012-09-10 11:31:22,602 DEBUG [wire] >> "[\r][\n]"
</code></pre>
<p>I want Accept-Encoding another headers as part of post, how do i add them ? It hast to be part of the post request i believe and not http header.</p>
| 0 | 1,357 |
JNDI Name binding in JBOSS 5.1.0 Beta
|
<p>I am following the MasteringEJB4thEdition book, which I downloaded from The Server Site website.</p>
<p>There is a simple example of HelloBean, which works perfectly with GlassFish V3 app server. The same example when deployed on JBOSS fails because of JNDI name lookup.</p>
<p>Is there any rule how the JNDI lookup names in JBOSS are decided if we don't provide any ? I found while googling that it is "ear-file-name/Bean-class-name/remote" but it doesn't work for me.</p>
<p>Here is the bean</p>
<pre><code>
1. package com.hardik.stateless;
2. import javax.ejb.Stateless;
3. import javax.ejb.Remote
4.
5.
6.
7.
8. @Stateless
9. @Remote(Hello.class)
10. public class HelloBean implements Hello {
11.
12. public String hello() {
13. System.out.println("hello()");
14. return "Hello, World!";
15. }
16.
17. }
</code></pre>
<p>Here is the client I am using: </p>
<pre><code>
1. package com.hardik.stateless;
2.
3. import javax.naming.Context;
4. import javax.naming.InitialContext;
5.
6.
7. /**
8. * This is an example of client code which invokes
9. * methods on a simple, remote stateless session bean
10. * @author hardik
11. *
12. */
13. public class HelloClient {
14.
15. public static void main(String[] args) throws Exception {
16.
17. Context ctx = new InitialContext();
18. // works for Glassfish
19. //Hello hello = (Hello) ctx.lookup("com.hardik.stateless.Hello");
20. // doesn't work for JBOSS
21. Hello hello = (Hello) ctx.lookup("hello-bean/HelloBean/remote");
22.
23. System.out.println(hello.hello());
24. }
25.
26. }
</code></pre>
<p>Here is the error I get while executing the client </p>
<pre><code>
# $ wsrunclient.sh -Djava.naming.factory.initial=org.jnp.interfaces.NamingContextFactory -Djava.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces -Djava.naming.provider.url=jnp://localhost:1099 -cp "lib/hello-bean.jar:dist/hello-client.jar:/home/hardik/apps/jboss/client/*" com.hardik.stateless.HelloClient
# log4j:WARN No appenders could be found for logger (org.jnp.interfaces.TimedSocketFactory).
# log4j:WARN Please initialize the log4j system properly.
# Exception in thread "main" javax.naming.NameNotFoundException: hello-bean not bound
# at org.jnp.server.NamingServer.getBinding(NamingServer.java:771)
# at org.jnp.server.NamingServer.getBinding(NamingServer.java:779)
# at org.jnp.server.NamingServer.getObject(NamingServer.java:785)
# at org.jnp.server.NamingServer.lookup(NamingServer.java:396)
# at sun.reflect.GeneratedMethodAccessor260.invoke(Unknown Source)
# at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
# at java.lang.reflect.Method.invoke(Method.java:597)
# at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:305)
# at sun.rmi.transport.Transport$1.run(Transport.java:159)
# at java.security.AccessController.doPrivileged(Native Method)
# at sun.rmi.transport.Transport.serviceCall(Transport.java:155)
# at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:535)
# at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
# at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
# at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
# at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
# at java.lang.Thread.run(Thread.java:619)
# at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:255)
# at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:233)
# at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:142)
# at org.jnp.server.NamingServer_Stub.lookup(Unknown Source)
# at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:722)
# at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:682)
# at javax.naming.InitialContext.lookup(InitialContext.java:392)
# at com.hardik.stateless.HelloClient.main(Unknown Source)
</code></pre>
| 0 | 1,949 |
Can't Build NetBeans/Ant Project
|
<p>I have inherited a project originally written in NetBeans using Ant to build. I am an Eclipse user and have used Ant but do not completely understand the NetBeans specific way of using Ant. I know it uses a <code>build-impl.xml</code> file (imported into the <code>build.xml</code>), but am at a loss as to how that file is <code>generated/updated</code> by the IDE.</p>
<p>I made some minor changes to a couple of classes and want to build a jar. I tried running the <code>"clean"</code> and <code>"jar"</code> targets in Eclipse from both the <code>build.xml</code> and <code>build-impl.xml</code> but get the following errors:</p>
<pre><code>BUILD FAILED
C:\Devel\Projects\MyProject\nbproject\build-impl.xml:661: The following error occurred while executing this line:
C:\Devel\Projects\MyProject\nbproject\build-impl.xml:337: Compile failed; see the compiler error output for details.
</code></pre>
<p>Line 661 is the j2seproject3 element in this target:</p>
<pre><code><target depends="init,deps-jar,-pre-pre-compile,-pre-compile, -copy-persistence-xml,-compile-depend" if="have.sources" name="-do-compile">
<j2seproject3:javac gensrcdir="${build.generated.sources.dir}"/>
<copy todir="${build.classes.dir}">
<fileset dir="${src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/>
</copy>
</target>
</code></pre>
<p>Line 337 is the javac line from this target:</p>
<pre><code><target depends="-init-ap-cmdline-properties" name="-init-macrodef-javac-without-processors" unless="ap.supported.internal">
<macrodef name="javac" uri="http://www.netbeans.org/ns/j2se-project/3">
<attribute default="${src.dir}" name="srcdir"/>
<attribute default="${build.classes.dir}" name="destdir"/>
<attribute default="${javac.classpath}" name="classpath"/>
<attribute default="${javac.processorpath}" name="processorpath"/>
<attribute default="${build.generated.sources.dir}/ap-source-output" name="apgeneratedsrcdir"/>
<attribute default="${includes}" name="includes"/>
<attribute default="${excludes}" name="excludes"/>
<attribute default="${javac.debug}" name="debug"/>
<attribute default="${empty.dir}" name="sourcepath"/>
<attribute default="${empty.dir}" name="gensrcdir"/>
<element name="customize" optional="true"/>
<sequential>
<property location="${build.dir}/empty" name="empty.dir"/>
<mkdir dir="${empty.dir}"/>
<javac debug="@{debug}" deprecation="${javac.deprecation}" destdir="@{destdir}" encoding="${source.encoding}" excludes="@{excludes}" executable="${platform.javac}" fork="yes" includeantruntime="false" includes="@{includes}" source="${javac.source}" sourcepath="@{sourcepath}" srcdir="@{srcdir}" target="${javac.target}" tempdir="${java.io.tmpdir}">
<src>
<dirset dir="@{gensrcdir}" erroronmissingdir="false">
<include name="*"/>
</dirset>
</src>
<classpath>
<path path="@{classpath}"/>
</classpath>
<compilerarg line="${endorsed.classpath.cmd.line.arg}"/>
<compilerarg line="${javac.compilerargs}"/>
<customize/>
</javac>
</sequential>
</macrodef>
</target>
</code></pre>
<p>I have no idea what these two targets are about and why they're failing. I downloaded NetBeans7 hoping that building it there would succeed, but get the same errors.</p>
<p>Can I safely remove these targets from my build? Do I need to update the project.properties file?</p>
<p>Any help getting this to build is appreciated.</p>
| 0 | 1,643 |
Calling ActionChains move_to_element() leads to attribute error?
|
<p>I'm getting the following error when running my python/selenium script:</p>
<p><strong>AttributeError: 'WebElement' object has no attribute 'move_to_element'</strong></p>
<p>What does this particular error message tell? Is it not recognizing move_to_element as a valid action? I am importing the actionchains module as such:</p>
<pre><code>from selenium.webdriver.common.action_chains import ActionChains
</code></pre>
<p>I'm able to use the click() and send_keys() actions without issues.</p>
<pre><code>def wait_for_element_visibility(self, waitTime, locatorMode, Locator):
element = None
if locatorMode == LocatorMode.ID:
element = WebDriverWait(self.driver, waitTime).\
until(EC.visibility_of_element_located((By.ID, Locator)))
elif locatorMode == LocatorMode.NAME:
element = WebDriverWait(self.driver, waitTime).\
until(EC.visibility_of_element_located((By.NAME, Locator)))
elif locatorMode == LocatorMode.XPATH:
element = WebDriverWait(self.driver, waitTime).\
until(EC.visibility_of_element_located((By.XPATH, Locator)))
elif locatorMode == LocatorMode.CSS_SELECTOR:
element = WebDriverWait(self.driver, waitTime).\
until(EC.visibility_of_element_located((By.CSS_SELECTOR, Locator)))
else:
raise Exception("Unsupported locator strategy.")
return element
def find_element(self, locatorMode, Locator):
element = None
if locatorMode == LocatorMode.ID:
element = self.driver.find_element_by_id(Locator)
elif locatorMode == LocatorMode.NAME:
element = self.driver.find_element_by_name(Locator)
elif locatorMode == LocatorMode.XPATH:
element = self.driver.find_element_by_xpath(Locator)
elif locatorMode == LocatorMode.CSS_SELECTOR:
element = self.driver.find_element_by_css_selector(Locator)
else:
raise Exception("Unsupported locator strategy.")
return element
def fill_out_field(self, locatorMode, Locator, text):
self.find_element(locatorMode, Locator).clear()
self.find_element(locatorMode, Locator).send_keys(text)
def click(self, waitTime, locatorMode, Locator):
self.wait_until_element_clickable(waitTime, locatorMode, Locator).click()
def hover_over(self, waitTime, locatorMode, Locator):
element = Locator
self.wait_for_element_visibility(waitTime, locatorMode, Locator).move_to_element(element).perform()
</code></pre>
<p>I'm trying to call it like this:</p>
<pre><code>self.hover_over(10,
"id",
WelcomePageMap['ShareButtonId']
)
</code></pre>
| 0 | 1,072 |
Accessing class variables
|
<p>It's the first time I use OOP with PHP 5.. so this is my problem..</p>
<p>I have a file <code>disp.php</code> that contains a class named class disp (model in MVC)</p>
<pre><code><?php
class disp{
public $n_pages;
public $current_page;
private $cmd2;
/***************SQL command generator*******************/
private function getCmd2($cmd1,$id,$first_entry,$perpage,$tri){
$cmd2=str_replace('COUNT(*)','*',$cmd1);
$cmd2=$cmd2.' ORDER BY '.$id.' '.$tri.' LIMIT '.$first_entry.','.$perpage;
return $cmd2;
}
/********************Items display******************/
function dispItems($cmd1,$id,$perpage,$tri){
require('global/connection.inc.php');
try{
foreach($pdo->query($cmd1)as $r){
$n_pages=ceil($r[0]/$perpage);
if (isset ($_GET['pg'])){
$current_page=intval($_GET['pg']);
if ($current_page>$n_pages){
$current_page=$n_pages;
}
if ($current_page<=0){
$current_page=1;
}
}
else{
$current_page=1;
$_GET['pg']=1;
}
}
$i=1;
$first_entry=($current_page-1)*$perpage;
$objet=new disp();
$cmd2=$objet->getCmd2($cmd1,$id,$first_entry,$perpage,$tri);
$data=array();
$i=0;
foreach($pdo->query($cmd2) as $r){
$data[$i]=$r;
$i++;
}
return $data;
}catch(PDOException $e){}
}
}
</code></pre>
<p>this is the file <code>news.php</code> (controller in MVC):</p>
<pre><code>require MODELS_DIR.'disp.php';
$objet=new disp();
$news=$objet->dispItems('SELECT COUNT(*) FROM tbl_nouveautes','ID_EVENT',10,'DESC');
$c_page=$objet->$current_page;
$n_pages= $objet->$n_pages;
require VIEWS_DIR.'disp-news.php';
</code></pre>
<p>in this code, I created an object (objet) of the type disp... I want to use the variables declared in the function <code>dispItems</code>, (<code>$n_pages</code> and <code>$current_page</code>) in the view (<code>disp-news.php</code>)</p>
<p>so I think that the class variables are the same variables in the function <code>dispItems()</code>... but when trying to access them from the controller ...using object. it shows me a error :</p>
<p>See:</p>
<pre><code>Notice: Undefined variable: n_pages in C:\Program Files\EasyPHP-5.3.6.1\www\example\admin\global\news.php on line 14
Fatal error: Cannot access empty property in C:\Program Files\EasyPHP-5.3.6.1\www\example\admin\global\news.php on line 14
</code></pre>
<p>Inspite of <code>$n_pages</code> and <code>$current_pages</code> being public in the class disp</p>
<p>thank you in advance</p>
| 0 | 1,168 |
HighCharts is not defined
|
<p>Hi I have a simple MVC extjs application : </p>
<p>My app.js : </p>
<pre><code>Ext.Loader.setConfig({
enabled: true,
paths : {
'Chart' : './Chart'
}
});
Ext.require('Chart.ux.Highcharts');
Ext.require('Chart.ux.Highcharts.Serie');
Ext.require('Chart.ux.Highcharts.SplineSerie');
Ext.application({
name: 'MyAppli',
autoCreateViewport: true,
});
</code></pre>
<p>My Controller : </p>
<pre><code>showWindow: function () {
var chartStore = this.getHighChartDataStore();
var win = Ext.create('Ext.window.Window', {
width : 800,
height : 600,
minHeight : 400,
minWidth : 550,
hidden : false,
shadow : false,
maximizable : true,
collapsible: true,
title : 'Highchart example',
renderTo : Ext.getBody(),
layout : 'fit',
items : [{
xtype : 'highchart',
id : 'chart',
defaultSerieType : 'spline',
series : [{
dataIndex : 'yesterday',
name : 'Yesterday',
visible : true
}, {
dataIndex : 'today',
name : 'Today',
visible : true
}],
store : chartStore,
xField : 'time',
chartConfig : {
chart : {
type: 'spline',
marginRight : 130,
marginBottom : 120,
zoomType : 'x',
animation : {
duration : 1500,
easing : 'swing'
}
},
title : {
text : 'Standalone Highcharts for ExtJs 4 example',
x : -20 //center
},
subtitle : {
text : 'Random value',
x : -20
},
xAxis : [{
title : {
text : 'Time',
margin : 20
},
labels : {
rotation : 270,
y : 35
}
}],
yAxis : {
title : {
text : 'Value'
},
plotLines : [{
value : 0,
width : 1,
color : '#808080'
}]
},
plotOptions : {
series : {
animation : {
duration : 3000,
easing : 'swing'
}
}
},
legend : {
layout : 'vertical',
align : 'right',
verticalAlign : 'top',
x : -10,
y : 100,
borderWidth : 0
}
}
}]
});
win.show();
}
</code></pre>
<p>My problem is that the above function shows an empty window, while the console says :
<code>Uncaught ReferenceError: Highcharts is not defined</code> in the file <code>highcharts.js</code> on the function <code>draw</code>.</p>
<p>What am I doing wrong? I'm using Extjs 4.1 with the latest HighChart (taken from github).</p>
<p>My index.html : </p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="../extjs/resources/css/ext-all.css">
<link rel="stylesheet" type="text/css" href="app/view/combo_release.css">
<script type="text/javascript" src="../extjs/ext-all.js"></script>
<script type="text/javascript" src="app/app.js"></script>
<script type="text/javascript" src="Chart/ux/highcharts.js"></script>
</head>
<body>
</body>
</html>
</code></pre>
| 0 | 2,504 |
how to display an error message in an array
|
<p>i have this code:</p>
<pre><code>$allowed_extension = array('jpg', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
$errors = array();
$output = array();
if(!empty($_FILES['image']['tmp_name'])){
foreach($_FILES['image']['name'] as $key => $array_value){
if(!in_array(pathinfo($_FILES['image']['name'][$key], PATHINFO_EXTENSION), $allowed_extension)){
die("Die!");
}
}
foreach($_FILES['image']['name'] as $key => $array_value){
$file_name = $_FILES['image']['name'][$key];
$file_size = $_FILES['image']['size'][$key];
$file_tmp = $_FILES['image']['tmp_name'][$key];
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);
if (!in_array($file_extension, $allowed_extension)){
$errors[$file_name][] = "format $file_extension in image $file_name is not accepted";
continue;
}
if ($file_size > 2097152){
$errors[$file_name][] = "maxsize of 2MB on $file_name has reached";
}
if (count($errors) == 0){
$dir = "a/b/c";
if (is_dir($dir)){
mkdir("a/b/c/tmp_images", 0755);
}else{
mkdir("a/b/c", 0755);
mkdir("a/b/c/tmp_images", 0755);
}
$path = "a/b/c/tmp_images";
$prifix = basename($file_name, "." . $file_extension);
//var_dump ($prifix);
$uploadfile = $path . "/" . $file_name;
$x = 0;
while (file_exists($uploadfile)){
$x ++;
$uploadfile = "{$path}/{$prifix}-{$x}.{$file_extension}";
}
if (move_uploaded_file($file_tmp, $uploadfile)){
$file_name = basename($uploadfile);
$output [$file_name] = "OK";
}else{
$output[$file_name] = "Failure while Uploading!";
$errors[$file_name][] = "Failure: Can't move uploaded pictures!";
}//else...
}//if(count($errors))...
}//foreach($_FILES['image']['name']...
}//if(!empty($_FILES['image']['tmp_name'])...
</code></pre>
<p>and my problem is, that i dont know how to display the error messages that should be shown, when the array</p>
<pre><code>$errors
</code></pre>
<p>is given. up to now, it just will be displayed:</p>
<pre><code>array
</code></pre>
<p>instead of:</p>
<pre><code>maxsize of 2MB on abc.jpg has reached
</code></pre>
<p>in the html i have this code:</p>
<pre><code><?php if(isset($errors)):?>
<div class="form-error-message" id="signup-error-message" style="display": none;">
<div class="arrow-wrapper">
<div class="border-wrapper">
<?php foreach($errors as $error):?>
<p class="layer-content">
<?php echo $error;?>
</p>
<?php endforeach;?>
</div>
</div>
</div>
</code></pre>
<p>if there is someone who could be that friendly and help me out i really would appreciate. thanks a lot.</p>
| 0 | 1,565 |
Inserting JSON into MySQL using Python
|
<p>I have a JSON object in Python. I am Using Python DB-API and SimpleJson. I am trying to insert the json into a MySQL table.</p>
<p>At moment am getting errors and I believe it is due to the single quotes '' in the JSON Objects. </p>
<p>How can I insert my JSON Object into MySQL using Python?</p>
<p>Here is the error message I get:</p>
<pre><code>error: uncaptured python exception, closing channel
<twitstream.twitasync.TwitterStreamPOST connected at
0x7ff68f91d7e8> (<class '_mysql_exceptions.ProgrammingError'>:
(1064, "You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for
the right syntax to use near ''favorited': '0',
'in_reply_to_user_id': '52063869', 'contributors':
'NULL', 'tr' at line 1")
[/usr/lib/python2.5/asyncore.py|read|68]
[/usr/lib/python2.5/asyncore.py|handle_read_event|390]
[/usr/lib/python2.5/asynchat.py|handle_read|137]
[/usr/lib/python2.5/site-packages/twitstream-0.1-py2.5.egg/
twitstream/twitasync.py|found_terminator|55] [twitter.py|callback|26]
[build/bdist.linux-x86_64/egg/MySQLdb/cursors.py|execute|166]
[build/bdist.linux-x86_64/egg/MySQLdb/connections.py|defaulterrorhandler|35])
</code></pre>
<p>Another error for reference</p>
<pre><code>error: uncaptured python exception, closing channel
<twitstream.twitasync.TwitterStreamPOST connected at
0x7feb9d52b7e8> (<class '_mysql_exceptions.ProgrammingError'>:
(1064, "You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right
syntax to use near 'RT @tweetmeme The Best BlackBerry Pearl
Cell Phone Covers http://bit.ly/9WtwUO''' at line 1")
[/usr/lib/python2.5/asyncore.py|read|68]
[/usr/lib/python2.5/asyncore.py|handle_read_event|390]
[/usr/lib/python2.5/asynchat.py|handle_read|137]
[/usr/lib/python2.5/site-packages/twitstream-0.1-
py2.5.egg/twitstream/twitasync.py|found_terminator|55]
[twitter.py|callback|28] [build/bdist.linux-
x86_64/egg/MySQLdb/cursors.py|execute|166] [build/bdist.linux-
x86_64/egg/MySQLdb/connections.py|defaulterrorhandler|35])
</code></pre>
<p>Here is a link to the code that I am using <a href="http://pastebin.com/q5QSfYLa" rel="noreferrer">http://pastebin.com/q5QSfYLa</a></p>
<pre><code>#!/usr/bin/env python
try:
import json as simplejson
except ImportError:
import simplejson
import twitstream
import MySQLdb
USER = ''
PASS = ''
USAGE = """%prog"""
conn = MySQLdb.connect(host = "",
user = "",
passwd = "",
db = "")
# Define a function/callable to be called on every status:
def callback(status):
twitdb = conn.cursor ()
twitdb.execute ("INSERT INTO tweets_unprocessed (text, created_at, twitter_id, user_id, user_screen_name, json) VALUES (%s,%s,%s,%s,%s,%s)",(status.get('text'), status.get('created_at'), status.get('id'), status.get('user', {}).get('id'), status.get('user', {}).get('screen_name'), status))
# print status
#print "%s:\t%s\n" % (status.get('user', {}).get('screen_name'), status.get('text'))
if __name__ == '__main__':
# Call a specific API method from the twitstream module:
# stream = twitstream.spritzer(USER, PASS, callback)
twitstream.parser.usage = USAGE
(options, args) = twitstream.parser.parse_args()
if len(args) < 1:
args = ['Blackberry']
stream = twitstream.track(USER, PASS, callback, args, options.debug, engine=options.engine)
# Loop forever on the streaming call:
stream.run()
</code></pre>
| 0 | 1,409 |
UITableView inside UITableViewCell with dynamic height
|
<p>I need to put UITableView inside UITableViewCell with auto-layout because second table has different number of rows and one row can have different height.<br>
This is my ViewController</p>
<pre><code>class ViewController: UIViewController {
let tableView = UITableView()
let cellId = "firstTableCellId"
override func viewDidLoad() {
super.viewDidLoad()
setupView()
tableView.reloadData()
view.backgroundColor = UIColor.gray
}
func setupView() {
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.register(NextTable.self, forCellReuseIdentifier: cellId)
tableView.backgroundColor = UIColor.green
tableView.separatorStyle = .singleLine
view.addSubview(tableView)
view.addConstraintsWithFormat("V:|-60-[v0]-5-|", views: tableView)
view.addConstraintsWithFormat("H:|-8-[v0]-8-|", views: tableView)
}
}
extension ViewController: UITableViewDelegate {
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! NextTable
cell.layoutIfNeeded()
return cell
}
}
</code></pre>
<p>And NextTable which is the cell in first table</p>
<pre><code>class NextTable: UITableViewCell {
var myTableView: UITableView!
let cellId = "nextTableCellId"
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor.brown
setupView()
myTableView.reloadData()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
let label: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.text = "Next table:"
label.textColor = UIColor.black
label.sizeToFit()
label.backgroundColor = UIColor.cyan
return label
}()
func setupView() {
myTableView = UITableView()
myTableView.delegate = self
myTableView.dataSource = self
myTableView.separatorStyle = .singleLineEtched
myTableView.backgroundColor = UIColor.blue
myTableView.register(TableCell.self, forCellReuseIdentifier: cellId)
myTableView.isScrollEnabled = false
addSubview(myTableView)
addSubview(label)
addConstraintsWithFormat("H:|-30-[v0]-30-|", views: myTableView)
addConstraintsWithFormat("H:|-30-[v0]-30-|", views: label)
addConstraint(NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 15))
addConstraint(NSLayoutConstraint(item: myTableView, attribute: .top, relatedBy: .equal, toItem: label, attribute: .bottom, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: myTableView, attribute: .top, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: myTableView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: -15))
}
}
extension NextTable: UITableViewDelegate {
}
extension NextTable: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! TableCell
cell.layoutIfNeeded()
return cell
}
}
</code></pre>
<p>And cell in second table</p>
<pre><code>class TableCell: UITableViewCell {
let label: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.text = "Some text"
label.textColor = UIColor.black
label.sizeToFit()
label.backgroundColor = UIColor.red
return label
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor.yellow
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView(){
addSubview(label)
addConstraintsWithFormat("V:|-8-[v0]-8-|", views: label)
addConstraintsWithFormat("H:|-5-[v0]-5-|", views: label)
}
}
</code></pre>
<p>This is the effect of my code
<img src="https://i.stack.imgur.com/NFaO7.png" alt="Program result">
<br>
There is no second table so I create new class and use it in cell as new table view</p>
<pre><code>class InnerTableView: UITableView {
override var intrinsicContentSize: CGSize {
return self.contentSize
}
}
</code></pre>
<p>And now table is show but size is too large
<img src="https://i.stack.imgur.com/o2Wck.png" alt="Result of InnerTableView">
<br>
What can I do to show full second table without empty space at bottom of cell.</p>
| 0 | 2,429 |
unable to download artifact from nexus repo
|
<p>I am using a nexus repo in a linux system which downloads missing artifacts for me in my windows system when i build my project, by using:</p>
<pre><code>mvn install command
</code></pre>
<p>The artifacts are downloaded by my nexus repo from a remote repo which is mapped to the nexus repo.</p>
<p>This connection between the nexus repo set up in linux system and the remote repo used to work earlier and thus I used to get all the required artifacts for my maven build automatically when i used to build my project using maven.</p>
<p>But due to some reasons the nexus repo in linux is not downloading artifacts from the remote repo.I want this connection to happen so that i could get the required artifact say, tomcat-catalina-7.0.16.jar,downloaded from the remote repo.</p>
<p>I am new to nexus..so may be I would not have been able to explain my problem properly or would have been technically unsound in my question.But I eagerly want to solve my problem.So please if any one could help, please do.</p>
<p>hi, i checked nexus.log and found the following exception while mvn install command was running and when nexus was trying to download the missing tomcat-catalina-7.0.16.jar artifact from the remote repo:</p>
<p>2012-01-18 11:58:35 ERROR [http-8090-23 ] - o.s.n.p.m.m.M2Repos~ - Got Storage Exception while storing remote artifact, will attempt next mirror, cause: org.sonatype.nexus.proxy.RemoteStorageException: The method execution returned result code 407. [repositoryId="central", requestPath="/org/apache/tomcat/tomcat-catalina/7.0.16/tomcat-catalina-7.0.16.jar.sha1", remoteUrl="http://repo.ibsplc.com/artifactory/repo/org/apache/tomcat/tomcat-catalina/7.0.16/tomcat-catalina-7.0.16.jar.sha1"]</p>
<p>2012-01-18 11:58:35 ERROR [http-8090-23 ] - o.s.n.r.ContentPlex~ - Got exception during processing request "GET <a href="http://192.168.4.8:8090/nexus/content/repositories/central/org/apache/tomcat/tomcat-catalina/7.0.16/tomcat-catalina-7.0.16.jar.sha1" rel="nofollow">http://192.168.4.8:8090/nexus/content/repositories/central/org/apache/tomcat/tomcat-catalina/7.0.16/tomcat-catalina-7.0.16.jar.sha1</a>":
org.apache.lucene.store.AlreadyClosedException: this IndexWriter is closed</p>
<p>2012-01-18 11:58:35 ERROR [http-8090-23 ] - o.s.n.p.m.m.M2Repos~ - Got Storage Exception while storing remote artifact, will attempt next mirror, cause: org.sonatype.nexus.proxy.RemoteStorageException: The method execution returned result code 407. [repositoryId="central", requestPath="/org/apache/tomcat/tomcat-catalina/7.0.16/tomcat-catalina-7.0.16.jar.sha1", remoteUrl="http://repo.ibsplc.com/artifactory/repo/org/apache/tomcat/tomcat-catalina/7.0.16/tomcat-catalina-7.0.16.jar.sha1"]</p>
<p>2012-01-18 11:58:35 ERROR [http-8090-23 ] - o.s.n.r.ContentPlex~ - Got exception during processing request "GET <a href="http://192.168.4.8:8090/nexus/content/repositories/central/org/apache/tomcat/tomcat-catalina/7.0.16/tomcat-catalina-7.0.16.jar.sha1" rel="nofollow">http://192.168.4.8:8090/nexus/content/repositories/central/org/apache/tomcat/tomcat-catalina/7.0.16/tomcat-catalina-7.0.16.jar.sha1</a>":
org.apache.lucene.store.AlreadyClosedException: this IndexWriter is closed</p>
<p>2012-01-18 11:58:25 INFO [http-8090-23 ] - o.a.c.h.a.AuthChall~ - Basic authentication scheme selected</p>
<p>2012-01-18 11:58:25 INFO [http-8090-23 ] - o.a.c.h.HttpMethodD~ - Failure authenticating with BASIC 'Squid proxy-caching web server'@192.168.0.46:80</p>
<p>2012-01-18 11:58:25 ERROR [http-8090-23 ] - o.s.n.p.m.m.M2Repos~ - Got Storage Exception while storing remote artifact, will attempt next mirror, cause: org.sonatype.nexus.proxy.RemoteStorageException: The method execution returned result code 407. [repositoryId="central", requestPath="/org/apache/tomcat/tomcat-catalina/7.0.16/tomcat-catalina-7.0.16.pom", remoteUrl="http://repo.ibsplc.com/artifactory/repo/org/apache/tomcat/tomcat-catalina/7.0.16/tomcat-catalina-7.0.16.pom"]</p>
<p>If anyone can find a solution.please do help</p>
| 0 | 1,511 |
How to merge multiple datatables (every datatable return one row) in one row
|
<p>I have multiple data tables : i want to merge them (My <strong>P.K : emp_num</strong>)</p>
<pre><code>var tblEmp_data = new DataTable();//one row
var tblEmp_time = new DataTable();//one row
var tbl_emp_mission = new DataTable();//one row
tblEmp_data = GetEmpInfo(empNum);
tblEmp_time = GetEmpTime(empNum, start_period, end_period);
tbl_emp_mission = GetEmpMission(empNum, start_period, end_period);
tblEmp_data.Merge(tblEmp_time, false, MissingSchemaAction.Add);
tblEmp_data.AcceptChanges();
tblEmp_data.Merge(tbl_emp_mission, false, MissingSchemaAction.Add);
tblEmp_data.AcceptChanges();
</code></pre>
<hr />
<p>Now i get the data on multiple rows rather than one row !
I want the data on one row ? how to do this ?</p>
<hr />
<p>Note: i want all the columns allow null except the primary key so i avoid this exception :</p>
<pre><code>failed to enable constraints. one or more rows contain values violating non-null, unique, or foreign-key constraints
</code></pre>
<hr />
<h1>Edited:</h1>
<p>The third table which cause the problem:</p>
<pre><code>public static DataTable GetEmpMission(int empNum, DateTime start_period, DateTime end_period)
{
using (IfxConnection con = new IfxConnection(ConfigurationManager.ConnectionStrings["tl"].ToString()))
{
DataTable dt = new DataTable();
StringBuilder cmdTxt = new StringBuilder();
cmdTxt.Append(" SELECT COUNT(emp_num) ");
cmdTxt.Append(" FROM hs_mission WHERE emp_num = ? AND from_date BETWEEN ? AND ? ");
using (var myIfxCmd = new IfxCommand(cmdTxt.ToString(), con))
{
myIfxCmd.CommandType = CommandType.Text;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
myIfxCmd.Parameters.Add("emp_num", IfxType.SmallInt);
myIfxCmd.Parameters.Add("start_period", IfxType.Date);
myIfxCmd.Parameters.Add("end_period", IfxType.Date);
myIfxCmd.Parameters[0].Value = ((object)empNum) ?? DBNull.Value;
myIfxCmd.Parameters[1].Value = ((object)start_period.Date) ?? DBNull.Value;
myIfxCmd.Parameters[2].Value = ((object)end_period.Date) ?? DBNull.Value;
using (IfxDataReader dr = myIfxCmd.ExecuteReader())
{
dt.Load(dr);
dt.Columns.Add("emp_num", typeof(Int32));
dt.Rows[0]["emp_num"] = empNum;
dt.AcceptChanges();
}
}
con.Close();
con.Dispose();
return dt;
}
}
</code></pre>
<hr />
<p>Return data like this :</p>
<pre><code>column1 emp_num
0 6762
</code></pre>
<p>and throw exception :</p>
<pre><code>failed to enable constraints. one or more rows contain values violating non-null, unique, or foreign-key constraints
</code></pre>
| 0 | 1,557 |
Using font-awesome in python django application
|
<p>I'm trying to load a local copy of font awesome icons in my python django app.</p>
<p>My template base.html contains:</p>
<pre><code>{% load static %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'appointments/css/all.css' %}" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
<title>{% block title %}Hello, world!{% endblock %}</title>
</head>
</code></pre>
<p>as adapted from <a href="https://docs.djangoproject.com/en/2.0/howto/static-files/" rel="noreferrer">https://docs.djangoproject.com/en/2.0/howto/static-files/</a></p>
<p>The directory structure of my app is:</p>
<pre><code>joel@hp:~/myappointments$ tree
.
βββ appointments
βΒ Β βββ admin.py
βΒ Β βββ apps.py
βΒ Β βββ __init__.py
βΒ Β βββ migrations
βΒ Β βΒ Β βββ __init__.py
βΒ Β βββ models.py
βΒ Β βββ static
βΒ Β βΒ Β βββ appointments
βΒ Β βΒ Β βββ css
βΒ Β βΒ Β βΒ Β βββ all.css
βΒ Β βΒ Β βββ webfonts
βΒ Β βΒ Β βββ fa-brands-400.eot
βΒ Β βΒ Β βββ fa-brands-400.svg
βΒ Β βΒ Β βββ fa-brands-400.ttf
βΒ Β βΒ Β βββ fa-brands-400.woff
βΒ Β βΒ Β βββ fa-brands-400.woff2
βΒ Β βΒ Β βββ fa-regular-400.eot
βΒ Β βΒ Β βββ fa-regular-400.svg
βΒ Β βΒ Β βββ fa-regular-400.ttf
βΒ Β βΒ Β βββ fa-regular-400.woff
βΒ Β βΒ Β βββ fa-regular-400.woff2
βΒ Β βΒ Β βββ fa-solid-900.eot
βΒ Β βΒ Β βββ fa-solid-900.svg
βΒ Β βΒ Β βββ fa-solid-900.ttf
βΒ Β βΒ Β βββ fa-solid-900.woff
βΒ Β βΒ Β βββ fa-solid-900.woff2
βΒ Β βββ templates
βΒ Β βΒ Β βββ appointments
βΒ Β βΒ Β βββ base.html
βΒ Β βΒ Β βββ createappointment.html
βΒ Β βΒ Β βββ doctor.html
βΒ Β βΒ Β βββ doctors.html
βΒ Β βΒ Β βββ home.html
βΒ Β βΒ Β βββ index.html
βΒ Β βΒ Β βββ navbar.html
βΒ Β βΒ Β βββ patient.html
βΒ Β βΒ Β βββ patients.html
βΒ Β βββ tests.py
βΒ Β βββ urls.py
βΒ Β βββ using shell.txt
βΒ Β βββ views.py
βββ appointments.ipynb
βββ db.sqlite3
βββ manage.py
βββ myappointments
βΒ Β βββ __init__.py
βΒ Β βββ settings.py
βΒ Β βββ urls.py
βΒ Β βββ wsgi.py
</code></pre>
<p>However these icons are not being served. It works if I use the following:</p>
<pre><code><link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
</code></pre>
| 0 | 1,408 |
Core Data nested managed object contexts and frequent deadlocks / freezes
|
<p><strong>I have a problem that is almost identical to the problem described by this person here, but it hasn't get answered:</strong></p>
<p><a href="http://www.cocoabuilder.com/archive/cocoa/312683-core-data-nested-managed-object-contexts-and-frequent-deadlocks.html#312683" rel="noreferrer">http://www.cocoabuilder.com/archive/cocoa/312683-core-data-nested-managed-object-contexts-and-frequent-deadlocks.html#312683</a></p>
<p><strong>Here is the problem:</strong></p>
<p>I have a parent MOC setup with NSPrivateQueueConcurrencyType and a persistent store coordinator set, it has a child MOC setup with NSMainQueueConcurrencyType. The idea being most of the long hard work and saves can be done on the private MOC freeing the main thread from blocking the UI. Unfortunately I seem to be running into a couple of situations that cause deadlocks.</p>
<p>If the child MOC (on the main thread) is performing a fetch with NSFetchedResultsController the parent context is sent an -executeFetchRequest: it can create a deadlock. Both operations are done within the context of a performBlock: for their respective MOCs although the docs seem to indicate that using a main thread concurrency type MOC on the main thread without performBlock: is fine.</p>
<p>It appears that the private queue is waiting on the PSCs lock which the child context on the main thread has already locked. It appears that the child context (while holding the PSCs lock) is trying to dispatch_sync to the parent context and thus they are both waiting for each other.</p>
<p>Is PriveQueue -> MainQueue a supported configuration? It seems most people still have the parent context on the main thread.</p>
<p>The main thread looks like this:</p>
<blockquote>
<pre><code>> #0 0x960f6c5e in semaphore_wait_trap ()
> #1 0x04956bb5 in _dispatch_thread_semaphore_wait ()
> #2 0x04955c8f in _dispatch_barrier_sync_f_slow ()
> #3 0x04955dea in dispatch_barrier_sync_f ()
> #4 0x01797de5 in _perform ()
> #5 0x01798547 in -[NSManagedObjectContext(_NestedContextSupport) newValuesForObjectWithID:withContext:error:] ()
> #6 0x0176416b in _PFFaultHandlerLookupRow ()
> #7 0x01763f97 in -[NSFaultHandler fulfillFault:withContext:forIndex:] ()
> #8 0x01763b75 in _PF_FulfillDeferredFault ()
> #9 0x017639f2 in _sharedIMPL_pvfk_core ()
> #10 0x017681a0 in _pvfk_11 ()
> #11 0x0001b322 in -[FBUser sectionName] at /Users/mlink/Code/x/x/FBUser.m:62
> #12 0x011a8813 in _NSGetUsingKeyValueGetter ()
> #13 0x017a0652 in -[NSManagedObject valueForKey:] ()
> #14 0x011ab8d5 in -[NSObject(NSKeyValueCoding) valueForKeyPath:] ()
> #15 0x01851f72 in -[NSFetchedResultsController(PrivateMethods) _sectionNameForObject:] ()
> #16 0x01853af6 in -[NSFetchedResultsController(PrivateMethods) _computeSectionInfo:error:] ()
> #17 0x01850ea6 in -[NSFetchedResultsController performFetch:] ()
> #18 0x0003a4fc in __62-[SYFriendsTableViewController updateFetchedResultsController]_block_invoke_0 ()
> #19 0x01797af3 in developerSubmittedBlockToNSManagedObjectContextPerform ()
> #20 0x049554f0 in _dispatch_main_queue_callback_4CF ()
> #21 0x01b3e833 in __CFRunLoopRun ()
> #22 0x01b3ddb4 in CFRunLoopRunSpecific ()
> #23 0x01b3dccb in CFRunLoopRunInMode ()
> #24 0x023d6879 in GSEventRunModal ()
> #25 0x023d693e in GSEventRun ()
> #26 0x0089aa9b in UIApplicationMain ()
> #27 0x00002656 in main at /Users/mlink/Code/x/x/main.mm:16
</code></pre>
</blockquote>
<p>the private queue stack looks like this:</p>
<pre><code>#0 0x960f8876 in __psynch_mutexwait ()
#1 0x97e9e6af in pthread_mutex_lock ()
#2 0x0172ec22 in -[_PFLock lock] ()
#3 0x0172ebfa in -[NSPersistentStoreCoordinator lock] ()
#4 0x01746a8c in -[NSManagedObjectContext(_NSInternalAdditions) lockObjectStore] ()
#5 0x01745030 in -[NSManagedObjectContext executeFetchRequest:error:] ()
#6 0x0009d49f in -[NSManagedObjectContext(Additions) executeFetchRequest:] at /Users/mlink/Code/objc/C/C/NSManagedObjectContext+Additions.m:44
#7 0x0002177f in +[FBUser usersForFbids:inManagedObjectContext:] at /Users/mlink/Code/x/x/FBUser.m:435
#8 0x00021fc0 in __77+[FBUser updateUserFromGraphValues:inManagedObjectContext:completionHandler:]_block_invoke_0 at /Users/mlink/Code/x/x/FBUser.m:461
#9 0x0180f9f3 in developerSubmittedBlockToNSManagedObjectContextPerform_privateasync ()
#10 0x04954ecf in _dispatch_queue_drain ()
#11 0x04954d28 in _dispatch_queue_invoke ()
#12 0x049544af in _dispatch_worker_thread2 ()
#13 0x97ea1b24 in _pthread_wqthread ()
#14 0x97ea36fe in start_wqthread ()
</code></pre>
<p><strong>He also writes this:</strong></p>
<p>I'm starting to think the problem is with NSFetchedResultsController which is always stuck at performFetch: when these deadlocks occur. Most of the time it will be stuck trying to fault in an object as a result of asking for it's section name. As a test I tried to reproduce what the FRC does and performed the executeFetchRequest: and then iterated through the results asking each object for it's section name. And this doesn't cause a deadlock. If I leave the FRC to do performFetch: after I do my test it will still deadlock there. I'm 99% sure that the FRC has a synchronization problem with nested contexts.</p>
<p><strong>Question: Does anybody know why this problem occurs? Do you know how to solve it? Is this a bug?</strong></p>
| 0 | 1,994 |
How do I get didReadData within GCDAsyncSocket execute within the current RunLoop?
|
<p>I'm trying to get a simple example working with GCDAsyncSocket, and am discovering that I'm missing certain bits of understanding and hope you fine people can help explain this.</p>
<p>I've setup the GCDAsyncSocket stuff below:</p>
<pre><code>dispatch_queue_t mainQueue = dispatch_get_main_queue();
asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:mainQueue];
NSString *host = @"192.168.169.132";
uint16_t port = 2112;
DDLogInfo(@"Connecting to \"%@\" on port %hu...", host, port);
self.viewController.label.text = @"Connecting...";
NSError *error = nil;
if (![asyncSocket connectToHost:host onPort:port withTimeout:5.0 error:&error])
{
DDLogError(@"Error connecting: %@", error);
self.viewController.label.text = @"Oops";
}
else
{
DDLogVerbose(@"Connecting...");
}
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
DDLogInfo(@"socket:%p didConnectToHost:%@ port:%hu", sock, host, port);
self.viewController.label.text = @"Connected";
// We're just going to send a test string to the server.
NSString *myStr = @"testing...123...\r\n";
NSData *myData = [myStr dataUsingEncoding:NSUTF8StringEncoding];
[asyncSocket writeData:myData withTimeout:5.0 tag:0];
}
</code></pre>
<p>And can see my socket test server app receive the string </p>
<blockquote>
<p>"testing...123...\r\n"</p>
</blockquote>
<p>But when I then have my socket test server send a string back, I naively expected the <strong><em>didReadData</em></strong> delegate to execute</p>
<pre><code>- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
</code></pre>
<p>Yet the cold hard reality forced me learn that until I call</p>
<pre><code>[asyncSocket readDataWithTimeout:5.0 tag:0];
</code></pre>
<p>... the <strong><em>didReadData</em></strong> delegate will not get called.</p>
<p>OK, that's fine. I get it.</p>
<p>Reading up on <a href="http://code.google.com/p/cocoaasyncsocket/wiki/Reference_AsyncSocket#RunLoop_Configuration" rel="noreferrer">the documentation</a> some more it clearly states that </p>
<blockquote>
<p>AsyncSocket is a RunLoop based TCP socket library.</p>
</blockquote>
<p>So now I'm looking at this <strong><em>RunLoop</em></strong> thing, which in my view is like the <a href="http://en.wikipedia.org/wiki/Message_loop_in_Microsoft_Windows" rel="noreferrer">Message loop in Microsoft Windows</a>. Being that iOS is an event/msg driven architecture (just like Win32), then the default main thread I'm currently in obviously has it's own msg loop to handle events.</p>
<p>My confusion is now having iOS RunLoop seem like some separate entity to have to work with in getting GCDAsyncSocket to work properly.</p>
<p>When it states that its default set of run loop mode is NSDefaultRunLoopMode, which is in the main thread.</p>
<p>Confused yet?</p>
<p>So under Win32 my comm event handling code would look like this:</p>
<pre><code>while( sCOMport.hCOMport != INVALID_HANDLE_VALUE ) // ...while the COM port is open...
{
// Wait for an event to occur on the port.
WaitCommEvent( sCOMport.hCOMport, &dwCommStatus, NULL );
</code></pre>
<p>It would of course be in its own thread (haven't gotten there yet using GCDAsyncSocket), but that would be its own "RunLoop" in a way.</p>
<p>How do I do the same using <strong>GCDAsyncSocket</strong> so that I'm not stuck in some polling loop filling the queue with <strong>[asyncSocket readDataWithTimeout]</strong> calls?</p>
<p>I feel we need better examples in using this library.</p>
| 0 | 1,204 |
jQuery mobile data-rel="back" link causing wrong events to be fired
|
<p>Have a look at the <a href="http://dl.dropbox.com/u/16705233/data-rel-back.html" rel="nofollow">test-case</a></p>
<p>When you open the link, <code>pagebeforeshow</code> for <em>page 1</em> is fired. When you click the link to go to <em>page 2</em>, <code>pagebeforeshow</code> for <em>page 2</em> is fired. So far, so good.</p>
<p>If you then use the left button (<code>data-rel="back"</code>) to go back, excess events are fired. Using the right button instead (direct link to <em>page 1</em>) does what I'd expect, namely, only <code>pagebeforeshow</code> for <em>page 1</em> gets fired.</p>
<p><code>pagebeforeshow</code> can also be replaced with <code>pageshow</code>, doesn't matter. What's happening here?</p>
<p>(Tested in up-2-date Chrome)</p>
<p>Source for reference:</p>
<pre><code><html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.js"></script>
<script>
$('#test1').live('pagebeforeshow', function() {
console.log("=== pagebeforeshow for #test1");
});
$('#test2').live('pagebeforeshow', function() {
console.log("=== pagebeforeshow for #test2");
});
</script>
</head>
<body>
<div data-role="page" id="test1">
<div data-role="header" align="center">
<p>Page 1.</p>
</div><!-- /header -->
<div data-role="content">
<p><a href="#test2">Go to page 2.</a></p>
</div><!-- /content -->
</div><!-- /page -->
<div data-role="page" id="test2">
<div data-role="header" align="center">
<a href="/" data-icon="back" data-rel="back">Back</a>
<p>Page 2.</p>
<a href="data-rel-back.html" data-icon="back">Go directly to page 1</a>
</div><!-- /header -->
<div data-role="content">
<p>
Try the two buttons and have a look at the console.<br>
Using the left button (data-rel="back") triggers "too many" events.<br>
The right button does what I'd expect.
</p>
</div><!-- /content -->
</div><!-- /page -->
</body>
</html>
</code></pre>
| 0 | 1,207 |
How to wait for subscriptions inside a for loop to complete before proceeding
|
<p>I have a subscription inside of a for loop that fetches JSON data as a series of "category data" from an external source, then filters that data based on the users current location. What I need is to wait for all of the subscriptions to complete, and then and only then can my app proceed. Right now, it does not wait for all of the subscriptions to complete, it only completes a few, and then proceeds, while the other subscriptions continue in the background.</p>
<p>I've tried the following "brute force" method, where i know a certain number of categories will be added to the filtered array, and it works, but I don't know how to make it work for any situation.</p>
<p>Here's my code:</p>
<pre><code>getMultipleCategoryData(categoryIds: string[]) {
for (let i = 0; i < this.waypointIds.length; i++) {
//after user selects their categories, its added to waypointNames, and occurences() gets the # of occurences of each waypoint name
let occurences = this.occurences(this.waypointNames[i], this.waypointNames);
this.categoryApi.getCategoryData(this.waypointIds[i]).toPromise().then(data => {
let filteredLocs = data.locations.filter(loc => this.distanceTo(loc, this.hbLoc) < MAX_RADIUS);
let foundLocs = [];
//fill filteredLocs with first n, n = occurences, entries of data
for (let n = 0; n < occurences; n++) {
if (filteredLocs[n] != undefined) {
foundLocs[n] = filteredLocs[n];
}
}
//find locations closest to hbLoc (users current location), and add them to waypoints array
for (let j = 0; j < foundLocs.length; j++) {
for (let k = 0; k < filteredLocs.length; k++) {
if (this.distanceTo(this.hbLoc, filteredLocs[k]) < this.distanceTo(this.hbLoc, foundLocs[j]) && foundLocs.indexOf(filteredLocs[k]) < 0) {
foundLocs[j] = filteredLocs[k];
}
}
}
if (foundLocs.length > 0 && foundLocs.indexOf(undefined) < 0) {
for (let m = 0; m < foundLocs.length; m++) {
this.waypointLocs.push(foundLocs[m]);
}
}
}).then(() => {
//this hardcoded, brute force method works, but i'd need it to be more elegant and dynamic
if (this.waypointLocs.length >= 5) {
let params = { waypointLocs: this.waypointLocs, hbLoc: this.hbLoc };
this.navCtrl.push(MapPage, params);
}
});
}
}
</code></pre>
<p>And the categoryApi.getCategoryData method:</p>
<pre><code>getCategoryData(categoryId): Observable<any> {
// don't have data yet
return this.http.get(`${this.baseUrl}/category-data/${categoryId}.json`)
.map(response => {
this.categoryData[categoryId] = response.json();
this.currentCategory = this.categoryData[categoryId];
return this.currentCategory;
});
}
</code></pre>
<p>Everything is working fine except waiting for the subscriptions to complete, I'd really like a way to determine when all of the subscriptions have completed. Any help is appreciated!</p>
| 0 | 1,109 |
Why doesn't blur(0) remove all text blur in Webkit/Chrome on retina screens?
|
<p>I recently came across an odd behaviour in Webkit browsers (under OSX at least) which took far longer to resolve than I would like!</p>
<p>Essentially: setting <code>filter: blur(0)</code> (or the vendor-specific <code>-webkit-filter</code>) on an element should mean that no form of blur is applied to the element.</p>
<p>However Webkit still blurs the element when either <code>blur(0)</code> or zeroing with a unit specified (ie: <code>blur(0px)</code>) is assigned to it.</p>
<p>I've knocked together a quick Fiddle here to demonstrate: <a href="http://jsfiddle.net/f9rBE/" rel="nofollow noreferrer">http://jsfiddle.net/f9rBE/</a></p>
<p>This shows three identical divs containing text (no custom fonts):</p>
<pre class="lang-html prettyprint-override"><code><div class="no-blur">
<p><strong>This has absolutely nothing assigned</strong></p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam facilisis orci in quam venenatis, in tempus ipsum sagittis. Suspendisse potenti. Donec ullamcorper lacus vel odio accumsan, vel aliquam libero tempor. Praesent nec libero venenatis, ultrices arcu non, luctus quam. Morbi scelerisque sit amet turpis sit amet tincidunt. Praesent semper erat non purus pretium consequat. Aenean et iaculis turpis. Curabitur diam tellus, consectetur non massa et, commodo venenatis metus.</p>
</div>
</code></pre>
<p>One has no style at all assigned to it whilst the other two have <code>blur(0)</code> and <code>blur(0px)</code>:</p>
<pre class="lang-css prettyprint-override"><code>.no-blur{}
.zero-px-blur{
-webkit-filter: blur(0px);
-moz-filter: blur(0px);
-o-filter: blur(0px);
-ms-filter: blur(0px);
filter: blur(0px);
}
.zero-blur{
-webkit-filter: blur(0);
-moz-filter: blur(0);
-o-filter: blur(0);
-ms-filter: blur(0);
filter: blur(0);
}
</code></pre>
<p>If you take a look in Safari or Chrome, the bottom two are blurred:</p>
<p><img src="https://i.stack.imgur.com/Yh58U.png" alt="enter image description here"></p>
<p>A few things worth noting:</p>
<ul>
<li>This unintentional blurring also occurs in Safari on iOS7 devices (both iPhones and iPads);</li>
<li>It also occurs on Chrome and Safari under OSX;</li>
<li>It doesn't appear to occur under Chrome and Safari on non-retina Apple hardware;</li>
<li>It doesn't happen under FireFox in OSX.</li>
</ul>
<p>Of course, <code>filter: blur</code> isn't supported at all in Firefox just yet so it's hard to tell whether the behaviour I'm seeing is intentional/expected behaviour, or whether this is a bug in Webkit?</p>
<p>I eventually came to the conclusion that using <code>blur(none)</code> instead had the desired effect (ie: removed all blur effects), but I'm confused as to why using zero doesn't have the same effect given that in other filter examples (eg: <code>filter: grayscale</code>) can be reset simply using zero rather than the none keyword.</p>
<p>Why is this?</p>
| 0 | 1,065 |
Remove selected event from the Calendar
|
<p>I am using JQuery Full Calendar along with Spring MVC.</p>
<p>Hello,
I have made a demo like <a href="https://i.stack.imgur.com/zy8Aa.jpg" rel="nofollow noreferrer">that</a>.</p>
<p>Target: I need when the user clicks on an event s/he already inserted,a dialog box appears and gives him/her the capability to either remove that event or cancel.</p>
<p>Issue: Now whenever the user clicks on any day, a dialog appears to allow the user to enter title for that event then user clicks "Ok" to save that event.</p>
<p>Freemarker:
Freemarker:</p>
<pre><code><script type="text/javascript">
var resourceVacation;
function censor(censor) {
return (function() {
var i = 0;
return function(key, value) {
if (i !== 0 && typeof(censor) === 'object' && typeof(value) == 'object' && censor == value)
return '[Circular]';
++i; // so we know we aren't using the original object anymore
return value;
}
})(censor);
}
function doAjax() {
$.each(resourceVacation, function(index) {
var tmpDate = resourceVacation[index].start;
tmpDate.setHours(tmpDate.getHours() - tmpDate.getTimezoneOffset() / 60);
resourceVacation[index].start=tmpDate;
});
// var arrays = [
// {"id":111,"title":"event1","start":"2012-04-15T22:00:00.000Z","url":"http://yahoo.com/"}
// ];
// var objects = {"id":111,"title":"event2","start":"2012-04-16T22:00:00.000Z","url":"http://yahoo2.com/"};
//
// arrays.push(objects);
var test = JSON.stringify(resourceVacation, censor(resourceVacation));
var x = test;
$.ajax(
{
url:"[@spring.url '/vacation/saveResourceVacation'/]",
type: "POST",
data :x ,
dataType: "json",
contentType: "application/json"
});
}
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$.getJSON('[@spring.url '/vacation/loadResourceVacation'/]', function (data) {
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
selectable: true,
selectHelper: true,
select:
function(start, end, allDay) {
var title = prompt('Event Title:');
if (title) {
start.setHours(start.getHours() - start.getTimezoneOffset() / 60);
// var dat=$.fullCalendar.formatDate( start, "yyyy/MM/dd")
var newVacation= {id:133,title:'title',start:start,url: 'title'};
resourceVacation.push(newVacation);
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
eventClick: function(calEvent, jsEvent, view) {
alert('Event: ' + calEvent.title);
alert('start: ' + calEvent.start);
}
editable: true,
events:data
});
resourceVacation = data;
});
});
</script>
</code></pre>
<p>Controller:</p>
<pre><code> @RequestMapping(value = "/vacation/loadResourceVacation", method = RequestMethod.GET)
public
@ResponseBody
String loadResourceVacation(HttpServletResponse response) throws Exception {
//Here I build my vacationFormBean
List<VacationFormBean> vacationFormBeanList= buildVacationFormBean();
// Convert to JSON string.
String json = new Gson().toJson(vacationFormBeanList);
// Write JSON string.
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
return json;
}
@RequestMapping(value = "/vacation/saveResourceVacation", method = RequestMethod.POST)
public
@ResponseBody
void saveResourceVacation(@RequestBody String jsonString, Principal principal) throws Exception {
List<String> resourceVacations = extractVacationDatesFromJsonObject(jsonString);
}
</code></pre>
<p>VacationFormBean:</p>
<pre><code>public class VacationFormBean {
int id; // (With Setter & Getter)
String title; // (With Setter & Getter)
String start; // (With Setter & Getter)
String url; // (With Setter & Getter)
}
</code></pre>
<p>I need something like that :</p>
<p><img src="https://i.stack.imgur.com/zy8Aa.jpg" alt="enter image description here"></p>
<p>======================UPDATE=========================</p>
<p>I have add the click event as a result of domi27 recomendation.
Kindly review the freemarker updates.
I have added a java script method that uses :<a href="http://arshaw.com/fullcalendar/docs/event_data/removeEvents/" rel="nofollow noreferrer">http://arshaw.com/fullcalendar/docs/event_data/removeEvents/</a></p>
<p>The new JS method : </p>
<pre><code> $('#calendar').fullCalendar('removeEvents', 1);
</code></pre>
<p>This method works perfectly with the events that was initially loaded from the controller.
However,whenever I try to use the same method to remove the new events I have just added,Nothing happens.
When I fire the "select event" for the new event I created ,I get for its id"undefined".</p>
<p>As I've mentiond on my freemarker,that are the lines I use to build the new event object that I aappend to the list.</p>
<pre><code>var newVacation = {id:'133',title:'title',start:start,url: 'title'};
resourceVacation.push(newVacation);
</code></pre>
<p>When I debug my script,I observe a difference among the objects loaded from the controller and the new object I created when the user adds a new event.</p>
<p>Here is the old object I got from the controller when I initiated the calendar:
<img src="https://i.stack.imgur.com/8pjIG.jpg" alt="enter image description here"></p>
<p>Here is the new Object I got after I insert the new event:</p>
<p><img src="https://i.stack.imgur.com/PBQL3.jpg" alt="enter image description here"></p>
| 0 | 3,245 |
org.hibernate.QueryException: could not resolve property
|
<p>This is the first time that I use JPA. I write the code with Java and JPA. My code is below.</p>
<pre><code> String queryStr = "SELECT m.title, b.isbn, b.authors";
queryStr += " FROM Book b, Media m";
queryStr += " WHERE m.MediaID = b.MediaID";
queryStr += " AND b.isbn = '" + isbn + "' AND m.title = '%" + title +"%'";
Query query = em.createQuery(queryStr);
</code></pre>
<p>From my code, Class Book extends class Media.</p>
<p>But I got the error which is </p>
<blockquote>
<p>org.hibernate.QueryException: could not resolve property: MediaID of: mediaManagement.Media [SELECT m.title, b.isbn, b.authors FROM mediaManagement.Book b, mediaManagement.Media m WHERE m.MediaID = b.MediaID ]</p>
</blockquote>
<p>This is the Media class.</p>
<pre><code>@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "Media")
@NamedQuery(name = "findAllMedias", query = "select b from Media b")
public class Media {
@Id
@Column(name = "MediaID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int mediaID;
/**
* Getter of the property <tt>mediaID</tt>
*
* @return Returns the mediaID.
* @uml.property name="mediaID"
*/
public int getMediaID() {
return mediaID;
}
/**
* Setter of the property <tt>mediaID</tt>
*
* @param mediaID
* The mediaID to set.
* @uml.property name="mediaID"
*/
public void setMediaID(int mediaID) {
this.mediaID = mediaID;
}
/**
* @uml.property name="title"
*/
@Column(name = "title")
private String title;
/**
* Getter of the property <tt>title</tt>
*
* @return Returns the title.
* @uml.property name="title"
*/
public String getTitle() {
return title;
}
/**
* Setter of the property <tt>title</tt>
*
* @param title
* The title to set.
* @uml.property name="title"
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @uml.property name="editionDate"
*/
private Calendar editionDate;
/**
* Getter of the property <tt>editionDate</tt>
*
* @return Returns the editionDate.
* @uml.property name="editionDate"
*/
public Calendar getEditionDate() {
return editionDate;
}
/**
* Setter of the property <tt>editionDate</tt>
*
* @param editionDate
* The editionDate to set.
* @uml.property name="editionDate"
*/
public void setEditionDate(Calendar editionDate) {
this.editionDate = editionDate;
}
/*
* Two medias are equal if their mediaID is the same
*/
@Override
public boolean equals(Object media) {
if (media == null)
return false;
Media b = (Media) media;
if (b.mediaID == mediaID)
return true;
return false;
}
public Media() {
};
/**
* Creates a media All parameters should be given
*
* @param title
* the title of the media
*
* @param editionDate
* date of the edition of the media
*
* @throws BadParametersException
*/
public Media(String title, Calendar editionDate)
throws BadParametersException {
if ((title == null) || (editionDate == null))
throw new BadParametersException();
this.title = title;
this.editionDate = editionDate;
}
/**
* Returns a description of the media
*/
public String toString() {
return this.title + " " + String.valueOf(this.title);
}
/**
* @uml.property name="copies"
* @uml.associationEnd multiplicity="(0 -1)" inverse="media:copyManagement.Copy"
*/
@OneToMany(mappedBy="mediaRef") protected Set<Copy> copies;
public void addCopy(Copy copy) {
copies.add(copy);
}
/**
* Getter of the property <tt>copies</tt>
* @return Returns the copies.
* @uml.property name="copies"
*/
public Set<Copy> getCopies() {
return copies;
}
/**
* Setter of the property <tt>copies</tt>
* @param editionDate The copies to set.
* @uml.property name="copies"
*/
public void setCopies(Set<Copy> copies) {
this.copies = copies;
}
</code></pre>
<p>And this is Book class.</p>
<pre><code>@Entity
@Table(name = "Book")
@NamedQuery(name = "findAllBooks", query = "select b from Book b")
public class Book extends Media {
/**
* @uml.property name="authors"
*/
@Column(name = "authors")
private ArrayList<String> authors;
/**
* Getter of the property <tt>authors</tt>
*
* @return Returns the authors.
* @uml.property name="authors"
*/
public ArrayList<String> getAuthors() {
return authors;
}
/**
* Setter of the property <tt>authors</tt>
*
* @param authors
* The authors to set.
* @uml.property name="authors"
*/
public void setAuthors(ArrayList<String> authors) {
this.authors = authors;
}
/**
* @uml.property name="isbn"
*/
@Column(name = "isbn")
private String isbn;
/**
* Getter of the property <tt>isbn</tt>
*
* @return Returns the isbn.
* @uml.property name="isbn"
*/
public String getisbn() {
return isbn;
}
/**
* Setter of the property <tt>isbn</tt>
*
* @param isbn
* The isbn to set.
* @uml.property name="isbn"
*/
public void setisbn(String isbn) {
this.isbn = isbn;
}
public Book() {
// TODO Auto-generated constructor stub
}
public Book(String title, Calendar editionDate, ArrayList<String> authors,
String isbn) throws BadParametersException {
super(title, editionDate);
this.authors = authors;
this.isbn = isbn;
// TODO Auto-generated constructor stub
}
}
</code></pre>
<p>Anyone can help?</p>
| 0 | 2,095 |
django.db.utils.OperationalError: (1054, "Unknown column
|
<p>An interesting issue.
Getting Unknown column exception -- Please find the stack trace</p>
<p>I try to get new leads list and responded leads. I merge them. When I merge them there is an exception. </p>
<p>After debugging its found that new_leads method has exclude of two fields collection and delivery . If we make it one exclude all is well . I mean dont check the other, if we include both the filters we have an issue. </p>
<p>I tried using filter/ exclude etc. but it didnt work.</p>
<p>Query Set contains following method </p>
<pre><code> def all_leads_related_to_user(self, user):
""" User new and past leads
Use this queryset for performing lead search.
"""
new_leads = self.new_leads_for_user(user)
responded_leads = self.leads_responded_by_user(user)
all_leads = (new_leads | responded_leads).distinct() <= Issue is here.
return all_leads
def new_leads_for_user(self, user):
....
# User's location filter
if user.sub_region_excluded_list:
sub_region_exclude_list = [10, 12]
qs = qs.exclude( Q(collection_point__sub_region_id__in=sub_region_exclude_list) |
Q(delivery_point__sub_region_id__in=sub_region_exclude_list))
# <== Make it just one exclude it works.
Model
class Suburb(models.Model):
state = models.ForeignKey(State, blank=False)
sub_region = models.ForeignKey(SubRegion, blank=False)
postcode = models.CharField(_('postcode'), blank=False, max_length=10)
name = models.CharField(_('suburb name'), blank=False, max_length=200)
class Load(models.Model):
.....
collection_point = models.ForeignKey(Suburb, related_name='collection_point', on_delete=models.SET_NULL, null=True)
delivery_point = models.ForeignKey(Suburb, related_name='delivery_point', on_delete=models.SET_NULL, null=True)
</code></pre>
<p>Stack Trace:- </p>
<pre><code> >>> Load.objects.all_leads_related_to_user(User.objects.all()[0])
Load.objects.all_leads_related_to_user(User.objects.all()[0])
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/data/fq/venv/lib/python3.4/site-packages/django/db/models/query.py", line 226, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/data/fq/venv/lib/python3.4/site-packages/django/db/models/query.py", line 250, in __iter__
self._fetch_all()
File "/data/fq/venv/lib/python3.4/site-packages/django/db/models/query.py", line 1103, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/data/fq/venv/lib/python3.4/site-packages/django/db/models/query.py", line 53, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
File "/data/fq/venv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 886, in execute_sql
raise original_exception
File "/data/fq/venv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 876, in execute_sql
cursor.execute(sql, params)
File "/data/fq/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/data/fq/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/data/fq/venv/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/data/fq/venv/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/data/fq/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/data/fq/venv/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 101, in execute
return self.cursor.execute(query, args)
File "/data/fq/venv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 250, in execute
self.errorhandler(self, exc, value)
File "/data/fq/venv/lib/python3.4/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler
raise errorvalue
File "/data/fq/venv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 247, in execute
res = self._query(query)
File "/data/fq/venv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 411, in _query
rowcount = self._do_query(q)
File "/data/fq/venv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 374, in _do_query
db.query(q)
File "/data/fq/venv/lib/python3.4/site-packages/MySQLdb/connections.py", line 292, in query
_mysql.connection.query(self, query)
django.db.utils.OperationalError: (1054, "Unknown column 'locations_suburb.sub_region_id' in 'having clause'")
>>>
</code></pre>
<p>I'm using MySqlDB</p>
<h2>Note:-</h2>
<p>All migrations are applied and Db is in right state</p>
<p><strong>Update</strong></p>
<p>Issue is related to MYSQL madating columns to be available in select statements when its creating a Having clause . Refer to -
<a href="https://stackoverflow.com/questions/36105812/unknown-column-in-having-clause">Unknown column in 'having clause'</a>.
Django in this instance is not adding as the column to be selected. hence the error.
I need to some how find a way to add this in the select clause with other params.</p>
| 0 | 2,055 |
List of objects not binding to the model on post back in asp.net mvc 4
|
<p>In my my MVC 4 application, I have a Customer which can have multiple sites and can subscribe to multiple service packages. A short version of my view model looks like below </p>
<pre><code>public class SubscriptionModel
{
public int MemberId { get; set; }
public List<SitePackage> SitePackges { get; set; }
public SubscriptionModel()
{
SitePackges=new List<SitePackage>();
}
}
public class SitePackage
{
public int SiteId { get; set; }
public List<PackageDisplayItem> LstPackageDisplayItems { get; set; }
public SitePackage()
{
LstPackageDisplayItems=new List<PackageDisplayItem>();
}
}
public class PackageDisplayItem
{
public int PackageId { get; set; }
[Display(Name = "Package")]
public string Name { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Start Date")]
public DateTime? StartDate { get; set; }
}
</code></pre>
<p>In my controller I fill in the model and then pass to View Model for rendering</p>
<pre><code> @using (@Html.BeginForm("CalculateCost", "HelpDesk", FormMethod.Post, new { @class = "form", id = "PackageSubscription", name = "PackageSubscription" }))
{
@Html.HiddenFor(x=>x.MemberId)
<table class="table">
@foreach (var site in Model.SitePackges)
{
<input name="SiteId" id="SiteId" type="hidden" value=@site.SiteId.ToString() />
<tr><td class="col-sm-3">@site.SiteId</td></tr>
<tr>
<th class="col-sm-3">
Name
</th>
<th class="col-sm-2">
Start Date
</th>
</tr>
@Html.Partial("_Packages",site.LstPackageDisplayItems)
}
</code></pre>
<p>My partial view is like</p>
<pre><code>@model List<PackageDisplayItem>
@for (int i = 0; i < Model.Count; i++)
{
@Html.HiddenFor(x => x[i].PackageId)
<tr id="@Model[i].PackageId">
<td>
@Html.DisplayFor(x => x[i].Name)
</td>
<td>
@Html.TextBoxFor(x => x[i].StartDate, "{0:d MMM yyyy}", new { @class = "jquery_datepicker form-control", autocomplete = "off" })
</td>
</tr>
}
</code></pre>
<p>Every thing renders fine but on the form post the model binder is not binding <code>SitePackges</code> list and its count is always 0. My controller has the following signatures.</p>
<pre><code>[HttpPost]
public ActionResult CalculateCost(SubscriptionModel subscriptionModel )
{
var receivedModel = subscriptionModel;
}
</code></pre>
<p>Not sure if the model I have designed is the best approach to handle this requirement (The requirement is to show a single site and just below it show the packages and then 2nd site and packages and so on). The controls seems to have unique indexes generated.</p>
<p>Jquery Post</p>
<pre><code>function SubmitForm() {
console.log($("#PackageSubscription").serialize());
$.ajax({
url: '/HelpDesk/CalculateCost',
cache: false,
dataType: 'json',
data: $("#PackageSubscription").serialize(),
type: 'POST',
success: function (data) {
}
});
</code></pre>
<p>}</p>
<p>I will appreciate any help. thanks</p>
| 0 | 1,428 |
Log4net configuration from assembly attribute does not load configuration file
|
<p>I have the following file Log4net.config in my bin directory:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8" ?>
<log4net xmlns="urn:log4net">
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<param name="file" value="MyLogFile.log"/>
<param name="appendToFile" value="false"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date (%logger) [%5level] - %message" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date (%logger) [%5level] - %message" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="FileAppender" />
<appender-ref ref="ConsoleAppender"/>
</root>
<logger name="NHibernate" additivity="false">
<level value="WARN"/>
</logger>
</log4net>
</code></pre>
<p>And the following code in my AssemblyInfo.cs file:</p>
<pre class="lang-cs prettyprint-override"><code>using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyTitle("My Project")]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4net.config", Watch = true)]
</code></pre>
<p>When I run the program, I get the following log4net debug output:</p>
<pre><code>log4net: log4net assembly [log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821]. Loaded from [D:\Data\Projects\Active\Clients\MyProject\src\MyProject.Importer\bin\Debug\log4net.dll]. (.NET Runtime [4.0.30319.1] on Microsoft Windows NT 6.1.7600.0)
log4net: DefaultRepositorySelector: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy]
log4net: DefaultRepositorySelector: Creating repository for assembly [MyCompany.Framework, Version=2.1.72.0, Culture=neutral, PublicKeyToken=null]
log4net: DefaultRepositorySelector: Assembly [MyCompany.Framework, Version=2.1.72.0, Culture=neutral, PublicKeyToken=null] Loaded From [D:\Data\Projects\Active\Clients\MyProject\src\MyProject.Importer\bin\Debug\MyCompany.Framework.dll]
log4net: DefaultRepositorySelector: Assembly [MyCompany.Framework, Version=2.1.72.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.
log4net: DefaultRepositorySelector: Assembly [MyCompany.Framework, Version=2.1.72.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: DefaultRepositorySelector: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy]
The thread 'vshost.RunParkingWindow' (0xd30) has exited with code 0 (0x0).
The thread '<No Name>' (0x15d0) has exited with code 0 (0x0).
log4net: Hierarchy: Shutdown called on Hierarchy [log4net-default-repository]
</code></pre>
<p>Log4net loads, but doesn't seem to be processing my config file. When I comment out the attribute in AssemblyInfo.cs and run the following code during my program initialization, it works as expected:</p>
<pre class="lang-cs prettyprint-override"><code>var log4netConfig = "Log4net.config";
var log4netInfo = new FileInfo(log4netConfig);
log4net.Config.XmlConfigurator.ConfigureAndWatch(log4netInfo);
</code></pre>
<p>What am I doing wrong? I want to load from AssemblyInfo.cs.</p>
| 0 | 1,378 |
Java Web Application Error - Can't understand why it's happening now
|
<p>I am using eclipse and I can build the webapp and deploy it to Jboss4.2.1. It was working previously and I haven't changed anything really extensively to make this error come about. When I go to the webapp thru my browser, I previously have been signing in with a generic username and then I could use my webapp as usual. </p>
<p>Now when I go to the webapp thru the browser, this error occurs repeatedly and will not show anything. Here is the error that I am receiving:</p>
<pre><code>07:55:06,174 INFO [security] User '' attempting login via SiteMinder...
07:55:06,174 INFO [security] User '' attempting login via SiteMinder...
07:55:06,174 ERROR [[jsp]] Servlet.service() for servlet jsp threw exception
java.lang.LinkageError: Class javax/el/ExpressionFactory violates loader constraints
at org.apache.jsp.WEB_002dINF.jsp.layout.header_jsp._jspx_meth_c_005fset_005f0(header_jsp.java:207)
at org.apache.jsp.WEB_002dINF.jsp.layout.header_jsp._jspx_meth_c_005fif_005f0(header_jsp.java:179)
at org.apache.jsp.WEB_002dINF.jsp.layout.header_jsp._jspService(header_jsp.java:82)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:387)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:687)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:590)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:505)
at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:968)
at org.apache.jasper.runtime.PageContextImpl.doInclude(PageContextImpl.java:643)
at org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:637)
at net.sourceforge.stripes.tag.layout.LayoutRenderTag.doEndTag(LayoutRenderTag.java:122)
at org.apache.jsp.WEB_002dINF.jsp.layout.layout_jsp._jspx_meth_stripes_005flayout_002drender_005f0(layout_jsp.java:796)
at org.apache.jsp.WEB_002dINF.jsp.layout.layout_jsp._jspx_meth_stripes_005flayout_002dcomponent_005f2(layout_jsp.java:759)
at org.apache.jsp.WEB_002dINF.jsp.layout.layout_jsp._jspService(layout_jsp.java:200)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:387)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:687)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:590)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:505)
at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:968)
at org.apache.jasper.runtime.PageContextImpl.doInclude(PageContextImpl.java:643)
at org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:637)
at net.sourceforge.stripes.tag.layout.LayoutRenderTag.doEndTag(LayoutRenderTag.java:122)
at org.apache.jsp.view.public_.login_jsp._jspService(login_jsp.java:335)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:387)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at net.sourceforge.stripes.controller.StripesFilter.doFilter(StripesFilter.java:180)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:112)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:265)
at org.acegisecurity.ui.switchuser.SwitchUserProcessingFilter.doFilter(SwitchUserProcessingFilter.java:341)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.intercept.web.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:107)
at org.acegisecurity.intercept.web.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:72)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.ui.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:110)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.ui.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:110)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:125)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.wrapper.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:81)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:229)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:229)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:286)
at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
at org.acegisecurity.util.FilterChainProxy.doFilter(FilterChainProxy.java:149)
at org.acegisecurity.util.FilterToBeanProxy.doFilter(FilterToBeanProxy.java:98)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:179)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:241)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:580)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:595)
</code></pre>
<p>Any help would be greatly appreciated. </p>
| 0 | 3,368 |
Stop form refreshing page on submit
|
<p>How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?</p>
<p>The validation is setup working fine, all fields go red but then the page is immediately refreshed. My knowledge of JS is relatively basic.</p>
<p>In particular I think the <code>processForm()</code> function at the bottom is 'bad'.</p>
<p><strong>HTML</strong></p>
<pre><code><form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" />
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" />
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" />
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
<button id="form_send" tabindex="5" class="btn" type="submit" onclick="return processForm()">Send</button>
<div id="form_validation">
<span class="form_captcha_code"></span>
<input id="form_captcha" class="boxsize" type="text" name="form_captcha" placeholder="Enter code" tabindex="4" value="" />
</div>
<div class="clearfix"></div>
</form>
</code></pre>
<p><strong>JS</strong></p>
<pre><code>$(document).ready(function() {
// Add active class to inputs
$("#prospects_form .boxsize").focus(function() { $(this).addClass("hasText"); });
$("#form_validation .boxsize").focus(function() { $(this).parent().addClass("hasText"); });
// Remove active class from inputs (if empty)
$("#prospects_form .boxsize").blur(function() { if ( this.value === "") { $(this).removeClass("hasText"); } });
$("#form_validation .boxsize").blur(function() { if ( this.value === "") { $(this).parent().removeClass("hasText"); } });
///////////////////
// START VALIDATION
$("#prospects_form").ready(function() {
// DEFINE GLOBAL VARIABLES
var valName = $('#form_name'),
valEmail = $("#form_email"),
valEmailFormat = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
valMsg = $('#form_message'),
valCaptcha = $('#form_captcha'),
valCaptchaCode = $('.form_captcha_code');
// Generate captcha
function randomgen() {
var rannumber = "";
// Iterate through 1 to 9, 4 times
for(ranNum=1; ranNum<=4; ranNum++){ rannumber+=Math.floor(Math.random()*10).toString(); }
// Apply captcha to element
valCaptchaCode.html(rannumber);
}
randomgen();
// CAPTCHA VALIDATION
valCaptcha.blur(function() {
function formCaptcha() {
if ( valCaptcha.val() == valCaptchaCode.html() ) {
// Incorrect
valCaptcha.parent().addClass("invalid");
return false;
} else {
// Correct
valCaptcha.parent().removeClass("invalid");
return true;
}
}
formCaptcha();
});
// Remove invalid class from captcha if typing
valCaptcha.keypress(function() {
valCaptcha.parent().removeClass("invalid");
});
// EMAIL VALIDATION (BLUR)
valEmail.blur(function() {
function formEmail() {
if (!valEmailFormat.test(valEmail.val()) && valEmail.val() !== "" ) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmail();
});
// Remove invalid class from email if typing
valEmail.keypress(function() {
valEmail.removeClass("invalid");
});
// VALIDATION ON SUBMIT
$('#prospects_form').submit(function() {
console.log('user hit send button');
// EMAIL VALIDATION (SUBMIT)
function formEmailSubmit() {
if (!valEmailFormat.test(valEmail.val())) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmailSubmit();
// Validate captcha
function formCaptchaSubmit() {
if( valCaptcha.val() === valCaptchaCode.html() ) {
// Captcha is correct
} else {
// Captcha is incorrect
valCaptcha.parent().addClass("invalid");
randomgen();
}
}
formCaptchaSubmit();
// If NAME field is empty
function formNameSubmit() {
if ( valName.val() === "" ) {
// Name is empty
valName.addClass("invalid");
} else {
valName.removeClass("invalid");
}
}
formNameSubmit();
// If MESSAGE field is empty
function formMessageSubmit() {
if ( valMsg.val() === "" ) {
// Name is empty
valMsg.addClass("invalid");
} else {
valMsg.removeClass("invalid");
}
}
formMessageSubmit();
// Submit form (if all good)
function processForm() {
if ( formEmailSubmit() && formCaptchaSubmit() && formNameSubmit() && formMessageSubmit() ) {
$("#prospects_form").attr("action", "/clients/oubc/row-for-oubc-send.php");
$("#form_send").attr("type", "submit");
return true;
} else if( !formEmailSubmit() ) {
valEmail.addClass("invalid");
return false;
} else if ( !formCaptchaSubmit() ) {
valCaptcha.parent().addClass("invalid");
return false;
} else if ( !formNameSubmit() ) {
valName.addClass("invalid");
return false;
} else if ( !formMessageSubmit() ) {
valMsg.addClass("invalid");
return false;
} else {
return false;
}
}
});
});
// END VALIDATION
/////////////////
});
</code></pre>
| 0 | 3,080 |
Angular: focusout event not working with div tag
|
<p>I have a div tag which works as select box with multi select feature.</p>
<pre><code><div class="multiselect" id="multiFocus" *ngIf="editMode" (focusout)="disableSelect($event)">
<div class="selectBox">
<div class="multi-select-user">
<div style="width:180px; display:inline-block">
<ng-container *ngFor="let selectedBaseVal of selectedBaseLicences.icdata; let baseVal=index">
<div class="base-selection" (click)="canshowCheckBoxes = !canshowCheckBoxes" *ngIf="(selectedBaseVal.License !== 'Select Base License')&& selectedBaseVal.Checked">
<span style="padding:5px;">{{selectedBaseVal.License}}</span>
<span class="icon-close icon--small icn-float" (click)="selectedBaseVal.Checked = !selectedBaseVal.Checked"></span>
</div>
<div style="padding:6px;" *ngIf="selectedBaseVal.License === 'Select Base License'">
Select Base License
</div>
</ng-container>
</div>
<div (click)="canshowCheckBoxes = !canshowCheckBoxes" class="icon-dropdown icn-float inline-display">
</div>
</div>
</div>
<div class="multi-select-list" *ngIf="canshowCheckBoxes">
<div id="baseCheckboxes" style="display:block; width:200px; border:1px solid #dfdfdf; border-top:none">
<ng-container *ngFor="let base of selectedBaseLicences.icdata">
<div>
<label class="checkbox">
<input type="checkbox" [checked]="base.Checked" name="checkbox1" (change)="base.Checked = !base.Checked">
<span class="checkbox__input"></span>
<span class="checkbox__label">{{base.License}}</span>
</label>
</div>
</ng-container>
</div>
</div>
</code></pre>
<p></p>
<p>It looks like this <a href="https://i.stack.imgur.com/c55k2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c55k2.png" alt="Multiselect"></a>What I'm trying is, when I click outside the div it should get disabled, so I'm trying with focusout event and in disableSelect() method I'm just making a value false. But focusout event is not working. Does div doesn't support focusout? Or is there any other way to disable?</p>
| 0 | 1,279 |
Logcat says - The application may be doing too much work on its main thread and error message says - StringtoReal.invalidReal(string.boolean)line:63
|
<p>Whenever I running my app in emulator,
Logcat says - The application may be doing too much work on its main thread and
error message says - StringtoReal.invalidReal(string.boolean)line:63
here, i am trying to add values of 3 textviews and show their total in another textview using tick on checbox(es)</p>
<pre><code>10-12 17:23:21.074: W/ActivityThread(700):
Application com.suvendu.tutorial.cb is waiting for the debugger on port 8100...
10-12 17:23:21.134: I/System.out(700): Sending WAIT chunk
10-12 17:23:21.143: I/dalvikvm(700): Debugger is active
10-12 17:23:21.334: I/System.out(700): Debugger has connected
10-12 17:23:21.334: I/System.out(700): waiting for debugger to settle...
10-12 17:23:21.545: I/System.out(700): waiting for debugger to settle...
10-12 17:23:21.744: I/System.out(700): waiting for debugger to settle...
10-12 17:23:21.943: I/System.out(700): waiting for debugger to settle...
10-12 17:23:22.155: I/System.out(700): waiting for debugger to settle...
10-12 17:23:22.353: I/System.out(700): waiting for debugger to settle...
10-12 17:23:22.554: I/System.out(700): waiting for debugger to settle...
10-12 17:23:22.754: I/System.out(700): waiting for debugger to settle...
10-12 17:23:22.954: I/System.out(700): waiting for debugger to settle...
10-12 17:23:23.164: I/System.out(700): debugger has settled (1368)
10-12 17:23:25.243: I/Choreographer(700): Skipped 46 frames!
The application may be doing too much work on its main thread.
10-12 17:23:25.533: D/gralloc_goldfish(700): Emulator without GPU emulation detected.
</code></pre>
<p>Activity Code:-</p>
<pre><code>OnClickListener checkBoxListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text_regular_code=(TextView)findViewById(R.id.text_regular);
text_small_code=(TextView)findViewById(R.id.text_small);
text_large_code=(TextView)findViewById(R.id.text_large);
text_check_regular_code=(TextView)findViewById(R.id.text_check_regular);
text_check_small_code=(TextView)findViewById(R.id.text_check_small);
text_check_large_code=(TextView)findViewById(R.id.text_check_large);
text_price_regular_code=(TextView)findViewById(R.id.text_price_regular);
text_price_small_code=(TextView)findViewById(R.id.text_price_small);
text_price_large_code=(TextView)findViewById(R.id.text_price_large);
edit_qty_regular_code=(EditText)findViewById(R.id.edit_qty_regular);
edit_qty_small_code=(EditText)findViewById(R.id.edit_qty_small);
edit_qty_large_code=(EditText)findViewById(R.id.edit_qty_large);
chk_regular_code=(CheckBox)findViewById(R.id.chk_regular);
chk_small_code=(CheckBox)findViewById(R.id.chk_small);
chk_large_code=(CheckBox)findViewById(R.id.chk_large);
checkBoxListener =new OnClickListener() {
public void onClick(View v) {
if(chk_regular_code.isChecked())
{
text_price_regular_code.setText
(text_regular_code.getText().toString());
text_check_regular_code.setText
(chk_regular_code.getText().toString());
}
else {
text_price_regular_code.setText("");
text_check_regular_code.setText("");
edit_qty_regular_code.setText("");
}
if(chk_small_code.isChecked())
{
text_price_small_code.setText
(text_small_code.getText().toString());
text_check_small_code.setText
(chk_small_code.getText().toString());
}
else {
text_price_small_code.setText("");
text_check_small_code.setText("");
edit_qty_small_code.setText("");
}
if(chk_large_code.isChecked())
{
text_price_large_code.setText
(text_large_code.getText().toString());
text_check_large_code.setText
(chk_large_code.getText().toString());
}
else {
text_price_large_code.setText("");
text_check_large_code.setText("");
edit_qty_large_code.setText("");
}
// whenever i use below code getting error "start"
x=Double.parseDouble
(text_price_regular_code.getText().toString());
y=Double.parseDouble
(text_price_small_code.getText().toString());
z=Double.parseDouble
(text_price_large_code.getText().toString());
a=x+y+z;
text_total_code.setText(Double.toString(a));
// whenever i use below code getting error "end"
}
};
chk_regular_code.setOnClickListener(checkBoxListener);
chk_small_code.setOnClickListener(checkBoxListener);
chk_large_code.setOnClickListener(checkBoxListener);
}
</code></pre>
| 0 | 2,278 |
Get the list of items in Venn diagram
|
<p>It is easy to the draw a Venn diagram with the following code:</p>
<pre><code>library(VennDiagram)
set.seed(1) # For reproducibility of results
xx.1 <- list(A = sample(LETTERS, 15), B = sample(LETTERS, 15),
C = sample(LETTERS, 15), D = sample(LETTERS, 15))
venn.diagram(xx.1, filename ="1.tiff", height = 1000, width = 1000)
</code></pre>
<p><img src="https://i.imgur.com/IalHBjs.png" alt="A venn diagram with four sets"></p>
<p>But how do I figure out the items in each field? For example, I would like to know what are the two letters only found in A? </p>
<p><strong>EDIT</strong>:</p>
<p>Here is my solution, it is not perfect but could give all the intersections.</p>
<pre><code>library(reshape)
library(R.utils)
## data
A <- data.frame(names = sample(LETTERS, 15), A = 1)
B <- data.frame(names = sample(LETTERS, 15), B = 1)
C <- data.frame(names = sample(LETTERS, 15), C = 1)
D <- data.frame(names = sample(LETTERS, 15), D = 1)
## a merged data frame.
xx.1 <- list(A = A, B= B, C= C, D = D)
xx.2 <- merge_recurse(xx.1)
## function
ff.vennFourItems <- function(X)
{
## get the items from venn diagram; for four sets, there are 15 fields;
vennItems <- list()
cate.n <- names(X)[2:5]
for (i in 1:15)
{
xx.b <- intToBin(i)
## make it four bits;
if (nchar(xx.b) != 4)
{
xx.b <- paste(paste(rep("0", 4 - nchar(xx.b)), collapse = ""), xx.b, sep ="")
}
xx.b.1 <- unlist(strsplit(xx.b, ""))
xx.1 <- X
if(xx.b.1[1] == "0") { xx.1 <- xx.1[is.na(xx.1[, 2]), ] }
else { xx.1 <- xx.1[!is.na(xx.1[, 2]), ] }
if(xx.b.1[2] == "0") { xx.1 <- xx.1[is.na(xx.1[, 3]), ] }
else { xx.1 <- xx.1[!is.na(xx.1[, 3]), ] }
if(xx.b.1[3] == "0") { xx.1 <- xx.1[is.na(xx.1[, 4]), ] }
else { xx.1 <- xx.1[!is.na(xx.1[, 4]), ] }
if(xx.b.1[4] == "0") { xx.1 <- xx.1[is.na(xx.1[, 5]), ] }
else { xx.1 <- xx.1[!is.na(xx.1[, 5]), ] }
chipC <- paste(paste(cate.n, collapse = "#"), xx.b, sep = "***")
if (dim(xx.1)[1] == 0)
{
xx.2 <- list(genes = dim(xx.1)[1], chipC = chipC, chipCN = i, detailChipS = xx.1, shortL = data.frame(genes = "noInteraction", cl = i, fullCl = chipC))
}
else
{
xx.2 <- list(genes = dim(xx.1)[1], chipC = chipC, chipCN = i, detailChipS = xx.1, shortL = data.frame(genes = as.character(xx.1[, 1]), cl = i, fullCl = chipC))
}
vennItems <- c(vennItems, list(xx.2))
}
vennItems
}
xx.3 <- ff.vennFourItems(xx.2)
str(xx.3)
List of 15
$ :List of 5
..$ genes : int 1
..$ chipC : chr "A#B#C#D***0001"
..$ chipCN : int 1
..$ detailChipS:'data.frame': 1 obs. of 5 variables:
.. ..$ names: Factor w/ 25 levels "A","B","E","F",..: 25
.. ..$ A : num NA
.. ..$ B : num NA
.. ..$ C : num NA
.. ..$ D : num 1
..$ shortL :'data.frame': 1 obs. of 3 variables:
.. ..$ genes : Factor w/ 1 level "Z": 1
.. ..$ cl : int 1
.. ..$ fullCl: Factor w/ 1 level "A#B#C#D***0001": 1
$ :List of 5
..$ genes : int 0
..$ chipC : chr "A#B#C#D***0010"
..$ chipCN : int 2
</code></pre>
| 0 | 1,653 |
How to fix 'SQLRecoverableException: Closed Connection' in Java
|
<p>We are working for an ecommerce built with Hybris framework and currently we have an issue with database connection (I suppose) and no idea on how to solve it. It happens only on production environment and only on servers that are used by ESB (2 servers in a total of 40).</p>
<p>Basically, sometimes (1-3/day), we discover sessions waiting for some idle session (SEL*NET message from client). We can only manually kill the holder in order to free these sessions.</p>
<p>All the servers share the same application code and the main difference between ESB and Frontend servers is in the controllers that are called and in the requests count.</p>
<p>ESB Server: 10 requests per minute
Frontend Server: 300 requests per minute</p>
<p>In the application log I found a lot of Closed Connection errors on these 2 servers and I think that this is related to our problem but actually I don't know why.
In access.log I have this request:</p>
<pre><code>[26/Mar/2019:09:04:39 +0100] "GET /blockorder?orderCode=XXXX&access_token=XXXX HTTP/1.1" 400 122 "-" "AHC/1.0"
</code></pre>
<p>and in the console.log I have this:</p>
<pre><code>hybrisHTTP8 2019-03-26 09:04:39,184 ERROR [[10.125.31.2] ] () [de.hybris.platform.jdbcwrapper.ConnectionImpl] error resetting AutoCommit
java.sql.SQLRecoverableException: Closed Connection
at oracle.jdbc.driver.PhysicalConnection.setAutoCommit(PhysicalConnection.java:3763)
at de.hybris.platform.jdbcwrapper.ConnectionImpl.doSetAutoCommit(ConnectionImpl.java:431)
at de.hybris.platform.jdbcwrapper.ConnectionImpl.restoreAutoCommit(ConnectionImpl.java:185)
at de.hybris.platform.jdbcwrapper.ConnectionImpl.unsetTxBound(ConnectionImpl.java:175)
at de.hybris.platform.tx.Transaction.unsetTxBoundConnection(Transaction.java:920)
at de.hybris.platform.tx.Transaction.clearTxBoundConnectionAndNotify(Transaction.java:897)
at de.hybris.platform.tx.Transaction.clearTxBoundConnectionAndNotifyRollback(Transaction.java:887)
at de.hybris.platform.tx.Transaction.rollbackOuter(Transaction.java:1084)
at de.hybris.platform.tx.Transaction.rollback(Transaction.java:1028)
at de.hybris.platform.tx.Transaction.commit(Transaction.java:690)
at de.hybris.platform.tx.Transaction.finishExecute(Transaction.java:1218)
at de.hybris.platform.tx.Transaction.execute(Transaction.java:1205)
at de.hybris.platform.tx.Transaction.execute(Transaction.java:1160)
at de.hybris.platform.jalo.Item.setAllAttributes(Item.java:2082)
at de.hybris.platform.jalo.Item.setAllAttributes(Item.java:2057)
at de.hybris.platform.servicelayer.internal.converter.impl.ItemModelConverter.storeAttributes(ItemModelConverter.java:1503)
at de.hybris.platform.servicelayer.internal.converter.impl.ItemModelConverter.save(ItemModelConverter.java:730)
at de.hybris.platform.servicelayer.internal.model.impl.wrapper.ModelWrapper.save(ModelWrapper.java:336)
at de.hybris.platform.servicelayer.internal.model.impl.ResolvingModelPersister.saveOthers(ResolvingModelPersister.java:64)
at de.hybris.platform.servicelayer.internal.model.impl.ResolvingModelPersister.persist(ResolvingModelPersister.java:49)
at de.hybris.platform.servicelayer.internal.model.impl.DefaultModelService.saveViaJalo(DefaultModelService.java:1059)
at de.hybris.platform.servicelayer.internal.model.impl.DefaultModelService.doJaloPersistence(DefaultModelService.java:648)
at de.hybris.platform.servicelayer.internal.model.impl.DefaultModelService.persistWrappers(DefaultModelService.java:1002)
at de.hybris.platform.servicelayer.internal.model.impl.DefaultModelService.performPersistenceOperations(DefaultModelService.java:626)
at de.hybris.platform.servicelayer.internal.model.impl.DefaultModelService.saveAllInternal(DefaultModelService.java:620)
at de.hybris.platform.servicelayer.internal.model.impl.DefaultModelService.saveAll(DefaultModelService.java:600)
at de.hybris.platform.servicelayer.internal.model.impl.DefaultModelService.save(DefaultModelService.java:548)
at com.test.fulfilment.process.impl.DefaultOrderProcessService.requestForcedOrderCancellation(DefaultOrderProcessService.java:131)
at com.test.application.order.facades.impl.DefaultOrderFacade.forcedOrderCancel(DefaultOrderFacade.java:62)
at com.test.application.controllers.OrderController.blockOrder(OrderController.java:520)
</code></pre>
<p>Our pool config is the following:</p>
<pre><code>{
"maxIdle": 90,
"minIdle": 2,
"maxActive": 90,
"maxWait": 10000,
"whenExhaustedAction": 1,
"testOnBorrow": true,
"testOnReturn": true,
"testWhileIdle": true,
"timeBetweenEvictionRunsMillis": 10000,
"numTestsPerEvictionRun": 100,
"minEvictableIdleTimeMillis": 300000,
"softMinEvictableIdleTimeMillis": -1,
"lifo": true
}
</code></pre>
<p>Our tomcat config is:</p>
<pre><code>tomcat.generaloptions.JDBC=-Doracle.jdbc.ReadTimeout=60000
tomcat.generaloptions.TIMEOUT=-Dsun.net.client.defaultConnectTimeout\=60000 -Dsun.net.client.defaultReadTimeout\=60000
tomcat.ajp.acceptCount=100
tomcat.ajp.maxThreads=400
tomcat.maxthreads=400
tomcat.minsparethreads=50
tomcat.maxidletime=10000
tomcat.connectiontimeout=120000
tomcat.acceptcount=100
</code></pre>
<p>We tried to remove the oracle.jdbc.ReadTimeout but the result was that we started to see Closed Connections on the other servers.</p>
<p>The code that trigger this error is pretty simple (and it works in the 95% of time):</p>
<pre><code> @Override
public boolean requestForcedOrderCancellation(final OrderModel order) {
Transaction.current().begin();
try {
modelService.lock(order.getPk());
modelService.refresh(order);
order.setForcedCancelled(true);
modelService.save(order);
Transaction.current().commit();
return true;
catch (Exception e) {
LOG.error(e.getMessage(), e);
Transaction.current().rollback();
return false;
}
}
</code></pre>
<p>We tried also without explicit locking and the problem is exactly the same.
It seems like the connection is already closed and we cannot rollback (or commit) the transactions that are still waiting in DB.</p>
<p>I expect to avoid this lock and these closed connection errors.</p>
| 0 | 2,301 |
JTable row color depending on Value in model?
|
<p>I have this code in my Table model:</p>
<pre><code>public class DocumentProjectTableModel extends AbstractTableModel{
private List<MyDocument> myDocuments;
public String getValueAt(int row, int column) {
String toReturn = null;
MyDocument myDocument = myDocuments.get(row);
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
switch (column) {
case 0:
if(myDocument.getProject().getRegDate()!=null) toReturn = format.format(myDocument.getProject().getRegDate());
break;
case 1:
toReturn = myDocument.getProject().getRegNum();
break;
case 2:
toReturn = myDocument.getProject().getDescription();
break;
case 3:
toReturn = myDocument.getProject().getShortName();
break;
case 4:
toReturn = myDocument.getProject().getSecondName()+myDocument.getProject().getFirstName()+myDocument.getProject().getMiddleName();
break;
}
return toReturn;
}
// some other stuff is not shown
</code></pre>
<p>I want to change background color of each row, for example if <code>myDocument.getIsRegistered() == true</code>, I want this row to have yellow background, if <code>myDocument.getIsValid == false</code> row is blue and so on.</p>
<p>I've found examples that recolor rows depending on values in JTable. But getIsValid and getIsRegistered() aren't actually displayed, they exist only in model. Any advice or example would really help. thanks in advance.</p>
<p>update. my TableCellRenderer:</p>
<pre><code>public class MyTableCellRenderer extends JLabel implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
String actualValue = (String) value;
// Set the colors as per the value in the cell...
if(actualValue.equals("lifesucks") ){
setBackground(Color.YELLOW);
}
return this;
}
}
</code></pre>
<p>using renderer:</p>
<pre><code> int vColIndex = 0;
TableColumn col = resultTable.getColumnModel().getColumn(vColIndex);
col.setCellRenderer(new MyTableCellRenderer());
resultTable.setModel(new DocumentProjectTableModel(docs));
</code></pre>
<p>table is shown as usual no yellow color. why?</p>
<p>update2.</p>
<pre><code>resultTable=new JTable(new DocumentProjectTableModel(docs)){
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
{
Component c = super.prepareRenderer(renderer, row, column);
// Color row based on a cell value
if (!isRowSelected(row)) {
c.setBackground(getBackground());
int modelRow = convertRowIndexToModel(row);
String type = (String) getModel().getValueAt(modelRow, 0);
c.setBackground(Color.GREEN);
}
return c;
}
};
</code></pre>
<p>table is empty:(</p>
| 0 | 1,462 |
rails - running production mode locally = No such file to load - config/environment
|
<p>I am trying to run locally in production mode with:</p>
<pre><code>$ RAILS_ENV=production rails s
</code></pre>
<p>But I get:</p>
<pre><code>/home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/activesupport-3.1.8/li
b/active_support/dependencies.rb:306:in `rescue in depend_on': No such file
to load -- /home/durrantm/Dropnot/webs/rails_apps/linker/app/assets/../con
fig/environment (LoadError)
</code></pre>
<p>I can create a brand new rails <code>3.1.8</code> app and do <code>RAILS_ENV=production rails server</code> and I don't get this problem.</p>
<p>I can also do <code>rails s</code> and that runs the server fine in development mode without error.</p>
<p>I can also do <code>RAILS_ENV=development rails s</code> and that runs the server fine in development mode without error.</p>
<p>fwiw, my app was originally a rails <code>2.3</code> app so perhaps I am missing something that's been added or changed in rails ?</p>
<p>I do have the <code>config</code> directory with an <code>environment.rb</code> file. Perhaps the way it's being referenced is wrong somehow?</p>
<p>I added <code>config.assets.enabled = true</code> to <code>config/application.rb</code> but it didn't help (didn't expect it to as that is asset compilation, but it was a difference I found!).</p>
<p>Full Trace:</p>
<pre><code>durrantm@Castle2012:~/Dropnot/webs/rails_apps/linker/config/environments (v3.1.8_with_assets)
$ RAILS_ENV=production rails s
=> Booting WEBrick
=> Rails 3.1.8 application starting in production on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
Exiting
/home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/activesupport-3.1.8/lib/active_support/dependencies.rb:306:in `rescue in depend_on': No such file to load -- /home/durrantm/Dropnot/webs/rails_apps/linker/app/assets/../config/environment (LoadError)
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/activesupport-3.1.8/lib/active_support/dependencies.rb:301:in `depend_on'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/activesupport-3.1.8/lib/active_support/dependencies.rb:214:in `require_dependency'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/engine.rb:417:in `block (2 levels) in eager_load!'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/engine.rb:416:in `each'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/engine.rb:416:in `block in eager_load!'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/engine.rb:414:in `each'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/engine.rb:414:in `eager_load!'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/application/finisher.rb:51:in `block in <module:Finisher>'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/initializable.rb:30:in `instance_exec'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/initializable.rb:30:in `run'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/initializable.rb:55:in `block in run_initializers'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/initializable.rb:54:in `each'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/initializable.rb:54:in `run_initializers'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/application.rb:96:in `initialize!'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/railtie/configurable.rb:30:in `method_missing'
from /home/durrantm/Dropnot/webs/rails_apps/linker/config/environment.rb:5:in `<top (required)>'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/activesupport-3.1.8/lib/active_support/dependencies.rb:240:in `require'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/activesupport-3.1.8/lib/active_support/dependencies.rb:240:in `block in require'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/activesupport-3.1.8/lib/active_support/dependencies.rb:223:in `block in load_dependency'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/activesupport-3.1.8/lib/active_support/dependencies.rb:640:in `new_constants_in'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/activesupport-3.1.8/lib/active_support/dependencies.rb:223:in `load_dependency'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/activesupport-3.1.8/lib/active_support/dependencies.rb:240:in `require'
from /home/durrantm/Dropnot/webs/rails_apps/linker/config.ru:4:in `block in <main>'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/rack-1.3.6/lib/rack/builder.rb:51:in `instance_eval'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/rack-1.3.6/lib/rack/builder.rb:51:in `initialize'
from /home/durrantm/Dropnot/webs/rails_apps/linker/config.ru:1:in `new'
from /home/durrantm/Dropnot/webs/rails_apps/linker/config.ru:1:in `<main>'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/rack-1.3.6/lib/rack/builder.rb:40:in `eval'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/rack-1.3.6/lib/rack/builder.rb:40:in `parse_file'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/rack-1.3.6/lib/rack/server.rb:200:in `app'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/commands/server.rb:46:in `app'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/rack-1.3.6/lib/rack/server.rb:301:in `wrapped_app'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/rack-1.3.6/lib/rack/server.rb:252:in `start'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/commands/server.rb:70:in `start'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/commands.rb:54:in `block in <top (required)>'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/commands.rb:49:in `tap'
from /home/durrantm/.rvm/gems/ruby-1.9.3-p194@linker/gems/railties-3.1.8/lib/rails/commands.rb:49:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
</code></pre>
| 0 | 3,194 |
How to send POST request to Phil Sturgeon's CodeIgniter RestServer
|
<p>I'm new to CodeIgniter. I'm using Phil Sturgeon's RestServer and RestClient. I've been trying to make a POST request in my CodeIgniter RestClient controller to update data in my CodeIgniter RestServer, but it never updates data in my database. I think my POST request is not right.</p>
<p>Here is my RestClient POST request in controller:</p>
<pre><code>$result = $this->rest->post('newscontroller/news/format/json',
array('news_id' => $news_id,
'news_title' => $news_title,
'news_category' => $news_category ),
'json');
if(isset($result->status) && $result->status == 'success')
{
$data['message'] ='News has been updated.';
$this->load->view('otherpageview',$data);
}
else
{
$data['message'] ='Something has gone wrong';
$this->load->view('otherpageview',$data);
}
</code></pre>
<p>It seems that <strong>$result</strong> doesn't get any value, because I did echo the <strong>$result->status</strong> and it has nothing to display. And I've also have this in this controller's constructor :</p>
<pre><code>// Load the rest client spark
$this->load->spark('restclient/2.1.0');
// Load the library
$this->load->library('rest');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.therestserver.com/index.php/'));
</code></pre>
<p>And in the RestServer's controller, which is <strong>newscontroller</strong>, has this method :</p>
<pre><code>function news_post()
{
$news=array(
'news_id' => $this->post('news_id'),
'news_title' => $this->post('news_title'),
'news_category' => $this->post('news_category') );
$result = $this->News_model->UpdateNews($news);
if($result === FALSE)
{
$this->response(array('status' => 'failed'));
}
else
{
$this->response(array('status' => 'success'));
}
}
</code></pre>
<p>With the <strong>News_model</strong> :</p>
<pre><code>public function UpdateNews($news)
{
$this->db->where('news_id',$news->news_id);
$this->db->update('news',$news);
}
</code></pre>
<p>I just don't know where I'm doing wrong, because I still don't understand how the POST request and method work. I've read through the tutorial in Nettuts and search about this, but still.. maybe because of my bad English reading-writing. I hope someone can help me out, any help would be appreciated. Thanks a TON! :)</p>
| 0 | 1,044 |
mach-o file, but is an incompatible architecture have 'x86_64', need 'arm64e' M1 MAC
|
<pre class="lang-py prettyprint-override"><code>from PyQt6.QtWidgets import *
from model.Department import Department
from view.main_window import Ui_Form
from model.Department import Department, Employee
class Homewidget(QWidget,Ui_Form):
def __init__(self):
QWidget.__init___(self)
self.setupUi(self)
self.depts = Department.get_all_depts()
self.load_depts
self.emps= Employee.get_all_emps()
self.load_emps
self.cb_depts.currentIndexChanged.connect(self.filter_emps_by_dept)
self.le_search.textChanged.connect(self.filter_emps_by_name)
def load_depts(self):
names = [d.dept_name for d in self.depts]
self.cb_depts.addItems(names)
def load_emps(self):
self.tb_emps.setRowCount(0)
for i, e in self.emps:
self.tb_emps.insertRow(i)
for j, info in enumerate(e.__dict__.values()):
self.tb_emps.setItem(i , j, QTableWidgetItem(str(info)))
def filter_emps_by_dept(self, idx):
self.load_emps()
if idx != 0:
dept = self.depts[idx - 1]
for i, e in enumerate(self.emps):
if e.dept_id != dept.dept_id:
self.tb_emps.hideRow(i)
def filter_emps_by_name(self):
self.load_emps()
query = self.le_search.text().lower()
if query != "":
for i , e in enumerate(self.emps):
if not e.emp_name.lower().startswith(query):
self.tb_emps.hideRow(i)}
app = QApplication([])
window = Homewidget()
window.show()
app.exec()
</code></pre>
<p>this is the error I'm facing on my m1 MacBook Pro Monetery can't run my GUI project for school .
the PyQt6 comes with default in arm64 and I'm not sure but I think my software is arm64e I am new to osx idk what to do can I change the software from arm64e to arm64 ?</p>
<p>this is the error I'm facing below...</p>
<blockquote>
<p>ahmed@Ahmeds-MacBook-Pro hr_system % /usr/local/bin/python3 >/Users/ahmed/hr_system/app.py
Traceback (most recent call last):
File "/Users/ahmed/hr_system/app.py", line 1, in
from PyQt6.QtWidgets import *
ImportError: >dlopen(/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/sit>e-packages/PyQt6/QtWidgets.abi3.so, 0x0002): Library not loaded: >@rpath/QtWidgets.framework/Versions/A/QtWidgets
Referenced from: >/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site->packages/PyQt6/QtWidgets.abi3.so
Reason: tried: >'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site->packages/PyQt6/Qt6/lib/QtWidgets.framework/Versions/A/QtWidgets' (mach-o >file, but is an incompatible architecture (have 'x86_64', need 'arm64e')), >'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site->packages/PyQt6/Qt6/lib/QtWidgets.framework/Versions/A/QtWidgets' (mach-o >file, but is an incompatible architecture (have 'x86_64', need 'arm64e')), >'/System/Library/Frameworks/QtWidgets.framework/Versions/A/QtWidgets' (no >such file)</p>
</blockquote>
| 0 | 1,490 |
How do you REALLY remove Copy from UIMenuController
|
<p>There apparently used to be an <a href="https://stackoverflow.com/questions/4311009/uimenucontroller-in-uiwebview-with-custom-menu-items-without-more-menu/4413464#4413464">easy way</a> to prevent the "More..." label from appearing in UIMenuController when you added more than one custom menu item. You just had to remove all of the system menu items. There was even a <a href="https://stackoverflow.com/questions/3255070/problems-adding-more-than-one-uimenuitem-to-uimenucontroller">workaround here</a> for still having copy work. You just had to implement a custom copy command using a different selector and then override canPerformAction:withSender: to not show the system copy:</p>
<pre><code>-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(copy:))
return NO;
else
// logic to show or hide other things
}
</code></pre>
<p>Unfortunately this method no longer works (at least in a UIWebView subclass). canPerformAction:withSender: is called for every system menu item except copy: so the result is that the system copy menu item is always displayed. This means that if you have more than one custom menu item, they are always hidden behind "More..."</p>
<p>So, is there a way to really remove the system's copy item or some alternate way to prevent menu items from hiding behind "More..."?</p>
<p><strong>Update</strong></p>
<p>This is the output I get when I override canPerformAction:withSender: notice that the method is never called for the "copy:" action:</p>
<pre><code>cannot perform action cut: with sender <UIMenuController: 0x7227d30>.
cannot perform action select: with sender <UIMenuController: 0x7227d30>.
cannot perform action selectAll: with sender <UIMenuController: 0x7227d30>.
cannot perform action paste: with sender <UIMenuController: 0x7227d30>.
cannot perform action delete: with sender <UIMenuController: 0x7227d30>.
cannot perform action promptForReplace: with sender <UIMenuController: 0x7227d30>.
cannot perform action _showMoreItems: with sender <UIMenuController: 0x7227d30>.
cannot perform action _setRtoLTextDirection: with sender <UIMenuController: 0x7227d30>.
cannot perform action _setLtoRTextDirection: with sender <UIMenuController: 0x7227d30>.
can perform action customCopy: with sender <UIMenuController: 0x7227d30>.
can perform action custom1: with sender <UIMenuController: 0x7227d30>.
cannot perform action custom2: with sender <UIMenuController: 0x7227d30>.
can perform action custom3: with sender <UIMenuController: 0x7227d30>.
can perform action custom4: with sender <UIMenuController: 0x7227d30>.
cannot perform action cut: with sender <UIMenuController: 0x7227d30>.
cannot perform action select: with sender <UIMenuController: 0x7227d30>.
cannot perform action selectAll: with sender <UIMenuController: 0x7227d30>.
cannot perform action paste: with sender <UIMenuController: 0x7227d30>.
cannot perform action delete: with sender <UIMenuController: 0x7227d30>.
cannot perform action promptForReplace: with sender <UIMenuController: 0x7227d30>.
cannot perform action _showMoreItems: with sender <UIMenuController: 0x7227d30>.
cannot perform action _setRtoLTextDirection: with sender <UIMenuController: 0x7227d30>.
cannot perform action _setLtoRTextDirection: with sender <UIMenuController: 0x7227d30>.
</code></pre>
| 0 | 1,161 |
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
|
<p>I have to develop one Android application. Here I am getting following error:</p>
<pre><code>03-26 21:29:00.394: E/AndroidRuntime(684): FATAL EXCEPTION: main
03-26 21:29:00.394: E/AndroidRuntime(684): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
03-26 21:29:00.394: E/AndroidRuntime(684): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
03-26 21:29:00.394: E/AndroidRuntime(684): at java.util.ArrayList.get(ArrayList.java:311)
03-26 21:29:00.394: E/AndroidRuntime(684): at com.xmlparsing.MainActivity.loadXMLData(MainActivity.java:303)
03-26 21:29:00.394: E/AndroidRuntime(684): at com.xmlparsing.MainActivity.access$2(MainActivity.java:118)
03-26 21:29:00.394: E/AndroidRuntime(684): at com.xmlparsing.MainActivity$GetXmlFiles.onPostExecute(MainActivity.java:369)
03-26 21:29:00.394: E/AndroidRuntime(684): at com.xmlparsing.MainActivity$GetXmlFiles.onPostExecute(MainActivity.java:1)
03-26 21:29:00.394: E/AndroidRuntime(684): at android.os.AsyncTask.finish(AsyncTask.java:417)
03-26 21:29:00.394: E/AndroidRuntime(684): at android.os.AsyncTask.access$300(AsyncTask.java:127)
03-26 21:29:00.394: E/AndroidRuntime(684): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
03-26 21:29:00.394: E/AndroidRuntime(684): at android.os.Handler.dispatchMessage(Handler.java:99)
03-26 21:29:00.394: E/AndroidRuntime(684): at android.os.Looper.loop(Looper.java:123)
03-26 21:29:00.394: E/AndroidRuntime(684): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-26 21:29:00.394: E/AndroidRuntime(684): at java.lang.reflect.Method.invokeNative(Native Method)
03-26 21:29:00.394: E/AndroidRuntime(684): at java.lang.reflect.Method.invoke(Method.java:521)
03-26 21:29:00.394: E/AndroidRuntime(684): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-26 21:29:00.394: E/AndroidRuntime(684): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-26 21:29:00.394: E/AndroidRuntime(684): at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>Here I have used below code:</p>
<pre><code>String[] stockArrVideo = new String[Appscontent.Sub_arraylistvideo.size()];
stockArrVideo = Appscontent.Sub_arraylistvideo.toArray(stockArrVideo);
for (String s : stockArrVideo) {
if (s.startsWith(number)) {
String _Substring;
_Substring = s.substring(1);
if(_Substring.equals("")||_Substring == null) {
_Substring = "No Records";
}
Appscontent.Sub_arraylistvideosub.add(_Substring);
}
h++;
}
</code></pre>
<p>If the data is empty, it means I have to display the "No Records" message. Otherwise display the correct data.</p>
<pre><code>TextView mVideo = new TextView(this);
System.out.println(Appscontent.Sub_arraylistvideosub.get(j));
mVideo.setText(Appscontent.Sub_arraylistvideosub.get(j));
mVideo.setLayoutParams(textLayoutParams);
mVideo.setBackgroundColor(Color.BLACK);
</code></pre>
<p>Here I have wrote the code for checking the empty data.</p>
<p>What is causing this exception?</p>
| 0 | 1,207 |
CSS - Aligning Navigation bar with images and text
|
<p>I have a menu (shown in the picture below) which I am trying to correctly align the text with the images (i.e. [img] [text]) as well as "stretch" the whole contents to fit all the width.</p>
<p>Image:
<img src="https://i.stack.imgur.com/DP89b.png" alt="Navigation Menu"></p>
<p>HTML:</p>
<pre><code><div id="menu">
<ul>
<li><a class="current" href="home.html" title="">HOME</a></li>
<li><a href="services.html" title="">TRANSPORT</a></li>
<li><a href="#" title="">ACCOMODATION</a></li>
<li><a href="#" title="">DEALS</a></li>
<li><a href="contact.html" title="">CONTACT</a></li>
</ul>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>#menu{
width:900px;
height: 50px;
clear:both;
background-color: #f7951e;
font-family: 'Exo 2', sans-serif;
text-align: center;
}
#menu ul{
font-family: 'Exo 2', sans-serif;
list-style:none;
margin-top: 5px;
margin-bottom: 5px;
display:block;
float: left;
width: auto;
}
#menu ul li{
font-family: 'Exo 2', sans-serif;
list-style:none;
display:inline;
width:auto;
height:50px;
line-height:42px;
font-size:18px;
}
#menu ul li a{
font-family: 'Exo 2', sans-serif;
font-size: 18px;
height: auto;
width: auto;
float:next;
text-decoration: none;
color:#fff;
padding-left: 40px;
padding-right: 10px;
}
#menu ul li a:hover{
height:auto;
width: auto;
text-decoration:none;
color: #fff;
}
#menu ul li a.current{
height:auto;
width: auto;
text-decoration:none;
color: #fff;
}
#menu ul li:nth-of-type(1){
background:url(./images/iconza/house_32x32.png) no-repeat;
float: start;
padding-top: 5px;
padding-bottom: 10px;
}
#menu ul li:nth-of-type(2){
background:url(./images/iconza/Car.png) no-repeat;
float: start;
padding-top: 5px;
padding-bottom: 10px;
}
#menu ul li:nth-of-type(3){
background:url(./images/iconza/house.png) no-repeat;
float: start;
padding-top: 5px;
padding-bottom: 10px;
}
#menu ul li:nth-of-type(4){
background:url(./images/iconza/offer.png) no-repeat;
float: start;
padding-top: 5px;
padding-bottom: 10px;
}
#menu ul li:nth-of-type(5){
background:url(./images/iconza/mail_32x32.png) no-repeat;
float: start;
padding-top: 5px;
padding-bottom: 10px;
}
</code></pre>
| 0 | 1,286 |
javamail - 504 5.5.2 : Helo command rejected: need fully-qualified hostname
|
<p>i will send mail via java mail in my webapp. i wrote a code and test it via gmail account and it works fine. then i replace my host smtp detail with gmail information and test it. oops it return my a following exception:</p>
<pre><code>javax.mail.MessagingException: 504 5.5.2 <rasta-PC>: Helo command rejected: need fully-qualified hostname
at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:2099)
at com.sun.mail.smtp.SMTPTransport.helo(SMTPTransport.java:1490)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:662)
at javax.mail.Service.connect(Service.java:367)
at javax.mail.Service.connect(Service.java:226)
at javax.mail.Service.connect(Service.java:175)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at util.MailUtil.sendViaSSL(MailUtil.java:43)
at control.member.AddMemberControl.add(AddMemberControl.java:107)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:357)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at filter.CheckLoginFilter.doFilter(CheckLoginFilter.java:57)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
</code></pre>
<p>you can see my code in the following: </p>
<pre><code>public static void sendViaSSL(final MailServerDetail msd,String to, String subject, String text){
Properties props=new Properties();
props.put("mail.smtp.host", "smtp.hostname");
props.put("mail.smtp.socketFactory.port", "587");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.ssl", "true");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.timeout", "5000");
props.put("mail.smtp.connectiontimeout", "5000");
Session session=Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("My Mail Address", "Mail Password");
}
});
MimeMessage message=new MimeMessage(session);
try {
message.setHeader("Content-Type", "text/plain; charset=UTF-8");
message.setFrom(new InternetAddress("My Mail Address"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject,"UTF-8");
message.setText(text, "UTF-8","html");
Transport.send(message);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
</code></pre>
<p>can you help me solve it?
thanks.</p>
| 0 | 2,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.